forked from DanielChronlund/DCToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DCToolbox.psm1
3434 lines (2449 loc) · 129 KB
/
DCToolbox.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
function Get-DCHelp {
$DCToolboxVersion = '1.0.28'
$HelpText = @"
____ ____________ ____
/ __ \/ ____/_ __/___ ____ / / /_ ____ _ __
/ / / / / / / / __ \/ __ \/ / __ \/ __ \| |/_/
/ /_/ / /___ / / / /_/ / /_/ / / /_/ / /_/ /> <
/_____/\____/ /_/ \____/\____/_/_.___/\____/_/|_|
A PowerShell toolbox for Microsoft 365 security fans.
---------------------------------------------------
Author: Daniel Chronlund
Version: $DCToolboxVersion
This PowerShell module contains a collection of tools for Microsoft 365 security tasks, Microsoft Graph functions, Azure AD management, Conditional Access, zero trust strategies, attack and defense scenarios, etc.
The home of this module: https://github.com/DanielChronlund/DCToolbox
Please follow me on my blog https://danielchronlund.com, on LinkedIn and on Twitter!
@DanielChronlund
To get started, explore and copy script examples to your clipboard with:
"@
Write-Host -ForegroundColor "Yellow" $HelpText
Write-Host -ForegroundColor "Cyan" "Copy-DCExample"
Write-Host ""
}
function Copy-DCExample {
function CreateMenu {
param
(
[parameter(Mandatory = $true)]
[string]$MenuTitle,
[parameter(Mandatory = $true)]
[string[]]$MenuChoices
)
# Create a counter.
$Counter = 1
# Write menu title.
Write-Host -ForegroundColor "Yellow" "*** $MenuTitle ***"
Write-Host -ForegroundColor "Yellow" ""
# Generate the menu choices.
foreach ($MenuChoice in $MenuChoices) {
Write-Host -ForegroundColor "Yellow" "[$Counter] $MenuChoice"
# Add to counter.
$Counter = $Counter + 1
}
# Write empty line.
Write-Host -ForegroundColor "Yellow" ""
# Write exit line.
Write-Host -ForegroundColor "Yellow" "[0] Quit"
# Write empty line.
Write-Host -ForegroundColor "Yellow" ""
# Prompt user for input.
$prompt = "Choice"
Read-Host $prompt
# Return users choice.
return $prompt
}
# Function for handling the menu choice.
function HandleMenuChoice {
param
(
[parameter(Mandatory = $true)]
[string[]]$MenuChoice
)
# Menu choices.
switch ($MenuChoice) {
1 {
$Snippet = @'
# Microsoft Graph with PowerShell examples.
# *** Connect Examples ***
# Connect to Microsoft Graph with delegated permissions.
$Parameters = @{
ClientID = ''
ClientSecret = ''
}
$AccessToken = Connect-DCMsGraphAsDelegated @Parameters
# Connect to Microsoft Graph with application permissions.
$Parameters = @{
TenantName = 'example.onmicrosoft.com'
ClientID = ''
ClientSecret = ''
}
$AccessToken = Connect-DCMsGraphAsApplication @Parameters
# *** Microsoft Graph Query Examples ***
# GET data from Microsoft Graph.
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'GET'
GraphUri = 'https://graph.microsoft.com/v1.0/users'
}
Invoke-DCMsGraphQuery @Parameters
# POST changes to Microsoft Graph.
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'POST'
GraphUri = 'https://graph.microsoft.com/v1.0/users'
GraphBody = @"
<Insert JSON request body here>
"@
}
Invoke-DCMsGraphQuery @Parameters
# PUT changes to Microsoft Graph.
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'PUT'
GraphUri = 'https://graph.microsoft.com/v1.0/users'
GraphBody = @"
<Insert JSON request body here>
"@
}
Invoke-DCMsGraphQuery @Parameters
# PATCH changes to Microsoft Graph.
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'PATCH'
GraphUri = 'https://graph.microsoft.com/v1.0/users'
GraphBody = @"
<Insert JSON request body here>
"@
}
Invoke-DCMsGraphQuery @Parameters
# DELETE data from Microsoft Graph.
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'DELETE'
GraphUri = 'https://graph.microsoft.com/v1.0/users'
}
Invoke-DCMsGraphQuery @Parameters
<#
Filter examples:
/users?$filter=startswith(givenName,'J')
/users?$filter=givenName eq 'Test'
#>
# Learn more about the Graph commands.
help Connect-DCMsGraphAsDelegated -Full
help Connect-DCMsGraphAsApplication -Full
help Invoke-DCMsGraphQuery -Full
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
2 {
$Snippet = @'
# Manage Conditional Access as code.
<#
You first need to register a new application in your Azure AD according to this article:
https://danielchronlund.com/2018/11/19/fetch-data-from-microsoft-graph-with-powershell-paging-support/
The following Microsoft Graph API permissions are required for this to work:
Policy.ReadWrite.ConditionalAccess
Policy.Read.All
Directory.Read.All
Agreement.Read.All
Application.Read.All
Also, the user running this (the one who signs in when the authentication pops up) must have the appropriate permissions in Azure AD (Global Admin, Security Admin, Conditional Access Admin, etc).
#>
# Export your Conditional Access policies to a JSON file for backup.
$Parameters = @{
ClientID = ''
ClientSecret = ''
FilePath = 'C:\Temp\Conditional Access Backup.json'
}
Export-DCConditionalAccessPolicyDesign @Parameters
# Import Conditional Access policies from a JSON file exported by Export-DCConditionalAccessPolicyDesign.
$Parameters = @{
ClientID = ''
ClientSecret = ''
FilePath = 'C:\Temp\Conditional Access Backup.json'
SkipReportOnlyMode = $false
DeleteAllExistingPolicies = $false
}
Import-DCConditionalAccessPolicyDesign @Parameters
# Export Conditional Access policy design report to Excel.
$Parameters = @{
ClientID = ''
ClientSecret = ''
}
New-DCConditionalAccessPolicyDesignReport @Parameters
# Export Conditional Access Assignment Report to Excel.
$Parameters = @{
ClientID = ''
ClientSecret = ''
IncludeGroupMembers = $false
}
New-DCConditionalAccessAssignmentReport @Parameters
# Learn more about the different Conditional Access commands in DCToolbox.
help Export-DCConditionalAccessPolicyDesign -Full
help Import-DCConditionalAccessPolicyDesign -Full
help New-DCConditionalAccessPolicyDesignReport -Full
help New-DCConditionalAccessAssignmentReport -Full
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
3 {
$Snippet = @'
# Install required modules (if you are local admin) (only needed first time).
Install-Module -Name DCToolbox -Force
Install-Module -Name AzureADPreview -Force
Install-Package msal.ps -Force
# Install required modules as curren user (if you're not local admin) (only needed first time).
Install-Module -Name DCToolbox -Scope CurrentUser -Force
Install-Module -Name AzureADPreview -Scope CurrentUser -Force
Install-Package msal.ps -Scope CurrentUser -Force
# If you want to, you can run Connect-AzureAD before running Enable-DCAzureADPIMRole, but you don't have to.
# If you want to use another accoutn than your current account using SSO, first connect with this.
Connect-AzureAD -AccountId '[email protected]'
# Enable one of your Azure AD PIM roles.
Enable-DCAzureADPIMRole
# Enable multiple Azure AD PIM roles.
Enable-DCAzureADPIMRole -RolesToActivate 'Exchange Administrator', 'Security Reader'
# Fully automate Azure AD PIM role activation.
Enable-DCAzureADPIMRole -RolesToActivate 'Exchange Administrator', 'Security Reader' -UseMaximumTimeAllowed -Reason 'Performing some Exchange security coniguration according to change #12345.'
<#
Example output:
VERBOSE: Connecting to Azure AD...
*** Activate PIM Role ***
[1] User Account Administrator
[2] Application Administrator
[3] Security Administrator
[0] Exit
Choice: 3
Reason: Need to do some security work!
Duration [1 hour(s)]: 1
VERBOSE: Activating PIM role...
VERBOSE: Security Administrator has been activated until 11/13/2020 11:41:01!
#>
# Learn more about Enable-DCAzureADPIMRole.
help Enable-DCAzureADPIMRole -Full
# Privileged Identity Management | My roles:
# https://portal.azure.com/#blade/Microsoft_Azure_PIMCommon/ActivationMenuBlade/aadmigratedroles
# Privileged Identity Management | Azure AD roles | Overview:
# https://portal.azure.com/#blade/Microsoft_Azure_PIMCommon/ResourceMenuBlade/aadoverview/resourceId//resourceType/tenant/provider/aadroles
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
4 {
$Snippet = @'
# Learn how to set this up.
Get-Help New-DCStaleAccountReport -Full
# Export stale Azure AD account report to Excel.
$Parameters = @{
ClientID = ''
ClientSecret = ''
LastSeenDaysAgo = 30
}
New-DCStaleAccountReport @Parameters
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
5 {
$Snippet = @'
### Clean up phone authentication methods for all Azure AD users ###
<#
Set the registered applications ClientID and ClientSecret further down. This script requires the following Microsoft Graph permissions:
Delegated:
UserAuthenticationMethod.ReadWrite.All
Reports.Read.All
It also requires the DCToolbox PowerShell module:
Install-Module -Name DCToolbox -Force
Note that this script cannot delete a users phone method if it is set as the default authentication method. Microsoft Graph cannot, as of 7/10 2021, manage the default authentication method for users in Azure AD. Hopefully the users method of choice was changed when he/she switched to the Microsoft Authenticator app or another MFA/passwordless authentication method. If not, ask them to change the default method before running the script.
Use the following report to understand how many users are registered for phone authentication (can lag up to 48 hours): https://portal.azure.com/#blade/Microsoft_AAD_IAM/AuthenticationMethodsMenuBlade/AuthMethodsActivity
#>
# Connect to Microsoft Graph with delegated permissions.
Write-Verbose -Verbose -Message 'Connecting to Microsoft Graph...'
$Parameters = @{
ClientID = ''
ClientSecret = ''
}
$AccessToken = Connect-DCMsGraphAsDelegated @Parameters
# Fetch all users with phone authentication enabled from the Azure AD authentication usage report (we're using this usage report to save time and resources when querying Graph, but their might be a 24 hour delay in the report data).
Write-Verbose -Verbose -Message 'Fetching all users with any phone authentication methods registered...'
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'GET'
GraphUri = "https://graph.microsoft.com/beta/reports/credentialUserRegistrationDetails?`$filter=authMethods/any(t:t eq microsoft.graph.registrationAuthMethod'mobilePhone') or authMethods/any(t:t eq microsoft.graph.registrationAuthMethod'officePhone')"
}
$AllUsersWithPhoneAuthentication = Invoke-DCMsGraphQuery @Parameters
# Output the number of users found.
Write-Verbose -Verbose -Message "Found $($AllUsersWithPhoneAuthentication.Count) users!"
# Loop through all those users.
$ProgressCounter = 0
foreach ($User in $AllUsersWithPhoneAuthentication) {
# Show progress bar.
$ProgressCounter += 1
[int]$PercentComplete = ($ProgressCounter / $AllUsersWithPhoneAuthentication.Count) * 100
Write-Progress -PercentComplete $PercentComplete -Activity "Processing user $ProgressCounter of $($AllUsersWithPhoneAuthentication.Count)" -Status "$PercentComplete% Complete"
# Retrieve a list of registered phone authentication methods for the user. This will return up to three objects, as a user can have up to three phones usable for authentication.
Write-Verbose -Verbose -Message "Fetching phone methods for $($User.userPrincipalName)..."
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'GET'
GraphUri = "https://graph.microsoft.com/beta/users/$($User.userPrincipalName)/authentication/phoneMethods"
}
$phoneMethods = Invoke-DCMsGraphQuery @Parameters
<#
The value of id corresponding to the phoneType to delete is one of the following:
b6332ec1-7057-4abe-9331-3d72feddfe41 to delete the alternateMobile phoneType.
e37fc753-ff3b-4958-9484-eaa9425c82bc to delete the office phoneType.
3179e48a-750b-4051-897c-87b9720928f7 to delete the mobile phoneType.
#>
# Loop through all user phone methods.
foreach ($phoneMethod in $phoneMethods) {
# Delete the phone method.
try {
if ($phoneMethod.phoneType) {
Write-Verbose -Verbose -Message "Deleting phone method '$($phoneMethod.phoneType)' for $($User.userPrincipalName)..."
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'DELETE'
GraphUri = "https://graph.microsoft.com/beta/users/$($User.userPrincipalName)/authentication/phoneMethods/$($phoneMethod.id)"
}
Invoke-DCMsGraphQuery @Parameters | Out-Null
}
}
catch {
Write-Warning -Message "Could not delete phone method '$($phoneMethod.phoneType)' for $($User.userPrincipalName)! Is it the users default authentication method?"
}
}
}
break
# BONUS SCRIPT: LIST ALL GUEST USERS WITH SMS AS A REGISTERED AUTHENTICATION METHOD.
# First, create app registration and grant it:
# User.Read.All
# UserAuthenticationMethod.Read.All
# Reports.Read.All
# Connect to Microsoft Graph with delegated permissions.
Write-Verbose -Verbose -Message 'Connecting to Microsoft Graph...'
$Parameters = @{
ClientID = ''
ClientSecret = ''
}
$AccessToken = Connect-DCMsGraphAsDelegated @Parameters
# Fetch user authentication methods.
Write-Verbose -Verbose -Message 'Fetching all users with any phone authentication methods registered...'
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'GET'
GraphUri = "https://graph.microsoft.com/beta/reports/credentialUserRegistrationDetails?`$filter=authMethods/any(t:t eq microsoft.graph.registrationAuthMethod'mobilePhone') or authMethods/any(t:t eq microsoft.graph.registrationAuthMethod'officePhone')"
}
$AllUsersWithPhoneAuthentication = Invoke-DCMsGraphQuery @Parameters
# Fetch all guest users.
Write-Verbose -Verbose -Message 'Fetching all guest users...'
$Parameters = @{
AccessToken = $AccessToken
GraphMethod = 'GET'
GraphUri = "https://graph.microsoft.com/beta/users?`$filter=userType eq 'Guest'"
}
$AllGuestUsers = Invoke-DCMsGraphQuery @Parameters
# Check how many users who have an authentication phone number registered.
foreach ($Guest in $AllGuestUsers) {
if ($AllUsersWithPhoneAuthentication.userPrincipalName.Contains($Guest.UserPrincipalName)) {
Write-Output "$($Guest.displayName) ($($Guest.mail))"
}
}
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
6 {
$Snippet = @'
<#
.SYNOPSIS
A simple script template.
.DESCRIPTION
Write a description of what the script does and how to use it.
.PARAMETER Parameter1
Inputs a string into the script.
.PARAMETER Parameter2
Inputs an integer into the script.
.PARAMETER Parameter3
Sets a script switch.
.INPUTS
None
.OUTPUTS
System.String
.NOTES
Version: 1.0
Author: Daniel Chronlund
Creation Date: 2021-01-01
.EXAMPLE
Script-Template -Parameter "Text" -Verbose
.EXAMPLE
Script-Template -Parameter "Text" -Verbose
#>
# ----- [Initialisations] -----
# Script parameters.
param (
[parameter(Mandatory = $true)]
[string]$Parameter1 = "Text",
[parameter(Mandatory = $true)]
[int32]$Parameter2 = 1,
[parameter(Mandatory = $false)]
[switch]$Parameter3
)
# Set Error Action - Possible choices: Stop, SilentlyContinue
$ErrorActionPreference = "Stop"
# ----- [Declarations] -----
# Variable 1 description.
$Variable1 = ""
# Variable 2 description.
$Variable2 = ""
# ----- [Functions] -----
function function1
{
<#
.SYNOPSIS
A brief description of the function1 function.
.DESCRIPTION
A detailed description of the function1 function.
.PARAMETER Parameter1
A description of the Parameter1 parameter.
.EXAMPLE
function1 -Parameter1 'Value1'
#>
param (
[parameter(Mandatory = $true)]
[string]$Parameter1
)
$Output = $Parameter1
$Output
}
# ----- [Execution] -----
# Do the following.
function1 -Parameter1 'Test'
# ----- [End] -----
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
7 {
$Snippet = @'
# README: This script is an example of what you might want to/need to do if your Azure AD has been breached. This script was created in the spirit of the zero trust assume breach methodology. The idea is that if you detect that attackers are already on the inside, then you must try to kick them out. This requires multiple steps and you also must handle other resources like your on-prem AD. However, this script example helps you in the right direction when it comes to Azure AD admin roles.
# More info on my blog: https://danielchronlund.com/2021/03/29/my-azure-ad-has-been-breached-what-now/
break
# *** Connect to Azure AD ***
Import-Module AzureADPreview
Connect-AzureAD
# *** Interesting Azure AD roles to inspect ***
$InterestingDirectoryRoles = 'Global Administrator',
'Global Reader',
'Privileged Role Administrator',
'Security Administrator',
'Application Administrator',
'Compliance Administrator'
# *** Inspect current Azure AD admins (if you use Azure AD PIM) ***
# Fetch tenant ID.
$TenantID = (Get-AzureADTenantDetail).ObjectId
# Fetch all Azure AD role definitions.
$AzureADRoleDefinitions = Get-AzureADMSPrivilegedRoleDefinition -ProviderId "aadRoles" -ResourceId $TenantID | Where-Object { $_.DisplayName -in $InterestingDirectoryRoles }
# Fetch all Azure AD PIM role assignments.
$AzureADDirectoryRoleAssignments = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId $TenantID | Where-Object { $_.RoleDefinitionId -in $AzureADRoleDefinitions.Id }
# Fetch Azure AD role members for each role and format as custom object.
$AzureADDirectoryRoleMembers = foreach ($AzureADDirectoryRoleAssignment in $AzureADDirectoryRoleAssignments) {
$UserAccountDetails = Get-AzureAdUser -ObjectId $AzureADDirectoryRoleAssignment.SubjectId
$LastLogon = (Get-AzureAdAuditSigninLogs -top 1 -filter "UserId eq '$($AzureADDirectoryRoleAssignment.SubjectId)'" | Select-Object CreatedDateTime).CreatedDateTime
if ($LastLogon) {
$LastLogon = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date $LastLogon), (Get-TimeZone).Id)
}
$CustomObject = New-Object -TypeName psobject
$CustomObject | Add-Member -MemberType NoteProperty -Name "AzureADDirectoryRole" -Value ($AzureADRoleDefinitions | Where-Object { $_.Id -eq $AzureADDirectoryRoleAssignment.RoleDefinitionId }).DisplayName
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserID" -Value $UserAccountDetails.ObjectID
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserAccount" -Value $UserAccountDetails.DisplayName
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserPrincipalName" -Value $UserAccountDetails.UserPrincipalName
$CustomObject | Add-Member -MemberType NoteProperty -Name "AssignmentState" -Value $AzureADDirectoryRoleAssignment.AssignmentState
$CustomObject | Add-Member -MemberType NoteProperty -Name "AccountCreated" -Value $UserAccountDetails.ExtensionProperty.createdDateTime
$CustomObject | Add-Member -MemberType NoteProperty -Name "LastLogon" -Value $LastLogon
$CustomObject
}
# List all Azure AD role members (newest first).
$AzureADDirectoryRoleMembers | Sort-Object AccountCreated -Descending | Format-Table
# *** Inspect current Azure AD admins (only if you do NOT use Azure AD PIM) ***
# Interesting Azure AD roles to inspect.
$InterestingDirectoryRoles = 'Global Administrator',
'Global Reader',
'Privileged Role Administrator',
'Security Administrator',
'Application Administrator',
'Compliance Administrator'
# Fetch Azure AD role details.
$AzureADDirectoryRoles = Get-AzureADDirectoryRole | Where-Object { $_.DisplayName -in $InterestingDirectoryRoles }
# Fetch Azure AD role members for each role and format as custom object.
$AzureADDirectoryRoleMembers = foreach ($AzureADDirectoryRole in $AzureADDirectoryRoles) {
$RoleAssignments = Get-AzureADDirectoryRoleMember -ObjectId $AzureADDirectoryRole.ObjectId
foreach ($RoleAssignment in $RoleAssignments) {
$LastLogon = (Get-AzureAdAuditSigninLogs -top 1 -filter "UserId eq '$($RoleAssignment.ObjectId)'" | Select-Object CreatedDateTime).CreatedDateTime
if ($LastLogon) {
$LastLogon = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date $LastLogon), (Get-TimeZone).Id)
}
$CustomObject = New-Object -TypeName psobject
$CustomObject | Add-Member -MemberType NoteProperty -Name "AzureADDirectoryRole" -Value $AzureADDirectoryRole.DisplayName
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserID" -Value $RoleAssignment.ObjectID
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserAccount" -Value $RoleAssignment.DisplayName
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserPrincipalName" -Value $RoleAssignment.UserPrincipalName
$CustomObject | Add-Member -MemberType NoteProperty -Name "AccountCreated" -Value $RoleAssignment.ExtensionProperty.createdDateTime
$CustomObject | Add-Member -MemberType NoteProperty -Name "LastLogon" -Value $LastLogon
$CustomObject
}
}
# List all Azure AD role members (newest first).
$AzureADDirectoryRoleMembers | Sort-Object AccountCreated -Descending | Format-Table
# *** Check if admin accounts are synced from on-prem (bad security) ***
# Loop through the admins from previous output and fetch sync status.
$SyncedAdmins = foreach ($AzureADDirectoryRoleMember in $AzureADDirectoryRoleMembers) {
$IsSynced = (Get-AzureADUser -ObjectId $AzureADDirectoryRoleMember.UserID | Where-Object {$_.DirSyncEnabled -eq $true}).DirSyncEnabled
$CustomObject = New-Object -TypeName psobject
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserID" -Value $AzureADDirectoryRoleMember.UserID
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserAccount" -Value $AzureADDirectoryRoleMember.UserAccount
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserPrincipalName" -Value $AzureADDirectoryRoleMember.UserPrincipalName
if ($IsSynced) {
$CustomObject | Add-Member -MemberType NoteProperty -Name "SyncedOnPremAccount" -Value 'True'
} else {
$CustomObject | Add-Member -MemberType NoteProperty -Name "SyncedOnPremAccount" -Value 'False'
}
$CustomObject
}
# List admins (synced on-prem accounts first).
$SyncedAdmins | Sort-Object UserPrincipalName -Descending -Unique | Sort-Object SyncedOnPremAccount -Descending | Format-Table
# *** ON-PREM SYNC PANIC BUTTON: Block all Azure AD admin accounts that are synced from on-prem ***
# WARNING: Make sure you understand what you're doing before running this script!
# Loop through admins synced from on-prem and block sign-ins.
foreach ($SyncedAdmin in ($SyncedAdmins | Where-Object { $_.SyncedOnPremAccount -eq 'True' })) {
Set-AzureADUser -ObjectID $SyncedAdmin.UserID -AccountEnabled $false
}
# Check account status.
foreach ($SyncedAdmin in ($SyncedAdmins | Where-Object { $_.SyncedOnPremAccount -eq 'True' })) {
Get-AzureADUser -ObjectID $SyncedAdmin.UserID | Select-Object userPrincipalName, AccountEnabled
}
# *** Check admins last password set time ***
# Connect to Microsoft online services.
Connect-MsolService
# Loop through the admins from previous output and fetch LastPasswordChangeTimeStamp.
$AdminPasswordChanges = foreach ($AzureADDirectoryRoleMember in ($AzureADDirectoryRoleMembers| Sort-Object UserID -Unique)) {
$LastPasswordChangeTimeStamp = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date (Get-MsolUser -ObjectId $AzureADDirectoryRoleMember.UserID | Select-Object LastPasswordChangeTimeStamp).LastPasswordChangeTimeStamp), (Get-TimeZone).Id)
$CustomObject = New-Object -TypeName psobject
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserID" -Value $AzureADDirectoryRoleMember.UserID
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserAccount" -Value $AzureADDirectoryRoleMember.UserAccount
$CustomObject | Add-Member -MemberType NoteProperty -Name "UserPrincipalName" -Value $AzureADDirectoryRoleMember.UserPrincipalName
$CustomObject | Add-Member -MemberType NoteProperty -Name "LastPasswordChangeTimeStamp" -Value $LastPasswordChangeTimeStamp
$CustomObject
}
# List admins (newest passwords first).
$AdminPasswordChanges | Sort-Object LastPasswordChangeTimeStamp -Descending | Format-Table
# *** ADMIN PASSWORD PANIC BUTTON: Reset passwords for all Azure AD admins (except for current user and break glass accounts) ***
# WARNING: Make sure you understand what you're doing before running this script!
# IMPORTANT: Define your break glass accounts.
$BreakGlassAccounts = '[email protected]', '[email protected]'
# The current user running PowerShell against Azure AD.
$CurrentUser = (Get-AzureADCurrentSessionInfo).Account.Id
# Loop through admins and set new complex passwords (using generated GUIDs).
foreach ($AzureADDirectoryRoleMember in ($AzureADDirectoryRoleMembers | Sort-Object UserPrincipalName -Unique)) {
if ($AzureADDirectoryRoleMember.UserPrincipalName -notin $BreakGlassAccounts -and $AzureADDirectoryRoleMember.UserPrincipalName -ne $CurrentUser) {
Write-Verbose -Verbose -Message "Setting new password for $($AzureADDirectoryRoleMember.UserPrincipalName)..."
Set-AzureADUserPassword -ObjectId $AzureADDirectoryRoleMember.UserID -Password (ConvertTo-SecureString (New-Guid).Guid -AsPlainText -Force)
} else {
Write-Verbose -Verbose -Message "Skipping $($AzureADDirectoryRoleMember.UserPrincipalName)!"
}
}
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
100 {
$Snippet = @'
X
'@
Set-Clipboard $Snippet
Write-Host -ForegroundColor "Yellow" ""
Write-Host -ForegroundColor "Yellow" "Example copied to clipboard!"
Write-Host -ForegroundColor "Yellow" ""
}
0 {
break
} default {
break
}
}
}
# Create example menu.
$Choice = CreateMenu -MenuTitle "Copy DCToolbox example to clipboard" -MenuChoices "Microsoft Graph with PowerShell examples", "Manage Conditional Access as code", "Activate an Azure AD Privileged Identity Management (PIM) role", "Manage stale Azure AD accounts", "Azure MFA SMS and voice call methods cleanup script", "General PowerShell script template", "Azure AD Security Breach Kick-Out Process"
# Handle menu choice.
HandleMenuChoice -MenuChoice $Choice
}
function New-DCM365AssetInventoryReport {
<#
.SYNOPSIS
Gather basic asset information from a Microsoft 365 tenant and crates an Excel report.
.DESCRIPTION
This CMDlet uses Microsoft Graph to gather asset information (users, devices, applications, etc) The purpose of this tool is to quickly inventory tenant assets and document it in Excel.
.INPUTS
None
.OUTPUTS
An Excel report.
.NOTES
Author: Daniel Chronlund
GitHub: https://github.com/DanielChronlund/DCToolbox
Blog: https://danielchronlund.com/
.EXAMPLE
New-DCM365AssetInventoryReport
#>
# Check if the Azure AD Preview module is installed.
if (Get-Module -ListAvailable -Name "Microsoft.Graph") {
# Do nothing.
}
else {
Write-Error -Exception "The Microsoft.Graph PowerShell module is not installed. Please, run 'Install-Module -Name Microsoft.Graph -Force' as an admin and try again." -ErrorAction Stop
}
# Check if the Excel module is installed.
if (Get-Module -ListAvailable -Name "ImportExcel") {
# Do nothing.
}
else {
Write-Error -Exception "The Excel PowerShell module is not installed. Please, run 'Install-Module ImportExcel -Force' as an admin and try again." -ErrorAction Stop
}
# Connect to Microsoft Graph.
Connect-MgGraph -Scopes 'Directory.Read.All', 'User.Read.All'
# Function to add a report row.
function Add-ReportRow {
param (
$Type,
$Name,
$ObjectId,
$Details
)
$CustomObject = New-Object -TypeName psobject
$CustomObject | Add-Member -MemberType NoteProperty -Name "Type" -Value $Type
$CustomObject | Add-Member -MemberType NoteProperty -Name "Name" -Value $Name
$CustomObject | Add-Member -MemberType NoteProperty -Name "ObjectId" -Value $ObjectId
$CustomObject | Add-Member -MemberType NoteProperty -Name "Details" -Value $Details
$CustomObject
}
# Gather tenant data.
Write-Verbose -Verbose -Message "Gathering tenant data..."
$Users = Get-MgUser
$Devices = Get-MgDevice
$ScriptBlock = {
foreach ($User in ($Users | where UserType -eq '')) {
Add-ReportRow -Type 'UserAccount' -Name $User.UserPrincipalName -ObjectId $User.Id -Details "Test"
}
}
$Result = Invoke-Command $ScriptBlock
# Export the result to Excel.
Write-Verbose -Verbose -Message "Exporting report to Excel..."
$Path = "$((Get-Location).Path)\M365 Asset Inventory Report $(Get-Date -Format 'yyyy-MM-dd').xlsx"
$Result | Export-Excel -Path $Path -WorksheetName "M365 Asset Inventory" -BoldTopRow -FreezeTopRow -AutoFilter -AutoSize -ClearSheet -NoNumberConversion * -Show
Write-Verbose -Verbose -Message "Saved $Path"
Write-Verbose -Verbose -Message "Done!"
}
function Connect-DCMsGraphAsDelegated {
<#
.SYNOPSIS
Connect to Microsoft Graph with delegated credentials (interactive login will popup).
.DESCRIPTION
This CMDlet will prompt you to sign in to Azure AD. If successfull an access token is returned that can be used with other Graph CMDlets. Make sure you store the access token in a variable according to the example.
Before running this CMDlet, you first need to register a new application in your Azure AD according to this article:
https://danielchronlund.com/2018/11/19/fetch-data-from-microsoft-graph-with-powershell-paging-support/
.PARAMETER ClientID
Client ID for your Azure AD application with Conditional Access Graph permissions.
.PARAMETER ClientSecret
Client secret for the Azure AD application with Conditional Access Graph permissions.
.INPUTS
None
.OUTPUTS
None
.NOTES
Author: Daniel Chronlund
GitHub: https://github.com/DanielChronlund/DCToolbox
Blog: https://danielchronlund.com/
.EXAMPLE
$AccessToken = Connect-DCMsGraphAsDelegated -ClientID '8a85d2cf-17c7-4ecd-a4ef-05b9a81a9bba' -ClientSecret 'j[BQNSi29Wj4od92ritl_DHJvl1sG.Y/'
#>
param (
[parameter(Mandatory = $true)]
[string]$ClientID,
[parameter(Mandatory = $true)]
[string]$ClientSecret
)
# Declarations.
$Resource = "https://graph.microsoft.com"
$RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"
# Force TLS 1.2.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# UrlEncode the ClientID and ClientSecret and URL's for special characters.
Add-Type -AssemblyName System.Web
$ClientSecretEncoded = [System.Web.HttpUtility]::UrlEncode($ClientSecret)
$ResourceEncoded = [System.Web.HttpUtility]::UrlEncode($Resource)
$RedirectUriEncoded = [System.Web.HttpUtility]::UrlEncode($RedirectUri)