Using encrypted password to send mail is failing - powershell

I'm trying to use a stored encrypted password in a script that sends an email but I keed getting the error:
send-mailmessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
[DM6PR66666019.namprd456.prod.outlook.com]
I used the following code to create the text file:
$passwordtostore = 'NotTheRealPassword$9gv8z6VHnPfDd8zc'
$secureStringPWD = $passwordtostore | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPWD | ConvertFrom-SecureString
Set-Content "c:\temp\scriptsencrypted_password1.txt" $secureStringText
I use the following to import the password:
$passwordFile = "c:\temp\scriptsencrypted_password1.txt"
$password = Get-Content $passwordFile | ConvertTo-SecureString
Here's the sendmail function I am using:
function SendMail($ToEmails,$FromEmail,$Subj,$Body,$UserName,$Password){
$cred = New-Object System.Management.Automation.PSCredential $UserName,$Password
$MailParams=#{"from"=$FromEmail; "to"=$ToEmails;"body"=$Body;"subject"=$Subj;"smtpserver"="smtp.office365.com"}
send-mailmessage #MailParams -Credential $cred -UseSsl $true -port 587
}
Here's the code which calls the function:
$alertEmail = "me.stillme#mydomain.com"
$username="psemail#mydomain.com"
$passwordFile = "c:\temp\scriptsencrypted_password1.txt"
$password = Get-Content $passwordFile | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($username, $password)
Import-Module -Name "..\SendMail.psm1"
... Doing some stuff
SendMail $alertEmail $username "This is the subject" "this is the body" $credential.UserName $credential.Password

Personally, I fail to see why you would make a function in a module you need to import for the Send-MailMessage cmdlet..
This makes things a lot harder to use.
Also, it kind of looks like you are switching the emailaddresses To and From inside the function.
Anyway, things go wrong when you are creating the credentials, split it into username and (secure) password to send as parameters to the function and recombine them into a credentials object in there.
Why not skip that module function and simply do:
$password = Get-Content 'c:\temp\scriptsencrypted_password1.txt' -Raw | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PsCredential('YourLoginName', $password)
$MailParams=#{
From = 'me.stillme#mydomain.com'
To = 'psemail#mydomain.com'
Body = "this is the body"
Subject = "This is the subject"
SmtpServer = 'smtp.office365.com'
Port = 587
UseSsl = $true
Credential = $credential
}
Send-MailMessage #MailParams
This will make your script far more readable/maintainable

I found two issues with my code above:
An unescaped $ in the password.
Once I added " -NoNewline" to the set-content, it began to work.
So, to create the encrypted file:
$passwordtostore = "7K9CBgvc4rttvfctrsef6PVHqnP6fDdwhatevervtfdscttzSc"
$secureStringPWD = $passwordtostore | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPWD | ConvertFrom-SecureString
Set-Content "D:\Powershell Scripts\encrypted.hash" $secureStringText -NoNewline
Then to retrieve the password and use it in a credential:
$password = Get-Content $passwordFile -Raw | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($username, $password)
It wasn't the source of the issue, but I did implement #Theo's suggestion re: using send-mailmessage.

Related

How to retrieve Password from PSCredential in a .cred file

I have two functions, Save Credential to create a .cred file:
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($Username, $PWord)
$cred.Password | Out-File "some\path\$($cred.Username).cred" -Force
and Get Credential to retrieve the password:
$string = Get-Content "some\path\$($Username).cred" | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $string
return $cred
I cannot for the life of me figure out how to retrieve the password from the .cred file that I created. The errors I get are:
ConvertTo-SecureString: Input String was not in the correct format
New-Object: Exception calling .actor with 2 arguments. Cannot process argument because the value of argument "password" is null. change the value of argument password to a non-null value
What version are you bound to? I might not be following properly, but it looks like you don't care about the whole credential and just want the password, so couldn't it just be:
#set
$pwd = "replace me"
$securepwd = $pwd | ConvertTo-SecureString -AsPlainText -Force
$encryptedpwd = $securepwd | ConvertFrom-SecureString
Out-File -FilePath C:\temp\Reference.cred -InputObject $encryptedpwd
then
#get
$securepwd = (Get-Content -Path C:\temp\Reference.cred) | ConvertTo-SecureString
#commented out 3 lines shows how to decrypt in case you want to view it/verify it, but isn't necessary
#$Marshal = [System.Runtime.InteropServices.Marshal]
#$Bstr = $Marshal::SecureStringToBSTR($securepwd)
#$pswd = $Marshal::PtrToStringAuto($Bstr)
#$Marshal::ZeroFreeBSTR($Bstr)
$RunAs = New-Object System.Management.Automation.PSCredential ('Domain\Account', $securepwd)
I'm not as good as most folks on here though, just giving it a stab.

