HostBadger.psm1

# HostBadger 3.4 - the module face of the scripts next to this file.
#
# GENERATED by tools\New-HostBadgerModule.ps1 from the scripts themselves. Do not edit: a change
# here is lost at the next build, and the parameters belong to the scripts. Each function runs
# its script in process, so the script keeps its own $PSScriptRoot and finds lib\ and data\.

$script:HbCommon = @([System.Management.Automation.PSCmdlet]::CommonParameters) +
    @([System.Management.Automation.PSCmdlet]::OptionalCommonParameters)

function Get-HostBadgerPath {
<#
.SYNOPSIS
    The folder this module was installed in, where the scripts, lib\, data\ and the examples are.
.DESCRIPTION
    Use it to reach a file of the module from your own script: the collector to copy to a host, the
    example policy, the synthetic fleet the README analyzes.
.PARAMETER ChildPath
    A path inside the module folder. Optional.
.EXAMPLE
    Copy-Item (Get-HostBadgerPath 'Collect-HostSnapshot.ps1') \\deploy\scripts
    Takes the collector out of the module: one self-contained file to run on the hosts.
.EXAMPLE
    Invoke-HostBadger -Snapshot (Get-HostBadgerPath 'examples\fleet')
    Analyzes the synthetic fleet that ships with the module.
#>

    param([string]$ChildPath = '')
    if ($ChildPath) { Join-Path $PSScriptRoot $ChildPath } else { $PSScriptRoot }
}

function Invoke-HostBadger {
<#
.SYNOPSIS
    HostBadger: Windows host hardening analyzer. Reads snapshots written by
    Collect-HostSnapshot.ps1 and writes an HTML report, a findings CSV and,
    optionally, JSON Lines for a SIEM.

.DESCRIPTION
    Collect once on each host (as SYSTEM or as a local administrator, through
    any tool that runs a .ps1: an EDR's live response, an RMM, Configuration
    Manager or Intune, a startup script, PowerShell remoting) and analyze
    anywhere. This script needs no
    module and no rights on the hosts, and it only goes on the network if you
    ask for the optional AI step. Give it one snapshot, a zip or a folder of
    them, and it reports every host in one place.

    If the data for a check couldn't be collected on a host (a section that
    failed, Defender in passive mode, ACLs skipped), the check is listed as
    "not evaluated" for that host. It is never counted as clean.

.PARAMETER Snapshot
    Snapshot files (hostsnapshot_*.json or .zip) or folders holding them
    (searched recursively). Several can be given.
.PARAMETER OutDir
    Folder for the output files. Default .\output. A -OutHtml / -OutCsv /
    -OutJsonl / -OutRemediation given as a bare file name lands here; a name
    with a folder, or an absolute path, is used exactly as given. The folder
    is created if it does not exist.
.PARAMETER OutHtml
    HTML report. Default hostbadger_<time>.html, written in -OutDir (.\output).
.PARAMETER SkipStig
    Leave out the DISA STIG checks (about 500 registry rules, one finding
    each). The other checks are not affected.
.PARAMETER HideCis
    Do not list the CIS-based findings in the HTML report (the compliance
    charts still count them; the CSV and JSON Lines keep them).
.PARAMETER HideStig
    Same for the DISA STIG findings.
.PARAMETER AiIncludeStig
    Also send the DISA STIG findings to Gemini. Without it they stay out of the
    prompt: there can be hundreds per host, and a prompt that large may make
    Gemini time out.
.PARAMETER KevFile
    CISA Known Exploited Vulnerabilities catalog (known_exploited_vulnerabilities.json)
    that you downloaded. Installed software is matched to it by vendor and product;
    the catalog has no version ranges, so a match is a lead to verify, not a verdict.
.PARAMETER KevOnline
    Download that catalog now. One HTTPS GET to
    www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json;
    nothing is sent. The copy is kept next to the report (<report>_kev.json).
.PARAMETER DriversOnline
    Download the LOLDrivers catalog of known vulnerable and malicious drivers now,
    instead of using the copy shipped in data\vulnerable-drivers.json. One HTTPS
    GET of about 30 MB to www.loldrivers.io/api/drivers.json; nothing is sent.
    The converted copy is kept next to the report (<report>_drivers.json).
.PARAMETER DriversFile
    A LOLDrivers catalog you already have, instead of the copy in data\: the
    drivers.json from www.loldrivers.io, or the <report>_drivers.json that
    -DriversOnline keeps next to a report. No network.
