Basic firewall using iptables

A firewall is a network service which is used to filter network traffic for unwanted traffic, block it, and allow the desired traffic to pass. The most powerful tool on Linux is iptables, which has kernel integration in recent versions of the kernels.

How to do it...

iptables is present, by default, on all modern Linux distributions. We will see how to configure iptables for common scenarios.

  1. Block traffic to a specific IP address:
    #iptables -A OUTPUT -d 8.8.8.8 -j DROP
    

    If you run PING 8.8.8.8 in another terminal before running the iptables command, you will see this:

    PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
    64 bytes from 8.8.8.8: icmp_req=1 ttl=56 time=221 ms
    64 bytes from 8.8.8.8: icmp_req=2 ttl=56 time=221 ms ...

Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.