Usage

The python API in python-iptables tries to mimic the logic of iptables. You have

  • Tables, Table.FILTER, Table.NAT, Table.MANGLE and Table.RAW for IPv4; Table6.FILTER, Table6.SECURITY, Table6.MANGLE and Table6.RAW for IPv6. They can be used to filter packets, do network address translation or modify packets in various ways.
  • Chains inside tables. Each table has a few built-in chains, but you can also create your own chains and jump into them from other chains. When you create your chains you should also specify which table it will be used in. Chains have Policies, which tell what to do when the end of a chain is reached.
  • Each chain has zero or more rules. A rule specifies what kind of packets to match (matches, each rule can have zero, one or more matches) and what to do with them (target, each rule has one of them). Iptables implements a plethora of match and target extensions. For IPv4, the class implementing this is called Rule, for IPv6 it is called Rule6.
  • Matches, specifying when a rule needs to be applied to a packet. To create a match object you also has to specify the rule to which it belongs.
  • Targets, specifying what to do when a rule is applied to a packet. To create a target object you also has to specify the rule to which it belongs.

The python API is quite high-level and hides the low-level details from the user. Using only the classes Table, Chain, Rule, Match and Target virtually anything can be achieved that you can do with iptables from the command line.

Table

class iptc.Table

A table is the most basic building block in iptables.

There are four fixed tables:
  • Table.FILTER, the filter table,
  • Table.NAT, the NAT table,
  • Table.MANGLE, the mangle table and
  • Table.RAW, the raw table.

The four tables are cached, so if you create a new Table, and it has been instantiated before, then it will be reused. To get access to e.g. the filter table:

>>> table = iptc.Table(iptc.Table.FILTER)

The interface provided by Table is rather low-level, in fact it maps to libiptc API calls one by one, and take low-level iptables structs as parameters. It is encouraged to, when possible, use Chain, Rule, Match and Target to achieve what is wanted instead, since they hide the low-level details from the user.

ALL = ['filter', 'mangle', 'raw', 'nat', 'security']

This is the constant for all tables.

FILTER = 'filter'

This is the constant for the filter table.

MANGLE = 'mangle'

This is the constant for the mangle table.

NAT = 'nat'

This is the constant for the nat table.

RAW = 'raw'

This is the constant for the raw table.

SECURITY = 'security'

This is the constant for the security table.

builtin_chain(chain)

Returns True if chain is a built-in chain.

chains

List of chains in the table.

close()

Close the underlying connection handle to iptables.

commit()

Commit any pending operation.

first_rule(chain)

Returns the first rule in chain or None if it is empty.

flush()

Flush and delete all non-builtin chains the table.

get_target(entry)

Returns the standard target in entry.

is_chain(chain)

Returns True if chain exists as a chain.

next_rule(prev_rule)

Returns the next rule after prev_rule.

refresh()

Commit any pending operation and refresh the status of iptables.

strerror()

Returns any pending iptables error from the previous operation.

Table6

class iptc.Table6

The IPv6 version of Table.

There are four fixed tables:
  • Table.FILTER, the filter table,
  • Table.MANGLE, the mangle table,
  • Table.RAW, the raw table and
  • Table.SECURITY, the security table.

The four tables are cached, so if you create a new Table, and it has been instantiated before, then it will be reused. To get access to e.g. the filter table:

>>> import iptc
>>> table = iptc.Table6(iptc.Table6.FILTER)

The interface provided by Table is rather low-level, in fact it maps to libiptc API calls one by one, and take low-level iptables structs as parameters. It is encouraged to, when possible, use Chain, Rule, Match and Target to achieve what is wanted instead, since they hide the low-level details from the user.

ALL = ['filter', 'mangle', 'raw', 'nat', 'security']

This is the constant for all tables.

FILTER = 'filter'

This is the constant for the filter table.

MANGLE = 'mangle'

This is the constant for the mangle table.

NAT = 'nat'

This is the constant for the nat table.

RAW = 'raw'

This is the constant for the raw table.

SECURITY = 'security'

This is the constant for the security table.

builtin_chain(chain)

Returns True if chain is a built-in chain.

close()

Close the underlying connection handle to iptables.

commit()

Commit any pending operation.

first_rule(chain)

Returns the first rule in chain or None if it is empty.

flush()

Flush and delete all non-builtin chains the table.

get_target(entry)

Returns the standard target in entry.

is_chain(chain)

Returns True if chain exists as a chain.

