This command says "if network traffic is incoming from X IP address, but is not on Y interface, then DROP it." Note that it is in the raw table, which is the first and fastest table hit when network traffic comes in to IPtables.
iptables -t raw -A PREROUTING -s ${X} ! -i ${Y} -j DROP
You should have another permutation of this rule in the opposite direction:
iptables -t raw -A PREROUTING ! -s ${X} -i ${Y} -j DROP
You can log violations of these rules by having these four commands:
iptables -t raw -A PREROUTING -s ${X} ! -i ${Y} -j LOG --log-prefix "Wrong IP: "
iptables -t raw -A PREROUTING -s ${X} ! -i ${Y} -j DROP
iptables -t raw -A PREROUTING ! -s ${X} -i ${Y} -j LOG --log-prefix "Wrong Interface: "
iptables -t raw -A PREROUTING ! -s ${X} -i ${Y} -j DROP
EDIT: Edited after I received more clarification in the comments.
This rule says "if traffic is incoming from IP address X and is not destined for IP address Z, then drop the traffic."
iptables -t raw -A PREROUTING -s ${X} ! -d ${Z} -j DROP
This rules says "if traffic is incoming on interface Y and is not destined for IP address Z, then drop the traffic."
iptables -t raw -A PREROUTING -i ${Y} ! -d ${Z} -j DROP
Here is a combination of those two rules, that says "if traffic is incoming from IP address X and is incoming on interface Y and is not destined for IP address Z, then drop the traffic."
iptables -t raw -A PREROUTING -s ${X} -i ${Y} ! -d ${Z} -j DROP.
Just a note: I like to use the raw
table if the rules do not require connection tracking. The raw
table does not track any connections. In this case, no connection tracking is necessary for these rules. Connection tracking is necessary for the nat
table and for the conntrack
module (-m conntrack
). The raw
table is much more performant than other tables because connection tracking takes up significantly more resources on your server. The filter table is fine to use, however, and if it's simpler and makes more sense for you, then use the filter table. The rules would be exactly the same, but just -t raw
would become -t filter
When packets enter IPtables, they traverse the tables like this:
raw --> mangle (where connection tracking begins) --> nat --> filter