I write a lot of PowerShell scripts, and I work on modules a lot, including ones which I load automatically in my profile. Sometimes I forget to sign those modules before I restart my console/host, and then I get errors when they’re loaded from the profile. I wrote a script to solve this problem by automatically signing files every time they’re edited, and I figured I’d share it below, but first let me try explaining what code signing is, and why you should care.
What is code signing?
Code signing is the process of digitally signing files to confirm the author and guarantee that the file has not been altered or corrupted. It’s essentially the same as signing emails: it guarantees that they were actually authored by the person claiming to be the author, and that they weren’t changed after the author signed them. (For more information see Apple’s explanation and Microsoft’s).
How does digital signing work?
Basically, digital signing is cryptography, so a full understanding of it really requires taking a 400-level college course, but here are the basics: You take some data (binary bits) and use a well-known algorithm to calculate what is called a “hash” of the bits. This hash is mathematically-generated from the source data, and so it can be re-calculated by the receiver. The hash is then “signed” via another algorithm: using a private key (see Public Key Infrastructure (PKI) for more about how these keys are managed) the signer encrypts the hash and attaches it to the file.
With public/private key encryption, data that is encrypted by the private key can be decrypted by the public key, so the encryption of the hash (and sometimes the public key, as well) is attached to the file so that the end user can re-calculate the hash and decrypt the signature to verify: a) that it was encrypted by the private key belonging to the author, and b) that the hash matches the hash that the author signed.
What’s all this about keys?
In PKI, the “key” is actually part of what’s called an SSL certificate issued to you by a Certificate Authority (CA) who verifies your identity. Verisign introduced the idea of “classes” for certificates, and you can now get free, Class 1 certificates for email signing from most CA’s now (like Thawte and Comodo and StartCOM), where the only thing they verify is that the person being issued the certificate can send/receive email at that address.
Of course, if you want to verify yourself as the author of code, we want to know more about you than your email address. So to sign code, you need at least a Class 2 certificate, for which proof of identity is required. This typically comes in the form of providing (photos of) your passport, driver’s license and/or other photo ID to verify that you are who you claim to be, and answering a few questions on the phone to validate that you own the phone number provided… or providing tax or other documents to prove the existence of an organization and that you’re qualified to speak for them. There are also additional classes: Class 3, 4, and 5 are extended validation certificates used for servers, software signing, b2b transactions and government security.
Why should I sign PowerShell scripts?
Well, the chances are, you don’t need to. Script signing is really a feature for corporations. The idea is that scripts from your IT department need to be verifiable and unalterable… code-signing gives companies a way to lock down and secure PowerShell scripts: setting a global policy requiring script signing, and ensuring that all scripts produced by the corporate administrators are properly signed…
As an individual, script-signing doesn’t really offer you much unless you share your computer with other administrator users. After all, what it protects you from is intentional or accidental altering of the script. If there’s no one else who has access to your computer, then nobody can alter your scripts. Of course, if someone hacks your computer enough to alter or create files on your hard drive and wanted to do something malicious, scripts would be a silly thing to target
There is, however, one additional time when you might want to sign your scripts. If you’re distributing scripts, whether via PoshCode.org, the TechNet script gallery, or on CodePlex or the MSDN code gallery … signing them gives you (and your users) the assurance that you are the author, and they haven’t been altered. In fact, the PoshCode Module which is available on PoshCode.org, and which allows you to search and download (as well as upload) PoshCode scripts uses script signing to allow it to safely upgrade itself. It features a Get-PoshCode -Upgrade command which will check for, and fetch, the latest version of the PoshCode module, and then validate it’s code signature is the same as the previous one before using it.
Remember, code signing cannot:
- Guarantee that code is free of security vulnerabilities.
- Guarantee that a script doesn’t load unsafe or altered code during execution.
- Prevent copying or altering of your scripts (although PowerShell policies can prevent accidental execution of altered scripts).
How do I sign scripts?
Assuming that after skimming all of that, you want to try signing your scripts, you need a certificate. You can generate one yourself (although it’s not easy, and the signed scripts which will only work locally on your system, and won’t be trusted by anyone else) or you can get one from a public Certificate Authority (I recommend StartCom/StartSSL which only costs $40 for two year certificates).
Typically, your certificate will be a .pfx file which you can load using Get-PfxCertificate, or you might have imported it into your local certificate store using CertMgr.msc, in which case you can load it using Get-Item Cert:\CurrentUser\My\ with the thumbprint of the certificate. In either case, you’ll have a certificate object you can pass to Set-AuthenticodeSignature along with the file path.
Wasn’t there supposed to be something automatic here?
Awhile back I wrote an Authenticode Script Module which has wrappers for signing and testing signatures on scripts. It uses a metadata file (which you have to create yourself) with a PrivateData variable that points to either the thumbprint of a certificate you’ve imported to your computer’s certificate store, or the path to a .pfx file … and allows you to sign files by just writing sign .\FileToSign.ps1 without having to Get-PfxCertificate each time, or even remember to turn on the -TimeStampUrl feature so that your signed scripts stay signed even after the certificate expires. That script helps a lot, but I’ve been wanting my text editor to sign the scripts automatically when I save them …
I mostly use Notepad++ for editing PowerShell scripts (with a PowerShell Syntax lexer I helped create), but after playing with the idea of writing a plugin to sign things after saving, I ended up deciding to go with something simpler: a PowerShell script to watch a folder for changes and sign any scripts I edit or save.
I’ve added a function I call Start-AutoSign to my authenticode script module which takes a path and a -Recurse flag and sets up a System.IO.FileSystemWatcher to detect saves, creates, and moves … and (re)sign the script if it needs it. Here is Start-AutoSign without the help docs or anything (so I can discuss it). You should just download the whole script module if you want to use it
if(!$NoNotify -and (Get-Module Growl -ListAvailable -ErrorAction 0)) {
Import-Module Growl
Register-GrowlType AutoSign "Signing File" -ErrorAction 0
} else { $NoNotify = $false }
$realItem = Get-Item $Path -ErrorAction Stop
if (-not $realItem) { return }
$Action = {
$InvalidForm = "The form specified for the subject is not one supported or known by the specified trust provider"
ForEach($file in Get-ChildItem $eventArgs.FullPath | Get-AuthenticodeSignature |
Where-Object { $_.Status -ne "Valid" -and $_.StatusMessage -ne $invalidForm } |
Select-Object -ExpandProperty Path )
{
if(!$NoNotify) {
Send-Growl AutoSign "Signing File" "File $($eventArgs.ChangeType), signing:" "$file"
}
if($CertPath) {
Set-AuthenticodeSignature -FilePath $file -Certificate $CertPath
} else {
Set-AuthenticodeSignature -FilePath $file
}
}
}
$watcher = New-Object IO.FileSystemWatcher $realItem.Fullname, $filter -Property @{ IncludeSubdirectories = $Recurse }
Register-ObjectEvent $watcher "Created" "AutoSignCreated$($realItem.Fullname)" -Action $Action > $null
Register-ObjectEvent $watcher "Changed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null
Register-ObjectEvent $watcher "Renamed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null
A few things to notice: first, I’m assuming you’re using my Set-AuthenticodeSignature wrapper, so by default I don’t pass it an actual certificate. Second, in order to avoid eternally looping and re-signing the script over-and-over, you have to have a way to make sure you don’t re-sign it when it “changes” because you signed it. The approach I took was to test and see if the signature was valid or not (and if it’s valid, then don’t sign it again). Third: when you Get-AuthenticodeSignature, the Status codes leave much to be desired, returning the same “UnknownError” in several cases where they know exactly what the error is. You can check the StatusMessage and see that they even tell you what the error was:
- The form specified for the subject is not one supported or known by the specified trust provider
- A certificate chain could not be built to a trusted root authority
- A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider
- A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file
There may be other reasons too that I haven’t encountered yet, but the one thing we’re concerned with is the first one that the “form” isn’t supported. That means this is a file type which Set-AuthenticodeSignature can’t sign. PowerShell’s signing only works with executables, PowerShell scripts, modules, metadata, and xml files … so there’s no point trying to sign anything else. You may also notice that in my script (by default) I’m only signing .ps* files (that is: scripts, modules, metadata and ps1xml files), and that’s because with .dll and .exe files, I would prefer to sign them as part of my build step anyway.
One last thing: as with a few of my recent scripts, this one is designed to use Growl for Windows to notify you whenever it signs anything. If you don’t have the Growl module available, it should just skip right over that without any problems, but you can disable it in any case with the -NoNotify switch. Personally, I like seeing the popup so that I know it’s working, and know that I’m not accidentally signing something … and I love Growl for script notices because I can skin it, configure sounds, and forward the notices to other machines … or even temporarily disable them, all without having to tweak scripts.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=3a72101f-e58c-47ed-accc-fc1c866ae964)
[...] but first let me try explaining what code signing is, and why you should care.huddledmasses.org, Huddled Masses, Nov [...]
[...] MVP Joel Bennett tells how to sign PowerShell scripts automatically [...]