From a7f350230bb18b4eda7c7cb7f003af8d0a6b213e Mon Sep 17 00:00:00 2001 From: Tomas Kracmar Date: Wed, 4 Nov 2026 13:04:46 +0100 Subject: [PATCH] fix(Prepare-KHDBStorage): actually write invalid-hashes.txt The summary says "Invalid lines saved to .../invalid-hashes.txt" and prints samples, but the file was always empty. $ensureInvalidWriter is a scriptblock invoked with `&`, so it runs in a child scope: `$invalidWriter = New-Object StreamWriter(...)` created a variable local to that call, the outer $invalidWriter stayed $null, and every `if ($invalidWriter) { ...WriteLine() }` was skipped. Same class of bug as the $meta counter fixed in 06e7607. Side effect: each invalid line opened another StreamWriter on the same file (FileShare.Read) and never disposed it. macOS does not enforce .NET share modes, so this only showed up as the empty file here; on Windows the second open is expected to throw a sharing violation and abort the publish once the input has two or more invalid lines (not verified on Windows). The writer now lives in a hashtable (`$invalidOutput.Writer`), which the scriptblock mutates by reference; all 14 uses switched over. Found by the new publish -> update round-trip test, included here: tools/Prepare-KHDBStorage.ps1 -SkipUpload on 400 pre-sorted hashes with mixed case, HASH:count suffixes, adjacent duplicates and a junk line, then Update-ElysiumKhdb consumes the package. Asserts the junk line lands in invalid-hashes.txt and the client rebuilds exactly the sorted, unique, upper-case set. Before the fix: invalid-hashes.txt empty (0 bytes with two junk lines). After: both lines written; 23/23 Pester tests pass. --- AGENTS.md | 2 +- CHANGELOG.md | 3 ++- tests/Elysium.Tests.ps1 | 45 +++++++++++++++++++++++++++++++++++ tools/Prepare-KHDBStorage.ps1 | 20 +++++++++------- 4 files changed, 59 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 214086c..a4d159b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,7 +106,7 @@ There is no package manager or build system. The tool is run directly: No CI pipeline exists. Two automated checks, both runnable on any OS with `pwsh`: -- `Invoke-Pester ./tests` (Pester 5): module helpers - settings parsing, storage URIs, SigV4 signatures checked against values generated by botocore, KHDB manifest/merge validation - an end-to-end `Update-ElysiumKhdb` incremental sync with only `Invoke-DownloadWithRetry` mocked, `Update-ElysiumLithnetStore` against stubbed Lithnet cmdlets, and the pure password-quality helpers (domain list, KHDB normalization for DSInternals). The AD/DSInternals code paths themselves need a Windows host and a domain. Run after touching anything in `src/Elysium/`. +- `Invoke-Pester ./tests` (Pester 5): module helpers - settings parsing, storage URIs, SigV4 signatures checked against values generated by botocore, KHDB manifest/merge validation - an end-to-end `Update-ElysiumKhdb` incremental sync with only `Invoke-DownloadWithRetry` mocked, `Update-ElysiumLithnetStore` against stubbed Lithnet cmdlets, the pure password-quality helpers (domain list, KHDB normalization for DSInternals), and a publish -> update round trip that runs `tools/Prepare-KHDBStorage.ps1 -SkipUpload` and rebuilds its package with `Update-ElysiumKhdb`. The AD/DSInternals code paths themselves need a Windows host and a domain. Run after touching anything in `src/Elysium/`. - `python3 tests/test_decrypt.py` (needs `pwsh` on PATH and `pycryptodome`): encrypts with the real `Protect-FileWithAES` (`src/Elysium/Private/Crypto.ps1`) and decrypts with `tools/decrypt.py`. Run it after touching either side of the export format. ## Testing & Validation diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ae029c..fa83e9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,10 +16,11 @@ Starting with **v2.2.0**, Elysium uses a **unified project version**. All script - The `Restart-WithPwshIfAvailable` / `Restart-WithWindowsPowerShellIfAvailable` relaunchers in `Elysium.Common.ps1` relaunched `Elysium.Common.ps1` itself instead of the calling script (`$PSCommandPath` inside a function is the file that defines it), then exited. Whenever a relaunch fired, the script silently did nothing: `Update-KHDB.ps1`, `Prepare-KHDBStorage.ps1`, `Update-LithnetStore.ps1` and `Uninstall.ps1` started from Windows PowerShell on a host with `pwsh` installed (including menu options 1, 4 and 5), and `Extract-NTHashes.ps1` / `Test-WeakADPasswords.ps1` started directly from `pwsh`. They now relaunch the calling script with its parameters. - `Update-KHDB.ps1 -MaxParallelTransfers N`, as documented in the README, was silently ignored: the script had no `param()` block, so the value never reached the downloader and PowerShell 7 always used 5 concurrent transfers. The script now declares and forwards the parameter (values outside 1-64 are rejected). - `Update-LithnetStore.ps1` failed on every run right after opening the store: it called `.ToArray()` on its `HashSet[string]` source lists, but `ToArray` is a LINQ extension method that PowerShell cannot see, so PowerShell applied it to each string in the set and threw. The hash list always has at least one entry (configured sources or the default KHDB), so no list was ever imported. The lists are now enumerated through the pipeline. +- `Prepare-KHDBStorage.ps1` (now `tools/`) always left `invalid-hashes.txt` empty, although its summary said invalid lines were saved there: the writer was created inside a scriptblock invoked with `&`, so the assignment stayed in that child scope and every write was skipped. Each invalid line also opened another undisposed writer on the same file, which on Windows is expected to fail with a sharing violation from the second invalid line on. The writer is now held in a shared hashtable. ### Changed - Elysium is becoming a PowerShell module (`src/Elysium`). The manifest's `ModuleVersion` is now the only place the version is defined; the per-file banner versions and `Bump-Version.ps1` are gone. Shared helpers moved from `Elysium.Common.ps1` into `src/Elysium/Private` (`Elysium.Common.ps1` is now a loader for them), and the scripts are being converted into exported cmdlets: `Update-ElysiumKhdb`, `Update-ElysiumLithnetStore`, `Test-ElysiumPasswordQuality` and `Send-ElysiumHashExport`. `Update-KHDB.ps1`, `Update-LithnetStore.ps1`, `Test-WeakADPasswords.ps1` and `Extract-NTHashes.ps1` remain as thin wrappers, so the menu and existing invocations are unchanged. -- Added Pester tests (`Invoke-Pester ./tests`): settings parsing, storage URIs, SigV4 signatures checked against botocore-generated values, manifest validation, an end-to-end incremental KHDB sync against a fake storage container, and the Lithnet import against stubbed Lithnet cmdlets. +- Added Pester tests (`Invoke-Pester ./tests`): settings parsing, storage URIs, SigV4 signatures checked against botocore-generated values, manifest validation, an end-to-end incremental KHDB sync against a fake storage container, the Lithnet import against stubbed Lithnet cmdlets, and a publish -> update round trip (the real publisher's package rebuilt by the client). ## [2.4.6] — 2026-07-29 diff --git a/tests/Elysium.Tests.ps1 b/tests/Elysium.Tests.ps1 index f2631b1..c2bdd86 100644 --- a/tests/Elysium.Tests.ps1 +++ b/tests/Elysium.Tests.ps1 @@ -263,3 +263,48 @@ Describe 'Password-quality helpers' { { Resolve-DSInternalsWeakHashFile -Path $malformed } | Should -Throw '*invalid content at line 1*' } } + +Describe 'KHDB publish -> update round trip' { + # Runs the real publisher (tools/Prepare-KHDBStorage.ps1 -SkipUpload) and feeds its package to + # Update-ElysiumKhdb, so the manifest/shard format both sides use is checked end to end. + BeforeAll { + Import-Module (Join-Path $PSScriptRoot '../src/Elysium/Elysium.psd1') -Force + $root = Join-Path $TestDrive 'client' + $package = Join-Path $TestDrive 'package' + New-Item -ItemType Directory -Path $root -Force | Out-Null + & (Get-Module Elysium) { param($r) $script:InstallRoot = $r } $root + Set-Content -LiteralPath (Join-Path $root 'ElysiumSettings.txt') -Value @( + 'storageAccountName=acct', 'containerName=khdb', 'sasToken=sv=2022-11-02&sig=x') + + # 400 distinct hashes spread over many two-hex prefixes, pre-sorted as the publisher expects. + $md5 = [System.Security.Cryptography.MD5]::Create() + $expected = [string[]](1..400 | ForEach-Object { + [BitConverter]::ToString($md5.ComputeHash([Text.Encoding]::UTF8.GetBytes("$_"))).Replace('-', '') + }) + [Array]::Sort($expected, [StringComparer]::Ordinal) + $source = for ($i = 0; $i -lt $expected.Count; $i++) { + switch ($i % 4) { + 0 { $expected[$i].ToLowerInvariant() } # lower case + 1 { "$($expected[$i]):$i" } # legacy HASH:count + 2 { $expected[$i]; $expected[$i] } # adjacent duplicate + default { $expected[$i] } + } + } + $sourcePath = Join-Path $TestDrive 'source.txt' + Set-Content -LiteralPath $sourcePath -Value (@($source) + 'not-a-hash') + & (Join-Path $PSScriptRoot '../tools/Prepare-KHDBStorage.ps1') -SourcePath $sourcePath -OutputRoot $package -SkipUpload 6>$null 3>$null + + # Blob 'khdb/manifest.json' -> /manifest.json, 'khdb/shards/' -> /shards/ + Mock -ModuleName Elysium Invoke-DownloadWithRetry { + $blob = ([uri]$Uri).AbsolutePath -replace '^/khdb/khdb/', '' + Copy-Item -LiteralPath (Join-Path $package $blob) -Destination $TargetPath + } + } + + It 'publishes valid entries only and the client rebuilds exactly the sorted, unique, upper-case set' { + (Get-Content -LiteralPath (Join-Path $package 'manifest.json') -Raw | ConvertFrom-Json).shards.Count | Should -BeGreaterThan 100 + Get-Content -LiteralPath (Join-Path $package 'invalid-hashes.txt') | Should -Contain 'not-a-hash' + Update-ElysiumKhdb -MaxParallelTransfers 1 6>$null + Get-Content -LiteralPath (Join-Path $root 'khdb.txt') | Should -Be $expected + } +} diff --git a/tools/Prepare-KHDBStorage.ps1 b/tools/Prepare-KHDBStorage.ps1 index 4057766..86b8e1d 100644 --- a/tools/Prepare-KHDBStorage.ps1 +++ b/tools/Prepare-KHDBStorage.ps1 @@ -325,14 +325,16 @@ function Split-KhdbIntoShards { $currentSource = if ($sourceItem.PSIsContainer) { $sourceItem.FullName } else { $sourceItem.Name } $maxInvalidSamples = 10 - [System.IO.StreamWriter]$invalidWriter = $null + # Held in a hashtable so $ensureInvalidWriter (invoked with &, i.e. in a child scope) can set + # it for the whole function; a plain variable assignment there would stay local to that call. + $invalidOutput = @{ Writer = $null } $ensureInvalidWriter = { if (-not $InvalidOutputPath) { return } - if (-not $invalidWriter) { + if (-not $invalidOutput.Writer) { $parent = Split-Path -Parent $InvalidOutputPath if ($parent) { Ensure-Directory $parent } $appendInvalid = $Resume -and (Test-Path -LiteralPath $InvalidOutputPath) - $invalidWriter = New-Object System.IO.StreamWriter($InvalidOutputPath, $appendInvalid, $encoding, 1048576) + $invalidOutput.Writer = New-Object System.IO.StreamWriter($InvalidOutputPath, $appendInvalid, $encoding, 1048576) } } @@ -364,7 +366,7 @@ function Split-KhdbIntoShards { param([long]$filePosition) if (-not $EnableCheckpoint) { return } foreach ($s in $shardStates.Values) { $s.Writer.Flush() } - if ($invalidWriter) { $invalidWriter.Flush() } + if ($invalidOutput.Writer) { $invalidOutput.Writer.Flush() } $payload = [ordered]@{ version = 1 savedAt = (Get-Date).ToUniversalTime().ToString('o') @@ -475,7 +477,7 @@ function Split-KhdbIntoShards { [void]$meta.InvalidSamples.Add($trimmed) } & $ensureInvalidWriter - if ($invalidWriter) { $invalidWriter.WriteLine($trimmed) } + if ($invalidOutput.Writer) { $invalidOutput.Writer.WriteLine($trimmed) } & $invokeProgress $false return } @@ -485,7 +487,7 @@ function Split-KhdbIntoShards { [void]$meta.InvalidSamples.Add($trimmed) } & $ensureInvalidWriter - if ($invalidWriter) { $invalidWriter.WriteLine($trimmed) } + if ($invalidOutput.Writer) { $invalidOutput.Writer.WriteLine($trimmed) } & $invokeProgress $false return } @@ -559,7 +561,7 @@ function Split-KhdbIntoShards { [void]$meta.InvalidSamples.Add($pathValue) } & $ensureInvalidWriter - if ($invalidWriter) { $invalidWriter.WriteLine($pathValue) } + if ($invalidOutput.Writer) { $invalidOutput.Writer.WriteLine($pathValue) } & $invokeProgress $true return $null } @@ -649,7 +651,7 @@ function Split-KhdbIntoShards { [void]$meta.InvalidSamples.Add($trimmed) } & $ensureInvalidWriter - if ($invalidWriter) { $invalidWriter.WriteLine($trimmed) } + if ($invalidOutput.Writer) { $invalidOutput.Writer.WriteLine($trimmed) } } & $invokeProgress $false } @@ -662,7 +664,7 @@ function Split-KhdbIntoShards { } } } finally { - if ($invalidWriter) { $invalidWriter.Dispose() } + if ($invalidOutput.Writer) { $invalidOutput.Writer.Dispose() } } foreach ($entry in ($shardStates.GetEnumerator() | Sort-Object Key)) {