Using a Yubikey for PowerShell CodeSigning
PowerShell is a powerful automation and configuration management tool widely used by system administrators and developers. However, running untrusted PowerShell scripts can pose security risks, as malicious code could potentially harm your system or steal sensitive data. To mitigate these risks, it’s important to sign your PowerShell scripts with a trusted digital certificate. One convenient and secure way to do this is by using a YubiKey – a hardware security key that provides strong two-factor authentication and can also store code signing certificates to sign the PowerShell script code with YubiKey.
In this comprehensive guide, we’ll walk you through the process of signing PowerShell script code using a YubiKey. We’ll cover everything from setting up your YubiKey, generating a code signing certificate, and configuring PowerShell’s execution policy to actually signing your script files. By the end, you’ll have the knowledge and tools to ensure the integrity and authenticity of your PowerShell scripts.
Key Takeaways
- Signing PowerShell scripts with a digital certificate enhances security by verifying the script’s authenticity and integrity.
- YubiKeys provide a secure and portable way to store code-signing certificates.
- Configuring PowerShell’s execution policy is crucial for running signed scripts.
- The Set-AuthenticodeSignature cmdlet is actually used to sign PowerShell script files.
Understanding Code Signing and YubiKeys
Before we dive into the hands-on steps, let’s first cover some background information on code signing and YubiKeys.
What is Code Signing?
Code signing is the process of digitally signing executable code and scripts to verify the software author’s identity and ensure that the code has not been altered or corrupted since it was signed. When you sign the code, you attach a digital signature that includes information about the signer and a hash of the code. This allows users to verify that the code originated from a trusted source and hasn’t been tampered with.
Code signing helps protect against malicious scripts in PowerShell. By default, PowerShell’s execution policy is set to “Restricted,” which prevents scripts from running. To run your scripts, you need to either relax the execution policy (not recommended) or sign your scripts with a trusted certificate.
What are YubiKeys?
YubiKeys are small hardware devices, typically in the form of a USB key, that provide secure two-factor authentication and can also store cryptographic keys and certificates. They are manufactured by Yubico and are used to enhance security for online accounts, password managers, computer logins, and more.
One advantage of YubiKeys is that they perform cryptographic operations on the device itself rather than exposing the private key to the host computer. This makes them much more secure against malware and phishing attacks compared to software-based keys.
For code signing, YubiKeys can generate and store code-signing certificates directly on the device. This provides an extra layer of protection, as the private key never leaves the YubiKey. Even if your computer is compromised, attackers won’t be able to access or steal your code signing key.
Setting Up Your YubiKey for Code Signing
Now that you understand the basics of code signing and YubiKeys let’s set up your YubiKey to sign PowerShell scripts.
Step 1: Install the YubiKey Manager
The first step is to install the YubiKey Manager application on your computer. This app allows you to configure and manage your YubiKey.
- Go to the Yubico website’s YubiKey Manager download page
- Download the appropriate version for your operating system (Windows, macOS, or Linux)
- Run the installer and follow the prompts to complete the installation
Step 2: Check Your YubiKey’s Firmware Version
Before proceeding, check that your YubiKey’s firmware is up to date. Newer firmware versions often include security enhancements and bug fixes.
- Insert your YubiKey into a USB port on your computer
- Open the YubiKey Manager application
- Click on the “Device” tab to see information about your YubiKey, including the firmware version
- If a newer firmware version is available, follow Yubico’s instructions to upgrade your YubiKey
Step 3: Generate a Code Signing Certificate
With your YubiKey set up, you’re ready to generate a code-signing certificate. There are several different ways to obtain a code-signing certificate, such as through a public certificate authority (CA) or by generating a self-signed certificate. For this guide, we’ll use a self-signed certificate for simplicity.
- Open PowerShell as an administrator
- Install the Yubico.YubiKey PowerShell module by running:
Install-Module -Name Yubico.YubiKey
- Generate a new self-signed code signing certificate with:
$cert = New-YubiKeySelfSignedCert -Subject "CN=PowerShell Code Signing" -KeyAlgorithm RSA -KeyLength 2048 -CertType CodeSigningCert -ValidDays 365
- Verify the certificate:
Get-YubiKeyCert
You should see details about the code signing certificate you just created.
Configuring PowerShell Script Execution Policy
With your code signing certificate in place, the next step is to configure PowerShell to allow scripts signed with your cert to run. This is done through PowerShell’s execution policy settings.
Understanding Execution Policies
PowerShell’s execution policies help control the conditions under which PowerShell loads and runs scripts. There are several execution policy levels:
- Restricted (default): No scripts can run
- AllSigned: Only signed scripts can run, including both locally created and downloaded scripts
- RemoteSigned: Locally created scripts can run unsigned, but downloaded scripts must be signed
- Unrestricted: All scripts can run, regardless of whether they are signed (not recommended)
For our purposes, we’ll set the execution policy to AllSigned, which will allow us to run scripts signed with your YubiKey code signing cert.
Setting the Execution Policy
- Open PowerShell as an administrator
- Check the current execution policy:
Get-ExecutionPolicy
- Change the execution policy to AllSigned:
Set-ExecutionPolicy AllSigned
- Confirm the change by pressing “Y”
Now, PowerShell will only run scripts that have been signed with a trusted certificate. Unsigned scripts will be blocked.
Signing Your PowerShell Script Code
Finally, we get to the actual process of signing your PowerShell script files with the YubiKey code signing certificate.
Step 1: Write Your PowerShell Script
Start by creating the PowerShell script you want to sign. For this example, we’ll use a simple “Hello World” script:
- Open your favourite text editor
- Create a new file named HelloWorld.ps1
- Add the following code:
Write-Host "Hello World!"
- Save the file
Step 2: Sign the Script with YubiKey
Now we’ll use the Set-AuthenticodeSignature cmdlet along with the YubiKey PowerShell module to sign the script:
- Open PowerShell
- Navigate to the directory containing your HelloWorld.ps1 script
- Run the following command to sign the script:
Set-AuthenticodeSignature -FilePath .\HelloWorld.ps1 -Certificate (Get-YubiKeyCert -ValidOnly)
- Verify the script signature:
Get-AuthenticodeSignature .\HelloWorld.ps1 | Format-List
This displays information about the signature, including the signer’s certificate details. Ensure that the status shows “Valid”.
Step 3: Run the Signed Script
With the script signed, you can now execute it:
- Run the script with:
.\HelloWorld.ps1
Since the script is signed correctly and PowerShell’s execution policy is set to AllSigned, the script is allowed to run. You should see the “Hello World!” output.
Automating the Signing Process
If you have multiple PowerShell scripts that need to be signed, manually signing each one can be tedious. Fortunately, you can automate the process using a simple PowerShell script.
Creating the Signing Script
- Create a new PowerShell script file named SignScripts.ps1
- Add the following code:
$cert = Get-YubiKeyCert -ValidOnly
$scriptFiles = Get-ChildItem -Path "C:\Scripts" -Filter "*.ps1"
foreach ($file in $scriptFiles) {
Set-AuthenticodeSignature -FilePath $file.FullName -Certificate $cert
Write-Host "Signed $($file.Name)"
}
This script does the following:
- Retrieves the valid code signing certificate from the YubiKey
- Gets a list of all .ps1 script files in the specified directory (C:\Scripts in this example)
- Loops through each script file and signs it with the YubiKey certificate
- Outputs a message indicating which file was signed
- Save the SignScripts.ps1 file
Running the Signing Script
- Open PowerShell
- Navigate to the directory containing your SignScripts.ps1 file
- Run the script:
.\SignScripts.ps1
You’ll be prompted to touch your YubiKey to authorize each signing operation. Once complete, all the .ps1 files in the specified directory will be signed.
Best Practices for Code Signing
While signing your PowerShell scripts with a YubiKey provides a high level of security, there are some additional best practices to keep in mind:
- Keep your YubiKey physically secure, and don’t leave it unattended.
- Enable a PIN on your YubiKey for an extra layer of protection.
- Use a separate YubiKey for code signing versus your other security keys.
- If using a self-signed certificate, add it to the Trusted Publishers certificate store on machines where the scripts will run.
- Regularly review and audit your signed scripts to ensure they haven’t been tampered with
- Have a plan for certificate expiration and renewal.
By following these practices, you can further enhance the security and integrity of your PowerShell scripting environment.
Conclusion
In this guide, we’ve covered the process of signing PowerShell script code using a YubiKey hardware security key. We discussed the importance of code signing and the benefits of using a YubiKey and walked through the steps of setting up your YubiKey, generating a code signing certificate, configuring PowerShell execution policies, and signing your script files.
By implementing code signing with a YubiKey, you can ensure that your PowerShell scripts are authentic, have not been tampered with, and originate from a trusted source. This helps protect against malicious scripts and enhances the overall security of your scripting environment.
Remember to follow best practices for managing your YubiKey and code signing process. With these tools and techniques, you can confidently develop and deploy PowerShell scripts while maintaining a high level of security.
FAQs About Sign the PowerShell Script Code with YubiKey
Can I use a YubiKey for code signing on multiple computers?
Yes, you can use the same YubiKey to sign code on multiple computers. The YubiKey stores the private key securely on the device itself, so you can plug it into different machines and use it to sign without exposing the key. Just make sure to have the necessary YubiKey software and drivers installed on each computer.
What happens if I lose my YubiKey?
If you lose your YubiKey, you’ll no longer be able to sign the code with the certificate stored on that key. However, you can mitigate the risk by having a backup YubiKey with the same certificate or by using a separate certificate issued by a trusted CA. It’s also a good idea to revoke the lost YubiKey certificate to prevent unauthorized use if someone else finds it.
How do I renew or replace an expired code signing certificate on my YubiKey?
The process for renewing or replacing a code signing certificate on your YubiKey is similar to generating a new one. You’ll need to use the YubiKey Manager or PowerShell tools to develop a new certificate signing request (CSR), submit it to your chosen certificate authority, and then import the issued certificate back onto your YubiKey. Be sure to plan and renew your certificates before they expire to avoid interruptions.
Can I use a YubiKey to sign code other than PowerShell scripts?
Yes, YubiKeys can be used to sign various types of code and executables, not just PowerShell scripts. The specific steps and tools may vary depending on the programming language and platform. Still, the general principles of generating a certificate, configuring your environment to use the YubiKey, and signing the code remain the same. Check the documentation for your particular use case to learn more.
Are there any limitations to using a YubiKey for code signing?
One limitation of using a YubiKey for code signing is that the key must be physically present to sign the code. This can be inconvenient in automated build and deployment scenarios where signing needs to happen on a server or CI/CD pipeline. In such cases, a hardware security module (HSM) or a cloud-based code signing service may be more suitable. Additionally, YubiKeys have limited storage capacity, so you may need multiple keys if you have many certificates or other credentials to store.
How do I securely back up my code signing certificates?
Backing up your code signing certificates is important to ensure continuity in case of loss or damage to your YubiKey. However, you must be careful to protect the backup from unauthorized access. One approach is to use a second YubiKey as a backup, keeping it in a secure location like a safe deposit box. Alternatively, you can export the certificate and private key to a password-protected file and then store that file on an encrypted drive or secure storage service. Always follow best practices for managing private keys and sensitive data.
Priya Mervana
Verified Web Security Experts
Priya Mervana is working at SSLInsights.com as a web security expert with over 10 years of experience writing about encryption, SSL certificates, and online privacy. She aims to make complex security topics easily understandable for everyday internet users.