-
Notifications
You must be signed in to change notification settings - Fork 214
/
PRT.ps1
2055 lines (1663 loc) · 76.2 KB
/
PRT.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 Persistent Refresh Token and related device operations
# Get the PRT token from the current user
# Aug 19th 2020
function Get-UserPRTToken
{
<#
.SYNOPSIS
Gets user's PRT token from the Azure AD joined or Hybrid joined computer.
.DESCRIPTION
Gets user's PRT token from the Azure AD joined or Hybrid joined computer.
Uses browsercore.exe or Token Provider DLL to get the PRT token.
.Parameter Method
Method to use to retrieve the user's PRT token.
"BrowserCore" for browsercore.exe or "TokenProvider" for Token Provider DLL
.EXAMPLE
PS C:\> Get-AADIntUserPRTToken
eyJ4NWMiOi...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet('BrowserCore','TokenProvider')]
[String]$Method="BrowserCore"
)
Process
{
# Get the nonce
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/Common/oauth2/token" -Body "grant_type=srv_challenge"
$nonce = $response.Nonce
if($Method -eq "BrowserCore")
{
# There are two possible locations
$locations = @(
"$($env:ProgramFiles)\Windows Security\BrowserCore\browsercore.exe"
"$($env:windir)\BrowserCore\browsercore.exe"
)
# Check the locations
foreach($file in $locations)
{
if(Test-Path $file)
{
$browserCore = $file
}
}
if(!$browserCore)
{
throw "Browsercore not found!"
}
# Create the process
$p = New-Object System.Diagnostics.Process
$p.StartInfo.FileName = $browserCore
$p.StartInfo.UseShellExecute = $false
$p.StartInfo.RedirectStandardInput = $true
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.CreateNoWindow = $true
# Create the message body
$body = @"
{
"method":"GetCookies",
"uri":"https://login.microsoftonline.com/common/oauth2/authorize?sso_nonce=$nonce",
"sender":"https://login.microsoftonline.com"
}
"@
# Start the process
$p.Start() | Out-Null
$stdin = $p.StandardInput
$stdout = $p.StandardOutput
# Write the input
$stdin.BaseStream.Write([bitconverter]::GetBytes($body.Length),0,4)
$stdin.Write($body)
$stdin.Close()
# Read the output
$response=""
while(!$stdout.EndOfStream)
{
$response += $stdout.ReadLine()
}
Write-Debug "RESPONSE: $response"
$p.WaitForExit()
# Strip the stuff from the beginning of the line
$response = $response.Substring($response.IndexOf("{")) | ConvertFrom-Json
# Check for error
if($response.status -eq "Fail")
{
Throw "Error getting PRT: $($response.code). $($response.description)"
}
# Get the index of the x-ms-RefreshTokenCredential data or throw error
$token_index = $response.response.name.IndexOf("x-ms-RefreshTokenCredential")
if($token_index -lt 0)
{
throw "Could not find the x-ms-RefreshTokenCredential cookie in response"
}
# Return the data for x-ms-RefreshTokenCredential
$tokens = $response.response[$token_index].data
return $tokens
}
else
{
$tokens = [AADInternals.Native]::getCookieInfoForUri("https://login.microsoftonline.com/common/oauth2/authorize?sso_nonce=$nonce")
if($tokens.Count)
{
Write-Verbose "Found $($tokens.Count) token(s)."
# Get the index of the x-ms-RefreshTokenCredential data or throw error
$token_index = $tokens.name.IndexOf("x-ms-RefreshTokenCredential")
if($token_index -lt 0)
{
throw "Could not find the x-ms-RefreshTokenCredential cookie in response"
}
# Return the data for x-ms-RefreshTokenCredential
$token = $tokens[$token_index]["data"]
return $token.Split(";")[0]
}
else
{
Throw "Error getting tokens."
}
}
}
}
# Creates a new PRT token
# Aug 26th 2020
function New-UserPRTToken
{
<#
.SYNOPSIS
Creates a new PRT JWT token.
.DESCRIPTION
Creates a new Primary Refresh Token (PRT) as JWT to be used to sign-in as the user.
.Parameter RefreshToken
Primary Refresh Token (PRT) or the user.
.Parameter SessionKey
The session key of the user
.Parameter Context
The context used = B64 encoded byte array (size 24)
.Parameter Settings
PSObject containing refresh_token and session_key attributes.
.Parameter Nonce
Nonce to be added to the token.
.Parameter GetNonce
Get nonce automatically by connecting to Azure AD.
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
PS C:\>$creds = Get-Credential
PS C:\>$prtKeys = Get-UserAADIntPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -Credentials $cred
PS C:\>$prtToken = New-AADIntUserPRTToken -RefreshToken $prtKeys.refresh_token -SessionKey $prtKeys.session_key -GetNonce
PS C:\>$at = Get-AADIntAccessTokenForAADGraph -PRTToken $prtToken
.EXAMPLE
PS C:\>New-AADIntUserPRTToken -RefreshToken "AQABAAAAAAAGV_bv21oQQ4ROqh0_1-tAHenMcJD..." -SessionKey "O1g9LD9+jiE5yFulMcIeCPZrttzfEHyIPtF5X17cA5+="
eyJhbGciOiJIUzI1NiIsICJjdHgiOiJBQUFBQUFBQUFBQUF...
.EXAMPLE
PS C:\>New-AADIntUserPRTToken -Settings $prtKeys -GetNonce
eyJhbGciOiJIUzI1NiIsICJjdHgiOiJBQUFBQUFBQUFBQUF...
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)]
[String]$RefreshToken,
[Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)]
[String]$SessionKey,
[Parameter(Mandatory=$False)]
[String]$Context,
[Parameter(Mandatory=$False)]
[String]$Nonce,
[Parameter(ParameterSetName='Settings',Mandatory=$True)]
$Settings,
[switch]$GetNonce,
[bool]$KdfV2 = $true
)
Process
{
if($Settings)
{
if([string]::IsNullOrEmpty($Settings.refresh_token) -or [string]::IsNullOrEmpty($Settings.session_key))
{
throw "refresh_token and/or session_key missing!"
}
$RefreshToken = $Settings.refresh_token
$SessionKey = $Settings.session_key
}
if(!$Context)
{
# Create a random context
$ctx = New-Object byte[] 24
([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($ctx)
}
else
{
$ctx = Convert-B64ToByteArray -B64 $Context
}
$sKey = Convert-B64ToByteArray -B64 $SessionKey
$iat = [int]((Get-Date).ToUniversalTime() - $epoch).TotalSeconds
# Create the header and body
$hdr = [ordered]@{
"alg" = "HS256"
"typ" = "JWT"
"ctx" = (Convert-ByteArrayToB64 -Bytes $ctx)
}
$pld = [ordered]@{
"refresh_token" = $RefreshToken
"is_primary" = "true"
"iat" = $iat
}
# Derive the key from session key and context
if($KdfV2)
{
$hdr["kdf_ver"] = 2
$derivedContext = Get-KDFv2Context -Context $ctx -Payload $pld
}
else
{
$derivedContext = $ctx
}
$key = Get-PRTDerivedKey -Context $derivedContext -SessionKey $sKey
# Fetch the nonce if not provided
if([string]::IsNullOrEmpty($Nonce))
{
$Nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/Common/oauth2/token" -Body "grant_type=srv_challenge").Nonce
}
$pld["request_nonce"] = $Nonce
# As the payload may have changed due to nonce, derive the key again if needed
if($KdfV2)
{
$derivedContext = Get-KDFv2Context -Context $ctx -Payload $pld
$key = Get-PRTDerivedKey -Context $derivedContext -SessionKey $sKey
}
# Create the JWT
$jwt = New-JWT -Key $key -Header $hdr -Payload $pld
# Return
return $jwt
}
}
# Register the device to Azure AD
# Aug 20th 2020
function Join-DeviceToAzureAD
{
<#
.SYNOPSIS
Emulates Azure AD Join or Azure AD Hybrid Join by registering the given device to Azure AD.
.DESCRIPTION
Emulates Azure AD Join or Azure AD Hybrid Join by registering the given device to Azure AD and generates a corresponding certificate.
You may use any name, type or OS version you like.
For Hybrid Join, the SID, tenant ID, and the certificate of the existing synced device must be provided - no access token needed.
The generated certificate can be used to create a Primary Refresh Token and P2P certificates. The certificate has no password.
.Parameter AccessToken
The access token used to join the device. To get MFA claim to PRT, the access token needs to be get using MFA.
If not given, will be prompted.
.Parameter DeviceName
The name of the device to be registered.
.Parameter DeviceType
The type of the device to be registered. Defaults to "Windows"
.Parameter OSVersion
The operating system version of the device to be registered. Defaults to "10.0.18363.0"
.Parameter Certificate
x509 device's user certificate.
.Parameter PfxFileName
File name of the .pfx device certificate.
.Parameter PfxPassword
The password of the .pfx device certificate.
.Parameter DomainControllerName
The fqdn of the domain controller from where the device information is "fetched". Defaults to "dc.aadinternals.com"
.Parameter DomainName
The domain name of the target Azure AD tenant. Defaults to "dc.aadinternals.com"
.Parameter TenantId
The tenant id of the target Azure AD tenant where the hybrid join device exists.
.Parameter SID
The SID of the device. Must be a valid SID and match the SID of the existing AAD device object.
.Parameter JoinType
The join type "Join" or "Register". Defaults to Join.
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS\:>Join-AADIntDeviceToAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4
TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS\:>Join-AADIntDeviceToAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" -JoinType Register
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4
TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
.EXAMPLE
PS C\:>Join-AADIntDeviceToAzureAD -DeviceName "My computer" -SID "S-1-5-21-685966194-1071688910-211446493-3729" -PfxFileName .\f24f116f-6e80-425d-8236-09803da7dfbe-user.pfx -TenantId 40cb9912-555c-42b8-80e9-3b3ad50dda8a
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: f24f116f-6e80-425d-8236-09803da7dfbe
AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4
TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b
Cert thumbprint: A531B73CFBAB2BA26694BA2AD31113211CC2174A
Cert file name : "f24f116f-6e80-425d-8236-09803da7dfbe.pfx"
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="Hybrid", Mandatory=$True)]
[String]$PfxFileName,
[Parameter(ParameterSetName="Hybrid", Mandatory=$False)]
[String]$PfxPassword,
[Parameter(ParameterSetName="HybridCert", Mandatory=$True)]
[Parameter(ParameterSetName="Hybrid", Mandatory=$True)]
[String]$SID,
[Parameter(ParameterSetName="HybridCert", Mandatory=$True)]
[Parameter(ParameterSetName="Hybrid", Mandatory=$True)]
[GUID]$TenantId,
[Parameter(ParameterSetName="HybridCert", Mandatory=$False)]
[Parameter(ParameterSetName="Hybrid", Mandatory=$False)]
[Parameter(ParameterSetName="Normal", Mandatory=$False)]
[String]$DomainName,
[Parameter(ParameterSetName="HybridCert", Mandatory=$False)]
[Parameter(ParameterSetName="Hybrid", Mandatory=$False)]
[String]$DomainControllerName="dc.aadinternals.com",
[Parameter(ParameterSetName="HybridCert", Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName="Normal", Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName="Normal", Mandatory=$False)]
[ValidateSet('Join','Register')]
[String]$JoinType="Join",
[Parameter(ParameterSetName="Normal", Mandatory=$True)]
[Parameter(ParameterSetName="Hybrid", Mandatory=$True)]
[Parameter(ParameterSetName="HybridCert", Mandatory=$True)]
[String]$DeviceName,
[Parameter(ParameterSetName="Normal", Mandatory=$False)]
[Parameter(ParameterSetName="Hybrid", Mandatory=$False)]
[Parameter(ParameterSetName="HybridCert", Mandatory=$False)]
[String]$DeviceType="Windows",
[Parameter(ParameterSetName="Normal", Mandatory=$False)]
[Parameter(ParameterSetName="Hybrid", Mandatory=$False)]
[Parameter(ParameterSetName="HybridCert", Mandatory=$False)]
[String]$OSVersion="10.0.19041.804"
)
Process
{
if(!$TenantId)
{
# Get from cache if not provided
try
{
# Try first with access token retrieved with BPRT
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "b90d5b8f-5503-4153-b545-b31cecfaece2" -Resource "urn:ms-drs:enterpriseregistration.windows.net"
}
catch
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9"
}
# Get the domain and tenant id
$tenantId = (Read-Accesstoken -AccessToken $AccessToken).tid
}
# Load the Certificate for Hybrid Join if not provided
if($PfxFileName)
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
# Register the Device
$DeviceCertResponse = Register-DeviceToAzureAD -AccessToken $AccessToken -DeviceName $DeviceName -DeviceType $DeviceType -OSVersion $OSVersion -Certificate $Certificate -DomainController $DomainControllerName -SID $SID -TenantId $TenantId -DomainName $DomainName -RegisterOnly ($JoinType -eq "Register")
if(!$DeviceCertResponse)
{
# Something went wrong :(
return
}
[System.Security.Cryptography.X509Certificates.X509Certificate2]$deviceCert = $DeviceCertResponse[0]
$regResponse = $DeviceCertResponse[1]
# Parse certificate information
$oids = Parse-CertificateOIDs -Certificate $deviceCert
$deviceId = $oids.DeviceId.ToString()
$tenantId = $oids.TenantId.ToString()
$authUserObjectId = $oids.AuthUserObjectId.ToString()
# Write the device certificate to disk
Set-BinaryContent -Path "$deviceId.pfx" -Value $deviceCert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx)
# Remove the private key from the store
Unload-PrivateKey -PrivateKey $deviceCert.PrivateKey
Write-Host "Device successfully registered to Azure AD:"
Write-Host " DisplayName: ""$DeviceName"""
Write-Host " DeviceId: $deviceId"
Write-Host " AuthUserObjectId: $authUserObjectId"
Write-Host " TenantId: $tenantId"
Write-Host " Cert thumbprint: $($regResponse.Certificate.Thumbprint)"
Write-host " Cert file name : ""$deviceId.pfx"""
foreach($change in $regResponse.MembershipChanges)
{
Write-Host "Local SID:"
Write-Host " $($($change.LocalSID))"
Write-Host "Additional SIDs:"
foreach($sid in $change.AddSIDs)
{
Write-Host " $sid"
}
}
}
}
# Generates a new P2P certificate
# Aug 21st 2020
function New-P2PDeviceCertificate
{
<#
.SYNOPSIS
Creates a new P2P device or user certificate using the device certificate or PRT information.
.DESCRIPTION
Creates a new peer-to-peer (P2P) device or user certificate and exports it and the corresponding CA certificate.
It can be used to enable RDP trust between devices of the same AAD tenant.
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS\:>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
.Parameter Certificate
x509 certificate used to sign the certificate request.
.Parameter PfxFileName
File name of the .pfx certificate used to sign the certificate request.
.Parameter PfxPassword
The password of the .pfx certificate used to sign the certificate request.
.Parameter TenantId
The tenant id or name of users' tenant.
.Parameter DeviceName
The name of the device. Will be added to DNS Names attribute of the certificate.
.Parameter OSVersion
The operating system version of the device. Defaults to "10.0.18363.0"
.Parameter RefreshToken
Primary Refresh Token (PRT) or the user.
.Parameter SessionKey
The session key of the user
.Parameter Context
The context used = B64 encoded byte array (size 24)
.Parameter Settings
PSObject containing refresh_token and session_key attributes.
.EXAMPLE
PS C\:>New-AADIntP2PDeviceCertificate -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -DeviceName "mypc1.company.com"
Device P2P certificate successfully created:
Subject: "CN=d03994c9-24f8-41ba-a156-1805998d6dc7, DC=4169fee0-df47-4e31-b1d7-5d248222b872"
DnsName: "mypc1.company.com"
Issuer: "CN=MS-Organization-P2P-Access [2020]"
Cert thumbprint: 84D7641F9BFA90767EA3456E443E21948FC425E5
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7-P2P.pfx"
CA file name : "d03994c9-24f8-41ba-a156-1805998d6dc7-P2P-CA.der"
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
PS C:\>$creds = Get-Credential
PS C:\>$prtKeys = Get-UserAADIntPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -Credentials $cred
PS C:\>New-AADIntP2PDeviceCertificate -RefreshToken $prtKeys.refresh_token -SessionKey $prtKeys.session_key
User certificate successfully created:
Subject: "CN=TestU@contoso.com, CN=S-1-12-1-xx-xx-xx-xx, DC=0f73eaa6-7fd6-48b8-8897-e382ba96daf4"
Issuer: "CN=MS-Organization-P2P-Access [2020]"
Cert thumbprint: A7F1D1F134569E0234E6AA722354D99C3AA68D0F
Cert file name : "TestU@contoso.com-P2P.pfx"
CA file name : "TestU@contoso.com-P2P-CA.der"
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword,
[Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)]
[String]$RefreshToken,
[Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)]
[String]$SessionKey,
[Parameter(Mandatory=$False)]
[String]$Context,
[Parameter(ParameterSetName='Settings',Mandatory=$True)]
$Settings,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[String]$TenantId,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[String]$DeviceName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String]$OSVersion="10.0.18363.0",
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String[]]$DNSNames
)
Process
{
if($Settings)
{
if([string]::IsNullOrEmpty($Settings.refresh_token) -or [string]::IsNullOrEmpty($Settings.session_key))
{
throw "refresh_token and/or session_key missing!"
}
$RefreshToken = $Settings.refresh_token
$SessionKey = $Settings.session_key
}
if($SessionKey -ne $null -and [string]::IsNullOrEmpty($Context))
{
# Create a random context
$ctx = New-Object byte[] 24
([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($ctx)
}
elseif($Context)
{
$ctx = Convert-B64ToByteArray -B64 $Context
}
if($Certificate -eq $null -and [string]::IsNullOrEmpty($PfxFileName) -eq $false)
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
if(!$DNSNames)
{
$DNSNames = @($DeviceName)
}
if($Certificate)
{
$TenantId = (Parse-CertificateOIDs -Certificate $Certificate).TenantId
}
if(!$TenantId)
{
$TenantId = (Read-Accesstoken $prtKeys.id_token).tid
}
# Get the nonce
$nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/token" -Body "grant_type=srv_challenge").Nonce
# We are doing this with the existing device certificate
if($Certificate)
{
# Get the private key
$privateKey = Load-PrivateKey -Certificate $Certificate
# Initialize the Certificate Signing Request object
$CN = $Certificate.Subject
$req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($CN, $privateKey, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
# Create the signing request
$csr = [convert]::ToBase64String($req.CreateSigningRequest())
# B64 encode the public key
$x5c = [convert]::ToBase64String(($certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)))
# Create the header and body
$hdr = [ordered]@{
"alg" = "RS256"
"typ" = "JWT"
"x5c" = "$x5c"
}
$pld = [ordered]@{
"client_id" = "38aa3b87-a06d-4817-b275-7a316988d93b"
"request_nonce" = $nonce
"win_ver" = $OSVersion
"grant_type" = "device_auth"
"cert_token_use" = "device_cert"
"csr_type" = "http://schemas.microsoft.com/windows/pki/2009/01/enrollment#PKCS10"
"csr" = $csr
"netbios_name" = $DeviceName
"dns_names" = $DNSNames
}
# 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"
}
}
else # We are doing this with the PRT keys information
{
# Create a private key and do something with it to get it stored
$rsa=[System.Security.Cryptography.RSA]::Create(2048)
# 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))
# Initialize the Certificate Signing Request object
$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]::ToBase64String($req.CreateSigningRequest())
# Create the header and body
$hdr = [ordered]@{
"alg" = "HS256"
"typ" = "JWT"
"ctx" = (Convert-ByteArrayToB64 -Bytes $ctx)
}
$pld = [ordered]@{
"iss" = "aad:brokerplugin"
"grant_type" = "refresh_token"
"aud" = "login.microsoftonline.com"
"request_nonce" = $nonce
"scope" = "openid aza ugs"
"refresh_token" = $RefreshToken
"client_id" = "38aa3b87-a06d-4817-b275-7a316988d93b"
"cert_token_use" = "user_cert"
"csr_type" = "http://schemas.microsoft.com/windows/pki/2009/01/enrollment#PKCS10"
"csr" = $csr
}
# Create the JWT
$jwt = New-JWT -Key (Get-PRTDerivedKey -Context $ctx -SessionKey (Convert-B64ToByteArray $SessionKey)) -Header $hdr -Payload $pld
# Construct the body
$body = @{
"grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer"
"request" = "$jwt"
"windows_api_version" = "1.0"
}
}
try
{
# Make the request to get the P2P certificate
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body
}
catch
{
$errorMessage = $_.ErrorDetails.Message | ConvertFrom-Json
Write-Error $errorMessage.error_description
return
}
# Get the certificate
$binCert = [byte[]](Convert-B64ToByteArray -B64 $response.x5c)
# Create a new x509certificate
$P2PCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($binCert,"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$P2PCert.PrivateKey = $privateKey
# Write the device P2P certificate to disk
$certName = $P2PCert.Subject.Split(",")[0].Split("=")[1]
Set-BinaryContent -Path "$certName-P2P.pfx" -Value $P2PCert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx)
# Write the P2P certificate CA to disk
$CA = @"
-----BEGIN PUBLIC KEY-----
$($response.x5c_ca)
-----END PUBLIC KEY-----
"@
$CA | Set-Content "$certName-P2P-CA.der"
if($Certificate)
{
# Unload the private key
Unload-PrivateKey -PrivateKey $privateKey
}
# Print out information
if($Certificate)
{
Write-Host "Device P2P certificate successfully created:"
}
else
{
Write-Host "User certificate successfully created:"
}
Write-Host " Subject: ""$($P2PCert.Subject)"""
if($Certificate)
{
Write-Host " DnsNames: ""$($P2PCert.DnsNameList.Unicode)"""
}
Write-Host " Issuer: ""$($P2PCert.Issuer)"""
Write-Host " Cert thumbprint: $($P2PCert.Thumbprint)"
Write-host " Cert file name : ""$certName-P2P.pfx"""
Write-host " CA file name : ""$certName-P2P-CA.der"""
}
}
# Generates a new set of PRT keys for the user.
# Aug 21st 2020
function Get-UserPRTKeys
{
<#
.SYNOPSIS
Creates a new set of session key and refresh_token (PRT) for the user and saves them to json file.
.DESCRIPTION
Creates a new set of Primary Refresh Token (PRT) keys for the user, including a session key and a refresh_token (PRT).
Keys are saved to a json file.
.Parameter Certificate
x509 certificate used to sign the certificate request.
.Parameter PfxFileName
File name of the .pfx certificate used to sign the certificate request.
.Parameter PfxPassword
The password of the .pfx certificate used to sign the certificate request.
.Parameter Credentials
Credentials of the user.
.Parameter CloudAP
Get PRT and Session key from CloudAP cache using user's credentials
.Parameter OSVersion
The operating system version of the device. Defaults to "10.0.18363.0"
.Parameter UseRefreshToken
Uses cached refresh token instead of credentials. Use Get-AADIntAccessTokenForMDM with -SaveToCache switch.
.Parameter TransportKeyFileName
Name of the .PEM file containing the transport key
.Parameter WHfBKeyFileName
Name of the .PEM file containing the Windows Hello for Business (WHfB) key.
If provided, AADInternals is trying to use WHfB key as the proof-of-identity
.Parameter UseDeviceCertForWHfB
If set, AADInternals is trying to use the provided device certificate key as WHfB key.
.Parameter SAMLToken
Uses the provided SAML token instead of credentials.
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4
TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
PS C:\>$creds = Get-Credential
PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -Credentials $cred
PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4
TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
PS C:\>Get-AADIntAccessTokenForIntuneMDM -SaveToCache
PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -UseRefreshToken
PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys
.EXAMPLE
Get-AADIntAccessTokenForAADJoin -SaveToCache
PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4
TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
PS C:\>$saml = New-AADIntSAMLToken -ImmutableID "2Vt0xz0EgESz+vF+8BzxPw==" -Issuer "http://sts.company.com/adfs/services/trust" -PfxFileName .\ADFSSigningCertificate.pfx
PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -SAMLToken $saml
PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys
.Example
PS C\:>Export-AADIntLocalDeviceCertificate
Device certificate exported to f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx
PS C\:>Export-AADIntLocalDeviceTransportKey
Transport key exported to f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem
PS C:\>$creds = Get-Credential
PS C\:>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx -TransportKeyFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem -Credentials $creds
PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys
.Example
PS C\:>Export-AADIntLocalDeviceCertificate
Device certificate exported to f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx
PS C\:>Export-AADIntLocalDeviceTransportKey
Transport key exported to f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem
PS C\:>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx -TransportKeyFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem
PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys
.Example
PS C\:>$creds = Get-Credential
PS C\:>$prtKeys = Get-AADIntUserPRTKeys -CloudAP -Credentials $creds
WARNING: Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore AzureAD\User1 rights.
Keys saved to 31abceff-a84c-4f3b-9461-582435d7d448.json
PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys
.EXAMPLE
PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -UseDeviceCertForWHfB -UserName user@company.com
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Certificate' ,Mandatory=$True)]
[Parameter(ParameterSetName='RTCertificate' ,Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword' ,Mandatory=$True)]
[Parameter(ParameterSetName='RTFileAndPassword',Mandatory=$True)]