.PARAMETER ExtensionsOnline
    Download the current list of browser extensions removed from the Chrome Web
    Store and Edge Add-ons (malicious_extension_sentry by toborrm9, malext.io,
    CC BY 4.0, updated daily) instead of the copy shipped in
    data\malicious-extensions.json. One HTTPS GET of about 2 MB to
    raw.githubusercontent.com; nothing is sent. The converted copy is kept next
    to the report (<report>_extensions.json).
.PARAMETER ExtensionsFile
    A list you already have instead of the shipped copy: the
    malicious_extensions_detailed.csv of malicious_extension_sentry, or the
    <report>_extensions.json that -ExtensionsOnline keeps next to a report. No
    network.
.PARAMETER EolOnline
    Download software lifecycle data from endoflife.date now (MIT licensed): the
    release lines of Python, Node.js, .NET, Office, Exchange, Oracle Java, Firefox,
    Chrome, Notepad++, PowerShell, VirtualBox and Wireshark, with their end of
    support and latest version. One HTTPS GET of about 3 MB to
    endoflife.date/api/v1/products/full; nothing is sent. Turns on
    software_outdated and gives software_eol current dates. The reduced copy is
    kept next to the report (<report>_eol.json).
.PARAMETER EolFile
    endoflife.date data you already have: the <report>_eol.json that -EolOnline
    keeps, or an API v1 response (/products/full or one product). No network.
.PARAMETER ChocoOnline
    Download the version history of programs that endoflife.date does not cover
    (7-Zip, VLC, Git for Windows, GIMP, WinSCP, PuTTY, FileZilla, KeePass,
    Audacity, Mullvad VPN, OBS Studio, AnyDesk) from the Chocolatey community
    repository: a few HTTPS GETs per package to community.chocolatey.org/api/v2/,
    the same list whatever the hosts have; nothing is sent. Turns on
    software_outdated for them. The copy is kept next to the report
    (<report>_choco.json).
.PARAMETER ChocoFile
    The <report>_choco.json that -ChocoOnline keeps. No network.
.PARAMETER CveOnline
    Download the known vulnerabilities (CVEs) of Python, Node.js, .NET, Notepad++,
    PowerShell 7, VirtualBox, Wireshark, 7-Zip, VLC, Git, GIMP, WinSCP, PuTTY,
    FileZilla, KeePass, Audacity, Mullvad VPN and AnyDesk from the NVD CVE API
    (services.nvd.nist.gov, one GET per product and page, by product and never by
    version, the same list whatever the hosts have; about 2.5 minutes without a
    key, faster with an NVD API key in NVD_API_KEY), then the FIRST EPSS daily
    file (epss.empiricalsecurity.com, one GET of about 3 MB). Nothing about the
    hosts is sent. Turns on software_cve. The reduced copy is kept next to the
    report (<report>_cve.json).
.PARAMETER CveFile
    The <report>_cve.json that -CveOnline keeps. No network.
.PARAMETER ExploitsOnline
    Download the public-exploit references and note, next to each CVE that
    software_cve already found by version, whether a Metasploit module or an
    Exploit-DB entry exists. A prioritization signal like KEV and EPSS: only the
    module name and the Exploit-DB id are kept, never exploit code. Two HTTPS
    GETs, nothing is sent: the Metasploit module metadata from
    raw.githubusercontent.com (rapid7/metasploit-framework, BSD-3) and the
    Exploit-DB index from gitlab.com (exploit-database, GPLv2 data), the whole
    lists whatever the hosts have. A ready Metasploit exploit module raises the
    CVE finding to High. The reduced copy is kept next to the report
    (<report>_exploits.json). Has an effect only together with the CVE data.
.PARAMETER ExploitFile
    The <report>_exploits.json that -ExploitsOnline keeps. No network.
.PARAMETER SoftwareGraceDays
    Days a program may take to install a new release before software_outdated
    flags it (default 30).
.PARAMETER SnapshotPassword
    Password of snapshots encrypted with the collector's -EncryptPassword
    (.hbx). Without it, HostBadger asks for it when it finds such a snapshot.
.PARAMETER SnapshotPfx
    A .pfx with the private key for snapshots encrypted with the collector's
    -EncryptCertificate. Without it, the private key is looked for in the
    certificate stores of the current user and of the computer.
.PARAMETER SnapshotPfxPassword
    Password of the .pfx (asked for when needed).
.PARAMETER PerHost
    Also write one HTML report per host next to the fleet report
    (<OutHtml name>_<HOST>.html), when there are two hosts or more.
.PARAMETER OutCsv
    Findings CSV. Default: next to the HTML report.
