Skip to content

About

A script to bring Windows 10/11 and Server 2016+ up to baseline security

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

Review findings and consolidation notes

Deliverable: Invoke-EndpointHardening.ps1 (same folder). It replaces three of the uploaded scripts: Invoke-LegacyProtocolHardening.ps1 (v1 and v2 are byte-identical), Repair-RegistryFindings-v2.ps1 and Repair-UnquotedServicePaths.ps1. Everything else in the zip was reviewed but deliberately left separate (see section 6).

Important caveat up front: this environment has no Windows and no PowerShell interpreter, so the new script was checked statically (bracket/quote balance, PS 5.1-only syntax, function ordering, a line-by-line read) but has NOT been executed. Run it on one workstation and one server with -Mode Audit and -Mode Remediate -WhatIf before pushing it through Datto. Section 8 lists exactly what to look at.


1. The three-run workflow

Run Command (Datto input variable Mode) What happens
1 -Mode EnableAudit Turns on Schannel handshake logging (event 36880), SMB1 access auditing (event 3000), Logon success auditing (4624), SMB signing audit events on builds that have them, grows the System log to 128 MB so it does not wrap, registers a 15-minute usage sampler scheduled task, stamps the start time in HKLM\SOFTWARE\Wavemark\Hardening, then runs a baseline audit. Exit 3010: one reboot is needed before Schannel starts writing 36880 events.
2 -Mode Audit (default), a week later Reads everything. Prints a "data coverage" block (how many days of usable data each source has), a per-item table, an INUSE: / NODATA: block between <-Start Result-> and <-End Result->, and a `SUMMARY
3 -Mode Remediate -MaxTier n [-Include ...] [-Exclude ...] [-Force] Same gating as before (tier, usage) plus a new one: a data-dependent item (NTLMV1, SMB1SERVER, SMB1CLIENT, NBTNS, TLS10, TLS11) is skipped as NODATA unless at least -MinDataDays (default 7) of audit data exist. -Force overrides both usage and data gates. -MinDataDays 0 turns the data gate off.
4 -Mode DisableAudit (optional) Restores Schannel logging, SMB1/SMB-signing audit flags to what they were, removes the sampler task, archives the samples.

Items and IDs are unchanged for the scanner mapping: LLMNR, MDNS, NBTNS, NTLMV1, PS2, SMBSIGNING, SMB1CLIENT, SMB1SERVER, TLS12, TLS10, TLS11, WDIGEST, plus WINVERIFYTRUST, SPECULATIVE, EVENTLOGCRASHER (report only) and UNQUOTEDPATHS.

Datto RMM deployment

  • Paste the script as a PowerShell component. Add input variables with the same names as the parameters (Mode, MaxTier, Include, Exclude, Force, LookbackDays, MinDataDays, IgnoreSourceIPs, DattoUdf, UsageToStdErr, NoSampler). Booleans arrive as the string true; lists are comma separated. Values set on the command line win over the environment.
  • The script relaunches itself in 64-bit PowerShell when the 32-bit agent starts it (ServerManager cmdlets such as Get-WindowsFeature do not exist in 32-bit PowerShell, and registry writes would land in WOW6432Node).
  • UDFs are written to both HKLM\SOFTWARE\CentraStage and HKLM\SOFTWARE\WOW6432Node\CentraStage, so they are picked up whichever view the agent reads.
  • Exit codes: Audit runs exit 0 even with findings (findings are the normal outcome of an audit; the old "1 on any finding" turned every audit job red). Remediate exits 1 when items remain, 2 on an error, 3010 when a reboot is pending. -StrictExit restores the old behaviour.
  • Set the Datto job timeout generously (DISM / Get-WindowsFeature / a 20k-event Security query can take minutes).

2. Bugs in Invoke-LegacyProtocolHardening.ps1 (fixed in the consolidated script)

Severity: H = would change the outcome or break something, M = wrong data or misleading output, L = cosmetic/robustness.

  1. H - -WhatIf suppressed the reports. $WhatIfPreference is honoured by New-Item, Export-Csv, Set-Content, Set-ItemProperty and Copy-Item, so a WhatIf run wrote no CSV/JSON, no registry summary and no UDFs, while the log claimed Report: <path>. New script captures the switch into $script:WhatIf, resets $WhatIfPreference, and implements WhatIf only in the change helpers.
  2. H - SMB1SERVER remediation also killed the SMB1 client. The fix disabled the parent feature SMB1Protocol, which removes the client as well, even when SMB1CLIENT was skipped for detected usage (old NAS). Now each side removes only its own sub-feature; the parent package is removed only once both sides are off.
  3. H - Server SKUs were handled with client feature names. SMB1Protocol-Client/-Server do not exist as DISM optional features on Server 2016 (NotAvailable was silently treated as compliant), and Uninstall-WindowsFeature was never used. New script uses FS-SMB1-CLIENT / FS-SMB1-SERVER / FS-SMB1 on servers and falls back to registry-only disable on 2016 where the sub-features do not exist.
  4. H - Confirmation prompts could hang a Datto job. Set-Service, Stop-Service, Remove-ItemProperty and the Set-Smb*Configuration calls can prompt; under a non-interactive host that is an error or a hang. New script sets $ConfirmPreference = 'None' and passes -Force -Confirm:$false on the SMB cmdlets.
  5. H - 32-bit PowerShell. Datto's agent is 32-bit; Get-WindowsFeature is unavailable and HKLM\SOFTWARE writes are redirected to WOW6432Node. Added the sysnative relaunch and dual-view UDF writes.
  6. H - mrxsmb10 key could be created from nothing. Set-RegDword ...\Services\mrxsmb10 Start 4 runs New-Item when the key is absent, leaving a half-formed service key for the SCM. Now only written when the key exists.
  7. H - Disabling TLS 1.0/1.1 with TLS 1.2 disabled. -Include TLS10 on a host with TLS 1.2 explicitly disabled would leave Schannel with nothing to negotiate. The TLS10/TLS11 fix now refuses (even with -Force) until TLS12 is compliant.
  8. M - NTLM audit keys were enabled but never read. AuditReceivingNTLMTraffic, RestrictSendingNTLMTraffic and AuditNTLMInDomain only feed the NTLM/Operational log, which the script never queried; NTLMv1 detection comes from 4624 LmPackageName. They generated noise for no data, so they are no longer touched (and nothing is left to revert).
  9. M - Audit window was unknown, so "not in use" could be false. The script claimed 14 days of lookback even when Schannel logging was enabled yesterday or the System log had wrapped after two days (EventLogging=7 is very chatty on IIS/RDS hosts). New script records when auditing was enabled, measures the oldest available record per source, prints a coverage block, caps the usable window, grows the System log, and refuses to call a data-dependent item "not in use" with less than -MinDataDays of data.
  10. M - Event parsing was English-only. auditpol /subcategory:"Logon", nbtstat -c (UNIQUE/GROUP), Client Address: and Protocol version: are localised. Now: auditpol by GUID, nbtstat matched on the <xx> and IP tokens, event 3000 client read from the event property, TLS version taken from the un-localised TLS 1.x token or the numeric event property.
  11. M - $env:USERDNSDOMAIN is empty under SYSTEM, so -CollectTo filed every Datto-run report under WORKGROUP\<host>. Now uses Win32_ComputerSystem.Domain.
  12. M - SMBSIGNING check could never pass when the Server service is stopped (Get-SmbServerConfiguration fails, $s is null). It now falls back to the registry values and says why.
  13. M - [version]$_.Dialect threw inside Where-Object when a session had an empty dialect. Replaced with a tolerant string test.
  14. M - Datto UDF written to one registry view only (see 5). Also the -DattoUdf upper bound of 28 is kept so N+2 never exceeds Custom30.
  15. M - Remediation results counted WhatIf actions as "remediated" in the SUMMARY line and registry summary. WhatIf actions are now prefixed WHATIF: and excluded.
  16. M - IgnoreSourceIPs did not match IPv4-mapped addresses (::ffff:10.0.0.5). Normalised.
  17. L - Set-RegDword treated a REG_SZ "0" as already compliant. Now checks the value kind and re-types.
  18. L - $this = $it overwrote an automatic variable to pass the TLS version into script blocks. Items now receive themselves as a parameter.
  19. L - #Requires -RunAsAdministrator plus Start-Transcript/Stop-Transcript without try/catch produced red errors on hosts where transcription is unavailable. Replaced with a plain log file.
  20. L - PS2 removal reported Reboot = $false on servers; Uninstall-WindowsFeature reports RestartNeeded, which is now honoured. DISM results likewise.
  21. L - Typos in -Include silently selected nothing. Unknown IDs are now rejected (Include) or warned (Exclude).
  22. L - NTLMV1 flagged a reboot that is not needed (LmCompatibilityLevel and NoLMHash apply to new authentications without a restart per the policy documentation). Changed to no-reboot; TLS/WDigest/SMB1 keep theirs.
  23. L - NBTNS fix was registry-only (reboot for every adapter). Active adapters are now switched with SetTcpipNetbios(2) (immediate), registry for the rest; reboot is flagged only when something needed it.
  24. L - WDIGEST "absent = compliant" meant the scanner line item would never clear on 2016+. Explicit 0 is now required (the fix is harmless and the evidence text already said so).
  25. L - TLS10/11 compliance accepted DisabledByDefault=1 with Enabled absent. Scanners read Enabled; the check now requires an explicit Enabled=0 on both sides.

Design decision to be aware of: the script still treats an absent TLS 1.0/1.1 key as "not explicitly disabled" on Windows 11 24H2 / Server 2025 even though Microsoft documents those builds as off-by-default. That matches what the scanner reports and setting the keys explicitly is harmless.

3. Repair-RegistryFindings (v1 vs v2)

v2 fixed two real bugs in v1 and the consolidated script carries the v2 logic:

  • v1 compared FeatureSettingsOverride -eq 72, so a host with the correct bits plus the HT-off or BHI bits was flagged non-compliant and then overwritten. v2 tests the bits; kept.
  • v1 wrote MinVmVersionForCpuBasedMitigations under ...\Control\Hypervisor; the documented key is HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization. v2 is correct; kept.
  • Both versions: $bios.ReleaseDate.ToString(...) throws on VMs that report no BIOS date (the Write-Log line and the Risk text both evaluate it). Guarded.
  • EnableCertPaddingCheck: both versions write REG_DWORD, which is right. Microsoft's original 2013 .reg created a REG_SZ and it was re-specified as REG_DWORD in 2023/2024; scanners now check the type. The new check also flags a leftover REG_SZ "1" as non-compliant and re-types it.
  • Get-SpeculationControlSettings was called without -ErrorAction Stop inside try; harmless, tidied.

4. Repair-UnquotedServicePaths

  • H - Get-ItemProperty returns REG_EXPAND_SZ values already expanded, so %ProgramFiles%\Vendor\svc.exe was rewritten as "C:\Program Files\Vendor\svc.exe" and the value type forced to ExpandString. The new code reads the raw value (DoNotExpandEnvironmentNames), expands only for the existence test, writes back the raw quoted path and preserves the original value kind.
  • M - Paths that start with %VAR% were skipped entirely by ^[A-Za-z]: once the raw value is used; both forms are accepted now.
  • L - $args was assigned (automatic variable). Renamed.
  • Behaviour kept: MSIX (WindowsApps) services skipped; services whose executable is missing are reported for manual review and not rewritten, and they keep the item non-compliant so the scanner finding is not forgotten.

5. Behaviour changes in the consolidated script you should know about

  • Audit modes exit 0 on findings (see Datto notes). -StrictExit brings back exit 1.
  • The usage sampler is a new scheduled task (Wavemark Hardening Usage Sampler, SYSTEM, every 15 min, hidden) that appends one CSV row to UsageSamples_<host>.csv. -NoSampler skips it; DisableAudit removes it. Without it, NBTNS, SMB1CLIENT and the SMB1-session part of SMBSIGNING only have point-in-time evidence and the data gate will keep NBTNS/SMB1CLIENT at NODATA (use -Force or -MinDataDays 0).
  • EnableAudit grows the System log to 128 MB (-SystemLogMB, 0 = leave alone) and does not shrink it back.
  • Logon success auditing is enabled by GUID and is not reverted by DisableAudit (it is the Windows default anyway).
  • PS2 on servers is removed with Uninstall-WindowsFeature PowerShell-V2 without -Remove (payload kept; the scanner only checks the install state). Add -Remove in Uninstall-ServerFeatureSafe if you want it gone from the component store.
  • SMB signing audit events (3021/3022, 31998/31999) are used on Windows 11 24H2 / Server 2025 / hosts with KB5066913. The exact mapping of each ID to "signing" versus "encryption" differs between Microsoft documents, so any of these events counts as evidence for SMBSIGNING (conservative) and the detail lists peers by event ID.

6. Scripts reviewed but not consolidated, and why

They do not fit the audit-then-remediate endpoint pattern (they need interactive Graph/Exchange sign-in, run against a domain or tenant rather than a device, or are one-off cleanups). Bugs found:

Update-DotNetRuntimes.ps1

  • H - the "stale" regex at the end is hard-coded (8.0.0-8.0.32, 10.0.0-10.0.13 = stale). As of November 2025 the current patches are well below those numbers, so every host reports stale= and exits 1 after a successful update. Compare against the version the aka.ms installer actually delivered, or pass the expected version in.
  • M - winget is resolved under $env:ProgramFiles; in 32-bit PowerShell that is Program Files (x86), so it is never found (falls back to direct download, which works, but silently).
  • M - -RemoveEol removes 6.0 too; the header says 3.1 and 7.
  • L - winget under SYSTEM usually fails on sources; the fallback covers it but the log says "did not complete" every time.

Invoke-OctoberCleanup-v3.ps1

  • M - Per-user Teams cleanup resolves the SID from the profile folder name (NTAccount($pr.Name)); folder names such as jsmith.DOMAIN or jsmith.001 throw and the HKU hive edits are skipped. Map via Win32_UserProfile (SID to LocalPath) instead.
  • L - if ($pol.WUServer -and -not $pol.UseWUServer -eq 0) parses as (-not $pol.UseWUServer) -eq 0; it happens to give the intended answer for 0/1 but is fragile. Write $pol.UseWUServer -ne 0.
  • L - UDF substring arithmetic is correct but only by coincidence of the 12-character prefix; use [Math]::Min(255, $s.Length) on the final string.

Invoke-ADHygiene.ps1 (run it with care - these are the ones that can hurt)

  • H - AzureADKerberos (and any RODC-style object) is not excluded from stale computers. It never "logs on", so -DisableStaleComputers would disable it and break cloud Kerberos trust / Windows Hello / FIDO2 for on-prem resources. Exclude name AzureADKerberos, primaryGroupID 521 and any object with msDS-KrbTgtLink. Cluster name objects deserve a look too.
  • H - $LegacyGroupPattern matches any group containing "Exchange" or "SharePoint", including Exchange Trusted Subsystem, Exchange Windows Permissions, Exchange Servers and the other groups a hybrid tenant must keep. They are not isCriticalSystemObject, so -RemoveLegacyGroups deletes them. Restrict to an explicit list or to the legacy OU.
  • H - privileged membership is silently incomplete. Get-ADGroupMember -Recursive fails on groups that contain foreign security principals or more than the member limit, the catch {} swallows it, and a privileged user can then be classified disable. Fall back to the member attribute or an LDAP memberOf:1.2.840.113556.1.4.1941: query and abort the user step when a privileged group could not be read.
  • M - a custom nested -QuarantineOU is created at the domain root instead of under its parent.
  • M - Compare-Object with an empty previous export throws under $ErrorActionPreference = 'Stop'.

Get-M365PostureReport.ps1

  • H - $reg (MFA registration) is assigned inside the Identity Try-Section script block and read in the Admin roles block. Variables assigned inside a script block invoked by a function are local to that invocation, so $reg is $null there and every admin is reported as "without MFA registered" (Fail). Assign with $script:reg like $script:Users.
  • M - Try-Section's catch calls .Substring(0, Min(200, originalLength)) on the whitespace-collapsed message; a message with runs of whitespace can be shorter than the original and throw inside the catch.
  • L - Get-CASMailbox -ResultSize Unlimited is run twice; the SPF lookup counter counts mx inside words.

Get-EnterpriseAppUsage.ps1

  • L - uses Get-MgUser, so Microsoft.Graph.Users must be loaded; the header only mentions Connect-MgGraph.
  • L - apps with no service-principal sign-in record at all are classified REMOVE even when the activity feed is present but simply has no entry; defensible, but worth a note in the CSV.

Get-OffsiteSignins.ps1

  • Read-only, client-specific constants. No functional bugs found; the beta sign-in filter and paging are correct.

Remove-UserFromAllGroups.ps1

  • No functional bugs found. The rewrite is careful (ShouldProcess, OPATH escaping, dedupe by object id).

7. Things that could not be verified here

  • Exact Schannel 36880 property order on each build (used only as a fallback after the message text).
  • Whether New-ScheduledTaskPrincipal -UserId 'S-1-5-18' is accepted on every build (the code retries with NT AUTHORITY\SYSTEM).
  • The SMB signing audit event ID mapping (handled conservatively, see section 5).
  • That the Datto agent on your fleet reads the 64-bit or the WOW6432Node CentraStage key (both are written).

8. Test plan before fleet use

  1. Workstation (Win 11) and server (2016 or 2019), interactive elevated PowerShell: .\Invoke-EndpointHardening.ps1 -Mode Audit - expect a coverage block, 16 item lines, a table, no ERROR: lines.
  2. .\Invoke-EndpointHardening.ps1 -Mode Remediate -MaxTier 3 -WhatIf -MinDataDays 0 -Force - expect WHATIF: lines for every non-compliant item and no registry changes (HKLM\SOFTWARE\Wavemark\Hardening is the only key written).
  3. .\Invoke-EndpointHardening.ps1 -Mode EnableAudit - check schtasks /query /tn "Wavemark Hardening Usage Sampler", wait 20 minutes, confirm UsageSamples_<host>.csv has rows, reboot, confirm System log shows 36880 events.
  4. From Datto: a job with Mode=Audit and DattoUdf=25; confirm the job's StdOut shows the <-Start Result-> block and UDF 25-27 populate after the next audit.
  5. .\Invoke-EndpointHardening.ps1 -Mode Remediate -MaxTier 1 on the test boxes, then rescan.

About

A script to bring Windows 10/11 and Server 2016+ up to baseline security

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages