Mark packets with iptables by destination mac address

11,073

The trick is to combine iptables --mac-source with CONNMARK:

  • First use --mac-source to match packets coming from the mac address you're interested in. It's the wrong direction since you're interested in packets going to this mac address, but now you can
  • use CONNMARK to mark the whole connection, ie both directions (!) and
  • set the mark from the connection mark with --restore-mark


# lan interface
if_lan=eth0

# create 'mark_mac' table for marking connections:
iptables -t mangle -N mark_mac
iptables -t mangle -A mark_mac -j MARK --set-mark 1234
iptables -t mangle -A mark_mac -j CONNMARK --save-mark

# mark connections involving mac address:
iptables -t mangle -A PREROUTING -i $if_lan -m state --state NEW -m mac --mac-source 9c:4e:36:aa:bb:cc -j mark_mac

# mark packets going to mac:
iptables -t mangle -A POSTROUTING -o $if_lan -m state --state ESTABLISHED,RELATED -j CONNMARK --restore-mark


Initially i thought this would only work for tcp connections originating from the lan, but given the definition of --state NEW it should work in both directions for both tcp and udp (!)

See also Policy Routing on Linux based on Sender MAC Address which was the inspiration for this answer.

Share:
11,073

Related videos on Youtube

Serhii Matrunchyk
Author by

Serhii Matrunchyk

Updated on September 18, 2022

Comments

  • Serhii Matrunchyk
    Serhii Matrunchyk over 1 year

    I need to mark packets which goes to a specified mac address.

    I need this to use in shaper with tc.

    --mac-destination doesn't exist in iptables.

    Also I tried to use ebtables:

    ebtables -t nat -A POSTROUTING -d 9c:4e:36:aa:bb:cc -j mark --set-mark 0x2003 --mark-target ACCEPT

    but it doesn't mark anything (at least ebtables -t nat -L --Lc shows me 0 counters)

    Please help! Thank you so much!

  • Serhii Matrunchyk
    Serhii Matrunchyk over 8 years
    Thank you. I used ebtables -t nat -A PREROUTING -p arp --arp-mac-dst bc:5f:f4:aa:bb:cc -j mark --mark-set 0x2003 and ebtables -t nat -L --Lv shows no matches..
  • lemonsqueeze
    lemonsqueeze almost 7 years
    This answer is misleading: wifi networks do have mac addresses and iptables --mac-source works fine with them. The man page should probably read "... coming from an ethernet/wifi device"