.PARAMETER OutLog
    Run log: the settings of the run (passwords and the Gemini key left out)
    and everything it prints. Default: next to the HTML report, same name,
    .log.
.PARAMETER NoLog
    Write no run log.
.PARAMETER OutJsonl
    JSON Lines for a SIEM (findings, resolved findings with -CompareTo, one
    summary per host). Not written unless given.
.PARAMETER CompareTo
    Findings CSV of an earlier run: new and resolved findings are shown.
.PARAMETER History
    Score history file (CSV, created when missing): every run adds the score of
    each host, one line per host and snapshot (a snapshot analyzed again
    replaces its line; each host keeps its newest 100). The report then shows
    how each host's score moved over the runs, not only against the previous
    one, and JSON Lines gets score_previous and score_change. The guided menu
    and the window keep it in their output folder (hostbadger-history.csv).
.PARAMETER Threads
    How many hosts to analyze at once. Default 0: up to 4 when there are
    enough hosts to pay for it (from 16 hosts), else one at a time. 1
    analyzes one host at a time. The result is the same either way.
.PARAMETER ExceptionsFile
    JSON list of accepted risks: [{ "type", "host", "object", "reason",
    "owner", "expires" }], host and object accept "*".
.PARAMETER PolicyFile
    The organization's own policy (JSON): { "name": "...", "disabledChecks":
    [ "check_type" | "stig_*" | { "check": "...", "reason": "..." } ] }. The
    checks it turns off do not run, do not count in the score, and the report
    lists them with the reason. A name that matches no check stops the run.
.PARAMETER AllowedAdmins
    Members of the local Administrators group that belong there (names as
    "DOMAIN/Group", the bare name, or SIDs). Domain Admins and the built-in
    Administrator are always expected.
.PARAMETER ExpectedEdr
    The EDR every host should run, for example CrowdStrike or SentinelOne (more than one is
    fine). A host without it gets a High finding. Known names: CrowdStrike, SentinelOne,
    DefenderForEndpoint, CarbonBlack, CortexXDR, Sophos, TrendMicro, Trellix, ESET, Symantec,
    Elastic, Cybereason, Cylance, Bitdefender, Huntress. Any other text is looked for in the
    names of the services. Without it, only a host with no known EDR at all is reported.
.PARAMETER ExtraEdrServices
    Names of services that belong to an EDR that HostBadger does not know, so that they are
    counted as an agent (and flagged if they are stopped).
.PARAMETER AllowedExtensions
    Optional: the browser extensions the organization approves, by id or name
    (wildcards allowed, e.g. 'uBlock Origin', 'nngceckbapebfimnlniiiahkandclblb').
    The other enabled extensions are reported as browser_extension_not_allowed;
    without the list, those that can read every website are reported as Low.
