Lessons

Firewall with ufw and iptables

Level: Intermediate Module: TCP/IP & Networking 6 min read Lesson 19 of 66

Overview

  • What you’ll learn: Firewall concepts, the Linux netfilter framework, how iptables chains and rules work, using ufw as a simplified front-end, common firewall policies for servers, logging, and rate limiting.
  • Prerequisites: Lesson 18 – DHCP Server with isc-kea
  • Estimated reading time: 22 minutes

Introduction

A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined rules. On Linux servers, the firewall is your first line of defense against unauthorized access, port scanning, and network-based attacks.

Linux implements firewalling through the netfilter framework in the kernel. The traditional user-space tool for configuring netfilter is iptables, which provides fine-grained control over packet filtering, NAT, and traffic mangling. Ubuntu provides ufw (Uncomplicated Firewall) as a simplified front-end that makes common firewall tasks accessible without memorizing complex iptables syntax.

In this lesson, you will learn both tools: ufw for everyday firewall management and iptables for advanced scenarios requiring granular control.

UFW — Uncomplicated Firewall

UFW is the default firewall management tool on Ubuntu. It provides a simple command-line interface for managing firewall rules. Behind the scenes, ufw translates your commands into iptables rules.

# Check ufw status
$ sudo ufw status verbose
Status: inactive

# Enable the firewall (CAUTION: ensure SSH is allowed first!)
$ sudo ufw allow ssh
Rules updated

$ sudo ufw enable
Firewall is active and enabled on system startup

# Check status with numbered rules
$ sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 1] 22/tcp (v6)                ALLOW IN    Anywhere (v6)

# Allow common services
$ sudo ufw allow http          # Port 80
$ sudo ufw allow https         # Port 443
$ sudo ufw allow 53            # DNS (TCP and UDP)
$ sudo ufw allow 53/tcp        # DNS TCP only
$ sudo ufw allow 53/udp        # DNS UDP only

# Allow from a specific IP or subnet
$ sudo ufw allow from 192.168.1.0/24 to any port 22
$ sudo ufw allow from 10.0.0.5 to any port 3306

# Deny a specific port
$ sudo ufw deny 23             # Block telnet

# Delete a rule by number
$ sudo ufw delete 3

# Set default policies
$ sudo ufw default deny incoming
$ sudo ufw default allow outgoing

# View the full ufw status
$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)

     To                         Action      From
     --                         ------      ----
22/tcp                         ALLOW IN    Anywhere
80/tcp                         ALLOW IN    Anywhere
443/tcp                        ALLOW IN    Anywhere

IPtables Fundamentals

For advanced firewall configurations, you need to understand iptables directly. Iptables organizes rules into tables and chains. The three most important tables are: filter (default — for packet filtering), nat (for address translation), and mangle (for packet modification).

The filter table has three built-in chains: INPUT (packets destined for the local machine), OUTPUT (packets originating from the local machine), and FORWARD (packets being routed through the machine).

# View current iptables rules
$ sudo iptables -L -n -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source        destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source        destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source        destination

# Allow established and related connections
$ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow loopback traffic
$ sudo iptables -A INPUT -i lo -j ACCEPT

# Allow SSH from anywhere
$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP and HTTPS
$ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
$ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow ICMP (ping)
$ sudo iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

# Drop everything else (set default policy)
$ sudo iptables -P INPUT DROP
$ sudo iptables -P FORWARD DROP
$ sudo iptables -P OUTPUT ACCEPT

Advanced iptables Rules

Iptables supports powerful matching criteria including source/destination addresses, port ranges, connection states, rate limiting, and logging.

# Rate limit SSH connections (prevent brute force)
$ sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW 
    -m recent --set --name SSH
$ sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW 
    -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP

# Allow a specific subnet to access MySQL
$ sudo iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 3306 -j ACCEPT

# Log dropped packets (useful for debugging)
$ sudo iptables -A INPUT -j LOG --log-prefix "IPT-DROP: " --log-level 4
$ sudo iptables -A INPUT -j DROP

# View logged packets
$ sudo journalctl -k | grep "IPT-DROP"

