Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Last active June 18, 2016 09:22
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 FGRibreau/aed6872583cc060c31a0e6929c7e0d52 to your computer and use it in GitHub Desktop.
Save FGRibreau/aed6872583cc060c31a0e6929c7e0d52 to your computer and use it in GitHub Desktop.

On your server (ubuntu/debian)

apt-get update
# We want to make ensure to allow all established connections and on-going sessions through the firewall, otherwise, the firewall would block the current SSH session
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Then use the following rule to block incoming port 22 (SSH)
iptables -A INPUT -p tcp --destination-port 22 -j DROP


# Once you have established your iptables rules, you can automate the restore process at reboot with iptables-persistent.
apt-get install iptables-persistent

# save current configuration
iptables-save

# install knockd
apt-get install knockd

# edit knockd configuration
nano /etc/knockd.conf

# change the knock sequence with your favorite (and available) ports

# change:
# /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
# to:
# /sbin/iptables -I INPUT 1 -s %IP% -p tcp --dport 22 -j ACCEPT
# so the rules will be inserted on top, before the blocking rule.

# edit default to activate knockd
nano /etc/default/knockd

# pass "START_KNOCKD" to 1
# don't forget to change KNOCKD_OPTS if your interface differs 
# save it

service knockd start

From your laptop (macOS/zsh)

# install
brew install knock

# edit
nano ~/.zshrc
knockIn() {
  knock -v -d 200 $1 1000 2000 3000
}

knockOut() {
  knock -v -d 200 $1 3000 2000 1000
}

sshWithKnock() {
  knockIn $1
  ssh $1
  knockOut $1
}

yourServer() {
  sshWithKnock yourServer.com
}

# save

# reload
source ~/.zshrc

# enjoy!
myServer

Sources

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