.PARAMETER AllowedRemoteTools
    The remote access tools the organization approves (AnyDesk, TeamViewer, ScreenConnect, VNC,
    NinjaOne...: the tool's key or part of its name). Others found are Medium; without the list,
    every remote access tool found is Low, to be verified.
.PARAMETER MaxPatchAgeDays
    Days without an installed update before updates_stale (default 45).
.PARAMETER MaxSignatureAgeDays
    Days before Defender signatures are stale (default 7).
.PARAMETER SupportWarningDays
    Warn this many days before the OS goes out of support (default 90).
.PARAMETER DormantAccountDays
    Days without a logon before an enabled local account counts as dormant
    (default 180).
.PARAMETER OutRemediation
    Optional folder: besides the fix scripts that the report already shows under
    each check, write one remediate_<host>.ps1 per host with all of that host's
    fixes in one file, for scripted rollouts. It previews unless run with -Apply,
    writes a rollback file, and HostBadger never runs it.
.PARAMETER RemediationProfile
    Optional, with -OutRemediation: add a remediation profile to every
    remediate_<host>.ps1, on top of the fixes of the findings. Essential (CIS
    Level 1 and Essential Eight Maturity Level One settings safe on any machine
    that change nothing the user sees or does: the fixes that would, such as
    CTRL+ALT+DEL, hiding the last user name, screen lock or extra UAC prompts,
    are listed in the script and left to Recommended),
    Recommended (Essential, plus the rest of CIS Level 1 for managed machines and
    Essential Eight Maturity Level Two: attack surface reduction rules in block
    mode) or Strict (Recommended, plus CIS Level 2, Essential Eight Maturity
    Level Three, opinionated hardening and the removal of preinstalled apps).
    The settings come from data\remediation-profiles.json, filtered by the host's
    role; each one quotes its rule. Some Strict changes cannot be undone by the
    rollback file: the script marks them NOT REVERSIBLE.
.PARAMETER RemediationDebloat
    Optional, with -OutRemediation: debloat. Adds the removal of the
    preinstalled apps (games, consumer apps, trials; workstations) and the unused
    consumer services and components (Xbox services, Retail Demo, Windows
    Insider, Windows Fax and Scan, Work Folders, Steps Recorder...: the items
    marked debloat in data\remediation-profiles.json) to the scripts, with or
    without a profile (Strict already includes it). The apps are not
    reversible: they come back only from the Microsoft Store.
.PARAMETER RemediationPrivacy
    Optional, with -OutRemediation: add the privacy and telemetry settings of
    every profile tier (data\remediation-profiles.json, category privacy) to the
    scripts, with or without a profile. With -RemediationDebloat and no profile it
    gives "debloat and telemetry only": no hardening setting is added.
.PARAMETER RemediationNoApps
    Optional, with -OutRemediation: leave the removal of preinstalled apps out of
    the scripts even with -RemediationProfile Strict or -RemediationDebloat. The
    guided menu (option 6) uses it: it lists the apps found on the machine and
    asks for them itself.
.PARAMETER RemediationOnlyProfile
    Optional, with -OutRemediation: leave the safe fixes of the findings out of the
    scripts, so they hold only what -RemediationProfile, -RemediationPrivacy and
    -RemediationDebloat add. "Debloat and telemetry only" in the guided menu uses
    it with -RemediationPrivacy and -RemediationDebloat.
.PARAMETER SendToAI
    Optional: after the report is saved, send the findings to Gemini for an
    executive summary and a remediation plan, and add them to the report.
    Without this switch (or -AiDryRun) nothing is ever sent and HostBadger
    never asks. Host names, domains, accounts, groups, SIDs, paths, service,
    task and autorun names and addresses are replaced by tokens first, the
    collector's error messages are never included, and a leak check refuses
    to send if any real name survived. The exact prompt is saved as
    <report>_ai_prompt.txt, the reply as <report>_ai_response.json.
.PARAMETER AiConfirm
    With -SendToAI: show what will be sent and ask y/N first.
.PARAMETER AiDryRun
    Path: write the exact pseudonymized prompt that would be sent and send
    nothing. Useful for a privacy review before enabling the AI step.
.PARAMETER Nis2Acn
    Optional, for organizations in Italy: add the NIS2 basic security measures
    of the Agenzia per la Cybersicurezza Nazionale (Determinazione 379907/2025,
    D.Lgs. 138/2024) to the report: a dashboard panel with the requirements a
    host shows evidence against, a row in the summary by framework, the
    measures under each check, and acn_unmet / acn_not_judged in JSON Lines.
.PARAMETER AiLater
    Used by the guided menu: without -SendToAI or -AiDryRun, keep the analysis
    in this PowerShell session's memory (never on disk) so that a following
    run with -AiContinue can add the AI step without analyzing again.
.PARAMETER AiContinue
    Run only the AI step (with -SendToAI or -AiDryRun and their options) on
    the analysis kept by an -AiLater run in the same PowerShell session, and
    add its section to that report.
.PARAMETER AiReport
    Run only the AI step (with -SendToAI or -AiDryRun and their options) on a
    report already written: its findings come from the report and its CSV,
    nothing is analyzed and no catalog is read or downloaded, and the AI
    section is added to that report. -Snapshot must still reach the snapshots
    of its hosts, as collected then: their names, accounts and paths are what
    the prompt replaces with tokens, so without them nothing is written or
    sent. A file or folder works; only the files of those hosts are read.
.PARAMETER ApiKey
    Gemini API key. Defaults to $env:GEMINI_API_KEY.
.PARAMETER Model
    Gemini model name. Defaults to gemini-3.8-flash.
.PARAMETER AiMaxAttempts
    How many times to try Gemini on a timeout or a busy server (429/5xx).
    Default 3; 0 keeps trying until it works (Ctrl+C to stop).

.EXAMPLE
    Invoke-HostBadger -Snapshot .\snapshots\ -OutHtml fleet.html
.EXAMPLE
    Invoke-HostBadger -Snapshot hostsnapshot_PC01_20261006101500.zip -CompareTo last_month.csv -OutJsonl siem.jsonl
#>

    [CmdletBinding()]
    param(
        [string[]]$Snapshot,
        [string]$OutDir = '',
        [string]$OutHtml = '',
        [string]$OutCsv = '',
        [string]$OutJsonl = '',
        [string]$CompareTo = '',
        [string]$ExceptionsFile = '',
        [string]$PolicyFile = '',
        [string[]]$AllowedAdmins = @(),
        [int]$MaxPatchAgeDays = 45,
        [int]$MaxSignatureAgeDays = 7,
        [int]$SupportWarningDays = 90,
        [int]$DormantAccountDays = 180,
        [int]$MaxCachedLogonsWorkstation = 4,
        [int]$MaxCachedLogonsServer = 1,
        [int]$MinSecurityLogKB = 196608,
        [string[]]$ExpectedEdr = @(),
        [string[]]$ExtraEdrServices = @(),
        [string[]]$AllowedRemoteTools = @(),
        [string[]]$AllowedExtensions = @(),
        [string]$OutRemediation = '',
        [ValidateSet('', 'Essential', 'Recommended', 'Strict')]
        [string]$RemediationProfile = '',
        [switch]$RemediationDebloat,
        [switch]$RemediationPrivacy,
        [switch]$RemediationNoApps,
        [switch]$RemediationOnlyProfile,
        [switch]$PerHost,
        [switch]$SkipStig,
        [string]$KevFile = '',
        [switch]$KevOnline,
        [switch]$DriversOnline,
        [string]$DriversFile = '',
        [switch]$ExtensionsOnline,
        [string]$ExtensionsFile = '',
        [switch]$EolOnline,
        [string]$EolFile = '',
        [switch]$ChocoOnline,
        [string]$ChocoFile = '',
        [switch]$CveOnline,
        [string]$CveFile = '',
        [switch]$ExploitsOnline,
        [string]$ExploitFile = '',
        [int]$SoftwareGraceDays = 30,
        [System.Security.SecureString]$SnapshotPassword,
        [string]$SnapshotPfx = '',
        [System.Security.SecureString]$SnapshotPfxPassword,
        [switch]$HideCis,
        [switch]$HideStig,
        [switch]$AiIncludeStig,
        [switch]$SendToAI,
        [switch]$AiConfirm,
        [string]$AiDryRun = '',
        [switch]$AiLater,
        [switch]$AiContinue,
        [string]$AiReport = '',
        [switch]$Nis2Acn,
        [string]$ApiKey = $env:GEMINI_API_KEY,
        [string]$Model = 'gemini-3.8-flash',
        [int]$AiMaxAttempts = 3,
        [string]$OutLog = '',
        [switch]$NoLog,
        [string]$History = '',
        [ValidateRange(0, 256)]
        [int]$Threads = 0
    )
    $hbScript = Join-Path $PSScriptRoot 'HostBadger.ps1'
    & $hbScript @PSBoundParameters
}