next_rule(prev_rule)

Returns the next rule after prev_rule.

refresh()

Commit any pending operation and refresh the status of iptables.

strerror()

Returns any pending iptables error from the previous operation.

Chain

class iptc.Chain(table, name)

Rules are contained by chains.

iptables has built-in chains for every table, and users can also create additional chains. Rule targets can specify to jump into another chain and continue processing its rules, or return to the caller chain.

table is the table this chain belongs to, name is the chain’s name.

If a chain already exists with name in table it is returned.

append_rule(rule)

Append rule to the end of the chain.

delete()

Delete chain from its table.

delete_rule(rule)

Removes rule from the chain.

flush()

Flush all rules from the chain.

get_counters()

This method returns a tuple pair of the packet and byte counters of the chain.

get_policy()

Returns the policy of the chain as a Policy object.

get_target(rule)

This method returns the target of rule if it is a standard target, or None if it is not.

insert_rule(rule, position=0)

Insert rule as the first entry in the chain if position is 0 or not specified, else rule is inserted in the given position.

is_builtin()

Returns whether the chain is a built-in one.

rename(new_name)

Rename chain to new_name.

replace_rule(rule, position=0)

Replace existing rule in the chain at position with given rule

rules

This is the list of rules currently in the chain.

The indexes of the Rule items produced from this list should correspond to the IPTables –line-numbers value minus one. Keeping in mind that iptables rules are 1-indexed whereas the Python list is 0-indexed

set_policy(policy, counters=None)

Set the chain policy to policy, which should either be a string or a Policy object. If counters is not None, the chain counters are also adjusted. Counters is a list or tuple with two elements.

zero_counters()

This method zeroes the packet and byte counters of the chain.

Policy

class iptc.Policy(name)

If the end of a built-in chain is reached or a rule in a built-in chain with target RETURN is matched, the target specified by the chain policy determines the fate of the packet.

ACCEPT = 'ACCEPT'

If no matching rule has been found so far then accept the packet.

DROP = 'DROP'

If no matching rule has been found so far then drop the packet.

QUEUE = 'QUEUE'

If no matching rule has been found so far then queue the packet to userspace.

RETURN = 'RETURN'

Return to calling chain.

Match

class iptc.Match(rule, name=None, match=None, revision=None)

Matches are extensions which can match for special header fields or other attributes of a packet.

Target and match extensions in iptables have parameters. These parameters are implemented as instance attributes in python. However, to make the names of parameters legal attribute names they have to be converted. The rule is to cut the leading double dash from the name, and replace dashes in parameter names with underscores so they are accepted by python as attribute names. E.g. the TOS target has parameters –set-tos, –and-tos, –or-tos and –xor-tos; they become target.set_tos, target.and_tos, target.or_tos and target.xor_tos, respectively. The value of a parameter is always a string, if a parameter does not take any value in the iptables extension, an empty string “” should be used.

rule is the Rule object this match belongs to; it can be changed later via set_rule(). name is the name of the iptables match extension (in lower case), match is the raw buffer of the match structure if the caller has it. Either name or match must be provided. revision is the revision number of the extension that should be used; different revisions use different structures in C and they usually only work with certain kernel versions. Python-iptables by default will use the latest revision available.

match

This is the C structure used by the extension.

match_buf

This is the buffer holding the C structure used by the extension.

reset()

Reset the match.

Parameters are set to their default values, any flags are cleared.

set_parameter(parameter, value=None)

Set a parameter for target or match extension, with an optional value.

@param parameter: name of the parameter to set @type parameter: C{str}

@param value: optional value of the parameter, defaults to C{None} @type value: C{str} or a C{list} of C{str}

size

This is the full size of the underlying C structure.

usersize

This is the size of the part of the underlying C structure that is used in userspace.

Target

class iptc.Target(rule, name=None, target=None, revision=None, goto=None)

Targets specify what to do with a packet when a match is found while traversing the list of rule entries in a chain.

Target and match extensions in iptables have parameters. These parameters are implemented as instance attributes in python. However, to make the names of parameters legal attribute names they have to be converted. The rule is to cut the leading double dash from the name, and replace dashes in parameter names with underscores so they are accepted by python as attribute names. E.g. the TOS target has parameters –set-tos, –and-tos, –or-tos and –xor-tos; they become target.set_tos, target.and_tos, target.or_tos and target.xor_tos, respectively. The value of a parameter is always a string, if a parameter does not take any value in the iptables extension, an empty string i.e. “” should be used.

