krkr
12/3/2016 - 12:35 AM

Generate Docker certificates

Generate Docker certificates

#!/bin/sh

CA_CERT=ca.pem
CA_KEY=ca-key.pem
CLIENT_CERT=cert.pem
CLIENT_KEY=key.pem
SERVER_CERT=server.pem
SERVER_KEY=server-key.pem

STATE=FR
ORG=Q
PASSPHRASE=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 42 | head -1)

main() {
  read -p "> hostname? " HOSTNAME
  read -p "> ip? " IP

  # clean
  rm -f *.pem

  # ca certificate generation
  openssl genrsa -aes256 -passout pass:$PASSPHRASE -out $CA_KEY 2048
  openssl req -new -x509 -days 365 -key $CA_KEY -sha256 -passin pass:$PASSPHRASE -subj "/C=FR/ST=$STATE/O=$ORG" -out $CA_CERT

  # server certificate generation
  openssl genrsa -out $SERVER_KEY 2048
  openssl req -subj "/CN=${HOSTNAME}" -new -key $SERVER_KEY -out server.csr 2>/dev/null
  echo subjectAltName = IP:${IP} > extfile.cnf
  openssl x509 -passin pass:$PASSPHRASE -req -days 365 -in server.csr -CA $CA_CERT -CAkey $CA_KEY -CAcreateserial -out $SERVER_CERT -extfile extfile.cnf

  # client certificate generation
  openssl genrsa -out $CLIENT_KEY 2048
  openssl req -subj '/CN=client' -new -key $CLIENT_KEY -out client.csr 2>/dev/null
  echo extendedKeyUsage = clientAuth > extfile.cnf
  openssl x509 -passin pass:$PASSPHRASE -req -days 365 -in client.csr -CA $CA_CERT -CAkey $CA_KEY -CAcreateserial -out $CLIENT_CERT -extfile extfile.cnf

  # clean
  rm -f client.csr server.csr extfile.cnf ca.srl
  chmod 0400 $CA_KEY $CLIENT_KEY $SERVER_KEY
  chmod 0444 $CA_CERT $SERVER_CERT $CLIENT_CERT

  echo "> server side: $CA_CERT $SERVER_CERT $SERVER_KEY"
  echo "> client side: $CA_CERT $CLIENT_CERT $CLIENT_KEY"
}

main