function New-HostSnapshot {
<#
.SYNOPSIS
    Takes a read-only snapshot of the local Windows host's security settings
    and writes it as JSON (and a zip), for HostBadger.ps1 to analyze anywhere.

.DESCRIPTION
    One self-contained file, with no module, no prompt and every parameter
    optional, so any tool that can run a .ps1 on your hosts can run it: an
    EDR's live response (a CrowdStrike Falcon cloud script, for example), an
    RMM, Configuration Manager or Intune scripts, a Group Policy startup
    script, PowerShell remoting (Invoke-Command -FilePath). Through
    CrowdStrike Real Time Response:

        runscript -CloudFile="Collect-HostSnapshot" -Timeout=600
        get C:\Windows\Temp\HostBadger\hostsnapshot_<host>_<time>.zip

    It only reads. That means registry values, CIM classes, the Defender,
    SMB, firewall, BitLocker, local account and scheduled task cmdlets, file
    ACLs, the Authenticode signer of the DLLs that LSASS, the print spooler
    and netsh load, the machine's root certificates and saved Wi-Fi profiles
    (never a key), setup answer files, Group Policy Preferences copies and
    PowerShell histories (only how many values or lines look like a secret,
    never the secret), "auditpol /backup" and "secedit /export" (the last two
    write a temporary file that is deleted right away). It changes no setting, starts
    no process and opens no network connection of its own. The one exception
    is the opt-in -CheckUpdates, where the Windows Update Agent contacts its
    update server. Test-HostBadgerSafety.ps1 checks this claim against the code.

    It runs as SYSTEM (live response, deployment tools, startup scripts) or
    as a local administrator. As a standard
    user it still runs, but some sections (Defender exclusions, BitLocker,
    the audit policy, the security policy, the security log) can't be read.
    Those failures are recorded in meta.collectionErrors, and the analyzer
    lists the checks that depend on them as "not evaluated", never as clean.

    Command lines of services, scheduled tasks and Run keys are kept, because
    the privilege escalation checks need them. Anything that looks like a
    password argument is masked first (-p, /password:, pwd=...).

.PARAMETER OutDir
    Where to write. Default C:\Windows\Temp\HostBadger when running elevated,
    otherwise %TEMP%\HostBadger.
.PARAMETER NoZip
    Keep only the JSON.
.PARAMETER SkipAcl
    Don't read file ACLs of service, task and Run key executables (faster on
    hosts with thousands of services; the "writable by users" checks are then
    not evaluated).
