REM Microsoft (R) IISCertDeploy.vbs Version 1.0
REM Copyright (C) 2003 Microsoft Corporation. All rights reserved.
REM
REM IISCertDeploy.vbs for usage info
REM


REM
REM LOCALIZATION
REM

L_SWITCH_HELP          = "-h"
L_SWITCH_CER           = "-new"
L_SWITCH_PFX           = "-c"
L_SWITCH_PFX_EXPORT    = "-e"
L_SWITCH_PFX_PASSWORD  = "-p"
L_SWITCH_INSTANCE_ID   = "-i"
L_SWITCH_PORT          = "-port"
L_SWITCH_SERVER        = "-s"
L_SWITCH_USER          = "-u"
L_SWITCH_PASSWORD      = "-pwd"
L_SWITCH_QUERY         = "-q"

L_DESC_COPYRIGHT       = _
"Microsoft (R) IISCertDeploy.vbs Version 1.0" & vbCrLf & _
"Copyright (C) 2003 Microsoft Corporation. All rights reserved." & vbCrLf

L_DESC_PROGRAM         = _
"INSTALLING A CERTIFICATE (.cer):" & vbCrLf & _
"--------------------------------" & vbCrLf & _
"Usage:    IISCertDeploy.vbs -new <cer_file> -c <pfx_file> -p <pfx_password>" & vbCrLf & _
"                      [-i <site>] [-port <secure_bindings>] [-u <user_name>]" & vbCrLf & _
"                      [-pwd <user_password>] [-q <ON|OFF>]" & vbCrLf & _
"" & vbCrLf & _
"Example:  IISCertDeploy.vbs -new certnew.cer -c certnew.pfx -p pfxpassword" & vbCrLf & _
"" & vbCrLf & _
"" & vbCrLf & _
"BACKING UP A CERTIFICATEE (to .pfx):" & vbCrLf & _
"-----------------------------------" & vbCrLf & _
"Usage:    IISCertDeploy.vbs -e <pfx_file> -p <pfx_password> [-i <site>]" & vbCrLf & _
"             [-s <server>] [-u <user_name>] [-pwd <user_password>] [-q <ON|OFF>]" & vbCrLf & _
"" & vbCrLf & _
"Example:  IISCertDeploy.vbs -e backup.pfx -p pfxpassword" & vbCrLf & _
"" & vbCrLf & _
"" & vbCrLf & _
"RESTORING A CERTIFICATE (from .pfx) / DEPLOYING A CERTIFICATE IN A CLUSTER:" & vbCrLf & _
"---------------------------------------------------------------------------" & vbCrLf & _
"Usage:    IISCertDeploy.vbs -c <pfx_file> [-p <pfx_password>] [-i <site>]" & vbCrLf & _
"                      [-port <secure_bindings>] [-s <server>] [-u <user_name>]" & vbCrLf & _
"                      [-pwd <user_password>] [-q <ON|OFF>]" & vbCrLf & _
"" & vbCrLf & _
"Example:  IISCertDeploy.vbs -c cert.pfx -p pfxpassword -i w3svc/1 -s iisserver1" & vbCrLf & _
"                            -u Administrator -pwd aal92790" & vbCrLf & _
"" & vbCrLf & _
"" & vbCrLf & _
"-new <cer_file>         : name of the .cer file that you received from your CA." & vbCrLf & _
"-c <pfx_file>           : name of .pfx file to import" & vbCrLf & _
"-e <pfx_file>           : name of the .pfx file that will be generated (this" & vbCrLf & _
"                          file contains certificate along with the private key)" & vbCrLf & _
"-p <pfx_password>       : the password used for encrypting the .pfx file" & vbCrLf & _
"-i <site>               : specify site name; default is ""w3svc/1""" & vbCrLf & _
"-port <secure_bindings> : specify secure bindings; default is "":443:""" & vbCrLf & _
"-s <server>             : specify server to install the .pfx on or backup from;" & vbCrLf & _
"                          default is local machine" & vbCrLf & _
"-u <user_name>          : user name used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-pwd <user_password>    : user password used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-q <ON|OFF>             : quiet mode, allows silent overwrites when file exists" & vbCrLf & _
"                          or when site has certificate installed; default is OFF" & vbCrLf & _
"" & vbCrLf & _
"Extended Help:" & vbCrLf & _
"--------------" & vbCrLf & _
"-h 1            : Installing a certificate (.cer)" & vbCrLf & _
"-h 2            : Backing up a certificate (to .pfx)" & vbCrLf & _
"-h 3            : Restoring a certificate (from .pfx) and Deploying in a cluster" & vbCrLf


