lib/AI.ps1
|
# Optional Gemini step. The ground rules: Findings are computed locally, and the report is saved # before anything is sent. The model writes on top of them and never decides what a finding is. # Nothing leaves without consent: with no flag there is no call, and HostBadger never prompts on its # own. -SendToAI is the consent, and -AiConfirm adds a y/N question. Host names, domains, accounts, # groups, SIDs, paths, the names of services, tasks, autoruns and adapters, and addresses are # swapped for tokens first. The map never leaves this machine, and the collector's error messages # are never sent. -AiDryRun writes the exact prompt to a file and sends nothing. Every real send # leaves the prompt and the reply next to the report (<report>_ai_prompt.txt and _ai_response.json), # still pseudonymized. The API key comes from -ApiKey or $env:GEMINI_API_KEY. # Names that are the same on every Windows machine. They help the model and give nothing away. $script:AiKeepNames = @( 'Administrator', 'Guest', 'DefaultAccount', 'WDAGUtilityAccount', 'Everyone', 'Authenticated Users', 'SYSTEM', 'LocalSystem', 'LocalService', 'NetworkService', 'TrustedInstaller', 'Spooler', 'Domain Admins', 'Domain Users', 'Domain Computers', 'Domain Controllers', 'Enterprise Admins', 'Schema Admins', 'Administrators', 'Users', 'Guests', 'Power Users', 'Remote Desktop Users', 'Remote Management Users', 'Account Operators', 'Server Operators', 'Print Operators', 'Backup Operators', 'Network Configuration Operators', 'Performance Log Users', 'Performance Monitor Users', 'Distributed COM Users', 'Event Log Readers', 'Hyper-V Administrators', 'IIS_IUSRS', 'Replicator', 'Cryptographic Operators' ) # Listener and excluded processes that are stock Windows or well-known server engines. $script:AiKeepProcesses = @('svchost', 'system', 'lsass', 'services', 'wininit', 'spoolsv', 'dns', 'sqlservr', 'mysqld', 'postgres', 'redis-server', 'mongod', 'powershell', 'cmd', 'wscript', 'cscript', 'mshta', 'rundll32', 'regsvr32', 'powershell.exe', 'cmd.exe', 'wscript.exe', 'cscript.exe', 'mshta.exe', 'rundll32.exe', 'regsvr32.exe') # Stock Windows tools under System32 and SysWOW64 look the same everywhere, and the model needs to # see that a scripting host is excluded from scanning. $script:AiKeepPathPattern = '(?i)^[a-z]:\\windows\\(?:system32|syswow64)\\(?:windowspowershell\\v1\.0\\)?(?:powershell|powershell_ise|cmd|wscript|cscript|mshta|rundll32|regsvr32|svchost|msiexec|certutil|bitsadmin|wmic|schtasks|net|reg|sc)\.exe$' # Account prefixes that are not a domain. $script:AiKeepAccountPrefixes = @('NT AUTHORITY', 'NT SERVICE', 'BUILTIN', 'Window Manager', 'Font Driver Host', 'NT VIRTUAL MACHINE') $script:AiTokenPattern = '\b(?:HOSTFQDN|HOST|DOMAIN|NETBIOS|USER|GROUP|SID|PATH|UNC|SERVICE|TASK|AUTORUN|ADAPTER|PROC|SOFTWARE|IP|WMI|SSID|CERT|PLUGIN)-\d+\b' $script:AiSidPattern = 'S-1-(?:5-21|12-1|5-80|5-82|5-83)(?:-\d+)+' # Not inside a longer dotted number, and not a CIS rule number ("CIS 18.10.7.3"), because those are # not addresses. $script:AiIpPattern = '(?<!CIS (?:Server \d{4} |Windows 1[01] )?)(?<!\(version )(?<![\d.])(?!0\.0\.0\.0(?!\d)|127\.0\.0\.1(?!\d))(?:\d{1,3}\.){3}\d{1,3}(?!\d|\.\d)' # -------------------------------------------------------------------------- # Pseudonymizer # -------------------------------------------------------------------------- function New-HostPseudonymizer { # $Snapshots holds every host's snapshot and $Findings the findings that will be sent. # $HostOrder is the order in which hosts will be listed, so that HOST-1 is the first one. param($Snapshots, $Findings, [string[]]$HostOrder = @()) $pz = [PSCustomObject]@{ Candidates = New-Object 'System.Collections.Generic.Dictionary[string,string]' ([StringComparer]::OrdinalIgnoreCase) Forward = New-Object 'System.Collections.Generic.Dictionary[string,string]' ([StringComparer]::OrdinalIgnoreCase) Reverse = @{} Counters = @{} Hints = @{} Ordered = $null DomainSuffixes = @() } $keep = @{}; foreach ($k in $script:AiKeepNames) { $keep[$k.ToLower()] = $true } $keepProc = @{}; foreach ($k in $script:AiKeepProcesses) { $keepProc[$k.ToLower()] = $true } $keepPrefix = @{}; foreach ($k in $script:AiKeepAccountPrefixes) { $keepPrefix[$k.ToLower()] = $true } $add = { param($Value, [string]$Prefix) $v = "$Value".Trim() if (-not $v -or $v.Length -lt 3) { return } if ($keep.ContainsKey($v.ToLower())) { return } if ($Prefix -eq 'PATH' -and $v -match $script:AiKeepPathPattern) { return } if ($Prefix -eq 'PROC' -and $keepProc.ContainsKey($v.ToLower())) { return } if (-not $pz.Candidates.ContainsKey($v)) { $pz.Candidates[$v] = $Prefix } } # DOMAIN\name, DOMAIN/name, name@domain.tld or a bare name. $addAccount = { param($Value, [string]$Kind = 'USER') $v = "$Value".Trim() if (-not $v) { return } if ($v -match '^([^\\/]+)[\\/](.+)$') { if ($keepPrefix.ContainsKey($Matches[1].ToLower())) { return } $left = $Matches[1]; $right = $Matches[2] & $add $left 'NETBIOS'; & $add $right $Kind } elseif ($v -match '^([^@]+)@(.+)$') { & $add $Matches[1] $Kind } else { & $add $v $Kind } } $suffixes = New-Object System.Collections.Generic.List[string] foreach ($s in @($Snapshots | Where-Object { $_ })) { $hn = Get-SnapshotHostName $s & $add $hn 'HOST'; & $add $s.host.name 'HOST'; & $add $s.meta.computerName 'HOST' $dns = "$($s.host.dnsDomain)" if ($dns) { & $add $dns 'DOMAIN'; $suffixes.Add($dns); & $add "$hn.$dns" 'HOSTFQDN' } foreach ($u in @($s.localAccounts.users | Where-Object { $_ })) { & $add $u.name 'USER' } foreach ($m in @($s.localAccounts.administrators | Where-Object { $_ })) { $kind = if ("$($m.class)" -match '(?i)group') { 'GROUP' } else { 'USER' } $p = "$($m.path)" if ($p -match '^([^\\/]+)[\\/](.+)$' -and $Matches[1] -ieq $hn) { & $add $Matches[2] $kind } else { & $addAccount $p $kind } } # The users whose own policy sets AlwaysInstallElevated: a profile name, so a person's name. foreach ($au in @($s.uac.alwaysInstallElevatedUsers | Where-Object { $_ })) { & $add $au.user 'USER' } # Rights held by an account that could not be turned into a SID are listed by name. if ($s.securityPolicy -and $s.securityPolicy.privilegeRights) { foreach ($pn in @($s.securityPolicy.privilegeRights.PSObject.Properties)) { foreach ($member in @($pn.Value)) { if ("$member" -and "$member" -notmatch '^S-1-') { & $addAccount "$member" } } } } foreach ($svc in @($s.services | Where-Object { $_ })) { & $addAccount $svc.account & $add $svc.pathName 'PATH'; & $add $svc.executable 'PATH' } foreach ($t in @($s.scheduledTasks | Where-Object { $_ })) { & $addAccount $t.userId; & $addAccount $t.groupId # The author reaches a finding only for a task that sits among Windows' own with an author # that is not Microsoft (scheduled_task_masquerade), and that is the only one tokenized: # masking "Microsoft" or a resource string would damage the rest of the prompt. $au = "$($t.author)".Trim() if ($au -and $au -notmatch '(?i)microsoft' -and $au -notmatch '^\$\(@' -and $au -notmatch '^@%') { & $addAccount $au } foreach ($a in @($t.actions | Where-Object { $_ })) { & $add $a.execute 'PATH'; & $add $a.executable 'PATH' } } foreach ($r in @($s.autoruns | Where-Object { $_ })) { & $add $r.command 'PATH'; & $add $r.executable 'PATH' } # Writable PATH and program folders: the folders, and the programs (an in-house one names its company). if ($s.writablePaths) { # Only the ones someone may write (the others never reach a finding): tokenizing C:\Windows\system32 # would hide stock tools, and a drive root every path. foreach ($e in @($s.writablePaths.systemPath | Where-Object { $_ -and @($_.writableBy | Where-Object { $_ }).Count -gt 0 })) { & $add $e.dir 'PATH' if ("$($e.parent)".Length -gt 3) { & $add $e.parent 'PATH' } } foreach ($e in @($s.writablePaths.programDirs | Where-Object { $_ })) { & $add $e.dir 'PATH'; & $add $e.name 'SOFTWARE' } } # A driver loaded from a user folder names the user in its path. if ($s.drivers) { foreach ($dv in @($s.drivers.list | Where-Object { $_ })) { & $add $dv.path 'PATH' } } foreach ($p in @($s.defender.exclusionPaths | Where-Object { $_ })) { & $add $p 'PATH' } foreach ($p in @($s.defender.exclusionProcesses | Where-Object { $_ })) { & $add $p $(if ("$p" -match '[\\/]') { 'PATH' } else { 'PROC' }) } # Credentials left on disk: the files, and the profile folders (named after their users). if ($s.credentialExposure) { foreach ($u in @($s.credentialExposure.unattendFiles | Where-Object { $_ })) { & $add $u.path 'PATH' } foreach ($g in @($s.credentialExposure.gppFiles | Where-Object { $_ })) { & $add $g.path 'PATH' } foreach ($ph in @($s.credentialExposure.psHistory | Where-Object { $_ })) { & $add $ph.profile 'USER' } } # Browser extensions: the users their profiles belong to, and the names of extensions that did not # come from a public store (an in-house extension names its company). if ($s.browserExtensions) { foreach ($bp in @($s.browserExtensions.profiles | Where-Object { $_ })) { & $add $bp.user 'USER' foreach ($be in @($bp.extensions | Where-Object { $_ -and "$($_.source)" -notin 'store', 'external-store' })) { & $add $be.name 'SOFTWARE' } } } # Persistence points: what they start, and the names someone gave to a WMI consumer. if ($s.persistence) { foreach ($w in @($s.persistence.wmiConsumers | Where-Object { $_ })) { & $add $w.name 'WMI'; & $add $w.command 'PATH' } foreach ($i in @($s.persistence.ifeoDebuggers | Where-Object { $_ })) { & $add $i.debugger 'PATH' } foreach ($i in @($s.persistence.silentProcessExit | Where-Object { $_ })) { & $add $i.monitor 'PATH' } foreach ($a in @($s.persistence.appInit | Where-Object { $_ })) { & $add $a.dlls 'PATH' } if ($s.persistence.winlogon) { & $add $s.persistence.winlogon.shell 'PATH'; & $add $s.persistence.winlogon.userinit 'PATH' } # DLLs that are not Windows' own: an in-house component names its company. $plugins = @(@($s.persistence.printMonitors) + @($s.persistence.netshHelpers) + @(foreach ($k in 'security', 'authentication', 'notification') { @($s.persistence.lsa.$k) }) | Where-Object { $_ -and -not (Test-StockSigner $_) }) foreach ($pl in $plugins) { & $add $pl.name 'PLUGIN'; & $add $pl.driver 'PATH'; & $add $pl.dll 'PATH' if ("$($pl.signer)" -and "$($pl.signer)" -notmatch '^Microsoft ') { & $add $pl.signer 'CERT' } } } # Root certificates someone added: a private CA names its organization. if ($s.certificates) { foreach ($c in @($s.certificates.roots | Where-Object { $_ -and $_.subject -and $_.inMicrosoftProgram -ne $true })) { $parts = Get-CertSubjectParts "$($c.subject)" & $add (Get-CertSubjectShort "$($c.subject)") 'CERT' foreach ($v in @($parts.CN, $parts.O, $parts.OU)) { & $add $v 'CERT' } } } foreach ($w in @($s.wifi | Where-Object { $_ })) { & $add $w.name 'SSID' } # Lesser-known load points: what they load or run, the users of the profiles read, BITS job owners. if ($s.loadPoints) { $lp = $s.loadPoints $dlls = @(@($lp.networkProviders) + @($lp.credentialProviders) + @($lp.appCertDlls) + @($lp.timeProviders) + @($lp.printProcessors) + @($lp.aeDebug) + @($lp.serviceHooks) | Where-Object { $_ -and -not (Test-StockSigner $_) }) foreach ($d in $dlls) { & $add $d.dll 'PATH'; & $add $d.serviceDll 'PATH'; & $add $d.debugger 'PATH'; & $add $d.failureCommand 'PATH' if ("$($d.signer)" -and "$($d.signer)" -notmatch '^Microsoft ') { & $add $d.signer 'CERT' } } foreach ($d in @(@($lp.networkProviders) + @($lp.timeProviders) + @($lp.printProcessors) | Where-Object { $_ -and -not (Test-StockSigner $_) })) { & $add $d.name 'PLUGIN' } foreach ($d in @($lp.credentialProviders | Where-Object { $_ -and -not (Test-StockSigner $_) })) { & $add $d.name 'PLUGIN' } if ($lp.dotnetProfiler) { & $add $lp.dotnetProfiler.dll 'PATH' } foreach ($x in @($lp.sessionManagerExecute | Where-Object { $_ -and "$($_.command)" -notmatch '(?i)^autocheck ' })) { & $add $x.command 'PATH' } foreach ($h in @($lp.hiddenServices | Where-Object { $_ })) { & $add $h.name 'SERVICE'; & $add $h.imagePath 'PATH' } foreach ($t in @($lp.hiddenTasks | Where-Object { $_ })) { & $add $t.path 'TASK' } foreach ($l in @($lp.logonScripts | Where-Object { $_ })) { & $add $l.command 'PATH'; & $add $l.parameters 'PATH'; & $add $l.user 'USER' } foreach ($o in @($lp.officeTestMachine | Where-Object { $_ })) { & $add $o.dll 'PATH' } foreach ($o in @($lp.officeProfiles | Where-Object { $_ })) { & $add $o.user 'USER'; & $add $o.officeTest 'PATH' foreach ($hp in @($o.homePages | Where-Object { $_ })) { & $add $hp.url 'URL' } foreach ($x in @($o.xll | Where-Object { $_ })) { & $add $x 'PATH' } } if ($lp.ssh) { foreach ($u in @($lp.ssh.userKeys | Where-Object { $_ })) { & $add $u.user 'USER' } } # Office trusted locations: the user whose list it is, and the folder itself (a share or a # profile folder names people and systems). foreach ($tl in @($lp.officeTrustedLocations | Where-Object { $_ })) { & $add $tl.user 'USER'; & $add $tl.path 'PATH' } # What was typed in the Run dialog: the user, and the addresses inside the command (the # command itself stays readable, so the AI can still see that it was mshta or PowerShell). foreach ($e in @($lp.runDialog | Where-Object { $_ })) { & $add $e.user 'USER' $cmd = "$($e.command)" foreach ($m in [regex]::Matches($cmd, '(?i)\b[a-z][a-z0-9+.\-]*://[^\s"'']+')) { & $add $m.Value 'URL' } foreach ($m in [regex]::Matches($cmd, '\\\\[^\s"'']+')) { & $add $m.Value 'PATH' } foreach ($m in [regex]::Matches($cmd, '(?i)\b[a-z]:\\[^\s"'']+')) { & $add $m.Value 'PATH' } } foreach ($j in @($lp.bitsJobs | Where-Object { $_ })) { & $add $j.name 'BITS'; & $addAccount $j.owner; & $add $j.notifyCmdLine 'PATH' } foreach ($m in @($lp.missingTargets | Where-Object { $_ })) { & $add $m.name $(if ("$($m.source)" -eq 'service') { 'SERVICE' } else { 'TASK' }); & $add $m.executable 'PATH' } } if ($s.tamper) { foreach ($c in @($s.tamper.trustedPublishers | Where-Object { $_ -and $_.subject })) { $parts = Get-CertSubjectParts "$($c.subject)" & $add (Get-CertSubjectShort "$($c.subject)") 'CERT' foreach ($v in @($parts.CN, $parts.O, $parts.OU)) { & $add $v 'CERT' } } if ($s.tamper.winHttpProxy) { & $add $s.tamper.winHttpProxy.proxy 'PROXY' } } if ($s.localGroups) { foreach ($g in @($s.localGroups.groups | Where-Object { $_ })) { foreach ($m in @($g.members | Where-Object { $_ -and "$($_.sid)" -notmatch '^S-1-5-(11|4|7|32-\d+)$|^S-1-1-0$' })) { & $addAccount "$($m.path)" $(if ("$($m.class)" -match '(?i)group') { 'GROUP' } else { 'USER' }) } } } foreach ($sh in @($s.shares | Where-Object { $_ })) { & $add $sh.name 'SHARE'; & $add $sh.path 'PATH' } # Attack surface: WSL distributions and their users, Office add-ins, profiles with saved # credentials, programs let in by the firewall, vendor named pipes, ASR exclusions. if ($s.surface) { $sf = $s.surface foreach ($w in @($sf.wslDistributions | Where-Object { $_ })) { & $add $w.name 'WSL'; & $add $w.user 'USER' } foreach ($a in @($sf.officeAddins | Where-Object { $_ -and -not ($_.dll -and "$($_.dll.status)" -eq 'Valid' -and "$($_.dll.signer)" -match '^Microsoft ') })) { & $add $a.progId 'PLUGIN'; & $add $a.manifest 'URL' if ("$($a.scope)" -ne 'machine') { & $add $a.scope 'USER' } if ($a.dll) { & $add $a.dll.path 'PATH'; if ("$($a.dll.signer)" -and "$($a.dll.signer)" -notmatch '^Microsoft ') { & $add $a.dll.signer 'CERT' } } } foreach ($c in @($sf.credentialFiles | Where-Object { $_ })) { & $add $c.user 'USER' } foreach ($r in @($sf.firewallUserApps | Where-Object { $_ })) { & $add $r.program 'PATH' } if ($sf.namedPipes) { foreach ($p in @($sf.namedPipes.writable | Where-Object { $_ -and -not (Test-WindowsPipe "$($_.name)") })) { & $add $p.name 'PIPE'; & $add $p.serverProcess 'PROC'; & $add $p.serverPath 'PATH' } } } # Port forwarding: both ends of every rule reach the finding, and an internal address says how # the network is laid out. The wildcards and loopback stay as they are. if ($s.network) { foreach ($pp in @($s.network.portProxy | Where-Object { $_ })) { foreach ($side in @("$($pp.listen)", "$($pp.connect)")) { $addr = ($side -split '/')[0] if ($addr -and @('0.0.0.0', '*', '::', '127.0.0.1', '::1', 'localhost') -notcontains $addr) { & $add $addr 'IP' } } } } # The update server set by policy: an internal name, printed by wsus_insecure_transport. if ($s.hardening -and $s.hardening.windowsUpdateSource) { & $add $s.hardening.windowsUpdateSource.server 'URL' & $add $s.hardening.windowsUpdateSource.statusServer 'URL' } if ($s.defender) { foreach ($x in @($s.defender.asrExclusions | Where-Object { $_ })) { & $add $x 'PATH' } foreach ($r in @($s.defender.asrRuleExclusions | Where-Object { $_ })) { foreach ($x in @($r.paths | Where-Object { $_ })) { & $add $x 'PATH' } } } } # Names that only a finding mentions (the Objects of the findings follow a fixed pattern). foreach ($f in @($Findings | Where-Object { $_ })) { $o = "$($f.Object)" # Stock service names from the CIS list say what the finding is: keep them. if ($o -match '^service: (.+)$' -and "$($f.Type)" -ne 'service_should_be_disabled') { & $add $Matches[1] 'SERVICE' } elseif ($o -match '^task: (.+?) -> ') { & $add $Matches[1] 'TASK' } elseif ($o -match '^task: (.+)$') { & $add $Matches[1] 'TASK' } elseif ($o -match '^share: (.+)$') { & $add $Matches[1] 'SHARE' } elseif ($o -match '^BITS job: (.+) \((.+)\)$') { & $add $Matches[1] 'BITS'; & $addAccount $Matches[2] } elseif ($o -match '^(?:network provider|time provider|AppCertDlls): (.+)$') { & $add $Matches[1] 'PLUGIN' } elseif ($o -match '^print processor: (.+) \(') { & $add $Matches[1] 'PLUGIN' } elseif ($o -match '^script: \S+ \S+ (.+)$') { & $add $Matches[1] 'PATH' } elseif ($o -match '^autorun: \S+ (.+)$') { & $add $Matches[1] 'AUTORUN' } elseif ($o -match '^adapter: (.+)$') { & $add $Matches[1] 'ADAPTER' } elseif ($o -match '^account: (.+)$') { & $addAccount $Matches[1] } elseif ($o -match '^wmi consumer: (.+)$') { & $add $Matches[1] 'WMI' } elseif ($o -match '^Wi-Fi: (.+)$') { & $add $Matches[1] 'SSID' } elseif ($o -match '^profile: (.+)$') { & $add $Matches[1] 'USER' } elseif ($o -match '^file: (.+)$') { & $add $Matches[1] 'PATH' } elseif ($o -match '^WSL: (.+) \((.+)\)$') { & $add $Matches[1] 'WSL'; & $add $Matches[2] 'USER' } elseif ($o -match '^pipe: (.+)$') { & $add $Matches[1] 'PIPE' } elseif ($o -match '^add-in: \S+ (.+)$') { & $add $Matches[1] 'PLUGIN' } elseif ($o -match '^program: (.+)$') { & $add $Matches[1] 'PATH' } elseif ($o -match '^ASR(?: [0-9a-f-]+)?: (.+)$') { & $add $Matches[1] 'PATH' } # A domain account lists the services and tasks that use it: "service X (state)", "task \path\name". if ("$($f.Type)" -eq 'service_domain_account') { foreach ($m in [regex]::Matches("$($f.Detail)", '(?:: |; )service (\S+) \(')) { & $add $m.Groups[1].Value 'SERVICE' } foreach ($m in [regex]::Matches("$($f.Detail)", '(?:: |; )task (.+?)(?=; |\.$)')) { & $add $m.Groups[1].Value 'TASK' } } elseif ($o -match '^member: (.+)$') { & $addAccount $Matches[1] } elseif (("$($f.Type)" -in 'kev_software_match', 'software_eol', 'software_outdated', 'software_cve') -and "$($f.Detail)" -match '^Installed as (.+) \((?:version [^)]*|no version recorded)\)\.') { & $add $Matches[1] 'SOFTWARE' } if ("$($f.Type)" -eq 'risky_listener' -and "$($f.Detail)" -match '^Listening on (\S+?)(?: by (.+?))?\.$') { if (@('0.0.0.0', '::', '127.0.0.1', '::1') -notcontains $Matches[1]) { & $add $Matches[1] 'IP' } if ($Matches[2]) { & $add $Matches[2] 'PROC' } } } # Longest first, so that "WKS-ACCT-017.corp.example" is replaced before "WKS-ACCT-017", and within # one length by the name itself, ordinal. The order has to be total: Sort-Object is not a stable # sort, so two names of the same length came out in a different order at every run and the tokens # were numbered differently each time (two runs on the same snapshot wrote two different prompts, # and the prompt kept next to a report did not match the one that had been sent). The key is the # length, complemented so that it sorts descending, followed by the name; [Array]::Sort with an # ordinal comparer then depends on nothing but the names themselves. $keys = [string[]]@($pz.Candidates.Keys) $sortKeys = [string[]]@($keys | ForEach-Object { ('{0:D5}' -f (99999 - $_.Length)) + $_ }) [Array]::Sort($sortKeys, $keys, [System.StringComparer]::Ordinal) $pz.Ordered = @($keys) $pz.DomainSuffixes = @($suffixes | Select-Object -Unique) # Hosts first, in the order of the listing, so the tokens read HOST-1, HOST-2... in the order of # the table. foreach ($h in $HostOrder) { if ($pz.Candidates.ContainsKey($h)) { [void](Get-AiToken $pz $h 'HOST') } } foreach ($d in $pz.DomainSuffixes) { if ($pz.Candidates.ContainsKey($d)) { [void](Get-AiToken $pz $d 'DOMAIN') } } return $pz } function Get-AiToken { param($Pz, [string]$Value, [string]$Prefix) if ($Pz.Forward.ContainsKey($Value)) { return $Pz.Forward[$Value] } if (-not $Pz.Counters.ContainsKey($Prefix)) { $Pz.Counters[$Prefix] = 0 } $Pz.Counters[$Prefix]++ $token = "$Prefix-$($Pz.Counters[$Prefix])" $Pz.Forward[$Value] = $token $Pz.Reverse[$token] = $Value if ($Prefix -eq 'PATH' -and (Test-CommandInUserWritablePlace $Value)) { $Pz.Hints[$token] = 'user-writable location' } return $token } # Finding text copies identifiers from the snapshot exactly as they are. Names that can also be an # ordinary word (an account called "support", a task called "Update") are therefore matched with # their exact case. Otherwise "Support ended" would turn into "USER-2 ended". Hosts, domains and # paths are never prose, so those ignore case. function Get-AiMatchOptions { param([string]$Prefix) if (@('HOST', 'HOSTFQDN', 'DOMAIN', 'NETBIOS', 'PATH', 'IP') -contains $Prefix) { return [System.Text.RegularExpressions.RegexOptions]::IgnoreCase } return [System.Text.RegularExpressions.RegexOptions]::None } # "CIS 2.3.7.5, 2.3.7.6" is a list of rule numbers, and four dotted numbers look like an address. # The references are set aside while we look for addresses. On servers a finding names the benchmark # too: "CIS Server 2022 2.3.5.2", "CIS Windows 11 2.3.10.2". $script:AiCisRefPattern = 'CIS (?:Server \d{4} |Windows 1[01] )?\d+(?:\.\d+)*(?:(?:, and |, | - | and )\d+(?:\.\d+)*)*' # Check titles are HostBadger's own text, never host data, and they are prose: "Windows version out of # support" must not become "out of USER-1" on a host with an account called "support". They are set # aside like the CIS references, and the leak test ignores them too. $script:AiTitlePatternCache = $null function Get-AiTitlePattern { if ($null -eq $script:AiTitlePatternCache -or $script:AiTitlePatternCache.Count -ne $script:CheckCatalog.Count) { $titles = @($script:CheckCatalog.Values | ForEach-Object { "$($_.Title)" } | Where-Object { $_ } | Sort-Object -Unique | Sort-Object Length -Descending) $script:AiTitlePatternCache = @{ Count = $script:CheckCatalog.Count; Pattern = '(?<![\w\-])(?:' + (($titles | ForEach-Object { [regex]::Escape($_) }) -join '|') + ')(?![\w\-])' } } return $script:AiTitlePatternCache.Pattern } function Protect-AiText { param($Pz, [string]$Text) if (-not $Text) { return $Text } $titles = New-Object System.Collections.Generic.List[string] $out = [regex]::Replace($Text, (Get-AiTitlePattern), { param($m) $titles.Add($m.Value); "$([char]2)$($titles.Count - 1)$([char]2)" }) # Structural identifiers go first, and whatever they contain is replaced as a whole. $out = [regex]::Replace($out, $script:AiSidPattern, { param($m) Get-AiToken $Pz $m.Value 'SID' }) $out = [regex]::Replace($out, '\\\\[^\s]+', { param($m) Get-AiToken $Pz $m.Value 'UNC' }) foreach ($suffix in $Pz.DomainSuffixes) { $fq = '(?i)(?<![\w.\-])(?:[a-z0-9\-_]+\.)+' + [regex]::Escape($suffix) + '(?![\w\-])' $out = [regex]::Replace($out, $fq, { param($m) Get-AiToken $Pz $m.Value 'HOSTFQDN' }) } foreach ($k in $Pz.Ordered) { $prefix = $Pz.Candidates[$k] $pattern = '(?<![\w.\-$])' + [regex]::Escape($k) + '(?![\w\-$]|\.[\w])' $out = [regex]::Replace($out, $pattern, { param($m) Get-AiToken $Pz $k $prefix }, (Get-AiMatchOptions $prefix)) } $refs = New-Object System.Collections.Generic.List[string] $out = [regex]::Replace($out, $script:AiCisRefPattern, { param($m) $refs.Add($m.Value); "$([char]1)$($refs.Count - 1)$([char]1)" }) $out = [regex]::Replace($out, $script:AiIpPattern, { param($m) Get-AiToken $Pz $m.Value 'IP' }) $out = [regex]::Replace($out, "$([char]1)(\d+)$([char]1)", { param($m) $refs[[int]$m.Groups[1].Value] }) $out = [regex]::Replace($out, "$([char]2)(\d+)$([char]2)", { param($m) $titles[[int]$m.Groups[1].Value] }) return $out } function Unprotect-AiText { param($Pz, [string]$Text) if (-not $Text) { return $Text } return [regex]::Replace($Text, $script:AiTokenPattern, { param($m) if ($Pz.Reverse.ContainsKey($m.Value)) { return $Pz.Reverse[$m.Value] } return $m.Value }) } # The last check before sending: if any real identifier is still there, we refuse. function Test-AiLeak { param($Pz, [string]$Text) $leaks = New-Object System.Collections.Generic.List[string] $prose = [regex]::Replace($Text, (Get-AiTitlePattern), ' ') foreach ($k in $Pz.Ordered) { if ($k.Length -lt 4) { continue } if ([regex]::IsMatch($prose,'(?<![\w.\-@$])' + [regex]::Escape($k) + '(?![\w\-$]|\.[\w])', (Get-AiMatchOptions $Pz.Candidates[$k]))) { $leaks.Add($k) } if ($leaks.Count -ge 10) { break } } if ($Text -match $script:AiSidPattern) { $leaks.Add('(a domain, Entra or service SID)') } if ($Text -match '\\\\[^\s]+') { $leaks.Add('(a UNC path)') } if ([regex]::Replace($Text, $script:AiCisRefPattern, '') -match $script:AiIpPattern) { $leaks.Add('(an IP address)') } foreach ($suffix in $Pz.DomainSuffixes) { if ($Text.IndexOf($suffix, [StringComparison]::OrdinalIgnoreCase) -ge 0) { $leaks.Add($suffix) } } # Any drive path left over, other than the stock Windows tools, is a path that wasn't masked. foreach ($m in [regex]::Matches($Text, '(?i)[a-z]:\\[^\s\\]\S*')) { if ($m.Value -notmatch $script:AiKeepPathPattern) { $leaks.Add('(a file path: ' + $m.Value.Substring(0, [Math]::Min(3, $m.Value.Length)) + '...)'); break } } return $leaks } # -------------------------------------------------------------------------- # Prompt # -------------------------------------------------------------------------- $script:AiSystemPrompt = @" You are a Windows endpoint security assistant helping the defenders who own these hosts plan remediation. You receive deterministic hardening findings that were already computed by a local tool from read-only host snapshots. Treat them as established facts: do not recompute, dispute or add findings that are not in the input. Identifiers were replaced by placeholder tokens (HOST-3, DOMAIN-1, USER-2, GROUP-1, SID-4, PATH-7, SERVICE-2, TASK-1, AUTORUN-1, ADAPTER-1, PROC-2, IP-1...). Always refer to objects by their token exactly as written; never guess the real name. Names that are the same on every Windows machine (Administrator, Guest, Users, Everyone...) are left as is. A PATH token listed under "Path tokens" is in a location low-privileged users can write. A section "Coverage gaps" lists checks that could NOT be evaluated on some hosts. Their state is unknown: never describe those hosts as clean for those checks, and mention the gap where it matters. A section "Attack paths complete on a host" may list chains whose every stage has an enabling condition on one and the same host, stage by stage, with the checks that opened each stage. The tool computed them; do not invent chains, stages or hosts that are not listed. Use them for ordering, not for drama: a chain breaks as soon as ONE of its stages is closed, so for each chain say in the rationale of the work package that breaks it which stage it breaks and why that stage is the cheapest or least disruptive one to close. A chain line may end with "cheapest stage to close": that is the tool's own count of what each stage costs (how many checks have to be settled, how many of them have a generated fix script). Start from it, and pick another stage only if you say why that one is better to close on that host. A host carrying a complete chain outranks a host with more findings but no chain. A complete chain means the conditions are present, not that an attack happened: never write that a host has been compromised. Your output is for defenders only. Describe risk in terms of impact and business consequence; do not write attack procedures, commands or exploitation steps. Produce: 1. executive_summary: 4-6 sentences for management. Overall posture of the fleet, the two or three exposures that matter most and why, in plain language. Say if coverage gaps limit the picture. 2. remediation_plan: an ordered list of work packages. Group related checks that share an owner or a change window (for example all Defender items, or all SMB and NetBIOS items). Order by risk reduction per unit of effort: exposures that let an attacker run code as SYSTEM or steal credentials first, then protection gaps, then hygiene. Each item: title, the check ids it covers, affected host tokens (at most 8), why this position in the order, effort (low | medium | high), and operational caveats (what can break, what to test first). Do NOT number the items yourself. 3. quick_wins: up to 5 changes that are low effort and low disruption. 4. monitoring: for exposures that cannot be fixed immediately, what to monitor meanwhile: relevant Windows event IDs and a short description of the detection logic for a SIEM. Only reference event IDs you are confident exist and apply. 5. comparison_narrative: only if a "Comparison" section is present, 2-4 sentences on the trend (real progress vs churn). Omit otherwise. 6. host_priorities: the hosts to work on first, with a rank (1 = first), the host tokens, and a one sentence rationale (what exposure, what role). 7. remediation_scripts: for the check ids where a safe, standard fix can be expressed as PowerShell, give a snippet. Each: the check id, a short PowerShell block using native cmdlets (Set-MpPreference, Set-SmbServerConfiguration, registry or policy settings; use the tokens as placeholders the operator will substitute), and caveats. Only for changes that are routine and reversible; for anything destructive or environment-specific, return guidance in caveats and keep the script minimal or empty. Never include credential theft or offensive code. 8. triage: re-rank the fired checks by real exploitability in THIS fleet (reachability, privilege, how many hosts, host role), not by static severity alone. Each: a rank (1 = fix first), the check ids, the key tokens, and a one sentence rationale. If no findings are provided, say so plainly and return empty lists. Respond with one JSON object only, no markdown fences: { "executive_summary": "...", "remediation_plan": [ { "title": "...", "checks": ["..."], "objects": ["..."], "rationale": "...", "effort": "low|medium|high", "caveats": "..." } ], "quick_wins": ["..."], "monitoring": [ { "checks": ["..."], "event_ids": ["4688"], "guidance": "..." } ], "comparison_narrative": "...", "host_priorities": [ { "rank": 1, "hosts": ["HOST-1"], "rationale": "..." } ], "remediation_scripts": [ { "check": "...", "powershell": "...", "caveats": "..." } ], "triage": [ { "rank": 1, "checks": ["..."], "objects": ["..."], "rationale": "..." } ] } "@ # The raw prompt, with real names. The whole of it goes through Protect-AiText, so nothing reaches # the model unmasked, whatever text a check wrote. function New-AiPromptRaw { param($Findings, $Hosts, $Comparison, [int]$MaxLinesPerCheck = 12) $sevOrder = @('Critical', 'High', 'Medium', 'Low') $lines = New-Object System.Collections.Generic.List[string] $hostList = @($Hosts | Sort-Object { $_.Score.Score }, Name) $avg = [int][Math]::Round((@($hostList | ForEach-Object { $_.Score.Score }) | Measure-Object -Average).Average) $sevText = ($sevOrder | ForEach-Object { $s = $_; "{0} {1}" -f @($Findings | Where-Object { $_.Severity -eq $s }).Count, $s.ToLower() }) -join ', ' $roles = ($hostList | Group-Object Role | Sort-Object Name | ForEach-Object { "$($_.Count) $($_.Name)" }) -join ', ' $lines.Add("Fleet: $($hostList.Count) host(s) ($roles). Average hardening score $avg/100. Findings: $sevText.") $lines.Add('') $lines.Add('Hosts (name, role, operating system, score, findings, checks not evaluated):') $byHost = Group-ByHost $Findings foreach ($h in $hostList) { $n = @(Get-HostItems $byHost $h.Name).Count $lines.Add("- $($h.Name): $($h.Role), $($h.Os), score $($h.Score.Grade) $($h.Score.Score)/100, $n finding(s), $(@($h.NotEvaluated).Count) not evaluated.") } # Attack paths: the chains every stage of which has an enabling condition on the same host. They are # computed by the tool, not by the model; breaking one stage breaks the chain, which is what the # model is asked to use when it orders the work. $chainHosts = @($hostList | Where-Object { @($_.AiChains).Count -gt 0 }) if ($chainHosts.Count -gt 0) { $lines.Add('') $lines.Add('Attack paths complete on a host (every stage has an enabling condition on that same host; breaking any one stage breaks the chain):') foreach ($h in $chainHosts) { foreach ($c in @($h.AiChains)) { # Chain and stage ids, like the check ids: a chain title would carry words (Domain, # Office, Access) that the pseudonymizer replaces with a token. $stages = (@($c.Stages) | ForEach-Object { "$($_.Stage) [$(@($_.Checks) -join ', ')]" }) -join ' -> ' # The stage the tool judged cheapest to close, when it computed one: fewest checks to # settle, a generated fix script for each of them where there is one. $brk = if ($c.Break) { " | cheapest stage to close: $($c.Break.StageId) ($(@($c.Break.Checks).Count) check(s), $([int]$c.Break.FixCount) with a fix script)" } else { '' } $lines.Add("- $($h.Name) | $($c.Id): $stages$brk") } } } $gaps = @($hostList | ForEach-Object { $_.NotEvaluated } | Where-Object { $_ }) if ($gaps.Count -gt 0) { $lines.Add('') $lines.Add('Coverage gaps (checks NOT evaluated: state unknown, not clean):') foreach ($g in ($gaps | Group-Object Type | Sort-Object Name)) { # The collector's error text never leaves. The model only learns that the data was # missing. $why = (@($g.Group | ForEach-Object { ("$($_.Reason)" -replace "(failed): [^;]*", '$1') } | Select-Object -Unique) -join ' / ') $lines.Add("- $($g.Name) ($($script:CheckCatalog[$g.Name].Title)): $(@($g.Group | ForEach-Object { $_.Host } | Select-Object -Unique) -join ', '). $why") } } $lines.Add('') $lines.Add('Findings grouped by check (severity, host, object, detail):') $groups = $Findings | Group-Object Type | Sort-Object { - ($_.Group | ForEach-Object { $script:SeverityRank[$_.Severity] } | Measure-Object -Maximum).Maximum }, @{ Expression = 'Count'; Descending = $true } foreach ($g in $groups) { $meta = $script:CheckCatalog[$g.Name] $ordered = @($g.Group | Sort-Object { - $script:SeverityRank[$_.Severity] }, Host, Object) $worst = $ordered[0].Severity $nHosts = @($ordered | ForEach-Object { $_.Host } | Select-Object -Unique).Count $lines.Add("## [$worst] $($g.Name): $($meta.Title) ($($ordered.Count) finding(s) on $nHosts host(s))") foreach ($f in ($ordered | Select-Object -First $MaxLinesPerCheck)) { $lines.Add("- [$($f.Severity)] $($f.Host) | $($f.Object) | $($f.Detail)") } if ($ordered.Count -gt $MaxLinesPerCheck) { $shown = @($ordered | Select-Object -First $MaxLinesPerCheck | ForEach-Object { $_.Host } | Select-Object -Unique).Count $lines.Add("- ... and $($ordered.Count - $MaxLinesPerCheck) more finding(s) with the same issue ($($nHosts - $shown) more host(s))") } } if ($Comparison -and (@($Comparison.New).Count + @($Comparison.Resolved).Count) -gt 0) { $lines.Add('') $lines.Add('Comparison with the previous run (already computed):') foreach ($f in @($Comparison.New | Select-Object -First 30)) { $lines.Add("- NEW [$($f.Severity)] $($f.Type): $($f.Host) | $($f.Object)") } foreach ($f in @($Comparison.Resolved | Select-Object -First 30)) { $lines.Add("- RESOLVED [$($f.Severity)] $($f.Type): $($f.Host) | $($f.Object)") } $lines.Add("- Still present: $(@($Comparison.Persisting).Count)") } return ($lines -join "`n") } function New-AiPrompt { param($Findings, $Hosts, $Pz, $Comparison, [int]$MaxLinesPerCheck = 12) $text = Protect-AiText $Pz (New-AiPromptRaw -Findings $Findings -Hosts $Hosts -Comparison $Comparison -MaxLinesPerCheck $MaxLinesPerCheck) # Which path tokens are in a place where low-privileged users can write. That is a class, not a # name. $writable = @($Pz.Hints.Keys | Where-Object { $text -match ('\b' + [regex]::Escape($_) + '\b') } | Sort-Object { [int]($_ -replace '\D', '') }) if ($writable.Count -gt 0) { $text += "`n`nPath tokens (in a location low-privileged users can write: profile, Temp, ProgramData, Downloads, drive root):`n- $($writable -join ', ')" } return $text } # The same text that goes into the request: the system instruction, then the user prompt. The dry # run and the copy kept before a real send both use it. function Write-AiPromptFile { param([string]$Path, [string]$UserPrompt) $text = "=== SYSTEM ===`n$script:AiSystemPrompt`n`n=== USER ===`n$UserPrompt`n" [System.IO.File]::WriteAllText($Path, $text, (New-Object System.Text.UTF8Encoding($false))) } # report_x.html -> report_x_ai_prompt.txt, in the same folder. function Get-AiSidecarPath { param([string]$ReportPath, [string]$Suffix) $dir = [System.IO.Path]::GetDirectoryName($ReportPath) Join-Path $dir ([System.IO.Path]::GetFileNameWithoutExtension($ReportPath) + $Suffix) } # What came back, before the tokens are swapped back to real names. function Write-AiResponseFile { param([string]$Path, $Raw) [System.IO.File]::WriteAllText($Path, ($Raw | ConvertTo-Json -Depth 10), (New-Object System.Text.UTF8Encoding($false))) } # -------------------------------------------------------------------------- # Talking to Gemini: HttpClient, a spinner, and retries with a growing wait. # -------------------------------------------------------------------------- function Invoke-HttpPostWithSpinner { param([string]$Uri, [string]$JsonBody, [string]$Message = "Contacting Gemini", [int]$TimeoutSeconds = 180, [hashtable]$Headers = @{}) Add-Type -AssemblyName System.Net.Http -ErrorAction SilentlyContinue # Windows PowerShell 5.1 can default to TLS 1.0. try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { } $client = New-Object System.Net.Http.HttpClient $client.Timeout = [TimeSpan]::FromSeconds($TimeoutSeconds) foreach ($hdr in $Headers.Keys) { [void]$client.DefaultRequestHeaders.Add($hdr, $Headers[$hdr]) } $content = New-Object System.Net.Http.StringContent($JsonBody, [System.Text.Encoding]::UTF8, 'application/json') try { $task = $client.PostAsync($Uri, $content) # The progress cursor (Step-Spinner) stays out of a run log, which keeps only the "done" line. while (-not $task.IsCompleted) { Step-Spinner $Message; Start-Sleep -Milliseconds 120 } Stop-Spinner Write-Host "$Message... done." $resp = $task.GetAwaiter().GetResult() return [PSCustomObject]@{ StatusCode = [int]$resp.StatusCode; IsSuccess = $resp.IsSuccessStatusCode; Body = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() } } finally { $client.Dispose() } } # -------------------------------------------------------------------------- # Catalog downloads: one HTTPS GET each, nothing is sent, these addresses and no other. # CISA Known Exploited Vulnerabilities (-KevOnline), LOLDrivers (-DriversOnline, about 30 MB) and the # endoflife.date software lifecycle data (-EolOnline, about 3 MB), the Chocolatey community package # versions (-ChocoOnline), the NVD CVEs and FIRST EPSS scores (-CveOnline), and the browser extensions # removed from the stores (-ExtensionsOnline, about 2 MB), and the public-exploit references (Metasploit # modules and the Exploit-DB index, -ExploitsOnline). HOSTBADGER_KEV_URL, HOSTBADGER_DRIVERS_URL, # HOSTBADGER_EOL_URL, HOSTBADGER_CHOCO_URL, HOSTBADGER_NVD_URL, HOSTBADGER_EPSS_URL, # HOSTBADGER_EXTENSIONS_URL, HOSTBADGER_MSF_URL and HOSTBADGER_EXPLOITDB_URL are the test hooks # (the regression runs a local listener). # -------------------------------------------------------------------------- $script:KevFeedUrl = 'https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json' $script:LolDriversUrl = 'https://www.loldrivers.io/api/drivers.json' $script:EolApiUrl = 'https://endoflife.date/api/v1/products/full' $script:ChocoApiUrl = 'https://community.chocolatey.org/api/v2/' $script:NvdApiUrl = 'https://services.nvd.nist.gov/rest/json/cves/2.0' $script:EpssUrl = 'https://epss.empiricalsecurity.com/epss_scores-current.csv.gz' $script:ExtensionSentryUrl = 'https://raw.githubusercontent.com/toborrm9/malicious_extension_sentry/main/malicious_extensions_detailed.csv' $script:MsfMetadataUrl = 'https://raw.githubusercontent.com/rapid7/metasploit-framework/master/db/modules_metadata_base.json' $script:ExploitDbUrl = 'https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv' # The analyzer on the main branch of the HostBadger repository: "Check for updates" in the window of a # copy that is not a git clone reads its version line (the test hook HOSTBADGER_UPDATE_URL replaces it). $script:HostBadgerMainUrl = 'https://raw.githubusercontent.com/g4bri-3l3/HostBadger/main/HostBadger.ps1' # An address set in the environment (an internal gateway, or the test hooks above) replaces a shipped # one only when it is https, or http on this machine. These variables are read at run time, so the # list of addresses the safety review finds in this file is not the whole story: without this rule a # variable, which anything running as this user can set, would be enough to send a prompt - or the # Gemini key, which travels in a header - wherever someone likes. A refused address stops the # request and never falls back to the shipped one, so nothing goes to an address the user did not # mean. The effective address is printed, so the run log says where the data went. Returns the # address to use, or '' when it was refused. function Resolve-HbUri { param([string]$Override, [string]$Default, [string]$Label) if (-not $Override) { return $Default } $u = $null if (-not [Uri]::TryCreate($Override, [UriKind]::Absolute, [ref]$u)) { Write-Host "$Label`: the address set in the environment is not a URL. Nothing is requested." -ForegroundColor Red return '' } if ($u.Scheme -ne 'https' -and -not ($u.Scheme -eq 'http' -and $u.IsLoopback)) { Write-Host "$Label`: the address set in the environment is $($u.Scheme)://$($u.Authority), which is not https. Nothing is requested." -ForegroundColor Red return '' } Write-Host "$Label`: using $($u.Scheme)://$($u.Authority), set in the environment." -ForegroundColor DarkGray return $Override } # -Headers: request headers (the NVD API key). -Binary: the body as bytes (the EPSS file is gzip). function Get-CatalogText { param([string]$Uri, [string]$Label, [int]$TimeoutSeconds = 60, [hashtable]$Headers = @{}, [switch]$Binary) # An address Resolve-HbUri refused: it has already said why. if (-not $Uri) { return $null } Add-Type -AssemblyName System.Net.Http -ErrorAction SilentlyContinue try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { } $client = New-Object System.Net.Http.HttpClient $client.Timeout = [TimeSpan]::FromSeconds($TimeoutSeconds) try { $req = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::Get, $Uri) foreach ($h in $Headers.Keys) { [void]$req.Headers.TryAddWithoutValidation($h, "$($Headers[$h])") } $task = $client.SendAsync($req) while (-not $task.IsCompleted) { Step-Spinner "Downloading the $Label catalog"; Start-Sleep -Milliseconds 120 } Stop-Spinner $resp = $task.GetAwaiter().GetResult() if (-not $resp.IsSuccessStatusCode) { Write-Host "$Label download failed: HTTP $([int]$resp.StatusCode)." -ForegroundColor Red; return $null } Write-Host "Downloading the $Label catalog... done." if ($Binary) { return , $resp.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult() } return $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() } catch { Write-Host "`r$Label download failed: $($_.Exception.Message) " -ForegroundColor Red; return $null } finally { $client.Dispose() } } function Get-KevCatalogOnline { param([int]$TimeoutSeconds = 60) $uri = Resolve-HbUri $env:HOSTBADGER_KEV_URL $script:KevFeedUrl 'CISA KEV' return Get-CatalogText -Uri $uri -Label 'CISA KEV' -TimeoutSeconds $TimeoutSeconds } # The caller converts it (ConvertFrom-LolDrivers in lib\Checks.ps1). function Get-LolDriversOnline { param([int]$TimeoutSeconds = 180) $uri = Resolve-HbUri $env:HOSTBADGER_DRIVERS_URL $script:LolDriversUrl 'LOLDrivers' return Get-CatalogText -Uri $uri -Label 'LOLDrivers' -TimeoutSeconds $TimeoutSeconds } # malicious_extension_sentry (malext.io, CC BY 4.0): the CSV of extensions removed from the stores. The # caller converts it (ConvertFrom-ExtensionSentryCsv in lib\Checks.ps1). function Get-HostBadgerLatestVersion { # The version on the main branch ($script:HostBadgerVersion in its HostBadger.ps1), '' when it # cannot be read. One GET; nothing about this machine is sent. param([int]$TimeoutSeconds = 30) $uri = Resolve-HbUri $env:HOSTBADGER_UPDATE_URL $script:HostBadgerMainUrl 'HostBadger version' $text = Get-CatalogText -Uri $uri -Label 'HostBadger version' -TimeoutSeconds $TimeoutSeconds if ("$text" -match "\`$script:HostBadgerVersion = '(\d+(\.\d+)+)'") { return $Matches[1] } return '' } function Get-ExtensionCatalogOnline { param([int]$TimeoutSeconds = 120) $uri = Resolve-HbUri $env:HOSTBADGER_EXTENSIONS_URL $script:ExtensionSentryUrl 'browser extensions' return Get-CatalogText -Uri $uri -Label 'browser extensions' -TimeoutSeconds $TimeoutSeconds } # Public-exploit references (-ExploitsOnline): the full Metasploit module metadata (raw.githubusercontent.com, # BSD-3) and the full Exploit-DB index (gitlab.com, GPLv2 data). Both lists are downloaded whole, the same # whatever the hosts have, so the requests reveal nothing. The caller reduces them to a CVE -> references # map (ConvertTo-ExploitIndex in lib\Checks.ps1); only module names and Exploit-DB ids are kept, never # exploit code. HOSTBADGER_MSF_URL and HOSTBADGER_EXPLOITDB_URL are the test hooks. Returns @{ Msf; Edb } # (the raw text of each), or nothing for a list that did not come back. function Get-ExploitCatalogOnline { param([int]$TimeoutSeconds = 180) $msfUri = Resolve-HbUri $env:HOSTBADGER_MSF_URL $script:MsfMetadataUrl 'Metasploit modules' $edbUri = Resolve-HbUri $env:HOSTBADGER_EXPLOITDB_URL $script:ExploitDbUrl 'Exploit-DB index' $msf = Get-CatalogText -Uri $msfUri -Label 'Metasploit modules' -TimeoutSeconds $TimeoutSeconds $edb = Get-CatalogText -Uri $edbUri -Label 'Exploit-DB index' -TimeoutSeconds $TimeoutSeconds return @{ Msf = $msf; Edb = $edb } } # Chocolatey community package versions (-ChocoOnline): for each package of $script:ChocoProductMap # (lib\Checks.ps1), all of the list whatever the hosts have, GETs of its versions page by page ($skip) # until an empty page, half a second apart. The first page asks only for the three fields it needs; # later pages ask for whole entries, because the feed answers 503 to $select with paging. The feed # also limits how often it is called: a page is tried three times (3 and 10 seconds apart), and if it # still fails the download stops there instead of insisting. A package whose history did not come # back whole is left out rather than judged on part of it. Returns @{ id = versions }. function Get-ChocoCatalogOnline { param([int]$TimeoutSeconds = 30) $base = Resolve-HbUri $env:HOSTBADGER_CHOCO_URL $script:ChocoApiUrl 'Chocolatey' if (-not $base) { return @{} } $out = @{} foreach ($m in $script:ChocoProductMap) { $all = New-Object System.Collections.Generic.List[object] $skip = 0; $whole = $false for ($page = 0; $page -lt 50; $page++) { $uri = $base + "FindPackagesById()?id='" + $m.Id + "'" + $(if ($skip -gt 0) { "&`$skip=$skip" } else { "&`$select=Version,Published,IsPrerelease" }) $feed = $null foreach ($wait in 3, 10, 0) { $text = Get-CatalogText -Uri $uri -Label "Chocolatey ($($m.Id))" -TimeoutSeconds $TimeoutSeconds $feed = if ($text) { ConvertFrom-ChocoFeed $text } else { $null } if ($feed -or $wait -eq 0) { break } Start-Sleep -Seconds $wait } if (-not $feed) { break } if ($feed.Entries -eq 0) { $whole = $true; break } foreach ($v in $feed.Versions) { $all.Add($v) } $skip += $feed.Entries Start-Sleep -Milliseconds 500 } if ($whole) { if ($all.Count -gt 0) { $out[$m.Id] = @(Merge-ChocoVersions $all.ToArray()) }; continue } $left = @($script:ChocoProductMap | Select-Object -Skip ([array]::IndexOf(@($script:ChocoProductMap | ForEach-Object { $_.Id }), $m.Id)) | ForEach-Object { $_.Label }) Write-Host "Chocolatey is not answering (it limits how often it is called): stopped. Not judged: $($left -join ', '). Try again later; -ChocoFile reuses a copy kept by an earlier run." -ForegroundColor Yellow break } return $out } # Known vulnerabilities (-CveOnline): the CVEs of every CPE of $script:CveCpeMap (lib\Checks.ps1) from # the NVD CVE API 2.0, by product and never by version (the whole list, whatever the hosts have), page # by page; then the EPSS daily file (one GET, every CVE; only the scores of these CVEs are kept). # Without a key NVD allows 5 requests in 30 seconds, so requests are 6.5 s apart (1 s with # NVD_API_KEY, sent as the apiKey header and never written anywhere). A product whose CVEs did not # come back whole is left out. Returns @{ Products; Epss; EpssDate } (no product when nothing came back). function Get-CveCatalogOnline { param([int]$TimeoutSeconds = 120) $base = Resolve-HbUri $env:HOSTBADGER_NVD_URL $script:NvdApiUrl 'NVD' if (-not $base) { return @{ Products = @{}; Epss = @{}; EpssDate = '' } } $epssUri = Resolve-HbUri $env:HOSTBADGER_EPSS_URL $script:EpssUrl 'FIRST EPSS' $headers = @{}; if ($env:NVD_API_KEY) { $headers['apiKey'] = $env:NVD_API_KEY } $pause = if ($env:NVD_API_KEY) { 1000 } else { 6500 } if ($env:HOSTBADGER_NVD_PAUSE_MS) { $pause = [int]$env:HOSTBADGER_NVD_PAUSE_MS } $products = @{} $first = $true foreach ($label in @($script:CveCpeMap.Keys)) { $cves = New-Object System.Collections.Generic.List[object] $ids = New-Object 'System.Collections.Generic.HashSet[string]' $whole = $true foreach ($cpe in @($script:CveCpeMap[$label])) { $start = 0 do { if (-not $first) { Start-Sleep -Milliseconds $pause } $first = $false $uri = $base + '?virtualMatchString=' + [uri]::EscapeDataString("cpe:2.3:a:$cpe") + "&startIndex=$start" $page = $null foreach ($wait in 10, 30, 0) { $text = Get-CatalogText -Uri $uri -Label "NVD ($label)" -TimeoutSeconds $TimeoutSeconds -Headers $headers if ($text) { try { $page = ConvertFrom-NvdPage $text $script:CveCpeMap[$label] } catch { $page = $null } } if ($page -or $wait -eq 0) { break } Start-Sleep -Seconds $wait } if (-not $page) { $whole = $false; break } foreach ($c in $page.Cves) { if ($ids.Add($c.id)) { $cves.Add($c) } } $start = $page.Start + $page.Count } while ($page.Count -gt 0 -and $start -lt $page.Total) if (-not $whole) { break } } if ($whole) { $products[$label] = $cves.ToArray() } else { Write-Host "NVD: the CVEs of $label did not come back whole; it is not judged." -ForegroundColor Yellow } } $epss = @{}; $epssDate = '' $wanted = New-Object 'System.Collections.Generic.HashSet[string]' foreach ($l in $products.Keys) { foreach ($c in $products[$l]) { [void]$wanted.Add($c.id) } } if ($wanted.Count -gt 0) { $gz = Get-CatalogText -Uri $epssUri -Label 'FIRST EPSS' -TimeoutSeconds $TimeoutSeconds -Binary if ($gz) { try { $in = New-Object System.IO.MemoryStream(, $gz) $unzip = New-Object System.IO.Compression.GZipStream($in, [System.IO.Compression.CompressionMode]::Decompress) $reader = New-Object System.IO.StreamReader($unzip) $parsed = ConvertFrom-EpssCsv $reader.ReadToEnd() $wanted $reader.Dispose() $epss = $parsed.Scores; $epssDate = $parsed.Date } catch { Write-Host "EPSS file not readable: $($_.Exception.Message)" -ForegroundColor Yellow } } } return @{ Products = $products; Epss = $epss; EpssDate = $epssDate } } # The caller converts it (ConvertFrom-EolCatalog in lib\Checks.ps1). function Get-EolCatalogOnline { param([int]$TimeoutSeconds = 120) $uri = Resolve-HbUri $env:HOSTBADGER_EOL_URL $script:EolApiUrl 'endoflife.date' return Get-CatalogText -Uri $uri -Label 'endoflife.date' -TimeoutSeconds $TimeoutSeconds } # MaxAttempts 0 keeps trying until it works (Ctrl+C to stop). Only timeouts, 429 and 5xx are # retried, because a 400, 401 or 403 won't fix itself. function Invoke-GeminiAnalysis { param([string]$UserPrompt, [string]$ApiKey, [string]$Model, [int]$MaxAttempts = 3, [int]$TimeoutSeconds = 180) $unlimited = $MaxAttempts -le 0 $ofText = if ($unlimited) { '' } else { "/$MaxAttempts" } $canRetry = { param($n) $unlimited -or $n -lt $MaxAttempts } # Wait 2, 4, 8... seconds, at most a minute. $backoff = { param($n) [int][Math]::Min(60, [Math]::Pow(2, [Math]::Min($n, 6))) } $body = @{ system_instruction = @{ parts = @(@{ text = $script:AiSystemPrompt }) } contents = @(@{ role = 'user'; parts = @(@{ text = $UserPrompt }) }) generationConfig = @{ temperature = 0.2; responseMimeType = 'application/json' } } | ConvertTo-Json -Depth 10 # The key goes in a header, not in the URL, so it stays out of proxy logs. # HOSTBADGER_GEMINI_BASEURL points at an internal gateway (or at the test endpoint); it is # accepted only as https, or http on this machine, and a refused address sends nothing at all # rather than quietly falling back to Google with a prompt meant for a gateway. $base = (Resolve-HbUri $env:HOSTBADGER_GEMINI_BASEURL 'https://generativelanguage.googleapis.com' 'Gemini').TrimEnd('/') if (-not $base) { Write-Host 'Nothing was sent. Set HOSTBADGER_GEMINI_BASEURL to an https address, or clear it to use Gemini itself.' -ForegroundColor Red; return $null } $uri = "$base/v1beta/models/${Model}:generateContent" $transient = @(429, 500, 502, 503, 504) $result = $null for ($attempt = 1; $unlimited -or $attempt -le $MaxAttempts; $attempt++) { try { $result = Invoke-HttpPostWithSpinner -Uri $uri -JsonBody $body -Headers @{ 'x-goog-api-key' = $ApiKey } -Message "Contacting Gemini (attempt $attempt$ofText)" -TimeoutSeconds $TimeoutSeconds } catch { $inner = $_.Exception; $isTimeout = $false while ($inner) { if ($inner -is [System.Threading.Tasks.TaskCanceledException] -or $inner -is [TimeoutException]) { $isTimeout = $true; break }; $inner = $inner.InnerException } if ($isTimeout -and (& $canRetry $attempt)) { $wait = & $backoff $attempt Write-Host "Gemini timed out after $TimeoutSeconds s, retrying in $wait s..." -ForegroundColor Yellow Start-Sleep -Seconds $wait; continue } Write-Host "ERROR: Gemini call failed: $($_.Exception.Message)" -ForegroundColor Red return $null } if ($result.IsSuccess) { break } if ($transient -contains $result.StatusCode -and (& $canRetry $attempt)) { $wait = & $backoff $attempt Write-Host "Gemini HTTP $($result.StatusCode), retrying in $wait s..." -ForegroundColor Yellow Start-Sleep -Seconds $wait; $result = $null; continue } Write-Host "ERROR: Gemini call failed: HTTP $($result.StatusCode). $($result.Body)" -ForegroundColor Red # A model that stays busy: a smaller one is usually served (names change, so point at the list). if (@(429, 503) -contains $result.StatusCode) { Write-Host "HTTP $($result.StatusCode) (model overloaded). When Gemini keeps answering $($result.StatusCode), a smaller model often gets through: run again with, for example, -Model gemini-3.5-flash-lite. The current model names are listed in the Gemini models page (ai.google.dev/gemini-api/docs/models)." -ForegroundColor Yellow } return $null } if (-not $result) { return $null } try { $resp = $result.Body | ConvertFrom-Json } catch { Write-Host 'ERROR: Gemini response is not valid JSON.' -ForegroundColor Red; return $null } $raw = $resp.candidates[0].content.parts[0].text $raw = ($raw -replace '^\s*```(?:json)?', '') -replace '```\s*$', '' try { return ($raw | ConvertFrom-Json) } catch { Write-Host "ERROR: model did not return clean JSON:`n$raw" -ForegroundColor Red; return $null } } # -------------------------------------------------------------------------- # Put the real names back, and drop anything about a check that didn't fire, because the model can't # invent findings. # -------------------------------------------------------------------------- function ConvertFrom-AiResponse { param($Raw, $Pz, $Findings, [string]$Model) $valid = @{}; foreach ($f in $Findings) { $valid[$f.Type] = $true } $u = { param($t) Unprotect-AiText $Pz "$t" } $plan = @() foreach ($item in @($Raw.remediation_plan | Where-Object { $_ })) { $checks = @($item.checks | Where-Object { $valid.ContainsKey("$_") }) if ($checks.Count -eq 0) { continue } $effort = "$($item.effort)".ToLower(); if (@('low', 'medium', 'high') -notcontains $effort) { $effort = '' } $plan += [PSCustomObject]@{ Title = & $u ($item.title -replace '^\s*\d+[\.\)]\s*', '') Checks = $checks Objects = @($item.objects | Where-Object { $_ } | Select-Object -First 8 | ForEach-Object { & $u $_ }) Rationale = & $u $item.rationale Effort = $effort Caveats = & $u $item.caveats } } $monitoring = @() foreach ($m in @($Raw.monitoring | Where-Object { $_ })) { $monitoring += [PSCustomObject]@{ Checks = @($m.checks | Where-Object { $valid.ContainsKey("$_") }) EventIds = @($m.event_ids | Where-Object { "$_" -match '^\d{3,5}$' } | ForEach-Object { "$_" }) Guidance = & $u $m.guidance } } # Only hosts that exist: a token the map doesn't know is dropped. $hostPrio = @() foreach ($hp in @($Raw.host_priorities | Where-Object { $_ })) { $hosts = @($hp.hosts | Where-Object { $_ -and $Pz.Reverse.ContainsKey("$_") } | Select-Object -First 8 | ForEach-Object { & $u $_ }) if ($hosts.Count -eq 0) { continue } $rank = 0; try { $rank = [int]$hp.rank } catch { $rank = 0 } $hostPrio += [PSCustomObject]@{ Rank = $rank; Hosts = $hosts; Rationale = & $u $hp.rationale } } $hostPrio = @($hostPrio | Sort-Object { if ($_.Rank -gt 0) { $_.Rank } else { 9999 } }) $remScripts = @() foreach ($rs in @($Raw.remediation_scripts | Where-Object { $_ })) { $chk = "$($rs.check)" if (-not $valid.ContainsKey($chk)) { continue } $ps = & $u $rs.powershell if (-not $ps -and -not $rs.caveats) { continue } $remScripts += [PSCustomObject]@{ Check = $chk; PowerShell = $ps; Caveats = & $u $rs.caveats } } $triage = @() foreach ($tr in @($Raw.triage | Where-Object { $_ })) { $checks = @($tr.checks | Where-Object { $valid.ContainsKey("$_") }) if ($checks.Count -eq 0) { continue } $rank = 0; try { $rank = [int]$tr.rank } catch { $rank = 0 } $triage += [PSCustomObject]@{ Rank = $rank Checks = $checks Objects = @($tr.objects | Where-Object { $_ } | Select-Object -First 8 | ForEach-Object { & $u $_ }) Rationale = & $u $tr.rationale } } $triage = @($triage | Sort-Object { if ($_.Rank -gt 0) { $_.Rank } else { 9999 } }) return [PSCustomObject]@{ Model = $Model ExecutiveSummary = & $u $Raw.executive_summary RemediationPlan = $plan QuickWins = @($Raw.quick_wins | Where-Object { $_ } | Select-Object -First 5 | ForEach-Object { & $u $_ }) Monitoring = $monitoring ComparisonNarrative = if ($Raw.comparison_narrative) { & $u $Raw.comparison_narrative } else { '' } HostPriorities = $hostPrio RemediationScripts = $remScripts Triage = $triage MaskedIdentifiers = $Pz.Reverse.Count } } function ConvertTo-AiSectionHtml { param($AiResult) $H = { param($t) ConvertTo-HtmlSafe "$t" } $sb = New-Object System.Text.StringBuilder $w = { param($t) [void]$sb.AppendLine($t) } & $w "<div class='ai-section'><div class='ai-badge'>AI-assisted · $(& $H $AiResult.Model) · $($AiResult.MaskedIdentifiers) identifiers pseudonymized before sending</div>" # An HTML entity instead of a literal emoji, because PS 5.1 reads these BOM-less files as ANSI. & $w "<h2><span class='ai-robot' role='img' aria-label='AI' style='margin-right:8px'>🤖</span>AI summary and remediation plan</h2>" & $w "<p>$(& $H $AiResult.ExecutiveSummary)</p>" if ($AiResult.ComparisonNarrative) { & $w "<h3>Trend since previous run</h3><p>$(& $H $AiResult.ComparisonNarrative)</p>" } if (@($AiResult.QuickWins).Count -gt 0) { & $w '<h3>Quick wins</h3><ul>' foreach ($q in $AiResult.QuickWins) { & $w "<li>$(& $H $q)</li>" } & $w '</ul>' } if (@($AiResult.HostPriorities).Count -gt 0) { & $w "<h3>Hosts to work on first</h3><div class='table-wrap'><table><tr><th>#</th><th>Hosts</th><th>Why</th></tr>" $i = 0 foreach ($p in $AiResult.HostPriorities) { $i++ $rank = if ($p.Rank -gt 0) { $p.Rank } else { $i } & $w "<tr class='data-row'><td>$rank</td><td>$(& $H ($p.Hosts -join ', '))</td><td>$(& $H $p.Rationale)</td></tr>" } & $w '</table></div>' } if (@($AiResult.RemediationPlan).Count -gt 0) { & $w '<h3>Suggested remediation order</h3><ol>' foreach ($p in $AiResult.RemediationPlan) { $effort = if ($p.Effort) { " <span class='check-id'>effort: $($p.Effort)</span>" } else { '' } $objs = if (@($p.Objects).Count -gt 0) { "<br><span class='meta'>Objects: $(& $H ($p.Objects -join ', '))</span>" } else { '' } $cav = if ($p.Caveats) { "<br><span class='meta'>Caveats: $(& $H $p.Caveats)</span>" } else { '' } & $w "<li><b>$(& $H $p.Title)</b>$effort<br>$(& $H $p.Rationale)<br><span class='meta'>Checks: $(($p.Checks | ForEach-Object { "<code>$_</code>" }) -join ' ')</span>$objs$cav</li>" } & $w '</ol>' } if (@($AiResult.Monitoring).Count -gt 0) { & $w "<h3>Monitoring until fixed</h3><div class='table-wrap'><table><tr><th>Checks</th><th>Event IDs</th><th>Guidance</th></tr>" foreach ($m in $AiResult.Monitoring) { & $w "<tr class='data-row'><td>$(($m.Checks | ForEach-Object { "<code>$_</code>" }) -join ' ')</td><td>$(& $H ($m.EventIds -join ', '))</td><td>$(& $H $m.Guidance)</td></tr>" } & $w '</table></div>' } if (@($AiResult.Triage).Count -gt 0) { & $w "<h3>Exploitability triage (fix order for this fleet)</h3><div class='table-wrap'><table class='ai-triage'><tr><th>#</th><th>Checks</th><th>Objects</th><th>Why</th></tr>" $i = 0 foreach ($t in $AiResult.Triage) { $i++ $rank = if ($t.Rank -gt 0) { $t.Rank } else { $i } & $w "<tr class='data-row'><td>$rank</td><td>$(($t.Checks | ForEach-Object { "<code>$_</code>" }) -join ' ')</td><td>$(& $H ($t.Objects -join ', '))</td><td>$(& $H $t.Rationale)</td></tr>" } & $w '</table></div>' } if (@($AiResult.RemediationScripts).Count -gt 0) { & $w '<h3>Remediation scripts (review before running)</h3>' & $w "<p class='meta'>Generated PowerShell using native cmdlets, with names as placeholders. HostBadger never runs it. Treat it as a starting point: read it, substitute the real values, and test on a pilot host first.</p>" foreach ($s in $AiResult.RemediationScripts) { & $w "<div style='margin:10px 0'><span class='check-id'>Fix for <code>$(& $H $s.Check)</code></span>" if ($s.PowerShell) { & $w "<div class='ai-script'>$(& $H $s.PowerShell)</div>" } if ($s.Caveats) { & $w "<div class='meta'>Caveats: $(& $H $s.Caveats)</div>" } & $w '</div>' } } & $w "<p class='meta'>Generated by a language model from findings computed locally. Verify every recommendation before acting; the deterministic sections of this report are authoritative.</p></div>" return $sb.ToString() } |