Blob Blame Raw
#!/bin/bash

set -e

ACMEUSER="bw"
WWWGROUP="www-data"

CERTS_DIR="$1"
SUBJ="$2"
EXT="$3"
TMP_DIR="/tmp"

if [ -z "$CERTS_DIR" ] || [ -z "$SUBJ" ]; then
  echo "Usage:"
  echo "$0 \\"
  echo "    /mysite/certs/dir/ \\"
  echo "    /CN=mysite.com \\"
  echo "    subjectAltName=DNS:mysite.com,DNS:www.mysite.com"
  exit 0
fi


BASE_DIR=$(cd `dirname "$0"`; pwd)
NAME=`date +%Y-%m-%d--%H-%M-%S--%N`
PREFIX="$CERTS_DIR/$NAME"
TMP_PREFIX="$TMP_DIR/$NAME"

if openssl x509 -checkend 864000 -noout -in "$CERTS_DIR/public.crt"; then
  echo " -------------------------------------------- "
  echo " certifiate is actual now ($NAME) "
  echo " -------------------------------------------- "
  exit 0
fi

echo " -------------------------------------------- "
echo " begin $PREFIX "
echo " -------------------------------------------- "

mkdir -p "$CERTS_DIR"
openssl req -newkey rsa:4096 -sha512 -nodes \
  -keyout "$PREFIX.key" \
  -out "$PREFIX.csr" \
  -subj "$SUBJ" \
  -reqexts san \
  -config <(echo '[req]'; echo 'distinguished_name=req'; echo '[san]'; echo $EXT)
sudo -u "$ACMEUSER" "$BASE_DIR/sign-cert.py" "$PREFIX.csr" "$PREFIX.crt"

echo "compare modulus"
MODULUS_CRT=`openssl x509 -noout -modulus -in "$PREFIX.crt"`
MODULUS_KEY=`openssl rsa -noout -modulus -in "$PREFIX.key"`
if [ "$MODULUS_CRT" != "$MODULUS_KEY" ]; then
  echo "ERROR: modulus of certificate do not matches modulus of key"
  exit 1
fi
echo "ok"

echo "verify certificate"
openssl verify -CAfile "$PREFIX.crt" "$TMP_PREFIX.crt"
cp "$TMP_PREFIX.crt" "$PREFIX.crt"
rm "$TMP_PREFIX.crt"


#chown root:root "$PREFIX.crt"
#chmod 644 "$PREFIX.crt"


echo "update symlinks"
chown :$WWWGROUP "$PREFIX.key"
chmod g+r "$PREFIX.key"
cd "$CERTS_DIR"
ln -fs "$NAME.key" "private.key"
ln -fs "$NAME.crt" "public.crt"

service nginx configtest
service nginx reload

echo " -------------------------------------------- "
echo " done $PREFIX "
echo " -------------------------------------------- "