L_DESC_HELP_1          = _
"-------------------------------" & vbCrLf & _
"INSTALLING A CERTIFICATE (.CER)" & vbCrLf & _
"-------------------------------" & vbCrLf & _
"Install a certificate (.cer file). This must be done on the server that" & vbCrLf & _
"originally generated the certificate request so that the private key on the" & vbCrLf & _
"server matches the certificate." & vbCrLf & _
"" & vbCrLf & _
"Usage:  IISCertDeploy.vbs -new <cer_file> -e <pfx_file> -p <pfx_password>" & vbCrLf & _
"                         [-i <site>] [-port <secure_bindings>] [-u <user_name>]" & vbCrLf & _
"                         [-pwd <user_password>] [-q <ON|OFF>]" & vbCrLf & _
"" & vbCrLf & _
"-new <cer_file>         : name of the .cer file that you received from your CA." & vbCrLf & _
"-c <pfx_file>           : name of the .pfx file that will be generated (this" & vbCrLf & _
"                          file contains certificate along with the private key)" & vbCrLf & _
"-p <pfx_password>       : the password used for encrypting the .pfx file" & vbCrLf & _
"-i <site>               : specify site name; default is ""w3svc/1""" & vbCrLf & _
"-port <secure_bindings> : specify secure bindings; default is "":443:""" & vbCrLf & _
"-u <user_name>          : user name used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-pwd <user_password>    : user password used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-q <ON|OFF>             : quiet mode, allows silent overwrites when file exists" & vbCrLf & _
"                          or when site has certificate installed; default is OFF" & vbCrLf & _
"" & vbCrLf & _
"  Example:" & vbCrLf & _
"     IISCertDeploy.vbs -new certnew.cer -c certnew.pfx -p pfxpassword" & vbCrLf


L_DESC_HELP_2          = _
"-------------------------------------" & vbCrLf & _
"BACKING UP YOUR CERTIFICATE (to .PFX)" & vbCrLf & _
"-------------------------------------" & vbCrLf & _
"Back-up a certificate and its matching private key to a .pfx file. If the .pfx" & vbCrLf & _
"file is stored separate from the original machine, it can be used later to" & vbCrLf & _
"restore the certificate and matching private key in the event of a failure or" & vbCrLf & _
"loss of data." & vbCrLf & _
"Usage:  IISCertDeploy.vbs -e <pfx_file> -p <pfx_password> [-i <site>]" & vbCrLf & _
"                          [-s <server>] [-u <user_name>] [-pwd <user_password>]" & vbCrLf & _
"                          [-q <ON|OFF>]" & vbCrLf & _
"" & vbCrLf & _
"-e <pfx_file>           : name of the .pfx file that will be generated (this" & vbCrLf & _
"                          file contains certificate along with the private key)" & vbCrLf & _
"-p <pfx_password>       : the password used for encrypting the .pfx file" & vbCrLf & _
"-i <site>               : specify site name; default is ""w3svc/1""" & vbCrLf & _
"-s <server>             : specify server to backup the .pfx from;" & vbCrLf & _
"                          default is local machine" & vbCrLf & _
"-u <user_name>          : user name used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-pwd <user_password>    : user password used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-q <ON|OFF>             : quiet mode, allows silent overwrites when file exists" & vbCrLf & _
"                          or when site has certificate installed; default is OFF" & vbCrLf & _
"" & vbCrLf & _
"  Example:" & vbCrLf & _
"     IISCertDeploy.vbs -e exported.pfx -p pfxpassword" & vbCrLf


