Openssl csr

From 0xWIKI
Jump to: navigation, search

This script will create a CSR with options for SANs in OpenSSL

#!/bin/bash
opensslconf="/tmp/openssl.cnf"
opensslconftail="$opensslconf".tail
countsan=2
countip=1

function gethelp {
        echo -e "Help for `basename ${0}`"
        echo -e ""
        echo -e "Usage: `basename ${0}` [OPTIONS]"
        echo -e ""
        echo -e "Example: `basename ${0}` -s wiki.mx.com -a hq-misc-wiki1.corp.ad.internal.mx -a hq-misc-wiki1 -a po-misc-wiki1 -i 10.16.19.43 -i 10.16.16.100"
        echo -e ""
        echo -e ""
        echo -e "Options:"
        echo -e "-s\t\tPrimary certificate subject; this is REQUIRED"
        echo -e ""
        echo -e "-a\t\tAdditional SAN(s) to add to the CSR"
        echo -e ""
        echo -e "-i\t\tIPs to add as additional SANs"
        echo -e ""
        echo -e "-h, --help\tdisplays this page"
        exit 1
}

while getopts "s:a:i::h --help" flag
        do
        case $flag in
                "s")subject="$OPTARG";;
                "a")echo "DNS.$countsan = $OPTARG" >> "$opensslconftail" && countsan=$((countsan+1));;
                "i")echo "IP.$countip = $OPTARG" >> "$opensslconftail" && countip=$((countip+1));;
                "h")gethelp;;
                "--help")gethelp;;
        esac
done

if [[ -z $subject ]];
	then
		echo -e "A SUBJECT IS REQUIRED\n\nSome help is below" && gethelp
		exit 1
fi

function writeconfig {
cat > $opensslconf <<EOL
[policy_match ]
countryName = match
stateOrProvinceName = match
localityName = match
organizationName = match
organizationalUnitName = match
commonName = supplied
emailAddress = optional

[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req

[req_distinguished_name]
countryName = Country Name (2 letter code)
countryName_default = US
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = UT
localityName = Locality Name (eg, city)
localityName_default = Lehi
organizationName = Organization
organizationName_default = MX Technologies Inc
organizationalUnitName	= Organizational Unit Name (eg, section)
organizationalUnitName_default	= MX
commonName = Primary domain name
commonName_default = $subject
commonName_max	= 64

[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = $subject
EOL
}

function writecsr {
cat $opensslconftail >> $opensslconf
openssl genrsa -out $subject.key 2048
openssl req -out $subject.csr -key $subject.key -new -sha256  -config "$opensslconf"
}

writeconfig
writecsr
Personal tools