-
Notifications
You must be signed in to change notification settings - Fork 218
/
AccessToken_utils.ps1
3161 lines (2802 loc) · 119 KB
/
AccessToken_utils.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This script contains functions for handling access tokens
# and some utility functions
# VARIABLES
# Unix epoch time (1.1.1970)
$epoch = Get-Date -Day 1 -Month 1 -Year 1970 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
# FOCI client ids
# Ref: https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv
$FOCIs = @{
"00b41c95-dab0-4487-9791-b9d2c32c80f2" = "Office 365 Management"
"04b07795-8ddb-461a-bbee-02f9e1bf7b46" = "Microsoft Azure CLI"
"1950a258-227b-4e31-a9cf-717495945fc2" = "Microsoft Azure PowerShell"
"1fec8e78-bce4-4aaf-ab1b-5451cc387264" = "Microsoft Teams"
"26a7ee05-5602-4d76-a7ba-eae8b7b67941" = "Windows Search"
"27922004-5251-4030-b22d-91ecd9a37ea4" = "Outlook Mobile"
"4813382a-8fa7-425e-ab75-3b753aab3abb" = "Microsoft Authenticator App"
"ab9b8c07-8f02-4f72-87fa-80105867a763" = "OneDrive SyncEngine"
"d3590ed6-52b3-4102-aeff-aad2292ab01c" = "Microsoft Office"
"872cd9fa-d31f-45e0-9eab-6e460a02d1f1" = "Visual Studio"
"af124e86-4e96-495a-b70a-90f90ab96707" = "OneDrive iOS App"
"2d7f3606-b07d-41d1-b9d2-0d0c9296a6e8" = "Microsoft Bing Search for Microsoft Edge"
"844cca35-0656-46ce-b636-13f48b0eecbd" = "Microsoft Stream Mobile Native"
"87749df4-7ccf-48f8-aa87-704bad0e0e16" = "Microsoft Teams - Device Admin Agent"
"cf36b471-5b44-428c-9ce7-313bf84528de" = "Microsoft Bing Search"
"0ec893e0-5785-4de6-99da-4ed124e5296c" = "Office UWP PWA"
"22098786-6e16-43cc-a27d-191a01a1e3b5" = "Microsoft To-Do client"
"4e291c71-d680-4d0e-9640-0a3358e31177" = "PowerApps"
"57336123-6e14-4acc-8dcf-287b6088aa28" = "Microsoft Whiteboard Client"
"57fcbcfa-7cee-4eb1-8b25-12d2030b4ee0" = "Microsoft Flow"
"66375f6b-983f-4c2c-9701-d680650f588f" = "Microsoft Planner"
"9ba1a5c7-f17a-4de9-a1f1-6178c8d51223" = "Microsoft Intune Company Portal"
"a40d7d7d-59aa-447e-a655-679a4107e548" = "Accounts Control UI"
"a569458c-7f2b-45cb-bab9-b7dee514d112" = "Yammer iPhone"
"b26aadf8-566f-4478-926f-589f601d9c74" = "OneDrive"
"c0d2a505-13b8-4ae0-aa9e-cddd5eab0b12" = "Microsoft Power BI"
"d326c1ce-6cc6-4de2-bebc-4591e5e13ef0" = "SharePoint"
"e9c51622-460d-4d3d-952d-966a5b1da34c" = "Microsoft Edge"
"eb539595-3fe1-474e-9c1d-feb3625d1be5" = "Microsoft Tunnel"
"ecd6b820-32c2-49b6-98a6-444530e5a77a" = "Microsoft Edge"
"f05ff7c9-f75a-4acd-a3b5-f4b6a870245d" = "SharePoint Android"
"f44b1140-bc5e-48c6-8dc0-5cf5a53c0e34" = "Microsoft Edge"
"be1918be-3fe3-4be9-b32b-b542fc27f02e" = "M365 Compliance Drive Client"
"cab96880-db5b-4e15-90a7-f3f1d62ffe39" = "Microsoft Defender Platform"
"d7b530a4-7680-4c23-a8bf-c52c121d2e87" = "Microsoft Edge Enterprise New Tab Page"
"dd47d17a-3194-4d86-bfd5-c6ae6f5651e3" = "Microsoft Defender for Mobile"
"e9b154d0-7658-433b-bb25-6b8e0a8a7c59" = "Outlook Lite"
}
# Resource ids
$RESIDs = @{
"00000003-0000-0000-c000-000000000000" = "https://graph.microsoft.com"
}
# Stored tokens (access & refresh)
$tokens=@{}
$refresh_tokens=@{}
## UTILITY FUNCTIONS FOR API COMMUNICATIONS
# Return user's login information
function Get-LoginInformation
{
<#
.SYNOPSIS
Returns authentication information of the given user or domain
.DESCRIPTION
Returns authentication of the given user or domain
.Example
Get-AADIntLoginInformation -Domain outlook.com
Tenant Banner Logo :
Authentication Url : https://login.live.com/login.srf?username=nn%40outlook.com&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=
Pref Credential : 6
Federation Protocol : WSTrust
Throttle Status : 0
Cloud Instance : microsoftonline.com
Federation Brand Name : MSA Realms
Domain Name : live.com
Federation Metadata Url : https://nexus.passport.com/FederationMetadata/2007-06/FederationMetadata.xml
Tenant Banner Illustration :
Consumer Domain : True
State : 3
Federation Active Authentication Url : https://login.live.com/rst2.srf
User State : 2
Account Type : Federated
Tenant Locale :
Domain Type : 2
Exists : 5
Has Password : True
Cloud Instance audience urn : urn:federation:MicrosoftOnline
Federation Global Version : -1
.Example
Get-AADIntLoginInformation -UserName [email protected]
Tenant Banner Logo : https://secure.aadcdn.microsoftonline-p.com/c1c6b6c8-okmfqodscgr7krbq5-p48zooi4b7m9g2zcpryoikta/logintenantbranding/0/bannerlogo?ts=635912486993671038
Authentication Url :
Pref Credential : 1
Federation Protocol :
Throttle Status : 1
Cloud Instance : microsoftonline.com
Federation Brand Name : Company Ltd
Domain Name : company.com
Federation Metadata Url :
Tenant Banner Illustration :
Consumer Domain :
State : 4
Federation Active Authentication Url :
User State : 1
Account Type : Managed
Tenant Locale : 0
Domain Type : 3
Exists : 0
Has Password : True
Cloud Instance audience urn : urn:federation:MicrosoftOnline
Desktop Sso Enabled : True
Federation Global Version :
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Domain',Mandatory=$True)]
[String]$Domain,
[Parameter(ParameterSetName='User',Mandatory=$True)]
[String]$UserName
)
Process
{
if([string]::IsNullOrEmpty($UserName))
{
$isDomain = $true
$UserName = "nn@$Domain"
}
$subScope = Get-TenantSubscope -Domain $UserName.Split("@")[1]
# Gather login information using different APIs
$realm1=Get-UserRealm -UserName $UserName -SubScope $subScope # common/userrealm API 1.0
$realm2=Get-UserRealmExtended -UserName $UserName -SubScope $subScope # common/userrealm API 2.0
$realm3=Get-UserRealmV2 -UserName $UserName -SubScope $subScope # GetUserRealm.srf (used in the old Office 365 login experience)
$realm4=Get-CredentialType -UserName $UserName -SubScope $subScope # common/GetCredentialType (used in the "new" Office 365 login experience)
# Create a return object
$attributes = @{
"Account Type" = $realm1.account_type # Managed or federated
"Domain Name" = $realm1.domain_name
"Cloud Instance" = $realm1.cloud_instance_name
"Cloud Instance audience urn" = $realm1.cloud_audience_urn
"Federation Brand Name" = $realm2.FederationBrandName
"Tenant Locale" = $realm2.TenantBrandingInfo.Locale
"Tenant Banner Logo" = $realm2.TenantBrandingInfo.BannerLogo
"Tenant Banner Illustration" = $realm2.TenantBrandingInfo.Illustration
"State" = $realm3.State
"User State" = $realm3.UserState
"Exists" = $realm4.IfExistsResult
"Throttle Status" = $realm4.ThrottleStatus
"Pref Credential" = $realm4.Credentials.PrefCredential
"Has Password" = $realm4.Credentials.HasPassword
"Domain Type" = $realm4.EstsProperties.DomainType
"Federation Protocol" = $realm1.federation_protocol
"Federation Metadata Url" = $realm1.federation_metadata_url
"Federation Active Authentication Url" = $realm1.federation_active_auth_url
"Authentication Url" = $realm2.AuthUrl
"Consumer Domain" = $realm2.ConsumerDomain
"Federation Global Version" = $realm3.FederationGlobalVersion
"Desktop Sso Enabled" = $realm4.EstsProperties.DesktopSsoEnabled
}
# Return
return New-Object psobject -Property $attributes
}
}
# Return user's authentication realm from common/userrealm using API 1.0
function Get-UserRealm
{
<#
.SYNOPSIS
Returns authentication realm of the given user
.DESCRIPTION
Returns authentication realm of the given user using common/userrealm API 1.0
.Example
Get-AADIntUserRealm -UserName "[email protected]"
ver : 1.0
account_type : Managed
domain_name : company.com
cloud_instance_name : microsoftonline.com
cloud_audience_urn : urn:federation:MicrosoftOnline
.Example
Get-AADIntUserRealm -UserName "[email protected]"
ver : 1.0
account_type : Federated
domain_name : company.com
federation_protocol : WSTrust
federation_metadata_url : https://sts.company.com/adfs/services/trust/mex
federation_active_auth_url : https://sts.company.com/adfs/services/trust/2005/usernamemixed
cloud_instance_name : microsoftonline.com
cloud_audience_urn : urn:federation:MicrosoftOnline
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$UserName,
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestSession]$webSession,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Call the API
$userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/common/userrealm/$UserName"+"?api-version=1.0") -WebSession $webSession -Headers @{"User-agent" = Get-UserAgent}
# Verbose
Write-Verbose "USER REALM $($userRealm | Out-String)"
# Return
$userRealm
}
}
# Return user's authentication realm from common/userrealm using API 2.0
function Get-UserRealmExtended
{
<#
.SYNOPSIS
Returns authentication realm of the given user
.DESCRIPTION
Returns authentication realm of the given user using common/userrealm API 2.0
.Example
Get-AADIntUserRealmExtended -UserName "[email protected]"
NameSpaceType : Managed
Login : [email protected]
DomainName : company.com
FederationBrandName : Company Ltd
TenantBrandingInfo : {@{Locale=0; BannerLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/bannerlogo?
ts=111; TileLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/til
elogo?ts=112; BackgroundColor=#FFFFFF; BoilerPlateText=From here
you can sign-in to Company Ltd services; [email protected];
KeepMeSignedInDisabled=False}}
cloud_instance_name : microsoftonline.com
.Example
Get-AADIntUserRealmExtended -UserName "[email protected]"
NameSpaceType : Federated
federation_protocol : WSTrust
Login : [email protected]
AuthURL : https://sts.company.com/adfs/ls/?username=user%40company.com&wa=wsignin1.
0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=
DomainName : company.com
FederationBrandName : Company Ltd
TenantBrandingInfo :
cloud_instance_name : microsoftonline.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$UserName,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Call the API
$userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/common/userrealm/$UserName"+"?api-version=2.0") -Headers @{"User-agent" = Get-UserAgent}
# Verbose
Write-Verbose "USER REALM $($userRealm | Out-String)"
# Return
$userRealm
}
}
# Return user's authentication realm from GetUserRealm.srf (used in the old Office 365 login experience)
function Get-UserRealmV2
{
<#
.SYNOPSIS
Returns authentication realm of the given user
.DESCRIPTION
Returns authentication realm of the given user using GetUserRealm.srf (used in the old Office 365 login experience)
.Example
Get-AADIntUserRealmV3 -UserName "[email protected]"
State : 4
UserState : 1
Login : [email protected]
NameSpaceType : Managed
DomainName : company.com
FederationBrandName : Company Ltd
CloudInstanceName : microsoftonline.com
.Example
Get-AADIntUserRealmV2 -UserName "[email protected]"
State : 3
UserState : 2
Login : [email protected]
NameSpaceType : Federated
DomainName : company.com
FederationGlobalVersion : -1
AuthURL : https://sts.company.com/adfs/ls/?username=user%40company.com&wa=wsignin1.
0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=
FederationBrandName : Company Ltd
CloudInstanceName : microsoftonline.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$UserName,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Call the API
$userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/GetUserRealm.srf?login=$UserName") -Headers @{"User-agent" = Get-UserAgent}
# Verbose
Write-Verbose "USER REALM: $($userRealm | Out-String)"
# Return
$userRealm
}
}
# Return user's authentication type information from common/GetCredentialType
function Get-CredentialType
{
<#
.SYNOPSIS
Returns authentication information of the given user
.DESCRIPTION
Returns authentication of the given user using common/GetCredentialType (used in the "new" Office 365 login experience)
.Example
Get-AADIntUserRealmExtended -UserName "[email protected]"
Username : [email protected]
Display : [email protected]
IfExistsResult : 0
ThrottleStatus : 1
Credentials : @{PrefCredential=1; HasPassword=True; RemoteNgcParams=; FidoParams=; SasParams=}
EstsProperties : @{UserTenantBranding=System.Object[]; DomainType=3}
FlowToken :
apiCanary : AQABAAA..A
NameSpaceType : Managed
Login : [email protected]
DomainName : company.com
FederationBrandName : Company Ltd
TenantBrandingInfo : {@{Locale=0; BannerLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/bannerlogo?
ts=111; TileLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/til
elogo?ts=112; BackgroundColor=#FFFFFF; BoilerPlateText=From here
you can sign-in to Company Ltd services; [email protected];
KeepMeSignedInDisabled=False}}
cloud_instance_name : microsoftonline.com
.Example
Get-AADIntUserRealmExtended -UserName "[email protected]"
Username : [email protected]
Display : [email protected]
IfExistsResult : 0
ThrottleStatus : 1
Credentials : @{PrefCredential=4; HasPassword=True; RemoteNgcParams=; FidoParams=; SasParams=; FederationRed
irectUrl=https://sts.company.com/adfs/ls/?username=user%40company.com&wa=wsignin1.0&wtreal
m=urn%3afederation%3aMicrosoftOnline&wctx=}
EstsProperties : @{UserTenantBranding=; DomainType=4}
FlowToken :
apiCanary : AQABAAA..A
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$UserName,
[Parameter(Mandatory=$False)]
[String]$FlowToken,
[Parameter(Mandatory=$False)]
[String]$OriginalRequest,
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestSession]$webSession,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Create a body for REST API request
$body = @{
"username"=$UserName
"isOtherIdpSupported" = $true
"checkPhones" = $true
"isRemoteNGCSupported" = $true
"isCookieBannerShown" = $false
"isFidoSupported" = $true
"isAccessPassSupported" = $true
"originalRequest" = $OriginalRequest
"flowToken" = $FlowToken
}
# TAP support can only be requested if originalRequest is provided. Otherwise we'll get error code 6000.
if(![string]::IsNullOrEmpty($OriginalRequest))
{
$body["isAccessPassSupported"] = $true
}
# Call the API
$userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/common/GetCredentialType") -ContentType "application/json; charset=UTF-8" -Method POST -Body ($body|ConvertTo-Json) -WebSession $webSession -Headers @{"User-agent" = Get-UserAgent}
# Verbose & Debug
Write-Verbose "CREDENTIAL TYPE: Exist=$($userRealm.IfExistsResult), Federated=$(![string]::IsNullOrEmpty($userRealm.Credentials.FederationRedirectUrl))"
Write-Debug "CREDENTIAL TYPE: $($userRealm | Out-String)"
# Return
$userRealm
}
}
# Return OpenID configuration for the domain
# Mar 21 2019
function Get-OpenIDConfiguration
{
<#
.SYNOPSIS
Returns OpenID configuration of the given domain or user
.DESCRIPTION
Returns OpenID configuration of the given domain or user
.Example
Get-AADIntOpenIDConfiguration -UserName "[email protected]"
.Example
Get-AADIntOpenIDConfiguration -Domain company.com
authorization_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/authorize
token_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/token
token_endpoint_auth_methods_supported : {client_secret_post, private_key_jwt, client_secret_basic}
jwks_uri : https://login.microsoftonline.com/common/discovery/keys
response_modes_supported : {query, fragment, form_post}
subject_types_supported : {pairwise}
id_token_signing_alg_values_supported : {RS256}
http_logout_supported : True
frontchannel_logout_supported : True
end_session_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/logout
response_types_supported : {code, id_token, code id_token, token id_token...}
scopes_supported : {openid}
issuer : https://sts.windows.net/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/
claims_supported : {sub, iss, cloud_instance_name, cloud_instance_host_name...}
microsoft_multi_refresh_token : True
check_session_iframe : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/checkses
sion
userinfo_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/openid/userinfo
tenant_region_scope : EU
cloud_instance_name : microsoftonline.com
cloud_graph_host_name : graph.windows.net
msgraph_host : graph.microsoft.com
rbac_url : https://pas.windows.net
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Domain',Mandatory=$True)]
[String]$Domain,
[Parameter(ParameterSetName='User',Mandatory=$True)]
[String]$UserName
)
Process
{
if([String]::IsNullOrEmpty($Domain))
{
$Domain = $UserName.Split("@")[1]
}
# Call the API
$openIdConfig=Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/$domain/.well-known/openid-configuration" -Headers @{"User-agent" = Get-UserAgent}
# Return
$openIdConfig
}
}
# Get the tenant ID for the given user/domain/accesstoken
function Get-TenantID
{
<#
.SYNOPSIS
Returns TenantID of the given domain, user, or AccessToken
.DESCRIPTION
Returns TenantID of the given domain, user, or AccessToken
.Example
Get-AADIntTenantID -UserName "[email protected]"
.Example
Get-AADIntTenantID -Domain company.com
.Example
Get-AADIntTenantID -AccessToken $at
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Domain',Mandatory=$True)]
[String]$Domain,
[Parameter(ParameterSetName='User',Mandatory=$True)]
[String]$UserName,
[Parameter(ParameterSetName='AccessToken', Mandatory=$True)]
[String]$AccessToken
)
Process
{
if([String]::IsNullOrEmpty($AccessToken))
{
if([String]::IsNullOrEmpty($Domain))
{
$Domain = $UserName.Split("@")[1]
}
Try
{
$TenantId = (Invoke-RestMethod -UseBasicParsing -Uri "https://odc.officeapps.live.com/odc/v2.1/federationprovider?domain=$domain" -Headers @{"User-agent" = Get-UserAgent}).TenantId
}
catch
{
return $null
}
}
else
{
$TenantId=(Read-Accesstoken($AccessToken)).tid
}
# Return
$TenantId
}
}
# Check if the access token has expired
function Is-AccessTokenExpired
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken
)
Process
{
# Read the token
$token = Read-Accesstoken($AccessToken)
$now=(Get-Date).ToUniversalTime()
# Get the expiration time
$exp=$epoch.Date.AddSeconds($token.exp)
# Compare and return
$retVal = $now -ge $exp
return $retVal
}
}
# Check if the access token signature is valid
# May 20th 2020
function Is-AccessTokenValid
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken
)
Process
{
# Token sections
$sections = $AccessToken.Split(".")
$header = $sections[0]
$payload = $sections[1]
$signature = $sections[2]
$signatureValid = $false
# Fill the header with padding for Base 64 decoding
while ($header.Length % 4)
{
$header += "="
}
# Convert the token to string and json
$headerBytes=[System.Convert]::FromBase64String($header)
$headerArray=[System.Text.Encoding]::ASCII.GetString($headerBytes)
$headerObj=$headerArray | ConvertFrom-Json
# Get the signing key
$KeyId=$headerObj.kid
Write-Debug "PARSED TOKEN HEADER: $($headerObj | Format-List | Out-String)"
# The algorithm should be RSA with SHA-256, i.e. RS256
if($headerObj.alg -eq "RS256")
{
# Get the public certificate
$publicCert = Get-APIKeys -KeyId $KeyId
Write-Debug "TOKEN SIGNING CERT: $publicCert"
$certBin=[convert]::FromBase64String($publicCert)
# Construct the JWT data to be verified
$dataToVerify="{0}.{1}" -f $header,$payload
$dataBin = [text.encoding]::UTF8.GetBytes($dataToVerify)
# Remove the Base64 URL encoding from the signature and add padding
$signature=$signature.Replace("-","+").Replace("_","/")
while ($signature.Length % 4)
{
$signature += "="
}
$signBytes = [convert]::FromBase64String($signature)
# Extract the modulus and exponent from the certificate
for($a=0;$a -lt $certBin.Length ; $a++)
{
# Read the bytes
$byte = $certBin[$a]
$nByte = $certBin[$a+1]
# We are only interested in 0x02 tag where our modulus is hidden..
if($byte -eq 0x02 -and $nByte -band 0x80)
{
$a++
if($nbyte -band 0x02)
{
$byteCount = [System.BitConverter]::ToInt16($certBin[$($a+2)..$($a+1)],0)
$a+=3
}
elseif($nbyte -band 0x01)
{
$byteCount = $certBin[$($a+1)]
$a+=2
}
# If the first byte is 0x00, skip it
if($certBin[$a] -eq 0x00)
{
$a++
$byteCount--
}
# Now we have the modulus!
$modulus = $certBin[$a..$($a+$byteCount-1)]
# Next byte value is the exponent
$a+=$byteCount
if($certBin[$a++] -eq 0x02)
{
$byteCount = $certBin[$a++]
$exponent = $certBin[$a..$($a+$byteCount-1)]
Write-Debug "MODULUS: $(Convert-ByteArrayToHex -Bytes $modulus)"
Write-Debug "EXPONENT: $(Convert-ByteArrayToHex -Bytes $exponent)"
break
}
else
{
Write-Debug "Error getting modulus and exponent"
}
}
}
if($exponent -and $modulus)
{
# Create the RSA and other required objects
$rsa = New-Object -TypeName System.Security.Cryptography.RSACryptoServiceProvider
$rsaParameters = New-Object -TypeName System.Security.Cryptography.RSAParameters
# Set the verification parameters
$rsaParameters.Exponent = $exponent
$rsaparameters.Modulus = $modulus
$rsa.ImportParameters($rsaParameters)
$signatureValid = $rsa.VerifyData($dataBin, $signBytes,[System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
$rsa.Dispose()
}
}
else
{
Write-Error "Access Token signature algorithm $($headerObj.alg) not supported!"
}
return $signatureValid
}
}
# Gets OAuth information using SAML token
function Get-OAuthInfoUsingSAML
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SAMLToken,
[Parameter(Mandatory=$True)]
[String]$Resource,
[Parameter(Mandatory=$False)]
[String]$ClientId="1b730954-1685-4b74-9bfd-dac224a7b894"
)
Begin
{
# Create the headers. We like to be seen as Outlook.
$headers = @{
"User-Agent" = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Tablet PC 2.0; Microsoft Outlook 16.0.4266)"
}
}
Process
{
$encodedSamlToken= [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($SAMLToken))
# Debug
Write-Debug "SAML TOKEN: $samlToken"
Write-Debug "ENCODED SAML TOKEN: $encodedSamlToken"
# Create a body for API request
$body = @{
"resource"=$Resource
"client_id"=$ClientId
"grant_type"="urn:ietf:params:oauth:grant-type:saml1_1-bearer"
"assertion"=$encodedSamlToken
"scope"="openid"
}
# Debug
Write-Debug "FED AUTHENTICATION BODY: $($body | Out-String)"
# Set the content type and call the Microsoft Online authentication API
$contentType="application/x-www-form-urlencoded"
try
{
$jsonResponse=Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType $contentType -Method POST -Body $body -Headers $headers
}
catch
{
Throw ($_.ErrorDetails.Message | convertfrom-json).error_description
}
return $jsonResponse
}
}
# Return OAuth information for the given user
function Get-OAuthInfo
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$True)]
[String]$Resource,
[Parameter(Mandatory=$False)]
[String]$ClientId="1b730954-1685-4b74-9bfd-dac224a7b894",
[Parameter(Mandatory=$False)]
[String]$Tenant="common"
)
Begin
{
# Create the headers. We like to be seen as Outlook.
$headers = @{
"User-Agent" = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Tablet PC 2.0; Microsoft Outlook 16.0.4266)"
}
if([string]::IsNullOrEmpty($Tenant))
{
$Tenant="common"
}
}
Process
{
# Get the user realm
$userRealm = Get-UserRealm($Credentials.UserName)
# Check the authentication type
if($userRealm.account_type -eq "Unknown")
{
Write-Error "User type of $($Credentials.Username) is Unknown!"
return $null
}
elseif($userRealm.account_type -eq "Managed")
{
# If authentication type is managed, we authenticate directly against Microsoft Online
# with user name and password to get access token
# Create a body for REST API request
$body = @{
"resource"=$Resource
"client_id"=$ClientId
"grant_type"="password"
"username"=$Credentials.UserName
"password"=$Credentials.GetNetworkCredential().Password
"scope"="openid"
}
# Debug
Write-Debug "AUTHENTICATION BODY: $($body | Out-String)"
# Set the content type and call the Microsoft Online authentication API
$contentType="application/x-www-form-urlencoded"
try
{
$jsonResponse=Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/$Tenant/oauth2/token" -ContentType $contentType -Method POST -Body $body -Headers $headers
}
catch
{
Throw ($_.ErrorDetails.Message | convertfrom-json).error_description
}
}
else
{
# If authentication type is Federated, we must first authenticate against the identity provider
# to fetch SAML token and then get access token from Microsoft Online
# Get the federation metadata url from user realm
$federation_metadata_url=$userRealm.federation_metadata_url
# Call the API to get metadata
[xml]$response=Invoke-RestMethod -UseBasicParsing -Uri $federation_metadata_url
# Get the url of identity provider endpoint.
# Note! Tested only with AD FS - others may or may not work
$federation_url=($response.definitions.service.port | where name -eq "UserNameWSTrustBinding_IWSTrustFeb2005Async").address.location
# login.live.com
# TODO: Fix
#$federation_url=$response.EntityDescriptor.RoleDescriptor[1].PassiveRequestorEndpoint.EndpointReference.Address
# Set credentials and other needed variables
$username=$Credentials.UserName
$password=$Credentials.GetNetworkCredential().Password
$created=(Get-Date).ToUniversalTime().toString("yyyy-MM-ddTHH:mm:ssZ").Replace(".",":")
$expires=(Get-Date).AddMinutes(10).ToUniversalTime().toString("yyyy-MM-ddTHH:mm:ssZ").Replace(".",":")
$message_id=(New-Guid).ToString()
$user_id=(New-Guid).ToString()
# Set headers
$headers = @{
"SOAPAction"="http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue"
"Host"=$federation_url.Split("/")[2]
"client-request-id"=(New-Guid).toString()
}
# Debug
Write-Debug "FED AUTHENTICATION HEADERS: $($headers | Out-String)"
# Create the SOAP envelope
$envelope=@"
<s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope' xmlns:a='http://www.w3.org/2005/08/addressing' xmlns:u='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'>
<s:Header>
<a:Action s:mustUnderstand='1'>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
<a:MessageID>urn:uuid:$message_id</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand='1'>$federation_url</a:To>
<o:Security s:mustUnderstand='1' xmlns:o='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'>
<u:Timestamp u:Id='_0'>
<u:Created>$created</u:Created>
<u:Expires>$expires</u:Expires>
</u:Timestamp>
<o:UsernameToken u:Id='uuid-$user_id'>
<o:Username>$username</o:Username>
<o:Password>$password</o:Password>
</o:UsernameToken>
</o:Security>
</s:Header>
<s:Body>
<trust:RequestSecurityToken xmlns:trust='http://schemas.xmlsoap.org/ws/2005/02/trust'>
<wsp:AppliesTo xmlns:wsp='http://schemas.xmlsoap.org/ws/2004/09/policy'>
<a:EndpointReference>
<a:Address>urn:federation:MicrosoftOnline</a:Address>
</a:EndpointReference>
</wsp:AppliesTo>
<trust:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</trust:KeyType>
<trust:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</trust:RequestType>
</trust:RequestSecurityToken>
</s:Body>
</s:Envelope>
"@
# Debug
Write-Debug "FED AUTHENTICATION: $envelope"
# Set the content type and call the authentication service
$contentType="application/soap+xml"
[xml]$xmlResponse=Invoke-RestMethod -UseBasicParsing -Uri $federation_url -ContentType $contentType -Method POST -Body $envelope -Headers $headers
# Get the SAML token from response and encode it with Base64
$samlToken=$xmlResponse.Envelope.Body.RequestSecurityTokenResponse.RequestedSecurityToken.Assertion.OuterXml
$encodedSamlToken= [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($samlToken))
$jsonResponse = Get-OAuthInfoUsingSAML -SAMLToken $samlToken -Resource $Resource -ClientId $ClientId
}
# Debug
Write-Debug "AUTHENTICATION JSON: $($jsonResponse | Out-String)"
# Return
$jsonResponse
}
}
# Parse access token and return it as PS object
function Read-Accesstoken
{
<#
.SYNOPSIS
Extract details from the given Access Token
.DESCRIPTION
Extract details from the given Access Token and returns them as PS Object
.Parameter AccessToken
The Access Token.
.Example
PS C:\>$token=Get-AADIntReadAccessTokenForAADGraph
PS C:\>Parse-AADIntAccessToken -AccessToken $token
aud : https://graph.windows.net
iss : https://sts.windows.net/f2b2ba53-ed2a-4f4c-a4c3-85c61e548975/
iat : 1589477501
nbf : 1589477501
exp : 1589481401
acr : 1
aio : ASQA2/8PAAAALe232Yyx9l=
amr : {pwd}
appid : 1b730954-1685-4b74-9bfd-dac224a7b894
appidacr : 0
family_name : company
given_name : admin
ipaddr : 107.210.220.129
name : admin company
oid : 1713a7bf-47ba-4826-a2a7-bbda9fabe948
puid : 100354
rh : 0QfALA.
scp : user_impersonation
sub : BGwHjKPU
tenant_region_scope : NA
tid : f2b2ba53-ed2a-4f4c-a4c3-85c61e548975
unique_name : [email protected]
upn : [email protected]
uti : -EWK6jMDrEiAesWsiAA
ver : 1.0
.Example
PS C:\>Parse-AADIntAccessToken -AccessToken $token -Validate
Read-Accesstoken : Access Token is expired
At line:1 char:1
+ Read-Accesstoken -AccessToken $at -Validate -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Read-Accesstoken
aud : https://graph.windows.net
iss : https://sts.windows.net/f2b2ba53-ed2a-4f4c-a4c3-85c61e548975/
iat : 1589477501
nbf : 1589477501