# NAT — Masquerade outgoing traffic (for router setups)
$ sudo iptables -t nat -A POSTROUTING -o ens34 -j MASQUERADE

# Port forwarding — Forward port 8080 to internal server
$ sudo iptables -t nat -A PREROUTING -i ens33 -p tcp --dport 8080 
    -j DNAT --to-destination 192.168.1.20:80
$ sudo iptables -A FORWARD -p tcp -d 192.168.1.20 --dport 80 -j ACCEPT

Persisting Firewall Rules

By default, iptables rules are lost on reboot. You need to save and restore them explicitly. The iptables-persistent package automates this process.

# Install iptables-persistent
$ sudo apt install -y iptables-persistent

# Save current rules
$ sudo netfilter-persistent save
run-parts: executing /usr/share/netfilter-persistent/plugins.d/15-ip4tables save
run-parts: executing /usr/share/netfilter-persistent/plugins.d/25-ip6tables save

# Rules are saved to:
# /etc/iptables/rules.v4 (IPv4)
# /etc/iptables/rules.v6 (IPv6)

# Manually save/restore
$ sudo iptables-save > /etc/iptables/rules.v4
$ sudo iptables-restore < /etc/iptables/rules.v4

# With ufw, rules are automatically persistent
# (ufw stores rules in /etc/ufw/ and loads them at boot)

Key Takeaways

  • UFW is Ubuntu’s simplified firewall front-end; always allow SSH before enabling to avoid locking yourself out.
  • The default policy should be “deny incoming, allow outgoing” — then explicitly allow only the services you need.
  • Iptables provides granular control through tables (filter, nat, mangle) and chains (INPUT, OUTPUT, FORWARD) for advanced scenarios.
  • Rate limiting with iptables protects against brute-force attacks; logging helps diagnose firewall issues.
  • Use iptables-persistent to save rules across reboots, or rely on ufw which persists rules automatically.

What’s Next

In Lesson 20, you will learn Network Troubleshooting Tools — a comprehensive toolkit including ping, traceroute, mtr, ss, netstat, tcpdump, nmap, and Wireshark for diagnosing and resolving network issues.

繁體中文

概述

  • 學習目標:防火牆概念、Linux netfilter 框架、iptables 鏈和規則的運作方式、使用 ufw 作為簡化前端、伺服器常見的防火牆策略、日誌記錄和速率限制。
  • 先決條件:第 18 課 – 使用 isc-kea 的 DHCP 伺服器
  • 預計閱讀時間:22 分鐘

簡介

防火牆是一種網路安全系統,根據預定規則監控和控制進出網路的流量。在 Linux 伺服器上,防火牆是防禦未授權存取、連接埠掃描和基於網路攻擊的第一道防線。

Linux 透過核心中的 netfilter 框架實現防火牆功能。設定 netfilter 的傳統使用者空間工具是 iptables,它提供對封包過濾、NAT 和流量修改的精細控制。Ubuntu 提供 ufw(簡單防火牆)作為簡化前端,使常見的防火牆任務變得容易,無需記住複雜的 iptables 語法。

在本課程中,您將學習兩種工具:用於日常防火牆管理的 ufw 和用於需要精細控制的進階場景的 iptables。

UFW — 簡單防火牆

UFW 是 Ubuntu 上的預設防火牆管理工具。它提供簡單的命令列介面來管理防火牆規則。在幕後,ufw 將您的命令轉換為 iptables 規則。

IPtables 基礎

對於進階防火牆設定,您需要直接了解 iptables。Iptables 將規則組織到中。最重要的三個表是:filter(預設——用於封包過濾)、nat(用於位址轉換)和 mangle(用於封包修改)。

進階 iptables 規則

Iptables 支援強大的匹配條件,包括來源/目的地位址、連接埠範圍、連線狀態、速率限制和日誌記錄。

持久化防火牆規則

預設情況下,iptables 規則在重新開機後會遺失。您需要明確地儲存和還原它們。iptables-persistent 套件可自動化此過程。

