Skip to content

Instantly share code, notes, and snippets.

@zorael
Created July 31, 2021 13:56
Show Gist options
  • Save zorael/93fcbba0d85cfec028681d6a6772cf0b to your computer and use it in GitHub Desktop.
Save zorael/93fcbba0d85cfec028681d6a6772cf0b to your computer and use it in GitHub Desktop.
iptables script to rate-limit the access to a QEMU RDP port open to the world (just use `iptables-save`)
#!/bin/bash
set -e
if [[ $UID -gt 0 ]]; then
echo "sudo ${0##*/} $@"
sudo $0 "$@"
exit $?
fi
NAME="qemu"
UPTO="1/min"
BURST=4
EXPIRE=90000
PORT=8986
LOG_NAME="qemu-log"
LOG_UPTO="2/min"
LOG_EXPIRE=30000
LOG_LABEL_DROP="QEMU DROP: "
LOG_LABEL_ACCEPT="QEMU ACCEPT: "
## Accept and LOG chain
iptables -F QEMU-ACCEPT 2>/dev/null || iptables -N QEMU-ACCEPT
iptables -A QEMU-ACCEPT \
-j LOG \
--log-level 4 \
--log-prefix "$LOG_LABEL_ACCEPT"
iptables -A QEMU-ACCEPT -j ACCEPT
## Eval chain (additionally logs DROPs)
iptables -F QEMU 2>/dev/null || iptables -N QEMU
iptables -A QEMU \
--match hashlimit \
--hashlimit-mode srcip \
--hashlimit-upto "$UPTO" \
--hashlimit-burst $BURST \
--hashlimit-htable-expire $EXPIRE \
--hashlimit-name "$NAME" \
-j QEMU-ACCEPT
iptables -A QEMU \
--match hashlimit \
--hashlimit-mode srcip \
--hashlimit-upto "$LOG_UPTO" \
--hashlimit-burst 1 \
--hashlimit-htable-expire $LOG_EXPIRE \
--hashlimit-name "$LOG_NAME" \
-j LOG \
--log-level 1 \
--log-prefix "$LOG_LABEL_DROP"
iptables -A QEMU -j DROP
## Input rules
iptables -A INPUT \
--proto tcp \
--match tcp \
--dport $PORT \
--match conntrack \
--ctstate NEW \
-j QEMU
iptables -A INPUT \
--proto tcp \
--match tcp \
--dport $PORT \
-j ACCEPT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment