PowerShell Script Signing
A) Create SSL for Code Signing
Process below creates a self signed SSl for code signing in case you are developing for offline system or don't have a Domain. These are not usually the best for production env. but provides that same basic proection for script signing.
# Create a self-signed code signing certificate and store it in the Current User's Personal certificate store
$cert = New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -Type CodeSigningCert -Subject "CN=Internal_Certificate"
# Define the export path and password
$pfxPath = "C:\Cert\MyCertificate.pfx"
$password = ConvertTo-SecureString -String "Games!arefun!2Play@" -Force -AsPlainText
# Export the certificate to a .pfx file
Export-PfxCertificate -Cert $cert -FilePath $pfxPath -Password $password
​
# Got to C:\Cert\MyCertificate.pfx file you just created and import it to your local Trusted Root CA store on the machine
Sign The Script
This step is where we use the cert to sign the script.
# Import the Certificate Provider module if not already available
Import-Module PKI
# Retrieve the code signing certificate from the Current User's Personal certificate store
$cert = Get-ChildItem -Path Cert:\CurrentUser\My | Where-Object { $_.Subject -eq "CN=Internal_Certificate" }
# Path to your script
$scriptPath = "C:\PowerShell\myscript.ps1"
​
# Sign the script using the retrieved certificate
Set-AuthenticodeSignature -FilePath $scriptPath -Certificate $cert
Change the PowerShell Execution Policy
# -------------Check the current execution policy------------------
Get-ExecutionPolicy
​
# Open PowerShell as Administrator and set the execution policy
Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope LocalMachine
Check and Verify it Works
#------------------- Verification--------------------------------
# !!!!!! Run the script once in Powershell and set to (A) always allow when prompted. !!!!!!!
​
# Replace with the path to your script
$scriptPath = "C:\PowerShell\myscript.ps1"
​​
# Retrieve the signature information
$signature = Get-AuthenticodeSignature -FilePath $scriptPath
​​
# Display the signature status
$signature.Status
​​
# Now if the script is alerted in any way the hash mismatch appears and stops execution
Cleanup...
Remove the scirpt you used to create the SSL with the password and save in a secure location.
​
Remove the SSL PFX file from the server location C:\Cert\ adn store it in secure location.
​
Always use least priviledge when assinging rights to a service account, local administrator is not usually required.
​
Never place a service account in Domain Admins group.