-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAmIHacked.ps1
More file actions
430 lines (361 loc) · 18.1 KB
/
AmIHacked.ps1
File metadata and controls
430 lines (361 loc) · 18.1 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
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
<#
.SYNOPSIS
Am I Hacked? - Comprehensive Windows Security Assessment Tool
.DESCRIPTION
Runs a battery of security checks across multiple domains including:
- Process & Service Analysis
- Network Indicators
- Account & Authentication
- File System Red Flags
- Defense Evasion Detection
Generates an HTML report with findings categorized as CRITICAL, WARNING, or INFO.
.PARAMETER OutputPath
Directory for the HTML report. Defaults to .\reports
.PARAMETER SkipModules
Array of module names to skip (e.g., 'Network','FileSystem')
.PARAMETER ConfigPath
Path to config.json for whitelists and API keys. Defaults to .\config\config.json
Copy config\config.example.json to config\config.json to customize.
.PARAMETER Offline
Disable all API calls (VirusTotal, AbuseIPDB). Rely purely on local heuristics.
.PARAMETER BaselinePath
Path to a previous baseline JSON for diff comparison.
.PARAMETER CreateBaseline
Export a baseline snapshot of the current system state. Run this on a known-clean system first.
.PARAMETER ExportJson
Emit findings as a JSON file alongside the HTML report.
.PARAMETER VerboseOutput
Enable verbose console output during scan
.PARAMETER Redact
Mask the operator's identity (computer name, username, domain, profile path) in console output,
HTML reports, and JSON exports. Useful for screenshots or sharing reports publicly.
.PARAMETER CIMode
Machine-friendly mode for CI pipelines and AI agents (Claude Code, Cursor, etc.).
Suppresses the ASCII banner and browser auto-open, auto-enables -Redact,
prints a JSON summary to stdout, and exits with a structured code (0=clean, 1=warnings, 2=critical).
.NOTES
Author: TM Hospitality Strategies / Am I Hacked Project
License: MIT
Requires: Windows 10/11, PowerShell 5.1+
Run as Administrator for full results.
#>
[CmdletBinding()]
param(
[string]$OutputPath = "",
[string[]]$SkipModules = @(),
[string]$ConfigPath = "",
[switch]$Offline,
[string]$BaselinePath,
[switch]$CreateBaseline,
[switch]$ExportJson,
[switch]$VerboseOutput,
[switch]$Redact,
[switch]$CIMode
)
# ── PSScriptRoot fallback (empty when invoked via powershell.exe -File) ────
if (-not $PSScriptRoot) {
$PSScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
}
if (-not $OutputPath) { $OutputPath = Join-Path $PSScriptRoot "reports" }
if (-not $ConfigPath) { $ConfigPath = Join-Path $PSScriptRoot "config\config.json" }
# ── Bootstrap ────────────────────────────────────────────────────────────────
$ErrorActionPreference = "Continue"
$script:StartTime = Get-Date
$script:Findings = [System.Collections.ArrayList]::new()
$script:SystemInfo = @{}
$script:Config = @{}
$script:OfflineMode = $Offline.IsPresent
$script:NonInteractive = $CIMode.IsPresent -or
-not [Environment]::UserInteractive
if ($script:NonInteractive) {
$script:RedactMode = $true
} else {
$script:RedactMode = $Redact.IsPresent
}
$script:RedactMap = @{}
$script:SuppressedCount = 0
$script:Version = "0.5.0"
# ── Helpers (loaded first) ───────────────────────────────────────────────────
. (Join-Path $PSScriptRoot "lib\Helpers.ps1")
# ── Load Config (silent — summary printed after banner) ──────────────────────
if (Test-Path $ConfigPath) {
try {
$script:Config = Get-Content $ConfigPath -Raw | ConvertFrom-Json
} catch {
Write-Warning "Failed to parse config at '$ConfigPath': $_. Using built-in defaults."
$script:Config = Get-DefaultConfig
}
} else {
$script:Config = Get-DefaultConfig
}
# ── Redact Map ───────────────────────────────────────────────────────────────
if ($script:RedactMode) {
$script:RedactMap = @{}
$rUser = $env:USERNAME
$rComp = $env:COMPUTERNAME
$rDomain = $env:USERDOMAIN
if ($rUser) { $script:RedactMap[$rUser] = "REDACTED-USER" }
if ($rComp) { $script:RedactMap[$rComp] = "REDACTED-PC" }
if ($rDomain -and $rDomain -ne $rComp) {
$script:RedactMap[$rDomain] = "REDACTED-DOMAIN"
}
}
# ── Admin Check ──────────────────────────────────────────────────────────────
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator
)
$script:IsAdmin = $isAdmin
if (-not $script:NonInteractive) {
Write-Banner
} else {
$adminTag = if ($isAdmin) { "ADMIN" } else { "LIMITED" }
Write-Host "Am I Hacked? v$($script:Version) [$adminTag] $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
}
# ── Post-Banner Status Lines ─────────────────────────────────────────────────
$companyCount = if ($script:Config.TrustedCompanies) { $script:Config.TrustedCompanies.Count } else { 0 }
$vtKey = if ($script:Config.VirusTotalAPIKey) { "VT" } else { $null }
$abKey = if ($script:Config.AbuseIPDBKey) { "AbuseIPDB" } else { $null }
$apis = @($vtKey, $abKey) | Where-Object { $_ }
$apiStr = if ($apis.Count -gt 0) { ", APIs: $($apis -join '+')" } else { ", no API keys" }
Write-Status "Config loaded ($companyCount trusted companies$apiStr)"
if ($script:OfflineMode) {
Write-Status "OFFLINE MODE: API integrations disabled." -Color Yellow
}
if ($script:NonInteractive) {
Write-Status "CI MODE: Agent-friendly output enabled (redact on, browser suppressed)." -Color Yellow
} elseif ($script:RedactMode) {
Write-Status "REDACT MODE: Sensitive identifiers will be masked." -Color Yellow
}
if (-not $isAdmin) {
Write-Status "Running without admin - some checks will be limited." -Color Yellow
Add-Finding -Severity "INFO" -Category "General" -Title "Not Running as Administrator" `
-Description "Some checks require elevated privileges for full results. Re-run as Administrator for comprehensive analysis." `
-Remediation "Right-click PowerShell > Run as Administrator, then re-run this script."
}
# ── Collect System Info ──────────────────────────────────────────────────────
Write-Status "Collecting system information..."
$os = Get-CimInstance Win32_OperatingSystem
$script:SystemInfo = @{
ComputerName = $env:COMPUTERNAME
UserName = $env:USERNAME
Domain = $env:USERDOMAIN
OSVersion = $os.Caption
OSBuild = $os.BuildNumber
LastBoot = $os.LastBootUpTime
IsAdmin = $isAdmin
ScanTime = $script:StartTime
PSVersion = $PSVersionTable.PSVersion.ToString()
}
if ($script:RedactMode) {
$script:SystemInfo.ComputerName = Invoke-Redact $script:SystemInfo.ComputerName
$script:SystemInfo.UserName = Invoke-Redact $script:SystemInfo.UserName
$script:SystemInfo.Domain = Invoke-Redact $script:SystemInfo.Domain
}
# ── Baseline Comparison ──────────────────────────────────────────────────────
$defaultBaselinePath = Join-Path (Join-Path $PSScriptRoot "reports") "baseline_latest.json"
if ('Baseline' -notin $SkipModules) {
if ($BaselinePath -and (Test-Path $BaselinePath)) {
Write-Section "Baseline Comparison"
Compare-Baseline -BaselinePath $BaselinePath
} elseif (-not $BaselinePath -and (Test-Path $defaultBaselinePath)) {
Write-Section "Baseline Comparison"
Compare-Baseline -BaselinePath $defaultBaselinePath
} elseif (-not $CreateBaseline) {
Add-Finding -Severity "INFO" -Category "General" -Title "No Baseline Found" `
-Description "No baseline snapshot exists for comparison. Run with -CreateBaseline on a known-clean system to enable change detection on future scans." `
-Remediation ".\AmIHacked.ps1 -CreateBaseline"
}
}
# ── Preflight: Signature Verification Capability ─────────────────────────────
Import-Module Microsoft.PowerShell.Security -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue 2>$null
$script:SignatureCheckAvailable = $null -ne (Get-Command Get-AuthenticodeSignature -ErrorAction SilentlyContinue)
if (-not $script:SignatureCheckAvailable) {
Add-Finding -Severity "WARNING" -Category "General" `
-Title "Signature Verification Degraded" `
-Description "The PowerShell Security module (Microsoft.PowerShell.Security) could not be loaded in this session. Authenticode signature checks will be skipped or may produce false positives. Affected checks: AMSI DLL integrity, COM hijack detection, unsigned process/file detection." `
-Remediation "Run the scan in a fresh PowerShell session. If the issue persists, run 'sfc /scannow' to repair PowerShell modules."
}
# ── Dynamic Module Discovery ─────────────────────────────────────────────────
$modulesDir = Join-Path $PSScriptRoot "modules"
$modules = @()
if (Test-Path $modulesDir) {
$modules = Get-ChildItem $modulesDir -Filter "Check-*.ps1" | ForEach-Object {
$name = $_.BaseName -replace '^Check-', ''
$description = "$name Analysis"
$content = Get-Content $_.FullName -Raw -ErrorAction SilentlyContinue
if ($content -match '(?s)<#\s*MODULE\s*\r?\n(.*?)#>') {
$metaBlock = $Matches[1]
if ($metaBlock -match 'Description:\s*(.+)') {
$description = $Matches[1].Trim()
}
}
@{ Name = $name; File = $_.Name; Description = $description; FullPath = $_.FullName }
}
}
# ── Run Modules ──────────────────────────────────────────────────────────────
$runnableModules = @($modules | Where-Object { $SkipModules -notcontains $_.Name })
$script:ModuleTotal = $runnableModules.Count + 1
$script:ModuleIndex = 0
$moduleNames = ($runnableModules | ForEach-Object { $_.Name }) -join ", "
Write-Status "Scanning $($runnableModules.Count) modules: $moduleNames"
foreach ($mod in $modules) {
if ($SkipModules -contains $mod.Name) {
Write-Status "SKIPPING: $($mod.Description)" -Color DarkGray
continue
}
$modulePath = $mod.FullPath
if (-not (Test-Path $modulePath)) {
Write-Status "MODULE NOT FOUND: $modulePath" -Color Red
continue
}
Write-Section $mod.Description
try {
. $modulePath
$functionName = "Invoke-$($mod.Name)Checks"
& $functionName
} catch {
Write-Host " [" -NoNewline -ForegroundColor DarkGray
Write-Host "X" -NoNewline -ForegroundColor Red
Write-Host "] " -NoNewline -ForegroundColor DarkGray
Write-Host "ERROR in $($mod.Name): $_" -ForegroundColor Red
Add-Finding -Severity "INFO" -Category $mod.Name -Title "Module Error" `
-Description "The $($mod.Description) module encountered an error: $_" `
-Remediation "Check that all dependencies are available and you have appropriate permissions."
}
}
# ── Generate Report ──────────────────────────────────────────────────────────
Write-SectionEnd
Write-Section "Generating Report"
. (Join-Path $PSScriptRoot "lib\ReportGenerator.ps1")
if (-not (Test-Path $OutputPath)) {
New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
}
$timestamp = $script:StartTime.ToString("yyyy-MM-dd_HHmmss")
$reportFile = Join-Path $OutputPath "AmIHacked_$timestamp.html"
$duration = (Get-Date) - $script:StartTime
Generate-HtmlReport -Findings $script:Findings `
-SystemInfo $script:SystemInfo `
-OutputFile $reportFile `
-Duration $duration `
-Version $script:Version `
-SuppressedCount $script:SuppressedCount
Write-SectionEnd
# ── JSON Export ──────────────────────────────────────────────────────────────
if ($ExportJson) {
$jsonFile = Join-Path $OutputPath "AmIHacked_$timestamp.json"
@{
Version = $script:Version
SystemInfo = $script:SystemInfo
Findings = $script:Findings
Duration = $duration.TotalSeconds
} | ConvertTo-Json -Depth 5 | Set-Content $jsonFile -Encoding UTF8
Write-Status "JSON export saved to: $jsonFile" -Color Green
}
# ── Baseline Snapshot (only when explicitly requested) ───────────────────────
if ($CreateBaseline) {
Export-Baseline -OutputPath $OutputPath
Write-Status "Baseline created. Future scans will auto-compare against it." -Color Green
}
# ── Summary ──────────────────────────────────────────────────────────────────
$critCount = @($script:Findings | Where-Object { $_.Severity -eq "CRITICAL" }).Count
$warnCount = @($script:Findings | Where-Object { $_.Severity -eq "WARNING" }).Count
$infoCount = @($script:Findings | Where-Object { $_.Severity -eq "INFO" }).Count
$totalCount = $script:Findings.Count
$verdict = "CLEAN"
$verdictColor = "Green"
if ($critCount -gt 0) {
$verdict = "COMPROMISED"
$verdictColor = "Red"
} elseif ($warnCount -gt 3) {
$verdict = "SUSPICIOUS"
$verdictColor = "Yellow"
} elseif ($warnCount -gt 0) {
$verdict = "CAUTION"
$verdictColor = "Yellow"
}
$durationStr = "$([math]::Round($duration.TotalSeconds, 1))s"
$w = 44
Write-Host ""
Write-Host ""
if ($script:NonInteractive) {
# ASCII-only box for CI/agent environments (avoids encoding issues in piped output)
$hbar = '=' * ($w + 2)
Write-Host " +$hbar+"
$verdictPad = $verdict.PadLeft([math]::Floor(($w + 2 + $verdict.Length) / 2)).PadRight($w + 2)
Write-Host " |$verdictPad|"
Write-Host " +$hbar+"
function Write-SummaryLine { param($Label, $Value, $Width)
$line = " | $Label$Value".PadRight($Width + 3) + " |"
Write-Host $line
}
Write-SummaryLine "CRITICAL " "$critCount" $w
Write-SummaryLine "WARNING " "$warnCount" $w
Write-SummaryLine "INFO " "$infoCount" $w
Write-SummaryLine "Suppressed " "$($script:SuppressedCount)" $w
Write-Host " | $(' ' * ($w - 2)) |"
Write-SummaryLine "Total " "$totalCount findings" $w
Write-SummaryLine "Duration " "$durationStr" $w
Write-Host " | $(' ' * ($w - 2)) |"
Write-SummaryLine "Report " "See path below" $w
Write-Host " +$hbar+"
} else {
Write-Host " ╔$('═' * $w)╗" -ForegroundColor DarkCyan
Write-Host " ║" -NoNewline -ForegroundColor DarkCyan
$verdictPad = $verdict.PadLeft([math]::Floor(($w + $verdict.Length) / 2)).PadRight($w)
Write-Host $verdictPad -NoNewline -ForegroundColor $verdictColor
Write-Host "║" -ForegroundColor DarkCyan
Write-Host " ╠$('═' * $w)╣" -ForegroundColor DarkCyan
function Write-SummaryLine { param($Label, $Value, $Color, $Width)
$content = "$Label$Value"
$innerWidth = $Width - 4
Write-Host " ║ " -NoNewline -ForegroundColor DarkCyan
Write-Host $Label -NoNewline -ForegroundColor DarkGray
Write-Host $Value -NoNewline -ForegroundColor $Color
$remaining = $innerWidth - $content.Length
if ($remaining -gt 0) { Write-Host (' ' * $remaining) -NoNewline }
Write-Host " ║" -ForegroundColor DarkCyan
}
Write-SummaryLine "CRITICAL " "$critCount" $(if ($critCount -gt 0) { "Red" } else { "Green" }) $w
Write-SummaryLine "WARNING " "$warnCount" $(if ($warnCount -gt 0) { "Yellow" } else { "Green" }) $w
Write-SummaryLine "INFO " "$infoCount" "DarkCyan" $w
Write-SummaryLine "Suppressed " "$($script:SuppressedCount)" "DarkGray" $w
Write-Host " ║$(' ' * $w)║" -ForegroundColor DarkCyan
Write-SummaryLine "Total " "$totalCount findings" "White" $w
Write-SummaryLine "Duration " "$durationStr" "DarkGray" $w
Write-Host " ║$(' ' * $w)║" -ForegroundColor DarkCyan
Write-SummaryLine "Report " "See path below" "DarkGray" $w
Write-Host " ╚$('═' * $w)╝" -ForegroundColor DarkCyan
}
Write-Host ""
if ($critCount -gt 0) {
Write-Host " !! CRITICAL findings detected. Review the report immediately." -ForegroundColor Red
} elseif ($warnCount -eq 0 -and $critCount -eq 0) {
Write-Host " [+] No threats detected. System appears clean." -ForegroundColor Green
}
Write-Host ""
Write-Host " $reportFile" -ForegroundColor White
Write-Host ""
# ── CI Mode: JSON summary + structured exit code ─────────────────────────────
if ($script:NonInteractive) {
$summary = @{
verdict = $verdict
critical = $critCount
warning = $warnCount
info = $infoCount
suppressed = $script:SuppressedCount
total = $totalCount
duration = [math]::Round($duration.TotalSeconds, 1)
reportPath = $reportFile
version = $script:Version
}
Write-Host "---AMIHACKED-SUMMARY-JSON---"
Write-Host ($summary | ConvertTo-Json -Compress)
if ($critCount -gt 0) { exit 2 }
elseif ($warnCount -gt 0) { exit 1 }
else { exit 0 }
}
try {
Start-Process $reportFile
} catch {
Write-Status "Could not auto-open report. Open the path above manually." -Color Yellow
}