Skip to content

Instantly share code, notes, and snippets.

@vmatekole
Last active December 7, 2022 10:09
Show Gist options
  • Save vmatekole/0a9c1829c8bce2dc00ec0be6e60b8bdf to your computer and use it in GitHub Desktop.
Save vmatekole/0a9c1829c8bce2dc00ec0be6e60b8bdf to your computer and use it in GitHub Desktop.
Secure your Docker socket with TLS/SSL
#!/bin/bash
# Generate self-cert certificates for Docker socket. I have tried many tutorials including http://tech.paulcz.net/2016/01/secure-docker-with-tls/
# None worked... So I took the official steps from Docker docs - https://docs.docker.com/engine/security/https/ and placed them
# in a script. Please ensure that you replace the IP addresses/DNS names denoted in X with IP's and hostnames you wish to allow
# to connect with your daemon, normally 127.0.0.1 is always required and the hostname of your server. If you have a coreos cluster
# placing IP's and hostnames of each node maybe preferable over creating unique certs for each node.
# This script does not cover the steps for copying your certs to the relevant locations, as per the following document - https://docs.docker.com/engine/security/https/
# 1. In our production setup we copy server.key, server-cert.pem and ca-cert.pem to /etc/docker/ssl
# 2. Client certs(ca.pem,cert.pem,key.pem) are copied to user dir in our case user core - /home/core/.docker/certs
# 3. Docker Daemon options should have the following to setup server certs e.g. DOCKER_OPTS=-H 127.0.0.1:2376 -H unix:///var/run/docker.sock --tlsverify --tlscacert=/etc/docker/ssl/ca-cert.pem --tlscert=/etc/docker/ssl/server-cert.pem --tlskey=/etc/docker/ssl/server-key.pem
# 4. All users wanting to access Docker daemon should have following environment variables set in their profile to enable their client to access server with TLS enabled e.g.:
# export DOCKER_HOST=tcp://127.0.0.1:2376
# export DOCKER_TLS_VERIFY=1
# export DOCKER_CERT_PATH=/home/core/.docker/certs
openssl genrsa -out ca-key.pem 4096
openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem
openssl genrsa -out server-key.pem 4096
openssl req -subj "/CN=127.0.0.1" -sha256 -new -key server-key.pem -out server.csr
echo subjectAltName = IP:X.X.X.X,IP:127.0.0.1,DNS:X,DNS:X > extfile.cnf
openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
-CAcreateserial -out server-cert.pem -extfile extfile.cnf
openssl genrsa -out key.pem 4096
openssl req -subj '/CN=client' -new -key key.pem -out client.csr
echo extendedKeyUsage = clientAuth > extfile.cnf
openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
-CAcreateserial -out cert.pem -extfile extfile.cnf
rm -v client.csr server.csr
chmod -v 0400 ca-key.pem key.pem server-key.pem
chmod -v 0444 ca.pem server-cert.pem cert.pem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment