Wildcard support for MAC addresses in netfilter (Linux kernel) and iptables

Some time ago Riki from Netlabs proposed a simple challenge: add wildcard support for MAC addresses when specifying netfilter rules in Linux.

Netfilter and iptables -its user-space counter part- let you filter network packets based on their source MAC address. However, there is currently no option to match all packets that meet a specific pattern (i.e.: those with prefix from a certain vendor). A wildcards syntax would be enough to accomplish this goal. In example, the following rule should drop every incoming packet on the ens3 interface:

A quick lookup in the Linux kernel source and in iptables brought me to a couple of files probably required by the implementation of this functionality: net/netfilter/xt_mac.c (kernel) and libxtables/xtoptions.c (iptables). The former is related to the decision of whether a packet should pass or not when filtering by MAC address. The latter has the iptables options parsing code, through which we can specify matching rules.

A possible implementation -not ready for production use- is at the end of this article. This implementation has a drawback: there is ambiguity between the wildcard character ‘*’ and the byte 0x2A (valid MAC address byte). As a result, we may want to filter the 2A:2A:2A:2A:2A:2A MAC address but all packets will skip the rule because this is equal to the *:*:*:*:*:* rule. A separate data structure to represent the mask would have been enough.

Code:

Tested on Fedora 25 (x86_64).

Leave a Reply

Your email address will not be published.