.PARAMETER CheckUpdates
    Ask the Windows Update Agent which updates are still missing. This is the
    only option that causes network traffic: the agent contacts the WSUS server
    set by policy (WUServer) or, without one, Microsoft Update (HTTPS to
    *.update.microsoft.com). Off by default; without it the pending updates are
    simply not part of the snapshot.
.PARAMETER NamedPipes
    Also read who may write to each named pipe, to find the ones everyone can
    write to. Each pipe is opened for reading for a moment (one of its
    instances is taken, then given back at once; busy ones are skipped), so it
    is off by default; without it that check is not evaluated.
.PARAMETER EncryptPassword
    Encrypt the snapshot with this password: AES-256 with an HMAC-SHA256, keys
    from PBKDF2. The output is hostsnapshot_<host>_<time>.hbx and nothing is
    written in clear (the zip is built in memory). HostBadger.ps1 asks for the
    password, or takes -SnapshotPassword. Mind that a password given on a
    command line ends up in the command log of the tool that ran it (EDR,
    RMM, deployment job); -EncryptCertificate avoids
    that.
.PARAMETER EncryptCertificate
    Encrypt the snapshot to a certificate instead (CMS, AES-256): the path of
    a .cer file (DER or PEM), or the thumbprint of a certificate in the
    LocalMachine or CurrentUser store. Only the public key is needed here; the
    analyzer opens the file with the private key (certificate store or -SnapshotPfx).
#>

    [CmdletBinding()]
    param(
        [string]$OutDir = '',
        [switch]$NoZip,
        [switch]$SkipAcl,
        [switch]$CheckUpdates,
        [string]$EncryptPassword = '',
        [string]$EncryptCertificate = '',
        [switch]$NamedPipes
    )
    $hbScript = Join-Path $PSScriptRoot 'Collect-HostSnapshot.ps1'
    & $hbScript @PSBoundParameters
}

Set-Alias -Name Collect-HostSnapshot -Value New-HostSnapshot

function Start-HostBadger {
<#
.SYNOPSIS
    HostBadger launcher: one guided entry point for collection and analysis.

.DESCRIPTION
    A small menu, so nobody has to remember parameters:

      1 Collect this machine (Collect-HostSnapshot.ps1, read-only)
      2 Analyze snapshots (HostBadger.ps1: one snapshot, a zip or a folder of them)
      3 Collect and analyze this machine
      4 Analyze with an AI summary (Gemini; names replaced by tokens first)
      5 Safety review (Test-HostBadgerSafety.ps1: what the scripts can do)
      6 Remediate this machine (collect, analyze, preview the fixes, apply after YES)
      7 Restore a remediation backup (put back the values a remediation changed)
      8 Global settings (the answers a run asks every time, saved)

    Options 1 to 5 change nothing on the machine. Option 6 is the only part of
    HostBadger that changes settings, and only on this machine, as
    administrator: it shows what the fix script would change, asks you to type
    YES, creates a System Restore point where Windows has one, and the script
    writes the previous value of every setting to a rollback file that option 7
    puts back. Removing preinstalled apps is asked one group at a time and
    cannot be rolled back (they come back from the Microsoft Store). The AI step
    sends nothing unless you choose it, and shows you the exact text first when
    you ask for a dry run.

    The answers of a run are saved as you give them (output\hostbadger-wizard-
    state.json, never passwords or keys), so a run stopped halfway can be
    resumed at the next start; a finished run removes the file. At the end of
    an analysis the menu offers to open the report in the default browser.

    Global settings (menu 8) keep the answers that are the same at every run
    (output\hostbadger-settings.json: report folder, STIG and CIS, catalogs,
    JSON Lines, remediation scripts, exceptions, allowed administrators, EDR,
    the AI step, and for a collection: snapshot folder, ACLs, missing updates
    and encryption). When the file exists, each run asks once whether to use
    them; with yes those questions are skipped, and the analysis lists every
    answer before it runs, still changeable for that run. Passwords and the
    Gemini key are never saved.

    Each session is logged in output\hostbadger-menu_<time>.log: the questions,
    the answers typed and what the collection and the analysis printed (each
    analysis also writes <report>.log next to its report). Passwords and the
    Gemini key are typed hidden and never reach a log.

    At the start the menu says whether it runs as administrator. If not, it
    marks the options that need it and, at an interactive console, offers to
    restart itself elevated (Windows asks you to confirm, UAC).

    Catalogs downloaded by an earlier analysis (CISA KEV, LOLDrivers,
    endoflife.date, Chocolatey, NVD/EPSS: <report>_kev.json and the like, next
    to the report or in .\output) are offered again: Enter uses the newest kept
    copy, O downloads a fresh one.

    Double-click use: powershell.exe -NoProfile -ExecutionPolicy Bypass -File Start-HostBadger
    (the policy is bypassed for that process only; a policy enforced by GPO still wins).

.EXAMPLE
    Start-HostBadger
#>

    [CmdletBinding()]
    Param(
        # Set by the restart as administrator: Windows starts an elevated process in System32, so the new
        # window is brought back to the folder the menu was started from.
        [string]$StartIn = ''
    )
    $hbScript = Join-Path $PSScriptRoot 'Start-HostBadger.ps1'
    & $hbScript @PSBoundParameters
}

