Filtering packets is a fundamental aspect of firewall configuration. It involves selectively allowing or denying network traffic based on specific criteria such as source and destination addresses, ports, and protocols. Here’s how you can filter packets using iptables:
Basic iptables Rules for Packet Filtering:
- Allowing Specific Incoming Traffic:
- To allow incoming traffic on a specific port (e.g., port 80 for HTTP):
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
- This rule allows TCP traffic on port 80.
- Blocking Specific Incoming Traffic:
- To block incoming traffic from a specific IP address (e.g., 192.168.1.100):
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
- This rule drops any incoming packets from the specified source IP.
- Allowing Outgoing Traffic:
- To allow outgoing traffic on a specific port (e.g., port 443 for HTTPS):
sudo iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
- This rule allows TCP traffic on port 443 for outgoing connections.
- Blocking Outgoing Traffic:
- To block outgoing traffic to a specific IP address (e.g., 192.168.2.200):
sudo iptables -A OUTPUT -d 192.168.2.200 -j DROP
- This rule drops any outgoing packets destined for the specified IP address.
Stateful Packet Filtering:
Stateful packet filtering allows the firewall to keep track of the state of active connections. It’s particularly useful for protocols like TCP, where there’s an established connection.
- Allow established connections:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
This rule allows incoming packets that are part of established connections or related to those connections.
Default Policies:
Set the default policies for each chain:
sudo iptables -P INPUT DROP sudo iptables -P OUTPUT DROP sudo iptables -P FORWARD DROP
These commands set the default policy for incoming, outgoing, and forwarded traffic to DROP, meaning any packets that don’t match specific rules will be discarded.
Testing:
After applying rules, it’s crucial to thoroughly test the firewall to ensure it’s functioning as intended. Verify that allowed traffic is passing through and blocked traffic is being denied.
Saving Rules:
To make the rules persistent after a reboot, save them:
sudo iptables-save > /etc/iptables/rules.v4
Monitoring and Adjusting:
Regularly monitor your firewall logs and adjust rules as necessary to address any new requirements or potential security threats.
Remember, careful planning and testing are essential to ensure that your packet filtering rules align with your security objectives.