重要觀念

  • UFW 是 Ubuntu 的簡化防火牆前端;啟用前務必先允許 SSH,以避免將自己鎖在外面。
  • 預設策略應為「拒絕傳入、允許傳出」——然後明確只允許您需要的服務。
  • Iptables 透過表(filter、nat、mangle)和鏈(INPUT、OUTPUT、FORWARD)為進階場景提供精細控制。
  • 使用 iptables 的速率限制可防禦暴力攻擊;日誌記錄有助於診斷防火牆問題。
  • 使用 iptables-persistent 在重新開機後保存規則,或依賴自動持久化規則的 ufw。

下一步

在第 20 課中,您將學習網路排除問題工具——包括 ping、traceroute、mtr、ss、netstat、tcpdump、nmap 和 Wireshark 的全面工具集,用於診斷和解決網路問題。

日本語

概要

  • 学習内容:ファイアウォールの概念、Linux netfilterフレームワーク、iptablesのチェーンとルールの仕組み、簡素化フロントエンドとしてのufwの使用、サーバーの一般的なファイアウォールポリシー、ロギング、レート制限。
  • 前提条件:レッスン18 – isc-keaによるDHCPサーバー
  • 推定読了時間:22分

はじめに

ファイアウォールは、事前に定められたルールに基づいて着信および発信ネットワークトラフィックを監視・制御するネットワークセキュリティシステムです。Linuxサーバーでは、ファイアウォールは不正アクセス、ポートスキャン、ネットワークベースの攻撃に対する最初の防御ラインです。

Linuxはカーネル内のnetfilterフレームワークを通じてファイアウォールを実装しています。netfilterを設定する従来のユーザー空間ツールはiptablesで、パケットフィルタリング、NAT、トラフィック操作のきめ細かい制御を提供します。Ubuntuはufw(Uncomplicated Firewall)を簡素化フロントエンドとして提供し、複雑なiptables構文を暗記することなく一般的なファイアウォールタスクにアクセスできるようにしています。

このレッスンでは、日常のファイアウォール管理用のufwと、きめ細かい制御が必要な高度なシナリオ用のiptablesの両方のツールを学びます。

UFW — Uncomplicated Firewall

UFWはUbuntuのデフォルトのファイアウォール管理ツールです。ファイアウォールルールを管理するためのシンプルなコマンドラインインターフェースを提供します。裏側では、ufwはコマンドをiptablesルールに変換します。

IPtablesの基礎

高度なファイアウォール設定には、iptablesを直接理解する必要があります。Iptablesはルールをテーブルチェーンに整理します。最も重要な3つのテーブルは:filter(デフォルト——パケットフィルタリング用)、nat(アドレス変換用)、mangle(パケット変更用)です。

高度なiptablesルール

Iptablesは、送信元/宛先アドレス、ポート範囲、接続状態、レート制限、ロギングを含む強力なマッチング基準をサポートしています。

ファイアウォールルールの永続化

デフォルトでは、iptablesルールは再起動時に失われます。明示的に保存・復元する必要があります。iptables-persistentパッケージがこのプロセスを自動化します。

重要ポイント

  • UFWはUbuntuの簡素化ファイアウォールフロントエンドです。ロックアウトを防ぐため、有効にする前に必ずSSHを許可してください。
  • デフォルトポリシーは「着信を拒否、発信を許可」にし、必要なサービスのみを明示的に許可します。
  • Iptablesはテーブル(filter、nat、mangle)とチェーン(INPUT、OUTPUT、FORWARD)を通じて高度なシナリオにきめ細かい制御を提供します。
  • iptablesによるレート制限はブルートフォース攻撃から保護し、ロギングはファイアウォールの問題の診断に役立ちます。
  • 再起動をまたいでルールを保存するにはiptables-persistentを使用するか、ルールを自動的に永続化するufwに依存してください。

次のステップ

レッスン20では、ネットワークトラブルシューティングツールを学びます——ping、traceroute、mtr、ss、netstat、tcpdump、nmap、Wiresharkを含むネットワーク問題の診断と解決のための包括的なツールキットです。

You Missed