How to use the Secret modules

Thomas

Q: I have a bunch of scripts we use in production that make use of Windows credentials. In some cases, these scripts accept an bodily password in manifestly text, while others read the password from an XML file. Is in that location a better fashion?

A: Scripts with high-privilege account passwords in manifestly text is not a good idea. There are several methods you tin use to ameliorate the security of credentials handling. Ane great way is to apply the SecretManagement and SecretStore modules from the PowerShell Gallery.

What are Secrets?

Secrets are, in general, passwords you need to access some resource. It might be the password for a domain administrator that you use to run a command on a remote host. You lot want to keep secrets surreptitious, notwithstanding you desire a great way to employ them as needed.

In my PowerShell books, I employ a domain (Reskit.Org) for all my examples. The password for this mythical domain's Enterprise and Domain administrator is "Pa$$W0rd". I am not too worried well-nigh exposing this password every bit it is only the password to a few dozen VMs. This ways many of the scripts from my books comprise the password in articulate text. While neat for books, this is non a best practice in production.

Over the years there take been numerous attempts at handling secrets. Y'all could store the secrets in an XML file and import the file when you needed those secrets. Or, you could strength the user to simply retype the password every fourth dimension they want to use it. Speaking personally – I get tired real fast of typing a long, circuitous, password time and time again!

What are the Secret modules?

The developers of this module recognized the challenge that users wanted consistency in managing secrets with flexibility over which hole-and-corner shop to use. The solution involves separating secrets management from secrets storage. So there there are two modules involved:

  • SecretManagement – you utilize this module in your scripts to make utilize of secrets.
  • SecretStore – this module contains the commands to manage a specific secret storage.

You lot besides need a vault-specific module which the SecretsStore module accesses. This layered approach allows you to use whatsoever secret store you wish, manage the secrets independently of the physical storage machinery. Yous could, in theory, change the underground shop and not need to modify your scripts that employ the secrets.

Installing the Modules

If yous want to follow along with the code and do not fancy cut/paste, I accept created a GitHub Gist for the code yous see in this commodity. Y'all can find it hither.

          PS> # 1. Discover the modules PS> Detect-Module -Name 'Microsoft.PowerShell.Secret*' |       Format-Table -Wrap -AutoSize  Version Proper name                                  Repository Description ------- ----                                  ---------- ----------- 1.1.0   Microsoft.PowerShell.SecretManagement PSGallery  This module provides a user-friendly style for a user                                                          to shop and remember secrets. The secrets are                                                          stored in registered extension vaults. An                                                           extension vault can shop secrets locally or remotely.                                                          SecretManagement coordinates admission to the secrets                                                          through the registered vaults.                                                          Go to GitHub for more information about the module                                                          and to submit issues:https://github.com/powershell/SecretManagement  1.0.4   Microsoft.PowerShell.SecretStore      PSGallery  This PowerShell module is an extension vault for the                                                          PowerShell SecretManagement module.                                                          Every bit an extension vault, this module stores secrets to the local                                                          machine based on the current user account context.                                                           The secrets are encrypted on file using .NETCrypto APIs.                                                           A password is required in the default configuration.                                                           The configuration can be inverse with the provided cmdlets.                                                          Go to GitHub for more data about this module                                                           and to submit bug: https:////github.com//powershell//SecretStore  PS> # 2. Install both modules PS> Install-Module -Name $Names -Forcefulness -AllowClobber        

When you lot install the module using Install-Module y'all see no output (unless yous use the -Verbose switch). Y'all tin always use Get-Module to check that you lot accept installed these new (to you lot) modules.

Discovering the commands available to you

One time you have thess 2 modules installed, you can discover the commands in each module:

                      PS> # 3. Examine them PS>PS> Become-Module -Name Microsoft*.Hush-hush* -ListAvailable |        Format-Table -Holding ModuleType, Version, Name, ExportedCmdlets  ModuleType Version Name                                  ExportedCmdlets ---------- ------- ----                                  ---------------     Binary 1.1.0   Microsoft.PowerShell.SecretManagement {[Annals-SecretVault, Register-SecretVault],                                                          [Unregister-SecretVault, Unregister-SecretVault], [Get-SecretVault,                                                             Become-SecretVault], [Set up-SecretVaultDefault, Set-SecretVaultDefault],                                                             [Test-SecretVault, Test-SecretVault], [Set-Secret, Set-Secret],                                                                 [Set-SecretInfo, Set-SecretInfo], [Go-Surreptitious, Get-Secret],                                                          [Get-SecretInfo, Get-SecretInfo], [Remove-Hugger-mugger, Remove-Hugger-mugger],                                                          [Unlock-SecretVault, Unlock-SecretVault]}     Binary i.0.5   Microsoft.PowerShell.SecretStore      {[Unlock-SecretStore, Unlock-SecretStore], [Set-SecretStorePassword,                                                            Gear up-SecretStorePassword], [Become-SecretStoreConfiguration,                                                          Get-SecretStoreConfiguration], [Ready-SecretStoreConfiguration,                                                          Set-SecretStoreConfiguration], [Reset-SecretStore,                                                          Reset-SecretStore]}                  

Every bit you tin see, both modules accept a number of commands you may need to use to manage secrets for your environment. Too – depending on your screen width you may notice your output is slightly diffetrent although it should contain the same information.

Registering and viewing a secret vault