L_DESC_HELP_3          = _
"--------------------------------------------------------------------" & vbCrLf & _
"RESTORING YOUR CERTIFICATE (from .PFX) / DEPLOYING YOUR CERTIFICATE IN A CLUSTER" & vbCrLf & _
"--------------------------------------------------------------------------------" & vbCrLf & _
"After a certificate and its matching private key have been backed up to a .pfx" & vbCrLf & _
"file, the .pfx file can be installed on other machines in a cluster." & vbCrLf & _
"The cluster name should match the common name (CN) in the certificate." & vbCrLf & _
"" & vbCrLf & _
"WARNING: Please confirm with your Certificate Authority that you are allowed" & vbCrLf & _
"to install your certificate in a cluster environment. Some Certificate" & vbCrLf & _
"Authorities restricts cluster deployments of certificates in their licensing" & vbCrLf & _
"agreement." & vbCrLf & _
"Usage:  IISCertDeploy.vbs -c <pfx_file> [-p <pfx_password>] [-i <site>]" & vbCrLf & _
"                       [-port <secure_bindings>] [-s <server>] [-u <user_name>]" & vbCrLf & _
"                       [-pwd <user_password>] [-q <ON|OFF>]" & vbCrLf & _
"" & vbCrLf & _
"-c <pfx_file>           : name of .pfx file to import" & vbCrLf & _
"-p <pfx_password>       : the password used for encrypting the .pfx file" & vbCrLf & _
"-i <site>               : specify site name; default is ""w3svc/1""" & vbCrLf & _
"-port <secure_bindings> : specify secure bindings; default is "":443:""" & vbCrLf & _
"-s <server>             : specify server to install the .pfx on;" & vbCrLf & _
"                          default is local machine" & vbCrLf & _
"-u <user_name>          : user name used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-pwd <user_password>    : user password used for authenticating to the server;" & vbCrLf & _
"                          default is the current user's credentials (requires" & vbCrLf & _
"                          credentials with Administrator Group access)" & vbCrLf & _
"-q <ON|OFF>             : quiet mode, allows silent overwrites when file exists" & vbCrLf & _
"                          or when site has certificate installed; default is OFF" & vbCrLf & _
"" & vbCrLf & _
"  Example:" & vbCrLf & _
"     IISCertDeploy.vbs -c cert.pfx -p pfxpassword -i w3svc/1 -s iisserver1" & vbCrLf & _
"                       -u Administrator -pwd aal92790" & vbCrLf


L_ERR_IMPORT_ERROR     = "Error importing certificate: "
L_ERR_IMPORT_SUCCESS   = "Import succeeded."

L_ERR_EXPORT_ERROR     = "Error exporting certificate: "
L_ERR_EXPORT_SUCCESS   = "Export succeeded."

L_DESC_FILE_EXISTS     = "File exists, replace?"
L_DESC_IS_INSTALLED    = "Certificate already installed, replace with new one?"

L_ERR_EXPORT_NO_PWD    = "You should specify password for pfx"
L_ERR_IMPORT_NO_FILE   = "You should specify file for backup"

L_DESC_POPUP_WRN       = "This script will throw popup messages if it works with WScript."
L_DESC_POPUP_QUESTION  = "Would you like to register CScript as your default host for VBscript?"
L_DESC_POPUP_TITLE     = "Register CScript"
L_DESC_POPUP_ADVICE    = "To avoid popup messages next time run this script type: ""CScript.exe IISCertDeploy.vbs <params>"""

L_ERR_POPUP_REGISTRY   = "Error Trying to write the registry settings!"

REM
REM END LOCALIZATION
REM