function Start-HostBadgerGui {
<#
.SYNOPSIS
    HostBadger in a window: collect and analyze this machine, or analyze
    snapshots already collected; add the AI summary, run the safety review,
    check for a newer HostBadger.

.DESCRIPTION
    The same steps as the guided menu (Start-HostBadger.ps1), with the answers
    as a form. It runs Collect-HostSnapshot.ps1 and HostBadger.ps1 with the
    parameters chosen here, in the background of this window, and shows what
    they print. The report is the usual HTML file, opened in the browser; the
    Results tab shows its findings (from the CSV next to it) by category, with
    filters and the details of each one.

    The one step that changes the machine is "Fix what the analysis finds" on
    this machine: the fix script is previewed, then applied only after a
    warning and Yes (as administrator, with a restore point and a rollback
    file). The one thing Settings can write outside HostBadger's folder is what you ask it
    to remember: GEMINI_API_KEY / NVD_API_KEY as environment variables of your
    Windows account (never in the settings file).

    Network: only what you ask for. "Download" on a catalog makes the analysis
    fetch it (the address is named next to it); "Send to Gemini" sends the
    pseudonymized findings; "Check for updates" asks the HostBadger repository
    on GitHub (git fetch of a git clone, otherwise one GET of HostBadger.ps1
    from raw.githubusercontent.com); "Update" runs git pull --ff-only origin
    main in a git clone on main with no local changes. The same check runs at
    every start only if it is ticked in Settings (off by default).

    The saved settings of the guided menu (output\hostbadger-settings.json,
    menu 8) fill the form. Settings writes them back, and each run saves the
    choices of the form, so the window opens as it was left.
.PARAMETER NoShow
    Build the windows without showing them, then close (used by the tests).
.PARAMETER StartIn
    The folder to work in. Restart as administrator passes the folder the window
    was started from: an elevated process starts in System32, where it would
    find neither the settings nor the kept catalogs.
#>

    [CmdletBinding()]
    param([switch]$NoShow, [string]$StartIn = '')
    $hbScript = Join-Path $PSScriptRoot 'Start-HostBadgerGui.ps1'
    & $hbScript @PSBoundParameters
}

