Skip to content

Instantly share code, notes, and snippets.

@cbluth
Forked from jdiamond/Dockerfile
Created September 16, 2019 11:02
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 cbluth/9107345b7c03de4170b72cabde3c0532 to your computer and use it in GitHub Desktop.
Save cbluth/9107345b7c03de4170b72cabde3c0532 to your computer and use it in GitHub Desktop.
SSH certificates
FROM alpine
# Install OpenSSH:
RUN apk -U add openssh
# Generate host keys:
RUN ssh-keygen -A
# Create users:
RUN adduser -D user1
RUN adduser -D user2
# Set passwords:
RUN echo "root:root" | chpasswd
RUN echo "user1:user1" | chpasswd user1
RUN echo "user2:user2" | chpasswd user2
# Allow root to log in via SSH:
RUN sed -i s/#PermitRootLogin.*/PermitRootLogin\ yes/ /etc/ssh/sshd_config
# Enable CA-signed keys:
RUN echo "TrustedUserCAKeys /etc/ssh/ca.pub" > /etc/ssh/sshd_config
WORKDIR /ssh
# Generate a CA key:
RUN ssh-keygen -f /etc/ssh/ca -C ca -N ""
# Generate a user1 key:
RUN ssh-keygen -f user1 -C user1 -N ""
# Sign user1's key so it can log in as both root and user1:
RUN ssh-keygen -s /etc/ssh/ca -V +52w -n root,user1 -I user1-key1 -z 1 user1.pub
# Same for user2:
RUN ssh-keygen -f user2 -C user2 -N ""
# Sign user2's so it can only log in as itself:
RUN ssh-keygen -s /etc/ssh/ca -V +52w -n user2 -I user2-key1 -z 2 user2.pub

The attached Dockerfile builds an image containing OpenSSH for experimenting with SSH certificates. It creates and signs all the keys so that you don't have to set anything up on your host OS.

Build the Docker image:

docker build -t ssh-certs .

Start a container with that image running sshd:

docker run --name sshd -d --rm -p 2233:22 ssh-certs /usr/sbin/sshd -D -e

Copy the user keys and certs to your local file system to use them:

docker cp sshd:/ssh/user1 .
docker cp sshd:/ssh/user1-cert.pub .
docker cp sshd:/ssh/user2 .
docker cp sshd:/ssh/user2-cert.pub .

View logs generated by sshd:

docker logs -f sshd

Ctrl+C to stop.

In another shell, try logging in with various keys and usernames:

ssh -i user1 root@127.0.0.1 -p 2233 # no password required
ssh -i user1 user1@127.0.0.1 -p 2233 # no password required
ssh -i user1 user2@127.0.0.1 -p 2233 # requires password (user2 not in cert)

ssh -i user2 root@127.0.0.1 -p 2233 # requires password (root not in cert)
ssh -i user2 user1@127.0.0.1 -p 2233 # requires password (user1 not in cert)
ssh -i user2 user2@127.0.0.1 -p 2233 # no password required

Stop the container:

docker stop sshd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment