Implementing Port Knocking

Implementing Port Knocking

Port knocking adds an additional authentication layer by requiring a specific sequence of connection attempts before opening the SSH port. While not suitable for all environments, it effectively hides SSH from automated scanners.

Deploy a port knocking solution:

# Install knockd
apt-get install knockd

# Configure knockd
cat > /etc/knockd.conf << 'EOF'
[options]
    UseSyslog
    LogFile = /var/log/knockd.log

[openSSH]
    sequence    = 7000,8000,9000
    seq_timeout = 5
    command     = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
    tcpflags    = syn

[closeSSH]
    sequence    = 9000,8000,7000
    seq_timeout = 5
    command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
    tcpflags    = syn

[tmpOpenSSH]
    sequence    = 1111,2222,3333
    seq_timeout = 5
    start_command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
    cmd_timeout   = 300
    stop_command  = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
    tcpflags      = syn
EOF

# Client-side knocking script
cat > /usr/local/bin/ssh-knock << 'EOF'
#!/bin/bash
# ssh-knock - Port knocking client

HOST=$1
shift

# Send knock sequence
for port in 7000 8000 9000; do
    nc -z -w1 $HOST $port
    sleep 0.5
done

# Wait for port to open
sleep 1

# Connect via SSH
ssh $HOST "$@"

# Close sequence after disconnect
for port in 9000 8000 7000; do
    nc -z -w1 $HOST $port
    sleep 0.5
done
EOF

chmod +x /usr/local/bin/ssh-knock