REM
REM --- Globals ---
REM

dim g_dictParms
set g_dictParms = CreateObject("Scripting.Dictionary")

REM
REM --- Set argument defaults ---
REM

g_dictParms(L_SWITCH_HELP)         = ""
g_dictParms(L_SWITCH_CER)          = ""
g_dictParms(L_SWITCH_PFX)          = ""
g_dictParms(L_SWITCH_PFX_EXPORT)   = ""
g_dictParms(L_SWITCH_PFX_PASSWORD) = ""
g_dictParms(L_SWITCH_INSTANCE_ID)  = "w3svc/1"
g_dictParms(L_SWITCH_PORT)         = ":443:"
g_dictParms(L_SWITCH_SERVER)       = ""
g_dictParms(L_SWITCH_USER)         = ""
g_dictParms(L_SWITCH_PASSWORD)     = ""
g_dictParms(L_SWITCH_QUERY)        = "ON"

REM
REM --- Begin Main Program ---
REM

DetectExeType

if not ParseCommandLine(g_dictParms, WScript.Arguments) then
    usage
    WScript.Quit 0
end if

help = g_dictParms(L_SWITCH_HELP)
if (help <> "") then
    dim strHelpMsg
    strHelpMsg = L_DESC_COPYRIGHT & vbCrLf

    select case help
        case "1" strHelpMsg = strHelpMsg & L_DESC_HELP_1
        case "2" strHelpMsg = strHelpMsg & L_DESC_HELP_2
        case "3" strHelpMsg = strHelpMsg & L_DESC_HELP_3
        case else strHelpMsg = strHelpMsg & L_DESC_PROGRAM
    end select

    WScript.echo strHelpMsg
    WScript.Quit 0
end if

cerfile = g_dictParms(L_SWITCH_CER)
pfxfile = g_dictParms(L_SWITCH_PFX)
pfxfile2Export = g_dictParms(L_SWITCH_PFX_EXPORT)
pfxfilepassword = g_dictParms(L_SWITCH_PFX_PASSWORD)
instance = g_dictParms(L_SWITCH_INSTANCE_ID)
port = g_dictParms(L_SWITCH_PORT)
server = g_dictParms(L_SWITCH_SERVER)
user = g_dictParms(L_SWITCH_USER)
userpassword = g_dictParms(L_SWITCH_PASSWORD)
DoQueryFlag = UCase(g_dictParms(L_SWITCH_QUERY))

REM
REM Check arguments
REM
if (pfxfile = "" AND cerfile = "" AND pfxfile2Export = "") then
    usage
    WScript.Quit 0
end if

on error resume next

dim iiscertobj

REM
REM Export certificate
REM

if (pfxfile2Export <> "") then
    if (pfxfile <> "" OR cerfile <> "") then
        usage
        WScript.Quit 0
    end if

    if (pfxfilepassword = "") then
        WScript.echo L_ERR_EXPORT_NO_PWD
        WScript.Quit 0
    end if

    set fso = CreateObject("Scripting.FileSystemObject")
    if (fso.FileExists(pfxfile2Export)) then
        if NotOverwrite(L_DESC_FILE_EXISTS) then
            WScript.Quit 0
        end if
    end if

    set iiscertobj = CreateObject("IIS.CertObj")
    if (user <> "") then
        iiscertobj.UserName = user
        if (userpassword <> "") then
            iiscertobj.UserPassword = userpassword
        end if
    end if
    if (server <> "") then
        iiscertobj.ServerName = server
    end if
    iiscertobj.InstanceName = instance
    iiscertobj.Export pfxfile2Export, pfxfilepassword, true, true, false

    if (err.number <> 0) then
        strMsg = L_ERR_EXPORT_ERROR & vbCrLf
        strMsg = strMsg & Err.Description & " (Error 0x" & Hex(Err.Number) & ")"
    else
        strMsg = L_ERR_EXPORT_SUCCESS
    end if
    WScript.echo strMsg

    WScript.Quit 0
