Skip to content

Instantly share code, notes, and snippets.

@sitedata
Forked from NiKiZe/start.sh
Created June 30, 2022 21:44
Show Gist options
  • Save sitedata/dcd99781b9e3d287e257ff54d36fe113 to your computer and use it in GitHub Desktop.
Save sitedata/dcd99781b9e3d287e257ff54d36fe113 to your computer and use it in GitHub Desktop.
Filter and route on hostname using SNI
#!/bin/bash
# Filter and route on hostname using SNI
# https://github.com/Lochnair/xt_tls/issues/52
# This creates iptables rules and ip rules to filter and route HTTPS traffic based on hostname in SNI field
# Some links on why packets might be droped, see rp_filter below
# https://serverfault.com/questions/934848/ip-rule-to-works-but-ip-rule-fwmark-fails-why
# https://serverfault.com/questions/932205/advanced-routing-with-firewall-marks-and-rp-filter
# https://serverfault.com/questions/816393/disabling-rp-filter-on-one-interface
# https://www.theurbanpenguin.com/rp_filter-and-lpic-3-linux-security/
iptables -N newtlsvpn
iptables -A FORWARD -p tcp --dport 443 -m tls --tls-hostset tlsvpn -j newtlsvpn
iptables -A FORWARD -p tcp --dport 443 -m tls --tls-hostset tlsvpn --tls-suffix -j newtlsvpn
iptables -A FORWARD -m recent --rdest --name tlsvpn --rcheck --seconds 3600 -j newtlsvpn
iptables -F newtlsvpn
# do not mark here since that only works in mangle.PREROUTING
iptables -A newtlsvpn -m recent --rdest --name tlsvpn --set -j ACCEPT
iptables -t mangle -A PREROUTING -m recent --rdest --name tlsvpn --update --seconds 3600 --reap -j MARK --set-mark 0x0200
ip rule add from all fwmark 0x200 lookup 200 prio 200
ip route add default via x.x.x.x table 200
# handling above means that initial connection will do TLS client hello and then fail due to connection issues.
# it should however retry and as long as destination IP is the same as before,
# it should now use ip rule and use different table and gateway
echo +facebook.com > /proc/net/xt_tls/hostset/tlsvpn
echo +googlevideo.com > /proc/net/xt_tls/hostset/tlsvpn
grep "" /proc/sys/net/ipv4/conf/*/rp_filter
# Without this traffic will be blocked after mangle PREROUTING table since there is no route back matching the interface
echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter
echo 0 > /proc/sys/net/ipv4/conf/tun0/rp_filter
cat /proc/net/xt_tls/hostset/tlsvpn
cat /proc/net/xt_recent/tlsvpn
iptables -vnL
iptables -vnL -t mangle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment