setup_sshdHiddenService.sh (use gist to copy code. Sometimes something doesn’t escape escaping of WordPress editor 😉 )

#! /bin/sh
 
# sshd tor authenticated hidden service setup script
# <configuration>
SSH_PORT="" # new SSH port, leave empty for no change
# </configuration>
# workflow:
# - change SSH port if not empty
# - setup SSH brute force protection: fail2ban
# - setup tor: basic authenticated sshd hidden service
# - output of hidden service connection data
# more about authenticated hidden services: 
# https://www.antitree.com/2017/08/tor-onion-service-stealth-and-basic-authentication-modes/
 
function setup {    
 
    # change SSH port if set
    if [ ! -z "$SSH_PORT" ]; then
        sed -i "s|Port [0-9]+|Port ${SSH_PORT}|" /etc/ssh/sshd_config
    fi
 
    # install fail2ban
    apt-get install -y fail2ban
 
    # setup tor
    apt-get install -y tor
 
    # setup basic authenticated hidden service sshd
    # NOTICE: sed -i '1i XXX' FILEPATH; adds value (XXX) on first line of file /etc/tor/torrc/
 
    # "basic" authenticated hidden server, set service name: HiddenServiceAuthorizeClient
    sed -i "1i HiddenServiceAuthorizeClient basic sshd" /etc/tor/torrc
 
    # forward hidden service port to local ssh: HiddenServicePort
    sed -i "1i HiddenServicePort ${SSH_PORT} 127.0.0.1:${SSH_PORT}" /etc/tor/torrc
 
    # hidden service directory contains services private key, address: HiddenServiceDir
    sed -i "1i HiddenServiceDir /var/lib/tor/sshd/" /etc/tor/torrc
 
    # restart tor to load new settings
    systemctl restart tor
 
    sleep 1
 
    # formated hidden service data output for user
    # get hidden service url, login from file, remove comment
    HIDDEN_SERVICE_COOKIE=$(cat /var/lib/tor/tcpproxy/hostname | sed -Ee "s| # client:||") 
 
    # get hidden service uri from cookie, get string until first whitespace
    HIDDEN_SERVICE_HOST=$(echo ${HIDDEN_SERVICE_COOKIE} | sed -Ee 's| .*||')
 
    # user output
    echo "##########"
    echo "add next line to your local tor configuration at /etc/tor/torrc:"
    echo "HidServAuth ${HIDDEN_SERVICE_COOKIE}"
    echo "##########"
    echo "connect to your hidden service sshd after local tor restart:"
    echo "torsocks ssh ${HIDDEN_SERVICE_HOST} -p ${SSH_PORT}"
 
    # message ssh will disconnect, wait for y key / restart
    RESTART_SSHD=""
    while [ "$RESTART_SSHD" != "y" ]; do
        echo "restart of sshd required"
        read -p "you need to reconnect ssh at port ${SSH_PORT} [y/STRG+C]: " RESTART_SSHD
    done
    systemctl restart sshd
}
 
# check root, ask for root, run setup as root
WHOAMI=$(whoami)
if [ "$WHOAMI" != "root" ]; then
    su -c "$(declare -f setup); setup"    
else
    setup
fi
no comments »