-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathPassFiltEx.c
1267 lines (1169 loc) · 36.7 KB
/
PassFiltEx.c
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
PassFiltEx.c
PassFiltEx by Joseph Ryan Ries
Author: Joseph Ryan Ries 2019-2025 <[email protected]>,<[email protected]>
A password filter for Active Directory that uses a blocklist of bad passwords/character sequences
and also has some other options for a more robust password policy.
Technical Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ms721882(v=vs.85).aspx
********************************************************************************************
# READ ME
This is a personal project and is NOT endorsed or supported by Microsoft in any way.
Use at your own risk. This code is not guaranteed to be free of errors, and comes
with no guarantees, liability, warranties or support.
********************************************************************************************
01/29/2025: I have removed the rest of the readme text. See the external README.md file for more info.
*/
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"
#pragma clang diagnostic ignored "-Wdeclaration-after-statement"
#define WIN32_LEAN_AND_MEAN
#define UNICODE
#define WIN32_NO_STATUS
#include <Windows.h>
#undef WIN32_NO_STATUS
#include <intrin.h>
#include <NTSecAPI.h>
#include <ntstatus.h>
#include <stdio.h>
#include <lm.h>
#pragma comment(lib, "Netapi32.lib")
#pragma comment(lib, "Advapi32.lib")
#include "PassFiltEx.h"
static HANDLE gLogFileHandle = INVALID_HANDLE_VALUE;
static HANDLE gBlocklistThread;
static CRITICAL_SECTION gBlocklistCritSec;
static CRITICAL_SECTION gLogCritSec;
static BADSTRING* gBlocklistHead;
static FILETIME gBlockListOldFileTime;
static FILETIME gBlockListNewFileTime;
static LARGE_INTEGER gPerformanceFrequency;
static DWORD gTokenPercentageOfPassword;
static wchar_t gBlocklistFileName[256] = { L"PassFiltExBlocklist.txt" };
static wchar_t gApplyToTheseGroups[1024];
static DWORD gRequireEitherUpperOrLower;
static DWORD gMinLower;
static DWORD gMinUpper;
static DWORD gMinDigit;
static DWORD gMinSpecial;
static DWORD gMinUnicode;
static DWORD gBlockSequential;
static DWORD gBlockRepeating;
static DWORD gDebug;
/*
DllMain
-------
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
The safest DllMain is one that does nothing.
*/
BOOL WINAPI DllMain(_In_ HINSTANCE DLLHandle, _In_ DWORD Reason, _In_ LPVOID Reserved)
{
UNREFERENCED_PARAMETER(DLLHandle);
UNREFERENCED_PARAMETER(Reason);
UNREFERENCED_PARAMETER(Reserved);
return(TRUE);
}
/*
InitializeChangeNotify
----------------------
The InitializeChangeNotify function is implemented by a password filter DLL. This function initializes the DLL.
Parameters:
None.
Return value:
TRUE
The password filter DLL is initialized.
FALSE
The password filter DLL is not initialized.
Remarks:
InitializeChangeNotify is called by the Local Security Authority (LSA) to verify that the password notification DLL is loaded and initialized.
This function must use the __stdcall calling convention, and must be exported by the DLL.
This function is called only for password filters that are installed and registered on a system.
*/
__declspec(dllexport) BOOL CALLBACK InitializeChangeNotify(void)
{
if ((gLogFileHandle = CreateFileW(FILTER_LOG_FILE_NAME, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
{
OutputDebugStringW(L"ERROR: Failed to create or open log file " FILTER_LOG_FILE_NAME L"!\n");
ASSERT(0);
return(FALSE);
}
// DO NOT ATTEMPT TO LOG ANYTHING UNTIL THESE CRITICAL SECTIONS ARE INITIALIZED
(void)InitializeCriticalSectionAndSpinCount(&gBlocklistCritSec, 100);
(void)InitializeCriticalSectionAndSpinCount(&gLogCritSec, 100);
QueryPerformanceFrequency(&gPerformanceFrequency);
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] %s %s is starting.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
L"PassFiltEx",
FILTER_VERSION_STRING);
if ((gBlocklistThread = CreateThread(NULL, 0, BlocklistThreadProc, NULL, 0, NULL)) == NULL)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] Failed to create blocklist update thread! Error 0x%08lx",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
GetLastError());
ASSERT(0);
return(FALSE);
}
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Blocklist update thread created.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
return(TRUE);
}
/*
PasswordChangeNotify
--------------------
The PasswordChangeNotify function is implemented by a password filter DLL. It notifies the DLL that a password was changed.
Parameters:
UserName [in]
The account name of the user whose password changed.
If the values of this parameter and the NewPassword parameter are NULL, this function should return STATUS_SUCCESS.
RelativeId [in]
The relative identifier (RID) of the user specified in UserName.
NewPassword [in]
A new plaintext password for the user specified in UserName. When you have finished using the password, clear the
information by calling the SecureZeroMemory function. For more information about protecting passwords, see Handling Passwords.
If the values of this parameter and the UserName parameter are NULL, this function should return STATUS_SUCCESS.
Return value:
STATUS_SUCCESS
Indicates the password of the user was changed, or that the values of both the UserName and NewPassword parameters are NULL.
Remarks:
The PasswordChangeNotify function is called after the PasswordFilter function has been called successfully and the new password has been stored.
This function must use the __stdcall calling convention and must be exported by the DLL.
When the PasswordChangeNotify routine is running, processing is blocked until the routine is finished. When appropriate, move any
lengthy processing to a separate thread prior to returning from this routine.
This function is called only for password filters that are installed and registered on the system.
Any process exception that is not handled within this function may cause security-related failures system-wide.
Structured exception handling should be used when appropriate.
*/
__declspec(dllexport) NTSTATUS CALLBACK PasswordChangeNotify(_In_ PUNICODE_STRING UserName, _In_ ULONG RelativeId, _In_ PUNICODE_STRING NewPassword)
{
UNREFERENCED_PARAMETER(NewPassword);
// UNICODE_STRINGs might not be null-terminated.
// Let's make a null-terminated copy of it.
// MSDN says that the upper limit of sAMAccountName is 256
// but SAM is AFAIK restricted to <= 20 characters. Let's pick a safe buffer size.
wchar_t UserNameCopy[257] = { 0 };
memcpy_s(&UserNameCopy, sizeof(UserNameCopy) - 1, UserName->Buffer, UserName->Length);
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Password for %s (RID %lu) was changed.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
UserNameCopy,
RelativeId);
return(STATUS_SUCCESS);
}
/*
PasswordFilter
--------------
The PasswordFilter function is implemented by a password filter DLL. The value returned by this function determines whether the new password is accepted by the system.
All of the password filters installed on a system must return TRUE for the password change to take effect.
Parameters:
AccountName [in]
Pointer to a UNICODE_STRING that represents the name of the user whose password changed.
FullName [in]
Pointer to a UNICODE_STRING that represents the full name of the user whose password changed.
Password [in]
Pointer to a UNICODE_STRING that represents the new plaintext password. When you have finished using the password, clear it from memory by calling the SecureZeroMemory function.
SetOperation [in]
TRUE if the password was set rather than changed.
Return value:
TRUE
Return TRUE if the new password is valid with respect to the password policy implemented in the password filter DLL.
When TRUE is returned, the Local Security Authority (LSA) continues to evaluate the password by calling any other password filters installed on the system.
FALSE
Return FALSE if the new password is not valid with respect to the password policy implemented in the password filter DLL.
When FALSE is returned, the LSA returns the ERROR_ILL_FORMED_PASSWORD (1324) status code to the source of the password change request.
Remarks:
Password change requests may be made when users specify a new password, accounts are created and when administrators override a password.
This function must use the __stdcall calling convention and must be exported by the DLL.
When the PasswordFilter routine is running, processing is blocked until the routine is finished. When appropriate, move any lengthy processing to a separate thread prior to returning from this routine.
This function is called only for password filters that are installed and registered on a system.
Any process exception that is not handled within this function may cause security-related failures system-wide. Structured exception handling should be used when appropriate.
*/
__declspec(dllexport) BOOL CALLBACK PasswordFilter(_In_ PUNICODE_STRING AccountName, _In_ PUNICODE_STRING FullName, _In_ PUNICODE_STRING Password, _In_ BOOL SetOperation)
{
UNREFERENCED_PARAMETER(FullName);
BOOL PasswordIsOK = TRUE;
BOOL SkipThisUser = TRUE;
size_t PasswordCopyLen = 0;
DWORD NumLowers = 0;
DWORD NumUppers = 0;
DWORD NumDigits = 0;
DWORD NumSpecials = 0;
DWORD NumUnicodes = 0;
LARGE_INTEGER StartTime = { 0 };
LARGE_INTEGER EndTime = { 0 };
LARGE_INTEGER ElapsedMicroseconds = { 0 };
EnterCriticalSection(&gBlocklistCritSec);
QueryPerformanceCounter(&StartTime);
BADSTRING* CurrentNode = gBlocklistHead;
// UNICODE_STRINGs are usually not null-terminated.
// Let's make a null-terminated copy of it.
// MSDN says that the upper limit of sAMAccountName is 256
// but SAM is AFAIK restricted to <= 20 characters.
// Anyway, let's pick a safe buffer size.
wchar_t AccountNameCopy[257] = { 0 };
wchar_t PasswordCopy[257] = { 0 };
memcpy_s(&AccountNameCopy, sizeof(AccountNameCopy) - 1, AccountName->Buffer, AccountName->Length);
if (wcscmp(AccountNameCopy, L"krbtgt") == 0)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Always allowing password change for krbtgt account.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
goto End;
}
if (wcsncmp(L"krbtgt_", AccountNameCopy, wcslen(L"krbtgt_")) == 0)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Always allowing password change for RODC krbtgt account.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
goto End;
}
memcpy_s(&PasswordCopy, sizeof(PasswordCopy) - 1, Password->Buffer, Password->Length);
PasswordCopyLen = wcslen(PasswordCopy);
// Don't print the password.
if (SetOperation)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Attempting to SET password for user %s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
AccountNameCopy);
}
else
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Attempting to CHANGE password for user %s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
AccountNameCopy);
}
if (Password->Length > 0)
{
for (size_t Counter = 0; Counter < PasswordCopyLen; Counter++)
{
PasswordCopy[Counter] = towlower(PasswordCopy[Counter]);
}
}
else
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Empty password! Cannot continue.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
PasswordIsOK = FALSE;
goto End;
}
// NOTE: Currently this only scans top-level global security group membership of the user.
// It does NOT expand all nested group membership.
// I do this on purpose because this is much faster, and I'm worried that calculating all nested
// group membership could slow us down too much.
if (wcslen(gApplyToTheseGroups) > 0)
{
NET_API_STATUS Status = ERROR_SUCCESS;
LPGROUP_USERS_INFO_0 GroupMemberships = NULL;
DWORD EntriesRead = 0;
DWORD TotalEntries = 0;
Status = NetUserGetGroups(
NULL,
AccountNameCopy,
0,
(LPBYTE*)&GroupMemberships,
MAX_PREFERRED_LENGTH,
&EntriesRead,
&TotalEntries);
if ((Status == NERR_Success) && (EntriesRead > 0) && (EntriesRead == TotalEntries))
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] %d group memberships found for user %s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
EntriesRead,
AccountNameCopy);
// gApplyToThesegroups always ends with a comma.
wchar_t GroupName[256] = { 0 };
wchar_t* c = gApplyToTheseGroups;
int idx = 0;
while (*c != L'\0')
{
if (*c != ',')
{
GroupName[idx++] = *c;
}
else
{
GroupName[idx] = L'\0';
for (DWORD g = 0; g < EntriesRead; g++)
{
//LogMessageW(LOG_DEBUG, L"Comparing GroupName %s to %s", GroupName, GroupMemberships[g].grui0_name);
if (_wcsicmp(GroupName, GroupMemberships[g].grui0_name) == 0)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] User %s was found to be a member of group %s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
AccountNameCopy,
GroupMemberships[g].grui0_name);
SkipThisUser = FALSE;
break;
}
}
idx = 0;
memset(GroupName, 0, sizeof(GroupName));
}
if (SkipThisUser == FALSE)
{
break;
}
c++;
}
}
else
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] ERROR: NetUserGetGroups failed with 0x%08lx while trying to check the group memberships for %s!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
Status,
AccountNameCopy);
if (GroupMemberships)
{
NetApiBufferFree(GroupMemberships);
}
PasswordIsOK = FALSE;
goto End;
}
if (GroupMemberships)
{
NetApiBufferFree(GroupMemberships);
}
}
else
{
LogMessageW(LOG_DEBUG,
L"[%s:%s@%d] Not filtering by security group.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
SkipThisUser = FALSE;
}
if (SkipThisUser)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Skipping the user %s because they are not a member of any of the groups specified in the registry setting %s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
AccountNameCopy,
FILTER_REG_APPLY_TO_GROUPS);
goto End;
}
while (CurrentNode != NULL && CurrentNode->Next != NULL)
{
CurrentNode = CurrentNode->Next;
if (wcsnlen(CurrentNode->String, MAX_BLOCKLIST_STRING_SIZE) == 0)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] ERROR: This blocklist token is 0 characters long. It will be skipped. Remove blank lines from your blocklist file!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
continue;
}
// if the blocklisted string starts with ! that means this string is totally forbidden regardless of how big the overall password is.
// else we will honor the gTokenPercentageOfPassword rule.
// the password copy has already been towlower'd at this point; this is a case-insensitive search
if (CurrentNode->String[0] == '!')
{
if (wcsstr(PasswordCopy, CurrentNode->String + 1))
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because it contains the super-blocked string \"%s\"!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
CurrentNode->String + 1);
PasswordIsOK = FALSE;
goto End;
}
}
else
{
if (wcsstr(PasswordCopy, CurrentNode->String))
{
if (((float)wcslen(CurrentNode->String) / (float)wcslen(PasswordCopy)) >= (float)gTokenPercentageOfPassword / 100)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because it contains the blocklisted string \"%s\" and it is at least %lu%% of the full password!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
CurrentNode->String,
gTokenPercentageOfPassword);
PasswordIsOK = FALSE;
goto End;
}
}
}
}
// Here we look at the original Password and not the toLowered PasswordCopy because we need case sensitivity for this section.
for (size_t Character = 0; Character < PasswordCopyLen; Character++)
{
if ((Password->Buffer[Character] >= ASCII_LOWERCASE_BEGIN) && (Password->Buffer[Character] <= ASCII_LOWERCASE_END))
{
NumLowers++;
}
if ((Password->Buffer[Character] >= ASCII_UPPERCASE_BEGIN) && (Password->Buffer[Character] <= ASCII_UPPERCASE_END))
{
NumUppers++;
}
if ((Password->Buffer[Character] >= ASCII_DIGITS_BEGIN) && (Password->Buffer[Character] <= ASCII_DIGITS_END))
{
NumDigits++;
}
if (((Password->Buffer[Character] >= 32 && Password->Buffer[Character] <= 47) ||
(Password->Buffer[Character] >= 58 && Password->Buffer[Character] <= 64) ||
(Password->Buffer[Character] >= 91 && Password->Buffer[Character] <= 96) ||
(Password->Buffer[Character] >= 123 && Password->Buffer[Character] <= 126) ||
(Password->Buffer[Character] >= 128 && Password->Buffer[Character] <= 255)))
{
NumSpecials++;
}
if ((Password->Buffer[Character] > 255))
{
NumUnicodes++;
}
}
// Not printing this in Release builds because I guess it would give too much detail about the user's password.
#ifdef _DEBUG
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Password composition: %d lowers, %d uppers, %d digits, %d specials, %d unicode.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
NumLowers,
NumUppers,
NumDigits,
NumSpecials,
NumUnicodes);
#endif
if (gRequireEitherUpperOrLower)
{
if (NumLowers + NumUppers == 0)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because %s is set but the password contains no uppercase or lowercase letters.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_REQUIRE_EITHER_LOWER_OR_UPPER);
PasswordIsOK = FALSE;
goto End;
}
}
if (NumLowers < gMinLower)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because %s is set to require %d lowercase letters, but the password contained %d lowercase letters.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_MIN_LOWER,
gMinLower,
NumLowers);
PasswordIsOK = FALSE;
goto End;
}
if (NumUppers < gMinUpper)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because %s is set to require %d uppercase letters, but the password contained %d uppercase letters.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_MIN_UPPER,
gMinUpper,
NumUppers);
PasswordIsOK = FALSE;
goto End;
}
if (NumDigits < gMinDigit)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because %s is set to require %d digits, but the password contained %d digits.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_MIN_DIGIT,
gMinDigit,
NumDigits);
PasswordIsOK = FALSE;
goto End;
}
if (NumSpecials < gMinSpecial)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because %s is set to require %d special symbols, but the password contained %d special characters.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_MIN_SPECIAL,
gMinSpecial,
NumSpecials);
PasswordIsOK = FALSE;
goto End;
}
if (NumUnicodes < gMinUnicode)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because %s is set to require %d unicode symbols, but the password contained %d unicode symbols.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_MIN_UNICODE,
gMinUnicode,
NumUnicodes);
PasswordIsOK = FALSE;
goto End;
}
// Only check alphanumeric characters for sequences, so block abc and 123 but not !@#
if (gBlockSequential)
{
for (size_t Character = 0; Character < PasswordCopyLen - 2; Character++)
{
if (((Password->Buffer[Character] >= ASCII_LOWERCASE_BEGIN) && (Password->Buffer[Character] <= ASCII_LOWERCASE_END)) ||
((Password->Buffer[Character] >= ASCII_UPPERCASE_BEGIN) && (Password->Buffer[Character] <= ASCII_UPPERCASE_END)) ||
((Password->Buffer[Character] >= ASCII_DIGITS_BEGIN) && (Password->Buffer[Character] <= ASCII_DIGITS_END)))
{
if ((Password->Buffer[Character + 1] == Password->Buffer[Character] + 1) &&
(Password->Buffer[Character + 2] == Password->Buffer[Character] + 2))
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because a sequential set was detected (e.g. 'abc' or '123' etc.) and %s is set to block it.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_BLOCK_SEQUENTIAL);
PasswordIsOK = FALSE;
goto End;
}
}
}
}
if (gBlockRepeating)
{
for (size_t Character = 0; Character < PasswordCopyLen - 2; Character++)
{
if ((Password->Buffer[Character + 1] == Password->Buffer[Character]) &&
(Password->Buffer[Character + 2] == Password->Buffer[Character]))
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Rejecting password because of repeating chars (e.g. 'aaa' or '1111' etc.) and %s is set to block it.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_BLOCK_REPEATING);
PasswordIsOK = FALSE;
goto End;
}
}
}
End:
QueryPerformanceCounter(&EndTime);
ElapsedMicroseconds.QuadPart = EndTime.QuadPart - StartTime.QuadPart;
ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= gPerformanceFrequency.QuadPart;
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Finished in %llu microseconds. Will accept new password: %s",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
ElapsedMicroseconds.QuadPart,
(PasswordIsOK == 0 ? L"FALSE" : L"TRUE"));
// NOTE: Despite what the MSDN documentation says, we should NOT be clearing the original password buffer that was passed in to us by Windows.
// We only need to clear any copies of the password that we have made.
//RtlSecureZeroMemory(&Password, Password->Length);
RtlSecureZeroMemory(PasswordCopy, sizeof(PasswordCopy));
LeaveCriticalSection(&gBlocklistCritSec);
return(PasswordIsOK);
}
DWORD WINAPI BlocklistThreadProc(_In_ LPVOID Args)
{
UNREFERENCED_PARAMETER(Args);
while (TRUE)
{
HANDLE BlocklistFileHandle = INVALID_HANDLE_VALUE;
LARGE_INTEGER StartTime = { 0 };
LARGE_INTEGER EndTime = { 0 };
LARGE_INTEGER ElapsedMicroseconds = { 0 };
EnterCriticalSection(&gBlocklistCritSec);
QueryPerformanceCounter(&StartTime);
if (UpdateConfigurationFromRegistry() != ERROR_SUCCESS)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] Failed to update configuration from registry! Something is very wrong!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
ASSERT(0);
goto Sleep;
}
// We are being loaded by lsass.exe. The current working directory of lsass should be C:\Windows\System32
if ((BlocklistFileHandle = CreateFileW(gBlocklistFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
{
wchar_t CurrentDir[MAX_PATH] = { 0 };
GetCurrentDirectoryW(MAX_PATH, CurrentDir);
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] Unable to open file %s! Current working directory: %s. Error 0x%08lx",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
gBlocklistFileName,
CurrentDir,
GetLastError());
goto Sleep;
}
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] %s opened for read.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
gBlocklistFileName);
if (GetFileTime(BlocklistFileHandle, NULL, NULL, &gBlockListNewFileTime) == 0)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] Failed to call GetFileTime on %s! Error 0x%08lx",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
gBlocklistFileName,
GetLastError());
ASSERT(0);
goto Sleep;
}
if ((CompareFileTime(&gBlockListNewFileTime, &gBlockListOldFileTime) != 0) || gBlockListOldFileTime.dwLowDateTime == 0)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] The last modified time of %s has changed since the last time we looked. Reloading the file.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
gBlocklistFileName);
// Initialize list head if we're here for the first time.
if (gBlocklistHead == NULL)
{
if ((gBlocklistHead = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BADSTRING))) == NULL)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] ERROR: Failed to allocate memory for list head!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
ASSERT(0);
goto Sleep;
}
}
// Need to clear blocklist and free memory first.
BADSTRING* CurrentNode = gBlocklistHead;
BADSTRING* NextNode = CurrentNode->Next;
while (NextNode != NULL)
{
CurrentNode = NextNode;
NextNode = CurrentNode->Next;
if (HeapFree(GetProcessHeap(), 0, CurrentNode) == 0)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] HeapFree failed while clearing blocklist! Error 0x%08lx",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
GetLastError());
ASSERT(0);
goto Sleep;
}
}
// Create a new node for the first line of text in the file.
if ((CurrentNode = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BADSTRING))) == NULL)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] ERROR: Failed to allocate memory for list node!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
ASSERT(0);
goto Sleep;
}
gBlocklistHead->Next = CurrentNode;
DWORD TotalBytesRead = 0;
DWORD BytesRead = 0;
BYTE Read = 0;
DWORD BytesOnThisLine = 0;
DWORD LinesRead = 1;
while (TRUE)
{
if (ReadFile(BlocklistFileHandle, &Read, 1, &BytesRead, NULL) == FALSE)
{
break;
}
if (BytesRead == 0)
{
break;
}
if (BytesOnThisLine >= MAX_BLOCKLIST_STRING_SIZE - 1)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] WARNING: Line longer than max length of %d! Will truncate this line and attempt to resume reading the next line.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
MAX_BLOCKLIST_STRING_SIZE);
Read = 0x0A;
}
// Ignore unprintable characters
if (Read < 0x20)
{
// Unless it's \n
if (Read != 0x0A)
{
TotalBytesRead++;
continue;
}
}
if (Read == 0x0A)
{
BytesOnThisLine = 0;
BADSTRING* NewNode = NULL;
if ((NewNode = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(BADSTRING))) == NULL)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] ERROR: Failed to allocate memory for list node!",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__);
ASSERT(0);
goto Sleep;
}
CurrentNode->Next = NewNode;
CurrentNode = NewNode;
TotalBytesRead++;
LinesRead++;
continue;
}
CurrentNode->String[BytesOnThisLine] = (wchar_t)towlower(Read);
TotalBytesRead++;
BytesOnThisLine++;
}
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Read %lu bytes, %lu lines from file %s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
TotalBytesRead,
LinesRead,
gBlocklistFileName);
}
Sleep:
if (BlocklistFileHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(BlocklistFileHandle);
}
gBlockListOldFileTime = gBlockListNewFileTime;
QueryPerformanceCounter(&EndTime);
ElapsedMicroseconds.QuadPart = EndTime.QuadPart - StartTime.QuadPart;
ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= gPerformanceFrequency.QuadPart;
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Finished in %llu microseconds.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
ElapsedMicroseconds.QuadPart);
LeaveCriticalSection(&gBlocklistCritSec);
Sleep(BLOCKLIST_THREAD_RUN_FREQUENCY);
}
return(0);
}
DWORD UpdateConfigurationFromRegistry(void)
{
DWORD Status = ERROR_SUCCESS;
HKEY SubKeyHandle = NULL;
DWORD SubKeyDisposition = 0;
DWORD RegDataSize = 0;
typedef struct DWORD_REG_SETTING
{
wchar_t* Name;
void* Destination;
DWORD MinValue;
DWORD MaxValue;
DWORD DefaultValue;
} DWORD_REG_SETTING;
DWORD_REG_SETTING DwordRegValues[] = {
{ .Name = FILTER_REG_DEBUG, .Destination = &gDebug, .MinValue = 0, .MaxValue = 1, .DefaultValue = 0 },
{ .Name = FILTER_REG_REQUIRE_EITHER_LOWER_OR_UPPER, .Destination = &gRequireEitherUpperOrLower, .MinValue = 0, .MaxValue = 1, .DefaultValue = 0 },
{ .Name = FILTER_REG_TOKEN_PERCENTAGE_OF_PASSWORD, .Destination = &gTokenPercentageOfPassword, .MinValue = 0, .MaxValue = 100, .DefaultValue = 60 },
{ .Name = FILTER_REG_MIN_LOWER, .Destination = &gMinLower, .MinValue = 0, .MaxValue = 16, .DefaultValue = 0 },
{ .Name = FILTER_REG_MIN_UPPER, .Destination = &gMinUpper, .MinValue = 0, .MaxValue = 16, .DefaultValue = 0 },
{ .Name = FILTER_REG_MIN_DIGIT, .Destination = &gMinDigit, .MinValue = 0, .MaxValue = 16, .DefaultValue = 0 },
{ .Name = FILTER_REG_MIN_SPECIAL, .Destination = &gMinSpecial, .MinValue = 0, .MaxValue = 16, .DefaultValue = 0 },
{ .Name = FILTER_REG_MIN_UNICODE, .Destination = &gMinUnicode, .MinValue = 0, .MaxValue = 16, .DefaultValue = 0 },
{ .Name = FILTER_REG_BLOCK_SEQUENTIAL, .Destination = &gBlockSequential, .MinValue = 0, .MaxValue = 1, .DefaultValue = 0 },
{ .Name = FILTER_REG_BLOCK_REPEATING, .Destination = &gBlockRepeating, .MinValue = 0, .MaxValue = 1, .DefaultValue = 0 }
};
if ((Status = RegCreateKeyExW(HKEY_LOCAL_MACHINE, FILTER_REG_SUBKEY, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &SubKeyHandle, &SubKeyDisposition)) != ERROR_SUCCESS)
{
LogMessageW(
LOG_ERROR,
L"[%s:%s@%d] Failed to open or create registry key HKLM\\%s! Error 0x%08lx",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_SUBKEY,
Status);
ASSERT(0);
goto Exit;
}
if (SubKeyDisposition == REG_CREATED_NEW_KEY)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Created new registry subkey HKLM\\%s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_SUBKEY);
}
else if (SubKeyDisposition == REG_OPENED_EXISTING_KEY)
{
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Opened existing registry subkey HKLM\\%s.",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
FILTER_REG_SUBKEY);
}
for (unsigned int setting = 0; setting < __crt_countof(DwordRegValues); setting++)
{
RegDataSize = (DWORD)sizeof(DWORD);
if ((Status = RegGetValueW(SubKeyHandle, NULL, DwordRegValues[setting].Name, RRF_RT_DWORD, NULL, DwordRegValues[setting].Destination, &RegDataSize)) != ERROR_SUCCESS)
{
if (Status == ERROR_FILE_NOT_FOUND)
{
*(DWORD*)DwordRegValues[setting].Destination = DwordRegValues[setting].DefaultValue;
LogMessageW(
LOG_DEBUG,
L"[%s:%s@%d] Registry value %s was not found. Using previous or default value %lu",
__FILENAMEW__,
__FUNCTIONW__,
__LINE__,
DwordRegValues[setting].Name,
*(DWORD*)DwordRegValues[setting].Destination);
Status = ERROR_SUCCESS;
}
else
{
LogMessageW(
LOG_ERROR,