If you’ve ever dealt with trying to control the traffic on your server and been confused by all the random packets, don’t worry—you aren’t the only one! Trust me, I've experienced this scenario countless times. You change a rule, you drop something and you are still thinking to yourself, why is this not work? This is when you realize that
IPTables with
connection tracking can be amazing.
Why Is Connection Tracking So Valuable
The first time I enabled
connection tracking (conntrack) I was shocked. I actually thought to myself, why have I not used this before? Instead of treating each packet incoming as a new packet, the
firewall now understands the status of the connection.
How Connection Tracking Works (very simplified)
Manage typical
IPTables packets normally one packet at a time. However, with
connection tracking, the firewall now rises to manage the entire communication (the connection).
The Stateful firewalls generally check four types of states:
•
NEW - It is a new connection
•
ESTABLISHED - It is an already established connection
•
RELATED - It is related to another connection
•
INVALID – It is a bad or broken packet
After I became familiar with these states, it was significantly easier to manage traffic. Have you ever wondered why
SSH still works even with restrictive rules? It has to do with connection tracking.
Why IPTables + Conntrack is Better Control
1. You can allow or block traffic more intelligently
You control connections based on state rather than without context.
2. Your server gets less junk traffic.
This isn't a gag.
MYSQL recommends dropping
INVALID packets to improve speed, performance increases are noticeable.
3. You are more secure.
Conntrack is useful for:
- Blocking fake packets
- Better handling of DDoS attacks
- Blocking strange/suspicious connections
What's refreshing with
IPTables, is when your firewall actually does help instead of just monitoring!
Useful IPTables rules
Here are simple, yet effective rules for almost every server I use, from IPTables:
- iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
- iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
- iptables -A INPUT -m conntrack --ctstate NEW -p tcp --dport 22 -j ACCEPT
These rules are simple and easy to understand!
Traffic Control Hacks
Always allow ESTABLISHED traffic
It allows your server to function without complications.
Drop INVALID traffic
In most cases it is just unneeded or harmful.
Log before you drop packets
Logs will help you understand the problems when they occur.
Simplify your rules with a few words
Trust me, your future self will thank you for this one.