-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path25-Lockdown-Account.ps1
More file actions
336 lines (305 loc) · 16.2 KB
/
Copy path25-Lockdown-Account.ps1
File metadata and controls
336 lines (305 loc) · 16.2 KB
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
# Bitpusher
# \`._,'/
# (_- -_)
# \o/
# The Digital
# Fox
# @VinceVulpes
# https://theTechRelay.com
# https://github.com/bitpusher2k
#
# Lockdown-Account.ps1 - By Bitpusher/The Digital Fox
# v5.0.0 - DEF CON edition - last updated 2026-08-05
# Script to lock down M365 accounts that are suspected of being compromised.
#
# Usage:
# powershell -executionpolicy bypass -f .\Lockdown-Account.ps1 -OutputPath "Default" -UserIds "compromisedaccount@contoso.com"
#
# Run with already existing connection to M365 tenant through
# PowerShell modules.
#
# Uses (ExchangePowerShell), Microsoft Graph commands.
# Minimally required tenant role(s): "User Administrator" + may need "Privileged Auth Admin" to operate on admin accounts
#
# If not connected:
# Connect-MgGraph -Scopes "User.ReadWrite.All", "Directory.AccessAsUser.All", "UserAuthenticationMethod.Read.All", "AuditLog.Read.All"
#
#comp #m365 #security #bec #script #irscript #powershell
#Requires -Version 5.1
#Requires -Modules Microsoft.Graph.Users, Microsoft.Graph.Users.Actions, Microsoft.Graph.Identity.DirectoryManagement
[CmdletBinding(SupportsShouldProcess)]
Param (
[string]$OutputPath = "Default",
[string]$UserIds,
[int]$DaysAgo,
[datetime]$StartDate,
[datetime]$EndDate,
[string]$scriptName = "Lockdown-Account",
[string]$ScriptVersion = "v5.0.0 - DEF CON edition - last updated 2026-08-05",
[string]$Priority = "Normal",
[string]$DebugPreference = "SilentlyContinue",
[string]$VerbosePreference = "SilentlyContinue",
[string]$InformationPreference = "Continue",
[string]$logFileFolderPath = "C:\temp\log",
[string]$ComputerName = $env:computername,
[string]$ScriptUserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name,
[string]$logFilePrefix = "$scriptName" + "_" + "$ComputerName" + "_",
[string]$logFileDateFormat = "yyyyMMdd_HHmmss",
[int]$logFileRetentionDays = 30,
[string]$Encoding = "utf8NoBOM", # PS 5 & 7: "Ascii" (7-bit), "BigEndianUnicode" (UTF-16 big-endian), "BigEndianUTF32", "Oem", "Unicode" (UTF-16 little-endian), "UTF32" (little-endian), "UTF7", "UTF8" (PS 5: BOM, PS 7: NO BOM). PS 7: "ansi", "utf8BOM", "utf8NoBOM",
[switch]$ReadOnly,
[switch]$NoExplorer
)
#region initialization
if ($PSVersionTable.PSVersion.Major -eq 5 -and ($Encoding -eq "utf8bom" -or $Encoding -eq "utf8nobom")) { $Encoding = "utf8" }
function Get-TimeStamp {
param(
[switch]$NoWrap,
[switch]$Utc
)
$dt = Get-Date
if ($Utc -eq $true) {
$dt = $dt.ToUniversalTime()
}
$str = "{0:yyyy-MM-dd} {0:HH:mm:ss}" -f $dt
if ($NoWrap -ne $true) {
$str = "[$str]"
}
return $str
}
if ($logFileFolderPath -ne "") {
if (!(Test-Path -PathType Container -Path $logFileFolderPath)) {
Write-Output "$(Get-TimeStamp) Creating directory $logFileFolderPath" | Out-Null
New-Item -ItemType Directory -Force -Path $logFileFolderPath | Out-Null
} else {
$DatetoDelete = $(Get-Date).AddDays(- $logFileRetentionDays)
Get-ChildItem $logFileFolderPath | Where-Object { $_.Name -like "*$logFilePrefix*" -and $_.LastWriteTime -lt $DatetoDelete } | Remove-Item | Out-Null
}
$logFilePath = $logFileFolderPath + "\$logFilePrefix" + (Get-Date -Format $logFileDateFormat) + ".LOG"
}
function Assert-M365Connection {
<#
.SYNOPSIS
Checks for active Exchange Online and/or MS Graph connections and attempts to connect if missing.
Scoped to the minimum permissions required by this script.
#>
param(
[switch]$RequireEXO,
[switch]$RequireGraph,
[switch]$RequireIPPS,
[string[]]$GraphScopes
)
if ($RequireEXO) {
$exoConnected = $false
try { $exoConnected = [bool](Get-ConnectionInformation -ErrorAction SilentlyContinue) } catch {}
if (-not $exoConnected) {
Write-Output "Exchange Online not connected. Attempting connection..."
try {
Connect-ExchangeOnline -ShowBanner:$false
Write-Output "Exchange Online connected."
} catch {
Write-Error "Failed to connect to Exchange Online: $_"
exit 1
}
} else {
Write-Output "Exchange Online connection verified."
}
}
if ($RequireIPPS) {
$ippsConnected = $false
try { $ippsConnected = [bool](Get-ConnectionInformation -ErrorAction SilentlyContinue | Where-Object { $_.ConnectionUri -match "compliance" }) } catch {}
if (-not $ippsConnected) {
Write-Output "Security & Compliance (IPPS) not connected. Attempting connection..."
try {
Connect-IPPSSession -ShowBanner:$false
Write-Output "IPPS connected."
} catch {
Write-Error "Failed to connect to IPPS: $_"
exit 1
}
} else {
Write-Output "IPPS connection verified."
}
}
if ($RequireGraph) {
$graphContext = $null
try { $graphContext = Get-MgContext -ErrorAction SilentlyContinue } catch {}
if (-not $graphContext) {
Write-Output "MS Graph not connected. Attempting connection with scopes: $($GraphScopes -join ', ')..."
try {
Connect-MgGraph -Scopes $GraphScopes -NoWelcome
Write-Output "MS Graph connected."
} catch {
Write-Error "Failed to connect to MS Graph: $_"
exit 1
}
} else {
# Verify required scopes are present
$currentScopes = $graphContext.Scopes
$missingScopes = $GraphScopes | Where-Object { $_ -notin $currentScopes }
if ($missingScopes) {
Write-Output "MS Graph connected but missing scopes: $($missingScopes -join ', '). Reconnecting..."
try {
Connect-MgGraph -Scopes $GraphScopes -NoWelcome
Write-Output "MS Graph reconnected with required scopes."
} catch {
Write-Warning "Could not reconnect with required scopes. Some operations may fail."
}
} else {
Write-Output "MS Graph connection verified with required scopes."
}
}
}
}
$sw = [Diagnostics.StopWatch]::StartNew()
$RunStart = Get-Date
$ReadScopes = @("Domain.Read.All", "User.Read.All")
$WriteScopes = @("User.ReadWrite.All")
if ($ReadOnly) {
Write-Output "-ReadOnly specified: requesting read-only Graph scopes; account lockdown will be reported as a dry-run only (no changes)." | Tee-Object -FilePath $logFilePath -Append
Assert-M365Connection -RequireGraph -GraphScopes $ReadScopes
} else {
Assert-M365Connection -RequireGraph -GraphScopes ($ReadScopes + $WriteScopes)
}
$WriteCapable = (-not $ReadOnly) -and ((Get-MgContext).Scopes -contains "User.ReadWrite.All")
if (-not $WriteCapable) {
Write-Output "DRY-RUN MODE: write scope 'User.ReadWrite.All' not granted$(if ($ReadOnly) { ' (-ReadOnly specified)' } else { '' }). Accounts will NOT be disabled/reset/revoked; intended actions are logged only." | Tee-Object -FilePath $logFilePath -Append
}
Write-Output "$scriptName started on $ComputerName by $ScriptUserName at $(Get-TimeStamp)" | Tee-Object -FilePath $logFilePath -Append
$process = Get-Process -Id $pid
Write-Output "Setting process priority to `"$Priority`"" | Tee-Object -FilePath $logFilePath -Append
$process.PriorityClass = $Priority
#endregion initialization
$date = Get-Date -Format "yyyyMMddHHmmss"
## If OutputPath variable is not defined, prompt for it
if (!$OutputPath) {
Write-Output ""
$OutputPath = Read-Host "Enter the output base path, e.g. $($env:userprofile)\Desktop\Investigation (default)" | Tee-Object -FilePath $logFilePath -Append
If ($OutputPath -eq '') { $OutputPath = "$($env:userprofile)\Desktop\Investigation" }
Write-Output "Output base path will be in $OutputPath" | Tee-Object -FilePath $logFilePath -Append
} elseif ($OutputPath -eq 'Default') {
Write-Output ""
$OutputPath = "$($env:userprofile)\Desktop\Investigation"
Write-Output "Output base path will be in $OutputPath" | Tee-Object -FilePath $logFilePath -Append
}
## If OutputPath does not exist, create it
$CheckOutputPath = Get-Item $OutputPath -ErrorAction SilentlyContinue
if (!$CheckOutputPath) {
Write-Output ""
Write-Output "Output path does not exist. Directory will be created." | Tee-Object -FilePath $logFilePath -Append
mkdir $OutputPath
}
## Get Primary Domain Name for output subfolder
# $PrimaryDomain = Get-AcceptedDomain | Where-Object Default -eq $true
# $DomainName = $PrimaryDomain.DomainName
$PrimaryDomain = Get-MgDomain | Where-Object { $_.isdefault -eq $True } | Select-Object -Property ID
if ($PrimaryDomain) {
$DomainName = $PrimaryDomain.ID
} else {
$DomainName = "DefaultOutput"
}
$CheckSubDir = Get-Item $OutputPath\$DomainName -ErrorAction SilentlyContinue
if (!$CheckSubDir) {
Write-Output ""
Write-Output "Domain sub-directory does not exist. Sub-directory `"$DomainName`" will be created." | Tee-Object -FilePath $logFilePath -Append
mkdir $OutputPath\$DomainName
}
Write-Output "Domain sub-directory will be `"$DomainName`"" | Tee-Object -FilePath $logFilePath -Append
$OutputCSV = "$OutputPath\$DomainName\AccountsBlocked_$($date).csv"
## If UserIds variable is not defined, prompt for it
if (!$UserIds) {
Write-Output ""
$UserIds = Read-Host 'Enter the user ID(s) (email address/UPN or object ID) of accounts to lock down (revoke sessions, set random password, block sign-in), comma separated'
}
Write-Output "Attempting to block access and revoke sessions for $UserIds..."
foreach ($User in ($UserIds -split ",")) {
$User = $User.Trim()
if ($WriteCapable -and $PSCmdlet.ShouldProcess($User, "Disable sign-in (AccountEnabled=false)")) { Update-MgUser -UserId $User -AccountEnabled:$False } elseif (-not $WriteCapable) { Write-Output "DRY-RUN: would disable sign-in (AccountEnabled=false) for $User" | Tee-Object -FilePath $logFilePath -Append }
$NewPassword = @{}
$RandomString = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count 20 | ForEach-Object {[char]$_})
$NewPassword["Password"] = $RandomString
# $NewPassword["ForceChangePasswordNextSignIn"] = $True # Not helpful if they need PW reset through AD
if ($WriteCapable -and $PSCmdlet.ShouldProcess($User, "Reset password to a random value")) { Update-MgUser -UserId $User -PasswordProfile $NewPassword } elseif (-not $WriteCapable) { Write-Output "DRY-RUN: would reset password to a random value for $User" | Tee-Object -FilePath $logFilePath -Append }
# $InvalidateStatus = Invoke-MgInvalidateUserRefreshToken -UserId $User # Deprecated
if ($WriteCapable -and $PSCmdlet.ShouldProcess($User, "Revoke all sign-in sessions")) { $RevokeStatus = Revoke-MgUserSignInSession -UserId $User } elseif (-not $WriteCapable) { Write-Output "DRY-RUN: would revoke all sign-in sessions for $User" | Tee-Object -FilePath $logFilePath -Append; $RevokeStatus = $null }
If ($RevokeStatus.Value -eq $true) {
Write-Host ("Access revoked for user {0}" -f $User.DisplayName)
}
# Disable user's registered devices - more useful for termination than compromise
# [array]$UserDevices = Get-MgUserRegisteredDevice -UserId $User.Id
# If ($UserDevices) {
# ForEach ($Device in $UserDevices) {
# Update-MgDevice -DeviceId $Device.Id -AccountEnabled $False}
# Write-Output "Disabled $Device.Id"
# }
$UserStatus = Get-MgUser -UserID $User -Property GivenName, Surname, DisplayName, userPrincipalName, SignInSessionsValidFromDateTime, OnPremisesSyncEnabled, AccountEnabled, createdDateTime | Select-Object GivenName, Surname, DisplayName, userPrincipalName, SignInSessionsValidFromDateTime, OnPremisesSyncEnabled, AccountEnabled, createdDateTime
$UserStatus
if ($UserStatus) {
$UserStatus | Export-Csv -Path $OutputCSV -NoTypeInformation -Append -Encoding $Encoding
} else {
Write-Output "`$UserStatus is empty - skipping AccountsBlocked output" | Tee-Object -FilePath $logFilePath -Append
}
}
Write-Output "Account(s) blocked & passwords reset. Note that if AD sync is configured it may revert the password and re-enable the account."
Write-Output "If this happens you must disable account/reset password from AD."
Write-Output "Manually reset account password with: $NewPassword[`"Password`"] = 'XXXXXXXX'; Update-MgUser -UserId XXXXXXXX -PasswordProfile $NewPassword"
Write-Output "Manually re-enable the account with: Update-MgUser -UserId XXXXXXX -AccountEnabled:$True"
Write-Output "Or from M365 Admin Console > Users > Active Users"
if ((Test-Path -Path $OutputCSV) -eq "True") {
Write-Output `n" The Output file is available at:" | Tee-Object -FilePath $logFilePath -Append
Write-Output $OutputCSV | Tee-Object -FilePath $logFilePath -Append
# $Prompt = New-Object -ComObject wscript.shell
# $UserInput = $Prompt.popup("Do you want to open output file?", 0, "Open Output File", 4)
# if ($UserInput -eq 6) {
# Invoke-Item "$OutputCSV"
# }
}
Write-Output "Script complete." | Tee-Object -FilePath $logFilePath -Append
Write-Output "Seconds elapsed for script execution: $($sw.elapsed.totalseconds)" | Tee-Object -FilePath $logFilePath -Append
Write-Output "`nDone! Check output path for results." | Tee-Object -FilePath $logFilePath -Append
## ---- Run manifest & case-local log copy ----
try {
$RunStopUtc = (Get-Date).ToUniversalTime()
$ManifestGraphCtx = $null
try { $ManifestGraphCtx = Get-MgContext -ErrorAction SilentlyContinue } catch {}
$ManifestTenant = if ($ManifestGraphCtx -and $ManifestGraphCtx.TenantId) { $ManifestGraphCtx.TenantId } elseif ($DomainName) { $DomainName } else { "(unknown)" }
$ManifestScopes = if ($ManifestGraphCtx -and $ManifestGraphCtx.Scopes) { ($ManifestGraphCtx.Scopes -join ", ") } else { "(no Microsoft Graph session)" }
$CaseFolder = if ($OutputPath -and $DomainName) { Join-Path $OutputPath $DomainName } else { $null }
$Manifest = New-Object System.Collections.Generic.List[string]
$Manifest.Add("")
$Manifest.Add("==================== RUN MANIFEST ====================")
$Manifest.Add("Script : $scriptName $ScriptVersion")
$Manifest.Add("Operator : $ScriptUserName")
$Manifest.Add("Computer : $ComputerName")
$Manifest.Add("Tenant : $ManifestTenant")
$Manifest.Add("Graph scopes : $ManifestScopes")
$Manifest.Add("UTC start : $($RunStart.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"))Z")
$Manifest.Add("UTC stop : $($RunStopUtc.ToString("yyyy-MM-dd HH:mm:ss"))Z")
$Manifest.Add("Elapsed seconds : $([math]::Round($sw.Elapsed.TotalSeconds, 2))")
$Manifest.Add("Output files (SHA256):")
if ($CaseFolder -and (Test-Path $CaseFolder)) {
$ProducedFiles = Get-ChildItem -Path $CaseFolder -File -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -ge $RunStart -and $_.Extension -ne ".LOG" }
if ($ProducedFiles) {
foreach ($pf in $ProducedFiles) {
$ph = try { (Get-FileHash -Path $pf.FullName -Algorithm SHA256 -ErrorAction Stop).Hash } catch { "(hash failed)" }
$Manifest.Add((" {0} {1}" -f $ph, $pf.FullName))
}
} else {
$Manifest.Add(" (no output files detected for this run)")
}
} else {
$Manifest.Add(" (no case output folder resolved)")
}
$Manifest.Add("=====================================================")
$Manifest | Tee-Object -FilePath $logFilePath -Append
if ($CaseFolder -and (Test-Path $CaseFolder) -and $logFilePath -and (Test-Path $logFilePath)) {
$CaseLogFolder = Join-Path $CaseFolder "log"
if (!(Test-Path $CaseLogFolder)) { New-Item -ItemType Directory -Force -Path $CaseLogFolder | Out-Null }
Copy-Item -Path $logFilePath -Destination (Join-Path $CaseLogFolder (Split-Path $logFilePath -Leaf)) -Force -ErrorAction SilentlyContinue
Write-Output "Run log copied to $CaseLogFolder" | Tee-Object -FilePath $logFilePath -Append
}
} catch {
Write-Warning "Run manifest / log copy step failed: $($_.Exception.Message)"
}
if (-not $NoExplorer) { Invoke-Item "$OutputPath\$DomainName" }
Exit