Tags:
KeePass is a free, open source password manager utility. This article has two parts: 1) some sample PowerShell code for scripting KeePass, and 2) a few suggested best practices for securing KeePass on Windows.
[Update: There is now a GitHub project (PSKeePass) that incorporates this sample code; please look for updates there, it is far better than what's here.]
And if you want to launch PowerShell scripts from within KeePass while securely injecting passwords into those scripts too, see this article with sample code.
Background
KeePass can be freely installed on Windows, Linux, Mac OS X, Android, iPhone, Blackberry, and other platforms. KeePass runs on top of the .NET Framework or Mono, hence, it is accessible to PowerShell, C#, VB.NET and other .NET languages for use in scripts, command-line binaries, or graphical tools. KeePass includes an easy-to-use graphical interface by default.
KeePass can store many types of secrets, not just passwords, including files, images, scripts, encryption keys, credit card numbers, and other valuables.
KeePass includes several security features, has been around for years, and is actively maintained. It is one of the most popular password managers available on the Internet (and the current author's favorite). Importantly, KeePass is not implemented as a browser plug-in, which is a good thing: of all the applications running on a user's computer, the user's browser is the most likely to be attacked or infected with malware, so integrating a password manager directly into the browser is not ideal for security. KeePass runs as a separate process from the browser and communicates through the clipboard, which is architecturally safer.
There are many plug-ins for KeePass to enhance its capabilities, including a scripting utility if you don't want to write PowerShell or C# yourself. No plug-in is required, however, when scripting with PowerShell.
Sample PowerShell Code
Here is some not-fancy PowerShell sample code to get you started. It's just the bare minimum, so you'll need to adapt it for your own scripts. You can find more code samples on the Internet if you search for "PowerShell KeePass" and similar, such as this one on CodePlex.
You can download the following script and hundreds others in the SEC505 zip file from BlueTeamPowerShell.com. This script is one of the scripts given to attendees of the SANS six-day course on "Securing Windows and PowerShell Automation" (SEC505). All the SEC505 scripts are in the public domain. The KeePass script is in the zip file under \Day1\Crypto. There are other crypto-related scripts in there too, such as for DPAPI and the TrueRNG hardware random number generator.
############################################################################# Helper Function: Convert secure string back into plaintext ############################################################################ Function Convert-FromSecureStringToPlaintext ( $SecureString ) { [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)) } ########################################################################### # # Load the classes from KeePass.exe: # ########################################################################### $KeePassProgramFolder = Dir C:\'Program Files (x86)'\KeePass* | Select-Object -Last 1 $KeePassEXE = Join-Path -Path $KeePassProgramFolder -ChildPath "KeePass.exe" [Reflection.Assembly]::LoadFile($KeePassEXE) ########################################################################### # # To open a KeePass database, the decryption key is required, and this key # may be a constructed from a password, key file, Windows user account, # and/or other information sources. # ########################################################################### # $CompositeKey represents a key, possibly constructed from multiple sources of data. # The other key-related objects are added to this composite key. $CompositeKey = New-Object -TypeName KeePassLib.Keys.CompositeKey #From KeePass.exe # The currently logged-on Windows user account can be added to a composite key. $KcpUserAccount = New-Object -TypeName KeePassLib.Keys.KcpUserAccount #From KeePass.exe # A key file can be added to a composite key. $KeyFilePath = 'C:\SomeFolder\KeePassKeyFile.keyfile' $KcpKeyFile = New-Object -TypeName KeePassLib.Keys.KcpKeyFile($KeyFilePath) # A password can be added to a composite key. $Password = Read-Host -Prompt "Enter passphrase" -AsSecureString $Password = Convert-FromSecureStringToPlaintext -SecureString $Password $KcpPassword = New-Object -TypeName KeePassLib.Keys.KcpPassword($Password) # Add the Windows user account key to the $CompositeKey, if necessary: #$CompositeKey.AddUserKey( $KcpUserAccount ) $CompositeKey.AddUserKey( $KcpPassword ) $CompositeKey.AddUserKey( $KcpKeyFile ) ########################################################################### # # To open a KeePass database, the path to the .KDBX file is required. # ########################################################################### $IOConnectionInfo = New-Object KeePassLib.Serialization.IOConnectionInfo $IOConnectionInfo.Path = 'C:\SomeFolder\KeePass-Database.kdbx' ########################################################################### # # To open a KeePass database, an object is needed to record status info. # In this case, the progress status information is ignored. # ########################################################################### $StatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger ########################################################################### # # Open the KeePass database with key, path and logger objects. # $PwDatabase represents a KeePass database. # ########################################################################### $PwDatabase = New-Object -TypeName KeePassLib.PwDatabase #From KeePass.exe $PwDatabase.Open($IOConnectionInfo, $CompositeKey, $StatusLogger) ########################################################################### # # List groups. A group is shown as a folder name in the KeePass GUI. # ########################################################################### $PwDatabase.RootGroup.Groups $PwDatabase.RootGroup.Groups | Format-Table Name,LastModificationTime,Groups -AutoSize ########################################################################### # # List all entries from all groups, including nested groups. # ########################################################################### $PwDatabase.RootGroup.GetEntries($True) | ForEach { $_.Strings.ReadSafe("Title") + " : " + $_.Strings.ReadSafe("UserName") } ########################################################################### # # Get a particular group named 'Websites-1' and show some of its properties. # ########################################################################### $Group = $PwDatabase.RootGroup.Groups | Where { $_.Name -eq 'Websites-1' } $Group.Name $Group.Notes $Group.CreationTime $Group.LastAccessTime $Group.LastModificationTime $Group.GetEntriesCount($True) #Count of all entries, including in subgroups. ########################################################################### # # Get the unique UUID for the Websites-1 group. Objects in KeePass have # unique ID numbers so that multiple objects may have the same name. # ########################################################################### $Group.Uuid.ToHexString() [Byte[]] $byteArray = $Group.Uuid.UuidBytes ########################################################################### # # List the entries from the Websites-1 group, including plaintext passwords. # ########################################################################### $tempObj = " | Select Title,UserName,Password,URL,Notes $Group.GetEntries($True) | ForEach ` { $tempObj.Title = $_.Strings.ReadSafe("Title") $tempObj.UserName = $_.Strings.ReadSafe("UserName") $tempObj.Password = $_.Strings.ReadSafe("Password") $tempObj.URL = $_.Strings.ReadSafe("URL") $tempObj.Notes = $_.Strings.ReadSafe("Notes") $tempObj } ########################################################################### # # Export all the usernames and passwords from the Websites-1 group to an # XML temp file where the passwords are encrypted using the Data Protection # API (DPAPI) such that only the current user on the local computer can # recreate PSCredential objects from the data. Very useful when piped into # other cmdlets that accept a -Credential parameter, like Get-WmiObject. # Computer names (the "Titles") and usernames will be in plaintext in the # XML file, but the passwords will be encrypted using the DPAPI. # ########################################################################### $ServersHashTable = @{} #Key = computer name, Value = PSCredential object $Group.GetEntries($True) | ForEach ` { $ComputerName = $_.Strings.ReadSafe("Title") $UserName = $_.Strings.ReadSafe("UserName") $secureString = ConvertTo-SecureString -String ($_.Strings.ReadSafe("Password")) -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential($UserName, $secureString) $ServersHashTable.Add( $ComputerName, $Cred ) } $ServersHashTable | Export-Clixml -Path .\EncryptedForMe.xml $RestoredTable = Import-Clixml -Path .\EncryptedForMe.xml $cred = $RestoredTable.Item("server47.sans.org") #Example use ########################################################################### # # Function to return an entry from a KeePass database. # ########################################################################### function Get-KeePassEntryByTitle { <# .SYNOPSIS Find and return a KeePass entry from a group based on entry title. .DESCRIPTION After opening a KeePass database, provide the function with the name of a top-level group in KeePass (cannot be a nested subgroup) and the title of a unique entry in that group. The function returns the username, password, URL and notes for the entry by default, all in plaintext. Alternatively, just a PSCredential object may be returned instead; an object of the same type returned by the Get-Credential cmdlet. Note that the database is not closed by the function. .PARAMETER PwDatabase The previously-opened KeePass database object. .PARAMETER TopLevelGroupName Name of the KeePass folder. Must be top level, cannot be nested, and must be unique, i.e., no other groups/folders of the same name. .PARAMETER Title The title of the entry to return. Must be unique. .PARAMETER AsSecureStringCredential Switch to return a PSCredential object with just the username and password as a secure string. Username cannot be blank. The object is of the same type returned by the Get-Credential cmdlet. #> [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [KeePassLib.PwDatabase] $PwDatabase, [Parameter(Mandatory=$true)] [String] $TopLevelGroupName, [Parameter(Mandatory=$true)] [String] $Title, [Switch] $AsSecureStringCredential ) # This only works for a top-level group, not a nested subgroup (lazy). $PwGroup = @( $PwDatabase.RootGroup.Groups | where { $_.name -eq $TopLevelGroupName } ) # Confirm that one and only one matching group was found if ($PwGroup.Count -eq 0) { throw "ERROR: $TopLevelGroupName group not found" ; return } elseif ($PwGroup.Count -gt 1) { throw "ERROR: Multiple groups named $TopLevelGroupName" ; return } # Confirm that one and only one matching title was found $entry = @( $PwGroup[0].GetEntries($True) | Where { $_.Strings.ReadSafe("Title") -eq $Title } ) if ($entry.Count -eq 0) { throw "ERROR: $Title not found" ; return } elseif ($entry.Count -gt 1) { throw "ERROR: Multiple entries named $Title" ; return } if ($AsSecureStringCredential) { $secureString = ConvertTo-SecureString -String ($entry[0].Strings.ReadSafe("Password")) -AsPlainText -Force [string] $username = $entry[0].Strings.ReadSafe("UserName") if ($username.Length -eq 0){ throw "ERROR: Cannot create credential, username is blank" ; return } New-Object System.Management.Automation.PSCredential($username, $secureString) } else { $output = " | Select Title,UserName,Password,URL,Notes $output.Title = $entry[0].Strings.ReadSafe("Title") $output.UserName = $entry[0].Strings.ReadSafe("UserName") $output.Password = $entry[0].Strings.ReadSafe("Password") $output.URL = $entry[0].Strings.ReadSafe("URL") $output.Notes = $entry[0].Strings.ReadSafe("Notes") $output } } Get-KeePassEntryByTitle -PwDatabase $PwDatabase -TopLevelGroupName Websites-1 -Title paypal.com Get-KeePassEntryByTitle -PwDatabase $PwDatabase -TopLevelGroupName Websites-1 -Title Server47 -AsSecureStringCredential ########################################################################### # # Function to add an entry to a KeePass database. # ########################################################################### function New-KeePassEntry { <# .SYNOPSIS Adds a new KeePass entry. .DESCRIPTION Adds a new KeePass entry. The database must be opened first. The name of a top-level group/folder in KeePass and an entry title are mandatory, but all other arguments are optional. The group/folder must be at the top level in KeePass, i.e., it cannot be a nested subgroup. The password, if any, is passed in as plaintext unless you specify a PSCredential object, in which case the secure string from the PSCredential is converted to plaintext and then saved to the KeePass entry. The PSCredential object is normally created using the Get-Credential cmdlet. .PARAMETER PwDatabase The previously-opened KeePass database object (mandatory). .PARAMETER TopLevelGroupName Name of the KeePass folder (mandatory). Must be top level, cannot be nested, and must be unique, i.e., no other groups of the same name. .PARAMETER Title The title of the entry to add (mandatory). If possible, avoid duplicate titles for the sake of other KeePass scripts. .PARAMETER PSCredential A PowerShell secure string credential object (optional), typically created with the Get-Credential cmdlet. If this is specified, any UserName and Password parameters are ignored and the KeePass entry will be created using the user name and plaintext password of the PSCredential object. Other data, such as Notes or URL, may still be added. The KeePass entry will have the plaintext password from the PSCredential in the KeePass GUI, not the secure string. .PARAMETER UserName The user name of the entry to add, if no PSCredential. .PARAMETER Password The password of the entry to add, in plaintext, if no PSCredential. .PARAMETER URL The URL of the entry to add. .PARAMETER Notes The Notes of the entry to add. #> [CmdletBinding(DefaultParametersetName="Plain")] Param ( [Parameter(Mandatory=$true)] [KeePassLib.PwDatabase] $PwDatabase, [Parameter(Mandatory=$true)] [String] $TopLevelGroupName, [Parameter(Mandatory=$true)] [String] $Title, [Parameter(ParameterSetName="Plain")] [String] $UserName, [Parameter(ParameterSetName="Plain")] [String] $Password, [Parameter(ParameterSetName="Cred")] [System.Management.Automation.PSCredential] $PSCredential, [String] $URL, [String] $Notes ) # This only works for a top-level group, not a nested subgroup: $PwGroup = @( $PwDatabase.RootGroup.Groups | where { $_.name -eq $TopLevelGroupName } ) # Confirm that one and only one matching group was found if ($PwGroup.Count -eq 0) { throw "ERROR: $TopLevelGroupName group not found" ; return } elseif ($PwGroup.Count -gt 1) { throw "ERROR: Multiple groups named $TopLevelGroupName" ; return } # Use PSCredential, if provided, for username and password: if ($PSCredential) { $UserName = $PSCredential.UserName $Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($PSCredential.Password)) } # The $True arguments allow new UUID and timestamps to be created automatically: $PwEntry = New-Object -TypeName KeePassLib.PwEntry( $PwGroup[0], $True, $True ) # Protected strings are encrypted in memory: $pTitle = New-Object KeePassLib.Security.ProtectedString($True, $Title) $pUser = New-Object KeePassLib.Security.ProtectedString($True, $UserName) $pPW = New-Object KeePassLib.Security.ProtectedString($True, $Password) $pURL = New-Object KeePassLib.Security.ProtectedString($True, $URL) $pNotes = New-Object KeePassLib.Security.ProtectedString($True, $Notes) $PwEntry.Strings.Set("Title", $pTitle) $PwEntry.Strings.Set("UserName", $pUser) $PwEntry.Strings.Set("Password", $pPW) $PwEntry.Strings.Set("URL", $pURL) $PwEntry.Strings.Set("Notes", $pNotes) $PwGroup[0].AddEntry($PwEntry, $True) # Notice that the database is automatically saved here! $StatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger $PwDatabase.Save($StatusLogger) } New-KeePassEntry -PwDatabase $PwDatabase -TopLevelGroupName 'Wireless' -Title 'TestingPlain' -UserName "UserTest99" -Password "Pazzwurd" -URL "http://www.sans.org/sec505" -Notes "Some notes here." $cred = Get-Credential New-KeePassEntry -PwDatabase $PwDatabase -TopLevelGroupName 'Wireless' -Title 'TestingCred' -PSCredential $cred ########################################################################### # # Close the open database. Don't forget! # ########################################################################### $PwDatabase.Close()
Best Practices for KeePass
Here are a few best practices that are somewhat unique to KeePass. This isn't an exhaustive list, it just contains some important items that are sometimes overlooked, and some recommendations are only for IT personnel, not for users in general:
* When scripting KeePass, avoid displaying plaintext passwords in the shell or saving plaintext passwords to files. If transcript logging is enabled, which logs all commands and output to a file, then never display passwords. Instead, use PSCredential objects (in memory or exported with Export-CliXml), pipe passwords directly to the clipboard with clip.exe or Set-Clipboard, or at least place the password in a variable for use. When exporting PSCredential objects to a temp file, the passwords are encrypted using DPAPI, but it's also good to use UEFI Secure Boot and BitLocker too because of weaknesses in DPAPI. When done with the temp file, sector-scrub it off the drive or use a RAM drive, don't just delete it normally (which may move it into the Recycle Bin).
* KeePass can be installed and run entirely from an NTFS-formatted flash drive. The flash drive can be unplugged at the end of the day to sleep better at night (nothing like a true air gap). NTFS permissions, auditing, and BitLocker can all be used to help secure the flash drive itself.
* Use a combination of a master passphrase and a seed key file to generate the final key used to encrypt the database. The key file should be kept in a different folder than the KeePass database file or the KeePass program, and its name and folder should not indicate that it is being used as a KeePass key file. Even if a keystroke logger has captured the master passphrase, the key file would still also need to be stolen too in order to decrypt the database. The key file can also be stored on a thumb drive, which can also be disconnected when not in use.
* Read and write access to the KeePass database file and key file should be restricted with both NTFS permissions and an MIC integrity level set to High. This means the KeePass program will have to be launched elevated every time (modify the shortcut). Do not turn off User Account Control (UAC) prompting either. Below are some sample CHML.EXE commands for modifying integrity labels. One of the advantages of running KeePass elevated is that your browser, PDF viewer and e-mail application will be running as a standard (sandboxed) process for the sake of User Interface Privilege Isolation (UIPI).
* Require switching to the User Account Control (UAC) secure desktop before entering the decryption passphrase. To do so, enable the option named "Enter master key on secure desktop" (Tools menu > Options > Security tab).
* Because laptops and tablets are more likely to be lost or stolen, on these devices in particular make sure to enable the option named "Lock workspace when the computer is about to be suspended" (Tools menu > Options > Security tab).
* Do not use the Windows account integration feature. This protects the KeePass database using the same techniques as the Windows Credential Manager, which isn't necessarily bad, but we want separation from Windows integration in this case. Also, troubleshooting SID issues with the Data Protection API (DPAPI) is not fun, such as when trying to move DPAPI-encrypted data from one machine to another or rebuilding a broken machine from scratch.
* If you choose to sync the KeePass database file over the network, use native Windows IPSec and/or SMB encryption, and confirm that the share and NTFS permissions are minimal on the SMB server. If you'd rather use SCP, SFTP or FTPS instead, there are KeePass extensions for these protocols too. Using a cloud provider can be secure, but it very much depends on the details of the cloud provider's security options and how they are configured. Always assume that your adversaries will get a copy of your encrypted database, hence, use a long passphrase and secondary key file.
* (Optional) Help hide the path to the key file on shared computers by disabling the option named "Remember key sources" (Tools menu > Options > Advanced tab). This is a minor issue though, it's not mandatory, since it will only be an inconvenience to a skilled adversary.
To use CHML.EXE to change the MIC label and rules on the KeePass files:
chml.exe DatabaseFilePath.kdbx -i:h -nr -nw -nx chml.exe KeyFilePath.gif -i:h -nr -nw -nx
Update History & Legal Stuff
As usual, the SEC505 scripts and best practices are in the public domain and provided "AS IS" without warranties or guarantees of any kind, use at your own risk.
12.Aug.2015: First posted.
19.Aug.2015: Added some functions and the DPAPI stuff.
27.May.2016: Added note about the GitHub project for this.
17.May.2021: Fixed download link.