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.
| 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.
- 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 stringtrue; 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-WindowsFeaturedo not exist in 32-bit PowerShell, and registry writes would land in WOW6432Node). - UDFs are written to both
HKLM\SOFTWARE\CentraStageandHKLM\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.
-StrictExitrestores the old behaviour. - Set the Datto job timeout generously (DISM /
Get-WindowsFeature/ a 20k-event Security query can take minutes).
Severity: H = would change the outcome or break something, M = wrong data or misleading output, L = cosmetic/robustness.
- H -
-WhatIfsuppressed the reports.$WhatIfPreferenceis honoured byNew-Item,Export-Csv,Set-Content,Set-ItemPropertyandCopy-Item, so a WhatIf run wrote no CSV/JSON, no registry summary and no UDFs, while the log claimedReport: <path>. New script captures the switch into$script:WhatIf, resets$WhatIfPreference, and implements WhatIf only in the change helpers. - 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. - H - Server SKUs were handled with client feature names.
SMB1Protocol-Client/-Serverdo not exist as DISM optional features on Server 2016 (NotAvailablewas silently treated as compliant), andUninstall-WindowsFeaturewas never used. New script usesFS-SMB1-CLIENT/FS-SMB1-SERVER/FS-SMB1on servers and falls back to registry-only disable on 2016 where the sub-features do not exist. - H - Confirmation prompts could hang a Datto job.
Set-Service,Stop-Service,Remove-ItemPropertyand theSet-Smb*Configurationcalls can prompt; under a non-interactive host that is an error or a hang. New script sets$ConfirmPreference = 'None'and passes-Force -Confirm:$falseon the SMB cmdlets. - H - 32-bit PowerShell. Datto's agent is 32-bit;
Get-WindowsFeatureis unavailable andHKLM\SOFTWAREwrites are redirected to WOW6432Node. Added the sysnative relaunch and dual-view UDF writes. - H -
mrxsmb10key could be created from nothing.Set-RegDword ...\Services\mrxsmb10 Start 4runsNew-Itemwhen the key is absent, leaving a half-formed service key for the SCM. Now only written when the key exists. - H - Disabling TLS 1.0/1.1 with TLS 1.2 disabled.
-Include TLS10on 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. - M - NTLM audit keys were enabled but never read.
AuditReceivingNTLMTraffic,RestrictSendingNTLMTrafficandAuditNTLMInDomainonly feed the NTLM/Operational log, which the script never queried; NTLMv1 detection comes from 4624LmPackageName. They generated noise for no data, so they are no longer touched (and nothing is left to revert). - 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
-MinDataDaysof data. - M - Event parsing was English-only.
auditpol /subcategory:"Logon",nbtstat -c(UNIQUE/GROUP),Client Address:andProtocol 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-localisedTLS 1.xtoken or the numeric event property. - M -
$env:USERDNSDOMAINis empty under SYSTEM, so-CollectTofiled every Datto-run report underWORKGROUP\<host>. Now usesWin32_ComputerSystem.Domain. - M - SMBSIGNING check could never pass when the Server service is stopped (
Get-SmbServerConfigurationfails,$sis null). It now falls back to the registry values and says why. - M -
[version]$_.Dialectthrew insideWhere-Objectwhen a session had an empty dialect. Replaced with a tolerant string test. - M - Datto UDF written to one registry view only (see 5). Also the
-DattoUdfupper bound of 28 is kept so N+2 never exceeds Custom30. - M - Remediation results counted WhatIf actions as "remediated" in the SUMMARY line and registry summary.
WhatIf actions are now prefixed
WHATIF:and excluded. - M -
IgnoreSourceIPsdid not match IPv4-mapped addresses (::ffff:10.0.0.5). Normalised. - L -
Set-RegDwordtreated a REG_SZ "0" as already compliant. Now checks the value kind and re-types. - L -
$this = $itoverwrote an automatic variable to pass the TLS version into script blocks. Items now receive themselves as a parameter. - L -
#Requires -RunAsAdministratorplusStart-Transcript/Stop-Transcriptwithout try/catch produced red errors on hosts where transcription is unavailable. Replaced with a plain log file. - L - PS2 removal reported
Reboot = $falseon servers;Uninstall-WindowsFeaturereportsRestartNeeded, which is now honoured. DISM results likewise. - L - Typos in
-Includesilently selected nothing. Unknown IDs are now rejected (Include) or warned (Exclude). - L - NTLMV1 flagged a reboot that is not needed (
LmCompatibilityLevelandNoLMHashapply to new authentications without a restart per the policy documentation). Changed to no-reboot; TLS/WDigest/SMB1 keep theirs. - 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. - 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).
- L - TLS10/11 compliance accepted
DisabledByDefault=1withEnabledabsent. Scanners readEnabled; the check now requires an explicitEnabled=0on 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.
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
MinVmVersionForCpuBasedMitigationsunder...\Control\Hypervisor; the documented key isHKLM\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.regcreated 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-SpeculationControlSettingswas called without-ErrorAction Stopinside try; harmless, tidied.
- H -
Get-ItemPropertyreturns REG_EXPAND_SZ values already expanded, so%ProgramFiles%\Vendor\svc.exewas 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 -
$argswas 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.
- Audit modes exit 0 on findings (see Datto notes).
-StrictExitbrings 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 toUsageSamples_<host>.csv.-NoSamplerskips it;DisableAuditremoves 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 atNODATA(use-Forceor-MinDataDays 0). EnableAuditgrows 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-V2without-Remove(payload kept; the scanner only checks the install state). Add-RemoveinUninstall-ServerFeatureSafeif 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.
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:
- 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 reportsstale=and exits 1 after a successful update. Compare against the version the aka.ms installer actually delivered, or pass the expected version in. - M -
wingetis resolved under$env:ProgramFiles; in 32-bit PowerShell that isProgram Files (x86), so it is never found (falls back to direct download, which works, but silently). - M -
-RemoveEolremoves 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.
- M - Per-user Teams cleanup resolves the SID from the profile folder name (
NTAccount($pr.Name)); folder names such asjsmith.DOMAINorjsmith.001throw and the HKU hive edits are skipped. Map viaWin32_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.
- H -
AzureADKerberos(and any RODC-style object) is not excluded from stale computers. It never "logs on", so-DisableStaleComputerswould disable it and break cloud Kerberos trust / Windows Hello / FIDO2 for on-prem resources. Exclude nameAzureADKerberos,primaryGroupID 521and any object withmsDS-KrbTgtLink. Cluster name objects deserve a look too. - H -
$LegacyGroupPatternmatches any group containing "Exchange" or "SharePoint", includingExchange Trusted Subsystem,Exchange Windows Permissions,Exchange Serversand the other groups a hybrid tenant must keep. They are notisCriticalSystemObject, so-RemoveLegacyGroupsdeletes them. Restrict to an explicit list or to the legacy OU. - H - privileged membership is silently incomplete.
Get-ADGroupMember -Recursivefails on groups that contain foreign security principals or more than the member limit, thecatch {}swallows it, and a privileged user can then be classifieddisable. Fall back to thememberattribute or an LDAPmemberOf: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
-QuarantineOUis created at the domain root instead of under its parent. - M -
Compare-Objectwith an empty previous export throws under$ErrorActionPreference = 'Stop'.
- H -
$reg(MFA registration) is assigned inside the IdentityTry-Sectionscript block and read in the Admin roles block. Variables assigned inside a script block invoked by a function are local to that invocation, so$regis$nullthere and every admin is reported as "without MFA registered" (Fail). Assign with$script:reglike$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 Unlimitedis run twice; the SPF lookup counter countsmxinside words.
- 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.
- Read-only, client-specific constants. No functional bugs found; the beta sign-in filter and paging are correct.
- No functional bugs found. The rewrite is careful (ShouldProcess, OPATH escaping, dedupe by object id).
- 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 withNT 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
CentraStagekey (both are written).
- 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, noERROR:lines. .\Invoke-EndpointHardening.ps1 -Mode Remediate -MaxTier 3 -WhatIf -MinDataDays 0 -Force- expectWHATIF:lines for every non-compliant item and no registry changes (HKLM\SOFTWARE\Wavemark\Hardeningis the only key written)..\Invoke-EndpointHardening.ps1 -Mode EnableAudit- checkschtasks /query /tn "Wavemark Hardening Usage Sampler", wait 20 minutes, confirmUsageSamples_<host>.csvhas rows, reboot, confirm System log shows 36880 events.- From Datto: a job with
Mode=AuditandDattoUdf=25; confirm the job's StdOut shows the<-Start Result->block and UDF 25-27 populate after the next audit. .\Invoke-EndpointHardening.ps1 -Mode Remediate -MaxTier 1on the test boxes, then rescan.