IptablesPacketFilterTable

class IptablesPacketFilterTable(table_name: str, chain_prefix: Optional[str] = None, runner=None, *, ipv6=False)[source]

A netfilter table containing chains.

The chains accessible via the methods of this class may be pruned based on an optionally provided prefix. Furthermore, when new chains are created, the prefix may be automatically added to the specified chain name.

A chain name without the prefix is referred to as the logical chain name, while the full chain name is referred to as the real chain name. When no prefix is specified, the logical and real names are identical.

Multiple IptablesPacketFilterTable objects for the same underlying netfilter table are not guaranteed to be in-sync.

An IptablesPacketFilterTable instance if either IPv4-specific or IPv6-specific depending on initialization.

Parameters:
  • table_name – one of filter, mangle, nat, raw, or security

  • chain_prefix – if specified, user chains are split into two groups: those with names starting with the prefix and those that don’t) with methods like get_user_chains() returning only these user chains; the chain name that excludes the prefix is referred to as the logical chain name

  • runner – optional Callable object used to invoke the iptables(8) command. The object should have the same signature as subprocess.run() and provide the same functionality. It also needs to consume the execute_always boolean parameter; this parameter is used to indicate that the iptables(8) command should be invoked even if the runner is in dryrun mode (this is used for read-only commands like iptables -L). The default is to use a function with similar functionality as subprocess.run().

  • ipv6 – if True, this is an IPv6-specific instance (i.e. ip6tables(8) will be invoked in place of iptables(8))

create_chain(chain_name: str, name_is_logical=True) Chain[source]

Create a new chain

Parameters:
  • chain_name – chain name, either logical or real

  • name_is_logical – indicates if chain_name is a logical chain name or a real chain name

delete_chain(chain: Chain, delete_referring_rules=True) None[source]

Delete the specified chain. The chain is flushed first.

Parameters:
  • chain – the Chain to delete

  • delete_referring_rules – if True, any rules targetting this chain will also be deleted

get_builtin_chain(chain_name: str) BuiltinChain[source]

Returns the BuiltinChain object with the specified chain_name.

Parameters:

chain_name – name of builtin chain

get_builtin_chains() List[Chain][source]

Returns a list of the builtin chains

get_chain(chain_name: str) Optional[Chain]

Returns the Chain object with the specified name or None if there is no such chain

Parameters:

chain_name – logical chain name

get_chain_by_lcn(chain_name: str) Optional[Chain][source]

Returns the Chain object with the specified name or None if there is no such chain

Parameters:

chain_name – logical chain name

get_chain_by_lcn_prefix(prefix: str) List[Chain][source]

Returns a list of Chain objects whose logical name starts with the specified prefix.

Parameters:

prefix – prefix of logical chain name

get_chain_by_rcn(real_chain_name: str) Optional[Chain][source]

Returns the Chain object with the specified name or None if there is no such chain

Parameters:

real_chain_name – real chain name

get_chain_map() Mapping[str, Chain][source]

Returns a dictionary containing all accessible chains; the key is the real chain name (if the IptablesPacketFilterTable uses a prefix, only chains with that prefix, and the builtin chains, will be included)

get_epoch() int[source]

Returns the number of times the iptables configuration has been initialized with iptables(8) output.

get_prefix() Optional[str][source]

Returns the chain prefix

get_rcn(lcn: str) str[source]

Returns the real chain name for the given logical chain name

Parameters:

lcn – logical chain name

get_rules_by_target(target: Target) List[List[ChainRule]][source]

The return value is a list of lists: the inner list contains ChainRule objects with the rules of a particular chain that are using the specified target, while the outer list corresponds to the chains containing these rules.

get_table_name() str[source]

Returns the table name

get_timestamp() Optional[float][source]

Returns the time that the iptables configuration was read (as obtained from time.time())

get_unparsed_chain_count() int[source]

Returns the number of chains that were not successfully parsed from the output of iptables(8)

get_unresolved_target_count() int[source]

Returns the number of rules with unresolved targets from the output of iptables(8). This may be due to targets being chains that we fail to find, or (more likely) special targets that we don’t know how to parse.

get_user_chains() List[Chain][source]

Returns a list of all user (i.e. non-builtin) chains

init_from_output(iptables_output: str, add_builtins=True, log_parsing_failures=True) bool[source]

Initialize the attributes of this IptablesPacketFilterTable from the output of iptables(8)

Parameters:
  • iptables_output – the output of iptables -L -xnv as included in subprocess.CompletedProcess.stdout

  • add_builtins – if this parameter is True then for any builtin chain that is not in the iptables_output (or if there is an error parsing its contents), an (empty) chain will be added to the IptablesPacketFilterTable

  • log_parsing_failures – if this parameter is True then parsing failures will be logged; such failures are typically the result of encountering rules with unknown matches/targets

Return type:

True if the iptables_output is successfully parsed with all expected builtin chains present, False otherwise

iptables_run(*args, **kwargs) CompletedProcess[source]

Execute an iptables(8) command with the specified arguments. The table name is added automatically. For example:

pft.iptables_run(['-N', 'newchain'])

will execute the command:

iptables -t mangle -N newchain

if the pft is an IptablesPacketFilterTable object for the mangle table.

Raises an IptablesExecutionError in the event of failure.

is_handler_of(rcn: str) bool[source]

Returns True if the real chain name rcn matches the prefix of this IptablesPacketFilterTable, or if this IptablesPacketFilterTable has no prefix.

Parameters:

rcn – real chain name

is_ipv6() bool[source]

Returns True if this table is for IPv6

rcn2lcn(rcn: str) str[source]

Convert a real chain name to a logical chain name by stripping the prefix (if there is one).

Raises an IptablesError if this IptablesPacketFilterTable has a prefix and it is unrelated to rcn.

Parameters:

rcn – real chain name

read_system_config(add_builtins=True, log_parsing_failures=True) bool[source]

Read the current iptables configuration and initialize the attributes of this IptablesPacketFilterTable.

Parameters:
  • add_builtins – if this parameter is True then for any builtin chain that is not in the output of iptables -xnv -L (or if there is a error parsing its contents), an (empty) chain will be added to the IptablesPacketFilterTable

  • log_parsing_failures – if this parameter is True then parsing failures will be logged; such failures are typically the result of encountering rules with unknown matches/targets

Return type:

True if the current iptables configuration is successfully parsed with all expected builtin chains present, False otherwise

set_prefix(prefix: Optional[str]) None[source]

Partition (or repartition) the user chains according to the specified prefix.

Parameters:

prefix – the new prefix

validate_chain_name(chain_name: str, *, description: Optional[str] = None, workaround: Optional[str] = None) None[source]

Check if the specified logical chain name is valid. Currently, only the name length is checked. An IptablesError will be raised if the name is not valid.

Parameters:
  • chain_name – logical chain name

  • description – text to include in the exception message (default: ‘chain’)

  • workaround – optional text to include in the exception message

zero_counters(chain: Optional[Chain] = None, rulenum: Optional[int] = None) None[source]

Zero the packet and byte counters for the specified chain or chain rule in the kernel. If no chain is specified, all chain counters are zero’d.

Note that this method does not affect the counters of Chain or ChainRule objects which will maintain the values they had from the last time the system configuration was read.