Skip to content

Instantly share code, notes, and snippets.

@sunscan
Forked from bradrydzewski/generate_docker_cert.sh
Last active October 6, 2017 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunscan/8f9d9c0a84735684dfb013f3fb92b946 to your computer and use it in GitHub Desktop.
Save sunscan/8f9d9c0a84735684dfb013f3fb92b946 to your computer and use it in GitHub Desktop.
Generate trusted CA certificates for running Docker with HTTPS
#!/bin/bash -x
#
# Generates client and server certificates used to enable HTTPS
# remote authentication to a Docker daemon.
#
# See http://docs.docker.com/articles/https/
#
# To start the Docker Daemon:
#
# sudo docker -d \
# --tlsverify \
# --tlscacert=ca-cert.pem \
# --tlscert=server-cert.pem \
# --tlskey=server-key.pem \
# -H=0.0.0.0:2376
#
# To connect to the Docker Daemon:
#
# sudo docker \
# --tlsverify \
# --tlscacert=ca-cert.pem \
# --tlscert=client-cert.pem \
# --tlskey=client-key.pem \
# -H=localhost:2376 version
#
# IMPORTANT: when connecting via IP instead of hostname you
# will need to substitute --tlsverify with --tls
DAYS=1825 # 5 years
# remove certificates from previous execution
rm -f *.cnf *.csr *.pem *.srl
# generate new random password
PASS=$(openssl rand -hex 16)
# get ip
for ip in $(ip -f inet -o addr show | cut -d\ -f 7 | cut -d/ -f 1 | sort)
do
IP_LIST="${IP_LIST}IP:${ip},"
done
IP_LIST=$(echo ${IP_LIST} | sed 's/,$//')
# generate CA private and public keys
openssl genrsa -aes256 -out ca-key.pem -passout pass:${PASS} 4096
openssl req -subj "/CN=*/" -new -x509 -days ${DAYS} -passin pass:${PASS} -key ca-key.pem -out ca-cert.pem
# create a server key and certificate signing request (CSR)
openssl genrsa -out server-key.pem
openssl req -new -sha256 -key server-key.pem -out server.csr -subj '/CN=*/'
# create an extensions config file and sign the server key with our CA
echo "subjectAltName = DNS:$(hostname),${IP_LIST}" > extfile.cnf
echo "extendedKeyUsage = serverAuth" >> extfile.cnf
openssl x509 -req -days ${DAYS} -sha256 -passin pass:${PASS} -in server.csr -CAcreateserial -CA ca-cert.pem -CAkey ca-key.pem -out server-cert.pem -extfile extfile.cnf
# create a client key and certificate signing request (CSR)
openssl genrsa -out client-key.pem 4096
openssl req -subj '/CN=client' -new -key client-key.pem -out client.csr
# create an extensions config file and sign
echo "extendedKeyUsage = clientAuth" > extfile.cnf
openssl x509 -req -days ${DAYS} -sha256 -passin pass:${PASS} -in client.csr -CAcreateserial -CA ca-cert.pem -CAkey ca-key.pem -out client-cert.pem -extfile extfile.cnf
# remove generated files that are no longer required
rm -f *.cnf *.csr *.srl
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment