add a source NAT service using iptables masquerade

This commit is contained in:
Jeff Ahrenholz 2018-10-09 15:19:14 -07:00
parent b839482198
commit 366f63fb96

View file

@ -110,3 +110,47 @@ class Firewall(CoreService):
logger.exception("Error opening Firewall configuration template (%s)", fname)
return cfg
class Nat(CoreService):
''' IPv4 source NAT service
'''
name = "NAT"
group = "Security"
configs = ('nat.sh', )
startup = ('sh nat.sh',)
custom_needed = False
@classmethod
def generateifcnatrule(cls, ifc, line_prefix=""):
''' Generate a NAT line for one interface.
'''
cfg = line_prefix + "iptables -t nat -A POSTROUTING -o "
cfg +=ifc.name + " -j MASQUERADE\n"
cfg += line_prefix + "iptables -A FORWARD -i " + ifc.name
cfg += " -m state --state RELATED,ESTABLISHED -j ACCEPT\n"
cfg += line_prefix + "iptables -A FORWARD -i "
cfg += ifc.name + " -j DROP\n"
return cfg
@classmethod
def generate_config(cls, node, filename):
''' NAT out the first interface
'''
cfg = "#!/bin/sh\n"
cfg += "# generated by security.py\n"
cfg += "# NAT out the first interface by default\n"
have_nat = False
for ifc in node.netifs():
if hasattr(ifc, 'control') and ifc.control == True:
continue
if have_nat:
cfg += cls.generateifcnatrule(ifc, line_prefix='#')
else:
have_nat = True
cfg += "# NAT out the " + ifc.name + " interface\n"
cfg += cls.generateifcnatrule(ifc)
cfg += "\n"
return cfg