Skip to content

Dynamic Docker containers for CTF

Objective

Get a per connection docker container.

Configuration

Create the systemd socket that will be exposed

bash
$ sudo systemtl edit --full --force ssh-forwarder.socket
# /etc/systemd/system/ssh-forwarder.socket
[Unit]
Description=Forward SSH connections

[Socket]
ListenStream=2222
Accept=yes

[Install]
WantedBy=sockets.target

Create the service dynamic service that will forward the connection to a per connection docker container

bash
$ sudo systemctl edit --full --force ssh-forwarder@.service
# /etc/systemd/system/ssh-forwarder@.service
[Unit]
Description=Forward SSH connections to Docker

[Service]
Type=simple
ExecStart=/root/spawner.sh %I
StandardInput=socket

Content of the spawner.sh script

bash
#!/bin/bash
# set -x
container_name="ssh_container_$(date +%s)"

docker_run_output=$(docker run --rm -d --expose 22 --name $container_name -P sshd)
mapped_port=$(docker port $docker_run_output 22/tcp | cut -d ':' -f 2)

function stop_container {
    docker stop $docker_run_output >/dev/null 2>&1
}

trap stop_container EXIT

sleep 1

socket_fd="$1"

socat - TCP:localhost:$mapped_port