2

We would like to use iptables to log all network connections except if the connecting address is A.B.C.D or the connecting address is E.F.G.H. These two addresses cannot be combined into a single CIDR range without the range including addresses we do want to include. I get part-way there by adding this iptables rule:

-I INPUT ! -s A.B.D.E -p tcp -m tcp --dport 3306 -m state --state NEW  -j LOG --log-level 1 --log-prefix "New Connection "

However, this still logs connections from E.F.G.H. Is there a way to get everything without logging either?

(These two addresses generate many connections and we don't need to log them.)

user35042
  • 2,681
  • 12
  • 34
  • 60

3 Answers3

1

Add a rule or two above the line you quoted specifically allowing A.B.C.D or E.F.G.H, then do the logging below that. iptables works in order of the rules, so allowing something through earlier is the end of the processing.

This is also why you add a generic "deny all" to the end of most firewall rulesets. If something isn't covered by your rules above, then deny it because it's unexpected and likely unwanted.

Example (adjust as necessary, don't just copy paste this in):

-A INPUT -s A.B.C.D -p tcp -m tcp --dport 3306 -m state --state NEW -j ACCEPT
-A INPUT -s E.F.G.H -p tcp -m tcp --dport 3306 -m state --state NEW -j ACCEPT
-A INPUT -p tcp -m tcp --dport 3306 -m state --state NEW  -j LOG --log-level 1 --log-prefix "New Connection "
-A INPUT -j DROP
Hyppy
  • 15,608
  • 1
  • 38
  • 59
0

You can create a custom chain, which could be named LOG_UNLESS, and then you could do as follows:

-A INPUT -p tcp -m tcp --dport 3306 -m state --state NEW -j LOG_UNLESS
-A LOG_UNLESS -s 192.0.2.1 -j RETURN
-A LOG_UNLESS -s 203.0.113.2 -j RETURN
-A LOG_UNLESS -j LOG --log-level 1 --log-prefix "New Connection "
kasperd
  • 30,455
  • 17
  • 76
  • 124
0

Another option would be to use ipset.

First, you create the proper IP set:

ipset create DO_NOT_LOG hash:ip

Then, add the addresses you want to exclude:

ipset add DO_NOT_LOG A.B.C.D
ipset add DO_NOT_LOG E.F.G.H

Finally, on the iptables logging rule, add a negative match:

-I INPUT -m set ! --match-set DO_NOT_LOG src -p tcp -m tcp --dport 3306 -m state --state NEW  -j LOG --log-level 1 --log-prefix "New Connection "

The ! --match-set DO_NOT_LOG src means: "Match against packets whose source (src) address is NOT found in the DO_NOT_LOG set"

pepoluan
  • 5,038
  • 4
  • 47
  • 72