-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathAPEX.ps1
3598 lines (3161 loc) · 149 KB
/
APEX.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
# Post Exploitation Tool for MS Cloud
# Combines Azure CLI and the Az and Graph PS Modules
# Optimized and tested with PS7. Some functions might not work with PS5
# Global variables to store tenant information and login accounts
$Global:tenantDomain = "Not set"
$Global:tenantID = "Not set"
$Global:azureCliAccount = "Not logged in"
$Global:azureCliId = "N/A"
$Global:azureCliSPName = "N/A"
$Global:azModuleAccount = "Not logged in"
$Global:azModuleId = "N/A"
$Global:azModuleSPName = "N/A"
$Global:graphModuleAccount = "Not logged in"
$Global:graphModuleId = "N/A"
# Header information for all menus
function DisplayHeader {
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host "==== APEX - Azure Post Exploitation Framework ====" -ForegroundColor Cyan
Write-Host "==================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Tenant Name: $tenantDomain" -ForegroundColor $(if ($tenantDomain -eq "Not set") { "Red" } else { "Green" })
Write-Host "Tenant ID: $tenantID" -ForegroundColor $(if ($tenantID -eq "Not set") { "Red" } else { "Green" })
Write-Host "Azure CLI Account Name: $azureCliAccount" -ForegroundColor $(if ($azureCliAccount -eq "Not logged in") { "Red" } else { "DarkGreen" })
Write-Host "Azure CLI Account Object ID: $azureCliId" -ForegroundColor $(if ($azureCliAccount -eq "Not logged in") { "Red" } else { "DarkGreen" })
Write-Host "Azure CLI Account Service Principal Name: $azureCliSPName" -ForegroundColor $(if ($azureCliAccount -eq "Not logged in") { "Red" } else { "DarkGreen" })
Write-Host "Az PS Module Account: $azModuleAccount" -ForegroundColor $(if ($azModuleAccount -eq "Not logged in") { "Red" } else { "Yellow" })
Write-Host "Az PS Module Object ID: $azModuleId" -ForegroundColor $(if ($azModuleAccount -eq "Not logged in") { "Red" } else { "Yellow" })
Write-Host "Az PS Module Service Principal Name: $azModuleSPName" -ForegroundColor $(if ($azModuleAccount -eq "Not logged in") { "Red" } else { "Yellow" })
Write-Host "Graph PS Module Account Name: $graphModuleAccount" -ForegroundColor $(if ($graphModuleAccount -eq "Not logged in") { "Red" } else { "DarkYellow" })
Write-Host "Graph PS Module Objet ID: $graphModuleId" -ForegroundColor $(if ($graphModuleAccount -eq "Not logged in") { "Red" } else { "DarkYellow" })
Write-Host ""
}
# Function to clear Azure CLI details
function ResetAzureCliDetails {
$Global:azureCliAccount = "Not logged in"
$Global:azureCliId = "N/A"
$Global:azureCliSPName = "N/A"
}
# Function to clear Az PowerShell module details
function ResetAzModuleDetails {
$Global:azModuleAccount = "Not logged in"
$Global:azModuleId = "N/A"
$Global:azModuleSPName = "N/A"
}
# Function to clear Graph PowerShell module details
function ResetGraphModuleDetails {
$Global:graphModuleAccount = "Not logged in"
$Global:graphModuleId = "N/A"
}
# Function to check if Azure CLI is installed and up to date
function Check-AzureCLI {
Write-Host "Checking if az CLI is installed..."
try {
$versionRawOutput = az --version
$hasUpdates = $false
$versionRawOutput | ForEach-Object {
Write-Host $_
}
if ($versionRawOutput -match 'WARNING: You have \d+ update\(s\) available.') {
Write-Host "Updates are available for az CLI." -ForegroundColor Yellow
$upgradeChoice = Read-Host -Prompt "Would you like to upgrade to the latest version? (Y/N)"
if ($upgradeChoice -eq "Y") {
Write-Host "Upgrading az CLI..."
az upgrade --yes
}
} else {
Write-Host "az CLI is up to date." -ForegroundColor Green
}
}
catch {
Write-Host "az CLI is not installed." -ForegroundColor Red
$installChoice = Read-Host -Prompt "Would you like to install it? (Y/N)"
if ($installChoice -eq "Y") {
Write-Host "Installing az CLI..."
Invoke-Expression "Invoke-WebRequest -Uri https://aka.ms/InstallAzureCliWindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -ArgumentList '/i', '.\AzureCLI.msi', '/quiet', '/norestart' -Wait; Remove-Item -Force .\AzureCLI.msi"
Write-Host "az CLI installed successfully." -ForegroundColor Green
}
}
}
# Function to check if a PowerShell module is installed, can be imported, and needs an update
function Check-UpdateModule {
param (
[string]$moduleName
)
Write-Host "Checking availability of $moduleName module..."
if (Get-Module -ListAvailable -Name $moduleName) {
try {
if (-not (Get-Module -Name $moduleName)) {
Write-Host "Importing $moduleName module..."
Import-Module $moduleName -ErrorAction Stop
}
Write-Host "$moduleName module is installed and successfully imported." -ForegroundColor Green
# Check for module updates
Write-Host "Checking for updates for $moduleName module..."
$moduleVersion = (Get-InstalledModule -Name $moduleName).Version
$availableVersion = (Find-Module -Name $moduleName).Version
if ($moduleVersion -lt $availableVersion) {
Write-Host "A newer version of $moduleName module is available." -ForegroundColor Yellow
$updateChoice = Read-Host -Prompt "Would you like to update $moduleName module? (Y/N)"
if ($updateChoice -eq "Y") {
Write-Host "Updating $moduleName module..."
Update-Module -Name $moduleName -Force
Write-Host "$moduleName module updated successfully." -ForegroundColor Green
}
} else {
Write-Host "$moduleName module is up to date." -ForegroundColor Green
}
}
catch {
Write-Host "Unable to import $moduleName module despite it being installed." -ForegroundColor Red
}
}
else {
Write-Host "$moduleName module is not installed." -ForegroundColor Yellow
$installChoice = Read-Host -Prompt "Would you like to install it? (Y/N)"
if ($installChoice -eq "Y") {
Write-Host "Installing $moduleName module..."
Install-Module -Name $moduleName -AllowClobber -Scope CurrentUser -Force
Write-Host "Importing $moduleName module..."
Import-Module $moduleName -ErrorAction Stop
Write-Host "$moduleName module was successfully installed and imported." -ForegroundColor Green
}
}
}
# Login menu structure
function LoginMenu {
while ($true) {
Clear-Host
DisplayHeader
Write-Host "Login Menu" -ForegroundColor Cyan
Write-Host "1. Set Tenant"
Write-Host "2. Azure CLI Login"
Write-Host "3. Az PowerShell Module Login"
Write-Host "4. Microsoft Graph PowerShell Module Login"
Write-Host "5. Get AccessToken"
Write-Host "6. Logout everything and forget Tenant"
Write-Host "B. Return to Main Menu"
$userInput = Read-Host -Prompt "Select an option"
switch ($userInput) {
"1" {
Set-Tenant
}
"2" {
AzureCLILoginMenu
}
"3" {
AzPSLoginMenu
}
"4" {
GraphPSLoginMenu
}
"5" {
GetAccessToken
}
"6" {
Logout-AllServices
}
"B" {
return
}
default {
Write-Host "Invalid selection, please try again."
Write-Host "`nPress any key to continue..."
[void][System.Console]::ReadKey($true)
}
}
}
}
# Function to set the tenant using an external API
function Set-Tenant {
while ($true) {
Clear-Host
DisplayHeader
Write-Host "Set Tenant Menu" -ForegroundColor Cyan
Write-Host "Enter tenant domain:" -ForegroundColor Yellow
$tenantDomainInput = Read-Host
if ($tenantDomainInput -eq "B") {
return
}
if ($tenantDomainInput) {
try {
$TenantId = (Invoke-RestMethod -UseBasicParsing -Uri "https://odc.officeapps.live.com/odc/v2.1/federationprovider?domain=$tenantDomainInput").TenantId
if ($TenantId) {
$Global:tenantID = $TenantId
$Global:tenantDomain = $tenantDomainInput
Write-Host "Tenant set to: $tenantDomain (ID: $tenantID)" -ForegroundColor Green
break
} else {
Write-Host "Failed to retrieve tenant ID. The domain might be incorrect." -ForegroundColor Red
}
}
catch {
Write-Host "Failed to retrieve tenant details. The domain might be incorrect." -ForegroundColor Red
}
} else {
Write-Host "Invalid tenant input." -ForegroundColor Red
}
}
}
# Function to get access tokens
function GetAccessToken {
Clear-Host
DisplayHeader
Write-Host "Get Access Token" -ForegroundColor Cyan
Write-Host "Select tool to use:" -ForegroundColor Yellow
Write-Host "1. Azure CLI" -ForegroundColor Yellow
Write-Host "2. Az PS Module" -ForegroundColor Yellow
$toolChoice = Read-Host
try {
Clear-Host
DisplayHeader
if ($toolChoice -eq "1") {
Write-Host "AZ CLI output:" -ForegroundColor Magenta
az account get-access-token --output json
}
elseif ($toolChoice -eq "2") {
Write-Host "AZ PS Module output:" -ForegroundColor Magenta
$token = Get-AzAccessToken
Write-Host "Token: $($token.Token)" -ForegroundColor Green
}
else {
Write-Host "Invalid selection, please try again." -ForegroundColor Red
}
}
catch {
Write-Host "Error fetching access token: $_" -ForegroundColor Red
}
Write-Host "`nPress any key to return to the login menu..."
[void][System.Console]::ReadKey($true)
}
# Azure CLI Login Menu
function AzureCLILoginMenu {
while ($true) {
Clear-Host
DisplayHeader
Write-Host "Azure CLI Login" -ForegroundColor Cyan
Write-Host "1. Interactively"
Write-Host "2. Service Principal"
Write-Host "B. Back to Login Menu"
$userInput = Read-Host -Prompt "Select a login method"
switch ($userInput) {
"1" {
Login-AzureCLI
}
"2" {
Login-AzureCLI-SP
}
"B" {
return
}
default {
Write-Host "Invalid selection, please try again."
Write-Host "`nPress any key to continue..."
[void][System.Console]::ReadKey($true)
}
}
}
}
# Function to login to Azure CLI
function Login-AzureCLI {
ResetAzureCliDetails
Write-Host "Logging into Azure CLI using tenant '$tenantID'..." -ForegroundColor Yellow
try {
az logout
if ($tenantID -ne "Not set") {
$result = az login --tenant $tenantID --output json
$loginInfo = $result | ConvertFrom-Json | Select-Object -First 1
$Global:azureCliAccount = $loginInfo.user.name
# Fetch Object ID using the logged-in user
$userId = az ad user show --id $loginInfo.user.name --query id -o tsv
$Global:azureCliId = $userId
Write-Host "Successfully logged into Azure CLI as $azureCliAccount." -ForegroundColor Green
Pause
} else {
Write-Host "Tenant must be set before logging in. Please set the tenant first." -ForegroundColor Red
Pause
}
}
catch {
Write-Host "Error during Azure CLI login: $_" -ForegroundColor Red
Pause
}
}
# Function to login to Azure CLI as a service principal
function Login-AzureCLI-SP {
ResetAzureCliDetails
Clear-Host
DisplayHeader
Write-Host "Login to Azure CLI as Service Principal" -ForegroundColor Cyan
Write-Host "Enter the application (client) ID:" -ForegroundColor Yellow
$appId = Read-Host
Write-Host "Enter the client secret:" -ForegroundColor Yellow
$clientSecret = Read-Host
try {
az logout
az login --service-principal -u $appId -p $clientSecret --tenant $Global:tenantId
$spDetails = az ad sp show --id $appId --query "{Name: displayName, Id: id, SpName: appId}" -o json | ConvertFrom-Json
$Global:azureCliAccount = $spDetails.Name
$Global:azureCliId = $spDetails.Id
$Global:azureCliSPName = $spDetails.SpName
Write-Host "Successfully logged into Azure CLI as Service Principal ($spDetails.Name)." -ForegroundColor Green
Pause
}
catch {
Write-Host "Failed to login to Azure CLI as Service Principal: $_" -ForegroundColor Red
Pause
}
Write-Host "`nPress any key to return to the login menu..."
[void][System.Console]::ReadKey($true)
}
# Az PowerShell Module Login Menu
function AzPSLoginMenu {
while ($true) {
Clear-Host
DisplayHeader
Write-Host "Az PowerShell Module Login" -ForegroundColor Cyan
Write-Host "1. Interactively"
Write-Host "2. Access Token"
Write-Host "3. Device Code"
Write-Host "4. Service Principal"
Write-Host "B. Back to Login Menu"
$userInput = Read-Host -Prompt "Select a login method"
switch ($userInput) {
"1" {
Login-AzModule
}
"2" {
Login-AzModule-AT
}
"3" {
Login-AzModule-DC
}
"4" {
Login-AzModule-SP
}
"B" {
return
}
default {
Write-Host "Invalid selection, please try again."
Write-Host "`nPress any key to continue..."
[void][System.Console]::ReadKey($true)
}
}
}
}
# Function to login to Az PowerShell module
function Login-AzModule {
ResetAzModuleDetails
Write-Host "Logging into Az PowerShell module using tenant '$tenantID'..." -ForegroundColor Yellow
try {
Disconnect-AzAccount -ErrorAction SilentlyContinue
if ($tenantID -ne "Not set") {
$account = Connect-AzAccount -Tenant $tenantID -ErrorAction Stop
$Global:azModuleAccount = (Get-AzContext).Account.Id
$userId = (Get-AzADUser -UserPrincipalName $Global:azModuleAccount).Id
$Global:azModuleId = $userId
Write-Host "Successfully logged into Az PowerShell module as $azModuleAccount." -ForegroundColor Green
Pause
} else {
Write-Host "Tenant must be set before logging in. Please set the tenant first." -ForegroundColor Red
Pause
}
}
catch {
Write-Host "Failed to login to Az PowerShell module: $_" -ForegroundColor Red
Pause
}
}
# Function to login to Az PowerShell module with AccessToken
function Login-AzModule-AT {
ResetAzModuleDetails
Clear-Host
DisplayHeader
Write-Host "Login to Az PS Module with Access Token" -ForegroundColor Cyan
Write-Host "Enter the Access Token" -ForegroundColor Yellow
$AccessToken = Read-Host
Write-Host "Enter the Account (Id or Name)" -ForegroundColor Yellow
$id = Read-Host
# Log out of existing sessions
Disconnect-AzAccount -ErrorAction SilentlyContinue
try {
Disconnect-AzAccount -ErrorAction SilentlyContinue
if ($tenantID -ne "Not set") {
$account = Connect-AzAccount -accesstoken $AccessToken -AccountId $id -TenantId $Global:tenantID -ErrorAction Stop
$Global:azModuleAccount = (Get-AzContext).Account.Id
$userId = (Get-AzADUser -UserPrincipalName $Global:azModuleAccount).Id
$Global:azModuleId = $userId
Write-Host "Successfully logged into Az PowerShell module as $azModuleAccount." -ForegroundColor Green
Pause
} else {
Write-Host "Tenant must be set before logging in. Please set the tenant first." -ForegroundColor Red
Pause
}
}
catch {
Write-Host "Failed to login to Az PowerShell module: $_" -ForegroundColor Red
Pause
}
}
# Function to login to Az PowerShell module
function Login-AzModule-DC {
ResetAzModuleDetails
Write-Host "Logging into Az PS module via Device Code flow using tenant '$tenantID'..." -ForegroundColor Yellow
try {
Disconnect-AzAccount -ErrorAction SilentlyContinue
if ($tenantID -ne "Not set") {
$account = Connect-AzAccount -Tenant $tenantID -devicecode -ErrorAction Stop
$Global:azModuleAccount = (Get-AzContext).Account.Id
$userId = (Get-AzADUser -UserPrincipalName $Global:azModuleAccount).Id
$Global:azModuleId = $userId
Write-Host "Successfully logged into Az PowerShell module as $azModuleAccount." -ForegroundColor Green
Pause
} else {
Write-Host "Tenant must be set before logging in. Please set the tenant first." -ForegroundColor Red
Pause
}
}
catch {
Write-Host "Failed to login to Az PowerShell module: $_" -ForegroundColor Red
Pause
}
}
# Function to login to Az PowerShell module as a service principal
function Login-AzModule-SP {
ResetAzModuleDetails
Clear-Host
DisplayHeader
Write-Host "Login to Az PS Module as Service Principal" -ForegroundColor Cyan
Write-Host "Enter the application (client) ID:" -ForegroundColor Yellow
$appId = Read-Host
Write-Host "Enter the client secret:" -ForegroundColor Yellow
$clientSecret = Read-Host
# Log out of existing sessions
Disconnect-AzAccount -ErrorAction SilentlyContinue
# Convert client secret to SecureString and create PSCredential
$secureSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$psCredential = [System.Management.Automation.PSCredential]::new($appId, $secureSecret)
try {
Connect-AzAccount -ServicePrincipal -Credential $psCredential -TenantId $Global:tenantID -ErrorAction Stop
$spDetails = Get-AzADServicePrincipal -ApplicationId $appId
$Global:azModuleAccount = $spDetails.AppDisplayName
$Global:azModuleId = $spDetails.Id
$Global:azModuleSPName = $spDetails.AppId
Write-Host "Successfully logged into Az PowerShell module as Service Principal ($spDetails.DisplayName)." -ForegroundColor Green
Pause
}
catch {
Write-Host "Detailed error during login: $($_.Exception.Message)" -ForegroundColor Red
Pause
}
Write-Host "`nPress any key to return to the login menu..."
[void][System.Console]::ReadKey($true)
}
# Microsoft Graph PowerShell Module Login Menu
function GraphPSLoginMenu {
while ($true) {
Clear-Host
DisplayHeader
Write-Host "Microsoft Graph PowerShell Module Login" -ForegroundColor Cyan
Write-Host "1. Interactively"
Write-Host "2. Access Token"
Write-Host "3. Device Code"
Write-Host "B. Back to Login Menu"
$userInput = Read-Host -Prompt "Select a login method"
switch ($userInput) {
"1" {
Login-GraphModule
}
"2" {
Login-GraphModule-AT
}
"3" {
Login-GraphModule-DC
}
"B" {
return
}
default {
Write-Host "Invalid selection, please try again."
Write-Host "`nPress any key to continue..."
[void][System.Console]::ReadKey($true)
}
}
}
}
# Function to login to Microsoft Graph PowerShell module
function Login-GraphModule {
ResetGraphModuleDetails
Write-Host "Logging into Microsoft Graph PS module using tenant '$tenantID'..." -ForegroundColor Yellow
try {
# Clear any existing session
Disconnect-MgGraph -ErrorAction SilentlyContinue
if ($tenantID -ne "Not set") {
Connect-MgGraph -TenantId $tenantID -ErrorAction Stop
$Global:graphModuleAccount = (Get-MgContext).Account
$Global:graphModuleId = (Get-MgUser -UserId $Global:graphModuleAccount).Id
Write-Host "Successfully logged into Microsoft Graph PS module as $graphModuleAccount." -ForegroundColor Green
Pause
} else {
Write-Host "Tenant must be set before logging in. Please set the tenant first." -ForegroundColor Red
Pause
}
}
catch {
Write-Host "Failed to login to Microsoft Graph PS module: $_" -ForegroundColor Red
Pause
}
}
# Function to login to Microsoft Graph PowerShell module via Access Token
function Login-GraphModule-AT {
ResetGraphModuleDetails
Write-Host "Logging into Microsoft Graph PS module with Access Token using tenant '$tenantID'..." -ForegroundColor Yellow
Write-Host "Enter the Access Token" -ForegroundColor Yellow
$AccessToken = Read-Host
$SecureToken = $AccessToken | ConvertTo-SecureString -AsPlainText -Force
try {
# Clear any existing session
Disconnect-MgGraph -ErrorAction SilentlyContinue
if ($tenantID -ne "Not set") {
Connect-MgGraph -AccessToken $SecureToken -ErrorAction Stop
$Global:graphModuleAccount = (Get-MgContext).Account
$Global:graphModuleId = (Get-MgUser -UserId $Global:graphModuleAccount).Id
Write-Host "Successfully logged into Microsoft Graph PowerShell module as $graphModuleAccount." -ForegroundColor Green
Pause
} else {
Write-Host "Tenant must be set before logging in. Please set the tenant first." -ForegroundColor Red
Pause
}
}
catch {
Write-Host "Failed to login to Microsoft Graph PowerShell module: $_" -ForegroundColor Red
Pause
}
}
# Function to login to Microsoft Graph PowerShell module via Devicecode
function Login-GraphModule-DC {
ResetGraphModuleDetails
Write-Host "Logging into Microsoft Graph PS module via Device Code flow using tenant '$tenantID'..." -ForegroundColor Yellow
try {
# Clear any existing session
Disconnect-MgGraph -ErrorAction SilentlyContinue
if ($tenantID -ne "Not set") {
Connect-MgGraph -TenantId $tenantID -UseDeviceAuthentication -ErrorAction Stop
$Global:graphModuleAccount = (Get-MgContext).Account
$Global:graphModuleId = (Get-MgUser -UserId $Global:graphModuleAccount).Id
Write-Host "Successfully logged into Microsoft Graph PowerShell module as $graphModuleAccount." -ForegroundColor Green
Pause
} else {
Write-Host "Tenant must be set before logging in. Please set the tenant first." -ForegroundColor Red
Pause
}
}
catch {
Write-Host "Failed to login to Microsoft Graph PowerShell module: $_" -ForegroundColor Red
Pause
}
}
# Function to logout of all services and clear tenant information
function Logout-AllServices {
Clear-Host
DisplayHeader
Write-Host "Logging out of all services and clearing tenant information..." -ForegroundColor Yellow
try {
az logout
Write-Host "Logged out of Azure CLI." -ForegroundColor Green
}
catch {
Write-Host "Failed to log out of Azure CLI." -ForegroundColor Red
}
try {
Disconnect-AzAccount -ErrorAction Stop
Write-Host "Logged out of Az PowerShell module." -ForegroundColor Green
}
catch {
Write-Host "Failed to log out of Az PowerShell module." -ForegroundColor Red
}
try {
Disconnect-MgGraph -ErrorAction Stop
Write-Host "Logged out of Microsoft Graph PowerShell module." -ForegroundColor Green
}
catch {
Write-Host "Failed to log out of Microsoft Graph PowerShell module." -ForegroundColor Red
}
$Global:tenantDomain = "Not set"
$Global:tenantID = "Not set"
$Global:azureCliAccount = "Not logged in"
$Global:azModuleAccount = "Not logged in"
$Global:graphModuleAccount = "Not logged in"
Write-Host "Tenant information and accounts have been cleared." -ForegroundColor Green
Write-Host "`nPress any key to return to the main menu..."
[void][System.Console]::ReadKey($true)
}
# Queries menu structure
function QueriesMenu {
while ($true) {
Clear-Host
DisplayHeader
Write-Host "Queries Menu" -ForegroundColor Cyan
Write-Host "1. User Info"
Write-Host "2. User Groups"
Write-Host "3. Group Members"
Write-Host "4. Role Assignments"
Write-Host "5. Available Resources"
Write-Host "6. Owned Objects"
Write-Host "7. Owned Applications"
Write-Host "8. Administrative Units (Graph only)"
Write-Host "9. Password Policy (Graph only)"
Write-Host "10. Get App Details (CLI only)"
Write-Host "11. Dynamic Groups (Graph only)"
Write-Host "12. Conditional Access Policies as low Priv User (needs AZ CLI and Graph Session and will only work till MS kills the Windows Graph API!!!)"
Write-Host "13. Raw Command Prompt"
Write-Host "B. Return to Main Menu"
$userInput = Read-Host -Prompt "Select an option"
switch ($userInput) {
"1" {
UserInfoQuery
}
"2" {
UserGroupsQuery
}
"3" {
GroupMembersQuery
}
"4" {
RoleAssignmentsQuery
}
"5" {
AvailableResourcesQuery
}
"6" {
OwnedObjectsQuery
}
"7" {
OwnedApplicationsQuery
}
"8" {
AdministrativeUnitsQuery
}
"9" {
PasswordPolicyQuery
}
"10" {
GetAppDetailsQuery
}
"11" {
DynamicGroupsQuery
}
"12" {
ConditionalAccessPoliciesQuery
}
"13" {
RawCommandPrompt
}
"B" {
return
}
default {
Write-Host "Invalid selection, please try again."
Write-Host "`nPress any key to continue..."
[void][System.Console]::ReadKey($true)
}
}
}
}
# Helper Function for CAPs to resolve IDs to display names for users and applications
function Resolve-Ids {
param (
[array]$Ids,
[string]$Type
)
$names = @{ }
$guidPattern = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
foreach ($id in $Ids) {
if ($id -eq "All" -or $id -eq "None") {
$names[$id] = $id
} elseif ($id -match $guidPattern) {
try {
if ($Type -eq "User") {
$entity = Get-MgUser -UserId $id -ErrorAction Stop
} elseif ($Type -eq "Application") {
$entity = Get-MgServicePrincipal -Filter "AppId eq '$id'" -ErrorAction Stop
}
$names[$id] = $entity.DisplayName
} catch {
$names[$id] = "Unavailable"
}
} else {
$names[$id] = $id # Assume that if it's not an ID, it might already be a name
}
}
return $names
}
# Helper Function for CAPs to fetch data from an endpoint
function Get-AllLegacyGraphData {
param (
[string]$AccessToken,
[string]$InitialEndpoint
)
$allResults = @()
$nextLink = $InitialEndpoint
while ($nextLink) {
$headers = @{ "Authorization" = "Bearer $AccessToken" }
try {
$response = Invoke-RestMethod -Uri $nextLink -Headers $headers -Method Get
} catch {
Write-Error "Failed to fetch data from ${nextLink}: $_"
return $null
}
if ($response.value) {
$allResults += $response.value
}
if ($response.'@odata.nextLink') {
$nextLink = $response.'@odata.nextLink'
Write-Host "Found nextLink for pagination: $nextLink"
} else {
$nextLink = $null
}
}
return $allResults
}
# Helper Function for CAPs to format policy details and resolve names
function Format-PolicyDetails {
param (
[array]$Policies
)
foreach ($policy in $Policies) {
$hasExclusions = $false
Write-Host "`nPolicy: $($policy.displayName)" -ForegroundColor Yellow
try {
$details = $policy.policyDetail | ForEach-Object { ConvertFrom-Json $_ }
foreach ($detail in $details) {
if ($detail.Conditions.Users.Exclude -or
$detail.Conditions.Applications.Exclude -or
$detail.Conditions.DevicePlatforms.Exclude -or
$detail.Conditions.ClientTypes.Exclude) {
$hasExclusions = $true
}
if ($hasExclusions) {
Write-Host "This Policy has Exclusions. Check for MFA Bypasses!!!" -ForegroundColor Red
}
if ($detail.Conditions.Users.Include) {
$userIds = $detail.Conditions.Users.Include | ForEach-Object { $_.Users } | Select-Object -Unique
$userNames = Resolve-Ids -Ids $userIds -Type "User"
$includedUsers = ($userIds | ForEach-Object { $userNames[$_] }) -join ", "
Write-Host "Included Users: $includedUsers"
}
if ($detail.Conditions.Users.Exclude) {
$userIdsEx = $detail.Conditions.Users.Exclude | ForEach-Object { $_.Users } | Select-Object -Unique
$userNamesEx = Resolve-Ids -Ids $userIdsEx -Type "User"
$excludedUsers = ($userIdsEx | ForEach-Object { $userNamesEx[$_] }) -join ", "
Write-Host "Excluded Users: $excludedUsers"
}
if ($detail.Conditions.Applications.Include) {
$appIds = $detail.Conditions.Applications.Include | ForEach-Object { $_.Applications } | Select-Object -Unique
$appNames = Resolve-Ids -Ids $appIds -Type "Application"
$includedApps = ($appIds | ForEach-Object { $appNames[$_] }) -join ", "
Write-Host "Included Applications: $includedApps"
}
if ($detail.Conditions.Applications.Exclude) {
$appIdsEx = $detail.Conditions.Applications.Exclude | ForEach-Object { $_.Applications } | Select-Object -Unique
$appNamesEx = Resolve-Ids -Ids $appIdsEx -Type "Application"
$excludedApps = ($appIdsEx | ForEach-Object { $appNamesEx[$_] }) -join ", "
Write-Host "Excluded Applications: $excludedApps"
}
if ($detail.Conditions.DevicePlatforms.Include) {
$DevicePlatformsInclude = ($detail.Conditions.DevicePlatforms.Include | ForEach-Object { $_.DevicePlatforms }) -join ", "
Write-Host "Included DevicePlatforms: $DevicePlatformsInclude"
}
if ($detail.Conditions.DevicePlatforms.Exclude) {
$DevicePlatformsExclude = ($detail.Conditions.DevicePlatforms.Exclude | ForEach-Object { $_.DevicePlatforms }) -join ", "
Write-Host "Excluded DevicePlatforms: $DevicePlatformsExclude"
}
if ($detail.Conditions.ClientTypes.Include) {
$ClientsInclude = ($detail.Conditions.ClientTypes.Include | ForEach-Object { $_.ClientTypes }) -join ", "
Write-Host "Included Clients: $ClientsInclude"
}
if ($detail.Conditions.ClientTypes.Exclude) {
$ClientsExclude = ($detail.Conditions.ClientTypes.Exclude | ForEach-Object { $_.ClientTypes }) -join ", "
Write-Host "Excluded Clients: $ClientsExclude"
}
if ($detail.Controls.Control) {
$controls = ($detail.Controls.Control) -join ", "
Write-Host "Controls Requirements (any): $controls"
}
if ($detail.SessionControls) {
$sessionControls = ($detail.SessionControls) -join ", "
Write-Host "Session controls: $sessionControls"
}
}
} catch {
Write-Error "Failed to parse policy details: $_"
}
}
}
# Main function to fetch CAPs inspired by Roadrecon by Dirk-jan https://github.com/dirkjanm/ROADtools/tree/master/roadrecon
function ConditionalAccessPoliciesQuery {
Clear-Host
DisplayHeader
Write-Host "Fetching Conditional Access Policies" -ForegroundColor Cyan
# Get a Graph Access Token from the authenticated Azure CLI session
$TokenResponse = az account get-access-token --resource https://graph.windows.net --tenant $Global:tenantID
$accessToken = ($tokenResponse | ConvertFrom-Json).accessToken
if (-not $accessToken) {
Write-Error "Failed to obtain access token."
return
}
# Define the policies endpoint
$policiesEndpoint = "https://graph.windows.net/$tenantId/policies?api-version=1.61-internal"
# Fetch and display data from the policies endpoint
Write-Host "Attempting to fetch data from: $policiesEndpoint" -ForegroundColor Cyan
$policies = Get-AllLegacyGraphData -AccessToken $accessToken -InitialEndpoint $policiesEndpoint
# Filter policies where policyType equals 18
$filteredPolicies = $policies | Where-Object { $_.policyType -eq 18 }
Format-PolicyDetails -Policies $filteredPolicies
Write-Host "`nPress any key to return to the queries menu..."
[void][System.Console]::ReadKey($true)
}
# Function to query dynamic groups using Microsoft Graph PowerShell
function DynamicGroupsQuery {
Clear-Host
DisplayHeader
Write-Host "Dynamic Groups Query" -ForegroundColor Cyan
try {
Clear-Host
DisplayHeader
Write-Host "Graph PS Module output:" -ForegroundColor Magenta
# Fetch dynamic groups using Microsoft Graph PowerShell
$dynamicGroups = Get-MgGroup -Filter "groupTypes/any(c:c eq 'DynamicMembership')"
foreach ($group in $dynamicGroups) {
$groupName = $group.DisplayName
$membershipQuery = $group.MembershipRule
$Description = $group.Description
Write-Output "Group Name: $groupName"
Write-Output "Description: $Description"
Write-Output "Membership Query: $membershipQuery"
Write-Output ""
}
}
catch {
Write-Host "Error retrieving dynamic groups: $_" -ForegroundColor Red
}
Write-Host "`nPress any key to return to the queries menu..."
[void][System.Console]::ReadKey($true)
}
# Function to query owned applications
function OwnedApplicationsQuery {
Clear-Host
DisplayHeader
Write-Host "Owned Applications Query" -ForegroundColor Cyan
# Display logged-in users
$accounts = @()
$accountIds = @()
if ($azureCliAccount -ne "Not logged in") {
$accounts += $azureCliAccount
$accountIds += $azureCliId
}
if ($azModuleAccount -ne "Not logged in") {
$accounts += $azModuleAccount
$accountIds += $azModuleId
}
if ($graphModuleAccount -ne "Not logged in") {
$accounts += $graphModuleAccount
$accountIds += $graphModuleId
}
# Show list and prompt for input
for ($i = 0; $i -lt $accounts.Length; $i++) {
Write-Host "$($i + 1). $($accounts[$i])" -ForegroundColor Yellow
}
Write-Host "Enter a number to select a user or type a custom Object ID:"
$input = Read-Host
# Determine user ID
$userId = if ($input -match '^\d+$' -and [int]$input -le $accounts.Length) {
$accountIds[$input - 1]
} else {
$input
}
Write-Host "Select tool(s) to use:" -ForegroundColor Yellow
Write-Host "1. Azure CLI" -ForegroundColor Yellow
Write-Host "3. Graph PS Module" -ForegroundColor Yellow
Write-Host "4. All" -ForegroundColor Yellow
$toolChoice = Read-Host
Start-Sleep -Seconds 2
try {
Clear-Host
DisplayHeader
if ($toolChoice -eq "1" -or $toolChoice -eq "4") {
Write-Host "AZ CLI output:" -ForegroundColor Magenta