end if


REM
REM Import certificate
REM

if (cerfile <> "") then
    if (pfxfile = "" OR pfxfilepassword = "") then
        WScript.echo L_ERR_IMPORT_NO_FILE
        WScript.Quit 0
    end if

    InstallResponseFile
end if

if (err.number = 0) then
    set iiscertobj = CreateObject("IIS.CertObj")
    if (user <> "") then
        iiscertobj.UserName = user
        if (userpassword <> "") then
            iiscertobj.UserPassword = userpassword
        end if
    end if
    if (server <> "") then
        iiscertobj.ServerName = server
    end if
    iiscertobj.InstanceName = instance
    if (iiscertobj.IsInstalled) then
        if NotOverwrite(L_DESC_IS_INSTALLED) then
            WScript.Quit 0
        end if
    end if
    iiscertobj.Import pfxfile, pfxfilepassword, true, true
end if

if (err.number = 0) then
    strPath = server
    if strPath = "" then
        strPath = "localhost"
    end if
    strPath = strPath & "/" & instance
    set objSite = GetObject("IIS://" & strPath)
    if not (IsObject(objSite)) then
        err.clear
        set root = GetObject("IIS:")
        set objSite = root.OpenDSObject("IIS://" & strPath, user, userpassword, 1)
    end if
    if IsObject(objSite) then
        objSite.SecureBindings  = port
        objSite.SetInfo
    end if
end if

REM
REM Show Result
REM
dim strMsg
if (err.number <> 0) then
    strMsg = L_ERR_IMPORT_ERROR & vbCrLf
    strMsg = strMsg & Err.Description & " (Error 0x" & Hex(Err.Number) & ")"
else
    strMsg = L_ERR_IMPORT_SUCCESS
end if
WScript.echo strMsg

WScript.Quit 0

REM
REM
REM --- End Main Program ---
REM
REM


REM
REM ParseCommandLine(dictParameters, cmdline)
REM     Parses the command line parameters into the given dictionary
REM
REM Arguments:
REM     dictParameters  - A dictionary containing the global parameters
REM     cmdline - Collection of command line arguments
REM
REM Returns - Success code
REM

Function ParseCommandLine(dictParameters, cmdline)
    dim     fRet
    dim     cArgs
    dim     i
    dim     strSwitch
    dim     strArgument

    fRet    = TRUE
    cArgs   = cmdline.Count
    i       = 0
    
    do while (i < cArgs)

        REM
        REM Parse the switch and its argument
        REM

        if i + 1 >= cArgs then
            REM
            REM Not enough command line arguments - Fail
            REM

            fRet = FALSE
            exit do
        end if

        strSwitch = cmdline(i)
        i = i + 1

        strArgument = cmdline(i)
        i = i + 1

        REM
        REM Add the switch,argument pair to the dictionary
        REM

        if NOT dictParameters.Exists(strSwitch) then
            REM
            REM Bad switch - Fail
            REM

            fRet = FALSE
            exit do
        end if 

        dictParameters(strSwitch) = strArgument

    loop

    ParseCommandLine = fRet
end function

REM
REM Usage ()
REM     prints out the description of the command line arguments
REM

Sub Usage
    dim strMsg

    strMsg = L_DESC_COPYRIGHT & vbCrLf
    strMsg = strMsg & L_DESC_PROGRAM & vbCrLf

    WScript.echo strMsg
end sub


