diff --git a/CHANGELOG.md b/CHANGELOG.md index efb855a..3bdbcd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,8 +21,10 @@ Starting with **v2.2.0**, Elysium uses a **unified project version**. All script ### Added - `-Domain` on `Test-WeakADPasswords.ps1` / `Extract-NTHashes.ps1` and `-Domain` / `-Credential` on `Test-ElysiumPasswordQuality` / `Send-ElysiumHashExport`, so runs can skip the domain and credential prompts (unattended runs call the cmdlets with a credential). Omitted, both prompt as before. Domain selection is shared (`Select-ElysiumDomain`); an unknown name lists the configured domains, and a domain without a DC now fails before credentials are requested in the export too. +- JSON report next to the text report (`_WeakPasswordReport_.json`): every non-empty password-quality check with its accounts and UPNs, duplicate-password groups kept grouped, plus domain, DC, version and accounts tested. `Test-ElysiumPasswordQuality` returns a summary object (domain, accounts tested, finding counts per check, report paths). ### Changed +- UPNs in the weak-password report come from the accounts already replicated for the test instead of one `Get-ADUser` LDAP query per dictionary hit (`Get-UserUPN` removed). - **No more pwsh relaunch:** with downloads concurrent on Windows PowerShell 5.1, `Update-KHDB.ps1`, `Update-LithnetStore.ps1` and `Uninstall.ps1` simply run in whichever PowerShell starts them. Only the two AD wrappers (`Test-WeakADPasswords.ps1`, `Extract-NTHashes.ps1`) still relaunch, into Windows PowerShell. `Elysium.Common.ps1` is gone; those two wrappers dot-source `src/Elysium/Private/Relaunch.ps1` directly. - **Client storage layer (one HTTP path):** KHDB downloads and the hash-export upload now share `Get-StorageConfig` / `Invoke-StorageDownload` / `Invoke-StorageUpload`. Shard downloads run concurrently on Windows PowerShell 5.1 as well as 7 (a runspace pool that imports the module, replacing `ForEach-Object -Parallel` plus function text injected with `Invoke-Expression`). The hash export is one PUT that the storage service verifies against a digest sent with it (Azure `Content-MD5`, S3 SigV4-signed SHA-256), instead of downloading the blob back - so upload credentials need write access only. Removed: the AWS Tools and Az.Storage code paths and the `s3UseAwsTools` setting (now ignored), the Az.Storage container probe (which needed list rights), and per-8 KB `Write-Progress` calls during downloads. Downloads now fail at once on non-transient HTTP errors (403/404) instead of retrying for ~30 s, storage settings are validated before the hash export replicates anything, and `s3Region` defaults to `us-east-1` for KHDB downloads too (previously signed with an empty region). - **Provider workflow (breaking):** `tools/Prepare-KHDBStorage.ps1` now only builds the KHDB package (shards, `manifest.json`, `khdb-clean.txt`, `invalid-hashes.txt`) and is fully standalone - no Elysium settings, credentials or shared code, runs on any OS with `pwsh`. Its built-in Azure/S3 upload, `-UploadOnly`, `-SkipUpload`, `-MaxParallelTransfers`, `-SettingsPath` and the storage parameters are gone (about 420 lines). Upload with the storage provider's CLI (`aws s3`/`rclone` or `azcopy`), shards first and manifest last; the README has the commands. diff --git a/README.md b/README.md index b4c5455..4501e49 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ When `-ForcePlainText` is specified the script automatically keeps a checkpoint ### Test Weak AD passwords Run script Elysium.ps1 as an administrator and choose option 2 (Test Weak AD Passwords). The script lists domains in the same order as they appear in `ElysiumSettings.txt`. After you pick one, it prompts for credentials and validates them against the selected domain controller before running the password-quality test. To skip the domain prompt, name the domain: `.\Test-WeakADPasswords.ps1 -Domain contoso.local` (the same works for `.\Extract-NTHashes.ps1`). For fully non-interactive runs, call the cmdlets with a credential: `Import-Module .\src\Elysium; Test-ElysiumPasswordQuality -Domain contoso.local -Credential $cred` (or `Send-ElysiumHashExport`). -The tool connects to the selected Domain Controller and compares accounts against KHDB (respecting the optional `CheckOnlyEnabledUsers` flag if configured). A timestamped text report is saved under `Reports`, and accounts with dictionary hits are also exported to a dedicated UPN-only text file to support follow-up automation. +The tool connects to the selected Domain Controller and compares accounts against KHDB (respecting the optional `CheckOnlyEnabledUsers` flag if configured). A timestamped text report is saved under `Reports`, and accounts with dictionary hits are also exported to a dedicated UPN-only text file to support follow-up automation. Next to the text report, a `.json` file holds the same results as data: one finding per check (`WeakPassword`, `LMHash`, `DuplicatePasswordGroups`, ...) with each account's logon name and UPN, plus domain, DC, tool version and the number of accounts tested. The cmdlet also returns a summary object (domain, accounts tested, finding counts per check, report paths). The KHDB file is consumed by DSInternals as a sorted hash list with one NT hash per line (for example `HASH`). Do not include `:count` suffixes in `khdb.txt`; the packaging and update scripts normalize legacy `HASH:count` input to the hash-only format automatically. #### Least privileges for password-quality testing diff --git a/src/Elysium/Private/PasswordQuality.ps1 b/src/Elysium/Private/PasswordQuality.ps1 index 0e9c52e..699b7e0 100644 --- a/src/Elysium/Private/PasswordQuality.ps1 +++ b/src/Elysium/Private/PasswordQuality.ps1 @@ -223,28 +223,6 @@ function Import-CompatModule { Write-Verbose ("Imported module '{0}' (Core={1}, Windows={2})" -f $Name, $runningInPSCore, $onWindows) } -# Function to get UPN for a given SAM account name -function Get-UserUPN { - param ( - [string]$SamAccountName, - [string]$Domain, - [System.Management.Automation.PSCredential]$Credential - ) - - Write-Verbose "Attempting to get UPN for $SamAccountName in domain $Domain" - try { - # Remove domain prefix if exists - $simplifiedSamAccountName = $SamAccountName -replace '^.*\\', '' - - $user = Get-ADUser -Identity $simplifiedSamAccountName -Properties UserPrincipalName -Server $Domain -Credential $Credential - Write-Verbose "UPN found: $($user.UserPrincipalName)" - return $user.UserPrincipalName - } catch { - Write-Verbose ("Failed to get UPN for {0}: {1}" -f $SamAccountName, $_.Exception.Message) - return "UPN not found" - } -} - function Resolve-DSInternalsWeakHashFile { param( [Parameter(Mandatory)][string]$Path @@ -456,6 +434,12 @@ function Invoke-WeakPasswordTest { } } + # UPNs come from the accounts already replicated above - no extra LDAP lookup per account. + $upnBySam = @{} + foreach ($account in @($accounts)) { + if ($account.SamAccountName -and $account.UserPrincipalName) { $upnBySam[[string]$account.SamAccountName] = [string]$account.UserPrincipalName } + } + # Report generation with dynamic content and UPNs $reportPath = Join-Path -Path $reportPathBase -ChildPath "$($selectedDomain.Name)_WeakPasswordReport_$timestamp.txt" $upnOnlyReportPath = Join-Path -Path $reportPathBase -ChildPath "$($selectedDomain.Name)_DictionaryPasswordUPNs_$timestamp.txt" @@ -475,8 +459,8 @@ function Invoke-WeakPasswordTest { foreach ($logonName in $dictionaryLogonNames) { $samAccountName = $logonName -replace '^.*\\', '' if (-not [string]::IsNullOrWhiteSpace($samAccountName) -and -not $dictionarySamToUpn.ContainsKey($samAccountName)) { - Write-Verbose "Looking up UPN for $samAccountName (dictionary hit)" - $upn = Get-UserUPN -SamAccountName $samAccountName -Domain $selectedDomain.DC -Credential $credential + $upn = $upnBySam[$samAccountName] + if ([string]::IsNullOrWhiteSpace($upn)) { $upn = "UPN not found" } $dictionarySamToUpn[$samAccountName] = $upn if ($upn -ne "UPN not found") { $upnReportContent += $upn @@ -531,7 +515,64 @@ function Invoke-WeakPasswordTest { $upnOnlyContent | Out-File -FilePath $upnOnlyReportPath -Encoding utf8 -ErrorAction Stop Write-Host "UPN-only report saved to $upnOnlyReportPath" + + $findings = @(ConvertTo-PasswordQualityFinding -Result $testResults -UpnBySam $upnBySam) + $jsonReportPath = [System.IO.Path]::ChangeExtension($reportPath, '.json') + $jsonReport = [ordered]@{ + tool = 'Elysium' + version = $ElysiumVersion + generatedAt = (Get-Date).ToUniversalTime().ToString('o') + domain = $selectedDomain.Name + domainController = $selectedDomain.DC + accountsTested = @($accounts).Count + findings = $findings + } + [System.IO.File]::WriteAllText($jsonReportPath, ($jsonReport | ConvertTo-Json -Depth 8), [System.Text.UTF8Encoding]::new($false)) + Write-Host "JSON report saved to $jsonReportPath" } catch { Write-Error ("Failed to save report: {0}" -f $_.Exception.Message) } + + $findingCounts = [ordered]@{} + foreach ($finding in $findings) { $findingCounts[$finding.check] = $finding.count } + [pscustomobject]@{ + Domain = $selectedDomain.Name + AccountsTested = @($accounts).Count + Findings = $findingCounts + ReportPath = $reportPath + JsonReportPath = $jsonReportPath + UpnReportPath = $upnOnlyReportPath + } +} + +function ConvertTo-PasswordQualityFinding { + # Plain-data view of a DSInternals Test-PasswordQuality result for the JSON report: one finding per + # non-empty result property (WeakPassword, LMHash, ...) listing its accounts with their UPNs. + # DuplicatePasswordGroups stays grouped: each of its entries is a list of accounts sharing a password. + # Arrays are built with List.ToArray(), not pipeline output: Windows PowerShell 5.1's ConvertTo-Json + # serializes pipeline-wrapped arrays as {"value": [...], "Count": n}. + param( + [Parameter(Mandatory)][AllowNull()]$Result, + [hashtable]$UpnBySam = @{} + ) + + $toAccount = { param($logonName) [ordered]@{ account = [string]$logonName; upn = $UpnBySam[([string]$logonName -replace '^.*\\', '')] } } + foreach ($testResult in @($Result)) { + if ($null -eq $testResult) { continue } + foreach ($property in $testResult.PSObject.Properties) { + $items = @($property.Value | Where-Object { $null -ne $_ }) + if ($items.Count -eq 0) { continue } + $accounts = [System.Collections.Generic.List[object]]::new() + foreach ($item in $items) { + if ($item -is [string]) { + $accounts.Add((& $toAccount $item)) + } else { + $group = [System.Collections.Generic.List[object]]::new() + foreach ($member in $item) { $group.Add((& $toAccount $member)) } + $accounts.Add($group.ToArray()) + } + } + [ordered]@{ check = $property.Name; count = $items.Count; accounts = $accounts.ToArray() } + } + } } diff --git a/tests/Elysium.Tests.ps1 b/tests/Elysium.Tests.ps1 index 506291b..480610c 100644 --- a/tests/Elysium.Tests.ps1 +++ b/tests/Elysium.Tests.ps1 @@ -257,6 +257,31 @@ Describe 'Password-quality helpers' { { Select-ElysiumDomain -DomainDetails $domains 6>$null } | Should -Throw '*Invalid selection*' } + It 'turns a password-quality result into JSON-ready findings with UPNs, keeping duplicate groups grouped' { + # Same shapes DSInternals returns: string sets, and a list of sets for DuplicatePasswordGroups. + $set = { param([string[]]$names) $h = [System.Collections.Generic.HashSet[string]]::new(); foreach ($n in $names) { [void]$h.Add($n) }; ,$h } + $groups = [System.Collections.Generic.List[object]]::new() + $groups.Add((& $set 'CONTOSO\bob', 'CONTOSO\carol')) + $result = [pscustomobject]@{ + WeakPassword = (& $set 'CONTOSO\alice', 'CONTOSO\svc-sql') + LMHash = (& $set @()) + DuplicatePasswordGroups = $groups + } + $upns = @{ alice = 'alice@contoso.com'; bob = 'bob@contoso.com'; carol = 'carol@contoso.com' } + $json = @(ConvertTo-PasswordQualityFinding -Result $result -UpnBySam $upns) | ConvertTo-Json -Depth 8 + $findings = $json | ConvertFrom-Json + + @($findings.check) | Should -Be @('WeakPassword', 'DuplicatePasswordGroups') # empty LMHash omitted + $weak = $findings | Where-Object check -eq 'WeakPassword' + $weak.count | Should -Be 2 + ($weak.accounts | Where-Object account -eq 'CONTOSO\alice').upn | Should -Be 'alice@contoso.com' + ($weak.accounts | Where-Object account -eq 'CONTOSO\svc-sql').upn | Should -BeNullOrEmpty + $dup = $findings | Where-Object check -eq 'DuplicatePasswordGroups' + $dup.count | Should -Be 1 + @($dup.accounts[0].account | Sort-Object) | Should -Be @('CONTOSO\bob', 'CONTOSO\carol') + $json | Should -Not -Match '"value"\s*:' # no PowerShell array-wrapper artefacts + } + It 'lists DomainNName/DomainNDC pairs in order and stops at the first gap' { $domains = Get-DomainDetailsFromSettings -Settings @{ Domain1Name = 'contoso.local'; Domain1DC = 'dc1.contoso.local'