Posts Tagged ‘Authenticode’
Signing PowerShell Scripts – Automatically
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.
PowerShell Authenticode Signatures and trust…
The cool thing about the way authenticode signatures are implemented is that even if a script is signed with a self-issued certificate, you can still tell if the script has been tampered with… Check this out:
Directory: SCRIPTS:\UnknownCert\
SignerCertificate Status Path
————————- ——— ——
0DA3A2A2189CD74AE371E6C57504FEB9A59BB22E UnknownError Sample.ps1
0DA3A2A2189CD74AE371E6C57504FEB9A59BB22E HashMismatch SampleBAD.ps1
Directory: SCRIPTS:\TrustedCert\
SignerCertificate Status Path
————————- ——— ——
B658C20AAD070B9FF105C69BBC47ADCF56FD5576 Valid Sample.ps1
B658C20AAD070B9FF105C69BBC47ADCF56FD5576 HashMismatch SampleBAD.ps1
As you can see, in the case of a UNTRUSTED, but correct, signature, you get the UnknownError status. If you checked the output object, it has a StatusMessage which says “A certificate chain could not be built to a trusted root authority”. If the script has been altered (as in my SampleBAD.ps1 scripts) then the signature is incorrect, you get the HashMismatch status, and the corresponding StatusMessage is: “The contents of file SCRIPTS:\TrustedCert\SampleBAD.ps1 may have been tampered because the hash of the file does not match the hash stored in the digital signature. The script will not execute on the system…”
One odd thing is that the messages are inaccurate about not executing the script: if you have your execution policy set to Unrestricted, the signatures aren’t checked at all, and if you have it set to RemoteSigned they are only checked for remote scripts. Furthermore: if you do have your execution policy set to AllSigned, neither the UnknownError nor the HashMismatch script will execute — only the one Valid scripts will.
So what?
The bottom line is: you can verify that nothing has happened to the script — even if you don’t trust the person who signed it nor the person, group, or company that issued a certificate to them. Why does this matter? Well, I recently wrote a post about generating self-signed code-signing certificates which can be used for signing PowerShell scripts, and if you chose to distribute scripts signed with one of those certificates, nobody would be able to verify the root CA(Certificate Authority) and so the signatures would never come out as valid.
Is there any usefulness in this? Well, I guess that depends on your perspective, but basically, I think that if I published my scripts signed and tell you on my blog what my certificate thumbprint is … that you’d be more able to trust those scripts than you are now (when they’re not signed at all). Of course, I could go one step further, and publish my own self-signed root CA certificate so you could choose to trust that …
I was recently having a conversation about the future of the PowerShell Script Repository and it involved some discussion of whether it would be safe to use the Repository Scripts to download dependencies automatically… The answer, obviously, is no.
But it started me thinking again about scripts being signed. If you had already chosen to run a script provided by me (which was signed by a certificate you couldn’t verify), maybe you’d be willing to trust other scripts signed by the same certificate, so we could automatically download them. Well, maybe even then you wouldn’t want to trust it, but lets assume that you were running a copy of the PowerShell Script Repository internally at your company …
Would you use automatic dependency downloading?
We could easily have a function that takes the script name and verifies that you have that script available — and if not, it could fetch the script from your designated repository and verify that the signature is valid even if the certificate isn’t signed by a root certificate authority you trust.
Of course, such automatically downloaded scripts would need to be marked as “Remote” so if you had your Execution Policy set to AllSigned or Remote Signed, then the script would only run if you had trusted it’s author (and you wouldn’t even be offered the option if you hadn’t trusted the CA(Certificate Authority) that issued his script. In that case you would need to review the script and re-sign it yourself — or manually remove the “remote” bit.
Imagine something like this:
# Get-Paste.ps1
function Get-Paste {
Resolve-Dependency Get-Webfile
# lots of code here that uses the Get-Webfile function ...
Get-Webfile http://HuddledMasses.org/
}
When you tried to execute Get-Paste, it would check for Get-Webfile, and if it couldn’t find it, would attempt to download it (presumably this would involve asking your permission, and placing it in some specific location that was in your PATH, so that the script could find it when it tried to execute it on the next line).
Or maybe, an Apt-Get?
Perhaps instead of this mechanism, we could use the new embeddable “Data Language” to provide a list of dependencies, like: DATA Dependencies { scripts = Get-WebFile } and run a Resolve-Dependencies function against each script before trying to execute it — this way, if you downloaded a script from the repository using Get-Paste, it could automatically Resolve-Dependencies and offer to download the other scripts at the same time.
The fact is that doing this correctly will require some major reworking of the script repository to allow tracking new versions of scripts better, and to let the script repository track dependencies explicitly so that you don’t have to download the whole script to find out what it’s dependencies are, but this could be done, if people are actually interested in it.
A web of trust?
Ad I’m thinking about this, I’m wondering again about the possibility of creating an informal web-of-trust style code-signing certificate tree. The idea would be that the Script Repository would have a CA certificate of it’s own, and would issue code-signing certificates to PowerShell developers cheaply (free?) by skipping over some of the usual verification steps. In an ideal world, Microsoft would issue the PowerShell Community a “SubCA” certificate signed by their root — in the interests of promoting code signing for PowerShell …
However, if we couldn’t get a SubCA certificate for “free” or cheap, we could simply generate and self-sign our own, and publish it on the Script Repository website, requiring users to download and import it into their trusted roots if they wanted to use trust permissions. Regardless of whether they chose to trust it or not, they could still verify the scripts were valid, which is better than what we have now — the rest would be up to the user.
Of course, if we were issuing certificates that were self-signed anyway, we could go a step further and sign SubCAs and distribute them to, say, the Microsoft PowerShell MVPs and trusted community leaders after verifying email addresses and physical mailing addresses etc … trusting them further to issue (less trusted) code-signing certificates to additional developers.
Call to action
All of this is extra work for the people maintaining the script repository web site (right now, that’s me), but it might be worth it if it makes it easier to use the script repository, easier to trust the scripts on it, and easier to verify that an author is who he says he is … what do you think?
- Should we put in the work to set up a web of trust or should we leave it up to individual developers to self-sign and generate their certificates (and publish their public roots on their websites or something)?
- Should we just leave it at that (scripters can sign their scripts if they feel like it), or should we push and promote script signing? As an incomplete example of promoting code-signing, I mean:
- We can use certificates as the primary (or only) way for authors to identify themselves (that is: no log-ins, unsigned scripts are marked “anonymous” ... but we track the thumbprints and allow you to browse scripts signed by the same author, etc).
- We can include the signature thumbprint with the short descriptions output on the search results and from the scripts which interact with repository.
- We can restrict “latest version” updates to only scripts which are signed, and optionally to new versions signed by the same certificate.
- Is there any point (or hope) in trying to get a signed CA certificate? Can Microsoft help us out? Do any of you work at a certificate authority?
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=3a72101f-e58c-47ed-accc-fc1c866ae964)