Use powershell to send email while saving your password securely in encrypted file

I have found similar threads but none that solve my issue. I am trying to send an email using SMTP server, with attachment (via gmail). That's the easy bit done. The main error response I get is
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."
I think it has to do with getting the password from the password file into the Credentials
"Password123" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Folder\Password.txt"
$EmailFrom = "emailaddress#gmail.com"
$EmailTo = "otheremailaddress#gmail.com"
$Subject = "Log file from server"
$Subject = "Subject"
$Body = "Here is the log file from the server"
$File = "C:\Folder\LogFile.txt"
$attachment = New-Object System.Net.Mail.Attachment($File,'text/plain')
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($emailto)
$mailmessage.Subject = $Subject
$mailmessage.Body = $Body
$mailmessage.Attachments.Add($attachment)
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$username = "emailaddress#gmail.com"
$pass = Get-Content "C:\Folder\Password.txt" | ConvertTo-SecureString -AsPlainText -Force
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($username, $pass);
$SMTPClient.Send($mailmessage)
I want to remove the first line of this code as it's never a good idea to have a password in the script.
If I change the password variable to the following I have no issue
$pass = "Password123"
All the other forum posts I found have suggested things haven't solved my problem.
Also changing gmails settings to allow access from less secure apps doesn't solve my problem.
Any help would greatly be appreciated
Thanks in advance.
EDIT:
I have gmail accessible for less secure apps
I have 2 step verification off for gmail
I believe the issue is reading the password file. It's a case of not being able to accept password from the file when it is encrypted. I tried it with an un-encrypted password but that isn't much better for scripting
I've ran into issues with this in the past - I think one of the common gotcha's was already mentioned by Mathias - watch out for running under different credentials (running as a schedule job) since decoding depends on using the user's session information. The one thing I'm not quite sure about in your example is why you're doing a subsequent convert to plain text- otherwise though, the below should take your username and password, export it to a file, then import it in as a credential you can use later.
$user = "UsernameGoesHere"
$passwordtostore = 'PasswordGoesHere'
$secureStringPWD = $passwordtostore | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPWD | ConvertFrom-SecureString
Set-Content "C:\temp\authenticationfile.cfg" $secureStringText
# Retrieve password
$pwdin = Get-Content "C:\temp\authenticationfile.cfg"
$password = $pwdin | ConvertTo-SecureString
$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $user,$password
Hope that helps?

Can't use send-mailmessage when using PSFTP Module

I've made a Powershell script which uploads data to a NAS.
After the Upload is completed the script should send an Email message.
When the script tries to send a mailmessage I get an error saying I used an incorrect security certificate.
This error only shows up when I use the PSFTP module. When i run the sendmail code on its own it works just fine.
The FTP session itself isn't alive anymore so this shouldn't be a problem.
Can someone point me in the right direction to sort this problem out?I've made a Powershell script which uploads data to a NAS.
After the Upload is completed the script should send an Email message.
When the script tries to send a mailmessage I get an error saying I used an incorrect security certificate.
This error only shows up when I use the PSFTP module. When i run the sendmail code on its own it works just fine.
The FTP session itself isn't alive anymore so this shouldn't be a problem.
Can someone point me in the right direction to sort this problem out?
$Execution = Get-ExecutionPolicy
If($Execution -eq "RemoteSigned")
{
Write-Host "HOI" -BackgroundColor Black -ForegroundColor Green
}
Else
{
Set-ExecutionPolicy Remotesigned
}
1.Module PSFTP importing
Import-Module PSFTP
$secpasswd = ConvertTo-SecureString “Wachtwoord” -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (“Admin”, $secpasswd)
Variables
$Session = "Alive"
$ftp = "IP"
$Credentials = "Admin"
$FtpFile = "C:\Test\Back-up.ps1"
$ftpDestination = "FTPLOCATIE"
2.Connect to FTP with module PSFTP
Set-FTPConnection -Server $ftp -Credentials $mycreds -Session $Session
( Connect to ftp)
3.TPItem for uploading to NAS
Get-ChildItem $FtpFile | Add-FTPItem -Session $Session -Path $ftpDestination -Overwrite
4.Section for mailing,variables
$secpasswd = ConvertTo-SecureString “Wachtwoord” -AsPlainText -Force
$mycredsMail = New-Object System.Management.Automation.PSCredential (“Email-address”, $secpasswd)
5. Section for mailing
$Smtp = "smtp.office365.com"
$Port = "587"
$To = "Email"
$Subject = "Back-up"
$From = "Email
6. this is where i want send the mail i use ssl
Send-MailMessage -to $To -from $From -Subject $Subject -SmtpServer $Smtp -Credential $mycredsMail -Port $Port -UseSsl

