From 3abf2cf6868e17246ef16df424a5978a47eb3a16 Mon Sep 17 00:00:00 2001 From: Manuel Fombuena Date: Mon, 3 Feb 2025 11:58:40 +0000 Subject: [PATCH] add email authentication based on credentials file Instead of using an email password stored on secrets.ps1 in clear text , use a credential file that provides a basic level of encryption. While it would be relatively simple to retrieve the original password, it wouldn't be as simple as opening secrets.ps1 and that could be enough on small deployments in which you don't want to leave the email password so easily available to the end users. Signed-off-by: Manuel Fombuena --- backup.ps1 | 34 +++++++++++++++++++++++++++++----- secrets_template.ps1 | 1 - 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/backup.ps1 b/backup.ps1 index cf67a16..c90ade7 100644 --- a/backup.ps1 +++ b/backup.ps1 @@ -294,6 +294,32 @@ function Invoke-Backup { return $return_value } +function Get-SavedCredential { + <# + .SYNOPSIS + Simple function to get and save domain credentials. + .LINK + http://community.spiceworks.com/scripts/show/1629-get-secure-credentials-function + #> + Param ([String]$AuthUser = $env:USERNAME, [string]$PathToCred) + + $Key = [byte]231,195,218,179,118,15,33,162,18,106,78,122,17,124,116,212,246,97,61,146,201,227,209,160 + + #Build the path to the credential file + $CredFile = $AuthUser.Replace("\","~") + $File = $PathToCred + "\Credentials-$CredFile.crd" + #And find out if it's there, if not create it + If (-not (Test-Path $File)) + { (Get-Credential $AuthUser).Password | ConvertFrom-SecureString -Key $Key | Set-Content $File + } + #Load the credential file + $Password = Get-Content $File | ConvertTo-SecureString -Key $Key + $AuthUser = (Split-Path $File -Leaf).Substring(12).Replace("~","\") + $AuthUser = $AuthUser.Substring(0,$AuthUser.Length - 4) + $Credential = New-Object System.Management.Automation.PsCredential($AuthUser,$Password) + Return $Credential +} + function Send-Email { Param($SuccessLog, $ErrorLog, $Action) @@ -304,12 +330,10 @@ function Send-Email { $Action = "Backup" } - # set email credentials if a username and passsword are provided in configuration - $credentials = @{} - if (-not [String]::IsNullOrEmpty($ResticEmailPassword) -and -not [String]::IsNullOrEmpty($ResticEmailUsername)) { - $password = ConvertTo-SecureString -String $ResticEmailPassword -AsPlainText -Force + # use file for credentials if a username is provided in configuration + if (-not [String]::IsNullOrEmpty($ResticEmailUsername)) { $credentials = @{ - "Credential" = [System.Management.Automation.PSCredential]::new($ResticEmailUsername, $password) + "Credential" = (Get-SavedCredential -AuthUser $ResticEmailUsername -PathToCred $PSScriptRoot) } } diff --git a/secrets_template.ps1 b/secrets_template.ps1 index dbfd02a..f97da98 100644 --- a/secrets_template.ps1 +++ b/secrets_template.ps1 @@ -14,4 +14,3 @@ $ResticEmailPort='' $ResticEmailTo='' $ResticEmailFrom='' $ResticEmailUsername='' -$ResticEmailPassword=''