forked from hausec/PowerZure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowerZure.psm1
2217 lines (2014 loc) · 93.9 KB
/
PowerZure.psm1
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
Set-ExecutionPolicy Bypass
Set-Item Env:\SuppressAzurePowerShellBreakingChangeWarnings "true"
function Get-AzureGraphToken
{
$token = Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com/"
$Headers = @{}
$Headers.Add("Authorization","Bearer"+ " " + "$($token.token)")
$Headers
}
function Get-AzureRESTToken
{
$token = Get-AzAccessToken
$Headers = @{}
$Headers.Add("Authorization","Bearer"+ " " + "$($token.token)")
$Headers
}
function Connect-AADUser {
$ConnectionTest = try{ [Microsoft.Open.Azure.AD.CommonLibrary.AzureSession]::AccessTokens['AccessToken']}
catch{"Error"}
If($ConnectionTest -eq 'Error'){
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$token = Get-AzAccessToken -ResourceTypeName AadGraph
Connect-AzureAD -AadAccessToken $token.token -AccountId $context.Account.Id -TenantId $context.tenant.id}
}
function Show-AzureCurrentUser
{
$APSUser = Get-AzContext
$Headers = Get-AzureGraphToken
if($APSUser)
{
$Headers = Get-AzureGraphToken
$Login = Connect-AADUser
$obj = New-Object -TypeName psobject
$username = $APSUser.Account
If($APSUser.Subscription){
$activesub = $APSUser.Subscription.Name + ' (' + $APSUser.Subscription.Id + ')'
}
$Subscriptions = get-azsubscription *>&1
$subcoll =@()
If ($Subscriptions){
ForEach ($Subscription in $Subscriptions){
$sub = $Subscription.Name + ' (' + $Subscription.Id + ')'
$subcoll += $sub
}
}
$user = Invoke-RestMethod -Headers $Headers -Uri 'https://graph.microsoft.com/beta/me'
$userid=$user.id
$Memberships = Get-AzureADUserMembership -ObjectId $userid
$Groups = @()
$AADRoles = @()
ForEach ($Membership in $Memberships){
If($Membership.ObjectType -eq 'Group'){
$GroupName = $Membership.DisplayName
$Groups += $GroupName
}else{
$AADRoles += $Membership.DisplayName
}
}
$coll = @()
try{$rbacroles = Get-AzRoleAssignment -ObjectId $userid *>&1}catch{}
If($rbacroles){
ForEach ($rbacrole in $rbacroles){
$RBACRoleCollection = $rbacrole.RoleDefinitionName + ' (' + $rbacrole.scope + ')'
$coll += $RBACRoleCollection
}
}
$obj | Add-Member -MemberType NoteProperty -Name TenantID -Value $APSUser.Tenant.id
$obj | Add-Member -MemberType NoteProperty -Name Username -Value $user.userPrincipalName
$obj | Add-Member -MemberType NoteProperty -Name ObjectId -Value $userId
$obj | Add-Member -MemberType NoteProperty -Name AADRoles -Value $AADRoles
$obj | Add-Member -MemberType NoteProperty -Name AADGroups -Value $Groups
$obj | Add-Member -MemberType NoteProperty -Name AzureRoles -Value $coll
$obj | Add-Member -MemberType NoteProperty -Name 'Active Subscription' -Value $activesub
$obj | Add-Member -MemberType NoteProperty -Name 'Available Subscriptions' -Value $subcoll
$obj
}
else{
Write-Error "Please login with Connect-AzAccount" -Category ConnectionError
}
}
function Invoke-PowerZure
{
<#
.SYNOPSIS
Displays info about this script.
.PARAMETER
-h (Help)
.EXAMPLE
Invoke-PowerZure -h
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false)][switch]$h = $null,
[Parameter(Mandatory=$false)][switch]$Checks = $null,
[Parameter(Mandatory=$false)][switch]$Banner = $null)
If($Checks)
{
$ErrorActionPreference = "Stop"
$Version = $PSVersionTable.PSVersion.Major
If ($Version -lt 5)
{
Write-Host "Az requires at least PowerShell 5.1"
Exit
}
#Module Check
$Modules = Get-InstalledModule
if ($Modules.Name -notcontains 'Az.Accounts')
{
Write-host "Install Az PowerShell Module?" -ForegroundColor Yellow
$Readhost = Read-Host " ( y / n ) "
if ($ReadHost -eq 'y' -or $Readhost -eq 'yes')
{
Install-Module -Name Az -AllowClobber -Scope CurrentUser
$Modules = Get-InstalledModule
if ($Modules.Name -contains 'Az.Accounts')
{
Write-Host "Successfully installed Az module. Please open a new PowerShell window and re-import PowerZure to continue" -ForegroundColor Yellow
Exit
}
}
if ($ReadHost -eq 'n' -or $Readhost -eq 'no')
{
Write-Host "Az PowerShell not installed, PowerZure cannot operate without this module." -ForegroundColor Red
Exit
}
}
if ($Modules.Name -notcontains 'AzureAD'){
Write-host "Install AzureAD PowerShell Module?" -ForegroundColor Yellow
$Readhost = Read-Host " ( y / n ) "
if ($ReadHost -eq 'y' -or $Readhost -eq 'yes')
{
Install-module -Name AzureADPreview -AllowClobber
$Modules = Get-InstalledModule
if ($Modules.Name -contains 'AzureADPreview')
{
Write-Host "Successfully installed AzureAD module. Please open a new PowerShell window and re-import PowerZure to continue" -ForegroundColor Yellow
Exit
}
}
if ($ReadHost -eq 'n' -or $Readhost -eq 'no')
{
Write-Host "AzureAD PowerShell not installed, PowerZure cannot operate without this module." -ForegroundColor Red
Exit
}
}
#Login Check
$APSUser = Get-AzContext
if(!$APSUser){
Write-Error "Please login with Connect-AzAccount" -Category ConnectionError
Pause
Exit
}
}
if($h -eq $true)
{
Write-Host @"
PowerZure Version 2.1
List of Functions
------------------Info Gathering -------------
Get-AzureADRole -------------------- Gets the members of one or all Azure AD role. Roles does not mean groups.
Get-AzureAppOwner ----------------- Returns all owners of all Applications in AAD
Get-AzureDeviceOwner -------------- Lists the owners of devices in AAD. This will only show devices that have an owner.
Get-AzureADGroup --------------------- Gathers a specific group or all groups in AzureAD and lists their members.
Get-AzureIntuneScript -------------- Lists available Intune scripts in Azure Intune
Get-AzureLogicAppConnector --------- Lists the connector APIs in Azure
Get-AzureManagedIdentities --------- Gets a list of all Managed Identities and their roles.
Get-AzurePIMAssignment ------------- Gathers the Privileged Identity Management assignments. Currently, only AzureRM roles are returned.
Get-AzureRole ---------------------- Gets the members of an Azure RBAC role.
Get-AzureRunAsAccounts ------------- Finds any RunAs accounts being used by an Automation Account
Get-AzureRolePermission ------------ Finds all roles with a certain permission
Get-AzureSQLDB --------------------- Lists the available SQL Databases on a server
Get-AzureTargets ------------------- Compares your role to your scope to determine what you have access to
Get-AzureTenantId ------------------ Returns the ID of a tenant belonging to a domain
Get-AzureUser ---------------------- Gathers info on a specific user or all users including their groups and roles in Azure & AzureAD
Show-AzureCurrentUser -------------- Returns the current logged in user name and any owned objects
Show-AzureKeyVaultContent ---------- Lists all available content in a key vault
Show-AzureStorageContent ----------- Lists all available storage containers, shares, and tables
------------------Operational --------------
Add-AzureADGroup ---------------- Adds a user to an Azure AD Group
Add-AzureADRole ----------------- Assigns a specific Azure AD role to a User
Add-AzureSPSecret --------------- Adds a secret to a service principal
Add-AzureRole ------------------- Adds a role to a user in Azure
Connect-AzureJWT ---------------- Logins to Azure using a JWT access token.
New-AzureBackdoor --------------- Creates a backdoor in Azure via Service Principal
Export-AzureKeyVaultContent ----- Exports a Key as PEM or Certificate as PFX from the Key Vault
Get-AzureKeyVaultContent -------- Get the secrets and certificates from a specific Key Vault or all of them
Get-AzureRunAsCertificate ------- Will gather a RunAs accounts certificate if one is being used by an automation account, which can then be used to login as that account.
Get-AzureRunbookContent --------- Gets a specific Runbook and displays its contents or all runbook contents
Get-AzureStorageContent --------- Gathers a file from a specific blob or File Share
Get-AzureVMDisk ----------------- Generates a link to download a Virtual Machiche’s disk. The link is only available for 24 hours.
Invoke-AzureCommandRunbook ------ Will execute a supplied command or script from a Runbook if the Runbook is configured with a “RunAs” account
Invoke-AzureCustomScriptExtension Runs a PowerShell script by uploading it as a Custom Script Extension
Invoke-AzureMIBackdoor ---------- Creates a managed identity for a VM and exposes the REST API on it to make it a persistent JWT backdoor generator.
Invoke-AzureRunCommand ---------- Will run a command or script on a specified VM
Invoke-AzureRunMSBuild ---------- Will run a supplied MSBuild payload on a specified VM.
Invoke-AzureRunProgram ---------- Will run a given binary on a specified VM
Invoke-AzureVMUserDataAgent ----- Deploys the agent used by Invoke-AzureVMUserDataCommand
Invoke-AzureVMUserDataCommand --- Executes a command using the userData channel on a specified Azure VM.
New-AzureUser ------------------- Creates a user in Azure Active Directory
New-AzureIntuneScript ----------- Uploads a PS script to Intune
Set-AzureElevatedPrivileges ----- Elevates the user’s privileges from Global Administrator in AzureAD to include User Access Administrator in Azure RBAC.
Set-AzureSubscription ----------- Sets default subscription. Necessary if in a tenant with multiple subscriptions.
Set-AzureUserPassword ----------- Sets a user’s password
Start-AzureRunbook -------------- Starts a Runbook
"@
}
if($Banner)
{
Write-Host @'
8888888b. ,/ 8888888888P
888 Y88b ,'/ d88P
888 888 ,' / d88P
888 d88P .d88b. 888 888 888 .d88b. 888d888 ,' /____ d88P 888 888 888d888 .d88b.
8888888P" d88""88b 888 888 888 d8P Y8b 888P" .'____ ,' d88P 888 888 888P" d8P Y8b
888 888 888 888 888 888 88888888 888 / ,' d88P 888 888 888 88888888
888 Y88..88P Y88b 888 d88P Y8b. 888 / ,' d88P Y88b 888 888 Y8b.
888 "Y88P" "Y8888888P" "Y8888 888 /,' d8888888888 "Y88888 888 "Y8888 version 2.1
/'
'@ -ForegroundColor Cyan
Write-Host 'Confused on what to do next? Check out the documentation: ' -ForegroundColor yellow -NoNewline
Write-Host 'https://powerzure.readthedocs.io/ ' -ForegroundColor Blue -NoNewline
Write-Host 'or type ' -ForegroundColor yellow -NoNewline
Write-Host 'Invoke-Powerzure -h ' -ForegroundColor Magenta -NoNewline
Write-Host 'for a function table.' -ForegroundColor yellow
Write-Host ""
Write-Host 'Please set your default subscription with ' -ForegroundColor yellow -NoNewline
Write-Host 'Set-AzureSubscription ' -ForegroundColor Magenta -NoNewline
Write-Host 'if you have multiple subscriptions. Functions WILL fail if you do not do this. Use ' -ForegroundColor yellow -NoNewline
Write-Host 'Show-AzureCurrentUser' -ForegroundColor Magenta -NoNewline
Write-Host ' to get list your accounts roles & permissions'-ForegroundColor Yellow
}
if(!$Checks -and !$h)
{
Write-Host "Please login with Connect-AzAccount" -ForegroundColor Red
}
}
Invoke-PowerZure -Checks -Banner
function Set-AzureSubscription
{
<#
.SYNOPSIS
Sets default subscription
.PARAMETER
-Id
.EXAMPLE
Set-AzureSubscription -Id b049c906-7000-4899-b644-f3eb835f04d0
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false,HelpMessage='Enter a subscription ID. Try Show-AzureCurrentUser to see a list of subscriptions')][String]$Id = $null)
$subs = Get-AzSubscription
Write-Host "Select a subscription to choose as the default subscription:" -ForegroundColor Yellow
Write-Host ""
$i=1
ForEach ($sub in $subs){
Write-Host "[$i]"- $sub.name
$i++}
Write-Host ""
$main = Read-Host "Please select a number: "
$choice = $subs[$main-1]
Set-AzContext -SubscriptionId $choice.Id
}
function Get-AzureADRole
{
<#
.SYNOPSIS
Lists the roles in Azure AD and what users are part of the role.
.PARAMETER
-All (Lists all roles, even those without a user in them)
-Role (Specific role)
.EXAMPLE
Get-AzureADRole -Role 'Global Administrator'
Get-AzureADRole -Role '4dda258a-4568-4579-abeb-07709e34e307'
Get-AzureADRole -All
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)][String]$Role = $null,
[Parameter(Mandatory=$False)][Switch]$All = $null)
$ConnectAAD = Connect-AADUser
$roles = Get-AzureADDirectoryRole
If($All)
{
ForEach ($AADRole in $Roles)
{
$roleid = $AADRole.ObjectId
$members = Get-AzureADDirectoryRoleMember -ObjectId $roleid
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name Role -Value $AADRole.DisplayName
$obj | Add-Member -MemberType NoteProperty -Name UserMember -Value $members.UserPrincipalName
$obj | Add-Member -MemberType NoteProperty -Name MemberType -Value $members.ObjectType
If($members.objectType -eq 'ServicePrincipal'){
$obj | Add-Member -MemberType NoteProperty -Name ServicePrincipalMember -Value $members.AppDisplayName
}
$obj
}
}
If($Role)
{
If($Role.length -eq 36)
{
Get-AzureADDirectoryRoleMember -ObjectId $Role
}
else
{
$roledata = Get-AzureADDirectoryRole | Where-Object {$_.DisplayName -eq "$Role"}
$roleid = $roledata.ObjectId
Get-AzureADDirectoryRoleMember -ObjectId $roleid
}
}
If(!$All -and !$Role)
{
Write-Host "Usage:" -ForegroundColor Red
Write-Host "Get-AzureADRoleMember -Role '4dda258a-4568-4579-abeb-07709e34e307'" -ForegroundColor Red
Write-Host "Get-AzureADRoleMember -All" -ForegroundColor Red
Write-Host "Get-AzureADRoleMember -Role 'Global Administrator'" -ForegroundColor Red
}
}
function Get-AzureUser
{
<#
.SYNOPSIS
Gathers info on a specific user or all users including their groups and roles in Azure & AzureAD
.PARAMETER
-Username (User Principal Name)
-All (Switch)
.EXAMPLE
Get-AzureUser -Username [email protected]
Get-AzureUser -All
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false,HelpMessage='Enter the username with the domain')][String]$Username = $null,
[Parameter(Mandatory=$false)][Switch]$All = $null)
$ConnectAAD = Connect-AADUser
If($All)
{
$users = Get-AzADUser
ForEach ($user in $users)
{
$obj = New-Object -TypeName psobject
$userid = $user.id
$Memberships = Get-AzureADUserMembership -ObjectId $userid
$Groups = @()
$AADRoles = @()
ForEach ($Membership in $Memberships){
If($Membership.ObjectType -eq 'Group'){
$GroupName = $Membership.DisplayName
$Groups += $GroupName
}else{
$AADRoles += $Membership.DisplayName
}
}
$rbac = @()
try{$rbacroles = Get-AzRoleAssignment -ObjectId $userid *>&1}catch{}
If($rbacroles){
ForEach ($rbacrole in $rbacroles){
$RBACRoleCollection = $rbacrole.RoleDefinitionName + ' (' + $rbacrole.scope + ')'
$rbac += $RBACRoleCollection
}
}
$obj | Add-Member -MemberType NoteProperty -Name Username -Value $user.userPrincipalName
$obj | Add-Member -MemberType NoteProperty -Name ObjectId -Value $userId
$obj | Add-Member -MemberType NoteProperty -Name AADRoles -Value $AADRoles
$obj | Add-Member -MemberType NoteProperty -Name AADGroups -Value $Groups
$obj | Add-Member -MemberType NoteProperty -Name AzureRoles -Value $rbac
$obj
}
}
If($Username){
If($Username -notcontains '@'){
Write-Error 'Please supply the full userprincipalname ([email protected])'-Category InvalidArgument
}
else{
$obj = New-Object -TypeName psobject
$userdata = Get-AzADUser -UserPrincipalName $Username
$userid = $userdata.Id
$Memberships = Get-AzureADUserMembership -ObjectId $userid
$Groups = @()
$AADRoles = @()
ForEach ($Membership in $Memberships){
If($Membership.ObjectType -eq 'Group'){
$GroupName = $Membership.DisplayName
$Groups += $GroupName
}else{
$AADRoles += $Membership.DisplayName
}
}
$rbac = @()
try{$rbacroles = Get-AzRoleAssignment -ObjectId $userid *>&1}catch{}
If($rbacroles){
ForEach ($rbacrole in $rbacroles){
$RBACRoleCollection = $rbacrole.RoleDefinitionName + ' (' + $rbacrole.scope + ')'
$rbac += $RBACRoleCollection
}
}
$obj | Add-Member -MemberType NoteProperty -Name Username -Value $username
$obj | Add-Member -MemberType NoteProperty -Name ObjectId -Value $userId
$obj | Add-Member -MemberType NoteProperty -Name AADRoles -Value $AADRoles
$obj | Add-Member -MemberType NoteProperty -Name AADGroups -Value $Groups
$obj | Add-Member -MemberType NoteProperty -Name AzureRoles -Value $rbac
$obj
}
}
If(!$Username -and !$All)
{
Write-Host "Usage:" -ForegroundColor Red
Write-Host "Get-AzureUser -Username [email protected]" -ForegroundColor Red
Write-Host "Get-AzureUser -All" -ForegroundColor Red
}
}
function Get-AzureADGroup
{
<#
.SYNOPSIS
Gets all the members of a specific group or all members of all groups. Group does NOT mean role.
.PARAMETER
-Group (Group name)
-All (List all group members of all groups)
.EXAMPLE
Get-AzureADGroup -Group 'Sql Admins'
Get-AzureADGroup -All
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false,HelpMessage='Group name')][String]$Group = $null,
[Parameter(Mandatory=$false)][Switch]$All = $false)
Connect-AADUser
If($All)
{
Write-Host ""
$groups=Get-AzADGroup
ForEach ($g in $groups)
{
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name GroupName -Value $g.displayname
$obj | Add-Member -MemberType NoteProperty -Name GroupId -Value $g.Id
$obj | Add-Member -MemberType NoteProperty -Name MemberName -Value ''
$obj | Add-Member -MemberType NoteProperty -Name MemberId -Value ''
$members = Get-AzADGroupMember -GroupObjectId $g.id
ForEach ($member in $members)
{
$obj | Add-Member -MemberType NoteProperty -Name MemberName -Value $member.userPrincipalName -Force
$obj | Add-Member -MemberType NoteProperty -Name MemberId -Value $member.Id -Force
}
$obj
}
}
If($group)
{
$groupdata = Get-AzADGroup -DisplayName $Group
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name GroupName -Value $Group
$obj | Add-Member -MemberType NoteProperty -Name GroupId -Value $groupdata.id
$members = Get-AzADGroupMember -GroupDisplayName $Group
$obj | Add-Member -MemberType NoteProperty -Name Members -Value $members.UserPrincipalName
$obj | Add-Member -MemberType NoteProperty -Name Members -Value $members.Id
$obj
}
if(!$All -and !$Group)
{
Write-Error "Must supply a group name or use -All switch" -Category InvalidArgument
}
}
function Add-AzureADGroup
{
<#
.SYNOPSIS
Adds a user to an Azure AD Group
.PARAMETER
-Username (UPN of the user)
-Group (AAD Group name)
.EXAMPLE
Add-AzureADGroup -User [email protected] -Group 'SQL Users'
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,HelpMessage='Target Group')][String]$Group = $null,
[Parameter(Mandatory=$true,HelpMessage='Username to add to group')][String]$Username = $null)
Add-AzADGroupMember -MemberUserPrincipalName $Username -TargetGroupDisplayName $Group
}
function Add-AzureADRole
{
<#
.SYNOPSIS
Adds a role to a user in AzureAD
.PARAMETER
-Username (Intended User)
-UserID (Intended User or Service Principal by ID)
-Role (Intended role)
-RoleId (Intended role by Id)
-ServicePrincipal (Add a role as a service principal)
.EXAMPLE
Add-AzureADRole -Username [email protected] -Role 'Company Administrator'
Add-AzureADRole -UserId 6eca6b85-7a3d-4fcf-b8da-c15a4380d286 -Role '4dda258a-4568-4579-abeb-07709e34e307'
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false)][String]$ServicePrincipal = $null,
[Parameter(Mandatory=$false)][String]$UserId = $null,
[Parameter(Mandatory=$false)][String]$Username = $null,
[Parameter(Mandatory=$false)][String]$RoleId = $null,
[Parameter(Mandatory=$false)][String]$Role = $null)
$ConnectAAD = Connect-AADUser
If($Role)
{
$roledata = Get-AzureADDirectoryRole | Where-Object {$_.DisplayName -eq "$Role"}
$roleid = $roledata.ObjectId
}
If($Username){
If($Username -notcontains '@')
{
Write-Error 'Please supply the full userprincipalname ([email protected])'-Category InvalidArgument
}
else{
$userdata = Get-AzADUser -UserPrincipalName $Username
$userid = $userdata.Id
Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $UserId
}
}
If($ServicePrincipal)
{
$spdata = Get-AzADServicePrincipal -DisplayName $ServicePrincipal
$spid = $spdata.Id
Add-AzureADDirectoryRoleMember -ObjectId $RoleId -RefObjectId $spid
}
If(!$ServicePrincipal -and !$Username)
{
Write-Error 'Please supply a userprincipalname ([email protected]) or service principal name'-Category InvalidArgument
}
If(!$Role -and !$RoldID)
{
Write-Error 'Please supply a role or roleId'-Category InvalidArgument
}
}
function Get-AzureTargets
{
<#
.SYNOPSIS
Checks your role against the scope of your role to determine what you have access to.
#>
$Connect = Connect-AADUser
$Context = Get-AzContext
$Headers = Get-AzureGraphToken
$user = Invoke-RestMethod -Headers $Headers -Uri 'https://graph.microsoft.com/beta/me'
$userid=$user.id
$Memberships = Get-AzureADUserMembership -ObjectId $userid
$aadroles = Get-AzureADUserMembership -ObjectId $userid
$Groups = @()
$AADRoles = @()
$AADRolesDetailed = @()
ForEach ($Membership in $Memberships){
If($Membership.ObjectType -eq 'Group'){
$GroupName = $Membership.DisplayName
$Groups += $GroupName
}else{
$AADRoles += $Membership.DisplayName
$AADRolesDetailed += $Membership
}
}
Write-Host "AzureAD Roles:" -ForegroundColor Magenta
Write-Host ""
ForEach ($aadrole in $AADRolesDetailed){
$aadrolename = $aadrole.DisplayName
$aadroledescription = $AADRole.Description
Write-Host "$aadrolename" -ForegroundColor Green -nonewline
Write-Host " - $aadroledescription"
}
Write-Host ""
Write-Host "Azure RBAC Roles:" -ForegroundColor Magenta
Write-Host ""
try{$rbacroles = Get-AzRoleAssignment -ObjectId $userid *>&1}catch{}
If($rbacroles){
$resources = Get-AzResource
ForEach ($rbacrole in $rbacroles){
$rolename = $rbacrole.RoleDefinitionName
$roledef = Get-AzRoleDefinition -Name $rolename
$roledesc = $roledef.Description
$rolescope = $rbacrole.scope
Write-Host "$rolename" -ForegroundColor Green -NoNewline
Write-Host " - $roledesc"
Write-Host "Scope: $rolescope"
Write-Host ""
Write-Host "Resources under that scope: " -ForegroundColor yellow
$coll = @()
ForEach ($resource in $resources){
If($resource.resourceId -match $rolescope){
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name 'Resource Name' -Value $resource.ResourceName
$obj | Add-Member -MemberType NoteProperty -Name 'Resource Group Name' -Value $resource.ResourceGroupName
$obj | Add-Member -MemberType NoteProperty -Name 'Resource Type' -Value $resource.Type
$coll += $obj
}
} $coll | ft
}
}
}
function Show-AzureKeyVaultContent
{
<#
.SYNOPSIS
Lists all available content in a key vault
.PARAMETER
-VaultName (Key Vault Name)
-All (All Key Vaults)
.EXAMPLE
Show-AzureKeyVaultContent -Name VaultName
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false,HelpMessage='Vault name')][String]$VaultName = $null,
[Parameter(Mandatory=$false)][Switch]$All = $null)
$name = Get-AzContext
If($All)
{
$vaults = Get-AzKeyVault
ForEach($vault in $vaults)
{
$vaultsname = $vault.VaultName
Set-AzKeyVaultAccessPolicy -VaultName $vaultsname -UserPrincipalName $name.Account -PermissionsToCertificates create,get,list,delete,import,update,recover,backup,restore -PermissionsToSecrets get,list,delete,recover,backup,restore -PermissionsToKeys create,get,list,delete,import,update,recover,backup,restore
$Secrets = $Vault | Get-AzKeyVaultSecret
$Keys = $Vault | Get-AzKeyVaultKey
$Certificates = $Vault | Get-AzKeyVaultCertificate
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name VaultName -Value $vaultsname
$obj | Add-Member -MemberType NoteProperty -Name SecretName -Value $Secrets.Name
$obj | Add-Member -MemberType NoteProperty -Name SecretContentType -Value $Secrets.ContentType
$obj | Add-Member -MemberType NoteProperty -Name CertificateName -Value $Certificates.Name
$obj | Add-Member -MemberType NoteProperty -Name KeyName -Value $Keys.Name
$obj | Add-Member -MemberType NoteProperty -Name KeyEnabled -Value $Keys.Enabled
$obj | Add-Member -MemberType NoteProperty -Name KeyRecoveryLevel -Value $Keys.RecoveryLevel
$obj
}
}
If($VaultName)
{
Set-AzKeyVaultAccessPolicy -VaultName $vaultname -UserPrincipalName $name.Account -PermissionsToCertificates create,get,list,delete,import,update,recover,backup,restore -PermissionsToSecrets get,list,delete,recover,backup,restore -PermissionsToKeys create,get,list,delete,import,update,recover,backup,restore
$Secrets = $vaultname | Get-AzKeyVaultSecret
$Keys = $vaultname | Get-AzKeyVaultKey
$Certificates = $vaultname | Get-AzKeyVaultCertificate
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name VaultName -Value $Vaultname
$obj | Add-Member -MemberType NoteProperty -Name SecretName -Value $Secrets.Name
$obj | Add-Member -MemberType NoteProperty -Name SecretContentType -Value $Secrets.ContentType
$obj | Add-Member -MemberType NoteProperty -Name CertificateName -Value $Certificates.Name
$obj | Add-Member -MemberType NoteProperty -Name KeyName -Value $Keys.Name
$obj | Add-Member -MemberType NoteProperty -Name KeyEnabled -Value $Keys.Enabled
$obj | Add-Member -MemberType NoteProperty -Name KeyRecoveryLevel -Value $Keys.RecoveryLevel
$obj
}
If(!$VaultName -and !$All)
{
Write-Error "Usage: Show-KeyVaultContent -Name VaultName" -Category InvalidArgument
Write-Error "Usage: Show-KeyVaultContent -All" -Category InvalidArgument
}
}
function Get-AzureKeyVaultContent
{
<#
.SYNOPSIS
Get the secrets and certificates from a specific Key Vault or all of them
.PARAMETER
-VaultName (Key Vault Name)
-All (All Key Vaults)
.EXAMPLE
Get-AzureKeyVaultContent -Name VaultName
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false,HelpMessage='Vault name')][String]$VaultName = $null,
[Parameter(Mandatory=$false)][Switch]$All = $true)
$name = Get-AzContext
if($All)
{
$vaults = Get-AzKeyVault
ForEach($vault in $vaults)
{
$vaultsname = $vault.VaultName
Set-AzKeyVaultAccessPolicy -VaultName $vaultsname -UserPrincipalName $name.Account -PermissionsToCertificates create,get,list,delete,import,update,recover,backup,restore -PermissionsToSecrets get,list,delete,recover,backup,restore -PermissionsToKeys create,get,list,delete,import,update,recover,backup,restore
$Secrets = Get-AzKeyVaultSecret -VaultName $vaultsname
ForEach($Secret in $Secrets)
{
$Value = Get-AzKeyVaultSecret -VaultName $vaultsname -name $Secret.name
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name SecretName -Value $Secret.Name
$obj | Add-Member -MemberType NoteProperty -Name SecretValue -Value $Value.SecretValueText
$obj | Add-Member -MemberType NoteProperty -Name ContentType -Value $Value.ContentType
$obj
}
}
}
If($VaultName)
{
Set-AzKeyVaultAccessPolicy -VaultName $vaultname -UserPrincipalName $name.Account -PermissionsToCertificates create,get,list,delete,import,update,recover,backup,restore -PermissionsToSecrets get,list,delete,recover,backup,restore -PermissionsToKeys create,get,list,delete,import,update,recover,backup,restore
$Secrets = Get-AzKeyVaultSecret -VaultName $vaultname
ForEach($Secret in $Secrets)
{
$Value = Get-AzKeyVaultSecret -VaultName $vaultname -name $Secret.name
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name SecretName -Value $Secret.Name
$obj | Add-Member -MemberType NoteProperty -Name SecretValue -Value $Value.SecretValueText
$obj | Add-Member -MemberType NoteProperty -Name ContentType -Value $Value.ContentType
$obj
}
}
If(!$VaultName -and !$All)
{
Write-Error "Usage: Get-KeyVaultContents -Name VaultName" -Category InvalidArgument
Write-Error "Usage: Get-KeyVaultContents -All" -Category InvalidArgument
}
}
function Export-AzureKeyVaultContent
{
<#
.SYNOPSIS
Exports a Key as PEM or Certificate as PFX from the Key Vault
.PARAMETER
-VaultName (Key Vault Name)
-Type (Key or Certificate)
-Name (Name of Key or Certificate)
-OutFilePath (Path of where to save the key or file
.EXAMPLE
Export-AzureKeyVaultContent -VaultName VaultTest -Type Key -Name Testkey1234 -OutFilePath C:\Temp
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,HelpMessage='Vault name')][String]$VaultName = $null,
[Parameter(Mandatory=$True,HelpMessage='Key/Cert name')][String]$Name = $null,
[Parameter(Mandatory=$True,HelpMessage='Where to save')][String]$OutFilePath = $null,
[Parameter(Mandatory=$True,HelpMessage='Key or Certificate?')][String]$Type = $null)
$user = Get-AzContext
Set-AzKeyVaultAccessPolicy -VaultName $vaultname -UserPrincipalName $user.Account -PermissionsToCertificates create,get,list,delete,import,update,recover,backup,restore -PermissionsToSecrets get,list,delete,recover,backup,restore -PermissionsToKeys create,get,list,delete,import,update,recover,backup,restore
If($Type -eq 'Key')
{
$Path = $OutFilePath + '\key.pem'
$Export = Get-AzKeyVaultKey -VaultName $VaultName -KeyName $Name -OutFile $Path
If($Export)
{
Write-Host "Successfully exported key to $path" -Foregroundcolor Green
}
else
{
Write-Host "Failed to export Key" -Foregroundcolor Red
}
}
If($Type -eq 'Certificate')
{
$Path = $OutFilePath + '\Cert.pfx'
$cert = Get-AzKeyVaultCertificate -VaultName $Vaultname -Name $Name
$secret = Get-AzKeyVaultSecret -VaultName $vaultName -Name $cert.Name
$secretByte = [Convert]::FromBase64String($secret.SecretValueText)
$x509Cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
$x509Cert.Import($secretByte, "", "Exportable,PersistKeySet")
$type = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx
$pfxFileByte = $x509Cert.Export($type, $password)
[System.IO.File]::WriteAllBytes("$Path", $pfxFileByte)
$test = ls C:\temp\cert.pfx
If($test)
{
Write-Host "Successfully exported Certificate to $path" -Foregroundcolor Green
}
else
{
Write-Host "Failed to export Certificate"
}
}
elseif($Type -ne 'Certificate' -and $Type -ne 'Key')
{
Write-Error "-Type must be a Certificate or Key!" -Category InvalidArgument
Write-Error "Usage: Export-KeyVaultContent -VaultName VaultTest -Type Key -Name Testkey1234 -OutFilePath C:\Temp" -Category InvalidArgument
}
}
function Show-AzureStorageContent
{
<#
.SYNOPSIS
Lists all available storage containers, shares, and tables
.PARAMETER
All- List all storage account contents
StorageAccountName - Name of a specific account
.EXAMPLE
Show-AzureStorageContent -All
Show-AzureStorageContent -StorageAccountName TestAcct
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false)][String]$StorageAccountName = $null,
[Parameter(Mandatory=$false)][Switch]$All = $null)
If($All)
{
$accounts = Get-AzStorageAccount
ForEach($account in $accounts)
{
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name StorageAccountName -Value $account.StorageAccountName
$obj | Add-Member -MemberType NoteProperty -Name ResourceGroup -Value $account.ResourceGroupname
$Containers = Get-AzStorageAccount -Name $account.StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageContainer
$obj | Add-Member -MemberType NoteProperty -Name ContainerName -Value $Containers.Name
$obj | Add-Member -MemberType NoteProperty -Name ContainerPublicAccess -Value $Containers.PublicAccess
$obj | Add-Member -MemberType NoteProperty -Name LastModified -Value $Containers.LastModified
$Blobs = Get-AzStorageAccount -Name $account.StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageContainer | Get-AzStorageBlob
$obj | Add-Member -MemberType NoteProperty -Name BlobName -Value $Blobs.Name
$obj | Add-Member -MemberType NoteProperty -Name BlobSize -Value $Blobs.Length
$obj | Add-Member -MemberType NoteProperty -Name BlobContentType -Value $Blobs.ContentType
$obj | Add-Member -MemberType NoteProperty -Name BlobHomeContainer -Value $Blobs.Context.StorageA
$Shares = Get-AzStorageAccount -Name $account.StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageShare
$obj | Add-Member -MemberType NoteProperty -Name ShareName -Value $Shares.name
$Files = Get-AzStorageAccount -Name $account.StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageShare | Get-AzStorageFile
$obj | Add-Member -MemberType NoteProperty -Name FileName -Value $Files.Name
$obj | Add-Member -MemberType NoteProperty -Name HomeShare -Value $Files.ShareDirectoryClient.ShareName
$obj
}
}
If($StorageAccountName)
{
$account = Get-AzStorageAccount -Name $StorageAccountName
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name StorageAccountName -Value $account.StorageAccountName
$obj | Add-Member -MemberType NoteProperty -Name ResourceGroup -Value $account.ResourceGroupname
$Containers = Get-AzStorageAccount -Name $StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageContainer
$obj | Add-Member -MemberType NoteProperty -Name ContainerName -Value $Containers.Name
$obj | Add-Member -MemberType NoteProperty -Name ContainerPublicAccess -Value $Containers.PublicAccess
$obj | Add-Member -MemberType NoteProperty -Name LastModified -Value $Containers.LastModified
$Blobs = Get-AzStorageAccount -Name $StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageContainer | Get-AzStorageBlob
$obj | Add-Member -MemberType NoteProperty -Name BlobName -Value $Blobs.Name
$obj | Add-Member -MemberType NoteProperty -Name BlobSize -Value $Blobs.Length
$obj | Add-Member -MemberType NoteProperty -Name BlobContentType -Value $Blobs.ContentType
$obj | Add-Member -MemberType NoteProperty -Name BlobHomeContainer -Value $Blobs.Context.StorageA
$Shares = Get-AzStorageAccount -Name $StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageShare
$obj | Add-Member -MemberType NoteProperty -Name ShareName -Value $Shares.name
$Files = Get-AzStorageAccount -Name $StorageAccountName -ResourceGroup $account.ResourceGroupname | Get-AzStorageShare | Get-AzStorageFile
$obj | Add-Member -MemberType NoteProperty -Name FileName -Value $Files.Name
$obj | Add-Member -MemberType NoteProperty -Name HomeShare -Value $Files.ShareDirectoryClient.ShareName
$obj
}
If(!$All -and !$StorageAccountName)
{
Write-Host "Usage:" -ForegroundColor Red
Write-Host "Show-AzureStorageContent -StorageAccountName TestAcct" -ForegroundColor Red
Write-Host "Show-AzureStorageContent -All" -ForegroundColor Red
}
}
function Get-AzureStorageContent
{
<#
.SYNOPSIS
Gathers a file from a specific blob or File Share
.PARAMETER
Share - Name of the share the file is located in
Path - Path of the file in the target share
Blob - Name of the blob the file is located in
StorageAccountName - Name of a specific account
ResourceGroup - The RG the Storage account is located in
ContainerName - Name of the Container the file is located in
.EXAMPLE
Get-AzureStorageContent
Get-AzureStorageContent -StorageAccountName TestAcct -Type Container
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][String]$StorageAccountName = $null,
[Parameter(Mandatory=$true)][String]$ResourceGroup = $null,
[Parameter(Mandatory=$false)][String]$Share = $null,
[Parameter(Mandatory=$false)][String]$Path = $null,
[Parameter(Mandatory=$false)][String]$Blob = $null,
[Parameter(Mandatory=$false)][String]$ContainerName = $null)
If($ContainerName -and $Blob)
{
Get-AzStorageAccount -Name $StorageAccountName -ResourceGroupName $ResourceGroup | Get-AzStorageBlobContent -Container $ContainerName -Blob $Blob
}
If($Share -and $Path)
{
Get-AzStorageAccount -Name $StorageAccountName -ResourceGroupName $ResourceGroup | Get-AzStorageFileContent -ShareName $Share -Path $Path
}
}
function Get-AzureVMDisk
{
<#
.SYNOPSIS
Generates a link to download a Virtual Machiche's disk. The link is only available for 24 hours.
.PARAMETER
-DiskName
.EXAMPLE
Get-AzureVMDisk -DiskName AzureWin10_OsDisk_1_c2c7da5a0838404c84a70d6ec097ebf5
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][String]$DiskName = $null)
$Disk = Get-AzDisk -Name $DiskName
$URI = Grant-AzDiskAccess -ResourceGroupName $Disk.ResourceGroupName -DiskName $DiskName -Access Read -DurationInSecond 86400
If($URI)
{
Write-Host "Successfully got a link. Link is active for 24 Hours" -ForegroundColor Yellow
$URI
}
}
function Get-AzureRunbookContent
{
<#
.SYNOPSIS
Gets a specific Runbook and displays its contents.
.PARAMETER
-Runbook (Name of Runbook)
-All
-OutFilePath (Where to save Runbook)
.EXAMPLE
Get-AzureRunbookContent -Runbook Runbooktest -OutFilePath 'C:\temp'
Get-AzureRunbookContent -All -OutFilePath 'C:\temp
#>
[CmdletBinding()]
Param(