Skip to content

Instantly share code, notes, and snippets.

@AfroThundr3007730
Created June 23, 2019 17:48
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save AfroThundr3007730/9bfdc305a8fceb805fb340dd1ca5b8c0 to your computer and use it in GitHub Desktop.
Save AfroThundr3007730/9bfdc305a8fceb805fb340dd1ca5b8c0 to your computer and use it in GitHub Desktop.
Create an on-demand SSH-based SOCKS5 proxy via systemd socket activation
#!/bin/bash
# These steps will allow the setup of an on-demand SSH proxy
# Three unit files will be created to serve this purpose:
# ssh-socks-helper.socket - The listening socket providing activation
# ssh-socks-helper.service - A systemd proxy to pass the socket fd
# ssh-socks.service - The actual SSH service providing the tunnel
cat <<'EOF' > ~/.config/systemd/user/ssh-socks-helper.socket
[Unit]
Description=Proxy Helper Socket for Bastion SOCKS5 Proxy
[Socket]
ListenStream=1080
[Install]
WantedBy=sockets.target
EOF
cat <<'EOF' > ~/.config/systemd/user/ssh-socks-helper.service
[Unit]
Description=Proxy Helper Service for Bastion SOCKS5 Proxy
Requires=ssh-socks-helper.socket
BindsTo=ssh-socks.service
After=ssh-socks.service
[Service]
ExecStartPre=/bin/sleep 5
ExecStart=/lib/systemd/systemd-socket-proxyd 127.0.0.1:10080
TimeoutStopSec=5
[Install]
WantedBy=multi-user.target
EOF
cat <<'EOF' > ~/.config/systemd/user/ssh-socks.service
[Unit]
Description=On-Demand Bastion SOCKS5 Proxy Service
[Service]
ExecStart=/usr/bin/ssh -aqND 10080 your.bastion.host
[Install]
WantedBy=multi-user.target
EOF
systemctl --user enable ssh-socks.service
systemctl --user enable ssh-socks-helper.service
systemctl --user enable ssh-socks-helper.socket
systemctl --user start ssh-socks-helper.socket
@AfroThundr3007730
Copy link
Author

If it is desired that the connection not linger indefinitely, the ExecStart line of ssh-socks.service can be modified like so:

ExecStart=/usr/bin/ssh -aqTD 10080 your.bastion.host sleep 3600

This will cause the connection to close after an hour (if there is no traffic currently passing through the proxy).

@MestreLion
Copy link

What is the systemd-socket-proxyd for? Couldn't the ssh-socks.service be bound directly to the socket service ?

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