using secure password with multiple users without prompt

I am trying to have my password secured and stored in a file so that I don't need to enter each time when I run the script.
First step, I ran the following, entered the password which got stored into E:\cred.txt file. The txt file now contains an encrypted password.
(Get-Credential).Password | ConvertFrom-SecureString | Out-File "E:\cred.txt"
Secondly, I ran the below Script:
$File = "E:\cred.txt"
$User = "jason#domain.com"
#### I have two different user accounts, one for admin and other for operator,
#### however both user accounts use same password.
$adminuser = $User
$operator = $User -replace "#domain.com"
#### I would need to read $File to get only the password
$pass = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList (Get-Content $File | ConvertTo-SecureString)
$adminuser
$operator
$pass
Output:
jason#domain.com
jason
UserName Password
-------- --------
From the output, it seems New-Object refers to both UserName and Password. And when I try to connect to systems, it fails with Authentication error. Since I already have two different usernames hard coded within the script, how should I get only the password stored in $pass? or is it possible to include all usernames ($User, $adminuser, $operator) into the cred.txt file?
Try this:
#saving credentials
Get-Credential | Export-CliXml -Path c:\credential.xml
#importing credentials to a variable
$Credential = Import-CliXml -Path c:\credential.xml
Or this:
#you could then write it to a file or, i say its a better approach to a registry key
$SecurePassword = ConvertTo-SecureString -String 'P#ssw0rd' -AsPlainText -Force | ConvertFrom-SecureString
#now you are taking it back as a secure string
$RegistrySecureString = $SecurePassword | ConvertTo-SecureString
#you can aslo see the password
$UserName = "NULL"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $RegistrySecureString
$Password = $Credentials.GetNetworkCredential().Password
#P#ssw0rd

Processing a PowerShell SecureString as a parameter or console entry

I'm having a lot of difficulty with a PowerShell script that I'm trying to call a DirectoryServices query from. Currently, if I do a
$password = read-host "Password" -asSecureString
and subsequently
$credential = New-Object System.Management.Automation.PSCredential $username,$password
everything works fine. However if I try to pass the string parameter with a param($password) and then convert it to a secure string with this code:
$password = ConvertTo-SecureString -AsPlainText -Force $password
After extensive debugging I can see this is working fine in terms of converting the string to a securestring, but I get a bad user/password from DirectoryServices when I use the parameter. Everything works fine when read from the console. Any ideas on what I can do to accept a parameter OR take console input in the absence of a parameter?
This is what I was hoping would work, but doesn't:
if($password -eq $null) {
$password = read-host "Password" -asSecureString
} else {
$password = ConvertTo-SecureString -AsPlainText -Force $password
}
$credential = New-Object System.Management.Automation.PSCredential $username,$password
I recently created a script and was running into the same issue. The work around I found in my case was the following:
#Prompts for the username/password, enter the username in the form of DomainName\UserName
$Credential = get-credential
#Converts the password to clear text to pass it through correctly as passing through a secure string does not work.
$Password = $credential.GetNetworkCredential().password
#Converts the $Credential to just the DomainName/UsernName.
$Account = $credential.UserName
Hopefully this will work in your situation