After you have the two modules installed, your next stride is to annals a underground vault. In that location are several vault options yous can take reward of, for this postal service, I'll use the built-in default vault. You lot configure the default vault similar this:

          PS> # four. Register the default secrets provider PS> $Modern = 'Microsoft.PowerShell.SecretStore' PS> Annals-SecretVault -Name RKSecrets -ModuleName $Mod -DefaultVault PS> Get-SecretVault  Name      ModuleName                       IsDefaultVault ----      ----------                       -------------- RKSecrets Microsoft.PowerShell.SecretStore Truthful        

Like the previous footstep, registering the vault does not create any output by default. Yous tin view the vault you just created past using the Get-SecretVault control.

Setting a secret

To create a new surreptitious in your secret vault, you use the Set-Secret command, like this:

                      PS> # 4. Register the default secrets provider PS> Import-Module -Proper noun 'Microsoft.PowerShell.SecretManagement' PS> Import-Module -Name 'Microsoft.PowerShell.SecretStore' PS> $Modernistic = 'Microsoft.PowerShell.SecretStore' PS> Register-SecretVault -Proper name RKSecrets -ModuleName $Mod -DefaultVault PS> # 5. View Secret vault PS> Get-SecretVault  Name      ModuleName                       IsDefaultVault ----      ----------                       -------------- RKSecrets Microsoft.PowerShell.SecretStore True  PS C:Foo> # 6. Ready the Admin password secret for Reskit woods PS C:Foo> Set-Hugger-mugger -Name ReskitAdmin -Secret 'Pa$$w0rd' Creating a new RKSecrets vault. A password is required by the current store configuration. Enter password: ********** Enter countersign again for verification: **********        

This lawmaking fragment explicitly loads both of the downloaded modules. If you use PowerShell module automatic loading, this is unnecessary.

Also, the first time you utilize Set-Secret to create a secret, the cmdlet prompts for a vault password. Note this countersign isd Non stored in the AD – so don't forget it!!!

As an aside – I promise you noticed the bad practice in the higher up lawmaking – using a clear text password in a script file. A better approach to this for production coding would be to utilise Read-Host to have the countersign passed in. In this case, you meet the actual countersign I prepare, and later see that this password was indeed saved and retreived correctly.

Using secrets stored in your secret vault

Now that you have gear up a password in the RKSecrets vault, you can use the Become-Hush-hush cmdlet to retrieve the cloak-and-dagger. As y'all can encounter here, although yous set a evidently text countersign, Get-Secret returns the secret as a secure string.

          PS> # 7. Create a credential object using the secet PS> $User = 'Reskit\Administrator' PS> $PwSS = Get-Cloak-and-dagger ReskitAdmin PS> $Cred = [System.Management.Automation.PSCredential]::New($User,$PwSS) PS> # 8. Let's cheat and see what the password is first. PS> $PW = $Cred.GetNetworkCredential().Password PS> "Password for this credential is [$Pw]" Password for this credential is [Pa$$w0rd] PS> # 9. Using the credential against DC1 PS> $Cmd = {hostname.exe} PS> Invoke-Command -ComputerName DC1 -Credential $Cred -ScriptBlock $Cmd DC1        

As you tin can see, it is straightforward to create a new credential object using a password retrieved from the vault. This lawmaking creates a new PSCredential object, because that is what PowerShell cmdlets utilize to authenticate remoting sessions. Y'all can apply the credential object's GetNetworkCredential() method to retrieve the evidently text countersign.

If you are running this lawmaking, the offset time y'all create a vault, the secrets module requires you to specify a vault password. Depending on what sequence of commands y'all enter and how quickly, yous may be asked to re-enter your vault password.

If you lot accept a large numbers of secrets to manage, you tin add additional metadata to help you keep track of the secrets y'all set up. Metadata is a simple hash tabular array containing the metadata you wish to use to a hugger-mugger. Each item in the hash table is a key-value pair. The keys can be anything y'all wish such as the purpose of the script and the script author. Yous use Set-Secret to add together metadata to an existing (or new) secret. To set the metadata, you tin apply the Become-SecretInfo cmdlet. Creating and using metadata looks like this:

          PS> # 10. Setting metadata PS> Gear up-Undercover -Name ReskitAdmin -Hush-hush 'Pa$$w0rd' -Metadata @{Purpose="Reskit.Org Enterprise\Domain Admin Pow"} PS> Become-SecretInfo -Name ReskitAdmin | Select-Object -Property Name, Metadata  Proper noun        Metadata ----        -------- ReskitAdmin {[Purpose, Reskit.Org Enterprise/Domain Admin Prisoner of war]}  PS> # xi. Updating the metadata PS> Set-SecretInfo -Proper name ReskitAdmin -Metadata @{Author = 'DoctorDNS@Gmail.Com';                                              Purpose="Reskit.Org Enterprise\Domain Admin Pow"} PS> # 12. View undercover information with metadata PS> Get-SecretInfo -Proper noun ReskitAdmin | Select-Object -Belongings Name, Metadata  Proper name        Metadata ----        -------- ReskitAdmin {[Purpose, Reskit.Org Enterprise\Domain Admin PW],               [Author, DoctorDNS@Gmail.Com]}        

Equally noted, Metadata can exist any key-value pair you wish to add to the secret. In this case, the code set two metadata items: the purpose of the secret and its writer. Feel free to add whatsoever metadata makes sense to you and your organization.

Summary

The two secrets modules provide a groovy way to use secrets in your PowerShell scripts and go on the secrets secure. These two modules work both with Windows PowerShell and PowerShell 7. The default secrets vault works well plenty for most cases, but y'all take options. If there is an interest, I can create a farther blog post to wait at using unlike clandestine vaults.

So stop using plain text secrets in your PowerShell scripts and employ the secrets modules.