diff --git a/Invoke-OpenSSHConfiguration.ps1 b/Invoke-OpenSSHConfiguration.ps1 index 8b2ccb4..2301735 100644 --- a/Invoke-OpenSSHConfiguration.ps1 +++ b/Invoke-OpenSSHConfiguration.ps1 @@ -553,6 +553,27 @@ Switch (Test-ProcessElevationStatus) $Null = [System.IO.File]::Copy($SSHDConfigPath.FullName, $SSHDConfigBackupPath.FullName, $True) $WriteLogMessage.Invoke(0, @("Backup created successfully.")) + + #region Cleanup Old Backups (Keep Last 3) + $BackupFilePattern = 'sshd_config.backup.*' + $BackupsToKeep = 3 + + $ExistingBackups = Get-ChildItem -Path $OpenSSHProgramDataDirectory.FullName -Filter $BackupFilePattern -File -ErrorAction SilentlyContinue | Sort-Object -Property @('LastWriteTime') -Descending + + Switch (($ExistingBackups | Measure-Object).Count -gt $BackupsToKeep) + { + {($_ -eq $True)} + { + $BackupsToRemove = $ExistingBackups | Select-Object -Skip $BackupsToKeep + + ForEach ($BackupToRemove In $BackupsToRemove) + { + $WriteLogMessage.Invoke(0, @("Removing old backup `"$($BackupToRemove.Name)`".")) + $Null = [System.IO.File]::Delete($BackupToRemove.FullName) + } + } + } + #endregion #endregion $SSHDConfigContent = [System.IO.File]::ReadAllText($SSHDConfigPath.FullName) @@ -659,14 +680,18 @@ Switch (Test-ProcessElevationStatus) { {($_ -eq $True)} { - [System.IO.FileInfo]$CABundlePath = [System.IO.Path]::Combine($OpenSSHProgramDataDirectory.FullName, 'OpenSSH-TrustedCertificateAuthorities-LocalMachine.pem') + $CABundleFileName = 'OpenSSH-TrustedCertificateAuthorities-LocalMachine.pem' + [System.IO.FileInfo]$CABundlePath = [System.IO.Path]::Combine($OpenSSHProgramDataDirectory.FullName, $CABundleFileName) + + #Use __PROGRAMDATA__ variable for sshd_config (portable path) + $CABundleConfigPath = "__PROGRAMDATA__/ssh/$($CABundleFileName)" Switch ($CABundlePath.Exists) { {($_ -eq $True)} { $TrustedCAKeysPattern = '(?m)^#?\s*TrustedUserCAKeys\s+.*$' - $TrustedCAKeysReplacement = "TrustedUserCAKeys $($CABundlePath.FullName)" + $TrustedCAKeysReplacement = "TrustedUserCAKeys $($CABundleConfigPath)" Switch ($SSHDConfigContent -imatch $TrustedCAKeysPattern) { @@ -674,7 +699,7 @@ Switch (Test-ProcessElevationStatus) { $SSHDConfigContent = [System.Text.RegularExpressions.Regex]::Replace($SSHDConfigContent, $TrustedCAKeysPattern, $TrustedCAKeysReplacement) $SSHDConfigModified = $True - $WriteLogMessage.Invoke(0, @("Configured TrustedUserCAKeys to `"$($CABundlePath.FullName)`".")) + $WriteLogMessage.Invoke(0, @("Configured TrustedUserCAKeys to `"$($CABundleConfigPath)`".")) } Default