Securing Powershell Scripts with Code-Signing Certificate


Ideally, all Powershell scripts should be signed by a code signing certificate by a certificate authority that is trusted by the host machine. You can also sign you Powershell script with a a self-signed code-signing certificate. You don't need any other tools like make cert to sign your Powershell script to generate self-signed code-signing certificate because Powershell has a built-in cmdlet (New-SelfSignedCertificate) to generate it.

Create a Self-Signed Code-Signing Certificate with Powershell CmdLet


$subject = "Imran Aftab Rana” 
$cert = New-SelfSignedCertificate -Subject $subject -Type CodeSigningCert -CertStoreLocation cert:\LocalMachine\My


The above cmdlet creates a self-signed code-signing certificate and places it in Local Machine Personal certificate store.

Export a Code-Signing Certificate with Powershell CmdLet

You can also export the certificate into a .p7b file and import it into another system or within same machine.

Export-Certificate -Cert $cert -FilePath C:\imranaftabrana.p7b -Type p7b

Import a Code-Signing Certificate to Trusted Store

You can import a code-signing certificate to a trusted store with Powershell CmdLet.

Import-Certificate -FilePath C:\imranaftabrana.p7b -CertStoreLocation Cert:\LocalMachine\Root

Searching existing certificate with Powershell CmdLet

If you have an existing certificate in local machine in certificate store and want to store its reference in Powershell object then you can find the certificate with following Powershell command:

$cert=(dir cert:currentuser\my\ -CodeSigningCert | Where {$_.Subject -eq "CN=ImranAftabRana"})

Code-Signing Powershell Script 

Finally, if you have a Powershell script lets say MyPowershellScript.ps1 then you can digitally sign it with following Powershell CmdLet:

Set-AuthenticodeSignature -Certificate $cert -FilePath "C:\MyPowershellScript.ps1"

Once a Powershell script is signed, there will be a digital signature appended at the end of script and if anyone makes a change in the Powershell script -  an error message will appears indicating that the scripts been modified :-)


Comments

Post a Comment

Popular posts from this blog

Implementing Basic and JWT Token authentication with C# .NET

Setting up Free Custom Domain on Microsoft Azure Web App Service

.NET Core 3 officially comes to Windows IoT Core

Setting up CI and CD pipeline in Azure DevOps for ASP.NET Core and Azure Web Apps

Microsoft Azure DevOps : A Complete CI & CD solution in the cloud

Microsoft Azure Blob Storage - Managing Blobs and storage containers from C#

Xamrin Android Push Notification using Firebase Cloud Messaging

Understanding Powershell ExecutionPolicy and securing Powershell CmdLets/Scripts with Code-Signing Certificate

Fundamental of Powershell Scripting