r/PowerShell • u/ITZ_RAWWW • Jun 30 '26
Solved Best way to Store Creds for Scripts?
Hey guys, for a long time I've been wondering what's the best way and most secure to store creds for powershell scripts? I know like absolute best (from my understanding) is to store them in some sort of 3rd party system and fetch them when needed say in secret server or the likes. Coming from a python background I know commonly you put stuff like that in a separate config file and import it.
So far I've been putting them in a json file and importing my creds that way but I can't help but think there's a more secure way. Like what's stopping an attacker on my system from just looking in the file and getting all my creds uk lol? Thanks for any advice!
128
u/JdoubleS98 Jun 30 '26
Hard code them and pretend like you didn't
64
u/MentalRip1893 Jun 30 '26
keeping your creds in plaintext is the worst way to do it. if you're on Windows, you could store them in Credential Manager. but what you want is some sort of secret server or key vault.
19
u/nealfive Jun 30 '26
I use the
https://github.com/PowerShell/SecretManagement
module, but it looks like the are sunsetting it :(
38
u/AdeelAutomates Jun 30 '26 edited Jun 30 '26
Locally you can leverage windows credentials manager if it's your machine you want to store them in. And then use
Get-StoredCredentialto get themI use key vault in Azure. Mainly for work but it's free to use for personal use as well. They will need an identity to login and access them during script runtimes.
You can run APIs or Az Module cmdlets to retrieve them from key vault.
11
u/purplemonkeymad Jun 30 '26
Are you talking service scripts or interactive?
For interactive you can use the Secrets module, and connect to a vault. You can then either unlock them before use or if you set the vault as a default it should prompt you for the password when something tries to retrieve the secret.
For service, it depends.
If you can use kerberos, then just use a gMSA so that it uses that principle. Or a keystore that supports kerberos.
If you can login as the running account then easiest is just letting powershell serialise a pscredential object (only valid on same account, same computer:)
If you can't login as the account, then you can use the *-cmsmessage commands with a certificate, to create a one way encrypted message for the script's principal to use. (you'll need to generate a certificate for the principal to decode it.)
5
u/Theratchetnclank Jun 30 '26
A shared secrets server or password manager.
Save the API used to access the server/password manager into a file accessible locally but crucially don't store in plain text use:
$apikey | ConvertTo-SecureString -asplaintext -force
and save that out to a file.
Then in subsequent scripts read in the encrypted string and decrypt to get the apikey.
$SecureString = Get-content file.txt -raw
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
$apikey = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
The api key will be in memory as plain text once decrypted but that's inevitable, but at least it wont be on disk.
13
u/dritmike Jun 30 '26
Plain text. In a text file next to the script labeled CREDENTIALS.txt
9
u/zero0n3 Jun 30 '26
gMSA acct - let AD manage the pw and manage the list of approved servers it can be used on.
Use gMSA acct to run script, or use it solely as your cred to access the “actual” credentials that do the “privileged work”
Make sure to sign your code as well.
And this is mainly for a basic starter setup where maybe it’s running as a scheduled task vs say using something like powershell flow or ansible
3
u/BigBobFro Jun 30 '26
Encrypted string stored in the HKCU hive. Decrypt with the machine cert (not transportable).
3
u/overlydelicioustea Jul 01 '26
there is no good way. dont hardcode password into script and use a credential safe? Well you need to tell the script how to access the safe..
Thats just the same issue pushed down one mor aisle.
the best solution is running the script under a user that has the neccesarry permissions.
2
u/dld2517 Jun 30 '26
PowerShell should be able to handle OAuth tokens - wouldn’t that be great.
2
u/RikiWardOG Jun 30 '26
Depends, what are you using the script for? Is it only running local? Running on other machines? etc. Options range from secrets management module to app registration with certificate and azure key vault. Really depends on needs and level of security required/how you're managing identities and what those secrets actually have keys to.
2
u/scor_butus Jun 30 '26
Powershell can use azure key vault as it's secret vault, instead of credential manager, directly. Use the microsoft.powershell.secretmanagement module.
Edit: can also use some other like keepass, hashicorp vault. Probably more.
2
u/cycoivan Jun 30 '26 edited Jun 30 '26
Way, way back in the day before my organization got Secret Server, I had a similar issue for when we needed to run unattended scripts on multiple machines. While I recommend the higher tech solutions if they work for you, this will work in a pinch. Pretty much you create your own AES Key, then encrypt the password out to a text file.
When you need to retrieve it you decrypt the password file with the stored key and create a credential object from the secure string. It'll look something like this. Make sure to store the key and password file in separate secure locations. 1 and 2 are part of a one time script. 3 needs to be on every other script that needs a credential.
#1. create the AES key$KeyFile = "C:\path\to\AES_KEY.key"$Key = New-Object Byte[] 32[System.Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)$Key | Out-File $KeyFile#2. create the encrypted password file$PasswordFile = "C:\path\to\encrypted_password.txt"$Key = Get-Content $KeyFile# Prompt for password and encryptRead-Host -AsSecureString | ConvertFrom-SecureString -Key $Key | Out-File $PasswordFile#3. when you need to create a credential object#EDIT you would need to redefine where $keyfile and $passwordfile are in your separate script$Key = Get-Content $KeyFile$EncryptedPwd = Get-Content $PasswordFile$SecurePwd = $EncryptedPwd | ConvertTo-SecureString -Key $Key# Create a PSCredential object$Credential = New-Object System.Management.Automation.PSCredential("Username", $SecurePwd)4.optional drop the unneded variables when you're done creating the credentialclear-variable key,encryptedpwd,securepwdThen it's just a matter of including -credential $credential on the commands you need to run that require elevated creds.
2
u/doughobbs Jul 01 '26
Azure key vault
Hashicorp vault
Call the script from a scheduled task that runs as the user you need
There are several ways
2
u/voobyStax Jul 03 '26 edited Jul 04 '26
If we’re talking a compromised system. That’s not really possible, for better or worse we live in a world where if there’s a will there’s a way. The CPU will always need instructions on how to use the password, so an attacker on the system could always in theory target that.
So your best bet is to prevent your system from getting compromised, keeping them on a separate device or using an isolated VM
As long as you’re taking precautions like not visiting sketchy websites, opening links in mails.(Period.) or opening ports on your firewall you don’t need to be opening you’re good.
As for the actual password, the absolute best is to have a separate for each login. We all know 99.9% won’t and will never. My rule of thumb things associated with eachother, DC and Admin account, Website login and email etc.. separate
Best way to do this while keeping them separate is to use passphrase, they’re waaaaaaaaaaaay easier to remember, Example:
Password: Ryshaer25$
Passphrase: RememberPassphraseBruteforceThrougher
That passphrase is not to hard to remember can even be written down with starting character if you want as a hint.
Hopefully this helps, stay secure, keep them away from AI’s
Edit: if you’re on Windows, TURN ON Bitlocker encrypting and set a BIOS password/pin/passphrase. Microsoft still haven’t patched the troubleshooting command prompt “privilege escalation”ish “feature” yet. I’ve know a about it for 10+ years.
2
u/Plug_USMC Jul 06 '26
Enterprise password vault
2
u/az987654 Jun 30 '26
Post it note, but on the underside of your keyboard.. No one will think to look there.
1
u/Liquidfoxx22 Jun 30 '26
Gmsa for local stuff. Azure key vault with managed identities if running on a trusted machine.
We worked a way of using PGP & Azure Key Vault for non-trusted machines.
1
u/jr49 Jun 30 '26
I use secure string but MS doesn’t recommend it anymore. You’d still need to compromise the host to get to them so it’s a bit more secure than plain text but depending on use case it will be decrypted in memory.
1
u/poolmanjim Jun 30 '26
It's been said here some, but the best way would be a Secrets Server or Vault or something.
Another option is to use CLIXML cmdlets if you are using an interactive prompt. The challenge this creates is for local system needs to run a script that needs a secret.
https://powershellisfun.com/2024/08/09/using-export-clixml-and-import-clixml-for-credentials-in-powershell-scripts/
Theoretical Option
I've been playing with this on the side for a off-domain/no-cloud solutions that cannot use traditional vaults. For example, I didn't want to have dependencies due to some BCDR concerns, but it needed to store creds to read some information. How would I store them.
If you have a Password as a SecureString it can't be read except by the user who created that secure string. This is a challenge for SYSTEM without using something like psexec (which I avoid).
The idea I was playing with was using a SecureString that has an associated certificate which would be installed on the system. This certificate would be used to do the encryption of the secure string, which makes the secure string exportable.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/convertto-securestring?view=powershell-7.6
Looking at -SecureKey or -Key, I believe was where I was going from. I posted about this in r/ActiveDirectory some time ago. Here's the link to that.
https://www.reddit.com/r/activedirectory/comments/1jgu2hh/thoughts_on_storing_user_creds_encrypted_using/
There are some limitations, but it does work and is more secure than storing it in a text file on the desktop. 😄
1
u/lister3000 Jun 30 '26
PowerShell has a secret management module, it's pretty decent for automated running
1
u/ostekages Jun 30 '26
I use Powershell Secret Management - to unlock the vault, a Get-Credential exported to a clixml file.
The clixml can only be opened by the same PC and same user that made it.
So all scripts run-as our script account, that made the clixml, and the Powershell secret vault had the individual secrets.
This way I can also rotate the clixml without impacting any scripts if needed
1
u/IndianaNetworkAdmin Jun 30 '26
Create your credential, then export it to a file. As long as your script runs on the same machine as the same user, you can re-use it.
It's not as secure as some methods, but it's better than plaintext.
1
u/McAUTS Jun 30 '26
I store the secure string that only the user, who encrypted the string, can decrypt. It is not perfect, but if you use a dedicated service account which runs the script then the attacker has some trouble to decrypt that.
Again, it's not perfect, but for my use cases it's okay I think.
1
u/xipodu Jun 30 '26
Keeping them in a crypted file that only can be opend with right account https://github.com/fardinbarashi/psGuiFilePasswordEncryptDecrypt
1
u/ftw_dan Jun 30 '26
I use 1password cli
1
u/chromespy200 Jun 30 '26
I use az keyvault / managed identities
Works great.
1
u/BlackV Jun 30 '26
As others said
What do your existing policies say, you said you were in the security team, so it think you would have guidance already
1
u/h0serdude Jun 30 '26
We use passwordstate API to pull creds on demand. They disappear once the script is done and are auto rotated so if a password changes the script is always pulling the latest.
1
u/CovertStatistician Jun 30 '26
Azure key vault but is paid, hashicorp vault and Doppler have free tier, some password managers like 1Password have secret storage and cli.. you could use certificates and lock them down to certain users, credential manager in windows
1
u/mjung79 Jun 30 '26
My preferred solution is to store secret data in Azure Keyvault. The script should fetch the secrets at runtime, preferably using its machine identity (Azure default credential) or else using a certificate for authentication to the cloud provider.
1
u/ashimbo Jun 30 '26
I like the TUN.CredentialManager module for storing creds in the built-in windows credential manager.
You have to store the creds using the same user account that will access the creds.
1
u/survivalist_guy Jun 30 '26
SecretsManagement module, windows credential store, or key vault
1
u/Conscious_Report1439 Jul 01 '26
Powershell module….PSInfisicalAPI and spin up a Infisical Secrets manager instance.
1
u/Th3Sh4d0wKn0ws Jul 01 '26
First step would be to leverage SecureString and Export-CliXml to store your creds with some encryption. However if an attacker gets access to the machine where Export-CliXml was run and your account then they can get the creds. If you run the scripts as a service account that you can't interactively log in with then you can use the service account to store credentials. https://courtneybodett.com/Secure-Creds-In-Powershell/
There's also the Secretsmanagement module but I haven't used it. Very first thing would be seeing if there's a way to do it without storing creds at all. Then if you absolutely must, securestring.
1
u/enforce1 Jul 01 '26
Use a key vault of some kind
1
u/theozero Jul 01 '26
Get everything out of plaintext.
check out varlock.dev - free and open source. Uses plugins to pull from most places youd want to store secrets, as well as supports built in local encryption. Adds validation and tons of other nice features too.
1
u/NeakoLeandros Jul 01 '26
Read up on the remote desktop connection manager rdg file and the rdcman.dll. You may have noticed that a RDG file with saved credentials, once moved to another user OR another computer, those saved credentials are no longer accessible. You can try another user on the same computer and it won't work. The encrypted password is there but it no longer decrypts. You can try the original user on another computer and it still won't work. I'm by no means the end all be all of security, but my paranoia has required me to test everything I could find and I've yet to find a way to crack it without the original computer and user Combination. I'm not saying someone else hasn't, or that's it's not possible, but if they have or it is, I've not yet found it. All that said something like Secret Server (Thycotic... I think, do they still exist?) or Cyberark is probably the better way to go if your implementation team is more than decent.
1
u/justaguyonthebus Jul 01 '26
One of the best ways is to store them in Azure key vault, then use a system assigned managed identity assigned to that system to access them. Then restrict access to that system to secured accounts.
1
u/KavyaJune Jul 01 '26
There are quite a few options that are more secure than storing credentials in a JSON file. For example, PowerShell Vault, Windows Credential Manager, Azure Key Vault. Also, use Managed identities or certificate-based authentication where possible, so you can avoid storing credentials altogether.
Each option has its own pros and trade-offs depending on whether you're automating locally, on servers, or in the cloud.
This guide compares the different approaches and when to use them: https://blog.admindroid.com/best-methods-to-securely-store-passwords-for-automated-powershell-scripts/
1
u/One_Baseball9801 Jul 01 '26
We worked on a similar scenario so the solution was to use the vaults but this may need a cloud account
1
u/corruptboomerang Jul 01 '26
Probably a bad solution, but I store mine in an encrypted file, that I put the
1
u/Ok_Society4599 Jul 01 '26
Visual Studio uses "developer secrets" in a user app data directory where the "application" is just a guide, the file format is JSON and should be fairly opaque where the credentials actually go. They aren't stored in version control, can be stored in a keystone, but copied to a user's system for Dev.
I've also used "safe strings" (I think that was the term) for PowerShell which are user token encrypted so every users strings are private to their instance. No other user or PC can decrypt the string.
1
u/digital-bandit Jul 01 '26
If interactive (not sched tasks that run by themselves for example) I use the 1Password CLI, check if you pw management solution has something equivalent.
1
u/SurzBoo Jul 01 '26
_env file or .env also works. Don't hardcode them in anything lmfao
1
u/Jacmac_ Jul 01 '26
Export-clixml. You must export the credential as the account that will import it. The exported credential can only be imported with the exporting account credential and it must be on the computer where it was exported from. This means that if you are logged on as joeadmin, but the script will running under serviceaccout1 and importing dbupload1 credential, you need to create a session using serviceaccount1 to export dbupload1. If you export dbupload1 under joeadmin, only joeadmin can import it.
1
u/mkdppwshr Jul 01 '26
Dpapi or windows cred store. Then write and pull your creds through there. Encrypted like the old efs system. So if you move machines or devices it wont work.
1
u/frAgileIT Jul 02 '26
I use PowerShell SecretStore in the Gallery. It’s easy to use. Just set up a vault and some secrets and then have your script pull from there using the service account principal via Scheduled Task.
1
u/SketchyPrivileges Jul 02 '26
What environment are you running this in? I ln my personal lab I let my script retrieve the credentials from 1Password at Runtime using the CLI plugin. Professionally I’ve used CyberArk Conjur (there’s also a free version), Key Vault, CyberArk Credential provider, etc.
1
u/zlappe Jul 03 '26
I would say that it depends on the level of security the password need to protected.
Is it a password that the script need to access for example a ftp i would use import/export-clixml
Them you can build it with levels on top.
Run the script as a schedule task with a gmsa account. Note that the xmlfile containing you secret need to be created by the gmsaaccount.
Then you can add a dfsshare with tight permissions that stores the xml, limit access to only the serviceaccount.
I wouldn’t store a domain admin password this way but it tightens the secret alot.
Happy hunting!
1
u/al_bundys_ghost Jul 03 '26
Organization specific, but I stored the credentials I needed in a CyberArk safe and retrieved them using the CyberArk REST API with certificate authentication. The certificate was stored in the personal store of the service account running the script.
1
u/TevePinch Jul 03 '26
Use Jenkins to run/automate/schedule scripts and save the credentials as secrets, works amazing for me.
1
u/gogreenenj Jul 04 '26
It’s 2026, claude.md
1
u/FeleaseRpseineEiles Jul 05 '26
I use bitwarden to save my bitwarden secrets manager key.
Then I use the bw cli to unlock it and retrieve it.
Then I use bws cli and it's key to get my api keys.
#!/bin/env bashread -sp 'GitHub Token: ' GH_TOKENecho ""# Install chezmoi nativelysh -c "$(curl -fsLS get.chezmoi.io)"# Init and apply using the token in the URL~/bin/chezmoi init --applyhttps://oauth2:${GH_TOKEN}@github.com/me/rc.gitI tie it all together with a public gist so all I have to do is paste my github token
ill call this from the shell like:
source <(curl -fsLS https://gist.githubusercontent.com/me/bootstrap.sh)paste the token and it installs chezmoi which handles my pre-reqs in a run_once_before_install_prereqs.sh script.
it'll install bw, bws, git, jq etc with my rc files and a few scripts for managing keys in bws and ssh keys in bw.
Using bw's ssh-agent then I get both API keys and SSH key managed without ever touch a private file on the system. Still need all the .ssh/id_*.pub files
1
u/gioXmama Jul 06 '26
The main question is what your end goal is and which credentials you're using. For example, if you're running a PowerShell script that leverages M365, Microsoft Graph, Exchange Online (EXO), or Teams, it's generally safe to store the credentials in a JSON file and import them later, but only if you're authenticating with a certificate.
Even if someone obtains the certificate thumbprint, they still can't authenticate without having access to the actual certificate. If you're using API keys instead, the situation is different, and I'm not sure what the security implications or best practices are in that case.
1
u/pertymoose Jul 07 '26
> Like what's stopping an attacker on my system from just looking in the file and getting all my creds uk lol?
If an attacker is already so deep in your server he can read the credentials off the disk, then there's really no security you can implement to stop him.
1
u/cw30755 Jul 01 '26
Just set the password to ******************. No one will ever catch on.
0
u/Bernd_Geralt_881 Jun 30 '26
Export-CliXml is the standard for service accounts, it encrypts with the machine/user key so only that account on that machine can decrypt it. If you need something more portable, the secretmanagement module with secretstore extension works well. Just avoid plaintext in scripts, even if its just a test environment, its a bad habit.
0
u/AnonRoot Jun 30 '26
powershell universal
-1
u/Apprehensive_Bat_980 Jun 30 '26
Notepad