Skip to content

Instantly share code, notes, and snippets.

@leanderjanssen
Created April 8, 2017 15:25
Show Gist options
  • Save leanderjanssen/28e89ef2daca39693605823eea6505f1 to your computer and use it in GitHub Desktop.
Save leanderjanssen/28e89ef2daca39693605823eea6505f1 to your computer and use it in GitHub Desktop.
Create Docker certificates
#!/bin/bash
# Retrieve public and private ip of instance
PUBLIC_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)
PRIVATE_IP=$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)
mkdir ~/docker-ca
chmod 0700 ~/docker-ca
cd ~/docker-ca || exit 1
# Generate CA private key and self-signed CA certificate
openssl genrsa -out ca-key.pem 2048
openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem \
-subj '/CN=Certificate Authority/O=Docker Training/L=London/C=UK'
# Generate Server private key and certificate signing request
openssl genrsa -out server-key.pem 2048
openssl req -subj "/CN=${PUBLIC_IP}" -new -key server-key.pem -out server.csr
# Add SANs to be included in Server certificate
cat << EOF > ~/docker-ca/extfile-server.cnf
subjectAltName = IP:${PUBLIC_IP},IP:${PRIVATE_IP},IP:127.0.0.1
EOF
# Sign Server signing request into certificate
openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem \
-CAcreateserial -out server-cert.pem -extfile extfile-server.cnf
# Generate Client private key and certificate signing request
openssl genrsa -out client-key.pem 2048
openssl req -subj '/CN=client' -new -key client-key.pem -out client.csr
# Add key usage extension to Client certificate for Client Authentication
cat << EOF > ~/docker-ca/extfile-client.cnf
extendedKeyUsage = clientAuth
EOF
# Sign Client signing request into certificate
openssl x509 -req -days 365 -in client.csr -CA ca.pem -CAkey ca-key.pem \
-CAcreateserial -out client-cert.pem -extfile extfile-client.cnf
# Secure the private keys and certificates
chmod -v 0400 ca-key.pem client-key.pem server-key.pem
chmod -v 0444 ca.pem client-cert.pem server-cert.pem
sudo mkdir -p /etc/docker
sudo USERNAME="$USER" sh -c 'chown "$USERNAME":docker /etc/docker'
sudo chmod 750 /etc/docker
cp ~/docker-ca/{ca,server-key,server-cert}.pem /etc/docker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment