Image

Image

Search This Blog

Tuesday, September 05, 2017

Deploy .pfx cert embedded in script (a sort of 'cat << EOF' for windows)

@echo off
::
::  
:: In order to prepare the certificate please run
:: 'certutil -encode the_pfx_cert base_64_cert`
:: then paste the base_64_cert in the section below
:: Please note that the certificate password has to be given as start paramater to this script!
:: (eq: "cert-inst.bat S3cr3tPassw0rd")

:: If the cert was already installed, exit
REG QUERY HKCU\SOFTWARE\neXt /v CertInstalled
If %errorlevel%==0 goto :eof

:: define the temp name of the extracted cert
set extractedfile=%temp%\extract-%random%.txt

:: set the password needed to decode the cert
set certpasswd=%~1

:: separate the cert from this script
call:extractembedded embeddedfile %extractedfile%

:: process the extracted file
certutil -decode %extractedfile% %extractedfile%.pfx

certutil -f -user -p %certpasswd% -importpfx %extractedfile%.pfx

:: clean-up
::del %extractedfile% %extractedfile%.pfx

:: leave a trace in the registry, so the cert will not be installed again and again
REG ADD HKCU\SOFTWARE\neXt /v CertInstalled /t REG_DWORD /d 1

:: clean exit
exit /b

:: begin of the embed cert & extraction procedure
:: After the next line, please paste the "base_64_cert" created by certutil -encode
goto:embeddedfile
-----BEGIN CERTIFICATE-----
MIIMngIBAzCCDGQGCSqG
[...]
k05EzAQIFXJaGHOuxZcCAggA
-----END CERTIFICATE-----
:embeddedfile
:: before the previous line you can find the end of the "base_64_cert"

:: cert extraction procedure
:extractembedded
setlocal EnableDelayedExpansion
set embedbegin=goto:%~1
set embedend=:%~1
set embedcert=%~2
if exist %embedcert% del %embedcert%
set tmprndfile=%temp%\%random%.%random%
findstr /n ^^ "%~f0" > %tmprndfile%
call :seekembed < %tmprndfile%
del %tmprndfile%
exit /B
:seekembed
set oneline=:eof
set /P oneline=
if !oneline! == :eof goto nostart
set oneline=!oneline:*:=!
if not !oneline! == %embedbegin% goto seekembed
:getline
set oneline=:eof
set /P oneline=
if !oneline! == :eof goto nostop
set oneline=!oneline:*:=!
if !oneline! == %embedend% goto :eof
echo/!oneline!>> %embedcert%
goto getline
:nostart
echo Error finding start delimiter %embedbegin%
goto :eof
:nostop
echo Error finding stop delimiter %embedend%
goto :eof

1 comment:

  1. You're so cool! I don't believe I have read a single thing like that
    before. So great to find someone with some original thoughts on this topic.
    Really.. thanks for starting this up. This web site is one thing that is
    required on the internet, someone with some originality!

    ReplyDelete

Blog Archive