forked from multiOTP/multiOTPCredentialProvider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.cpp
970 lines (860 loc) · 30.8 KB
/
helpers.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Helper functions for copying parameters and packaging the buffer
// for GetSerialization.
#include "helpers.h"
#include <intsafe.h>
void PrintLn(const wchar_t *message, const wchar_t *message2, const wchar_t *message3, const wchar_t *message4)
{
INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
GetCurrentTimeAndDate(date_time);
WriteLogFile(date_time);
WriteLogFile(message);
WriteLogFile(message2);
WriteLogFile(message3);
WriteLogFile(message4);
WriteLogFile("\n");
}
void PrintLn(const wchar_t *message, const wchar_t *message2, const wchar_t *message3)
{
PrintLn(message, message2, message3, L"");
}
void PrintLn(const wchar_t *message, const wchar_t *message2)
{
PrintLn(message, message2, L"");
}
void PrintLn(const wchar_t *message) {
PrintLn(message, L"");
}
void PrintLn(const char* message)
{
INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
GetCurrentTimeAndDate(date_time);
WriteLogFile(date_time);
WriteLogFile(message);
WriteLogFile("\n");
}
void PrintLn(const char* message, int line)
{
INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
GetCurrentTimeAndDate(date_time);
WriteLogFile(date_time);
char code[1024];
sprintf_s(code, sizeof(code), message, line);
WriteLogFile(code);
WriteLogFile("\n");
}
void PrintLn(const wchar_t *message, int line)
{
INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
GetCurrentTimeAndDate(date_time);
WriteLogFile(date_time);
wchar_t code[1024];
swprintf_s(code, sizeof(code), message, line);
// OutputDebugStringW(message);
WriteLogFile(code);
WriteLogFile("\n");
}
void PrintLn(int line)
{
INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
GetCurrentTimeAndDate(date_time);
WriteLogFile(date_time);
char code[1024];
sprintf_s(code, sizeof(code), "%d", line);
WriteLogFile(code);
WriteLogFile("\n");
}
void WriteLogFile(const char* szString)
{
FILE* pFile;
if (fopen_s(&pFile, LOGFILE_NAME, "a") == 0)
{
fprintf(pFile, "%s", szString);
fclose(pFile);
}
}
void WriteLogFile(const wchar_t* szString)
{
FILE* pFile;
if (fopen_s(&pFile, LOGFILE_NAME, "a") == 0)
{
fwprintf(pFile, L"%s", szString);
fclose(pFile);
}
}
/*
PWSTR path;
wchar_t logfile[1024];
if (readRegistryValueString(CONF_PATH, &path, L"c:\\multiotp\\")) {
wcscpy_s(logfile, 1024, path);
wcscat_s(logfile, 1024, LOGFILE_NAME);
}
else
{
wcscpy_s(logfile, 1024, LOGFILE_PATH);
wcscat_s(logfile, 1024, LOGFILE_NAME);
}
FILE* pFile;
if (_wfopen_s(&pFile, logfile, L"a") == 0)
{
fwprintf(pFile, L"%s", szString);
fclose(pFile);
}
*/
void GetCurrentTimeAndDate(char(&time)[MAX_TIME_SIZE])
{
SYSTEMTIME st;
GetSystemTime(&st);
sprintf_s(time, ARRAYSIZE(time), "%04d%02d%02d %02d%02d%02d%04d: ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
}
//
// Copies the field descriptor pointed to by rcpfd into a buffer allocated
// using CoTaskMemAlloc. Returns that buffer in ppcpfd.
//
HRESULT FieldDescriptorCoAllocCopy(
_In_ const CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR &rcpfd,
_Outptr_result_nullonfailure_ CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR **ppcpfd
)
{
HRESULT hr;
*ppcpfd = nullptr;
DWORD cbStruct = sizeof(**ppcpfd);
CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *pcpfd = (CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR*)CoTaskMemAlloc(cbStruct);
if (pcpfd)
{
pcpfd->dwFieldID = rcpfd.dwFieldID;
pcpfd->cpft = rcpfd.cpft;
pcpfd->guidFieldType = rcpfd.guidFieldType;
if (rcpfd.pszLabel)
{
hr = SHStrDupW(rcpfd.pszLabel, &pcpfd->pszLabel);
}
else
{
pcpfd->pszLabel = nullptr;
hr = S_OK;
}
}
else
{
hr = E_OUTOFMEMORY;
}
if (SUCCEEDED(hr))
{
*ppcpfd = pcpfd;
}
else
{
CoTaskMemFree(pcpfd);
}
return hr;
}
//
// Coppies rcpfd into the buffer pointed to by pcpfd. The caller is responsible for
// allocating pcpfd. This function uses CoTaskMemAlloc to allocate memory for
// pcpfd->pszLabel.
//
HRESULT FieldDescriptorCopy(
_In_ const CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR &rcpfd,
_Out_ CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR *pcpfd
)
{
HRESULT hr;
CREDENTIAL_PROVIDER_FIELD_DESCRIPTOR cpfd;
cpfd.dwFieldID = rcpfd.dwFieldID;
cpfd.cpft = rcpfd.cpft;
cpfd.guidFieldType = rcpfd.guidFieldType;
if (rcpfd.pszLabel)
{
hr = SHStrDupW(rcpfd.pszLabel, &cpfd.pszLabel);
}
else
{
cpfd.pszLabel = nullptr;
hr = S_OK;
}
if (SUCCEEDED(hr))
{
*pcpfd = cpfd;
}
return hr;
}
//
// This function copies the length of pwz and the pointer pwz into the UNICODE_STRING structure
// This function is intended for serializing a credential in GetSerialization only.
// Note that this function just makes a copy of the string pointer. It DOES NOT ALLOCATE storage!
// Be very, very sure that this is what you want, because it probably isn't outside of the
// exact GetSerialization call where the sample uses it.
//
HRESULT UnicodeStringInitWithString(
_In_ PWSTR pwz,
_Out_ UNICODE_STRING *pus
)
{
HRESULT hr;
if (pwz)
{
size_t lenString = wcslen(pwz);
USHORT usCharCount;
hr = SizeTToUShort(lenString, &usCharCount);
if (SUCCEEDED(hr))
{
USHORT usSize;
hr = SizeTToUShort(sizeof(wchar_t), &usSize);
if (SUCCEEDED(hr))
{
hr = UShortMult(usCharCount, usSize, &(pus->Length)); // Explicitly NOT including NULL terminator
if (SUCCEEDED(hr))
{
pus->MaximumLength = pus->Length;
pus->Buffer = pwz;
hr = S_OK;
}
else
{
hr = HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW);
}
}
}
}
else
{
hr = E_INVALIDARG;
}
return hr;
}
//
// The following function is intended to be used ONLY with the Kerb*Pack functions. It does
// no bounds-checking because its callers have precise requirements and are written to respect
// its limitations.
// You can read more about the UNICODE_STRING type at:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secauthn/security/unicode_string.asp
//
static void _UnicodeStringPackedUnicodeStringCopy(
__in const UNICODE_STRING& rus,
__in PWSTR pwzBuffer,
__out UNICODE_STRING *pus
)
{
pus->Length = rus.Length;
pus->MaximumLength = rus.Length;
pus->Buffer = pwzBuffer;
CopyMemory(pus->Buffer, rus.Buffer, pus->Length);
}
//
// Initialize the members of a KERB_INTERACTIVE_UNLOCK_LOGON with weak references to the
// passed-in strings. This is useful if you will later use KerbInteractiveUnlockLogonPack
// to serialize the structure.
//
// The password is stored in encrypted form for CPUS_LOGON and CPUS_UNLOCK_WORKSTATION
// because the system can accept encrypted credentials. It is not encrypted in CPUS_CREDUI
// because we cannot know whether our caller can accept encrypted credentials.
//
HRESULT KerbInteractiveUnlockLogonInit(
_In_ PWSTR pwzDomain,
_In_ PWSTR pwzUsername,
_In_ PWSTR pwzPassword,
_In_ CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus,
_Out_ KERB_INTERACTIVE_UNLOCK_LOGON *pkiul
)
{
KERB_INTERACTIVE_UNLOCK_LOGON kiul;
ZeroMemory(&kiul, sizeof(kiul));
KERB_INTERACTIVE_LOGON *pkil = &kiul.Logon;
// Note: this method uses custom logic to pack a KERB_INTERACTIVE_UNLOCK_LOGON with a
// serialized credential. We could replace the calls to UnicodeStringInitWithString
// and KerbInteractiveUnlockLogonPack with a single cal to CredPackAuthenticationBuffer,
// but that API has a drawback: it returns a KERB_INTERACTIVE_UNLOCK_LOGON whose
// MessageType is always KerbInteractiveLogon.
//
// If we only handled CPUS_LOGON, this drawback would not be a problem. For
// CPUS_UNLOCK_WORKSTATION, we could cast the output buffer of CredPackAuthenticationBuffer
// to KERB_INTERACTIVE_UNLOCK_LOGON and modify the MessageType to KerbWorkstationUnlockLogon,
// but such a cast would be unsupported -- the output format of CredPackAuthenticationBuffer
// is not officially documented.
// Initialize the UNICODE_STRINGS to share our username and password strings.
HRESULT hr = UnicodeStringInitWithString(pwzDomain, &pkil->LogonDomainName);
if (SUCCEEDED(hr))
{
hr = UnicodeStringInitWithString(pwzUsername, &pkil->UserName);
if (SUCCEEDED(hr))
{
hr = UnicodeStringInitWithString(pwzPassword, &pkil->Password);
if (SUCCEEDED(hr))
{
// Set a MessageType based on the usage scenario.
switch (cpus)
{
case CPUS_UNLOCK_WORKSTATION:
pkil->MessageType = KerbWorkstationUnlockLogon;
hr = S_OK;
break;
case CPUS_LOGON:
pkil->MessageType = KerbInteractiveLogon;
hr = S_OK;
break;
case CPUS_CREDUI:
pkil->MessageType = (KERB_LOGON_SUBMIT_TYPE)0; // MessageType does not apply to CredUI
hr = S_OK;
break;
default:
hr = E_FAIL;
break;
}
if (SUCCEEDED(hr))
{
// KERB_INTERACTIVE_UNLOCK_LOGON is just a series of structures. A
// flat copy will properly initialize the output parameter.
CopyMemory(pkiul, &kiul, sizeof(*pkiul));
}
}
}
}
return hr;
}
//
// WinLogon and LSA consume "packed" KERB_INTERACTIVE_UNLOCK_LOGONs. In these, the PWSTR members of each
// UNICODE_STRING are not actually pointers but byte offsets into the overall buffer represented
// by the packed KERB_INTERACTIVE_UNLOCK_LOGON. For example:
//
// rkiulIn.Logon.LogonDomainName.Length = 14 -> Length is in bytes, not characters
// rkiulIn.Logon.LogonDomainName.Buffer = sizeof(KERB_INTERACTIVE_UNLOCK_LOGON) -> LogonDomainName begins immediately
// after the KERB_... struct in the buffer
// rkiulIn.Logon.UserName.Length = 10
// rkiulIn.Logon.UserName.Buffer = sizeof(KERB_INTERACTIVE_UNLOCK_LOGON) + 14 -> UNICODE_STRINGS are NOT null-terminated
//
// rkiulIn.Logon.Password.Length = 16
// rkiulIn.Logon.Password.Buffer = sizeof(KERB_INTERACTIVE_UNLOCK_LOGON) + 14 + 10
//
// THere's more information on this at:
// http://msdn.microsoft.com/msdnmag/issues/05/06/SecurityBriefs/#void
//
HRESULT KerbInteractiveUnlockLogonPack(
_In_ const KERB_INTERACTIVE_UNLOCK_LOGON &rkiulIn,
_Outptr_result_bytebuffer_(*pcb) BYTE **prgb,
_Out_ DWORD *pcb
)
{
HRESULT hr;
const KERB_INTERACTIVE_LOGON *pkilIn = &rkiulIn.Logon;
// alloc space for struct plus extra for the three strings
DWORD cb = sizeof(rkiulIn) +
pkilIn->LogonDomainName.Length +
pkilIn->UserName.Length +
pkilIn->Password.Length;
KERB_INTERACTIVE_UNLOCK_LOGON *pkiulOut = (KERB_INTERACTIVE_UNLOCK_LOGON*)CoTaskMemAlloc(cb);
if (pkiulOut)
{
ZeroMemory(&pkiulOut->LogonId, sizeof(pkiulOut->LogonId));
//
// point pbBuffer at the beginning of the extra space
//
BYTE *pbBuffer = (BYTE*)pkiulOut + sizeof(*pkiulOut);
//
// set up the Logon structure within the KERB_INTERACTIVE_UNLOCK_LOGON
//
KERB_INTERACTIVE_LOGON *pkilOut = &pkiulOut->Logon;
pkilOut->MessageType = pkilIn->MessageType;
//
// copy each string,
// fix up appropriate buffer pointer to be offset,
// advance buffer pointer over copied characters in extra space
//
_UnicodeStringPackedUnicodeStringCopy(pkilIn->LogonDomainName, (PWSTR)pbBuffer, &pkilOut->LogonDomainName);
pkilOut->LogonDomainName.Buffer = (PWSTR)(pbBuffer - (BYTE*)pkiulOut);
pbBuffer += pkilOut->LogonDomainName.Length;
_UnicodeStringPackedUnicodeStringCopy(pkilIn->UserName, (PWSTR)pbBuffer, &pkilOut->UserName);
pkilOut->UserName.Buffer = (PWSTR)(pbBuffer - (BYTE*)pkiulOut);
pbBuffer += pkilOut->UserName.Length;
_UnicodeStringPackedUnicodeStringCopy(pkilIn->Password, (PWSTR)pbBuffer, &pkilOut->Password);
pkilOut->Password.Buffer = (PWSTR)(pbBuffer - (BYTE*)pkiulOut);
*prgb = (BYTE*)pkiulOut;
*pcb = cb;
hr = S_OK;
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}
//
// This function packs the string pszSourceString in pszDestinationString
// for use with LSA functions including LsaLookupAuthenticationPackage.
//
static HRESULT _LsaInitString(
__out PSTRING pszDestinationString,
__in PCSTR pszSourceString
)
{
size_t cchLength = strlen(pszSourceString);
USHORT usLength;
HRESULT hr = SizeTToUShort(cchLength, &usLength);
if (SUCCEEDED(hr))
{
pszDestinationString->Buffer = (PCHAR)pszSourceString;
pszDestinationString->Length = usLength;
pszDestinationString->MaximumLength = pszDestinationString->Length+1;
hr = S_OK;
}
return hr;
}
//
// Retrieves the 'negotiate' AuthPackage from the LSA. In this case, Kerberos
// For more information on auth packages see this msdn page:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secauthn/security/msv1_0_lm20_logon.asp
//
HRESULT RetrieveNegotiateAuthPackage(_Out_ ULONG *pulAuthPackage)
{
HRESULT hr;
HANDLE hLsa;
NTSTATUS status = LsaConnectUntrusted(&hLsa);
if (SUCCEEDED(HRESULT_FROM_NT(status)))
{
ULONG ulAuthPackage;
LSA_STRING lsaszKerberosName;
_LsaInitString(&lsaszKerberosName, NEGOSSP_NAME_A);
status = LsaLookupAuthenticationPackage(hLsa, &lsaszKerberosName, &ulAuthPackage);
if (SUCCEEDED(HRESULT_FROM_NT(status)))
{
*pulAuthPackage = ulAuthPackage;
hr = S_OK;
}
else
{
hr = HRESULT_FROM_NT(status);
}
LsaDeregisterLogonProcess(hLsa);
}
else
{
hr = HRESULT_FROM_NT(status);
}
return hr;
}
//
// Return a copy of pwzToProtect encrypted with the CredProtect API.
//
// pwzToProtect must not be NULL or the empty string.
//
static HRESULT _ProtectAndCopyString(
_In_ PCWSTR pwzToProtect,
_Outptr_result_nullonfailure_ PWSTR *ppwzProtected
)
{
*ppwzProtected = nullptr;
// pwzToProtect is const, but CredProtect takes a non-const string.
// So, make a copy that we know isn't const.
PWSTR pwzToProtectCopy;
HRESULT hr = SHStrDupW(pwzToProtect, &pwzToProtectCopy);
if (SUCCEEDED(hr))
{
// The first call to CredProtect determines the length of the encrypted string.
// Because we pass a NULL output buffer, we expect the call to fail.
//
// Note that the third parameter to CredProtect, the number of characters of pwzToProtectCopy
// to encrypt, must include the NULL terminator!
DWORD cchProtected = 0;
if (!CredProtectW(FALSE, pwzToProtectCopy, (DWORD)wcslen(pwzToProtectCopy)+1, nullptr, &cchProtected, nullptr))
{
DWORD dwErr = GetLastError();
if ((ERROR_INSUFFICIENT_BUFFER == dwErr) && (0 < cchProtected))
{
// Allocate a buffer long enough for the encrypted string.
PWSTR pwzProtected = (PWSTR)CoTaskMemAlloc(cchProtected * sizeof(wchar_t));
if (pwzProtected)
{
// The second call to CredProtect actually encrypts the string.
if (CredProtectW(FALSE, pwzToProtectCopy, (DWORD)wcslen(pwzToProtectCopy)+1, pwzProtected, &cchProtected, nullptr))
{
*ppwzProtected = pwzProtected;
hr = S_OK;
}
else
{
CoTaskMemFree(pwzProtected);
dwErr = GetLastError();
hr = HRESULT_FROM_WIN32(dwErr);
}
}
else
{
hr = E_OUTOFMEMORY;
}
}
else
{
hr = HRESULT_FROM_WIN32(dwErr);
}
}
else
{
hr = E_UNEXPECTED;
}
CoTaskMemFree(pwzToProtectCopy);
}
return hr;
}
//
// If pwzPassword should be encrypted, return a copy encrypted with CredProtect.
//
// If not, just return a copy.
//
HRESULT ProtectIfNecessaryAndCopyPassword(
_In_ PCWSTR pwzPassword,
_In_ CREDENTIAL_PROVIDER_USAGE_SCENARIO cpus,
_Outptr_result_nullonfailure_ PWSTR *ppwzProtectedPassword
)
{
*ppwzProtectedPassword = nullptr;
HRESULT hr;
// ProtectAndCopyString is intended for non-empty strings only. Empty passwords
// do not need to be encrypted.
if (pwzPassword && *pwzPassword)
{
// pwzPassword is const, but CredIsProtected takes a non-const string.
// So, ake a copy that we know isn't const.
PWSTR pwzPasswordCopy;
hr = SHStrDupW(pwzPassword, &pwzPasswordCopy);
if (SUCCEEDED(hr))
{
bool bCredAlreadyEncrypted = false;
CRED_PROTECTION_TYPE protectionType;
// If the password is already encrypted, we should not encrypt it again.
// An encrypted password may be received through SetSerialization in the
// CPUS_LOGON scenario during a Terminal Services connection, for instance.
if (CredIsProtectedW(pwzPasswordCopy, &protectionType))
{
if (CredUnprotected != protectionType)
{
bCredAlreadyEncrypted = true;
}
}
// Passwords should not be encrypted in the CPUS_CREDUI scenario. We
// cannot know if our caller expects or can handle an encryped password.
if (CPUS_CREDUI == cpus || bCredAlreadyEncrypted)
{
hr = SHStrDupW(pwzPasswordCopy, ppwzProtectedPassword);
}
else
{
hr = _ProtectAndCopyString(pwzPasswordCopy, ppwzProtectedPassword);
}
CoTaskMemFree(pwzPasswordCopy);
}
}
else
{
hr = SHStrDupW(L"", ppwzProtectedPassword);
}
return hr;
}
//
// Unpack a KERB_INTERACTIVE_UNLOCK_LOGON *in place*. That is, reset the Buffers from being offsets to
// being real pointers. This means, of course, that passing the resultant struct across any sort of
// memory space boundary is not going to work -- repack it if necessary!
//
void KerbInteractiveUnlockLogonUnpackInPlace(
_Inout_updates_bytes_(cb) KERB_INTERACTIVE_UNLOCK_LOGON *pkiul,
DWORD cb
)
{
if (sizeof(*pkiul) <= cb)
{
KERB_INTERACTIVE_LOGON *pkil = &pkiul->Logon;
// Sanity check: if the range described by each (Buffer + MaximumSize) falls within the total bytecount,
// we can be pretty confident that the Buffers are actually offsets and that this is a packed credential.
if (((ULONG_PTR)pkil->LogonDomainName.Buffer + pkil->LogonDomainName.MaximumLength <= cb) &&
((ULONG_PTR)pkil->UserName.Buffer + pkil->UserName.MaximumLength <= cb) &&
((ULONG_PTR)pkil->Password.Buffer + pkil->Password.MaximumLength <= cb))
{
pkil->LogonDomainName.Buffer = pkil->LogonDomainName.Buffer
? (PWSTR)((BYTE*)pkiul + (ULONG_PTR)pkil->LogonDomainName.Buffer)
: nullptr;
pkil->UserName.Buffer = pkil->UserName.Buffer
? (PWSTR)((BYTE*)pkiul + (ULONG_PTR)pkil->UserName.Buffer)
: nullptr;
pkil->Password.Buffer = pkil->Password.Buffer
? (PWSTR)((BYTE*)pkiul + (ULONG_PTR)pkil->Password.Buffer)
: nullptr;
}
}
}
//
// Use the CredPackAuthenticationBuffer and CredUnpackAuthenticationBuffer to convert a 32 bit WOW
// cred blob into a 64 bit native blob by unpacking it and immediately repacking it.
//
HRESULT KerbInteractiveUnlockLogonRepackNative(
_In_reads_bytes_(cbWow) BYTE *rgbWow,
_In_ DWORD cbWow,
_Outptr_result_bytebuffer_(*pcbNative) BYTE **prgbNative,
_Out_ DWORD *pcbNative
)
{
HRESULT hr = E_OUTOFMEMORY;
PWSTR pszDomainUsername = nullptr;
DWORD cchDomainUsername = 0;
PWSTR pszPassword = nullptr;
DWORD cchPassword = 0;
*prgbNative = nullptr;
*pcbNative = 0;
// Unpack the 32 bit KERB structure
CredUnPackAuthenticationBufferW(CRED_PACK_WOW_BUFFER, rgbWow, cbWow, pszDomainUsername, &cchDomainUsername, nullptr, nullptr, pszPassword, &cchPassword);
if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
{
pszDomainUsername = (PWSTR) LocalAlloc(0, cchDomainUsername * sizeof(wchar_t));
if (pszDomainUsername)
{
pszPassword = (PWSTR) LocalAlloc(0, cchPassword * sizeof(wchar_t));
if (pszPassword)
{
if (CredUnPackAuthenticationBufferW(CRED_PACK_WOW_BUFFER, rgbWow, cbWow, pszDomainUsername, &cchDomainUsername, nullptr, nullptr, pszPassword, &cchPassword))
{
hr = S_OK;
}
else
{
hr = GetLastError();
}
}
}
}
// Repack native
if (SUCCEEDED(hr))
{
hr = E_OUTOFMEMORY;
CredPackAuthenticationBufferW(0, pszDomainUsername, pszPassword, *prgbNative, pcbNative);
if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
{
*prgbNative = (BYTE*) LocalAlloc(LMEM_ZEROINIT, *pcbNative);
if (*prgbNative)
{
if (CredPackAuthenticationBufferW(0, pszDomainUsername, pszPassword, *prgbNative, pcbNative))
{
hr = S_OK;
}
else
{
LocalFree(*prgbNative);
}
}
}
}
LocalFree(pszDomainUsername);
if (pszPassword)
{
SecureZeroMemory(pszPassword, cchPassword * sizeof(wchar_t));
LocalFree(pszPassword);
}
return hr;
}
// Concatonates pwszDomain and pwszUsername and places the result in *ppwszDomainUsername.
HRESULT DomainUsernameStringAlloc(
_In_ PCWSTR pwszDomain,
_In_ PCWSTR pwszUsername,
_Outptr_result_nullonfailure_ PWSTR *ppwszDomainUsername
)
{
HRESULT hr;
*ppwszDomainUsername = nullptr;
size_t cchDomain = wcslen(pwszDomain);
size_t cchUsername = wcslen(pwszUsername);
// Length of domain, 1 character for '\', length of Username, plus null terminator.
size_t cbLen = sizeof(wchar_t) * (cchDomain + 1 + cchUsername +1);
PWSTR pwszDest = (PWSTR)HeapAlloc(GetProcessHeap(), 0, cbLen);
if (pwszDest)
{
hr = StringCbPrintfW(pwszDest, cbLen, L"%s\\%s", pwszDomain, pwszUsername);
if (SUCCEEDED(hr))
{
*ppwszDomainUsername = pwszDest;
}
else
{
HeapFree(GetProcessHeap(), 0, pwszDest);
}
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}
// Concatenates UPN (with @) pwszUsername and pwszDomain and places the result in *ppwszUsernameDomain.
HRESULT UpnUsernameDomainStringAlloc(
_In_ PCWSTR pwszUsername,
_In_ PCWSTR pwszDomain,
_Outptr_result_nullonfailure_ PWSTR *ppwszUsernameDomain
)
{
HRESULT hr;
*ppwszUsernameDomain = nullptr;
size_t cchUsername = wcslen(pwszUsername);
size_t cchDomain = wcslen(pwszDomain);
// Length of Username, 1 character for '@', length of domain, plus null terminator.
size_t cbLen = sizeof(wchar_t) * (cchUsername + 1 + cchDomain +1);
PWSTR pwszDest = (PWSTR)HeapAlloc(GetProcessHeap(), 0, cbLen);
if (pwszDest)
{
hr = StringCbPrintfW(pwszDest, cbLen, L"%s@%s", pwszUsername, pwszDomain);
if (SUCCEEDED(hr))
{
*ppwszUsernameDomain = pwszDest;
}
else
{
HeapFree(GetProcessHeap(), 0, pwszDest);
}
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}
HRESULT SplitDomainAndUsername(_In_ PCWSTR pszQualifiedUserName, _Outptr_result_nullonfailure_ PWSTR *ppszDomain, _Outptr_result_nullonfailure_ PWSTR *ppszUsername)
{
HRESULT hr = E_UNEXPECTED;
*ppszDomain = nullptr;
*ppszUsername = nullptr;
PWSTR pszDomain;
PWSTR pszUsername;
const wchar_t *pchWhack = wcschr(pszQualifiedUserName, L'\\');
// 2017-11-05 SysCo/al Add UPN support
const wchar_t *pchWhatSign = wcschr(pszQualifiedUserName, L'@');
const wchar_t *pchEnd = pszQualifiedUserName + wcslen(pszQualifiedUserName) - 1;
if (pchWhack != nullptr)
{
const wchar_t *pchDomainBegin = pszQualifiedUserName;
const wchar_t *pchDomainEnd = pchWhack - 1;
const wchar_t *pchUsernameBegin = pchWhack + 1;
const wchar_t *pchUsernameEnd = pchEnd;
size_t lenDomain = pchDomainEnd - pchDomainBegin + 1; // number of actual chars, NOT INCLUDING null terminated string
pszDomain = static_cast<PWSTR>(CoTaskMemAlloc(sizeof(wchar_t) * (lenDomain + 1)));
if (pszDomain != nullptr)
{
hr = StringCchCopyN(pszDomain, lenDomain + 1, pchDomainBegin, lenDomain);
if (SUCCEEDED(hr))
{
size_t lenUsername = pchUsernameEnd - pchUsernameBegin + 1; // number of actual chars, NOT INCLUDING null terminated string
pszUsername = static_cast<PWSTR>(CoTaskMemAlloc(sizeof(wchar_t) * (lenUsername + 1)));
if (pszUsername != nullptr)
{
hr = StringCchCopyN(pszUsername, lenUsername + 1, pchUsernameBegin, lenUsername);
if (SUCCEEDED(hr))
{
*ppszDomain = pszDomain;
*ppszUsername = pszUsername;
}
else
{
CoTaskMemFree(pszUsername);
}
}
else
{
hr = E_OUTOFMEMORY;
}
}
if (FAILED(hr))
{
CoTaskMemFree(pszDomain);
}
}
else
{
hr = E_OUTOFMEMORY;
}
}
// 2017-11-05 SysCo/al Add UPN support, but warning, the user and domain names are only splitted, nothing better
else if (pchWhatSign != nullptr)
{
const wchar_t *pchUsernameBegin = pszQualifiedUserName;
const wchar_t *pchUsernameEnd = pchWhatSign - 1;
const wchar_t *pchDomainBegin = pchWhatSign + 1;
const wchar_t *pchDomainEnd = pchEnd;
size_t lenDomain = pchDomainEnd - pchDomainBegin + 1; // number of actual chars, NOT INCLUDING null terminated string
pszDomain = static_cast<PWSTR>(CoTaskMemAlloc(sizeof(wchar_t) * (lenDomain + 1)));
if (pszDomain != nullptr)
{
hr = StringCchCopyN(pszDomain, lenDomain + 1, pchDomainBegin, lenDomain);
if (SUCCEEDED(hr))
{
size_t lenUsername = pchUsernameEnd - pchUsernameBegin + 1; // number of actual chars, NOT INCLUDING null terminated string
pszUsername = static_cast<PWSTR>(CoTaskMemAlloc(sizeof(wchar_t) * (lenUsername + 1)));
if (pszUsername != nullptr)
{
hr = StringCchCopyN(pszUsername, lenUsername + 1, pchUsernameBegin, lenUsername);
if (SUCCEEDED(hr))
{
*ppszDomain = pszDomain;
*ppszUsername = pszUsername;
}
else
{
CoTaskMemFree(pszUsername);
}
}
else
{
hr = E_OUTOFMEMORY;
}
}
if (FAILED(hr))
{
CoTaskMemFree(pszDomain);
}
}
else
{
hr = E_OUTOFMEMORY;
}
}
return hr;
}
//pack the struct of KERB_CHANGEPASSWORD_REQUEST
HRESULT KerbChangePasswordPack(
const KERB_CHANGEPASSWORD_REQUEST& kcpr,
BYTE** prgb,
DWORD* pcb
)
{
HRESULT hr;
DWORD cb = sizeof(kcpr) +
kcpr.DomainName.Length +
kcpr.AccountName.Length +
kcpr.OldPassword.Length +
kcpr.NewPassword.Length;
KERB_CHANGEPASSWORD_REQUEST* pkcpr = (KERB_CHANGEPASSWORD_REQUEST*)CoTaskMemAlloc(cb);
if (pkcpr)
{
pkcpr->MessageType = kcpr.MessageType;
BYTE* pbBuffer = (BYTE*)pkcpr + sizeof(KERB_CHANGEPASSWORD_REQUEST);
_UnicodeStringPackedUnicodeStringCopy(kcpr.DomainName, (PWSTR)pbBuffer, &pkcpr->DomainName);
pkcpr->DomainName.Buffer = (PWSTR)(pbBuffer - (BYTE*)pkcpr);
pbBuffer += pkcpr->DomainName.Length;
_UnicodeStringPackedUnicodeStringCopy(kcpr.AccountName, (PWSTR)pbBuffer, &pkcpr->AccountName);
pkcpr->AccountName.Buffer = (PWSTR)(pbBuffer - (BYTE*)pkcpr);
pbBuffer += pkcpr->AccountName.Length;
_UnicodeStringPackedUnicodeStringCopy(kcpr.OldPassword, (PWSTR)pbBuffer, &pkcpr->OldPassword);
pkcpr->OldPassword.Buffer = (PWSTR)(pbBuffer - (BYTE*)pkcpr);
pbBuffer += pkcpr->OldPassword.Length;
_UnicodeStringPackedUnicodeStringCopy(kcpr.NewPassword, (PWSTR)pbBuffer, &pkcpr->NewPassword);
pkcpr->NewPassword.Buffer = (PWSTR)(pbBuffer - (BYTE*)pkcpr);
*prgb = (BYTE*)pkcpr;
*pcb = cb;
hr = S_OK;
}
else
{
hr = E_OUTOFMEMORY;
}
return hr;
}