-
Notifications
You must be signed in to change notification settings - Fork 219
/
PRT.ps1
1577 lines (1265 loc) · 58 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
# 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 $($JoinType)ed 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) $(if($change.LocalSID -eq "S-1-5-32-544"){"(Local administrators)"})"
Write-Host "Additional SIDs:"
foreach($sid in $change.AddSIDs)
{
Write-Host " $sid $(Convert-SIDtoObjectID -SID $sid)"
}
}
}
}
# 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 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 [email protected]
#>
[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)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword' ,Mandatory=$False)]
[Parameter(ParameterSetName='RTFileAndPassword',Mandatory=$False)]
[string]$PfxPassword,
[Parameter(Mandatory=$False)]
[string]$TransportKeyFileName,
[Parameter(Mandatory=$False)]
[string]$WHfBKeyFileName,
[Parameter(Mandatory=$False)]
[string]$UserName,
[Parameter(Mandatory=$False)]
[switch]$UseDeviceCertForWHfB,
[Parameter(ParameterSetName='RTFileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='RTCertificate' ,Mandatory=$True)]
[switch]$UseRefreshToken,
[Parameter(Mandatory=$False)]
[String]$SAMLToken,
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$OSVersion="10.0.18363.0",
[Parameter(Mandatory=$False)]
[switch]$IncludePartialTGT
)
Process
{
# Load the certificate if not provided
if(!$Certificate)
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
# Get the private key
$privateKey = Load-PrivateKey -Certificate $Certificate
# Get the public key
$publicKey = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
# Parse certificate information
$oids = Parse-CertificateOIDs -Certificate $Certificate
$deviceId = $oids.DeviceId.ToString()
$tenantId = $oids.TenantId.ToString()
$objectId = $oids.AuthUserObjectId.ToString()
# Get the nonce
$nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body "grant_type=srv_challenge").Nonce
# Construct the header
$headerObj = [ordered]@{
"alg" = "RS256"
"typ" = "JWT"
"x5c" = Convert-ByteArrayToB64 ($publicKey)
}
$header = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.GetBytes(($headerObj | ConvertTo-Json -Compress))) -NoPadding
# Construct the payload
$payloadObj=@{
"client_id" = "38aa3b87-a06d-4817-b275-7a316988d93b"
"request_nonce" = "$nonce"
"scope" = "openid aza ugs"
"win_ver" = "$OSVersion"
}
if($SAMLToken)
{
$payloadObj["grant_type"] = "urn:ietf:params:oauth:grant-type:saml1_1-bearer"
$payloadObj["assertion"] = Convert-TextToB64 -Text $SAMLToken
}
elseif($Credentials)
{
$payloadObj["grant_type"] = "password"
$payloadObj["username"] = $Credentials.UserName
$payloadObj["password"] = $Credentials.GetNetworkCredential().Password
}
elseif($UseRefreshToken)
{
# Trying to get the refresh token from the cache
$refresh_token = Get-RefreshTokenFromCache -ClientID "29d9ed98-a469-4536-ade2-f981bc1d605e" -Resource "https://graph.windows.net"
if([string]::IsNullOrEmpty($refresh_token))
{
Throw "No refresh token found! Use Get-AADIntAccessTokenForIntuneMDM with -SaveToCache switch and try again."
}
$tokens = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "1b730954-1685-4b74-9bfd-dac224a7b894" -ClientId "29d9ed98-a469-4536-ade2-f981bc1d605e" -TenantId Common -IncludeRefreshToken $true
$payloadObj["grant_type"] = "refresh_token"
$payloadObj["refresh_token"] = $tokens[1]
$payloadObj["client_id"] = "29d9ed98-a469-4536-ade2-f981bc1d605e"
}
elseif($WHfBKeyFileName -or $UseDeviceCertForWHfB)
{
# Use Device Certificate key as WHfB key
if($UseDeviceCertForWHfB)
{
# Check do we have a user name
if([string]::IsNullOrEmpty($UserName))
{
throw "User name must be provided with -Username parameter."
}
$whfbParameters = $privateKey.ExportParameters($true)
}
# Use the provided WHfB key
else
{
# Check do we have a user name
if([string]::IsNullOrEmpty($UserName))
{
# Try to parse from the file name
try
{
Write-Warning "Username not provided, trying to parse from the filename"
$UserName = $WHfBKeyFileName.Split("_")[2]
Write-Verbose "Using $UserName for WHfB assertion."
}
catch
{
throw "Could not parse username from the filename, please provide user with -UserName parameter."
}
}
# Load WHfB key from the PEM file
$whfbPEM = (Get-Content $WHfBKeyFileName) -join "`n"
$whfbParameters = Convert-PEMToRSA -PEM $whfbPEM
}
# Set the parameters
$now = (Get-Date).toUniversalTime()
$assertion_iss = $UserName
$assertion_kid = Convert-ByteArrayToB64 -Bytes ([System.Security.Cryptography.SHA256]::Create().ComputeHash( (New-KeyBLOB -Parameters $whfbParameters -Type RSA1)))
$assertion_aud = $TenantId
$assertion_iat = [int](($now)-$epoch).TotalSeconds
$assertion_exp = [int](($now).AddMinutes(10)-$epoch).TotalSeconds
$assertion_hdr = [ordered]@{
"alg" = "RS256"
"typ" = "JWT"
"kid" = $assertion_kid
"use" = "ngc"
}
# 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
$assertion_pld = [ordered]@{
"iss" = $assertion_iss
"aud" = $assertion_aud
"iat" = $assertion_iat
"exp" = $assertion_exp
"request_nonce" = $nonce
"scope" = "openid aza ugs"
}
# Create and sign the assertion JWT
$assertion = New-JWT -PrivateKey ([System.Security.Cryptography.RSA]::Create($whfbParameters)) -Header $assertion_hdr -Payload $assertion_pld
$payloadObj["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
$payloadObj["assertion"] = $assertion
}
else
{
# Get access token interactively (supports MFA)
$tokens = Get-AccessToken -ClientId "29d9ed98-a469-4536-ade2-f981bc1d605e" -PfxFileName $PfxFileName -Resource "1b730954-1685-4b74-9bfd-dac224a7b894" -IncludeRefreshToken $true
$payloadObj["grant_type"] = "refresh_token"
$payloadObj["refresh_token"] = $tokens[1]
$payloadObj["client_id"] = "29d9ed98-a469-4536-ade2-f981bc1d605e"
}
$payload = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.GetBytes( ($payloadObj | ConvertTo-Json -Compress ) )) -NoPadding
# Construct the JWT data to be signed
$dataBin = [text.encoding]::UTF8.GetBytes(("{0}.{1}" -f $header,$payload))
# Get the signature
$sigBin = Sign-JWT -PrivateKey $PrivateKey -Data $dataBin
$sigB64 = Convert-ByteArrayToB64 $sigBin -UrlEncode -NoPadding
# B64 URL encode
$signature = $sigB64
# Construct the JWT
$jwt = "{0}.{1}.{2}" -f $header,$payload,$signature
# Construct the body
$body = @{
"windows_api_version" = "2.0"
"grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer"
"request" = "$jwt"
"client_info" = "1"
}
if ($IncludePartialTGT)
{
$body['tgt'] = $true
}
# Make the request
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body -ErrorAction SilentlyContinue
if(!$response.token_type)
{
throw "Error getting session key. Check your credentials!"
}
# Decrypt the session key and add it to return value
try
{
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)
}
$sessionKey = Decrypt-JWE -JWE $response.session_key_jwe -PrivateKey $privateKey
$response | Add-Member -NotePropertyName "session_key" -NotePropertyValue (Convert-ByteArrayToB64 -Bytes $sessionKey)
if ($IncludePartialTGT)
{
$tgt = Decrypt-JWE -JWE $response.tgt_client_key -SessionKey $sessionKey
$response | Add-Member -NotePropertyName "decrypted_tgt_client_key" -NotePropertyValue (Convert-ByteArrayToB64 -Bytes $tgt)
}
}
catch
{
Write-Error $($_.Exception.Message)
}
# Write to file
$outFileName = "$deviceId.json"
$response | ConvertTo-Json |Set-Content $outFileName -Encoding UTF8
Write-Host "Keys saved to $outFileName"
try
{
# Unload the private key
Unload-PrivateKey -PrivateKey $privateKey
}
catch {}
# Return
$response
}
}
# Removes the device from Azure AD
# Sep 2nd 2020
function Remove-DeviceFromAzureAD
{
<#
.SYNOPSIS
Removes the device from Azure AD.
.DESCRIPTION
Removes the device from Azure AD using the given device certificate.
.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 Force
Does not ask for "Are your sure?" questions.
.EXAMPLE
Remove-AADIntDeviceFromAzureAD -pfxFileName .\85c3252a-3b33-41cf-bd4f-c53b7a94c548.pfx
The device 85c3252a-3b33-41cf-bd4f-c53b7a94c548 succesfully removed from Azure AD. Attestation result KeyId: 0372f9ab-6103-4a0f-9095-9b49cd399479
#>
[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,
[switch]$Force
)
Process
{
if(!$Certificate)
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
$deviceID = $Certificate.Subject.Split("=")[1]
if(!$Force)
{
$promptValue = Read-Host "Are you sure you wan't to remove the device $deviceID? from Azure AD? Type YES to continue or CTRL+C to abort"
if($promptValue -ne "yes")
{
Write-Warning "Device removal of device $deviceID cancelled."
return
}
}
Write-Verbose "Unenrolling device $deviceID"
$requestId = (New-Guid).ToString()
$headers=@{
"User-Agent" = "Dsreg/10.0 (Windows 10.0.18363.0)"
"ocp-adrs-client-name" = "Dsreg"
"ocp-adrs-client-version" = "10.0.18362.0"
"client-Request-Id" = $requestId
"return-client-request-id" = "true"
}
try
{
$response = Invoke-WebRequest -UseBasicParsing -Certificate $Certificate -Method Delete -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/device/$($deviceID)?api-version=1.0" -Headers $headers -ErrorAction SilentlyContinue
}
catch
{
Write-Error ($_.ErrorDetails.Message | ConvertFrom-Json ).Message
return
}
$keyId = ($response.Content | ConvertFrom-Json).AttestationResult.KeyId
Write-Host "The device $deviceID succesfully removed from Azure AD. Attestation result KeyId: $keyId"
}
}
# Get device compliance
# Sep 11th 2020
function Get-DeviceRegAuthMethods
{
<#
.SYNOPSIS
Get's the authentication methods used while registering the device.
.DESCRIPTION
Get's the authentication methods used while registering the device.
.Parameter AccessToken
The access token used to get the methos.
.Parameter DeviceId
Azure AD device id of the device.
.Parameter ObjectId
Azure AD object id of the device.
.EXAMPLE
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C\:>Get-AADIntDeviceRegAuthMethods -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7"
pwd
mfa
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='DeviceID',Mandatory=$True)]
[String]$DeviceId,
[Parameter(ParameterSetName='ObjectID',Mandatory=$True)]
[String]$ObjectId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
$parsedToken = Read-Accesstoken -AccessToken $AccessToken
$tenantId = $parsedToken.tid
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Accept" = "application/json;odata=nometadata"
}
# Get the object Id if not given
if([string]::IsNullOrEmpty($ObjectId))
{
$ObjectId = Get-DeviceObjectId -DeviceId $DeviceId -TenantId $tenantId -AccessToken $AccessToken
}
# Get the methods
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?`$select=deviceSystemMetadata&api-version=1.61-internal" -Headers $headers
$methods = $response.deviceSystemMetadata | Where-Object key -eq RegistrationAuthMethods | Select-Object -ExpandProperty value | ConvertFrom-Json
return $methods
}
}
# Set device compliance
# Sep 11th 2020
function Set-DeviceRegAuthMethods
{
<#
.SYNOPSIS
Set's the authentication methods.
.DESCRIPTION
Set's the authentication methods. Affects what authentication claims the access tokens generated with device certificate or PRT.
.Parameter AccessToken
The access token used to set the methods.
.Parameter DeviceId
Azure AD device id of the device.
.Parameter ObjectId
Azure AD object id of the device.
.Parameter Methods
The list of methods. Can be any of "pwd","rsa","otp","fed","wia","mfa","mngcmfa","wiaormfa","none" but only pwd and mfa matters.
.EXAMPLE
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C\:>Set-AADIntDeviceRegAuthMethods -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7" -Methods mfa,pwd
pwd
mfa
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='DeviceID',Mandatory=$True)]
[String]$DeviceId,
[Parameter(ParameterSetName='ObjectID',Mandatory=$True)]
[String]$ObjectId,
[Validateset("pwd","rsa","otp","fed","wia","mfa","mngcmfa","wiaormfa","none")]
[Parameter(Mandatory=$False)]
[String[]]$Methods="none"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
$parsedToken = Read-Accesstoken -AccessToken $AccessToken
$tenantId = $parsedToken.tid
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Accept" = "application/json;odata=nometadata"
}