Created
September 27, 2017 17:41
-
-
Save paxswill/afdb2fddd86fd646e209580addfbb3ba to your computer and use it in GitHub Desktop.
Simple script to copy certificates from pfSense's certificate manager (which in my case were being updated with Let's Encrypt) to a Java keystore (in my case the one being used by Ubiquiti's Unifi Controller).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
set -eu | |
XMLLINT=/usr/local/bin/xmllint | |
BASE64_DECODE='/usr/local/bin/python2 -m base64 -d' | |
OPENSSL="/usr/bin/openssl" | |
KEYTOOL="/usr/local/bin/keytool" | |
PFSENSE_CONF=/cf/conf/config.xml | |
TEMP_KEY="`/bin/cat /dev/random | /usr/bin/tr -dc 'a-zA-Z0-9' | /usr/bin/fold -w 32 | /usr/bin/head -n1`" | |
extract_private_key() { | |
local RAW XPATH | |
XPATH="/pfsense/cert[descr[normalize-space(.) = '$1']]/prv/text()" | |
RAW="`"$XMLLINT" --xpath "$XPATH" "$PFSENSE_CONF"`" | |
printf "%s\n" "`echo "$RAW" | $BASE64_DECODE`" | |
} | |
extract_certificate() { | |
local RAW XPATH | |
XPATH="/pfsense/cert[descr[normalize-space(.) = '$1']]/crt/text()" | |
RAW="`"$XMLLINT" --xpath "$XPATH" "$PFSENSE_CONF"`" | |
printf "%s\n" "`echo "$RAW" | $BASE64_DECODE`" | |
} | |
combine_pem() { | |
local PRIVATE_KEY CERTIFICATE | |
PRIVATE_KEY="`extract_private_key "$1"`" | |
CERTIFICATE="`extract_certificate "$1"`" | |
printf '%s\n%s\n' "$PRIVATE_KEY" "$CERTIFICATE" | |
} | |
extract_pkcs12() { | |
combine_pem "$1" | "$OPENSSL" pkcs12 -export \ | |
-name "$2" \ | |
-password pass:"$TEMP_KEY" | |
} | |
main() { | |
local KEYSTORE KEYSTORE_PASSWORD P12_STORE PFSENSE_CERT_NAME ALIAS | |
if [ "$#" -ne 4 ]; then | |
printf "Not enough arguments.\nUsage:\n\t%s\n" \ | |
"$0 certificate_name /path/to/keystore keystore_password alias" | |
exit 1 | |
fi | |
PFSENSE_CERT_NAME="$1" | |
KEYSTORE="$2" | |
KEYSTORE_PASSWORD="$3" | |
ALIAS="$4" | |
echo "Creating temp file" | |
P12_STORE=`mktemp` || exit 2 | |
echo "Extracting cert+key form pfSense" | |
extract_pkcs12 "$PFSENSE_CERT_NAME" "$ALIAS" > "$P12_STORE" | |
echo "Importing to keystore" | |
sudo "$KEYTOOL" -importkeystore \ | |
-deststorepass "$KEYSTORE_PASSWORD" \ | |
-destkeypass "$KEYSTORE_PASSWORD" \ | |
-destkeystore "$KEYSTORE" \ | |
-srckeystore "$P12_STORE" \ | |
-srcstoretype PKCS12 \ | |
-srcstorepass "$TEMP_KEY" \ | |
-alias "$ALIAS" \ | |
-noprompt | |
echo "Cleaning up" | |
rm "$P12_STORE" | |
} | |
main $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks very much. This help me a lot.