Sub InstallResponseFile
    const CERT_SYSTEM_STORE_LOCAL_MACHINE = &H20000
    const CRYPT_EXPORTABLE = 1
    const AT_KEYEXCHANGE = 1
    const PROV_RSA_SCHANNEL = 12

    on error resume next

    if (pfxfile = "") then
        WScript.echo L_ERR_IMPORT_NO_FILE
        WScript.Quit 0
    end if

    set fso = CreateObject("Scripting.FileSystemObject")
    if (fso.FileExists(pfxfile)) then
        if NotOverwrite(L_DESC_FILE_EXISTS) then
            WScript.Quit 0
        end if
        fso.DeleteFile(pfxfile)
    end if

    err.clear

    dim objEnroll
    set objEnroll = CreateObject("CEnroll.CEnroll")
    if (err.number <> 0) then
        exit sub
    end if

    objEnroll.MyStoreFlags = CERT_SYSTEM_STORE_LOCAL_MACHINE
    objEnroll.GenKeyFlags = CRYPT_EXPORTABLE
    objEnroll.KeySpec = AT_KEYEXCHANGE
    objEnroll.ProviderType = PROV_RSA_SCHANNEL
    objEnroll.DeleteRequestCert = true

    if (err.number <> 0) then
        exit sub
    end if

    objEnroll.acceptFilePKCS7 cerfile
    if (err.number <> 0) then
        exit sub
    end if

    objEnroll.createFilePFX pfxfilepassword, pfxfile
end sub


Function NotOverwrite(strMsg)
    dim Input

    NotOverwrite = false

    if (DoQueryFlag = "OFF") then
        exit function
    end if

    on error resume next

    NotOverwrite = true

    err.clear
    WScript.StdOut.Write strMsg & " (y/n)"
    Input = WScript.StdIn.Read(1)
    if (err.number = 0) then
        if (Input <> "y" AND Input <> "Y") then
            exit function
        end if
    else
        err.clear
        set ShellObject = WScript.CreateObject("WScript.Shell")
        bResult = ShellObject.PopUp(strMsg, 0, "", 32 + 4)
        if (err.number <> 0 OR bResult <> 6) then
            exit function
        end if
    end if

    NotOverwrite = false
end function



REM
REM DetectExeType
REM
REM This can detect the type of exe the
REM script is running under and warns the
REM user of the popups.
REM

Sub DetectExeType()
    Dim ScriptHost
    Dim ShellObject

    Dim CurrentPathExt
    Dim EnvObject

    Dim RegCScript
    Dim RegPopupType
    RegPopupType = 32 + 4

    On Error Resume Next

    ScriptHost = WScript.FullName
    ScriptHost = Right(ScriptHost, Len(ScriptHost) - InStrRev(ScriptHost, "\"))

    if (UCase(ScriptHost) <> "WSCRIPT.EXE") then
        exit sub
    end if

    WScript.Echo L_DESC_POPUP_WRN

    ' Create a pop-up box and ask if they want to register cscript as the default host.
    Set ShellObject = WScript.CreateObject("WScript.Shell")
    ' -1 is the time to wait.  0 means wait forever.
    RegCScript = ShellObject.PopUp(L_DESC_POPUP_QUESTION, 0, L_DESC_POPUP_TITLE, RegPopupType)

    if (err.number <> 0 or RegCScript <> 6) then
        WScript.Echo L_DESC_POPUP_ADVICE
        exit sub
    end if

    ShellObject.RegWrite "HKEY_CLASSES_ROOT\VBSFile\Shell\Open\Command\", "%WINDIR%\System32\CScript.exe //nologo ""%1"" %*", "REG_EXPAND_SZ"
    ShellObject.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VBSFile\Shell\Open\Command\", "%WINDIR%\System32\CScript.exe //nologo ""%1"" %*", "REG_EXPAND_SZ"
    ' Check if PathExt already existed
    CurrentPathExt = ShellObject.RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATHEXT")
    If Err.Number = &H80070002 Then
        Err.Clear
        Set EnvObject = ShellObject.Environment("PROCESS")
        CurrentPathExt = EnvObject.Item("PATHEXT")
    End If

    ShellObject.RegWrite "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATHEXT", CurrentPathExt & ";.VBS", "REG_SZ"

    if (err.number <> 0) then
        WScript.Echo L_ERR_POPUP_REGISTRY
        WScript.Quit err.number
    End If

End Sub
