Tuesday, December 23, 2014

Powershell certificate signning

Mission:
Exeutable file that sign our certificate in "Trusted Root Certification Authorities".

Prerequisite:
- generate certificate(http://www.selfsignedcertificate.com)

Flow:
- by pass powershell execution policy
- write certificate to disk
- load certificate file to relevant store
- delete certificate file
- open certmgr
- compile ps file to exe using ps2exe (https://ps2exe.codeplex.com)

$certificate = @'
-----BEGIN CERTIFICATE-----
YOUR_CERTIFICATE_HERE
-----END CERTIFICATE-----
'@

#http://www.nivot.org/blog/post/2012/02/10/Bypassing-Restricted-Execution-Policy-in-Code-or-in-Script
function Disable-ExecutionPolicy {($ctx = $executioncontext.gettype().getfield("_context","nonpublic,instance").getvalue( $executioncontext)).gettype().getfield("_authorizationManager","nonpublic,instance").setvalue($ctx, (new-object System.Management.Automation.AuthorizationManager "Microsoft.PowerShell"))}

Disable-ExecutionPolicy

# Set the certificate file path
$certPath = ".deadbeef.cert"

# Write certificate to disk
$certificate | out-file $certPath

# Get the certificate store for "Trusted Root Certification Authorities" (Cert:\LocalMachine\Root)
$certStore = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store Root, LocalMachine

# Get the certificate from the location where it was placed by the export process
$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 $certPath

# delete certificate file from disk
Remove-Item $certPath

# Open the store with maximum allowed privileges
$certStore.Open("MaxAllowed")

# Add the certificate to the store
$certStore.Add($cert)

# Close the store
$certStore.Close()

# open certificate manager
Invoke-Item cert:\

No comments:

Post a Comment