Skip to content

Instantly share code, notes, and snippets.

@thefinn93
Last active March 12, 2022 00:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thefinn93/c70527233c0de4f200a8d655ca6fd04e to your computer and use it in GitHub Desktop.
Save thefinn93/c70527233c0de4f200a8d655ca6fd04e to your computer and use it in GitHub Desktop.
Finn's Amazing iptables Thing
# /etc/iptables.rules remove this line
*filter
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i enp5s0 -j DROP
-A FORWARD -i enp5s0 -p udp -m udp --dport 34197 -m state --state NEW -j ACCEPT
COMMIT
// /etc/port-forward.json dont forget to delete this line since comments are not valid JSON
// These are just sample values, obviously you'll want to change most of it
{
"public-if": "enp5s0",
"port-forwards": {
"80": "10.5.0.80:80",
"443": "10.5.0.80:443",
"8443": "10.5.0.60:8443",
"5222": "10.5.0.198:5222",
"5269": "10.5.0.198:5269",
"34197": "10.5.0.228:34197"
}
}
#!/usr/bin/env python3
# This goes at /etc/network/if-pre-up.d/iptables
import json
import sys
rules = {
"filter": ["-A INPUT -i lo -j ACCEPT", "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT"],
"nat": []
}
with open(sys.argv[1]) as f:
config = json.load(f)
public_if = config["public-if"]
for extport, dest in config['port-forwards'].items():
rules['nat'].append("-A PREROUTING -i {} -p tcp -m tcp --dport {} -j DNAT --to-destination {}".format(public_if, extport, dest))
rules['nat'].append("-A PREROUTING -i {} -p udp -m udp --dport {} -j DNAT --to-destination {}".format(public_if, extport, dest))
rules['filter'].append("-A FORWARD -i {} -p tcp -m tcp --dport {} -m state --state NEW -j ACCEPT".format(public_if, extport))
rules['filter'].append("-A FORWARD -i {} -p udp -m udp --dport {} -m state --state NEW -j ACCEPT".format(public_if, extport))
rules['nat'].append("-A POSTROUTING -o {} -j MASQUERADE".format(public_if))
rules['filter'].append("-A INPUT -i enp5s0 -j DROP")
for t in ['filter', 'nat']:
print("*{}".format(t))
print("\n".join(rules[t]))
print("COMMIT")
#!/bin/sh
# This goes at /etc/network/if-pre-up.d/iptables
set -ex
env | logger -t $0
/opt/port-forward.py /etc/port-forwards.json | /sbin/iptables-restore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment