ldx / python-iptables

Python bindings for iptables
730 stars 183 forks source link

REDIRECT to port #264

Closed smandon closed 3 years ago

smandon commented 5 years ago

Hi,

I'm trying to use python-iptables installed from pip (version 0.13.0) with python3 to create rules using --to-port with the REDIRECT target. For example: iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j REDIRECT --to-port 80

but I cannot get the --to-port parameter to work. I tried in a way similar to code found in other issues here (eg for --to-destination with DNAT), by setting to_port for my rule's target but it doesn't work. I don't know if it's not implemented in python-iptables, if the syntax I'm using is wrong or if it's a bug:

>>> import iptc
>>> rule=iptc.Rule()
>>> rule.protocol='tcp'
>>> rule.dport='8080'
>>> rule.target = iptc.Target(rule, 'REDIRECT')
>>> rule.target.to_port = '80'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/iptc/ip4tc.py", line 455, in __setattr__
    self.parse(name.replace("_", "-"), value)
  File "/usr/local/lib/python3.6/dist-packages/iptc/ip4tc.py", line 332, in parse
    self._parse(argv, inv, entry)
  File "/usr/local/lib/python3.6/dist-packages/iptc/ip4tc.py", line 795, in _parse
    self._orig_parse, self._orig_options)
  File "/usr/local/lib/python3.6/dist-packages/iptc/xtables.py", line 869, in new
    return fn(*args)
  File "/usr/local/lib/python3.6/dist-packages/iptc/xtables.py", line 1108, in parse_target
    argv[0]))
iptc.errors.XTablesError: b'REDIRECT': no such parameter b'to-port'
ldx commented 5 years ago

Can you try using to-ports instead of to-port? Iptables internally does some kind of aliasing between the two when calling via the command line.

jllorente commented 5 years ago

@smandon as of version 0.14 there is a new module added called iptc.easy (see the README for more information about this module). You can either use it as a replacement of the low level interface provided by iptc or as a simple debugging tool for your iptc code for rules, targets, etc. See the following example:

# iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j REDIRECT --to-port 80
# python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import iptc
>>> iptc.easy.dump_chain('nat', 'PREROUTING')
[{'tcp': {'dport': '8080'}, 'in-interface': 'eth0', 'protocol': 'tcp', 'target': {'REDIRECT': {'to-ports': '80'}}}]

As previsouly indicated by @ldx , the valid iptc syntax for this particular case is to-ports

>>> import iptc
>>> rule=iptc.Rule()
>>> rule.protocol='tcp'
>>> rule.dport='8080'
>>> rule.target = iptc.Target(rule, 'REDIRECT')
>>> rule.target.to_ports = '80'
>>>
jllorente commented 4 years ago

@smandon did any of the proposed fixes work for you?