Iptables Lecture

Module 0: The Lab Environment & Preparation

To practice the concepts in this lecture effectively, we will build a specific Virtual Lab. All examples in this course are adapted to fit this exact topology.

0.1 VirtualBox Lab Setup

Lab Topology Diagram

☁️ WAN (Internet) (Bridged Adapter)
"Router" VM Xubuntu 24.04
WAN IF: enp0s3 (DHCP)
LAN IF: enp0s8 (10.0.2.1/24)
"Client" VM Any OS
LAN IF: eth0 (10.0.2.100/24)
Gateway: 10.0.2.1
Both Router (LAN) and Client are connected to the "CyberLab" NAT Network (Subnet: 10.0.2.0/24).

0.2 Critical Preparation: Disabling UFW

Xubuntu comes with UFW (Uncomplicated Firewall) enabled by default. UFW is a frontend that manipulates iptables. To learn iptables directly, we must disable UFW so it doesn't interfere with our manual rules.

0.3 Managing Rules via Scripts

Typing commands one by one into the terminal is risky; if you make a mistake (like dropping SSH), you might lock yourself out. The professional way to manage rules is using Bash Scripts.

How to create an iptables script:

  1. Create a file: touch firewall_rules.sh
  2. Make it executable: chmod +x firewall_rules.sh
  3. Edit it: nano firewall_rules.sh
  4. Run it: sudo ./firewall_rules.sh

0.4 Enabling and Testing Routing (IP Forwarding)

By default, a Linux system drops any packet that is not destined for itself. To act as a "Router," we must tell the kernel to forward packets from one interface to another.

Step 1: Enable Routing (The "Router" VM)

You can do this temporarily (lost on reboot) or permanently.

Temporary Method:
# Write '1' to the forwarding control file
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward
Permanent Method (Recommended):
  1. Edit the sysctl config: sudo nano /etc/sysctl.conf
  2. Find the line #net.ipv4.ip_forward=1
  3. Uncomment it (remove the # so it looks like net.ipv4.ip_forward=1)
  4. Save and exit (Ctrl+O, Enter, Ctrl+X).
  5. Apply changes: sudo sysctl -p

Step 2: Verify Routing is Enabled

Run the following command on the Router VM:

cat /proc/sys/net/ipv4/ip_forward
  • Output 0: Routing is OFF (Client cannot reach internet).
  • Output 1: Routing is ON (Packets will be passed between interfaces).

Step 3: Test Connectivity from the "Client" VM

Once routing is enabled on the Router (and MASQUERADE rules from Module 7 are applied), go to your Client VM and test:

  1. Ping the Gateway (Router LAN IP): ping 10.0.2.1 (Proves LAN is working).
  2. Ping an Internet IP: ping 8.8.8.8 (Proves Routing + NAT are working).
  3. Ping a Domain Name: ping google.com (Proves DNS is working).