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.
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).
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.
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.
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:
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.
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
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:
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.
There’s been a lot of discussion on the #PowerShell IRC channel about code signing lately — mostly in response to my earlier posts (which I won’t link to here, because I should probably retract some of it after the discussions we’ve had). The discussion mostly revolves around how code signing applies to the PowerShell script repository and users’ ability to trust scripts that they download.
In order to keep the conversation going, and hopefully, include some of the Microsoft MVPs and PowerShell developers that don’t participate in the IRC channel at all, I’m going to post a summary of the conclusions we’ve drawn so far, and then outline a proposal for the repository.
In case you don’t know, PowerShell implements code-signing for scripts using x509 Certificates (basically, SSL certs with “Extended” use properties), but the signatures are just embedded in the script as a comment, much like PGP signatures in email. Depending on your settings, the engine will actually check the signature on a script before executing it, and refuse to execute it if the signature isn’t valid, for instance, if the script has been modified, or the certificate used to sign it can’t be traced to a trusted Certificate Authority.
PowerShell code-signing is inconvenient, and expensive. Scripts are only Valid if they are signed, unmodified, and the certificate traces back to a CA(Certificate Authority) that is in your Trusted Roots store (by default, basically, Microsoft’s, VeriSign, Thawte, and Comodo).
You can create your own “test” certificate (that is, one that you sign yourself), but scripts signed by that certificate will only work on that computer. This system works fine for large companies which typically have either a subscription for purchasing certificates, or their own in-house trusted CA, but not for small private developers or open source script sharing communities without financial motivation.
Because of this, to take advantage of PowerShell’s code-signing on your computer (that is, to set your ExecutionPolicy to “AllSigned” or “RemoteSigned”) you must do one of these things:
So far, it seems like that last option is the only one that’s going to fly, because although some developers are willing to buy certificates to sign software they’re going to sell … most scripters and sys-admins aren’t willing to buy one to share their certificates for free. Read the rest of this entry »