-
Notifications
You must be signed in to change notification settings - Fork 214
/
PRT_Utils.ps1
1221 lines (1043 loc) · 41.5 KB
/
PRT_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
# Aug 21st 2020
function Register-DeviceToAzureAD
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DeviceName,
[Parameter(Mandatory=$False)]
[String]$DeviceType,
[Parameter(Mandatory=$False)]
[String]$OSVersion,
[Parameter(Mandatory=$False)]
[Bool]$SharedDevice=$False,
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(Mandatory=$False)]
[String]$DomainName,
[Parameter(Mandatory=$False)]
[Guid]$TenantId,
[Parameter(Mandatory=$False)]
[String]$DomainController,
[Parameter(Mandatory=$False)]
[String]$SID,
[Parameter(Mandatory=$False)]
[Bool]$RegisterOnly=$false
)
Process
{
# If certificate provided, this is a Hybrid Join
if($hybrid = $Certificate -ne $null)
{
# Load the "user" certificate private key
try
{
$privateKey = Load-PrivateKey -Certificate $Certificate
}
catch
{
Write-Error "Could not extract the private key from the given certificate!"
return
}
$deviceId = $certificate.Subject.Split("=")[1]
try
{
$deviceIdGuid = [Guid]$deviceId
}
catch
{
Write-Error "The certificate subject is not a valid device id (GUID)!"
return
}
# Create the signature blob
$clientIdentity = "$($SID).$((Get-Date).ToUniversalTime().ToString("u"))"
$bClientIdentity = [System.Text.Encoding]::ASCII.GetBytes($clientIdentity)
$signedBlob = $privateKey.SignData($bClientIdentity, "SHA256")
$b64SignedBlob = Convert-ByteArrayToB64 -Bytes $signedBlob
}
else
{
# Get the domain and tenant id
$at_info = Read-Accesstoken -AccessToken $AccessToken
if([string]::IsNullOrEmpty($DomainName))
{
if($at_info.upn)
{
$DomainName = $at_info.upn.Split("@")[1]
}
else
{
# Access Token fetched with SAML token so no upn
# "unique_name" = "http://<domain>/adfs/services/trust/#"
$DomainName = $at_info.unique_name.split("/")[2]
$hybridSAML = $true
}
}
$tenantId = [GUID]$at_info.tid
$headers=@{"Authorization" = "Bearer $AccessToken"}
}
# Create a private key
$rsa = [System.Security.Cryptography.RSA]::Create(2048)
# Initialize the Certificate Signing Request object
$CN = "CN=7E980AD9-B86D-4306-9425-9AC066FB014A"
$req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($CN, $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
# Create the signing request
$csr = Convert-ByteArrayToB64 -Bytes $req.CreateSigningRequest()
# Use the device private key as a transport key just to make things simpler
$transportKey = Convert-ByteArrayToB64 -Bytes $rsa.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::GenericPublicBlob)
# Create the request body
# JoinType 0 = Azure AD join, transport key = device key
# JoinType 4 = Azure AD registered, transport key = device key
# JoinType 6 = Azure AD hybrid join, transport key = device key. Hybrid join this way is not supported, there must be an existing device with user cert.
$body=@{
"CertificateRequest" = @{
"Type" = "pkcs10"
"Data" = $csr
}
"Attributes" = @{
"ReuseDevice" = "$true"
"ReturnClientSid" = "$true"
"SharedDevice" = "$SharedDevice"
}
}
if($hybrid)
{
$body["JoinType"] = 6 # Hybrid Join
$body["ServerAdJoinData"] = @{
"TransportKey" = $transportKey
"TargetDomain" = $DomainName
"DeviceType" = $DeviceType
"OSVersion" = $OSVersion
"DeviceDisplayName" = $DeviceName
"SourceDomainController" = $DomainController
"TargetDomainId" = $tenantId.ToString()
"ClientIdentity" = @{
"Type" = "sha256signed"
"Sid" = $clientIdentity
"SignedBlob" = $b64SignedBlob
}
}
}
else
{
if($hybridSAML)
{
$body["JoinType"] = 6 # Hybrid Join
}
elseif($RegisterOnly)
{
$body["JoinType"] = 4 # Register
}
else
{
$body["JoinType"] = 0 # Join
}
$body["TransportKey"] = $transportKey
$body["TargetDomain"] = $DomainName
$body["DeviceType"] = $DeviceType
$body["OSVersion"] = $OSVersion
$body["DeviceDisplayName"] = $DeviceName
}
# Make the enrollment request
try
{
if($hybrid)
{
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/device/$deviceId`?api-version=1.0" -Body $($body | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8"
}
else
{
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/device/?api-version=1.0" -Headers $headers -Body $($body | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8"
}
}
catch
{
Write-Error $_
return
}
Write-Debug "RESPONSE: $response"
# Get the certificate
$binCert = [byte[]] (Convert-B64ToByteArray -B64 $response.Certificate.RawBody)
# Create a new x509certificate
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($binCert,"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet -band [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
# Store the private key to so that it can be exported
$cspParameters = [System.Security.Cryptography.CspParameters]::new()
$cspParameters.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"
$cspParameters.ProviderType = 24
$cspParameters.KeyContainerName ="AADInternals"
# Set the private key
$privateKey = [System.Security.Cryptography.RSACryptoServiceProvider]::new(2048,$cspParameters)
$privateKey.ImportParameters($rsa.ExportParameters($true))
$cert.PrivateKey = $privateKey
# Return
$returnValue=@(
$cert
$response
)
return $returnValue
}
}
# Aug 21st 2020
function Sign-JWT
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(Mandatory=$False)]
[Byte[]]$Key,
[Parameter(Mandatory=$True)]
[byte[]]$Data
)
Process
{
if($PrivateKey)
{
# Sign the JWT (RS256)
$signature = $PrivateKey.SignData($Data, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
}
else
{
# Sign the JWT (HS256)
$hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList @(,$Key)
$signature = $hmac.ComputeHash($Data)
$hmac.Dispose()
}
# Return
return $signature
}
}
# Aug 24th 2020
# Derives a 32 byte key using the given context and session key
function Get-PRTDerivedKey
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Byte',Mandatory=$True)]
[byte[]]$Context,
[Parameter(ParameterSetName='Byte',Mandatory=$True)]
[byte[]]$SessionKey,
[Parameter(ParameterSetName='B64',Mandatory=$True)]
[string]$B64Context,
[Parameter(ParameterSetName='B64',Mandatory=$True)]
[string]$B64SessionKey,
[Parameter(ParameterSetName='Hex',Mandatory=$True)]
[string]$HexContext,
[Parameter(ParameterSetName='Hex',Mandatory=$True)]
[string]$HexSessionKey
)
Process
{
if($B64Context)
{
$Context = Convert-B64ToByteArray $B64Context
$SessionKey = Convert-B64ToByteArray $B64SessionKey
}
elseif($HexContext)
{
$Context = Convert-HexToByteArray $HexContext
$SessionKey = Convert-HexToByteArray $HexSessionKey
}
# Fixed label
$label = [text.encoding]::UTF8.getBytes("AzureAD-SecureConversation")
# Derive the decryption key using a standard NIST SP 800-108 KDF
# As the key size is only 32 bytes (256 bits), no need to loop :)
$computeValue = @(0x00,0x00,0x00,0x01) + $label + @(0x00) + $Context + @(0x00,0x00,0x01,0x00)
$hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList @(,$SessionKey)
$hmacOutput = $hmac.ComputeHash($computeValue)
Write-Verbose "DerivedKey: $(Convert-ByteArrayToHex $hmacOutput)"
# Return
$hmacOutput
}
}
# Get the access token with PRT
# Aug 20th 2020
function Get-AccessTokenWithPRT
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Cookie,
[Parameter(Mandatory=$True)]
[String]$Resource,
[Parameter(Mandatory=$True)]
[String]$ClientId,
[Parameter(Mandatory=$False)]
[String]$RedirectUri,
[switch]$GetNonce,
[Parameter(Mandatory=$False)]
[String]$Tenant
)
Process
{
# If no tenant is given, use Common
if([string]::IsNullOrEmpty($Tenant))
{
$Tenant = "Common"
}
$parsedCookie = Read-Accesstoken $Cookie
#Set RedirectURI
if([string]::IsNullOrEmpty($RedirectUri))
{
$RedirectUri = Get-AuthRedirectUrl -ClientID $ClientId -Resource $Resource
}
# Create parameters
$mscrid = (New-Guid).ToString()
$requestId = $mscrid
# Create url and headers
$url = "https://login.microsoftonline.com/$Tenant/oauth2/authorize?resource=$Resource&client_id=$ClientId&response_type=code&redirect_uri=$RedirectUri&client-request-id=$requestId&mscrid=$mscrid"
# Add sso_nonce if exist
if($parsedCookie.request_nonce)
{
$url += "&sso_nonce=$($parsedCookie.request_nonce)"
}
$headers = @{
"User-Agent" = ""
"x-ms-RefreshTokenCredential" = $Cookie
}
# First, make the request to get the authorisation code (tries to redirect so throws an error)
$response = Invoke-WebRequest -UseBasicParsing -Uri $url -Headers $headers -MaximumRedirection 0 -ErrorAction SilentlyContinue
$code = Parse-CodeFromResponse -Response $response
if(!$code)
{
throw "Code not received!"
}
# Create the body
$body = @{
client_id = $ClientId
grant_type = "authorization_code"
code = $code
redirect_uri = $RedirectUri
}
# Make the second request to get the access token
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body $body -ContentType "application/x-www-form-urlencoded" -Method Post
Write-Debug "ACCESS TOKEN: $($response.access_token)"
Write-Debug "REFRESH TOKEN: $($response.refresh_token)"
# Return
return $response
}
}
# Get the access token with BPRT
# Jan 10th 2021
function Get-AccessTokenWithBPRT
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$BPRT,
[Parameter(Mandatory=$True)]
[String]$Resource,
[Parameter(Mandatory=$True)]
[String]$ClientId
)
Process
{
Get-AccessTokenWithRefreshToken -Resource "urn:ms-drs:enterpriseregistration.windows.net" -ClientId "b90d5b8f-5503-4153-b545-b31cecfaece2" -TenantId "Common" -RefreshToken $BPRT
}
}
# Get the token with deviceid claim
# Aug 28th
function Set-AccessTokenDeviceAuth
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[bool]$BPRT,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$RefreshToken,
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(Mandatory=$False)]
[string]$PfxFileName,
[Parameter(Mandatory=$False)]
[string]$PfxPassword,
[Parameter(Mandatory=$False)]
[string]$TransportKeyFileName
)
Process
{
if(!$Certificate)
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
if($BPRT)
{
# Fixed values for BPRT to get access token for Intune MDM
$clientId = "b90d5b8f-5503-4153-b545-b31cecfaece2"
$resource = "https://enrollment.manage.microsoft.com/"
}
else
{
# This is the only supported client id :(
$clientId = "29d9ed98-a469-4536-ade2-f981bc1d605e"
# Get the claims from the access token to get the resource
$claims = Read-Accesstoken -AccessToken $AccessToken
$resource = $claims.aud
}
# Get the private key
if($TransportKeyFileName)
{
# Get the transport key from the provided file
$tkPEM = (Get-Content $TransportKeyFileName) -join "`n"
$tkParameters = Convert-PEMToRSA -PEM $tkPEM
$privateKey = [System.Security.Cryptography.RSA]::Create($tkParameters)
}
else
{
$privateKey = Load-PrivateKey -Certificate $Certificate
}
$body=@{
"grant_type" = "srv_challenge"
"windows_api_version" = "2.0"
"client_id" = $clientId
"redirect_uri" = "ms-appx-web://Microsoft.AAD.BrokerPlugin/DRS"
"resource" = $resource
}
if($BPRT)
{
$body.Remove("redirect_uri")
}
# Get the nonce
$nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body $body).Nonce
# B64 encode the public key
$x5c = Convert-ByteArrayToB64 -Bytes ($certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert))
# Create the header and body
$hdr = [ordered]@{
"alg" = "RS256"
"typ" = "JWT"
"x5c" = "$x5c"
}
$OSVersion="10.0.18362.997"
$pld = [ordered]@{
"win_ver" = $OSVersion
"resource" = $resource
"scope" = "openid aza"
"request_nonce" = $nonce
"refresh_token" = $RefreshToken
"redirect_uri" = "ms-appx-web://Microsoft.AAD.BrokerPlugin/DRS"
"iss" = "aad:brokerplugin"
"grant_type" = "refresh_token"
"client_id" = $clientId
}
if($BPRT)
{
$pld.Remove("redirect_uri")
$pld["scope"] = "openid"
}
# Create the JWT
$jwt = New-JWT -PrivateKey $privateKey -Header $hdr -Payload $pld
# Construct the body
$body = @{
"windows_api_version" = "2.0"
"grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer"
"request" = "$jwt"
}
# Make the request to get the new access token
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body
if($BPRT)
{
$response | Add-Member -NotePropertyName "refresh_token" -NotePropertyValue $RefreshToken
}
Write-Debug "ACCESS TOKEN: $($response.access_token)"
Write-Debug "REFRESH TOKEN: $($response.refresh_token)"
# Return
return $response
}
}
function New-JWT
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='PrivateKey', Mandatory=$True)]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(ParameterSetName='Key',Mandatory=$True)]
[Byte[]]$Key,
[Parameter(Mandatory=$True)]
[System.Collections.Specialized.OrderedDictionary]$Header,
[Parameter(Mandatory=$True)]
[System.Collections.Specialized.OrderedDictionary]$Payload
)
Process
{
# Construct the header
$txtHeader = $Header | ConvertTo-Json -Compress
$txtPayload = $Payload | ConvertTo-Json -Compress
# Convert to B64 and strip the padding
$b64Header = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.getBytes($txtHeader )) -NoPadding
$b64Payload = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.getBytes($txtPayload)) -NoPadding
# Construct the JWT data to be signed
$binData = [text.encoding]::UTF8.GetBytes(("{0}.{1}" -f $b64Header,$b64Payload))
# Get the signature
$Binsig = Sign-JWT -PrivateKey $PrivateKey -Key $Key -Data $binData
$B64sig = Convert-ByteArrayToB64 -Bytes $Binsig -UrlEncode
# Construct the JWT
$jwt = "{0}.{1}.{2}" -f $b64Header,$b64Payload,$B64sig
# Return
return $jwt
}
}
function Get-PRTKeyInfo
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='PrivateKey',Mandatory=$True)]
[byte[]]$PrivateKey
)
Process
{
# Create a random context
$ctx = New-Object byte[] 24
([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($context)
# Get the private key
$privateKey = Load-PrivateKey -Certificate $Certificate
$body=@{
"grant_type" = "srv_challenge"
"windows_api_version" = "2.0"
"client_id" = $ClientId
"redirect_uri" = $RedirectUri
"resource" = $Resource
}
# Get the nonce
$nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body $body).Nonce
# B64 encode the public key
$x5c = Convert-ByteArrayToB64 -Bytes ($certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert))
# Create the header and body
$hdr = [ordered]@{
"alg" = "RS256"
"typ" = "JWT"
"x5c" = "$x5c"
}
$OSVersion="10.0.18362.997"
$pld = [ordered]@{
"win_ver" = $OSVersion
"resource" = $Resource
"scope" = "openid aza"
"request_nonce" = $nonce
"refresh_token" = $RefreshToken
"redirect_uri" = $RedirectUri
"iss" = "aad:brokerplugin"
"grant_type" = "refresh_token"
"client_id" = $ClientId
}
# Create the JWT
$jwt = New-JWT -PrivateKey $privateKey -Header $hdr -Payload $pld
# Construct the body
$body = @{
"windows_api_version" = "2.0"
"grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer"
"request" = "$jwt"
}
# Make the request to get the PRT key information
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body
Write-Debug "ACCESS TOKEN: $($response.access_token)"
Write-Debug "REFRESH TOKEN: $($response.refresh_token)"
# Return
return $response
}
}
# Parses the given JWE
# Dec 22nd 2021
Function Parse-JWE
{
[cmdletbinding()]
param(
[parameter(Mandatory=$True,ValueFromPipeline)]
[String]$JWE
)
process
{
$parts = $JWE.Split(".")
if($parts.Count -ne 5)
{
Throw "Invalid JWE: $($parts.Count) parts, expected 5"
}
# Decode and parse the header
$parsedJWT = Convert-B64ToText -B64 $parts[0] | ConvertFrom-Json
# Add other parts
$parsedJWT | Add-Member -NotePropertyName "Key" -NotePropertyValue $parts[1]
$parsedJWT | Add-Member -NotePropertyName "Iv" -NotePropertyValue $parts[2]
$parsedJWT | Add-Member -NotePropertyName "CipherText" -NotePropertyValue $parts[3]
$parsedJWT | Add-Member -NotePropertyName "Tag" -NotePropertyValue $parts[4]
return $parsedJWT
}
}
# Decrypt the given JWE
# Dec 22nd 2021
Function Decrypt-JWE
{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True,ValueFromPipeline)]
[String]$JWE,
[Parameter(Mandatory=$True,ParameterSetName = "RSA")]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(Mandatory=$False,ParameterSetName = "RSA")]
[bool]$returnKey = $true,
[Parameter(Mandatory=$True,ParameterSetName = "Key")]
[byte[]]$Key,
[Parameter(Mandatory=$True,ParameterSetName = "SessionKey")]
[byte[]]$SessionKey
)
process
{
$parsedJWE = Parse-JWE -JWE $JWE
$alg = $parsedJWE.alg
# If this is refresh_token or code, use RSA-OAEP
if([string]::IsNullOrEmpty($alg) -and $parsedJWE.ser -eq "1.0")
{
$alg = "RSA-OAEP"
}
elseif($parsedJWE.enc -ne "A256GCM")
{
Throw "Unsupported enc: $enc"
}
# Decrypt data using symmetric key
if($alg -eq "dir")
{
# Derive decryption key from the session key and context
if($SessionKey)
{
if(!$parsedJWE.ctx)
{
Throw "Missing ctx, unable to derive encryption key!"
}
$context = Convert-B64ToByteArray -B64 $parsedJWE.ctx
$key = Get-PRTDerivedKey -SessionKey $SessionKey -Context $context
}
if(!$parsedJWE.Iv -or !$parsedJWE.CipherText)
{
Throw "Missing Iv and/or CipherText, unable to decrypt!"
}
$iv = Convert-B64ToByteArray -B64 $parsedJWE.Iv
$encData = Convert-B64ToByteArray -B64 $parsedJWE.CipherText
# Create the crypto provider.
# The data is always encrypted using A256CBC instead of A256GCM, because AesCryptoServiceProvider does not support GCM mode.
$cryptoProvider = [System.Security.Cryptography.AesCryptoServiceProvider]::new()
$cryptoProvider.Key = $Key
$cryptoProvider.iv = $iv
# Create a crypto stream
$buffer = [System.IO.MemoryStream]::new()
$cryptoStream = [System.Security.Cryptography.CryptoStream]::new($buffer, $cryptoProvider.CreateDecryptor($Key,$iv),[System.Security.Cryptography.CryptoStreamMode]::Write)
# Decrypt the data
$cryptoStream.Write($encData,0,$encData.Count)
$cryptoStream.FlushFinalBlock()
$decData = $buffer.ToArray()
# Clean up
$cryptoStream.Dispose()
$cryptoProvider.Dispose()
return $decData
}
elseif($alg -eq "RSA-OAEP") # Decrypt data using encrypted key
{
if(!$PrivateKey)
{
Throw "PrivateKey required for RSA-OAEP encrypted JWE"
}
try
{
# Decrypt the content encryption key (CEK)
$encKey = Convert-B64ToByteArray -B64 $parsedJWE.Key
$CEK = [System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter]::new($privateKey).DecryptKeyExchange($encKey)
# Extract the parameters
$iv = Convert-B64ToByteArray -B64 $parsedJWE.Iv
$encData = Convert-B64ToByteArray -B64 $parsedJWE.CipherText
$tag = Convert-B64ToByteArray -B64 $parsedJWE.Tag
$keyParameter = [Org.BouncyCastle.Crypto.Parameters.KeyParameter]::new($CEK)
# Append Tag to Encrypted data
$buffer = New-Object byte[] ($encData.Count + $tag.Count)
[Array]::Copy($encData,0,$buffer,0 ,$encData.Count)
[Array]::Copy($tag ,0,$buffer,$encData.Count,$tag.Count)
$encData = $buffer
# Create & init block cipher. This data is correctly encrypted with A256GCM.
$AEADParameters = [Org.BouncyCastle.Crypto.Parameters.AeadParameters]::new($keyParameter,128,$iv)
$GCMBlockCipher = [Org.BouncyCastle.Crypto.Modes.GcmBlockCipher]::new([Org.BouncyCastle.Crypto.Engines.AesFastEngine]::new())
$GCMBlockCipher.init($false, $AEADParameters)
# Create an array for the decrypted data
$decData = New-Object byte[] $GCMBlockCipher.GetOutputSize($encData.Count)
# Decrypt the data
$res = $GCMBlockCipher.ProcessBytes($encData, 0, $encData.Count, $decData, 0)
$res = $GCMBlockCipher.DoFinal($decData, $res)
# Return the key instead of data
if($returnKey)
{
# With session_key_jwe the decrypted data seems always to be one byte: 32
if($decData[0] -ne 32)
{
Write-Warning "Decrypted data was not 32. Key may be invalid."
}
$retVal = $CEK
}
else
{
# De-deflate
if($parsedJWE.zip -eq "Deflate")
{
$retVal = Get-DeDeflatedByteArray -byteArray $decData
}
else
{
$retVal = $decData
}
}
# Return
return $retVal
}
catch
{
throw "Decrypting the key failed: ""$($_.Exception.InnerException.Message)"". Are you using the correct certificate or key?"
}
}
else
{
Throw "Unsupported alg: $alg"
}
}
}
# Derivate KDFv2 context
# Mar 3rd 2022
function Get-KDFv2Context
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[Byte[]]$Context,
[Parameter(Mandatory=$True)]
[System.Collections.Specialized.OrderedDictionary]$Payload
)
Begin
{
$sha256 = [System.Security.Cryptography.SHA256]::Create()
}
Process
{
# KDFv2 (Key Derivation Function v2) uses different context: SHA256(ctx || assertion payload)
# We need to compute SHA256 hash from a byte array combined from context and payload.
# Ref: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oapxbc/89dfb8d6-23b8-4963-8908-91b34340e367
# Get payload bytes
$pldBytes = [text.encoding]::UTF8.getBytes(($Payload | ConvertTo-Json -Compress))
# Create a buffer
$buffer = New-Object byte[] ($Context.Count + $pldBytes.Count)
# Copy context and payload to buffer
[array]::Copy($Context ,0,$buffer,0 ,$Context.Count)
[array]::Copy($pldBytes,0,$buffer,$Context.Count,$pldBytes.Count)
# Return SHA256 hash
return $sha256.ComputeHash($buffer)
}
End
{
$sha256.Dispose()
}
}
# Parses the Cloud AP Cache Data CacheData
# C:\Windows\system32\config\systemprofile\AppData\local\microsoft\windows\CloudAPCache\AzureAD\<hash>\cache\cachedata
# May 31st 2023
function Parse-CloudAPCacheData
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the header
$p = 0;
$version = [System.BitConverter]::ToInt32($Data,$p); $p += 4
if($version -ne 2)
{
Throw "Invalid version: $version. Was expecting 2."
}
$hash = $Data[($p)..($p-1 + 32)]; $p += 32
$p += 8
$dataLen = [System.BitConverter]::ToInt64($Data,$p); $p += 8
Write-Verbose "CacheData version: $version"
Write-Verbose "CacheData SHA256: $(Convert-ByteArrayToHex -Bytes $hash)"
Write-Verbose "CacheData length: $dataLen"
# As I don't know the structure of the header so we need to find values based on what we know.
# Guid starts at 0x38
$p = 0x38
$keyId = [guid][byte[]]$Data[($p)..($p-1 + 16)]; $p += 16
# The size of the encrypted blob seems to be at 0x60
$p = 0x60
$encDataSize = [System.BitConverter]::ToInt32($Data,$p); $p += 4
# Then we have a part of header we don't know. So we need to find the correct place.
# Structure is:
# encKeySize, encKey, encDataSize, encData
# Length of the key seems to be always 0x30 so let's loop until we found the correct place.
while($p -lt $dataLen)
{
$encKeySize = [System.BitConverter]::ToInt32($Data,$p); $p += 4
if($encKeySize -eq 0x30)
{
# If the encrypted key is followed by the encrypted data size, we found the correct location
if([System.BitConverter]::ToInt32($Data,$p + 0x30) -eq $encDataSize)
{
break
}
}
}
Write-Verbose "EncryptedKey length: $encKeySize"
$encKey = $Data[($p)..($p-1 + $encKeySize)]; $p += $encKeySize
$encDataSize = [System.BitConverter]::ToInt32($Data,$p); $p += 4
Write-Verbose "EncryptedData length: $encDataSize"
$encData = $Data[($p)..($p-1 + $encDataSize)]; $p += $encDataSize
Write-Verbose "CacheData key id: $keyId"
return [pscustomobject]@{
"EncryptedKey" = $encKey
"EncryptedData" = $encData
"Id" = $guid
}
}
}
# Parses the decrypted data blob from CacheData
# Jun 2nd 2023
function Parse-CloudAPCacheDataBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the header
$p = 0;
$version = [System.BitConverter]::ToInt32($Data,$p); $p += 4
if($version -ne 0)
{
Throw "Invalid version: $version. Was expecting 0."
}
$unk01 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk02 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk03 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk04 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk05 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk06 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk07 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$keyId = [guid][byte[]]$Data[($p)..($p-1 + 16)]; $p += 16
$id1 = $Data[($p)..($p-1 + 32)]; $p += 32
$id2 = $Data[($p)..($p-1 + 32)]; $p += 32
Write-Verbose "CacheData blob version: $version"
Write-Verbose "CacheData key id: $keyId"
Write-Verbose "CacheData blob ID1?: $(Convert-ByteArrayToHex -Bytes $id1)"
Write-Verbose "CacheData blob ID2?: $(Convert-ByteArrayToHex -Bytes $id2)"
# Return the payload
return $Data[$p..$($Data.Length)]
}
}
# Decrypts POP Key (Session Key) blob using DPAPI
# May 31st 2023
function Unprotect-POPKeyBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Begin
{
# Load system.security assembly
Add-Type -AssemblyName System.Security
}
Process
{
# Parse the header
$p = 0;
$version = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$type = [System.BitConverter]::ToInt32($Data,$p); $p += 4
Write-Verbose "SessionKey version: $version"
Write-Verbose "SessionKey type: $type"
if($type -ne 1)
{
Throw "Only software key (type 1) can be exported."
}
# Get the key
$key = $Data[$p..$($Data.Count)]