function Test-HostBadgerSafety {
<#
.SYNOPSIS
    Reads the HostBadger scripts (without running them) and shows everything
    they can do: every command they call, every file they write, every web
    address in them. Fails if anything falls outside the reviewed list.
 
.DESCRIPTION
    This is for whoever has to approve running Collect-HostSnapshot.ps1 on
    endpoints as SYSTEM. It uses the PowerShell parser, so it sees every
    command that is called, not just the ones a text search would find.
 
    It fails (exit code 1) when it finds:
      - a command that is not on the reviewed list below, so that a new one
        can't slip in unnoticed;
      - a command that changes the system, such as Set-, New-, Remove-, Add-,
        Enable-, Disable-, Start- or Stop- on Defender, the firewall, services,
        tasks, the registry, accounts, BitLocker or SMB. The only exceptions
        are New-Item, Remove-Item and Set-Content on HostBadger's own files;
      - auditpol with anything other than /get or /backup;
      - sc.exe with anything other than sdshow (it prints a service's permissions);
      - secedit with anything other than /export. /configure, /import,
        /analyze, /generaterollback and /validate change or rebuild policy;
      - ADSI or COM used for more than reading (InvokeMember with anything
        other than GetProperty, or a COM object other than
        Microsoft.Update.Session);
      - tricks that hide code at run time: Invoke-Expression, encoded
        commands, Base64, downloads, compiled C#, starting processes, CIM
        method calls;
      - a web address other than the MITRE ATT&CK links in the report and, in
        lib\AI.ps1 only, the Gemini endpoint of the optional AI step and the
        CISA KEV catalog address (www.cisa.gov, -KevOnline), the LOLDrivers
        catalog address (www.loldrivers.io, -DriversOnline), the software
        lifecycle address (endoflife.date, -EolOnline), the Chocolatey
        package feed (community.chocolatey.org, -ChocoOnline), the NVD CVE
        API and FIRST EPSS file (services.nvd.nist.gov,
        epss.empiricalsecurity.com, -CveOnline) and the public-exploit
        references (raw.githubusercontent.com, gitlab.com, -ExploitsOnline);
      - HTTP or socket code outside lib\AI.ps1. The collector and the checks
        never touch the network. Gemini is called only after -SendToAI, from
        HostBadger.ps1, once names have been replaced by tokens;
      - Start-Sleep outside lib\AI.ps1, or Read-Host outside the two entry
        points (HostBadger.ps1 and Start-HostBadger.ps1);
      - the commands of the guided menu's "Remediate this machine" (System
        Restore point, removing preinstalled Store apps) anywhere but
        Start-HostBadger.ps1. That menu option and "Fix what the analysis
        finds" in the window (Start-HostBadgerGui.ps1, this machine only) are
        the only parts of HostBadger that change the machine: they run the fix
        script HostBadger generated for this host, after showing it and asking
        (YES in the menu, a warning in the window), and that script makes the
        restore point and records every previous value in a rollback file. The
        collector and the analyzer stay read-only;
      - Start-Process anywhere but Start-HostBadger.ps1 and the window
        (Start-HostBadgerGui.ps1), and there only to restart itself as
        administrator (-Verb RunAs, after asking; Windows confirms with UAC);
      - git anywhere but the window, and there anything but checking and
        updating HostBadger's own git clone when asked: fetch from its
        origin, compare, pull --ff-only (never a merge, never with local
        changes).
 
    It also prints the SHA-256 of every script, so you can compare them with a
    release.
.PARAMETER Path
    HostBadger folder. Default: the folder of this script.
.PARAMETER Quiet
    Print only the verdict.
#>

    [CmdletBinding()]
    param([string]$Path = '', [switch]$Quiet)
    $hbScript = Join-Path $PSScriptRoot 'Test-HostBadgerSafety.ps1'
    & $hbScript @PSBoundParameters
}

function New-SyntheticHostSnapshot {
<#
.SYNOPSIS
    Writes synthetic HostBadger snapshots for tests and demos. No real host
    data: names, SIDs and paths are made up.
.PARAMETER Scenario
    weak a neglected domain workstation: triggers nearly every check
    hardened a well configured member server: two Low findings (built-in
              Administrator under LAPS, a server admin group)
    laptop a managed laptop: TPM-only BitLocker, Windows support ending
              soon, a narrow Defender exclusion
    dc a domain controller with the DC-only problems
    partial collected as a standard user, Defender in passive mode, ACLs
              skipped: shows the "not evaluated" handling
.PARAMETER OutFile
    Where to write the JSON.
.PARAMETER CollectedAtUtc
    Collection time (default 2026-10-01T08:00:00Z, so ages are stable).
#>

    param(
        [ValidateSet('weak', 'hardened', 'laptop', 'dc', 'partial', 'dc2016', 'srv2025')][string]$Scenario = 'weak',
        [Parameter(Mandatory)][string]$OutFile,
        [string]$CollectedAtUtc = '2026-10-01T08:00:00Z'
    )
    $hbScript = Join-Path $PSScriptRoot 'tests\New-SyntheticHostSnapshot.ps1'
    $hbArgs = @{}
    foreach ($k in $PSBoundParameters.Keys) { if ($script:HbCommon -notcontains $k) { $hbArgs[$k] = $PSBoundParameters[$k] } }
    & $hbScript @hbArgs
}

Export-ModuleMember -Function @('Get-HostBadgerPath', 'Invoke-HostBadger', 'New-HostSnapshot', 'New-SyntheticHostSnapshot', 'Start-HostBadger', 'Start-HostBadgerGui', 'Test-HostBadgerSafety') -Alias @('Collect-HostSnapshot')