rule is the Rule object this match belongs to; it can be changed later via set_rule(). name is the name of the iptables target extension (in upper case), target is the raw buffer of the target structure if the caller has it. Either name or target must be provided. revision is the revision number of the extension that should be used; different revisions use different structures in C and they usually only work with certain kernel versions. Python-iptables by default will use the latest revision available. If goto is True, then it converts ‘-j’ to ‘-g’.

reset()

Reset the target. Parameters are set to their default values, any flags are cleared.

set_parameter(parameter, value=None)

Set a parameter for target or match extension, with an optional value.

@param parameter: name of the parameter to set @type parameter: C{str}

@param value: optional value of the parameter, defaults to C{None} @type value: C{str} or a C{list} of C{str}

size

This is the full size of the underlying C structure.

standard_target

This attribute is used for standard targets. It can be set to ACCEPT, DROP, RETURN or to a name of a chain the rule should jump into.

target

This is the C structure used by the extension.

usersize

This is the size of the part of the underlying C structure that is used in userspace.

Rule

class iptc.Rule(entry=None, chain=None)

Rules are entries in chains.

Each rule has three parts:
  • An entry with protocol family attributes like source and destination address, transport protocol, etc. If the packet does not match the attributes set here, then processing continues with the next rule or the chain policy is applied at the end of the chain.
  • Any number of matches. They are optional, and make it possible to match for further packet attributes.
  • One target. This determines what happens with the packet if it is matched.

entry is the ipt_entry buffer or None if the caller does not have it. chain is the chain object this rule belongs to.

add_match(match)

Adds a match to the rule. One can add any number of matches.

counters

This is the packet and byte counters of the rule.

create_match(name, revision=None)

Create a match, and add it to the list of matches in this rule. name is the name of the match extension, revision is the revision to use.

create_target(name, revision=None, goto=False)

Create a new target, and set it as this rule’s target. name is the name of the target extension, revision is the revision to use. goto determines if target uses ‘-j’ (default) or ‘-g’.

dst

This is the destination network address with an optional network mask in string form.

final_check()

Do a final check on the target and the matches.

fragment

This means that the rule refers to the second and further fragments of fragmented packets. It can be True or False.

get_counters()

This method returns a tuple pair of the packet and byte counters of the rule.

in_interface

This is the input network interface e.g. eth0. A wildcard match can be achieved via + e.g. ppp+ matches any ppp interface.

mask

This is the raw mask buffer as iptables uses it when removing rules.

matches

This is the list of matches held in this rule.

out_interface

This is the output network interface e.g. eth0. A wildcard match can be achieved via + e.g. ppp+ matches any ppp interface.

protocol

This is the transport layer protocol.

remove_match(match)

Removes match from the list of matches.

rule

This is the raw rule buffer as iptables expects and returns it.

set_counters(counters)

This method set a tuple pair of the packet and byte counters of the rule.

src

This is the source network address with an optional network mask in string form.

tables

This is the list of tables for our protocol.

target

This is the target of the rule.

Rule6

class iptc.Rule6(entry=None, chain=None)

This is an IPv6 rule.

add_match(match)

Adds a match to the rule. One can add any number of matches.

counters

This method returns a tuple pair of the packet and byte counters of the rule.

create_match(name, revision=None)

Create a match, and add it to the list of matches in this rule. name is the name of the match extension, revision is the revision to use.

create_target(name, revision=None, goto=False)

Create a new target, and set it as this rule’s target. name is the name of the target extension, revision is the revision to use. goto determines if target uses ‘-j’ (default) or ‘-g’.

dst

This is the destination network address with an optional network mask in string form.

final_check()

Do a final check on the target and the matches.

get_counters()

This method returns a tuple pair of the packet and byte counters of the rule.

in_interface

This is the input network interface e.g. eth0. A wildcard match can be achieved via + e.g. ppp+ matches any ppp interface.

out_interface

This is the output network interface e.g. eth0. A wildcard match can be achieved via + e.g. ppp+ matches any ppp interface.

protocol

This is the transport layer protocol.

remove_match(match)

Removes match from the list of matches.

set_counters(counters)

This method set a tuple pair of the packet and byte counters of the rule.

src

This is the source network address with an optional prefix length in string form.

tables

This is the list of tables for our protocol.

IPTCError

exception iptc.IPTCError

This exception is raised when a low-level libiptc error occurs.

It contains a short description about the error that occurred while executing an iptables operation.