While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

FIREWALLS (IPTABLES, NFTABLES, PFSENSE) FOR EDUCATORS: A COMPLETE GUIDE TO TEACHING PERIMETER SECURITY STEP BY STEP

First edition. July 13, 2025.

Copyright © 2025 Diego S.

Written by Diego S.

10 9 8 7 6 5 4 3 2 1

Index

Part I: Fundamentals of Perimeter Security

1. Introduction to Perimeter Security

2. The Role of Firewalls in Network Defense

3. Network Models and Segmentation

4. Types of Firewalls: Filtering, Proxy, Stateful

5. Stateful vs Stateless Concepts

6. Architecture of a Secure Network

7. Best Practices for Cybersecurity Teaching

Part II: Teaching iptables from Scratch

8. Introduction to iptables

9. Installation and First Commands

10. Structure of Tables and Chains

11. Basic Accepting and Blocking Rules

12. Default Policies and Packet Flow

13. Creating a Customized Firewall

14. NAT and Port Forwarding with iptables

15. Saving, Loading, and Automating Rules

16. iptables Scripts for Classes

17. Practical Exercises: Basic Firewall

18. Attack Simulation and Blocking

19. Assessable Practices with iptables

20. Virtual Lab with iptables and VMs

Part III: Teaching nftables (the evolution of iptables)

21. Introduction to nftables

22. Comparison: iptables vs nftables

23. Syntax and Concepts of nftables

24. Configuration of Tables, Chains, and Rules

25. Practical Use Cases

26. Security Policies with nftables

27. Integration with Scripts and systemd

28. Practical Project: Complete Firewall with nftables

29. Teaching Debugging and Logging with nftables

30. Common Mistakes When Teaching nftables

31. Development of Guides and Rubrics for nftables

Part IV: Teaching with pfSense (Web Interface-Based Firewall)

32. Introduction to pfSense and its Ecosystem

33. Step-by-Step Installation in VirtualBox

34. First Access: pfSense GUI

35. Basic Configuration of Interfaces and WAN/LAN

36. Creating Firewall Rules

37. NAT, Port Forwarding, and Redirections

38. Configuration of VLANs and Segmentation

39. Users, Permissions, and Web Management

40. Content Filtering and QoS

41. VPNs with pfSense (OpenVPN/IPsec)

42. High Availability (CARP) and Backup

43. Distributed Firewall with pfSense

44. Educational Labs with pfSense

45. How to Teach pfSense in a Virtual Classroom

Part V: Didactics and Methodology for Teachers

46. Design of Academic Programs in Perimeter Security

47. How to Assess Learning in Firewalls

48. Creating Exams and Network Tests

49. Final Projects: Ideas and Templates

50. Gamification in Firewall Teaching

51. Integration with Simulators and Online Platforms (such as GNS3, EVE-NG, NetLab)

52. Open Resources for Teachers

53. How to Update Technical Content

54. Ethics and Legality in Teaching Security

Part VI: Complementary Materials and Resources

55. Bibliography and Academic Resources

56. List of Essential Commands by Technology

57. Quick Guides for Students

58. Recommended Software and Virtual Environments

59. Templates for Practices and Exams

60. Access to the Course GitHub Repository

61. Related Certifications (CompTIA, CEH, Cisco, etc.)

62. Tips for Teaching at a Distance

Firewalls (iptables, nftables, pfSense) for Educators: A Complete Guide to Teaching Perimeter Security Step by Step

Description

In a world where digital threats multiply every day, training future cybersecurity defenders becomes a fundamental mission. This work is more than just a manual: it is a complete and deeply practical journey into the heart of perimeter security, specially designed for technical educators and students.

From essential theory to real labs, this book guides the reader through the fundamentals, advanced configurations, and teaching strategies needed to excellently teach the use of modern firewalls, including iptables, nftables, and pfSense.

This guide not only explains what to do, but also how to teach it step by step, making it easier to create content, practices, exams, and final projects for your students.

It includes 62 thematic chapters, with exercises, simulations, best practices, common mistakes, and evaluation rubrics. Ideal for IT teachers, academy instructors, technical trainers, and those in charge of educational cybersecurity programs.

Get ready to transform your approach to teaching perimeter security.

Chapter 1: Introduction to Perimeter Security

Chapter Objectives

• Understand the concept of perimeter security and its role in network defense.

• Learn about the common threats that target the perimeter of a network.

• Identify the main perimeter protection elements.

• Prepare the educator to explain the concept with analogies, labs, and exercises.

1. What is Perimeter Security?

Perimeter security is the first line of defense in a network infrastructure. Its main objective is to protect the boundary between a trusted internal network (e.g., a corporate or educational network) and untrusted external networks (such as the Internet).

In the past, the perimeter was simple: a firewall between the LAN and the Internet connection. Today, the concept of perimeter is more blurred due to the growth of remote work, hybrid clouds, IoT, and distributed networks. However, it remains essential as part of a defense-in-depth strategy.

2. Educational Analogy for Introduction

Medieval Castle Analogy

Imagine a castle: the wall surrounding it represents the perimeter. Inside the wall are the citizens (users, servers). Outside, there can be allies... or enemies. The gate is the firewall. Only certain people (authorized traffic) can enter.

When explaining this to students, you can reinforce the concept of:

• Anticipatory defense

• Filtering at entry/exit

• Zones of trust (inside) and distrust (outside)

3. Why is It Important?

90% of cyberattacks begin with a perimeter scan. From there, attackers look for exposed vulnerabilities (open ports, misconfigured services) to gain initial access.

Implementing perimeter measures restricts the attack surface, reduces exposure, and provides visibility over the traffic.

4. Key Components of Perimeter Security

Component | Main Function
Firewall | Filters network traffic based on defined rules (iptables, nftables, pfSense, etc.)
IDS/IPS | Intrusion detection and prevention (Snort, Suricata)
Web Proxy | Controls and logs outgoing web traffic
VPN | Secure remote access to the internal network
DMZ (Demilitarized Zone) | Isolates public services from the rest of the network (web servers, mail, etc.)
NAT | Hides internal IP addresses
ACLs (Access Control Lists) | Rules in switches, routers, and firewalls

5. Common Perimeter Threats

Threat | Brief Description
Port Scanning | Discovery of open services
Spoofing | IP address impersonation
DoS/DDoS | Denial of service attacks
Intrusions | Unauthorized access to exposed services
Remote Exploit | Use of known vulnerabilities (such as CVEs) in perimeter services
Data Leaks | Data exfiltration via unmonitored channels

6. Designing a Network with Perimeter Security

Educators can use simple diagrams like the following to illustrate the basic structure of a protected network:

Internet 

| 

[FIREWALL/Router] 

| 

+————+—————-+ 

|  |  | 

DMZ  LAN  VPN Users 

(Web  (Internal  (Remote) 

Srv)  Users) 

7. Practical Approach for Classes

Activity 1: Draw a Perimeter

Objective: Have students represent the perimeter of an educational network.

Materials: Paper, marker, or diagramming software (such as draw.io or Lucidchart).

Instructions:

• Draw a school network with at least 3 zones: WAN, LAN, DMZ.

• Indicate which services would be in each zone.

• Mark the points where firewall rules would apply.

Activity 2: Scan Simulation

Objective: Show how an exposed system is detected without a firewall.

Tools: Kali Linux or nmap, an unprotected VM.

Instructions:

• Create a vulnerable virtual machine (e.g., with services like SSH and HTTP open).

• From another VM, run nmap <IP> and observe results.

• Repeat the scan after applying basic rules with iptables to block ports.

Activity 3: Create a Perimeter Policy

Objective: Teach how to define rules by roles and services.

Instructions:

• Define what traffic is allowed: users accessing the Internet, remote VPN, servers accessible from the outside.

• Create a table with the decisions:

Source | Destination | Service | Action
LAN | Internet | HTTP/HTTPS | ALLOW
WAN | DMZ Server | HTTP | ALLOW
WAN | LAN | Any | DENY

8. Tools for Teaching Perimeter Security

• VirtualBox / VMware Workstation: To simulate networks with multiple VMs.

• pfSense: Easy to use and powerful; ideal for beginners.

• iptables / nftables: To deepen knowledge in Linux-based networks.

• GNS3 / EVE-NG: For more advanced simulations with real routers/firewalls.

• Kali Linux / ParrotOS: To run scans, simulated attacks, and demonstrate vulnerabilities.

9. Tips for Educators

• Use visual analogies to teach abstract concepts.

• Create progressive network scenarios: first without a firewall, then with basic rules.

• Repeat concepts with different technologies (pfSense, iptables, nftables).

• Stimulate critical thinking: What would happen if this rule didn’t exist?

Perimeter security is the starting point for any network defense strategy. Teaching this topic properly requires not just conveying theory but also showing and doing: simulating threats, applying rules, visualizing traffic, and thinking like an attacker.

With this foundation, students will be ready to dive deeper into specific tools like iptables, nftables, and pfSense, addressed in the following chapters with a fully practical approach.

Chapter 2: The Role of the Firewall in Network Defense

Chapter Objectives

• Understand what a firewall is and its fundamental role in network security.

• Identify the different types of firewalls (hardware, software, personal, enterprise).

• Analyze its role in defense in depth.

• Apply practical examples of traffic filtering and implementation.

• Teach students to reason what to allow and what to block in a network.

1. What is a Firewall?

A firewall is a system that inspects, allows, or blocks network traffic between different segments, based on a series of rules defined by the administrator.

Its main purpose is to:

• Restrict unauthorized traffic

• Protect internal resources

• Prevent intrusions

• Log suspicious events

Think of the firewall as a nightclub bouncer: it only lets in those who are on the list and meet certain criteria.

2. Where is a Firewall Located?

Typically, the firewall is located at the perimeter of the network, between the internal network (LAN) and the external network (Internet), although it can also be used to segment internal networks or protect specific applications.

Common locations:

• Between the internal network and the ISP (gateway mode)

• On each server (local firewall)

• Within containers or VMs (micro-segmentation)

• On manageable routers or switches (ACLs)

3. Types of Firewalls

According to their location or implementation:

Type | Description
Network Firewall (hardware) | Physical device at the edge of the network (Cisco ASA, FortiGate)
Host Firewall (software) | Application that protects a specific machine (iptables, Windows Firewall)
Cloud-based Firewall | Cloud service to filter traffic (AWS Security Groups, Azure NSG)

According to their operation:

Type | Features
Stateless Filtering | Analyzes each packet individually, without context
Stateful Filtering | Analyzes the full connection, maintains state
Web Application Firewall (WAF) | Inspects HTTP/HTTPS traffic at the application level
Next-Generation Firewall (NGFW) | Includes DPI, IDS/IPS, user-based filtering, geolocation, etc.

4. Key Functions of a Firewall

Traffic Filtering: By IP, port, protocol, application.

Packet Inspection: Verifies headers, flags, sessions.

Logging and Monitoring: Access logs, alerts, and traffic analysis.

NAT/PAT: Address translation to hide internal networks.

VPN: Many perimeter solutions offer encrypted tunnels.

DoS Protection: Limits connections per IP, detects anomalies.

5. The Role of the Firewall in Defense in Depth

A firewall is not enough on its own, but it is a key piece in a layered security strategy, as shown in the diagram below:

[User] -> [Perimeter Firewall] -> [IPS/IDS] -> [WAF] -> [Antivirus/EDR] -> [Data]

Each layer serves a distinct role. The firewall is the first barrier and acts before an attacker can interact with internal services.

6. Practical Example: Rule Policy

Let’s consider an educational network. What basic rules should a firewall have?

Source | Destination | Service | Action | Justification
LAN | Internet | HTTP/HTTPS | ALLOW | Web browsing
WAN | DMZ Server | HTTP | ALLOW | Institutional website
WAN | LAN | Any | DENY | Prevent external access
LAN | DMZ Server | SSH | ALLOW | Secure remote administration
Any | Firewall | ICMP | DENY | Avoid reconnaissance (ping)

7. Practical Classroom Activities

Activity 1: Create Logical Rules on Paper

Objective: Practice designing firewall policies before applying them.

• Provide students with a scenario (e.g., company, school, lab).

• Give an empty rules table and a set of requirements.

• Students should design the appropriate rules.

Activity 2: Firewall Simulation with iptables

Objective: Implement real rules in a Linux environment.

Steps:

Create two VMs in VirtualBox: one attacker (Kali) and one victim (Debian).

On the victim machine, execute:

sudo iptables -P INPUT DROP 

sudo iptables -A INPUT -p tcp—dport 22 -j ACCEPT 

sudo iptables -A INPUT -p icmp -j ACCEPT 

Test from Kali if it can ping or SSH into the victim machine.

Compare the behavior with and without the rules.

Activity 3: Analyze Firewall Logs

Objective: Interpret logs generated by blocked events.

• Configure iptables with log:

sudo iptables -A INPUT -j LOG—log-prefix "FIREWALL DROP: " 

• Observe logs with:

bash

sudo tail -f /var/log/kern.log 

• Run a scan with nmap and review the generated logs.

8. What is NOT a Firewall?

It is important that students understand the limits of the firewall:

It is NOT... | Because...
An antivirus | It doesn’t detect malware within valid packets
A solution for phishing | It doesn’t inspect email content
An automated response tool | It doesn’t make behavior-based decisions without an IDS/IPS
A guarantee of security | It is only one of many layers needed

9. Best Configuration Practices

• Principle of Least Privilege: Only allow necessary traffic.

• Default Deny: DROP as the default policy.

• Use of Logs: Monitor activity and review regularly.

• Periodic Audits: Review obsolete or unnecessary rules.

• Security by Zones: Separate segments and apply different rules (LAN, DMZ, WiFi, VPN).

• Configuration Backups: Especially for complex firewalls or pfSense.

The firewall plays a critical and strategic role in network defense. It is the most accessible tool to start applying security policies and teaching traffic control. Properly teaching it allows students to think in terms of rules, flows, permissions, and blocks—fundamental skills for any cybersecurity professional.

This knowledge will lay the foundation for mastering tools such as iptables, nftables, and pfSense, which we will explore in-depth in subsequent chapters.

Chapter 3: Network Models and Segmentation

Chapter Objectives

• Understand network models from a security perspective.

• Recognize the importance of network segmentation in perimeter protection.

• Apply segmentation schemes: LAN, DMZ, VLANs, Wi-Fi networks, management networks.

• Design secure topologies using segmentation as a defensive strategy.

• Perform segmentation practices in real or simulated environments (pfSense, virtual switches, VLAN tagging).

1. What is a Network Model?

A network model describes how devices are organized and connected within an infrastructure. It can be physical (cables, switches, routers) or logical (VLANs, subnets, ACLs, firewalls).

From a security perspective, the network model allows you to define:

• Trusted zones.

• Allowed communication flows.

• Control and monitoring points.

2. What is Network Segmentation?

Segmentation is the process of dividing a network into multiple logical or physical subnets in order to:

• Reduce the scope of attacks.

• Contain threats (like ransomware).

• Limit lateral movement of an attacker.

• Control access between users, devices, and services.

Practical analogy:

Think of an office building: each floor is a department. Not all employees can enter all floors. There are doors (ACLs) and restricted access (internal firewalls).

Without segmentation, everyone works in one large open space without doors!

3. Common Types of Segmentation

Physical Segmentation

• Use of separate switches and routers.

• Less flexible but highly isolated.

• Example: server network on a dedicated switch with no access to the user network.

Logical Segmentation (VLANs)

• Virtual divisions on the same physical switch.

• Scalable, cost-effective, and manageable.

• Implemented via 802.1Q tagging.

• Ideal for classrooms, businesses, and mixed environments.

Function-based Segmentation

• By roles: users, administration, servers, IoT devices.

• By security level: high, medium, and low-trust zones.

4. Common Zones in a Segmented Network

Zone | Function | Examples
LAN | Internal users | PCs, laptops, printers
DMZ | Services exposed to the Internet | Web server, mail server, DNS
Administration Zone | Network and server management | Switch consoles, pfSense
Wi-Fi Zone | Wireless access | Guest users, BYOD
VPN | Secure remote access | Telecommuting staff
IoT/OT | Control or sensor devices | Cameras, PLCs, sensors

5. Segmentation Topologies (Proposed Diagrams)

Basic Segmented Topology:

[ Internet ]

|

[Firewall]

|

+—————+—————+

|  |  |

[DMZ]  [LAN]  [VPN Users]

|  |

Web/Mail  Students/Admins

Topology with VLANs:

[ Layer 3 Switch / Router ]

|  |  |

VLAN10  VLAN20  VLAN30

(Admin)  (Students)(Guest WiFi)

Each VLAN can have different firewall policies to control traffic.

6. Practical Exercise: Segmentation Design for a School

Scenario: An educational institution wants to segment its network for:

• Teachers

• Students

• Guests (Wi-Fi)

• Servers (virtual classroom, email, backup)

Proposed Solution:

VLAN | Name | Subnet | Purpose
10 | Teachers | 192.168.10.0/24 | Access to internal resources
20 | Students | 192.168.20.0/24 | Limited Internet access
30 | Guests | 192.168.30.0/24 | Web browsing only
40 | Servers | 192.168.40.0/24 | Restricted access, from admin

Configure firewall to:

• Deny access for students to VLAN10 and VLAN40.

• Allow teachers access to servers.

• Redirect guest traffic through a proxy or limit to Internet access.

7. Segmentation Lab with pfSense

Objective:

Create and configure network interfaces with VLANs in pfSense and apply basic firewall rules to segment traffic.

Requirements:

• pfSense installed (bare metal or in VirtualBox).

• At least 1 virtual network card configured in “bridged” or “host-only” mode.

• Virtual switch or system compatible with VLAN tagging.

Steps:

Create VLANs in pfSense

Go to Interfaces > Assignments > VLANs > Add.

Create VLAN 10, 20, 30 on the physical interface.

Assign VLAN Interfaces

Go to Interfaces > Assignments, add VLAN10, VLAN20, VLAN30.

Configure each with its respective subnet.

Firewall Rules per Interface

Go to Firewall > Rules.

For each interface, allow only the necessary traffic.
Example: In VLAN20, allow outgoing traffic on ports 80/443, block everything else.

Test Connectivity

Connect virtual machines to each VLAN.

Ensure they cannot reach each other except as permitted.

8. Use Cases: Real-Life Segmentation

Educational Scenario

• Each classroom in its own VLAN.

• Grade servers, Moodle, or backups isolated.

• Guests blocked from accessing institutional resources.

Hospital

• Medical network (monitoring equipment) isolated from guest Wi-Fi.

• Remote access to medical records only from the VPN.

Business

• Finance zone separated from the rest.

• Climate control IoT in isolated network.

• DMZ for web and external mail servers.

9. Best Practices in Segmentation

• Apply the minimum necessary connectivity between zones.

• Use descriptive labels and names for VLANs.

• Monitor traffic between segments with IDS/IPS.

• Review rules periodically.

• Never allow direct traffic from Wi-Fi to LAN.

• Implement authentication in critical zones (VPN, DMZ access).

Network segmentation is one of the most effective and accessible principles to enhance security in any network. It prevents a compromise from spreading, limits the scope of attacks, and allows for better administrative control.

Teaching segmented network models with real-life examples helps students think like security architects, not just users. This knowledge is reinforced in subsequent chapters by applying specific firewall rules for each segment.

Chapter 4: Types of Firewalls – Filtering, Proxy, and Stateful

Chapter Objectives

• Identify the main types of firewalls based on their operation and architecture.

• Understand how each type processes and filters traffic.

• Compare their advantages, limitations, and use cases.

• Apply practical examples using tools such as iptables, Squid, and pfSense.

• Prepare students to choose and implement the appropriate type of firewall for each network scenario.

1. Why Are There Different Types of Firewalls?

Not all environments require the same level of inspection or face the same risks. Different types of firewalls exist, distinguished by:

• The OSI layer they operate on.

• Their method of traffic inspection.

• Their ability to maintain connection states.

• Their performance and complexity.

These types are not mutually exclusive. Many environments combine several types.

2. Packet Filtering Firewall

Concept

This is the most basic and fastest type. It operates at OSI layers 3 and 4 (network and transport) by inspecting:

• Source and destination IP addresses

• Source and destination ports

• Protocol (TCP, UDP, ICMP, etc.)

Practical Example with iptables:

bash

# Block incoming traffic to port 23 (Telnet)

sudo iptables -A INPUT -p tcp—dport 23 -j DROP

Advantages:

• Very fast, low resource consumption.

• Useful as the first line of perimeter defense.

• Easy to configure on routers, switches, or Linux systems.

Limitations:

• Stateless unless combined with state tracking.

• Does not inspect the content of traffic.

• Cannot distinguish between a legitimate and malicious connection if the packet meets the rules.

Recommended Use:

• Basic firewalls on routers.

• Environments with minimal filtering needs.

• Traffic segmentation in internal networks.

3. Proxy Firewall (Application Layer Gateway)

Concept

Acts as an intermediary between the client and the server, operating at layer 7 (application). It evaluates and filters traffic based on content, headers, and application behavior.

Classic example: A proxy HTTP server that inspects and filters websites accessed by users.

Practical Example with Squid (Linux):

bash

sudo apt install squid

sudo nano /etc/squid/squid.conf

Add the following:

conf

acl blocked dstdomain .facebook.com .tiktok.com

http_access deny blocked

Restart:

bash

sudo systemctl restart squid

Advantages:

• High granularity: inspects by URLs, headers, domains.

• Hides the internal network.

• Can cache content (improves performance).

• Useful for parental control, corporate or educational policies.

Limitations:

• Adds latency.

• Requires more resources.

• Needs client configuration (or transparent proxy).

• Only filters protocols it understands (e.g., HTTP, FTP, DNS).

Recommended Use:

• Web browsing control in schools, businesses, or cybercafés.

• Environments that require monitoring of HTTP/HTTPS traffic.

• Detailed web access policies.

4. Stateful Firewall (Dynamic Filtering)

Concept

This type of firewall maintains information about the state of connections, allowing for more intelligent decision-making.

It operates at layers 3 and 4 but can tell whether a packet belongs to an existing, new, or invalid connection.

Example: It allows responses to a request initiated from inside but blocks responses to connections not initiated.

Practical Example with iptables (state tracking):

bash

# Allow established connections

sudo iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT

# Allow new SSH connections

sudo iptables -A INPUT -p tcp—dport 22 -m state—state NEW -j ACCEPT

Advantages:

• Greater security without excessive rules.

• Avoids false positives (allows legitimate responses).

• Scalable and efficient.

Limitations:

• Can be vulnerable to attacks if state information is blindly trusted.

• Additional memory consumption to maintain the connection table.

Recommended Use:

• Any environment with exposed services.

• Modern configurations (pfSense, firewalld, nftables).

• Traffic segmentation in networks with multiple roles.

5. Practical Comparison of Firewall Types

Feature | Packet Filtering | Proxy (Layer 7) | Stateful
OSI Layer | 3 / 4 | 7 | 3 / 4
Deep Inspection |  | Yes |
Aware of Connection State |  |  | Yes
Performance | 🔋🔋🔋🔋🔋 | 🔋🔋 | 🔋🔋🔋🔋
Ease of Configuration |  | 🟡 |
Content Filtering |  | Yes |
Recommended Use Cases | Simple perimeter | Web control | Any serious environment

6. Combining Firewalls in the Real World

In practice, modern environments combine several types of firewalls:

Example: School or University

• Perimeter firewall (stateful): pfSense blocking unauthorized access between segments.

• Packet filtering firewall: Layer 3 switches controlling VLANs.

• HTTP proxy: Squid blocking non-educational content.

• Local firewall: Windows Defender Firewall on each machine.

7. Practical Lab – Comparing Filtering, Proxy, and Stateful

Objective

Demonstrate how different types of firewalls behave with the same type of traffic.

Environment:

• 1 VM with pfSense (stateful)

• 1 VM with Squid (HTTP proxy)

• 1 Attacker VM (Kali Linux or Parrot)

• 1 Victim VM (Ubuntu with active services)

Activities:

Basic filtering: Block ICMP between Kali and Ubuntu from pfSense (stateful).

Proxy: Restrict access to YouTube from Ubuntu using Squid.

iptables (stateless): Block port 22 without state tracking.

Analyze differences in logs, behavior, and user experience.

8. Considerations for Teachers

• Ensure students understand the difference between layers 3, 4, and 7.

• Encourage critical analysis: When to use each type of firewall?

• Introduce monitoring tools: tcpdump, iftop, Wireshark.

• Propose real scenarios: Wi-Fi cafeteria, virtual classroom, server network.

9. General Best Practices

• Do not rely solely on packet filtering.

• Do not overload the proxy with too many rules.

• Use logs to audit behavior.

• Document rules and topology.

• Test all rules before deploying in production.

Each type of firewall provides a different layer of defense. Packet filtering firewalls offer simplicity, stateful firewalls balance security and efficiency, and proxy firewalls allow fine-grained application traffic control.

Knowing when and how to combine these approaches is what differentiates a technician from a true network security architect.

Chapter 5: Stateful vs Stateless Concepts

Chapter Objectives

• Understand the fundamental differences between stateful and stateless firewalls and mechanisms.

• Visualize how both types behave with different kinds of traffic.

• Implement practical configurations with real tools (iptables, nftables, pfSense).

• Develop criteria to choose the appropriate filtering type based on network context.

• Identify common errors and risks when misconfiguring stateful/stateless rules.

1. Introduction: Why is it Important to Understand This Concept?

Most network security devices (firewalls, IDS/IPS, routers) make decisions about allowing or blocking traffic based on two models:

Type | Brief Description
Stateless | Filters packets without remembering the connection state.
Stateful | Filters packets while remembering the context and state of the connection.

This concept is fundamental in security architecture because it affects:

• The system’s performance.

• The granularity of control.

• The ability to detect legitimate vs suspicious connections.

2. What is Stateless?

Definition

A stateless system makes decisions based solely on the information contained in each individual packet, such as:

• Source and destination IP address

• Source/destination port

• Protocol

• TCP flags (such as SYN, ACK)

It does not remember if the packet is part of a valid connection or not.

How It Works

Each packet is treated in isolation, as if nothing had happened before.

Practical Example: iptables Stateless

bash

# Block all packets to port 22

iptables -A INPUT -p tcp—dport 22 -j DROP

This blocks even legitimate responses unless a state tracking rule is used.

Advantages:

• Faster (no need to maintain connection tables).

• Lower resource usage (RAM and CPU).

• Simpler for network devices that just route.

Disadvantages:

• Does not distinguish between legitimate and malicious traffic.

• May cause blocking of useful traffic (false positives).

• Requires additional rules for return traffic.

3. What is Stateful?

Definition

A stateful system tracks the state of each network connection. This means that:

• It recognizes the start of a connection (e.g., TCP with SYN).

• It remembers active connections.

• It only allows response packets if the connection was initiated from a valid source.

What It Stores

• Active connection table.

• Connection state (NEW, ESTABLISHED, RELATED, INVALID).

• Protocol tracking information.

Practical Example: iptables Stateful

bash

# Allow established connections

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT

# Allow new SSH connections

iptables -A INPUT -p tcp—dport 22 -m state—state NEW -j ACCEPT

This allows incoming traffic only if it is new or an expected response.

Advantages:

• Greater security: only allows part of a valid connection.

• Fewer rules: responses to outgoing connections do not require a separate rule.

• Smarter against attacks like spoofing.

Disadvantages:

• Requires more resources (session tracking).

• May encounter issues if the state table fills up (DoS).

• The logic may be more complex to understand.

4. Comparative Visualization (Simulation)

TCP Traffic Simulation

TCP Phase | Stateless | Stateful
Client sends SYN | Allows or blocks based on rule | Registers as NEW connection
Server responds with SYN-ACK | Doesn’t know if it's a valid response | Recognizes as ESTABLISHED connection
Client sends final ACK | Treated as a new packet | Automatically allowed

5. Implementation in pfSense

Step-by-step in pfSense (stateful by default):

Access the pfSense web interface.

Go to Firewall > Rules > LAN.

Create a rule:
• Action: Pass
• Protocol: TCP
• Source: LAN net
• Destination: Any
• Description: “Allow outgoing traffic”
pfSense automatically creates state rules that allow incoming response traffic.

6. Practical Exercise in the Classroom

Scenario:

Set up two VMs (client and web server) with a firewall in between (pfSense or Linux). Implement stateless and stateful rules and measure the differences.

Activities:

• With stateless: Block incoming port 80.

• Try accessing a page from the client.

• Observe the logs (total block, even if it’s a legitimate response).

• Switch to stateful and allow outgoing HTTP connections.

• See how the server’s response is now allowed.

7. Use Cases and Application

Environment | Stateful | Stateless
Modern enterprise network | Ideal for advanced security | Only in simple network points
ISP backbone routing | Expensive scalability-wise | Ideal for speed
IoT embedded device |  | Very limited resources
Educational traffic filtering |  | Optional based on proxy

8. Related Attacks

In Stateless Environments:

• IP Spoofing: May accept malicious packets if the IP appears valid.

• TCP SYN Flood: May overwhelm the server without connection tracking.

In Stateful Environments:

• State table exhaustion: DoS attack that fills the firewall’s memory.

• Solution: Limit connections by IP and adjust the table size.

9. Best Practices

• Always use stateful firewalls in networks with dynamic traffic.

• Limit connections by source to prevent DoS.

• Monitor the state table.

• Document rules differentiating NEW, ESTABLISHED, and RELATED states.

• Do not trust untracked connections if there’s external access.

A deep understanding of stateful and stateless concepts is crucial for designing robust perimeter defense systems. While stateless offers simplicity and performance, stateful allows for intelligent and secure decisions.

Both approaches are valid, but their use should align with the technical context, device capabilities, and required security level.

Chapter 6: Architecture of a Secure Network

Chapter Objectives

• Understand the fundamental components of a secure network architecture.

• Apply principles of segmentation, defense in depth, and risk-based design.

• Design practical topologies including zones such as DMZ, LAN, VPN, servers, etc.

• Use real tools (pfSense, VLANs, firewalls) to implement this architecture.

• Analyze common design cases in educational institutions, SMEs, and hybrid environments.

1. What is a “Secure Network Architecture”?

A secure network architecture is a structured design that minimizes risks and controls the flow of information through:

• Separation of functions and zones.

• Granular traffic control.

• Use of firewalls, VLANs, proxies, IDS/IPS, VPNs.

• Physical and logical access planning.

• Redundancy and monitoring.

It’s not just about having firewalls, but how they are placed and how each part of the network communicates.

2. Fundamental Principles

Defense in Depth

Do not rely on a single security barrier. Each layer adds protection:

• Perimeter firewall

• Internal segmentation

• Access control

• Antivirus / EDR

• Monitoring / SIEM

Principle of Least Privilege

Each device, user, or network should only have access to what is strictly necessary.

Zones of Trust

Separate zones based on trust level:

• LAN (high trust)

• DMZ (intermediate trust)

• Internet (untrusted)

• IoT or visitors (no trust)

3. Key Components

Internal LAN

• Users, workstations, printers.

• Segmented by VLAN according to departments.

Internet

• Fully external and untrusted.

Perimeter Firewall

• Controls traffic between the Internet and the internal network.

• Typically stateful with NAT.

DMZ (Demilitarized Zone)

• Servers exposed to the outside (web, email, DNS).

• Separated from LAN to avoid lateral movement if compromised.

VPN

• Secure access from remote locations.

• Usually with strong authentication.

IDS/IPS

• Detects or blocks intrusions in real time.

VLANs and Layer 3 Switches

• Logical separation within the network.

• Enables micro-segmentation.

Internal Servers

• Databases, file servers, domain controllers.

• Should never be in the same zone as public servers.

4. Basic Secure Architecture Design

+—————————+

|  Internet  |

+————+————-+

|

[Perimeter Firewall]

|

+———————-+———————+

|  |

[DMZ: Web Servers]  [VPN Gateway]

|  |

+——-+——-+  +———-+————+

|  |  |  |

[Web Server] [Email Server] [Remote Users]  ...

|

[IPS/IDS sensor]  <- Traffic monitoring

|

(Layer 3 Switch)

|

+———-+————+

|  |  |

VLAN1  VLAN2  VLAN3  <- Segments by areas: Admin, IT, Students

5. Practical Case: School or University

Common Challenges:

• WiFi for students and visitors.

• Access to external educational platforms.

• Internal servers (email, Moodle).

• Cybersecurity in computer labs.

Practical Recommendations:

• Guest WiFi -> Isolated VLAN with no access to LAN.

• Student WiFi -> Restricted access to HTTP/HTTPS ports.

• Labs -> Segmented into VLANs, with a proxy (Squid) for browsing.

• DMZ -> Moodle, email, and other web services exposed with strict rules.

• VPN -> For teachers working remotely, with 2FA authentication.

6. Tools for Building Secure Architectures

Tool | Main Use
pfSense | Firewall, NAT, VPN, rule control
OpenVPN / WireGuard | Secure remote access
VLANs + Layer 3 switches | Internal segmentation
Suricata / Snort | Real-time IDS/IPS
Zabbix / Prometheus | Service monitoring
Grafana | Traffic and alert visualization

7. Practical Lab – Secure Network Simulation

Objective:

Design a secure network in a virtualized environment (VirtualBox, Proxmox, or VMware).

Suggested Components:

• 1 pfSense (firewall/router)

• 1 web server (Ubuntu)

• 1 internal server (file or database)

• 2 clients (admin and student)

• VLANs defined in the virtual switch

Activities:

• Configure DMZ for the web server.

• Create rules to restrict “student” access to the internal server.

• Configure and test OpenVPN in pfSense.

• Verify traffic with Wireshark or tcpdump.

8. Zones in a Secure Network (Color Model)

Zone | Trust Level | Allowed Traffic | Examples
Green | High | Access to everything with role control | Corporate or institutional LAN
Orange | Medium | Restricted access to and from LAN | DMZ (web, DNS, email)
Red | None | Only explicitly allowed traffic | Internet
Blue | Low | Total isolation or proxy only | IoT, guest WiFi, IP cameras

9. Best Practices for Secure Architecture

• “Never trust, always verify” (Zero Trust).

• Update and patch all network devices.

• Use strong authentication and segment users.

• Monitor logs, anomalies, and bandwidth consumption.

• Avoid exposing unnecessary internal services.

• Periodically test intrusion scenarios.

• Document topology, rules, and access policies.

A secure network architecture is not built only with products, but with principles. Designing the network with segmentation, trust zones, and granular traffic control drastically reduces attack surfaces.

Every educator or network professional must understand how to transform a set of devices into a solid and adaptable defense against modern threats.

Chapter 7: Best Teaching Practices in Cybersecurity

Chapter Objectives

• Provide principles and strategies for teaching cybersecurity in a structured and practical way.

• Foster ethics, responsibility, and critical thinking in students.

• Design effective classes with current resources, real exercises, and simulated labs.

• Prepare students for real-world scenarios, certifications, and professional work.

• Create secure learning environments without compromising real systems.

1. Introduction: Teaching Cybersecurity Goes Beyond Technical Knowledge

Cybersecurity is not just a technical discipline: it is also ethical, strategic, and social. A good educator should guide students in:

• How to think like defenders (and understand how attackers think).

• How to respect legal frameworks.

• How to apply good network and security practices.

• How to avoid “teaching hacking without purpose.”

2. Fundamental Principles for Effective Teaching

Problem-Based Learning
• Create simulated attack scenarios (DDoS, port exploitation, scans) that students must mitigate.
• Example: A misconfigured web server allows unauthorized access → students must identify and fix it.

Practical Approach First, Theory Later
• Start with a compelling practical demonstration (e.g., unauthorized remote access).
• Then explain the underlying concepts (firewalls, logs, vulnerabilities).

Learning by Doing
• Repeat processes such as firewall configuration, traffic analysis, and attack tracing in multiple sessions.
• Provide immediate feedback during labs.

Emphasis on Professional Ethics
• Include debates and exercises on ethical dilemmas.
• Present laws such as GDPR, LOPD, and the Cybercrime Law.
• Incorporate modules on digital responsibility and ethical hacking.

3. Specific Teaching Strategies

A. Design Measurable Competency-Based Objectives

• It’s not enough to say “knows how to use pfSense.”

• Real example:

“Configure a stateful firewall that blocks specific ports and allows legitimate traffic through optimized rules.”

B. Incident Simulation and Guided Resolution

• Case: Network lab undergoes port scanning and brute force attacks.

• Students must:

Analyze logs.

Generate firewall rules.

Write a technical report with recommendations.

C. Real-Time Traffic Monitoring and Analysis

• Tools: Wireshark, tcpdump, Suricata.

• Teach students how to “see” what’s happening on the network.

• Example: What protocol is being used? What IPs are appearing? Is there anything suspicious?

D. Gamification and CTF Challenges (Capture The Flag)

• Create challenges:

Gain access to a protected machine (isolated vulnerable machine).

Capture “flags” by finding configuration errors or vulnerabilities.
• Promotes logic, persistence, and technical application.

4. Classroom Design and Secure Testing Environment

Recommended Infrastructure

Resource | Description
VirtualBox / VMware / Proxmox | Virtual labs for each student or team.
pfSense | Perimeter firewall for practicing rules and DMZ.
Kali Linux | Attack simulator for controlled testing.
Ubuntu Server / Windows Server | Real systems that can be breached and protected.
Wireshark / tcpdump | For capturing real traffic on the virtual network.
Docker | To spin up containers with vulnerable services or specific configurations.

Recommendation: Use a separate virtual network

Never practice offensive activities on a real or internet-connected network.

5. Teaching Resources for Educators

Resource | Type | Use
TryHackMe | Online platform | Simulations with step-by-step guides.
Hack The Box (Academy) | Virtual lab | Intermediate/advanced level.
OWASP Juice Shop | Vulnerable app | Ideal for teaching web vulnerabilities.
MITRE ATT&CK | Framework | Classification of real attack techniques.
Blue Team Labs Online | Defense | Traffic analysis, threat detection.

6. Assessment: Beyond the Theoretical Exam

Recommended assessment methods:

• Practical rubrics: Check if the firewall works as expected.

• Incident reports: Students must write a post-mortem analysis.

• Traffic analysis: Provide logs and justify which rules were used.

• Group presentations: Defend their architecture or solution to the group.

7. Best Practices for Educators

• Create an environment where mistakes are learning opportunities, not punishments.

• Encourage collaborative work in incident resolution.

• Teach documentation: logs, manuals, diagrams.

• Emphasize legality: do not tolerate gray or dangerous practices.

• Stay up-to-date: participate in communities, forums, and courses.

8. Tips for Ethical and Responsible Teaching

Advice | Justification
Do not teach offensive techniques without defensive context | Avoid glorifying hacking without purpose.
Emphasize “ethical hacking” and certifications | Provides professional and legal direction.
Show real legal consequences | Reinforces the ethical framework.
Include examples of societal impact | Humanizes cybersecurity.

9. Example of an Effective Class

Topic: Firewall Rules and Suspicious Traffic

Duration: 90 minutes

Time | Activity
0-10 min | Demonstration: unfiltered SSH traffic → remote access.
10-30 min | Theoretical explanation about stateful/stateless firewalls.
30-70 min | Lab: Implement rules to filter and monitor traffic.
70-85 min | Group analysis of generated logs.
85-90 min | Wrap-up and questions.

Teaching cybersecurity requires a mix of technique, pedagogy, and ethics. It’s not enough to know how to configure a firewall; it’s essential to teach why, how, and with what responsibility.

A cybersecurity educator is a trainer of digital defenders. Their role is critical in preparing professionals capable of protecting data, people, and infrastructure in an increasingly connected and vulnerable world.

Chapter 8: Introduction to iptables

Chapter Objectives

• Understand what iptables is and its role in perimeter security on Linux.

• Learn about tables, chains, and operating policies.

• Apply basic and advanced rules for traffic filtering.

• Learn to inspect, save, and restore configurations.

• Prepare students to build functional firewalls from scratch.

1. What is iptables?

iptables is a command-line tool for configuring network firewall rules on Linux systems, based on the netfilter subsystem of the kernel.

It acts as the gatekeeper for network traffic, allowing or denying incoming, outgoing, and forwarded packets based on criteria such as IP, ports, protocol, interface, and more.

Although iptables has been replaced in many modern systems by nftables, it is still widely used and essential to understand the evolution of Linux firewalls.

2. Why Teach iptables?

• It is a core tool in many distributions (especially legacy systems).

• It reinforces logical thinking and understanding of packet filtering.

• It allows granular control without relying on graphical interfaces.

• It is compatible with headless servers (without a graphical environment).

• It integrates easily with scripts and automation.

3. iptables Architecture

iptables is based on three key concepts:

Tables
A table is a set of rules designed for a specific purpose:

Table | Main Purpose
filter | Packet filtering (default)
nat | Address translation (SNAT, DNAT)
mangle | Packet modification (QoS, TTL)
raw | Processing before connection tracking

Chains
Each table has chains that represent points where packets pass through:

Chain | Description
INPUT | Traffic destined for the local system
OUTPUT | Traffic generated by the system
FORWARD | Traffic passing through the system (routing)
PREROUTING | Applied before routing (used in nat, mangle)
POSTROUTING | Applied after routing

Rules
These are the conditions that determine what to do with a packet.
For example:

bash

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

This accepts incoming TCP connections to port 22 (SSH).

4. Installing and Checking iptables Status

Check if it’s installed:

bash

iptables—version

Install (on Debian/Ubuntu):

bash

sudo apt install iptables

Check current rules status:

bash

sudo iptables -L -n -v

5. Fundamental iptables Commands

Action | Base Command
List rules | iptables -L -v -n
Add rule | iptables -A [CHAIN] [CONDITIONS] -j [ACTION]
Delete rule | iptables -D [CHAIN] [NUMBER]
Insert rule | iptables -I [CHAIN] [POSITION] [RULE]
Default policy | iptables -P [CHAIN] [ACCEPT/DROP]
Save rules | iptables-save > /etc/iptables.rules
Restore rules | iptables-restore < /etc/iptables.rules

6. Practice 1: Configuring Basic Rules

Scenario:

A Linux server should only allow SSH (22), HTTP (80), and block everything else.

bash

# Set default policy: drop

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

# Allow loopback (localhost)

iptables -A INPUT -i lo -j ACCEPT

# Allow established connections

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

# Allow HTTP

iptables -A INPUT -p tcp—dport 80 -j ACCEPT

Check:

bash

iptables -L -n -v

7. Practice 2: IP-Specific Rules

Scenario:

Allow only host 192.168.1.100 to connect via SSH.

bash

iptables -A INPUT -p tcp -s 192.168.1.100—dport 22 -j ACCEPT

8. Practice 3: NAT with iptables

Scenario:

Turn your system into a gateway for an internal network.

bash

# Enable IP forwarding

echo 1 > /proc/sys/net/ipv4/ip_forward

# NAT rule (SNAT or MASQUERADE)

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

This turns the Linux machine into a router/NAT for clients connected to another interface (e.g., eth1).

9. Rule Persistence

iptables rules are lost after a restart unless saved.

Save rules (Debian):

bash

sudo iptables-save > /etc/iptables/rules.v4

Automatically restore (Debian):

Install:

bash

sudo apt install iptables-persistent

10. Tips and Best Practices

Tip | Reason
Start with DROP policy and open only what’s needed | Enforces the principle of least privilege
Allow ESTABLISHED, RELATED to maintain connections | Prevents errors in legitimate responses
Test rules in a separate terminal with sleep | Prevents accidental lockout
Document each rule with comments in scripts | Improves maintenance and readability
Use scripts to apply standard configurations | Automation in educational environments

11. Complementary Tools

Tool | Purpose
iptables-save / iptables-restore | Export/import rules
watch iptables -L -v | Real-time monitoring
log with—log-prefix | Debugging rejected traffic
fail2ban | Automatic blocking for access attempts

12. Practical End-of-Chapter Project

Objective: Design and apply a full firewall using iptables to protect a web server.

Requirements:

• Allow HTTP, HTTPS, SSH from specific IPs.

• Deny everything else.

• Implement NAT for internet access.

• Apply persistence.

• Document each rule.

iptables is a powerful, flexible, and widely compatible tool for Linux systems, ideal for introducing students to the concepts of perimeter firewalls, traffic control, and policy-based security.

Although technologies like nftables offer improvements, mastering iptables enables understanding the core of Linux network security, building firewalls from scratch, and confidently facing real-world challenges.

Chapter 9: Installation and First Commands

Chapter Objectives

• Install and verify iptables and nftables on GNU/Linux distributions.

• Install and access pfSense for initial management.

• Understand and execute the first key commands in each technology.

• Lay the groundwork for creating functional firewall rules.

• Prepare lab environments with interfaces, rules, and basic tests.

Part 1: iptables – Installation and First Steps

System Requirements

• Linux distribution (Debian, Ubuntu, CentOS, etc.)

• Access to terminal with root or sudo permissions.

Verify if Installed

bash

iptables—version

Expected result:

iptables v1.8.x (legacy)

Installation (if not available)

Debian/Ubuntu:

bash

sudo apt update

sudo apt install iptables

CentOS/RHEL:

bash

sudo yum install iptables iptables-services

Basic Initial Commands

Command | Description
iptables -L | List current rules
iptables -F | Clear all rules
iptables -P INPUT DROP | Set default policy to "DROP"
iptables -A INPUT -p tcp—dport 22 -j ACCEPT | Allow SSH

Save Configuration (Persistence)

Debian:

bash

sudo apt install iptables-persistent

sudo netfilter-persistent save

RHEL:

bash

sudo service iptables save

Part 2: nftables – Installation and First Steps

nftables is the modern replacement for iptables, more efficient and with unified syntax.

Verify if Available

bash

nft—version

Expected result:

nginx

nftables v1.0.x

Installation

Debian/Ubuntu:

bash

sudo apt update

sudo apt install nftables

RHEL/CentOS:

bash

sudo yum install nftables

Enable nftables as the default firewall

bash

sudo systemctl enable nftables

sudo systemctl start nftables

Fundamental Commands

List existing tables and rules:

bash

sudo nft list ruleset

Create a simple table, chain, and rule:

bash

sudo nft add table inet myfilter

sudo nft add chain inet myfilter input { type filter hook input priority 0 \; policy drop \; }

sudo nft add rule inet myfilter input ct state established,related accept

sudo nft add rule inet myfilter input tcp dport 22 accept

Save Configuration

bash

sudo nft list ruleset > /etc/nftables.conf

This will be automatically loaded at boot if the service is enabled.

Part 3: pfSense – Installation and Initial Access

Minimum Requirements for Lab:

Requirement | Description
Hardware or VM | 2 NICs (WAN/LAN), 1 GB RAM minimum
ISO Image | Download from: https://www.pfsense.org/download/
Virtualization | VirtualBox, VMware, Proxmox, or physical

Step-by-Step Installation

Download the ISO image.

Create a VM with 2 network interfaces (bridge + NAT or internal network).

Start the installation:

Choose the "Install pfSense" option.

Follow the wizard.

Assign the WAN and LAN interfaces.

Finish and start pfSense.

First Access to Web Interface

Connect to the virtual LAN network.

Open the browser and go to:

https://192.168.1.1

Username: admin
Password: pfsense

Follow the Setup Wizard:

Configure hostname, domain.

Configure DNS.

Configure WAN access.

Change the admin password.

First Useful Configurations

Task | Action
View firewall rules | Menu -> Firewall -> Rules
Create remote access rule (SSH, HTTP) | Add rule in LAN or WAN
Enable access on a specific port | Set protocol, destination IP, and port
Apply NAT | Firewall -> NAT
Restart interface | Status -> Interfaces

Practical Activities for Students

Activity 1: iptables Lab

Clear current rules.

Set default policy to DROP.

Allow SSH and HTTP traffic.

Verify connectivity from another machine.

Activity 2: First nftables Script

Create a script for inet table, input chain.

Set default policy to DROP.

Allow SSH.

Save and apply the configuration.

Activity 3: First Rules in pfSense

Create a WAN rule that only allows HTTP from a specific IP.

Block all outgoing traffic except DNS or HTTPS.

Test rules from a client machine on the LAN network.

Tips for the Instructor

• Accompany installation with screenshots or screen sharing.

• Simulate real network environments with 2 virtual machines.

• Assess understanding with small connectivity challenges.

• Use ping, traceroute, telnet, and netcat for port tests.

Additional Resources

Resource | Link or Command
Official iptables manual | man iptables
nftables documentation | https://wiki.nftables.org
pfSense guide | https://docs.netgate.com/pfsense/en/latest/
Virtual lab | https://tryhackme.com or https://virtualbox.org

Correct installation and initial use of iptables, nftables, and pfSense is the foundation for any effective firewall. This stage allows students to begin understanding traffic control logic, rule structuring, and security policy design.

With these tools ready, we are prepared to dive into advanced configuration, network segmentation, and active defense.

Chapter 10: Table and Chain Structure

Chapter Objectives

• Understand what tables and chains are in Linux firewalls.

• Differentiate the operation between iptables and nftables.

• Know at which point in the packet's journey each chain acts.

• Apply practical configurations for filter, nat, and mangle.

• Diagnose and design policies based on the network flow structure.

Why is it key to understand tables and chains?

Most firewall configuration errors arise from misunderstanding which chain a rule should be applied to. Understanding the structure allows:

• Optimizing performance.

• Avoiding ineffective or redundant rules.

• Precisely controlling traffic flow.

• Applying security based on context and stage of processing.

Fundamental Concepts

What is a Table?

A table groups chains and defines a general processing purpose:

Table | Main Purpose
filter | Accept or deny traffic
nat | Perform NAT: SNAT, DNAT, Masquerade
mangle | Modify header fields (QoS, TTL)
raw | Pre-connection tracking rules
security | For SELinux or AppArmor (less used)

What is a Chain?

A chain is a set of rules executed sequentially.

Each table has predefined (built-in) chains, and custom chains can be created.

Example:

In the filter table, the INPUT chain decides whether a packet can enter the system.

Packet Processing Flow (iptables)

Visually:

INET

↓

+——————-+

| PREROUTING  | ← mangle/nat

+——————-+

↓

Routing Decision

↙  ↘

+—————+  +—————+

|  INPUT  |  | FORWARD  |

| (to host)|  | (to LAN) |

+—————+  +—————+

↓  ↓

+———+  +—————-+

| LOCAL|  | POSTROUTING| ← nat/mangle

+———+  +—————-+

↓

OUT

Real Example with iptables

bash

iptables -t filter -A INPUT -p tcp—dport 22 -j ACCEPT

Interpretation:

• Table: filter

• Chain: INPUT (for packets directed to the host)

• Action: accept TCP connections on port 22 (SSH)

Chain by Table in iptables

filter table (most common)

Chain | Traffic
INPUT | Incoming to the local system
OUTPUT | Outgoing traffic generated by the host
FORWARD | Forwarded traffic (Linux router)

nat table

Chain | Description
PREROUTING | Before routing, for DNAT
POSTROUTING | After routing, for SNAT
OUTPUT | NAT for traffic generated by the host

mangle table

Chain | Typical Use
PREROUTING | Mark packets for QoS
INPUT | Change TTL or mark for filtering
FORWARD | Modify forwarded traffic
OUTPUT | Alter outgoing packets
POSTROUTING | Apply marks before packets leave the system

Practice: Rules Applied to Different Chains

Scenario:

You want to:

Mark incoming SSH packets.

Apply NAT for outgoing traffic to the internet.

Reject ICMP pings.

bash

# mangle table - mark SSH packets

iptables -t mangle -A PREROUTING -p tcp—dport 22 -j MARK—set-mark 100

# nat table - apply SNAT (masquerade)

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# filter table - deny ICMP

iptables -t filter -A INPUT -p icmp -j DROP

nftables: Modern Table and Chain Structure

In nftables, there are no predefined tables.

You must explicitly create the table and chain:

bash

sudo nft add table inet firewall

sudo nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }

Command | Description
type filter | Purpose of the chain
hook input | Hook point: input, output, prerouting, etc.
priority | Execution order
policy drop | Default policy

Comparison: iptables vs nftables

Element | iptables | nftables
Predefined Tables | Yes | No (you define them)
Predefined Chains | Yes (INPUT, etc.) | No, must declare them
Syntax | Verbose | Concise, structured
Grouped Rules | No | Yes (sets and maps)
Performance | Good | Better (uses netlink kernel)

Practice: Full Structure in nftables

bash

nft add table inet myfirewall

nft add chain inet myfirewall input { type filter hook input priority 0 \; policy drop \; }

nft add rule inet myfirewall input ct state established,related accept

nft add rule inet myfirewall input tcp dport 22 accept

Inspection Tools

Tool | Use
iptables -L -v -n—line-numbers | View rules with details
nft list ruleset | Show all tables and rules
iptables-save / restore | Export or import configuration
tcpdump or wireshark | View real traffic and its passage through chains
conntrack -L | View active connections (for packet state)

Lab Project

Objective: Design a complete firewall structure using all tables (filter, nat, mangle) in iptables or nftables.

Requirements:

• Accept SSH and HTTP.

• Apply NAT for an internal network.

• Mark DNS packets.

• Block ICMP traffic.

• Save and restore configuration.

Tips for Educators

• Start with flow diagrams drawn on the whiteboard or a schematic.

• Use virtual environments with VirtualBox, GNS3, or Proxmox.

• Assess understanding with interpretation exercises: What does this rule do? Where is it applied?

• Encourage students to write scripts that simulate real firewalls.

The table and chain structure is the backbone of the firewall. Understanding where and when each rule applies allows the creation of strong, secure, and efficient policies. Both iptables and nftables share this logic, but their syntax and capabilities vary.

Mastering these structures is key to advancing towards dynamic firewalls, network segmentation, and centralized rule management.

Chapter 11: Basic Rules for Accepting and Blocking

Chapter Objectives

• Understand the logic behind accepting or blocking traffic.

• Define correct rules based on traffic context.

• Apply basic firewall rules in iptables, nftables, and pfSense.

• Diagnose common errors in packet filtering.

• Develop practical skills for creating minimal functional policies.

Traffic Control Fundamentals

In a firewall, traffic control is based on two main decisions:

• ACCEPT: Allow the packet to continue its path.

• DROP: Silently ignore the packet (safer).

• REJECT: Actively block with an error message (more informative).

Golden Rule: Block everything by default and only allow what is necessary (default deny).

Key Elements of a Rule

Every firewall rule follows a logic similar to if...then:

bash

IF the traffic meets a condition

THEN apply an action (ACCEPT, DROP, REJECT)

Basic example in iptables:

bash

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

• Action: ACCEPT

• Protocol: TCP

• Port: 22 (SSH)

• Direction: Incoming traffic (INPUT)

Basic Rules with iptables

Safe Default Policy

bash

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

This blocks all incoming and forwarded traffic. Only specified traffic is allowed.

Allow SSH (port 22)

bash

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

Allow Established Traffic (responses)

bash

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT

Block Ping (ICMP)

bash

iptables -A INPUT -p icmp -j DROP

Reject HTTP Access from a Specific IP

bash

iptables -A INPUT -s 192.168.1.100 -p tcp—dport 80 -j REJECT

iptables Practical Example

Scenario: Only allow SSH access from a specific internal IP (192.168.1.10)

bash

iptables -P INPUT DROP

iptables -A INPUT -p tcp—dport 22 -s 192.168.1.10 -j ACCEPT

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT

Basic Rules with nftables

Create Rule Structure

bash

nft add table inet firewall

nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }

Allow Established Connections

bash

nft add rule inet firewall input ct state established,related accept

Allow SSH from Specific IP

bash

nft add rule inet firewall input ip saddr 192.168.1.10 tcp dport 22 accept

Block Everything Else
-> Already covered by the drop policy in the chain.

nftables Practical Example

Scenario:

• Allow outgoing DNS.

• Allow incoming HTTP from any IP.

• Completely block ICMP.

bash

# Structure

nft add table inet fw

nft add chain inet fw input { type filter hook input priority 0 \; policy drop \; }

# Rules

nft add rule inet fw input ct state established,related accept

nft add rule inet fw input ip protocol icmp drop

nft add rule inet fw input tcp dport 80 accept

nft add rule inet fw output udp dport 53 accept

Basic Rules in pfSense (GUI)

In pfSense, rules are created through the web interface:

Menu -> Firewall -> Rules -> LAN/WAN

Click "Add" (+) to add a new rule

Common parameters:

Field | Example
Action | Pass / Block / Reject
Interface | LAN or WAN
Protocol | TCP / UDP / ICMP
Source | any / Specific IP
Destination | any / destination port
Description | Optional comment

Example: Allow HTTP from LAN to the Internet

• Interface: LAN

• Protocol: TCP

• Destination Port: 80

• Action: Pass

Example: Block incoming ICMP from WAN

• Interface: WAN

• Protocol: ICMP

• Action: Block

Multi-tool Practical Lab

Activity A (iptables):

Objective:

• Block everything.

• Allow traffic only from 192.168.10.5 to port 22.

• Reject everything else with REJECT.

bash

iptables -P INPUT DROP

iptables -A INPUT -s 192.168.10.5 -p tcp—dport 22 -j ACCEPT

iptables -A INPUT -j REJECT

Activity B (nftables):

Objective:

• Allow outgoing HTTPS connections.

• Block all outgoing traffic except HTTPS and DNS.

bash

nft add table inet out

nft add chain inet out output { type filter hook output priority 0 \; policy drop \; }

nft add rule inet out output tcp dport 443 accept

nft add rule inet out output udp dport 53 accept

Activity C (pfSense):

Objective:

• From LAN, allow only outgoing to ports 80 and 443.

• From WAN, reject everything except incoming SSH from a public IP.

Common Errors in Accept/Block Rules

Error | Solution
Response traffic not allowed | Add ESTABLISHED,RELATED rule
Allow before blocking | Order matters: block first if there are exceptions
No default policy defined | Use DROP as the base policy
Incorrect use of REJECT vs DROP | REJECT for testing, DROP for real security

Didactic Suggestions

• Use colors and diagrams to visualize what happens with each rule.

• Simulate networks with 2-3 virtual machines and perform ping, curl, and netcat tests.

• Apply exercises like "What rule is missing here?" or "Diagnose why it isn't working."

Basic acceptance and blocking rules are the foundation of the firewall. Mastering their structure, syntax, and logic allows you to build strong and secure policies. A correctly filtered network that accepts only what is necessary and blocks everything else drastically reduces the attack surface.

Mastering this paves the way for advanced configurations, traffic segmentation, deep inspection, and real-time rule automation.

Chapter 12: Default Policies and Packet Flow

Chapter Objectives

• Understand what default policies are and their impact.

• Analyze the internal flow of a packet within the system and the firewall.

• Configure secure base policies with iptables, nftables, and pfSense.

• Apply best practices to reduce attack surfaces.

What is a Default Policy?

Default policies determine what happens to packets that don't match any explicit rule in a chain.

In tools like iptables and nftables, this is defined at the main chain level (INPUT, OUTPUT, FORWARD, etc.).

Common types:

Policy | Description
ACCEPT | Anything not blocked is allowed
DROP | Anything not explicitly allowed is silently blocked
REJECT | Same as DROP, but returns a message

Cybersecurity Base Rule: default policy = DROP or REJECT

This is part of the "deny by default" or "zero trust" principle.

Packet Flow in the System

Before creating effective rules, it's important to understand how packets travel inside a Linux system.

Basic packet path:

It comes from the network (physical or virtual interface).

It passes through PREROUTING.

It is decided whether the packet goes to the system (INPUT) or is forwarded (FORWARD).

If it’s directed to the host, it is processed locally.

If forwarded, it passes through POSTROUTING before exiting.

If the host generates traffic, it passes through OUTPUT and POSTROUTING.

Each of these stages can have different rules.

Default Policies in iptables

Basic Example:

bash

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

Meaning:

INPUT DROP: Nothing is allowed into the system unless there's an explicit rule.

FORWARD DROP: The host will not act as a router, or it will do so with very specific rules.

OUTPUT ACCEPT: Anything generated from the host is allowed (can be modified as needed).

Practical Lab: Apply Base Policy

Scenario:

• The system should only accept SSH connections and return response traffic.

• Everything else should be blocked.

bash

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

# Allow related traffic

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

Use iptables -L -n -v to check how many packets fall under the default policy.

Internal Flow in iptables (Visual Summary)

[INTERNET]

↓

[PREROUTING] -> (NAT, MANGLE)

↓

[INPUT] ← if the destination is the host

[FORWARD] -> if the destination is another network (routed)

↓

[POSTROUTING] -> exit to physical interface

Default Policies in nftables

In nftables, default policies are defined when creating the chain, not after.

bash

nft add table inet firewall

nft add chain inet firewall input { type filter hook input priority 0 \; policy drop \; }

nft add rule inet firewall input ct state established,related accept

nft add rule inet firewall input tcp dport 22 accept

If you don't define a policy, non-matching packets are not discarded automatically.

Practical Lab: Secure Policy in nftables

bash

nft add table inet myfw

nft add chain inet myfw input { type filter hook input priority 0 \; policy drop \; }

nft add rule inet myfw input ct state established,related accept

nft add rule inet myfw input ip saddr 192.168.1.10 tcp dport 22 accept

Default Policies in pfSense

In pfSense, no explicit chain policy is defined. However, its default logic is:

• All traffic is blocked if there is no rule that allows it (equivalent to DROP).

Practical Configuration:

• Go to Firewall > Rules > WAN

• If there are no rules, everything is blocked from the outside (which is desired).

• Add rules in LAN if you need to enable outgoing traffic.

pfSense blocks by interface and traffic direction, which can be configured very granularly.

Best Practices for Defining Default Policies

Recommendation | Justification
Use DROP as the base policy | Default security
Allow only what is necessary | Minimizes the attack surface
Accept related connections | Prevents breaking legitimate traffic (like responses)
Test rules in a controlled environment | Avoid accidental lockouts
Log DROP packets for diagnostics | Facilitates troubleshooting

Combined Lab Project

Objective:

• Configure secure default policies.

• Create minimal rules to allow only SSH and DNS.

With iptables:

bash

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

iptables -A INPUT -p udp—dport 53 -j ACCEPT

Diagnosis:

bash

ping 8.8.8.8 -> should fail (ICMP blocked)

ssh localhost -> should work

dig google.com -> should work if DNS is allowed

Complementary Tools

Tool | Function
tcpdump | View incoming/outgoing packets
iptables -L -v | View traffic by rule/chain
nft list ruleset | View the complete ruleset
conntrack -L | View connection states
pfSense Logs | Diagnostics in the GUI

Setting appropriate default policies is the first step in building an effective firewall. Understanding the internal flow of a packet allows you to place rules where they truly matter, not where it "seems" logical.

A poorly defined policy can open the network to the world or block essential services. A well-configured policy closes the door to malicious traffic and only lets authorized traffic in, as it should be.

Chapter 13: Creating a Custom Firewall

Chapter Objectives

• Understand the key elements for designing a firewall tailored to a specific network.

• Develop a coherent and secure script or set of rules from scratch.

• Configure and validate a custom firewall using iptables, nftables, and pfSense.

• Apply segmentation principles, minimal policies, and traffic control.

• Diagnose and adjust rules for different scenarios.

What is a Custom Firewall?

A custom firewall is a configuration built to protect a network or system, tailored to:

• Network architecture

• Exposed services

• Threat profile

• Intended use (servers, workstations, routers, IoT, etc.)

It is not about installing a tool and leaving it with default settings, but about planning, creating, testing, and maintaining the rules that only allow necessary traffic.

Phases to Create a Custom Firewall

Network Analysis

Security Policy Design

Technology Selection (iptables, nftables, pfSense)

Rule Implementation

Functional and Security Testing

Automation and Persistence

Documentation and Maintenance

Phase 1: Network Analysis

Before writing rules:

• What is the role of the system? (server, client, router, dedicated firewall)

• What interfaces does it have?

• What services should it allow?

• Who connects, and from where?

Example Scenario:

Ubuntu Server with:

• WAN interface: eth0

• LAN interface: eth1

• Services: SSH, HTTP, outgoing DNS

• Should act as a NAT firewall for the LAN

Phase 2: Designing the Security Policy

Base Policies:

• INPUT: DROP

• FORWARD: DROP

• OUTPUT: ACCEPT

• Only allow necessary connections

• Allow responses (ESTABLISHED, RELATED)

Allowed Traffic

Source | Destination | Service | Protocol | Port
Any IP | Host | SSH | TCP | 22
LAN | Internet | NAT | Any | Any
Host | Internet | DNS | UDP | 53

Phase 3: Implementation with iptables

Custom Firewall Script (firewall.sh)

bash

#!/bin/bash

# Cleanup

iptables -F

iptables -X

# Default Policies

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

# Allow loopback traffic

iptables -A INPUT -i lo -j ACCEPT

# Allow established connections

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

# Allow NAT for LAN

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

iptables -A FORWARD -i eth1 -o eth0 -m conntrack—ctstate NEW,ESTABLISHED,RELATED -j ACCEPT

iptables -A FORWARD -i eth0 -o eth1 -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow outgoing DNS

iptables -A OUTPUT -p udp—dport 53 -j ACCEPT

echo "Custom firewall activated."

Persistence (Debian/Ubuntu)

bash

apt install iptables-persistent

Phase 4: Implementation with nftables

Basic Configuration

bash

#!/usr/sbin/nft -f

flush ruleset

table inet myfw {

chain input {

type filter hook input priority 0;

policy drop;

iif "lo" accept

ct state established,related accept

tcp dport 22 accept

}

chain forward {

type filter hook forward priority 0;

policy drop;

iif "eth1" oif "eth0" ct state new,established accept

iif "eth0" oif "eth1" ct state established,related accept

}

chain output {

type filter hook output priority 0;

policy accept;

udp dport 53 accept

}

chain postrouting {

type nat hook postrouting priority 100;

oif "eth0" masquerade

}

}

Save as /etc/nftables.conf and enable with systemctl enable nftables.

Phase 5: Creating in pfSense (GUI)

Key steps:

Interfaces -> Assign WAN and LAN.

NAT -> Enable "Outbound NAT" in manual mode.

Firewall -> Rules:
• LAN -> Pass: DNS, HTTP, HTTPS, all outbound traffic.
• WAN -> Pass: SSH to the firewall.
• WAN -> Block: Everything else (already blocked by default).
• Logging: Enable for DROP or REJECT rules.

Phase 6: Practical Testing

Diagnostic Tools

Command | Function
ping, curl | Verify accessibility
nmap | Verify open ports
iptables -L -v | View packet count by rule
tcpdump | Traffic sniffing
pfSense Logs | View in GUI -> Status -> System Logs

Classroom or Lab Activities

Activity A – Basic SSH + HTTP Firewall (iptables)

• Default policy: DROP

• Allow SSH and HTTP

• Everything else blocked

• Validate with nmap localhost

Activity B – Broken Rules: Why doesn't it connect?

Provide rules with common errors:

• Missing ESTABLISHED

• Default policy set to ACCEPT without control

• Allowing a misspelled port

Ask students to diagnose the error.

Common Errors

Error | Solution
Allowing rules without state control | Add —ctstate ESTABLISHED,RELATED
Default policy set to ACCEPT | Always use DROP + exceptions
Missing NAT for LAN | Correctly configure POSTROUTING
Incorrectly identified interfaces | Verify with ip a

Best Practices

• Document each rule with comments.

• Use version-controlled scripts (Git).

• Test in virtual machines before production.

• Backup the configuration.

• Monitor with logs and alerts.

Creating a custom firewall is not just a technical task; it is a statement of control over the attack surface of your network. There is no one-size-fits-all solution, but rather a set of decisions tailored to each environment.

Mastering this skill means you can protect a network, filter malicious traffic, and secure essential services, from a small server to an enterprise infrastructure.

Chapter 14: NAT and Port Forwarding with iptables

Chapter Objectives

• Understand how NAT (Network Address Translation) works.

• Apply MASQUERADE NAT to share Internet using iptables.

• Configure Port Forwarding (DNAT) to expose internal services.

• Diagnose and test configurations in real-world scenarios.

• Automate NAT rules for persistent environments.

What is NAT?

NAT (Network Address Translation) allows changing the source or destination IP address of packets as they pass through a router or firewall. It is mainly used for:

• Sharing a public IP address among multiple private devices (outgoing to the Internet).

• Redirecting external traffic to internal services (web servers, SSH, etc.).

Types of NAT with iptables

Type | Table | Purpose
SNAT | nat | Change source IP (outgoing)
DNAT | nat | Change destination IP (incoming)
MASQUERADE | nat | Automatic SNAT variant
Port Forwarding | nat + filter | Redirect traffic to internal IP and allow passage

Requirements to Work with NAT

A Linux system with at least two network interfaces:
• eth0 (WAN / Internet)
• eth1 (Private LAN)

Enable packet forwarding:

bash

echo 1 > /proc/sys/net/ipv4/ip_forward

# To make it persistent:

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf

sysctl -p

Outbound NAT: Share Internet (MASQUERADE)

Scenario: Linux router with clients on eth1, accessing the Internet via eth0.

Practical Command:

bash

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# Allow forwarding of LAN -> WAN traffic

iptables -A FORWARD -i eth1 -o eth0 -m conntrack—ctstate NEW,ESTABLISHED,RELATED -j ACCEPT

iptables -A FORWARD -i eth0 -o eth1 -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

Verification:

From a host on the LAN:

bash

ping 8.8.8.8

curl ifconfig.me

If you see the public IP of the router, NAT is working correctly.

Port Forwarding (DNAT) – Redirect External Ports

Scenario: The firewall receives external traffic on its public IP on port 2222, and it must forward it to an SSH server on the internal network on port 22.

Configuration:

bash

# Change destination IP of the packet (DNAT)

iptables -t nat -A PREROUTING -i eth0 -p tcp—dport 2222 -j DNAT—to-destination 192.168.1.10:22

# Allow the forwarded traffic to pass

iptables -A FORWARD -p tcp -d 192.168.1.10—dport 22 -m conntrack—ctstate NEW,ESTABLISHED,RELATED -j ACCEPT

iptables -A FORWARD -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

Accidental Block: Why Doesn’t It Work?

Check:

• The FORWARD rules are not blocking the redirected traffic.

• The destination server allows the firewall's IP.

• The port is listening (ss -tnlp | grep 22).

• No internal firewalls are blocking (e.g., ufw, firewalld).

Forward Multiple Services

Service | External Port | Destination IP | Destination Port
SSH | 2222 | 192.168.1.10 | 22
HTTP | 8080 | 192.168.1.20 | 80
HTTPS | 8443 | 192.168.1.30 | 443

Configuration:

bash

iptables -t nat -A PREROUTING -i eth0 -p tcp—dport 8080 -j DNAT—to 192.168.1.20:80

iptables -A FORWARD -p tcp -d 192.168.1.20—dport 80 -j ACCEPT

Practical Activity for Students

Simulate a firewall with two NICs (you can use virtual machines with VirtualBox or GNS3).

Implement:
• MASQUERADE NAT for LAN browsing.
• Port forwarding from 2222 -> 192.168.1.100:22 (SSH server).

Test from an external machine with:

bash

ssh -p 2222 user@Public_IP

Additional Security

• Use -s or -d rules to limit source/destination IPs.

• Use conntrack to control the state.

• Use -m limit to avoid brute force attacks.

Example:

bash

iptables -A FORWARD -p tcp—dport 22 -s 203.0.113.10 -m conntrack—ctstate NEW -m limit—limit 5/min -j ACCEPT

Persistence on Ubuntu/Debian

Install iptables-persistent:

bash

apt install iptables-persistent

Save the rules:

bash

iptables-save > /etc/iptables/rules.v4

Diagnostics and Monitoring

Tool | Use
iptables -t nat -L -n -v | View active DNAT/SNAT rules
tcpdump -i eth0 port 2222 | View incoming external traffic
conntrack -L | View active connections (NAT tracking)
journalctl or SSH logs | View access logs

Guiding Questions for Students

What is the difference between SNAT and MASQUERADE?

Why isn’t DNAT enough to forward a port?

What happens if you forget to enable packet forwarding (ip_forward)?

How can you limit forwarding only to trusted IPs?

Configuring NAT and Port Forwarding with iptables allows transforming a Linux system into a full router/firewall capable of controlling access, protecting internal networks, and exposing selected services with clear and traceable rules. Understanding this functionality is essential for anyone aspiring to manage network security professionally.

Chapter 15: Save, Load, and Automate Rules

Chapter Objectives

• Understand why it is necessary to save iptables or nftables rules.

• Apply methods to save active rules and restore them on boot.

• Automate custom firewall scripts with systemd, cron, or specific tools.

• Implement best practices for educational and production environments.

Why Save and Automate Rules?

Iptables rules are volatile: they disappear after a system restart unless explicitly saved.

This implies that:

• Temporary changes = insecure (they are lost after a restart).

• Automation = necessary to ensure continuity in security.

• Teaching = reproducibility: students should be able to replicate environments.

Methods to Save and Restore Rules

Using iptables-save and iptables-restore
These tools allow saving and loading complete rules:

Save current rules

bash

sudo iptables-save > /etc/iptables/rules.v4

For IPv6:

bash

sudo ip6tables-save > /etc/iptables/rules.v6

Restore manually

bash

sudo iptables-restore < /etc/iptables/rules.v4

Using iptables-persistent (Recommended for Debian/Ubuntu)
Install the package:

bash

sudo apt install iptables-persistent

During installation, you will be asked if you want to save the current rules. The package uses the following files:

• /etc/iptables/rules.v4

• /etc/iptables/rules.v6

Save changes later

bash

sudo netfilter-persistent save

Restore on boot
This method automatically reloads rules on startup via a systemd service.

Automation with Custom Firewall Scripts
Ideal when you need:
• To document rules with comments
• To load different configurations for each environment
• To teach scripting to students

Example of a firewall script (/usr/local/bin/firewall.sh):

bash

#!/bin/bash

echo "Loading custom firewall rules..."

iptables -F

iptables -X

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

Make it executable:

bash

chmod +x /usr/local/bin/firewall.sh

Automate Script with systemd

Create service file

bash

sudo nano /etc/systemd/system/firewall.service

Content:

ini

[Unit]

Description=Custom iptables Firewall

After=network.target

[Service]

Type=oneshot

ExecStart=/usr/local/bin/firewall.sh

RemainAfterExit=true

[Install]

WantedBy=multi-user.target

Enable and start the service:

bash

sudo systemctl daemon-reexec

sudo systemctl enable firewall.service

sudo systemctl start firewall.service

This way, your script will run automatically on each boot.

Practical Activity for Students

Create a basic set of rules (firewall.sh) that blocks everything except SSH.

Save the rules with iptables-save and restore with iptables-restore.

Install and test iptables-persistent.

Create a systemd service to automate the script.

Restart the machine and verify the restoration with iptables -L.

Load Rules with Cron (Alternative)

If you don’t use systemd, you can use cron:

bash

@reboot root /usr/local/bin/firewall.sh

Edit with:

bash

sudo crontab -e

Verify loaded rules

bash

iptables -L -v -n

Verify that the rules appear after restarting. You can use a system log:

bash

journalctl -u firewall.service

Best Practices

Practice | Benefit
Use iptables-persistent | Easy, stable, integrates with system
Version your scripts with Git | Clear documentation, traceable changes
Add comments in scripts | Improves teaching and maintenance
Automate with systemd | Professional, controlled, auditable
Test before saving | Avoid errors that block remote access

Avoid Common Errors

Error | Solution
Rules disappear after reboot | Use iptables-persistent or a script with systemd
Script doesn’t run on startup | Check permissions, ExecStart, and Enable
Accidentally block SSH | Always test in a virtual environment
Syntax error in rules | Validate manually before saving

Saving and automating firewall rules not only ensures continuity of protection but also professionalizes the network environment. In educational contexts, it is a key tool for teaching system control and scripting with a clear and secure purpose.

A well-configured firewall that runs automatically with clear and maintained rules is the foundation of any secure and reliable infrastructure.

Chapter 16: Iptables Scripts for Classes

Chapter Objectives

• Understand the importance of using scripts in teaching iptables.

• Create reusable scripts to configure rules step by step.

• Prepare controlled labs with varying levels of difficulty.

• Document rules and encourage best practices among students.

Why Use Scripts in Classes?

• They allow reproducibility of the environment.

• Facilitate error diagnosis.

• Help document rules with educational comments.

• Promote automation and scripting, key skills in SysAdmin and SecOps.

Required Tools

• Linux Distribution (Debian/Ubuntu/CentOS)

• Root permissions or use of sudo

• Text editor: nano, vim, gedit

• Simulated network connection (optional: VirtualBox or GNS3 for multi-host environments)

Recommended Script Structure for Classes

bash

~/firewall-clases/

├── 01_limpiar.sh

├── 02_reglas_basicas.sh

├── 03_ssh_web_icmp.sh

├── 04_politicas_restrictivas.sh

├── 05_nat_masquerade.sh

├── 06_port_forwarding.sh

├── 07_defensa_dos_limit.sh

└── 99_restaurar_default.sh

Script 01 – Clean Rules

bash

#!/bin/bash

echo "Cleaning current rules..."

iptables -F

iptables -X

iptables -t nat -F

iptables -t nat -X

iptables -P INPUT ACCEPT

iptables -P FORWARD ACCEPT

iptables -P OUTPUT ACCEPT

echo "Rules deleted and policies restored."

Script 02 – Basic Incoming Rules

bash

#!/bin/bash

echo "Applying basic rules..."

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

echo "🚧 Incoming traffic restricted except for valid connections and loopback."

Script 03 – Allow SSH, Web, and Ping

bash

#!/bin/bash

echo "Enabling rules for SSH, HTTP, and ICMP..."

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

iptables -A INPUT -p tcp—dport 80 -j ACCEPT

iptables -A INPUT -p icmp -j ACCEPT

echo "SSH (22), HTTP (80), and ICMP allowed."

Script 04 – More Restrictive Policies

bash

#!/bin/bash

echo "Applying strict policies..."

iptables -P INPUT DROP

iptables -P OUTPUT DROP

iptables -P FORWARD DROP

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

iptables -A OUTPUT -m conntrack—ctstate NEW,ESTABLISHED,RELATED -j ACCEPT

echo "Firewall in restrictive mode, only valid traffic allowed."

Script 05 – NAT Masquerade (Share Internet)

bash

#!/bin/bash

echo "Configuring NAT Masquerade..."

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

iptables -A FORWARD -i eth1 -o eth0 -m conntrack—ctstate NEW,ESTABLISHED,RELATED -j ACCEPT

iptables -A FORWARD -i eth0 -o eth1 -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

echo "NAT enabled between LAN (eth1) and Internet (eth0)."

Script 06 – Port Forwarding

bash

#!/bin/bash

echo "Configuring port forwarding..."

iptables -t nat -A PREROUTING -i eth0 -p tcp—dport 2222 -j DNAT—to-destination 192.168.1.10:22

iptables -A FORWARD -p tcp -d 192.168.1.10—dport 22 -m conntrack—ctstate NEW,ESTABLISHED -j ACCEPT

echo "Port 2222 externally forwarded to internal SSH server."

Script 07 – Basic DoS Mitigation

bash

#!/bin/bash

echo "Enabling basic DoS protection on SSH port..."

iptables -A INPUT -p tcp—dport 22 -m conntrack—ctstate NEW -m limit—limit 3/min—limit-burst 5 -j ACCEPT

iptables -A INPUT -p tcp—dport 22 -j DROP

echo "SSH limited to 3 attempts per minute."

Script 99 – Restore Default Policies

bash

#!/bin/bash

echo "Restoring firewall to open state..."

iptables -F

iptables -X

iptables -t nat -F

iptables -t nat -X

iptables -P INPUT ACCEPT

iptables -P OUTPUT ACCEPT

iptables -P FORWARD ACCEPT

echo "Firewall restored to unrestricted state."

Teaching Recommendations for Instructors

Strategy | Practical Example
Comment each rule | # Accept traffic from loopback
Use echo to guide output | echo "✔️ SSH enabled"
Simulate attacks with hping3 | For DoS or scan testing
Break into phases or levels | Basic scripts -> Advanced ones
Version in GitLab/GitHub | Each student can "fork"
Integrate in VirtualBox environments | Simulate networks with real clients

Suggested Automation

Save all scripts in /usr/local/firewall-clases and automate with systemd, as discussed in previous chapters, or create a simple interactive menu with Bash so students can test different scenarios:

Interactive Menu (Optional)

bash

#!/bin/bash

echo "===== Iptables Script Menu ====="

select opt in "Clean" "Basic Rules" "SSH/HTTP" "NAT" "Forward" "DoS" "Restore" "Exit"; do

case $opt in

"Clean") sudo ./01_limpiar.sh ;;

"Basic Rules") sudo ./02_reglas_basicas.sh ;;

"SSH/HTTP") sudo ./03_ssh_web_icmp.sh ;;

"NAT") sudo ./05_nat_masquerade.sh ;;

"Forward") sudo ./06_port_forwarding.sh ;;

"DoS") sudo ./07_defensa_dos_limit.sh ;;

"Restore") sudo ./99_restaurar_default.sh ;;

"Exit") break ;;

esac

done

Recommended Practice for Students

Clone the class repository with the scripts.

Run 01_limpiar.sh and then 02_reglas_basicas.sh.

Check traffic using ping, curl, netcat.

Document each script with its comments and create their own versions.

Simulate traffic from another machine or container to test rules in action.

Iptables scripts not only facilitate practical and safe firewall teaching, but also train students in automation, scripting, analysis, and rule planning. They are the ideal step between theory and the real production environment.

Chapter 17: Practical Exercises: Basic Firewall

Chapter Objectives

• Develop the ability to create firewall rules from scratch.

• Apply concepts of default policies, ports, services, and network traffic.

• Use iptables interactively to block, allow, and log traffic.

• Validate rules using tools such as ping, curl, netcat, and iptables -L.

Teaching Methodology

This chapter is designed to be executed in a Linux environment (real or virtual) with superuser privileges. The following is recommended:

• A base Linux system (Ubuntu Server, Debian, Rocky, etc.)

• A multi-VM environment or containers (Docker or VirtualBox) to simulate the network

• At least two terminals (client and server) or two virtual interfaces

Each exercise is aimed at a unique practical goal and presents:

• Description

• Practical steps

• Verification commands

• Possible errors and how to fix them

Exercise 1: "Permissive" Firewall State

Objective

Establish an unrestricted environment to understand the starting point.

Steps

bash

sudo iptables -F

sudo iptables -P INPUT ACCEPT

sudo iptables -P FORWARD ACCEPT

sudo iptables -P OUTPUT ACCEPT

Verification

bash

iptables -L -v

ping 8.8.8.8

curl http://example.com

Exercise 2: Restrictive Firewall with Open Output

Objective

Block all incoming traffic except established connections and loopback.

Steps

bash

sudo iptables -F

sudo iptables -P INPUT DROP

sudo iptables -P FORWARD DROP

sudo iptables -P OUTPUT ACCEPT

sudo iptables -A INPUT -i lo -j ACCEPT

sudo iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

Verification

bash

# This should work:

ping -c 1 8.8.8.8

# This should fail:

nc -zv your_machine 22

Exercise 3: Allow Only Incoming SSH

Objective

Secure the system with remote access only via SSH (port 22).

Steps

bash

sudo iptables -A INPUT -p tcp—dport 22 -j ACCEPT

Verification

bash

nc -zv your_machine 22  # Should connect

nc -zv your_machine 80  # Should fail

Exercise 4: Allow HTTP (Port 80)

Objective

Simulate a secure web server with only HTTP traffic allowed.

bash

sudo iptables -A INPUT -p tcp—dport 80 -j ACCEPT

bash

curl http://localhost  # Should work if a server is active

Exercise 5: Block ICMP (Block Ping)

Objective

Prevent the system from being "discovered" by ping.

bash

sudo iptables -A INPUT -p icmp—icmp-type echo-request -j DROP

bash

ping -c 1 your_machine  # Should not respond

Exercise 6: Limit Access by IP

Objective

Only allow SSH connections from a specific IP address.

bash

sudo iptables -A INPUT -p tcp -s 192.168.1.50—dport 22 -j ACCEPT

sudo iptables -A INPUT -p tcp—dport 22 -j DROP

Verification

Connect from another IP. It should be blocked.

Exercise 7: Log Denied Attempts

Objective

Log blocked connection attempts for later analysis.

bash

sudo iptables -A INPUT -j LOG—log-prefix "FIREWALL BLOCKED: "—log-level 4

Verification

bash

dmesg | grep "FIREWALL BLOCKED"

Exercise 8: Restore Default Rules

Objective

Restore full system access in case of an error.

bash

sudo iptables -F

sudo iptables -P INPUT ACCEPT

sudo iptables -P OUTPUT ACCEPT

Exercise 9: Save Current Rules

Objective

Persist the configuration across reboots.

bash

sudo iptables-save > ~/iptables-rules.bak

Exercise 10: Automation with Script

Objective

Create and run a script that applies everything learned.

bash

nano ~/firewall-basic.sh

Script contents:

bash

#!/bin/bash

iptables -F

iptables -P INPUT DROP

iptables -P OUTPUT ACCEPT

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

iptables -A INPUT -p tcp—dport 80 -j ACCEPT

bash

chmod +x ~/firewall-basic.sh

sudo ~/firewall-basic.sh

Suggested Activities for Students

Activity | Suggested Tool
Create custom rules by role | bash, iptables, comments
Simulate attacks with nmap and observe logs | nmap, dmesg, journalctl
Evaluate inbound/outbound policies | Wireshark, netcat, curl
Share rules in groups and analyze them | Git, shared repository

Common Errors

Error | Solution
Accidental blocking of SSH port | Add the SSH rule before setting DROP
Rules disappear after reboot | Use iptables-save or iptables-persistent
Incorrect rule order | Ensure logical order: ACCEPT before DROP
Missing permissions on scripts | Use chmod +x and run with sudo

Creating and applying firewall rules from scratch is one of the most important skills for any cybersecurity technician. These exercises not only strengthen the understanding of iptables but also develop logical reasoning, traffic analysis, and incident response skills.

With regular practice and adequate feedback, students will not only understand the theory of packet filtering but will also apply it in real or simulated environments effectively and safely.

Chapter 18: Attack Simulation and Blocking

Chapter Objectives

• Simulate common attacks on local and remote networks to observe their impact.

• Apply firewall rules (iptables) to mitigate, block, and log these threats.

• Develop practical judgment in defensive response with firewalls.

• Strengthen awareness of real risks through hands-on exercises.

Prerequisites

• 2 machines (virtual or physical) in a network: one attacker and one victim.

• Root or sudo access on both machines.

• Tools: nmap, hping3, netcat, iptables, tcpdump, and dmesg.

• An environment with simulated internal connectivity (can be VirtualBox with internal network or Docker).

Chapter Structure

Fundamentals of simulated attacks

Pentesting tools for the classroom

Simulation of scans and reconnaissance

Simulation of DDoS and SYN flood

SSH brute-force simulation

Application of blockades with iptables

Attack logging and monitoring

Practical activities for students

Security recommendations

Post-mortem analysis

1. Fundamentals of Simulated Attacks

In a controlled learning environment, attack simulation aims to show how the network behaves in the face of threats and allows the application of immediate defense mechanisms.

Simulated attacks should:

• Be isolated from the internet.

• Use dedicated machines (virtual) or containers.

• Have clear rules to avoid unintended damage.

2. Pentesting Tools for the Classroom

Tool | Purpose
nmap | Network/Port scanning
hping3 | Generation of malicious packets
hydra | Brute force (ethical exercise)
netcat | Port testing and shell
tcpdump | Live traffic monitoring
iptables | Blocking and monitoring

Install them if needed:

bash

sudo apt install nmap hping3 hydra netcat tcpdump -y

3. Simulation of Scans and Reconnaissance

Attack: Port scanning

From the attacker:

bash

nmap -sS -T4 -p- 192.168.100.10

From the victim, observe with:

bash

sudo tcpdump -i eth0 port 22 or port 80

Suggested Blockade:

bash

sudo iptables -A INPUT -p tcp—syn -m recent—name portscan—set

sudo iptables -A INPUT -p tcp—syn -m recent—name portscan—update—seconds 60—hitcount 10 -j DROP

Simulate repeated scans and verify how it gets blocked after a certain threshold.

4. Simulation of DDoS or SYN Flood

Attack: SYN flood with hping3

bash

sudo hping3 -S—flood -V -p 80 192.168.100.10

Defense: Limit concurrent connections

bash

sudo iptables -A INPUT -p tcp—dport 80 -m connlimit—connlimit-above 20 -j REJECT

Alternative: Limit rate

bash

sudo iptables -A INPUT -p tcp—dport 80 -m limit—limit 10/s—limit-burst 20 -j ACCEPT

Verify on the victim machine that the web server does not collapse.

5. SSH Brute Force Simulation

Attack: Hydra against SSH

bash

hydra -l root -P rockyou.txt ssh://192.168.100.10

Prevention with iptables:

bash

sudo iptables -A INPUT -p tcp—dport 22 -m state—state NEW -m recent—name SSH—set

sudo iptables -A INPUT -p tcp—dport 22 -m state—state NEW -m recent—name SSH—update—seconds 60—hitcount 4 -j DROP

Try multiple connections within 1 minute: they will be automatically blocked.

6. Application of Blockades with iptables

Create a complete defensive script:

bash

#!/bin/bash

iptables -F

iptables -P INPUT DROP

iptables -P OUTPUT ACCEPT

iptables -A INPUT -i lo -j ACCEPT

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT

# SSH protection

iptables -A INPUT -p tcp—dport 22 -m state—state NEW -m recent—name SSH—set

iptables -A INPUT -p tcp—dport 22 -m state—state NEW -m recent—name SSH—update—seconds 60—hitcount 3 -j DROP

# HTTP SYN flood protection

iptables -A INPUT -p tcp—dport 80 -m connlimit—connlimit-above 20 -j DROP

# Port scan

iptables -A INPUT -p tcp—syn -m recent—name scan—set

iptables -A INPUT -p tcp—syn -m recent—name scan—update—seconds 30—hitcount 10 -j DROP

# LOG

iptables -A INPUT -j LOG—log-prefix "FIREWALL BLOCKED: "—log-level 4

7. Logging and Monitoring

Use tcpdump to observe attacks:

bash

sudo tcpdump -n -i eth0 'tcp[tcpflags] & tcp-syn != 0'

Review logs:

bash

dmesg | grep FIREWALL

Review open connections:

bash

sudo netstat -ntu | grep ESTABLISHED

8. Practical Activities for Students

Activity | Expected Outcome
Simulate 3 different types of attacks | Logs generated and traffic recorded
Apply dynamic blocking rules | Attacks stopped in real-time
Analyze logs with tcpdump and dmesg | Identification of malicious patterns
Design a defense script with comments | Documented and functional personalized script

9. Security Recommendations

• Always use private networks to simulate attacks.

• Never launch offensive tools outside controlled environments.

• Monitor CPU/RAM usage during DDoS tests.

• Restart the firewall after each practice to avoid persistent blockages.

10. Post-Mortem Analysis

After each exercise, answer:

• What traffic was detected?

• What behavior did the system exhibit?

• Which firewall rule was effective?

• How would you improve your defense?

Encourage students to document their analyses in short reports to foster critical thinking.

Simulating attacks is one of the best ways to truly understand how a firewall works and how vulnerable systems can be without proper protection. Through these exercises, students will see the real value of defensive rules and develop essential skills in practical cybersecurity.

Chapter 19: Assessable Practices with iptables

Chapter Objectives

• Design and apply practical, assessable exercises using iptables.

• Evaluate fundamental network security knowledge objectively.

• Promote critical thinking and real-world problem-solving.

• Generate evidence of practical learning for instructor feedback.

Introduction

Practical learning in cybersecurity must be measurable and demonstrable. This chapter presents a series of assessable practices designed to measure students' ability in:

• Designing firewall policies.

• Interpreting scenarios.

• Implementing specific rules.

• Verifying and performing functional tests.

These practices are aimed at intermediate-advanced levels and are fully executable in a local or virtualized environment.

Technical Requirements

• Linux distribution (Ubuntu, Debian, or Kali).

• Sudo or root access.

• Tools: iptables, nmap, netcat, curl, ssh, tcpdump.

• VirtualBox, VMware, or GNS3 for complex environments (optional).

• Script repository or LMS platform (Moodle, Google Classroom, etc.) for submitting evidence.

Practice Outline

Each practice includes:

• Exercise statement.

• Evaluation objective.

• Necessary materials.

• Step-by-step instructions.

• Grading criteria.

• Possible guiding solution.

Practice 1: Basic Denial Policy

Objective: Configure iptables with a default DROP policy, allowing only necessary traffic.

Instructions:

Set default policies:

bash

iptables -P INPUT DROP 

iptables -P OUTPUT DROP 

iptables -P FORWARD DROP 

Allow only:

Local traffic (lo)

Outgoing connections for DNS, HTTP, and HTTPS

Incoming connections related to responses (ESTABLISHED)

Verify connectivity:

bash

ping 8.8.8.8 

curl https://example.com 

Evaluation Criteria:

Criterion | Points
Default policies applied | 2 pts
Functional connectivity | 2 pts
Correct specific rules | 3 pts
Block non-permitted traffic | 3 pts

Practice 2: Allow SSH Access Only From One IP

Objective: Configure a rule to allow SSH connections only from IP 192.168.1.50.

Instructions:

Clear previous rules:

bash

iptables -F 

Add rule for SSH:

bash

iptables -A INPUT -p tcp -s 192.168.1.50—dport 22 -j ACCEPT 

iptables -A INPUT -p tcp—dport 22 -j DROP 

From another machine, try connecting via SSH from different IPs.
Evaluation:

Criterion | Points
Specific IP allowed | 3 pts
Other IPs correctly blocked | 3 pts
Functional connectivity from IP | 2 pts
Correct order of rules | 2 pts

Practice 3: Firewall for Web Server

Objective: Configure iptables for a server that must accept only HTTP and HTTPS traffic.

Instructions:

Install Apache or Nginx if necessary:

bash

sudo apt install apache2 

Apply these rules:

bash

iptables -F 

iptables -A INPUT -i lo -j ACCEPT 

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT 

iptables -A INPUT -p tcp—dport 80 -j ACCEPT 

iptables -A INPUT -p tcp—dport 443 -j ACCEPT 

iptables -A INPUT -j DROP 

Test from another machine:

bash

curl http://SERVER_IP 

Evaluation:

Criterion | Points
Only ports 80 and 443 open | 3 pts
Functional HTTP browsing | 3 pts
Secure incoming policies | 2 pts
Correct blocking of other ports | 2 pts

Practice 4: Protection Against Port Scanning

Objective: Detect and block fast scans using nmap.

Instructions:

From the attacking machine:

bash

nmap -T4 -sS -p- 192.168.1.X 

On the victim machine, create rules:

bash

iptables -A INPUT -p tcp—syn -m recent—name scan—set 

iptables -A INPUT -p tcp—syn -m recent—name scan—update—seconds 60—hitcount 10 -j DROP 

Check /var/log/kern.log or use dmesg.
Evaluation:

Criterion | Points
Attack detected | 3 pts
Attacker IP blocked | 3 pts
Log registered | 2 pts
Explanation in technical report | 2 pts

Practice 5: Automatic Restoration Script

Objective: Create a script that saves custom rules and restores them upon reboot.

Instructions:

Save your rules in a file:

bash

iptables-save > /etc/iptables.rules 

Create the script /etc/network/if-pre-up.d/iptables:

bash

#!/bin/sh 

/sbin/iptables-restore < /etc/iptables.rules 

Make it executable:

bash

chmod +x /etc/network/if-pre-up.d/iptables 

Restart the machine and verify that the rules remain active.
Evaluation:

Criterion | Points
Functional script | 4 pts
Persistence verified after reboot | 4 pts
Correct file structure | 2 pts

Tips for the Instructor

• Ask for evidence with screenshots, scripts, and results from iptables -L.

• Hold brief presentations where students explain their logic.

• Use rubrics to standardize grading.

• Evaluate documentation as well (use of comments and explanations).

Assessable practices are essential to ensure that students truly understand and apply perimeter security concepts. With well-defined exercises, they not only develop technical skills but also the ability to think as active network defenders.

Chapter 20: Virtual Lab with iptables and VMs

Chapter Objectives

• Create a reproducible virtual environment to experiment with iptables rules.

• Simulate an internal network, a server, an attacker machine, and a firewall.

• Apply firewall rules in real situations safely.

• Encourage autonomous and group practice in isolated environments.

Introduction

An essential part of learning cybersecurity is experimenting without putting real systems at risk. This chapter guides you step-by-step through setting up a virtual lab with iptables using virtual machines (VMs), ideal for both instructors and students.

This environment allows:

• Implementing firewalls in realistic scenarios.

• Simulating attacks and evaluating defenses.

• Documenting assessable practices in a controlled environment.

Prerequisites

Required Software

Tool | Function
VirtualBox or VMware | Virtualization
Linux ISO (Debian/Kali/Ubuntu Server) | Guest operating systems
GNS3 (optional) | Advanced network emulation
iptables | Console firewall tool
nmap, netcat, curl | Testing tools

It is recommended to use VirtualBox due to its ease of use and cost-free nature.

Lab Design

Proposed Topology:

+——————-+ +——————-+ +——————-+

| Attacker VM | <——-> | Firewall VM | <——-> | Server VM |

+——————-+ +——————-+ +——————-+

Kali Debian Ubuntu

• Attacker VM: Kali Linux – with tools like nmap, netcat.

• Firewall VM: Debian with iptables, acting as a gateway.

• Server VM: Ubuntu with services like Apache, SSH.

You can expand the topology with more clients or a GNS3 router if desired.

Step-by-Step to Create the Lab

Create the virtual machines
• VM1 (Firewall): Debian 11, 2 NICs (one internal, the other NAT or bridge).
• VM2 (Server): Ubuntu Server 22.04, 1 internal NIC.
• VM3 (Attacker): Kali Linux, 1 internal NIC.
Assign at least 1 GB of RAM per VM and 10 GB of disk space.

Configure internal network
Create an internal network in VirtualBox, e.g., intnet.
• Assign intnet interface to VM2 (Server) and VM3 (Attacker).
• Assign two interfaces to VM1 (Firewall):

NIC1: intnet (internal network)

NIC2: NAT or bridge for external access.

Configure manual IP addresses

VM Firewall:

bash

# intnet (eth0) 

IP: 192.168.10.1/24 

# NAT/bridge (eth1) 

IP: automatic (DHCP or manual depending on the network type) 

VM Server:

bash

IP: 192.168.10.10/24 

GW: 192.168.10.1 

VM Attacker:

bash

IP: 192.168.10.50/24 

GW: 192.168.10.1 

Ensure IP forwarding is enabled on the Firewall VM:

bash

echo 1 > /proc/sys/net/ipv4/ip_forward 

To make it permanent:

bash

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf 

sysctl -p 

Configuring iptables on the Firewall

Step 1: Clear previous rules

bash

iptables -F 

iptables -t nat -F 

Step 2: NAT rules for internet access

bash

iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE 

iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT 

iptables -A FORWARD -i eth1 -o eth0 -m state—state ESTABLISHED,RELATED -j ACCEPT 

This allows internal VMs to access the internet.

Step 3: Enable filtering policies

Block everything by default and only allow necessary traffic:

bash

iptables -P INPUT DROP 

iptables -P FORWARD DROP 

iptables -P OUTPUT ACCEPT 

iptables -A INPUT -i lo -j ACCEPT 

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT 

You can then apply custom rules to control traffic between the attacker and server.

Practices within the Lab

Practice 1: Configure HTTP Access Only

• Install Apache on the Server.

• Allow TCP traffic to port 80 from the attacker to the server.

bash

iptables -A FORWARD -p tcp -s 192.168.10.50 -d 192.168.10.10—dport 80 -j ACCEPT 

Test with:

bash

curl http://192.168.10.10 

Practice 2: Selective IP Blocking

Completely block the attacker:

bash

iptables -A FORWARD -s 192.168.10.50 -j DROP 

Verify that the attacker cannot ping or access via curl.

Practice 3: Traffic Monitoring

On the firewall VM:

bash

tcpdump -i eth0 port 80 

This will allow you to see HTTP requests in real time from the attacker.

Documentation and Evidence Submission

Ask students for:

• Screenshots of command results.

• iptables rule files (iptables-save).

• Custom scripts.

• A brief report explaining the filtering logic applied.

Lab Evaluation

Use this rubric:

Criterion | Points
Correctly set up topology | 3 pts
IP forwarding active and tested | 2 pts
Functional and correct rules | 4 pts
Clear and complete documentation | 3 pts
Tests performed and explained | 3 pts
Security applied (blocks) | 5 pts

Tips for the Instructor

• Encourage modification of the lab: "What happens if we change the port? What if we use UDP?"

• Use consistent rubrics and encourage peer evaluation among students.

• Promote the use of reusable scripts to automate configurations.

The virtual lab is the bridge between theory and reality. It allows learning iptables in a secure, controlled, and reproducible environment. Mastering the creation and management of these virtual networks is essential to train professionals capable of implementing effective perimeter security in real-world environments.

Chapter 21: Introduction to nftables

Chapter Objectives

• Understand what nftables is and why it replaces iptables.

• Learn about its modular architecture and how it improves network traffic management.

• Familiarize with essential concepts (tables, chains, rules).

• Perform a basic initial configuration for packet filtering.

1. What is nftables?

nftables is the modern packet filtering subsystem of the Linux kernel, designed to replace:

• iptables (IPv4),

• ip6tables (IPv6),

• arptables (ARP),

• ebtables (Ethernet).

It was introduced in Linux Kernel 3.13 (2014) and provides a unified, cleaner, and more flexible approach to control network traffic from user space.

Why replace iptables?

Feature | iptables | nftables
Rule Language | Procedural, repetitive | Declarative, compact
IPv4 and IPv6 Support | Separate | Unified
Tables and Chains | Static | Dynamic
Set Management | Limited | Advanced and efficient
Performance | Good | Better (fewer evaluations)
Future Maintenance | Deprecated | Active and recommended

2. Basic nftables Architecture

nftables is based on a modular structure of:

• Tables: Logical spaces where chains are grouped.

• Chains: Ordered sets of rules.

• Rules: Conditions that inspect packets and make decisions.

• Sets: Efficient lists (IP, ports, interfaces) reusable in rules.

nftables

└── table inet filter

├── chain input (input)

├── chain output (output)

└── chain forward (forward)

3. Getting Started: Installation and Verification

A. Installation (on Debian, Ubuntu, CentOS, etc.)

bash

sudo apt install nftables  # Debian/Ubuntu 

sudo systemctl enable nftables  # Enable on boot 

sudo systemctl start nftables  # Start the service 

B. Verify Status

bash

sudo nft list ruleset 

If there is no configuration, it will show something like:

bash

nftables v1.0.2 (Luna Moon) 

4. Practical Example: Basic Firewall with nftables

Next, we will create a basic set of rules to protect a server.

A. Create Table and Chains

bash

sudo nft add table inet myfw 

sudo nft add chain inet myfw input  { type filter hook input priority 0 \; policy drop \; } 

sudo nft add chain inet myfw output { type filter hook output priority 0 \; policy accept \; } 

sudo nft add chain inet myfw forward { type filter hook forward priority 0 \; policy drop \; } 

This sets a default block policy for incoming and forwarded traffic and allows outgoing traffic.

B. Allow Essential Traffic

bash

# Allow established connections 

sudo nft add rule inet myfw input ct state established,related accept 

# Allow loopback (localhost) 

sudo nft add rule inet myfw input iif lo accept 

# Allow SSH 

sudo nft add rule inet myfw input tcp dport 22 ct state new accept 

# Allow ping 

sudo nft add rule inet myfw input icmp type echo-request accept 

5. Save and Restore Configuration

Save current rules

bash

sudo nft list ruleset > /etc/nftables.conf 

Make it load on startup

bash

sudo systemctl enable nftables 

The file /etc/nftables.conf will load automatically.

6. Key Advantages for Perimeter Security Environments

Advantage | Practical Description
Clean Language | Easier to teach and audit.
Support for Objects and Sets | Ideal for efficiently filtering multiple IPs or ports.
IPv4/IPv6 Compatibility | Unified rules reduce errors.
Extensibility | Supports statistics, detailed logging, and rule tracing.
Transition from iptables | You can use iptables-translate to migrate.

7. Practical Tips for Teaching nftables

• Compare an iptables rule vs a nft rule live.

• Use colors or explanatory comments for rules.

• Generate errors on purpose to teach debugging.

• Encourage the use of nft -a list ruleset to view rule IDs and facilitate editing.

• Promote organized .nft scripts by zones: public, internal, VPN.

Quick Glossary

Term | Meaning
table | Grouping of rules by family (inet, ip, arp, etc.).
chain | Ordered list of rules attached to a kernel hook.
rule | Conditional instruction that accepts, blocks, or modifies a packet.
hook | Interception point: input, output, forward, etc.
priority | Evaluation order compared to other rules (default zero).

nftables represents the future of packet filtering in Linux. Its modular, readable, and efficient design makes it a fundamental tool for network administrators, cybersecurity professionals, and technical trainers. Understanding and practically using it opens the door to granular and modern perimeter security control in both professional and academic environments.

Chapter 22: Comparison: iptables vs nftables

Chapter Objectives

• Understand the motivations behind the development of nftables.

• Compare the technical features, syntax, performance, and flexibility between iptables and nftables.

• Conduct parallel practical examples to visualize their differences.

• Prepare educators and students for the migration or teaching of both approaches.

Context

For years, iptables has been the standard for firewalls on Linux systems. However, as network needs evolved, its structure began to show limitations. In response, nftables was introduced by the Netfilter project and the Linux kernel to progressively replace iptables, ip6tables, arptables, and ebtables.

Since kernel 3.13 (2014), nftables has been officially included and recommended for new configurations.

Conceptual Differences

Feature | iptables | nftables
Backend | Netfilter | Netfilter (with new infrastructure)
Main Tool | iptables | nft
Architecture | Based on separate commands (IPv4, IPv6, ARP) | Unified
Syntax | Verbose, line-by-line | Modern, structured, script-like
Tables and Chains | Separate tables by family | Multipurpose tables
Performance | Good | Better scalability, superior performance
Set Support | Limited, inefficient | Efficient, integrated
Logging | Limited | More flexible with expressions
Project Status | Maintenance (legacy) | Active and evolving

Practical Comparison

Scenario: Allow SSH access and block everything else

With iptables:

bash

iptables -F 

iptables -P INPUT DROP 

iptables -P FORWARD DROP 

iptables -P OUTPUT ACCEPT 

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT 

iptables -A INPUT -p tcp—dport 22 -j ACCEPT 

With nftables:

bash

nft add table inet filter 

nft add chain inet filter input { type filter hook input priority 0; policy drop; } 

nft add rule inet filter input ct state established,related accept 

nft add rule inet filter input tcp dport 22 accept 

Advantages in nftables:

• Less repetition.

• Handles both IPv4 and IPv6 simultaneously (inet).

• Clearer and more modular syntax.

Tables, Chains, and Rules

iptables

• Uses multiple binaries: iptables, ip6tables, arptables, etc.

• Each protocol has its own table (filter, nat, mangle).

• Less consistent in design.

nftables

• Unified architecture with a single CLI (nft).

• A set of tables/chains for all network families.

• Support for sets, maps, and expressions.

Advanced Example: Blocking Multiple IPs

With iptables (repetitive):

bash

iptables -A INPUT -s 192.168.1.10 -j DROP 

iptables -A INPUT -s 192.168.1.11 -j DROP 

iptables -A INPUT -s 192.168.1.12 -j DROP 

With nftables (using sets):

bash

nft add set inet filter blacklist { type ipv4_addr; flags interval; } 

nft add element inet filter blacklist { 192.168.1.10, 192.168.1.11, 192.168.1.12 } 

nft add rule inet filter input ip saddr @blacklist drop 

Using sets in nftables is much more efficient, especially for dynamic rules or those with many conditions.

Example: Port Forwarding

With iptables:

bash

iptables -t nat -A PREROUTING -p tcp—dport 8080 -j DNAT—to-destination 192.168.1.100:80 

iptables -A FORWARD -p tcp -d 192.168.1.100—dport 80 -j ACCEPT 

With nftables:

bash

nft add table ip nat 

nft add chain ip nat prerouting { type nat hook prerouting priority 0; } 

nft add rule ip nat prerouting tcp dport 8080 dnat to 192.168.1.100:80 

Advantages: nftables separates NAT and filtering into different tables, but within the same CLI and conceptual schema, reducing overall complexity.

Compatibility and Migration

Compatibility:

• iptables-nft and iptables-legacy are compatible on many systems.

• Some systems still use iptables by default, but nftables can be compiled.

Useful Tools:

bash

iptables-save > rules.v4 

iptables-restore < rules.v4 

For nftables:

bash

nft list ruleset > rules.nft 

nft -f rules.nft 

Automatic Conversion:

Use iptables-translate to convert rules to nftables format:

bash

iptables-translate -A INPUT -p tcp—dport 22 -j ACCEPT 

Output:

bash

nft add rule ip filter INPUT tcp dport 22 counter accept 

What Should Educators Teach?

• Introduce general concepts with iptables due to its simplicity.

• Progressively transition to nftables for intermediate and advanced students.

• Promote good documentation and scripting practices (nft -f).

• Teach through parallels and comparative labs.

• Highlight the performance and long-term maintenance benefits.

When to Use One or the Other

Case | Recommendation
Old Systems (pre-2018) | iptables
New Installations | nftables
Gradual Migration | Both (compatibility mode)
High Traffic or Complex Rules | nftables

The transition from iptables to nftables represents a natural step toward more modern, scalable, and powerful firewall management. Although iptables remains valid and useful, nftables offers a unified approach, modern syntax, and superior performance, making it ideal for teaching current perimeter security.

Chapter 23: Syntax and Concepts of nftables

Chapter Objectives

• Understand the basic structure of the nftables language.

• Familiarize yourself with the key components: tables, chains, rules, sets, and data types.

• Learn how to write readable and functional rules.

• Prepare to build configurations from scratch using a modular approach.

Introduction

nftables replaces iptables as the modern framework for packet filtering on Linux. Its great strength is a structured and readable syntax, inspired by modern scripting languages. Through a unified CLI (nft), it manages filtering rules, NAT, connection control, IP sets, counters, and more.

Unlike iptables, which requires multiple tools for different protocols (IPv4, IPv6, ARP), nftables uses a consistent syntax for all network families.

Fundamental Concepts

Tables (tables)
A table is the main container. It defines the context for the rules.

bash

nft add table inet filter

"inet" allows combined rules for both IPv4 and IPv6 (ideal for most cases).

Chains (chains)
Chains are lists of rules. They can be attached to a hook (kernel hook).

bash

nft add chain inet filter input {

type filter hook input priority 0;

policy drop;

}

Common hook types:

• input: Incoming traffic to the local system.

• output: Outgoing traffic from the system.

• forward: Traffic passing through the system (e.g., router/firewall).

Policy (policy):

Determines the default behavior (accept, drop).

Rules (rules)
A rule defines a condition and an action.

bash

nft add rule inet filter input ip protocol icmp accept

This rule accepts incoming ICMP packets (like pings).

Sets (sets)
They allow handling multiple IP addresses, ports, or ranges efficiently.

bash

nft add set inet filter blacklist { type ipv4_addr; }

nft add element inet filter blacklist { 192.168.1.10, 192.168.1.20 }

nft add rule inet filter input ip saddr @blacklist drop

Practical Syntax

Create a table, chain, and rule in three steps:

bash

nft add table inet mytable 

nft add chain inet mytable mychain { type filter hook input priority 0; policy drop; } 

nft add rule inet mytable mychain tcp dport 22 accept

Explanation:

• Creates a table named mytable.

• Within it, defines an input chain that drops everything by default.

• Adds a rule to accept TCP connections to port 22 (SSH).

Explanation by Components

a) Families (inet, ip, ip6, arp, bridge)

• ip: Only IPv4.

• ip6: Only IPv6.

• inet: Combined IPv4 and IPv6 (recommended).

• arp: ARP traffic.

• bridge: Bridge networks.

b) Priority (priority)

Defines the order of execution within hooks. Some typical values:

Purpose | Priority
NAT prerouting | -100
Filtering | 0
NAT postrouting | 100

c) Data Types

• ip saddr: Source IP address.

• ip daddr: Destination IP address.

• tcp dport: Destination port in TCP.

• udp sport: Source port in UDP.

• ct state: Connection state (e.g., established, new).

Complete Example

bash

nft flush ruleset

nft add table inet filter

nft add chain inet filter input {

type filter hook input priority 0;

policy drop;

}

nft add rule inet filter input ct state established,related accept

nft add rule inet filter input tcp dport 22 accept

nft add rule inet filter input tcp dport 80 accept

nft add rule inet filter input tcp dport 443 accept

This script configures a basic firewall that allows incoming traffic for SSH, HTTP, and HTTPS, and drops everything else.

Visualizing the Rule Set

Use:

bash

nft list ruleset

Expected output (a readable summary of the entire configuration):

bash

table inet filter {

chain input {

type filter hook input priority 0; policy drop;

ct state established,related accept

tcp dport 22 accept

tcp dport 80 accept

tcp dport 443 accept

}

}

Teaching Tips

• Teach the concepts from general (table/chain/rule) to specific (protocols, ports, sets).

• Encourage the use of inet instead of separating IPv4 and IPv6.

• Use nft -f file.nft to keep rules in easy-to-read, teachable, and versionable files.

• Practice each concept with mini-exercises: create a table, add a rule, use sets, change policies.

Best Practices

• Always use flush when starting tests to avoid conflicts from previous configurations.

• Name tables and chains clearly.

• Document rules in .nft files.

• Simulate traffic with tools like curl, ping, nmap, etc.

• Combine sets and maps for more complex but organized rules.

nftables offers a modern, clear, and powerful syntax that significantly overcomes the limitations of iptables. Mastering its structure is essential for developing maintainable, efficient, and secure firewalls in educational and professional environments. Teaching it modularly and with practical examples ensures an accessible and lasting learning curve.

Chapter 24: Configuring Tables, Chains, and Rules in nftables

Chapter Objectives

• Understand how to create and configure tables, chains, and rules in nftables.

• Apply logical structures to organize firewall rules in a modular and secure manner.

• Create real configurations in a controlled environment for educational and productive purposes.

• Introduce versioning practices and documentation for configurations.

Key Concepts

Before diving into practice, let's review the three main components that govern nftables configuration:

Component | Description
Table | Containing structure that groups chains.
Chain | Ordered collection of rules with a defined behavior.
Rule | Instruction that determines what to do with traffic that matches certain criteria.

1. Creating Tables

Basic Syntax:

bash

nft add table <family> <table_name>

Practical Example:

bash

nft add table inet myfirewall

A table named myfirewall has been created in the inet family (which handles both IPv4 and IPv6). This will serve as the base for chains and rules.

2. Configuring Chains

Basic Syntax:

bash

nft add chain <family> <table> <chain> {

type <type>;

hook <hook>;

priority <number>;

policy <accept|drop>;

}

Important Fields:

• type: filter, nat, route, etc.

• hook: input, output, forward, prerouting, postrouting.

• priority: Execution order.

• policy: Default behavior if no match is found.

Example: Input chain that drops everything by default

bash

nft add chain inet myfirewall input {

type filter hook input priority 0;

policy drop;

}

3. Adding Rules

Rules are added to an existing chain. They consist of a condition (what traffic to evaluate) and an action (what to do with it).

Basic Syntax:

bash

nft add rule <family> <table> <chain> <condition> <action>

Example 1: Allow SSH Traffic

bash

nft add rule inet myfirewall input tcp dport 22 accept

This accepts TCP connections destined for port 22 (SSH).

Example 2: Allow Established Traffic

bash

nft add rule inet myfirewall input ct state established,related accept

Essential to not break valid connections.

Example 3: Block a Range of IPs

bash

nft add set inet myfirewall blacklist { type ipv4_addr; }

nft add element inet myfirewall blacklist { 192.168.1.100, 192.168.1.101 }

nft add rule inet myfirewall input ip saddr @blacklist drop

Using sets to efficiently manage multiple IPs.

4. Guided Step-by-Step Exercise

Here’s a complete and modular practice:

Objective:

Build a basic firewall with the following conditions:

• Allow SSH, HTTP, HTTPS connections.

• Block all other non-established accesses.

• Log everything that is dropped.

Steps:

a) Clear previous rules

bash

nft flush ruleset

b) Create the table

bash

nft add table inet myfirewall

c) Create the input chain

bash

nft add chain inet myfirewall input {

type filter hook input priority 0;

policy drop;

}

d) Add rules

bash

# Allow established connections

nft add rule inet myfirewall input ct state established,related accept

# Allow SSH

nft add rule inet myfirewall input tcp dport 22 accept

# Allow HTTP/HTTPS

nft add rule inet myfirewall input tcp dport 80 accept

nft add rule inet myfirewall input tcp dport 443 accept

# Log and drop the rest

nft add rule inet myfirewall input log prefix "DROP_LOG: " flags all

5. Persistence of Configuration

Save the current rule set:

bash

nft list ruleset > /etc/nftables.conf

To ensure it loads on startup, enable the service:

bash

systemctl enable nftables 

systemctl start nftables

Best Practices

Practice | Justification
Name tables and chains logically | Eases maintenance.
Use the inet family | Simplifies configuration for both IPv4 and IPv6.
Separate traffic by chains | E.g., input, output, forward.
Log what gets blocked | Useful for auditing and troubleshooting.
Save copies in .nft files | Enables versioning with Git, teaching, and reuse.

Recommended Structure for Educational Projects

bash

/project-firewall/

│

├── rules/

│  ├── base.nft

│  ├── ssh_web.nft

│  └── blacklist.nft

│

├── docs/

│  └── rule_explanation.md

│

└── practices/

└── activity1_basic_config.md

Mini-Challenge for the Classroom

Activity: Create a firewall on a VM that only allows SSH access from a specific IP, blocks everything else, and logs any blocked connection attempts.

Mastering the creation of tables, chains, and rules in nftables is essential for building robust and adaptable firewalls. This chapter provides the technical and practical foundations necessary to teach and apply real configurations, with a modular, organized, and professional approach.

Chapter 25: Practical Use Cases with nftables

Chapter Objective

The objective of this chapter is to consolidate the knowledge learned about nftables through real and reproducible scenarios, focusing on solving common problems faced by network administrators, instructors, and technicians. Each case will be broken down step by step and designed to be replicated by students in virtual or physical labs.

Chapter Structure

Each case will include:

Realistic problem context.

Scenario requirements.

Suggested topology (optional).

Detailed firewall configuration.

Functional tests.

Suggested variations for teaching practice.

Case 1: Public Web Server with Restricted SSH Access

Scenario:

A server in the DMZ hosts a website accessible from the internet, but SSH access should only be allowed from the administrator's local network (192.168.1.0/24).

Requirements:

• Allow HTTP (80) and HTTPS (443) traffic from any source.

• Allow SSH only from 192.168.1.0/24.

• Block everything else.

• Log blocked access attempts.

Rules:

bash

# Create table and chain

nft add table inet webdmz

nft add chain inet webdmz input { type filter hook input priority 0; policy drop; }

# Accept established traffic

nft add rule inet webdmz input ct state established,related accept

# Allow HTTP/HTTPS

nft add rule inet webdmz input tcp dport {80,443} accept

# Allow SSH only from admin network

nft add rule inet webdmz input ip saddr 192.168.1.0/24 tcp dport 22 accept

# Log and drop the rest

nft add rule inet webdmz input log prefix "DROP_WEB: " flags all

Case 2: Student Desktop Firewall

Scenario:

A student workstation must be able to browse the internet, use SSH to class servers, and block any unsolicited incoming connections.

Requirements:

• Allow outgoing connections to HTTP, HTTPS, DNS, and SSH.

• Allow return traffic (related/established state).

• Block unsolicited incoming connections.

Rules:

bash

nft add table inet desktop

nft add chain inet desktop input { type filter hook input priority 0; policy drop; }

nft add chain inet desktop output { type filter hook output priority 0; policy accept; }

# Allow established or related connections

nft add rule inet desktop input ct state established,related accept

# Block the rest with logging

nft add rule inet desktop input log prefix "DROP_DESKTOP: " flags all

No explicit rules are needed for output, as the policy is set to "accept." This promotes normal browsing and usage.

Case 3: Router with NAT and Port Forwarding

Scenario:

A Linux router connecting an internal network to the internet must perform NAT and allow external connections to access an internal web server.

Requirements:

• Perform NAT for the internal network (192.168.10.0/24).

• Redirect external connections to port 8080 to an internal server at 192.168.10.10:80.

• Log NAT packets.

Rules:

bash

# Create NAT table

nft add table ip nat

# Prerouting and postrouting chains

nft add chain ip nat prerouting { type nat hook prerouting priority -100; }

nft add chain ip nat postrouting { type nat hook postrouting priority 100; }

# Redirect external port to internal server

nft add rule ip nat prerouting iif "eth0" tcp dport 8080 dnat to 192.168.10.10:80

# NAT (masquerade) for internet outgoing

nft add rule ip nat postrouting oif "eth0" ip saddr 192.168.10.0/24 masquerade

Case 4: Segmentation Between Student Groups

Scenario:

A test machine has several interfaces for different working groups: group1, group2, and the internet. The groups should not communicate with each other, but both must have access to the internet.

Requirements:

• Block traffic between group1 and group2.

• Allow access to the internet from both groups.

• Allow responses from the internet to both groups.

Rules:

bash

nft add table inet campusfw

nft add chain inet campusfw forward { type filter hook forward priority 0; policy drop; }

# Allow responses

nft add rule inet campusfw forward ct state established,related accept

# Block traffic between groups

nft add rule inet campusfw forward iif "group1" oif "group2" drop

nft add rule inet campusfw forward iif "group2" oif "group1" drop

# Allow traffic to the internet

nft add rule inet campusfw forward iif "group1" oif "internet" accept

nft add rule inet campusfw forward iif "group2" oif "internet" accept

Class Variations:

• Add restrictions by port or protocol.

• Add blacklists by IP or range.

• Introduce intentional delays to simulate latencies.

• Ask students to write the same logic in .nft scripts with comments.

Proposed Final Teaching Activity

Title: Design and Document Your Own Firewall Policy

Instructions:

Propose a real scenario (your home network, the classroom, an IoT network, etc.).

Clearly define the allowed and denied accesses.

Design a complete configuration with nftables.

Justify each rule and table structure.

Perform tests with curl, ping, nmap, etc.

Present the results and generate a functional .nft file.

Practical use cases not only consolidate technical knowledge but also form a foundation for active teaching and solving real-world problems. Mastering the creation of specific policies using tables, chains, and rules in nftables is key for any perimeter security professional and an invaluable resource in training new cybersecurity specialists.

Chapter 26: Security Policies with nftables

Chapter Objective

In this chapter, you will learn how to design, implement, and maintain effective security policies using nftables. This component is fundamental for protecting network infrastructures, servers, and workstations, ensuring that only legitimate and necessary traffic is allowed.

What is a Security Policy in Firewalls?

A security policy in nftables is a set of carefully designed rules that define:

• What types of traffic are allowed.

• What types of traffic should be blocked.

• How the firewall behaves in case of traffic that is not explicitly defined.

These policies are organized through:

• Tables

• Chains

• Rules

• Default policies

Technical Fundamentals

Tables

Contain chains and rules. Multiple tables can be created for each protocol type (ip, inet, ip6, arp).

bash

nft add table inet myfirewall

Chains

Chains are blocks of rules executed at specific points in the packet flow (hooks): input, output, forward, etc.

bash

nft add chain inet myfirewall input { type filter hook input priority 0; policy drop; }

Default Policies

This is the behavior for packets that do not match any rule.

bash

policy drop;  # Recommended security

Key Principles of a Secure Policy

Default Deny: Only allow explicitly necessary traffic.

Least Privilege: Allow only what is required.

Network Segmentation: Isolate zones (DMZ, users, administration).

Event Logging: Log rejected accesses for analysis.

State Handling: Accept established and related connections.

Practical Example: Basic Secure Server Policy

Scenario: Web server with SSH access only from a specific IP.

Objectives:

• Allow HTTP/HTTPS (ports 80 and 443) from any source.

• Allow SSH only from IP 192.168.1.100.

• Block everything else.

• Log blocked attempts.

Step-by-step Implementation

bash

# Create table and chain

nft add table inet servidor

nft add chain inet servidor input { type filter hook input priority 0; policy drop; }

# Allow established connections

nft add rule inet servidor input ct state established,related accept

# HTTP and HTTPS

nft add rule inet servidor input tcp dport {80, 443} accept

# SSH from authorized IP

nft add rule inet servidor input ip saddr 192.168.1.100 tcp dport 22 accept

# Log everything else

nft add rule inet servidor input log prefix "Server Block: " flags all

Common Policy Types

Network Type | Main Feature | Recommended Policy
Public Server | Exposed to the internet | Allow only necessary services + logging
Workstation | Browsing + Outgoing SSH | Accept output, filter input
Router/NAT | Routing + Port Forwarding | Forward filtering, explicit NAT
IoT/Embedded | Very limited connectivity | Strict whitelist, no input, only outgoing connections

Case Study: Academic Network Policy

Context: A student network divided into VLANs. Each group must have access to the internet, but not to each other. Only teachers can access via SSH.

Simplified Solution

bash

# Table and chain

nft add table inet campus

nft add chain inet campus forward { type filter hook forward priority 0; policy drop; }

# Established and related

nft add rule inet campus forward ct state established,related accept

# Internet access

nft add rule inet campus forward iifname "vlan10" oifname "eth0" accept

nft add rule inet campus forward iifname "vlan20" oifname "eth0" accept

# Block between VLANs

nft add rule inet campus forward iifname "vlan10" oifname "vlan20" drop

nft add rule inet campus forward iifname "vlan20" oifname "vlan10" drop

# Allow SSH to servers only from the teacher VLAN

nft add rule inet campus forward iifname "vlan30" oifname "srv_net" tcp dport 22 accept

Recommendations for Teachers

• Start by explaining open policies (allow all) to show vulnerabilities.

• Then introduce progressively restrictive policies.

• Use virtual environments to test and adjust rules.

• Create tasks where students document, apply, and test their own policies.

Suggested Activity

Challenge: Design and apply a security policy for a simulated home network.

The student creates a security table.

Defines which services to use (DNS, HTTP, ping, SSH, etc.).

Blocks everything not specified.

Tests the rules with tools (ping, curl, nmap, etc.).

Documents results and fixed errors.

Final Tips

• Always use ct state for state handling to reduce errors.

• Clear policies prevent problems and are easier to maintain.

• Keep your scripts under version control (git) and use comments in each rule.

Security policies in nftables are the core of robust perimeter defense. Implementing them correctly requires understanding the services that need protection, the network environment, and potential threats. This chapter lays the foundation for students and educators not only to apply rules but also to design them with consideration and purpose.

Chapter 27: Integration with Scripts and systemd

Chapter Objective

You will learn how to integrate your nftables configuration with automated scripts and the systemd init system in modern Linux distributions. This approach ensures that firewall policies are automatically applied at system startup and provides a solid foundation for maintaining secure and reproducible environments.

Why Automate?

Configuring nftables manually is useful for quick tests but is neither sustainable nor secure in the long term. If you reboot the system, all manually loaded rules will disappear. To avoid this:

• We persist rules in a file or script.

• We integrate with systemd to apply them at boot.

• We centralize security management in a reliable and controlled source.

Recommended File Structure

A good practice is to keep your rules organized:

bash

/etc/nftables/

├── firewall.nft  # Main rules

├── interfaces.nft  # Rules per interface

├── services.nft  # Rules per ports/services

├── logging.nft  # Logging rules

└── scripts/

└── apply-firewall.sh  # Automated load script

Creating a Load Script

Example: apply-firewall.sh

bash

#!/bin/bash

# File: /etc/nftables/scripts/apply-firewall.sh

echo "Loading nftables rules..."

nft flush ruleset

nft -f /etc/nftables/firewall.nft

if [ $? -eq 0 ]; then

echo "✔ Rules loaded successfully."

else

echo "❌ Error applying rules."

exit 1

fi

Don't forget to make it executable:

bash

chmod +x /etc/nftables/scripts/apply-firewall.sh

Example of Modular Rules File

Main file: /etc/nftables/firewall.nft

#!/usr/sbin/nft -f

table inet myfirewall {

include "/etc/nftables/interfaces.nft"

include "/etc/nftables/services.nft"

include "/etc/nftables/logging.nft"

}

Services file: /etc/nftables/services.nft

chain input {

type filter hook input priority 0; policy drop;

ct state established, related accept

iifname "lo" accept

tcp dport 22 accept  # SSH

tcp dport 80 accept  # HTTP

tcp dport 443 accept  # HTTPS

}

Integration with systemd

To load the rules automatically at system boot, you can use two methods:

Method 1: Use the native nftables.service

Many systems already include the nftables service integrated with:

bash

/etc/nftables.conf

Simply copy your main rules to this file:

bash

cp /etc/nftables/firewall.nft /etc/nftables.conf

And enable the service:

bash

systemctl enable nftables

systemctl start nftables

This is the recommended method for most environments.

Method 2: Create a Custom Service

If you want more control or your distribution does not include nftables.service, create a new service:

/etc/systemd/system/custom-nftables.service

[Unit]

Description=Custom Firewall with nftables

After=network.target

[Service]

Type=oneshot

ExecStart=/etc/nftables/scripts/apply-firewall.sh

RemainAfterExit=yes

[Install]

WantedBy=multi-user.target

Then activate it with:

bash

systemctl daemon-reexec

systemctl enable custom-nftables

systemctl start custom-nftables

Advantages of this Integration

Feature | Benefit
Modular scripts | Greater clarity, maintenance, and reuse
Automatic loading with systemd | Guaranteed security from startup
Logging and validation | Easy diagnostics and auditing
Customization per environment | Adapt rules to each server or virtual classroom

Didactic Approach for the Classroom

• Guided activity: have each student write a script with customized rules and integrate it into systemd.

• Common mistakes: missing execution permissions or incorrect paths.

• Practical evaluation: reboot the VM and verify if the rules load correctly.

Proposed Exercise

Objective: Automate the firewall in a test workstation.

Create the modular file structure.

Define basic rules: loopback, SSH, web browsing.

Write the load script.

Integrate with systemd (use method 1 or 2).

Validate with nft list ruleset after reboot.

Security Tip

Before applying a script or restarting rules, make sure you have physical or console access. Avoid locking yourself out, especially in network or remote access environments.

Integrating nftables with scripts and systemd not only professionalizes your network configuration but also enables teachers and students to create secure, reproducible, and automated environments. This is essential for quality practical teaching and for real-world production operations.

Chapter 28: Practical Project — Complete Firewall with nftables

Chapter Objective

The purpose of this project is to build, test, and automate a realistic firewall using nftables. The student or instructor will learn to:

• Design rules by zones and interfaces.

• Control public and private services.

• Implement NAT and logging.

• Automate the loading with systemd.

• Validate, document, and version the configuration.

By the end, you will have a functional and secure firewall, ready for production or virtual classrooms.

Simulated Scenario

Project environment:

• Linux Debian/Ubuntu or derivatives machine.

• Three interfaces:

o eth0: Internet (external zone).

o eth1: Internal LAN (teachers/students).

o eth2: DMZ (public services zone).

• Exposed services:

o HTTP(S) in the DMZ.

o Internal SSH only for LAN.

o Outgoing DNS from LAN.

Requirements:

• Filter traffic according to zone.

• Allow only explicitly defined traffic.

• Apply NAT for LAN outbound traffic.

• Log rejected packets.

File Structure

bash

/etc/nftables/

├── firewall.nft  # Main file

├── interfaces.nft  # Interfaces definitions

├── zones.nft  # Zones and groups definitions

├── input-lan.nft  # Input rules from LAN

├── input-dmz.nft  # Input rules from DMZ

├── input-wan.nft  # Input rules from WAN

├── forward.nft  # Forwarding and NAT rules

├── logging.nft  # Logging rules

├── sets.nft  # Trusted IPs or blacklist

└── scripts/

└── apply.sh  # Load script with verification

Step 1: Create Tables and Define Zones

firewall.nft

nft

#!/usr/sbin/nft -f

flush ruleset

table inet myfw {

include "zones.nft"

include "interfaces.nft"

include "sets.nft"

include "input-lan.nft"

include "input-dmz.nft"

include "input-wan.nft"

include "forward.nft"

include "logging.nft"

}

Step 2: Define Interfaces and Zones

zones.nft

nft

chain prerouting {

type filter hook prerouting priority -300;

}

chain input {

type filter hook input priority 0; policy drop;

}

chain forward {

type filter hook forward priority 0; policy drop;

}

chain output {

type filter hook output priority 0; policy accept;

}

interfaces.nft

nft

define wan = eth0

define lan = eth1

define dmz = eth2

Step 3: Create Rules by Zone

input-lan.nft

nft

chain input {

iifname $lan ct state established, related accept

iifname $lan ip protocol icmp accept

iifname $lan tcp dport 22 accept

}

input-dmz.nft

nft

chain input {

iifname $dmz tcp dport { 80, 443 } accept

}

input-wan.nft

nft

chain input {

iifname $wan ct state established, related accept

iifname $wan drop

}

Step 4: NAT and Forwarding

forward.nft

nft

chain forward {

# Allow LAN to WAN

iifname $lan oifname $wan ct state new, established, related accept

# Allow LAN to DMZ

iifname $lan oifname $dmz ct state new, established, related accept

# Drop everything else

drop

}

chain postrouting {

type nat hook postrouting priority 100;

oifname $wan masquerade

}

Step 5: Logging Suspicious Activity

logging.nft

nft

chain input {

log prefix "INPUT DROP: " flags all

drop

}

chain forward {

log prefix "FORWARD DROP: " flags all

drop

}

Step 6: Trust or Block Lists

sets.nft

nft

set blacklist {

type ipv4_addr;

flags timeout;

timeout 1h;

elements = { 192.168.1.100 }

}

chain input {

ip saddr @blacklist drop

}

Step 7: Load and Verification Script

scripts/apply.sh

bash

#!/bin/bash

echo "[INFO] Applying nftables rules..."

nft flush ruleset

nft -f /etc/nftables/firewall.nft

if [ $? -eq 0 ]; then

echo "[OK] Rules applied successfully."

else

echo "[ERROR] Failed to apply rules."

exit 1

fi

nft list ruleset

Assign execution permissions:

bash

chmod +x /etc/nftables/scripts/apply.sh

Step 8: Automate with systemd

Custom service:

# /etc/systemd/system/nftables-project.service

[Unit]

Description=Complete firewall with nftables

After=network.target

[Service]

Type=oneshot

ExecStart=/etc/nftables/scripts/apply.sh

RemainAfterExit=yes

[Install]

WantedBy=multi-user.target

bash

systemctl daemon-reexec

systemctl enable nftables-project

systemctl start nftables-project

Final Verification

• Verify rules with nft list ruleset

• Test SSH, HTTP, HTTPS access

• Check logs with journalctl or /var/log/syslog

• Perform scans from LAN and WAN (for example with Nmap)

• Attempt to use blocked IPs in the blacklist set

Suggested Evaluation

Criteria | Points
Functional and error-free firewall | 30
Modular and maintainable structure | 20
Logging and operational diagnostics | 15
Integration with systemd | 15
Internal code documentation | 10
Use of sets (dynamic lists) | 10

This project summarizes and applies all previous concepts, giving the student or instructor a realistic, fully functional firewall platform. Implementing and testing it is an excellent way to consolidate perimeter security skills, automation best practices, and professional documentation.

Chapter 29: Teaching Debugging and Logging with nftables

Chapter Objective

The purpose of this chapter is to train the student and the instructor in the use of practical debugging and event logging techniques in nftables—essential skills for:

• Verifying that rules work as expected.

• Auditing access and detecting intrusions.

• Diagnosing connectivity issues or configuration errors.

• Strengthening traceability and policy compliance.

The focus will be entirely practical, with examples that can be replicated in class or virtual labs.

Fundamental Concepts

Before starting with the exercises, it's important to remember:

• nftables allows rules with logging using the log statement.

• The generated logs can be viewed with journalctl, dmesg, or in /var/log/.

• The order of the rules and the use of ct state are key to avoid unnecessary logs.

• You can debug rule behavior with tools like nft monitor, tcpdump, and nmap.

Environment Preparation

Requirements:

• Debian/Ubuntu system with nftables installed.

• Access as root or user with privileges.

• Minimum services enabled: SSH, optional HTTP.

• Editor like nano, vim, or code.

Create base file:

bash

sudo mkdir -p /etc/nftables/logging/

cd /etc/nftables/logging/

sudo nano debug-logging.nft

1. Introduction to Logging with nftables

Basic Syntax

nft

log prefix "FIREWALL DROP: " group 0 flags all

• prefix: Custom text that will appear in the logs.

• group: Kernel logging group (default 0).

• flags all: Includes MAC, IP, ports, interfaces, etc.

Example rule with logging

nft

table inet filter {

chain input {

type filter hook input priority 0;

policy drop;

ct state established, related accept

tcp dport 22 accept

ip protocol icmp accept

log prefix "INPUT REJECTED: " flags all

drop

}

}

2. Exercise: Capture Blocking Events

Step by step:

Apply the above file:

bash

sudo nft -f debug-logging.nft

In another terminal, try to ping from another host to this machine.

Check the logs:

bash

sudo journalctl -f | grep "INPUT REJECTED"

You can also see them in real-time with:

bash

sudo dmesg | grep "INPUT REJECTED"

Class discussion: What fields were logged? Can you identify the source IP and protocol?

3. Visual Debugging with nft monitor

nftables allows monitoring rules, packets, and updates in real time.

Command:

bash

sudo nft monitor trace

This command shows the exact path of a packet through the rules.

Suggested exercise: Start nft monitor trace, then from another terminal, ping or connect via SSH. Analyze how the packet travels through each chain.

4. Debugging Configuration Errors

Most common errors:

Error | Symptom | Solution
Chain not linked | Rule never executes | Check if the chain is included
Duplicate rules | Ineffective or redundant rules | Use nft list ruleset and clean rules
Excessive logging | Logs or CPU saturation | Limit with limit rate
Misconfigured NAT | No external navigation | Check masquerade and chain order

Example: Limit logging

nft

log prefix "DOS ATTEMPT: " flags all limit rate 5/second

5. Guided Diagnostic Activity

Create an environment with the following conditions:

• Allow SSH only from LAN.

• All HTTP packets must be blocked.

• All non-allowed traffic is logged.

• The student must identify why a service (e.g., HTTP) does not work.

Students must use nft monitor, journalctl, and tcpdump to discover what is blocking the traffic.

6. Logging to Files

By default, messages go to the kernel buffer. To send them to files:

Configure rsyslog:

bash

sudo nano /etc/rsyslog.d/30-nftables.conf

Add:

conf

:msg, contains, "FIREWALL" /var/log/nftables.log

& stop

Restart service:

bash

sudo systemctl restart rsyslog

View logs:

bash

tail -f /var/log/nftables.log

7. Pedagogical Suggestions

• Divide the class into groups: some simulate attacks, others observe logs.

• Practical tasks: submit log files with event explanations.

• Guided evaluations: ask the student to explain why certain traffic was blocked using logs.

• Attack simulation: use nmap, hping3, or curl to generate test traffic.

Logging and debugging with nftables is a key skill for every cybersecurity professional. This chapter provides a solid foundation to teach how to track, debug, and analyze network traffic using system tools, well-designed rules, and pedagogical methodologies.

Extra Resources for Classes

• Rule templates with and without logging.

• Scripts to simulate scans.

• Log captures with explanations.

• Quick debugging command cheat sheet.

Chapter 30: Common Mistakes When Teaching nftables

Chapter Objective

This chapter aims to identify, analyze, and avoid the most common mistakes made when teaching nftables, both from a technical and pedagogical perspective. Its focus is aimed at educators who wish to improve the quality of their students' learning in perimeter security topics, specifically in the implementation, understanding, and effective use of nftables-based firewalls.

1. Mistake #1: Teaching Without Contextualizing the Replacement of iptables

What happens

Many instructors begin teaching nftables without clearly explaining why it replaces iptables, which leads to confusion among students who already know or have heard of iptables.

Correct approach

Start with a brief history and technical justification:

• nftables replaces iptables, ip6tables, arptables, and ebtables.

• It was designed by the netfilter team as a unified, more efficient solution with a structured syntax.

• It introduces reusable objects, expressions, and greater traceability capabilities.

Recommended activity: Compare side by side two similar rules in iptables and nftables.

2. Mistake #2: Skipping the Theory of Network Models

What happens

Many students do not understand why rules are placed in certain hooks (input, forward, output). This is because the network models and packet flow are not adequately explained.

Correct approach

Dedicate a session to key concepts:

• OSI model vs TCP/IP model

• Packet flow according to device role (router vs endpoint)

• Meaning and use of hooks (input, output, forward, prerouting, postrouting)

Practical resource: Use diagrams or flow simulators to show how a packet flows to and from a device.

3. Mistake #3: Introducing Complex Rules Too Early

What happens

Trying to teach complex rules involving multiple conditions, sets, or expressions from the start causes cognitive overload.

Correct approach

Adopt a layered progression:

Simple rules (allow/deny by port)

Introduction of protocols and addresses

Use of sets

Conditional cases with meta, ct, etc.

Incremental lab: Each student improves a previous version of the firewall.

4. Mistake #4: Not Teaching Persistence Properly

What happens

Rules are configured live (nft add rule ...) but students are not taught how to save and apply them persistently, leading to loss of rules after a reboot.

Correct approach

Introduce from the start:

• Use of .nft files and nft -f

• How to automate with systemd or startup scripts

• Useful commands: nft list ruleset, nft flush ruleset

Practical exercise: Create and test a systemd service that restores the rules.

5. Mistake #5: Not Teaching Logging and Debugging

What happens

Students lack tools to verify if their firewall works correctly, leading to frustration or the feeling that "it doesn't work."

Correct approach

Always include a section on:

• Logging with log prefix

• Using nft monitor trace

• Analysis with journalctl and tcpdump

Teaching tips:

• Simulate a connectivity failure and have the student solve it with traces and logs.

• Introduce intentional errors in rules to encourage troubleshooting.

6. Mistake #6: Ignoring Default Policies

What happens

Rules are configured arbitrarily without defining default policies for each chain, which can lead to unpredictable behavior.

Correct approach

• Explain the difference between accept and drop as default policies.

• Demonstrate how an incorrect default policy can leave the firewall completely open or closed.

Suggested task: Have the student build rules from scratch under a drop policy.

7. Mistake #7: Not Restarting from Clean Configurations

What happens

Students run tests over previous rules, accumulating configurations without cleaning them. This leads to inconsistent results.

Correct approach

• Always teach to reset the ruleset:

bash

sudo nft flush ruleset

• Encourage the use of base configuration files.

Teaching tip: Create .nft templates with comments for students to edit.

8. Mistake #8: Not Providing Consistent Environments

What happens

Students use different systems, environments, or versions, causing unexpected differences.

Correct approach

• Recommend a specific distribution (e.g. Debian 12, Ubuntu 22.04).

• Use preconfigured virtual machines or containers.

• If possible, provide a virtual lab with snapshots.

Resource: Vagrant images or automatic installation scripts.

9. Mistake #9: Not Applying Real-World Examples

What happens

If students only see abstract rules, they fail to understand the relevance in real-world scenarios.

Correct approach

Apply use cases such as:

• Allow only HTTP and SSH to a web server.

• Block scans using limit and ct.

• NAT and port redirection with dnat/masquerade.

Final activity: Group integrative project to protect a simulated network.

10. Mistake #10: Not Measuring Understanding with Assessable Practices

What happens

Without applying practical assessments, the opportunity to validate real learning is lost.

Correct approach

• Design rubrics with clear criteria: functionality, security, rule clarity, logs, and persistence.

• Use controlled virtual environments where the instructor can test the student's firewall in real time.

Teaching nftables effectively requires avoiding common technical and pedagogical mistakes, providing clear environments, and structuring learning progressively, supported by practice, debugging, and real-world application.

Recommended Supplementary Material

• .nft templates with pedagogical comments.

• Configuration review checklist.

• Diagnostic questionnaires (pre- and post-class).

• Quick scripts to create lab environments.

Chapter 31: Developing Guides and Rubrics for nftables

Chapter Objective

This chapter will provide you with the practical tools needed to:

• Develop clear, progressive, competency-oriented instructional guides.

• Design objective evaluation rubrics to assess the application of nftables knowledge.

• Create a practical, measurable, and repeatable learning environment suitable for educational institutions or technical training programs.

1. Why Use Guides and Rubrics?

Practical guides help standardize the learning process and ensure all students acquire key competencies.

Evaluation rubrics allow for objective and transparent grading of practical skills, especially useful in vocational and technical training.

2. Key Components of an Instructional Guide

A practical nftables guide should be structured with the following elements:

Element | Practical Description
Exercise Title | Brief and descriptive. Example: "Configure Basic Rules for SSH and HTTP Traffic".
Objectives | What the student will learn. Should be observable.
Prerequisites | Concepts or configurations that should already be in place.
Required Resources | VMs, simulated network, commands, scripts, software.
Step-by-Step Instructions | Commands with an explanation of each action. Preferably include examples for each step.
Common Mistakes | Typical situations to avoid, with troubleshooting tips.
Final Verification | Steps to check that the configuration works correctly.

Practical tip: Use reproducible environments such as Vagrant, LXC, Docker, or installation scripts in VMs to facilitate guided execution.

3. Example of a Complete Guide for Class

Example: Basic Firewall for Web Server

Element | Content
Title | Basic Firewall for Web Server using nftables
Objective | Configure rules to allow HTTP/HTTPS and SSH traffic, block everything else.
Prerequisites | Basic networking knowledge, Linux terminal, nftables installed.
Resources | Ubuntu Server 22.04 VM, nftables installed, root access.
Steps | 1. Create table: nft add table inet filter
| 2. Create chains: nft add chain inet filter input { type filter hook input priority 0; policy drop; }
| 3. Allow SSH traffic: nft add rule inet filter input tcp dport ssh accept
| 4. Allow HTTP/HTTPS traffic: nft add rule inet filter input tcp dport {80,443} accept
| 5. Allow loopback traffic: nft add rule inet filter input iif "lo" accept
| 6. Allow related packets: nft add rule inet filter input ct state related,established accept
Verification | nft list ruleset, curl http://localhost, SSH access from another machine.
Common Mistakes | Not allowing return traffic (ct state), forgetting loopback interface, not setting default policy.

4. Practical Evaluation Rubric

Here is an example rubric to assess practical exercises with nftables:

Criterion | Low Level (0-1) | Medium Level (2-3) | High Level (4-5)
Firewall Structure | Tables or chains poorly created | Valid structure but incomplete | Tables, chains, and policies well defined
Rule Accuracy | Incoherent or invalid rules | Partially correct rules | All rules are precise, functional, and secure
Persistence and Loading | Does not save rules | Saves manually | Uses .nft file and automates with systemd
Functional Verification | No verification or documentation | Incomplete verification | Complete verification with functional tests
Logging and Traceability | Not used | Used in one rule | Correct logging in key rules and well-used traces
Student Documentation | No comments or steps | Partial comments | Excellent documentation, organization, and explanation
Error Diagnosis | Does not identify errors | Detects some | Effectively identifies and solves errors

Maximum total: 35 points

Suggested pass: 24 points (70%)

5. Teacher Tips for Applying the Rubric

• Observe live how the student applies the configuration.

• Review the generated .nft file and perform functional tests.

• Assess the ability to explain what has been done.

• If done in groups: individually assess each member for their contribution.

6. Ideas for Guided Projects

Firewall for secure SSH and SFTP server.

Firewall for a simulated DMZ with NAT.

Desktop firewall with detailed logging.

Scan detection system with connection limiting.

Each project should have a teacher guide, real-world scenarios, and an associated rubric.

7. Recommended Tools

• GNS3 + Linux VMs to simulate complex topologies.

• VirtualBox with snapshots to facilitate recovery of previous states.

• Git so students can submit versions and documentation of their rules.

• Markdown to write reproducible guides with clear syntax.

Developing appropriate guides and rubrics is a fundamental pillar for teaching nftables in a rigorous and practical way. As an educator, your role is to facilitate structured learning, with clear objectives and objective assessments, so the student can apply and defend their firewall configuration in a real environment.

Chapter 32: Introduction to pfSense and Its Ecosystem

Chapter Objective

This chapter aims to provide a practical introduction for teachers and students to the use of pfSense, a FreeBSD-based distribution designed to act as a firewall, router, and comprehensive perimeter security solution, as well as to explore the additional tools that make up its ecosystem.

By the end of the chapter, the reader will be able to:

• Understand what pfSense is, its uses, and its advantages in educational and production environments.

• Perform a basic pfSense installation in a virtual lab.

• Navigate the web interface and become familiar with its main modules.

• Explore the additional package ecosystem that extends its functionality.

1. What is pfSense?

pfSense is a specialized operating system, based on FreeBSD, that offers:

• Stateful firewall (Stateful Inspection).

• Advanced routing (static, dynamic, multi-WAN).

• VPN (OpenVPN, IPsec, WireGuard).

• Bandwidth management (QoS).

• Captive portal, IDS/IPS, proxy, and much more.

It is entirely managed through a graphical web interface, making it ideal for educational use where students can focus on concepts without initially depending on complex command-line interfaces.

2. Why Use pfSense in Educational Environments?

Educational Advantage | Practical Description
Ease of Use | Intuitive web interface, ideal for learning without prior CLI knowledge.
Powerful for Real Labs | Supports VLANs, VPN, NAT, traffic filtering, etc.
Extensive Documentation and Community | Forums, manuals, and videos available for self-learners and teachers.
Installable on VMs or Bare Metal | Perfect for virtualized labs with VirtualBox, Proxmox, or VMware.
Extensible Packages | Can be transformed into IDS, web proxy, secure DNS server, and more.

Didactic Suggestion: pfSense is excellent for hands-on networking practices involving firewalls, VPNs, web filtering, proxy, and network segmentation.

3. General Architecture of pfSense

[Internet]

│

│ WAN (em0)

[ pfSense Firewall ]

│ LAN (em1)

│

[Internal Network]

• WAN: Interface connected to the Internet (real or simulated).

• LAN: Interface for the internal network, from which students manage the system.

• Other interfaces: For creating DMZ, VLAN networks, subnets, VPN tunnels, etc.

4. Basic pfSense Installation in the Lab

4.1 Minimum Requirements

Resource | Suggested Value
CPU | Minimum 2 cores
RAM | Minimum 1 GB (2 GB recommended for IDS packages)
Storage | 10 GB
NICs | 2 (LAN and WAN)

4.2 Step-by-Step Installation (VirtualBox or Proxmox)

Download pfSense ISO from https://www.pfsense.org/download/.

Create a VM with 2 NICs:

NIC1 (WAN): NAT or bridge mode.

NIC2 (LAN): Internal network to simulate the local LAN.

Boot from the ISO and follow the graphical installer.

Reboot and note the assigned LAN IP (usually 192.168.1.1).

Access via a web browser at https://192.168.1.1.

Teacher Tip: You can prepare snapshots with different scenarios (just installed, partially configured, configured with errors, etc.).

5. Initial Exploration of the Web Interface

Once accessed via browser:

Section | Key Functionality
Dashboard | General information, interfaces, and logs
Interfaces | WAN, LAN, VLANs configuration
Firewall | Rules, NAT, Aliases
Services | DHCP, DNS Resolver, Captive Portal, NTP
VPN | OpenVPN, IPsec, WireGuard
Diagnostics | Ping, traceroute, packets, logs
System > Package Manager | Install Snort, pfBlockerNG, Squid, etc.

Suggested Activity: Configure DHCP on LAN and create a rule to block HTTP traffic during a specific schedule.

6. The pfSense Ecosystem: Recommended Packages

pfSense can be extended by installing packages from the Package Manager. Some highlights include:

Package | Main Function
pfBlockerNG | Content filtering and geoblocking based on blacklists
Snort / Suricata | IDS/IPS with known attack signatures
Squid | Web proxy with caching
SquidGuard | Web content filtering
ntopng | Traffic monitor with real-time visualization
WireGuard / OpenVPN | Lightweight and modern VPN for secure connections

Practical Exercise: Install Snort and enable detection on the WAN interface, then perform a scan with nmap from another machine and review the alerts.

7. Practical Cases to Implement in Class

Configure rules to allow only HTTPS traffic and block social networks.

Create a DMZ with a third interface and publish a web server.

Implement a Captive Portal to control student access.

Redirect HTTP traffic to Squid proxy with content control.

8. Additional Resources

• Official Documentation

• Forums: https://forum.netgate.com

• YouTube Channel: "Netgate" and pfSense community

• GitHub repository with lab templates (pfSense Labs)

pfSense is a complete, powerful, and accessible tool that allows for simulating and implementing professional firewalls in educational settings. Its package ecosystem transforms it into a true "perimeter security lab" with real capabilities for defense, monitoring, and control.

As a teacher or trainer, pfSense provides the perfect context to teach concepts of perimeter security, access policies, intrusion detection, VPN networks, and much more, without requiring expensive licenses or dedicated hardware.

Chapter 33: Step-by-Step Installation of pfSense in VirtualBox

Chapter Objective

This chapter aims to guide teachers and students through the complete installation of pfSense in VirtualBox, step by step, facilitating a virtual lab environment for perimeter security practices.

By the end of the chapter, students will be able to:

• Install pfSense from scratch in VirtualBox.

• Correctly configure WAN and LAN network adapters.

• Access the web administration interface.

• Have the machine ready for firewall and security testing.

1. Lab Requirements

Software Requirements

• VirtualBox installed (Windows, Linux, or macOS).

• pfSense CE ISO image: https://www.pfsense.org/download/

Recommended VM Hardware Requirements

Resource | Recommended Value
CPU | 2 virtual cores
RAM | 1 to 2 GB
Hard Disk | At least 10 GB (20 GB ideal)
NIC Cards | 2 (WAN and LAN)

2. Create the Virtual Machine in VirtualBox

Step 1: Create a new VM

Open VirtualBox and click on "New."

Name: pfSense-Lab

Type: BSD

Version: FreeBSD (64-bit)

Note: pfSense is based on FreeBSD, which is why this OS type is selected.

Step 2: Configure hardware resources

• RAM: Allocate at least 1024 MB (2048 MB is better).

• Hard disk: Create a new VDI virtual disk, 20 GB, dynamically allocated.

3. Configure Network Interfaces

Two network cards are required:

Interface | Connection Mode in VirtualBox | Functional Description
WAN | NAT or Bridged Adapter | Simulates Internet connection
LAN | Internal Network (intnet) | Connects to other VMs or the host

How to do it:

Select the VM -> Settings -> Network.

Adapter 1 (WAN):

Enabled.

Mode: NAT (can be "Bridged Adapter" if direct connection is desired).

Adapter 2 (LAN):

Enabled.

Mode: Internal Network.

Name: intnet.

Teacher Tip: You can connect a second VM (such as a Linux or Windows machine) to intnet to simulate the firewall's LAN network.

4. Mount the ISO and Start the Installation

Step 1: Mount the ISO

In Settings -> Storage:

Click on the empty disk icon.

Select "Choose a disk file" and load the pfSense ISO.

Step 2: Start the installation

Start the VM and wait for pfSense to load.

Select:

Option 1: Install.

Keyboard: Default (us).

Installation disk: the only available disk.

Partitioning: Auto (UFS).

Wait for the installation (~2-3 minutes).

When done, select Reboot.

Important: Before rebooting, eject the ISO from the VirtualBox menu -> Devices -> Optical Drives -> "Remove disk from virtual drive."

5. First Configuration After Reboot

pfSense will automatically detect interfaces:

• It will detect em0 as WAN (Adapter 1).

• It will detect em1 as LAN (Adapter 2).

Key step: Confirm interfaces

The following message will appear:

nginx

Should VLANs be set up now? [no]:

• Type no.

kotlin

Enter WAN interface name: em0 

Enter LAN interface name: em1 

Confirm the selection.

6. Initial Access from Browser

Once the configuration is completed:

• The LAN interface will have an IP like 192.168.1.1.

To access from another VM or from the host (if you bridge networks):

Create a second VM (for example, Ubuntu or Windows).

Connect it to the internal network intnet.

Assign an IP like 192.168.1.X manually or via DHCP.

Access https://192.168.1.1 from a browser.

Default credentials:

• User: admin

• Password: pfsense

7. Suggested Practical Exercises for Teachers

Exercise | Pedagogical Objective
Access pfSense from client VM | Validate access to the web interface
Change LAN IP to 10.0.0.1/24 | Practice network reconfiguration
Create a rule to block LAN ping | Introduce firewall rule concepts
Enable DHCP and test with client | Configure and test basic network services
Test browsing from client (WAN) | Validate NAT and Internet access from LAN

8. Saving the Lab State

To avoid repeating the installation:

Shut down pfSense.

In VirtualBox -> Right-click the VM -> Clone or Save State.

Create multiple snapshots for different stages (base, configured, with errors, etc.).

Installing pfSense in VirtualBox allows the creation of a secure, replicable, and cost-effective environment for teaching perimeter security, firewalls, routing, VPNs, and traffic management.

This environment perfectly fits educational institutions, online courses, academies, and cybersecurity labs, offering a professional experience without the need for expensive physical hardware.

Chapter 34: First Access – pfSense GUI

Chapter Objective

This chapter teaches educators and students how to correctly perform the first access to the pfSense GUI (Graphical User Interface), recognize its key elements, and carry out the initial configuration after installation. It focuses on web interaction and understanding the structural organization of the tool.

By the end of this chapter, students will be able to:

• Access the pfSense web administration panel from a LAN network.

• Complete the initial setup wizard.

• Understand the structure of the GUI interface.

• Identify the most important components: Dashboard, Interfaces, Firewall, Routing, DHCP, etc.

1. Prerequisites

Before starting this chapter, you should have:

• pfSense correctly installed on a VM (see previous chapter).

• Virtual client (Windows/Linux) connected to the internal LAN network (intnet).

• Connectivity between the client and pfSense (verifiable by pinging 192.168.1.1).

2. Initial Access to the Web Interface (GUI)

Step 1: Open browser in client VM

From the client virtual machine connected to the same LAN network, open a modern browser (Firefox or Chrome recommended) and access the following address:

https://192.168.1.1

Important: Access is via HTTPS, which may trigger a certificate warning. This certificate is self-signed by pfSense.

Step 2: Ignore the security warning

The browser will show a warning like:

• "Your connection is not private" (Chrome)

• "Warning: Potential Security Risk Ahead" (Firefox)

Click on “Advanced” -> “Accept the risk and continue.”

3. Authentication

The login form will appear.

• Username: admin

• Password: pfsense

Educational tip: This is a good moment to discuss the importance of changing default passwords as a basic security practice.

4. Initial Setup Wizard

After the first login, pfSense launches a step-by-step wizard. This is recommended for beginners.

Step 1: Welcome

• Simply click “Next.”

Step 2: General Information

• Hostname: pfsense-lab

• Domain: localdomain

• DNS Servers: you can leave the defaults or use Google’s (8.8.8.8 and 8.8.4.4)

• Check the “Override DNS” option to use the provided DNS servers.

Step 3: Time Zone Configuration

• Time zone: select Europe/Madrid or the one appropriate to your location.

• NTP server: 0.pfsense.pool.ntp.org

Step 4: WAN Interface

• If you are using DHCP on WAN (typical in NAT mode), no changes are needed.

• You can configure PPPoE or static IP if necessary (advanced use).

Step 5: LAN Interface

• By default, it will be 192.168.1.1/24. You can change it if you prefer another subnet (e.g., 10.0.0.1/24).

• This step is key if you plan to have multiple labs.

Step 6: Change the admin password

• HIGHLY recommended.

• Set a secure password for admin.

Finish the wizard -> pfSense will briefly reboot.

5. Practical GUI Exploration

Once inside the system, you will be on the Dashboard. From here you can see the general system status.

Main Panel: Dashboard

• System status (CPU load, memory).

• WAN and LAN interfaces.

• Active services (DHCP, DNS Resolver, etc.).

• Recent logs.

Recommendation: add useful widgets from “+” -> “Firewall Logs”, “Services Status,” etc.

6. Main Menu (top section)

Section | Key Functionality
System | System administration, passwords, backups
Interfaces | Detailed configuration of WAN, LAN, VLANs
Firewall | Rule creation, NAT, Alias, Schedule
Services | DHCP Server, DNS Resolver, NTP, Captive Portal
VPN | IPsec, OpenVPN, WireGuard
Diagnostics | Network tools: ping, traceroute, ARP, packet capture
Status | Traffic monitoring, interfaces, logs, services

Class activity: Ask students to identify and briefly describe each section and its possible applications in a school environment.

7. Recommended Quick Configuration for Practices

You can now perform basic configurations useful for the classroom:

a) Enable the DHCP server on LAN

Go to Services -> DHCP Server.

Ensure it is enabled.

Suggested range: 192.168.1.100 – 192.168.1.200

Test: Restart the client VM to see if it obtains an IP automatically.

b) Create a simple firewall rule

Firewall -> Rules -> LAN

Add a new rule:

Action: Block

Protocol: ICMP

Destination: any

Description: “Block ping”

Move the rule up and apply changes.

Lab test: Ping from the client to Google (ping 8.8.8.8). The traffic should be blocked.

8. Suggested Activities for Students

Activity | Objective
Access GUI from client VM | Validate network and understand self-signed certificates
Complete the Setup Wizard | Understand pfSense basic configuration
Enable DHCP and check automatic assignment | Familiarize with essential network services
Create and test a blocking firewall rule | Introduction to basic rule creation
Change password and system configuration | Reinforce good security practices

This chapter introduces students to the operational core of pfSense, its graphical interface. Understanding this GUI is essential to mastering the configuration of rules, services, and network policies, as well as developing reproducible and secure practical labs.

Familiarity with this tool opens doors to realistic simulations of corporate, educational, or home environments where perimeter security is a basic necessity.

Chapter 35: Basic Configuration of Interfaces and WAN/LAN

Chapter Objectives

The purpose of this chapter is to teach students and educators how to identify, configure, and manage the main pfSense interfaces: WAN and LAN, as well as any additional interfaces that may be added. By the end of the chapter, readers will be able to:

• Understand the role of each interface in a perimeter network.

• Correctly assign interfaces.

• Configure static or dynamic IP parameters for WAN and LAN.

• Validate the connectivity of each network segment.

• Troubleshoot basic configuration issues.

1. Preliminary Concepts: What are WAN and LAN in pfSense?

• WAN (Wide Area Network): This is the interface that connects to the Internet or external network. All outbound traffic passes through it.

• LAN (Local Area Network): This is the interface that connects the internal network (users, local services) to the firewall.

• Optional Interfaces: In pfSense, you can add additional interfaces to create VLANs, DMZs, or guest networks.

Educational example: You can explain this by comparing the firewall to a security gate: WAN is the entrance from the street; LAN is the internal hallway; additional interfaces can be specific rooms inside the house.

2. Initial Interface Check

After installing pfSense:

On the console (welcome screen), pfSense will display the detected interfaces:

WAN -> em0 (DHCP)

LAN -> em1 (static 192.168.1.1/24)

This may vary depending on the network adapter and connection order in VirtualBox or your environment.

3. Accessing Interface Configuration (GUI)

Log in to the web GUI (https://192.168.1.1).

Top menu: Interfaces -> Assignments

Here you will see:

• WAN and LAN already assigned.

• Button to add more interfaces if available.

• Dropdown menu to select which physical adapter corresponds to each logical interface.

Tip for educators: Ask your students to identify which VirtualBox virtual adapter corresponds to em0 and em1.

4. Configuring the WAN Interface

a) Automatic assignment via DHCP

In most lab environments, pfSense obtains an IP automatically from the host router (if in NAT mode).

Steps:

Menu: Interfaces -> WAN

Check the box “Enable Interface.”

Under “IPv4 Configuration Type,” select: DHCP

Set IPv6 to None (for initial simplicity).

Save and apply.

b) Manual assignment (static IP)

If you are working with a more controlled network (such as a simulated ISP):

• Change “IPv4 Configuration Type” to Static IP.

• Enter:

IP Address: 192.168.100.2

Subnet: /24

Gateway: 192.168.100.1

Validation: From Diagnostics -> Ping, test connectivity to the gateway.

5. Configuring the LAN Interface

a) Default address

• pfSense assigns 192.168.1.1/24 by default.

• This interface acts as the gateway and DHCP server for connected clients.

b) Change LAN IP address

This can be useful if you are setting up multiple firewalls on the network or using different subnets.

Menu: Interfaces -> LAN

Change:

“IPv4 Configuration Type”: Static IP

“IP Address”: e.g., 10.0.0.1

Subnet: /24

Warning: Once you apply the changes, you will lose connection if you are accessing from the old subnet. You will need to change or renew your client’s IP to access again.

6. Check the Routing Table and Connectivity

Menu: Diagnostics -> Routes

Here you can review:

• Static or dynamic routes associated with WAN and LAN.

• Ensure there is a default route pointing to the WAN gateway.

You can also run pings from the WAN or LAN interface to verify connectivity.

7. Guided Educational Practice

Practice scenario:

pfSense in VirtualBox with 2 adapters:

Adapter 1: NAT (WAN)

Adapter 2: intnet (LAN)

Virtual client in intnet.

Configure:

WAN: via DHCP

LAN: IP 10.10.10.1/24

DHCP: Range 10.10.10.100 - 10.10.10.200

Validate that the client obtains an IP.

From the client, ping 10.10.10.1 and then 8.8.8.8.

Educational objective: Understand the flow from the internal client to the Internet through the firewall.

8. Minimum Interface Security

• Ensure the WAN interface has no permissive rules by default.

• Firewall rules should be clearly defined:

LAN: Allow outbound traffic to the Internet.

WAN: Deny everything by default.

You can check in: Firewall -> Rules -> WAN/LAN

9. Common Student Errors and How to Prevent Them

Common Error | Practical Solution
No GUI access after changing LAN IP | Check client IP, change to the new subnet
No Internet from LAN | Check firewall rules in LAN
pfSense doesn’t obtain IP on WAN | Check if the NAT adapter in VirtualBox is active
DHCP does not assign IP to client | Ensure DHCP server is enabled on LAN

The correct configuration of WAN and LAN interfaces in pfSense is the foundation of any perimeter security policy. It is the first critical step to allow or block traffic, segment networks, and deploy effective firewall rules.

In an educational environment, mastering this chapter ensures that students can perform more complex configurations, such as VLANs, DMZs, or VPNs, with a solid foundation.

Chapter 36: Creating Firewall Rules in pfSense

Learning Objectives

By the end of this chapter, the reader will be able to:

• Understand the logic behind traffic filtering in pfSense.

• Create custom firewall rules on specific interfaces (LAN, WAN, DMZ).

• Apply best practices for effective security rules.

• Use event logging to monitor rule behavior.

• Propose active learning exercises using firewall rules.

1. What is a Firewall Rule?

In pfSense, a firewall rule defines how a network packet entering through a specific interface will be handled. Each rule answers three fundamental questions:

• Who? (source)

• Where? (destination)

• What to do? (allow or block)

2. Key Components of a Rule in pfSense

Component | Description
Action | What to do with the packet (Pass, Block, Reject).
Interface | Through which interface the packet arrives (LAN, WAN, etc.).
Protocol | Type of protocol (TCP, UDP, ICMP, ANY).
Source | IP or network source of the traffic.
Destination | IP or network destination of the traffic.
Destination Port | Port or range of ports (e.g., 80 for HTTP).
Description | Descriptive comment for the rule.
Log | Enable or disable logging for that rule.

3. Path to Create Rules in the GUI

From the web interface:

Go to Firewall -> Rules.

Select the tab corresponding to the interface (LAN, WAN, etc.).

Click on the + Add button (at the top or bottom, depending on the desired order).

Configure each rule field.

Save and apply changes.

4. Basic Practices: Creating Rules on the LAN Interface

Example 1: Allow all traffic from LAN to any destination

• Interface: LAN

• Action: Pass

• Protocol: Any

• Source: LAN net

• Destination: Any

• Log: Enabled (optional)

• Description: "Allow all traffic from LAN"

This is the default behavior in pfSense for the LAN interface. However, it’s a good starting point to observe how the system works.

Example 2: Restrict access to a specific IP

Case: Block access to YouTube from any LAN device.

Identify YouTube’s IP range (e.g., 142.250.190.0/24).

Create the rule:
• Action: Block
• Protocol: Any
• Source: LAN net
• Destination: 142.250.190.0/24
• Description: "Block access to YouTube from LAN"

Validation: From a client device, try to open youtube.com. Check the logs.

Example 3: Allow only web traffic (ports 80 and 443)

• Action: Pass

• Protocol: TCP

• Source: LAN net

• Destination: Any

• Destination Port: 80 (add another rule for 443)

• Description: "Allow only HTTP/HTTPS traffic"

Suggested exercise: Ask students to test browsing on different ports and analyze why they fail (e.g., FTP, SSH).

5. Creating Rules on the WAN Interface

By default, pfSense blocks all incoming traffic on the WAN interface. Rules here are used when you want to:

• Allow external access to internal services (like a web server in LAN).

• Configure rules for VPN or remote access.

Example 4: Allow access to an internal web server from the Internet

Scenario: You have a server in LAN with IP 192.168.1.100 serving HTTP.

Configure NAT Port Forwarding (covered in another chapter).

Create a rule in WAN:
• Interface: WAN
• Action: Pass
• Protocol: TCP
• Destination Port: 80
• Destination: 192.168.1.100
• Description: "Allow web access to internal server"

Teacher tip: This is a good opportunity to discuss IDS/IPS, DMZ, or critical service segmentation.

6. Rule Logging

Each rule can log events when it matches traffic. This is useful for:

• Troubleshooting rule errors.

• Detecting unauthorized access attempts.

• Learning activities.

To view logs:

• Go to Status -> System Logs -> Firewall (tab)

Suggested activity: Create rules with logging enabled and review how connection attempts are logged.

7. Best Practices When Creating Rules

Practice | Justification
Describe each rule | Eases maintenance and teaching
Enable logging on key rules | Useful for debugging and monitoring
Place “block” rules before “pass” | pfSense evaluates rules sequentially
Minimize the use of "any" | More controlled, reduces attack surface
Use aliases for common IPs/ports | Improves readability and flexibility

8. Proposed Practical Exercises

Lab 1: Restrictive Firewall with Exceptions

• Block all traffic from LAN except HTTP/HTTPS and DNS.

• Log all blocked attempts.

• Validate with a connected client.

Lab 2: Parental Control

• Block social networks and YouTube by IP or domain name.

• Implement cron jobs to enable/disable rules by schedule (using pfBlockerNG or scripts).

9. Classroom Activity: “Safe Classroom Firewall”

Challenge for students:

Configure pfSense in router mode and create a set of rules that:

• Block torrent downloads.

• Allow access to educational platforms.

• Restrict traffic outside school hours.

• Log each policy violation.

Assessment: A rubric can be used to measure effectiveness, rule logic, use of descriptions, and logging.

10. Complementary Tools

• Aliases: You can group IPs, networks, ports, or FQDNs and reference them with a single name in multiple rules.

• Schedules: Allows you to create rules active only on certain days and times.

• pfBlockerNG: Plugin to create blacklists and advanced filters (ideal for educators).

Creating firewall rules in pfSense is the heart of perimeter security. A well-configured firewall not only protects the network but also teaches logical thinking, threat analysis, and granular traffic control.

Mastering this chapter enables students to plan and apply real-world security policies and allows educators to design effective educational scenarios.

Chapter 37: NAT, Port Forwarding, and Redirections

Learning Objectives

By the end of this chapter, the reader will be able to:

Understand the different types of NAT used in networks.

Configure Port Forwarding rules in pfSense.

Redirect traffic in a controlled and secure way.

Use aliases and advanced rules for complex scenarios.

Identify and avoid common NAT implementation errors.

1. What Is NAT?

NAT (Network Address Translation) is a technique that modifies the IP address information in packet headers as they traverse a firewall.

Common NAT types:

NAT Type | Description
SNAT (Source NAT) | Translates the source IP (e.g., outbound to the Internet).
DNAT (Destination NAT) | Translates the destination IP (e.g., redirects to an internal server).
1:1 NAT | One-to-one mapping between a public IP and a private IP.
NAT Reflection/Loopback | Allows internal users to reach a redirected service via the public IP.

In pfSense, the most frequently used form is Port Forwarding (a DNAT implementation).

2. Common Use Cases for NAT and Redirections

Scenario | Practical Example
Access to an internal web server | Redirect port 80 on WAN to a LAN web server
SSH access from the Internet | Redirect port 22 to an internal SSH host
Hosting multiplayer game servers | Redirect specific UDP/TCP port ranges
Remote IP camera access | Redirect unique ports for each camera IP

3. Configuring Port Forwarding in pfSense

Example: Redirect port 80 to a local web server

Scenario:

You have a web server at 192.168.1.100 on your LAN and want it to be accessible from the Internet via pfSense’s public IP.

Steps:

Go to Firewall > NAT > Port Forward.

Click Add (+).

Fill in the basic fields:

Field | Value
Interface | WAN
Protocol | TCP
Destination | WAN address
Destination Port Range | HTTP (80)
Redirect Target IP | 192.168.1.100
Redirect Target Port | HTTP (80)
Description | “Redirect WAN port 80 to internal web server”

Advanced options:

NAT Reflection: Enable if you need internal clients to use the public IP.

Filter rule association: Select “Add associated filter rule” to have pfSense generate the matching firewall rule automatically.

Save and Apply Changes.

Verification:

From an external client (outside the firewall), browse to http://<pfSense-public-IP> and confirm you reach the internal web server.

4. 1:1 NAT (One-to-One NAT)

Common scenario:

An organization has a block of public IPs and wants to map them one-to-one to internal hosts.

Steps in pfSense:

Go to Firewall > NAT > 1:1 and click Add.

Define:

External Subnet IP: the public IP.

Internal IP: the private host’s IP.

Destination: Any (or limit to a specific subnet).

Create matching firewall rules to allow the desired traffic.

This method is ideal when publishing multiple services on different internal hosts.

5. Multiple Port Redirection

Scenario:

An internal server provides multiple services (HTTP, HTTPS, SSH, RDP). Rather than creating individual NAT entries for each port, you can use a port alias.

Steps:

Create a port alias at Firewall > Aliases > Ports:

Name: SERVICES_WEB

Ports: 80, 443, 22, 3389

In Firewall > NAT > Port Forward, set:

Destination Port Range: SERVICES_WEB

Redirect Target Port: SERVICES_WEB

Using aliases lets you:

Avoid copy-paste errors.

Manage ports centrally.

Add/remove services without editing every NAT rule.

Verification:

From an external client, test each service:

bash

curl http://<public_IP>  # HTTP

curl -k https://<public_IP>  # HTTPS

ssh <public_IP>  # SSH

6. Logging and Monitoring Redirections

To ensure that your redirection rules are working correctly, check:

Firewall Logs

Status > System Logs > Firewall

Filter by the internal destination IP or port.

Diagnostics > States

Verify active state entries for connections between the public IP and the internal server.

Diagnostics > Packet Capture

Capture on the LAN or WAN interface, filtering for the redirected port to see the actual packets.

7. Common Errors and How to Avoid Them

Error | Practical Solution
Port is forwarded but no response from server | Ensure the internal service is listening on the correct IP and port.
NAT works externally but not from LAN clients | Enable NAT Reflection or configure local DNS resolution for the public IP.
Overlapping or ambiguous NAT rules | Check for rule conflicts and ensure distinct port/interface combinations.
No firewall rule created | Use “Add associated filter rule” when creating the NAT entry.

8. Classroom Practice Activity

Objective:

Configure and test multiple NAT redirections in a simulated environment.

Requirements:

pfSense installed in VirtualBox or Proxmox.

Two VMs: one acting as an external client, another as a LAN server.

Instructions:

Forward WAN port 80 to the internal server.

Forward SSH on an alternate port (e.g., external 2222 → internal 22).

Create a port alias and forward it to the server.

From the external client VM, test connectivity for each port.

Document screenshots of your NAT rule settings and test results.

9. Tips for Educators

Start with a single-port example, then scale to multiple ports.

Demonstrate live in a virtual lab environment.

Introduce intentional errors to teach troubleshooting.

Use aliases as a best-practice exercise in policy organization.

Assign graded labs with a rubric evaluating connectivity, alias usage, and log verification.

Mastering NAT and port forwarding in pfSense is not only a critical perimeter-security skill but also an excellent way to teach concepts like network visibility, address translation, and controlled inbound traffic. Through hands-on examples and realistic simulations, students learn how to safely, documentably, and repeatably manage what traffic is allowed into their network.

Chapter 38: VLAN Configuration and Segmentation

Learning Objectives

By the end of this chapter, the reader will be able to:

Understand the concept and purpose of VLANs in modern networks.

Configure VLANs in pfSense using virtual interfaces.

Integrate managed switches to carry VLANs.

Apply firewall policies to isolate and control traffic between VLANs.

Design lab exercises with multiple network segments.

1. What Is a VLAN and Why Is It Important?

A VLAN (Virtual Local Area Network) is a logical segmentation technique that lets you separate networks over the same physical hardware (switches and routers).

Key security benefits:

Traffic isolation: Devices in different VLANs cannot communicate unless explicitly allowed by firewall rules.

Reduced attack surface: A compromised device in one VLAN cannot affect other VLANs by default.

Role separation: Create VLANs for administration, students, guests, IoT, etc.

Simplified management: A single physical switch or router can handle multiple virtual networks.

2. Environment Requirements for Labs

pfSense installed (bare-metal, VirtualBox, or Proxmox).

A managed switch that supports 802.1Q (virtual, like Open vSwitch, or a real switch such as TP-Link, Netgear, HP).

At least two client machines (physical or virtual) connected to different VLANs.

In educational setups, you can simulate VLANs in virtualization platforms by creating separate internal networks or bridged adapters.

3. Creating and Configuring VLANs in pfSense

Step 1: Define VLANs

Go to Interfaces > Assignments > VLANs.

Click Add.

Configure the fields:

Field | Value
Parent Interface | em0 (your physical or virtual NIC)
VLAN Tag | 10 (first VLAN ID)
Description | VLAN10 – Administration

Repeat for additional VLANs:

VLAN Tag | Description
10 | Administration
20 | Students
30 | Guests / IoT

Step 2: Assign Virtual Interfaces

Go to Interfaces > Assignments.

Add each newly created VLAN as an interface (OPT1, OPT2, etc.).

Edit each interface:

Enable it.

Assign a static IP (e.g., VLAN10 → 192.168.10.1/24).

Step 3: (Optional) Enable DHCP per VLAN

Go to Services > DHCP Server.

Enable DHCP on each VLAN interface.

Define an IP range for clients in that segment.

4. Switch Configuration for pfSense VLANs

On your managed switch (real or virtual):

Configure the port connected to pfSense as a trunk (tagged) carrying all VLANs.

Set each client port as untagged in its assigned VLAN.

Disable unused VLANs on each port for extra security.

Example (TP-Link switch):

Port 1 (pfSense uplink): Tagged VLANs 10, 20, 30

Port 2 (Admin PC):  Untagged VLAN 10

Port 3 (Student PC):  Untagged VLAN 20

5. Applying Firewall Rules Between VLANs

Goal: Prevent student devices (VLAN20) from reaching the administration VLAN (VLAN10).

Go to Firewall > Rules > VLAN20 (Students).

Create a Block rule:

Field | Value
Action | Block
Protocol | Any
Source | VLAN20 net
Destination | VLAN10 net
Description | “Block Students → Admin”

Repeat similar rules on other VLAN tabs as needed.

Verify isolation by attempting to ping or browse between VLAN20 and VLAN10.

6. Lab Exercise: VLAN Segmentation

Scenario: A school network has three groups:

Administration (VLAN10): Full Internet and pfSense access.

Students (VLAN20): Internet only, no admin network access.

Guests (VLAN30): Web access only, minimal privileges.

Tasks:

Create and assign VLANs in pfSense and on the switch.

Enable DHCP servers for each VLAN.

Implement block rules between VLANs.

Test allowed and blocked connectivity.

Document the network topology.

7. Best Practices for VLAN Environments

Use clear naming (e.g., VLAN10_Admin, VLAN20_Students).

Disable unnecessary services (DHCP, DNS) on each VLAN.

Secure trunk ports to prevent VLAN hopping.

Apply ACLs on switches if supported.

Monitor inter-VLAN traffic for anomalies.

8. Tips for Educators

Start with just two VLANs, then expand to three or more as students gain confidence.

Use visual diagrams to illustrate segmentation.

Assign configuration troubleshooting tasks—students must find and fix VLAN misconfigurations.

Introduce tools like Wireshark to observe VLAN-tagged traffic.

Integrate with previous chapters on firewall rules, NAT, and DNS for comprehensive labs.

VLAN-based segmentation is one of the most effective perimeter-security techniques. Proper implementation in pfSense yields isolated, scalable, and secure environments. Mastery of VLANs equips students to design enterprise-grade networks and apply defense-in-depth principles.

Chapter 39: Users, Permissions, and Web Management

Learning Objectives

By the end of this chapter, the reader will be able to:

Understand pfSense’s authentication model.

Create and manage local users with different permission levels.

Define custom administrative roles.

Apply best practices for secure web access to pfSense.

Use certificates for secure GUI authentication.

1. Introduction: Why Manage Users?

Protecting a firewall isn’t just about network rules—it’s also about controlling who can configure it and what they may do. A single mistaken click in the GUI could disrupt an entire network. That’s why you need:

Secure access: strong passwords, HTTPS, limited user accounts.

Delegation of duties: users who only manage DHCP, firewall rules, or logs.

Audit and control: know who did what and when.

2. Securing Web GUI Access

By default, pfSense’s web interface is exposed on its LAN IP (e.g. https://192.168.1.1). Recommended initial settings:

Always use HTTPS.

Change the default port if possible (e.g. 8443 instead of 443).

Restrict GUI access only to trusted admin IP addresses.

Do not allow GUI access from WAN except in tightly controlled cases.

To tighten GUI access:

Go to System > Advanced > Admin Access.

Under WebGUI:

Check Disable web GUI redirect rule.

Enable SSL/TLS (set Protocol to HTTPS).

Change the TCP Port to your chosen port (e.g. 8443).

Save and verify by browsing to your new GUI address.

3. Managing Local Users in pfSense

pfSense can maintain its own user database without an external directory (though you can integrate LDAP/RADIUS).

To create a new local user:

Go to System > User Manager.

Under the Users tab, click + Add.

Fill in:

Field | Example Value
Username | docente1
Password | a secure password
Full name | Network Instructor
Expiration date | (optional)

Optionally upload a user certificate for secure GUI login.

4. Assigning Permissions and Groups

To define a group with specific privileges:

Go to System > User Manager > Groups and click + Add.

Name the group (e.g. firewall-editors).

Under Assigned Privileges, select the permissions:

Privilege | Description
WebCfg – Firewall: Rules | Edit firewall rules
WebCfg – Services: DHCP Server | Manage DHCP server settings
WebCfg – Status: System Logs | View system logs

Add your user (e.g. docente1) to the group.

Now that user can only edit firewall rules and view logs—no full system access.

5. Lab: Limited-Permission User

Scenario:

Create a user estudiante1 who can only view firewall rules and logs, not modify them.

Steps:

Create a group called auditors.

Assign permissions:

WebCfg – Firewall: Rules (view only)

WebCfg – Status: System Logs

Create user estudiante1 and assign to auditors.

Log in as estudiante1 and confirm they can see but not change rules.

Attempt to modify a rule → access denied.

This teaches students how to delegate limited admin roles safely.

6. Auditing User Access

pfSense logs every GUI login and configuration change.

To view audit entries:

Go to Status > System Logs > System > General.

Filter for authentication events or configuration changes.

Example log entry:

May 07 15:22:01 pfSense sshd[8301]: Accepted password for docente1 from 192.168.10.25 port 49822 ssh2

Use these logs for exercises in investigating failed or unauthorized attempts.

7. Best Practices for Web Access Management

Avoid using the admin account for daily tasks—create role-based users.

Use strong, unique passwords and change defaults immediately.

Enable two-factor authentication (2FA) for the main admin account if possible.

Set session timeouts under System > Advanced > Admin Access > Session Timeout.

8. Integrating External Authentication (Optional)

For larger schools or businesses, pfSense can link to:

LDAP / Active Directory

RADIUS

Configure under System > User Manager > Authentication Servers to use corporate or campus credentials.

9. Recommendations for Educators

Create temporary student accounts for labs.

Assign tasks in which students manage certain services without full system access.

Enforce the principle of least privilege.

Simulate unauthorized-access scenarios to teach incident response.

Use this chapter to segue into firewall hardening and access control labs.

Proper user and permission management in pfSense is essential to secure the firewall against both external threats and human error. Through the GUI’s user, group, and privilege settings, you can delegate responsibilities, audit actions, and safeguard your perimeter’s administration.

Chapter 40: Content Filtering and QoS

Learning Objectives

By the end of this chapter, readers will be able to:

Implement web content filtering to block undesirable sites.

Use pfBlockerNG to block domains, IP ranges, and content categories.

Configure QoS (Quality of Service) policies to prioritize important traffic.

Design educational exercises on bandwidth management and content restriction.

1. Introduction: Why Control Content and Traffic?

In school or business networks, it’s essential to:

Block access to inappropriate content (adult sites, games, social media).

Prevent bandwidth saturation by large downloads or streaming.

Prioritize educational or administrative traffic.

Ensure good performance for critical applications (e.g. virtual-class video calls).

You achieve this by combining content filtering with QoS.

2. Content Filtering with pfBlockerNG

pfBlockerNG is a pfSense package that can:

Block domains via DNSBL.

Block IP ranges with IP blocklists.

Categorize content by type.

Integrate blacklists from Spamhaus, Emerging Threats, etc.

Installing pfBlockerNG

Go to System > Package Manager > Available Packages.

Search for pfBlockerNG and click Install.

Once installed, open Firewall > pfBlockerNG.

Basic Setup

Under General, enable pfBlockerNG.

In DNSBL, enable DNS filtering.

Add a simple blocklist under DNSBL > DNSBL Feeds:

Name: social_block

URL: https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts

Category: Social, Ads

Apply changes and check the logs.

Test

Try to visit a blocked domain (e.g. facebook.com); it either fails to resolve or shows a warning page.

Lab Exercise: Block social media during class hours:

Create a DNSBL list with Facebook, Instagram, TikTok domains.

Set up a schedule to activate blocks Monday–Friday, 08:00–16:00.

Verify that students can access before or after those times, but not during.

3. QoS with Traffic Shaping

Quality of Service lets you prioritize traffic under congestion. pfSense offers two approaches:

Option 1: Traffic Shaper Wizard

Go to Firewall > Traffic Shaper > Wizards.

Select Multi LAN/WAN.

Enter your real upload/download speeds.

Define priorities—for example:

High priority: VoIP, DNS, HTTP

Low priority: P2P, streaming, FTP

The wizard creates queues and classification rules for you.

Option 2: Manual Limiters

Go to Firewall > Traffic Shaper > Limiters.

Create two limiters:

DownLimiter: 5 Mbps

UpLimiter: 1 Mbps

In Firewall > Rules > LAN, edit your LAN rule:

Under Advanced Options, apply the Up/Down limiters.

Practice: Limit each lab PC to 2 Mbps down and 0.5 Mbps up:

Create an alias lab_hosts listing PC IPs.

Define limiters of 2 Mbps/0.5 Mbps.

Apply those limiters to the LAN firewall rule matching lab_hosts.

Test with a speed-test site.

4. Pedagogical Approach

Suggested activities:

Simulate many students downloading large files; observe QoS effects.

Use QoS to guarantee stable video-conferencing bandwidth.

Block social media and measure the network’s performance difference.

Run A/B tests: with and without filtering/QoS to compare.

Sample evaluation rubric:

Criterion | Weight | Example
Correct DNSBL configuration | 30% | Blocklist loaded and active
Time-based firewall rule | 20% | Blocks only during scheduled hours
Active limiters | 30% | QoS applied correctly to targeted hosts
Functional validation | 20% | Measured traffic differences in tests

5. Best Practices

Never block critical domains (e.g. google.com).

Review DNSBL lists before applying them.

Monitor logs to see which sites or IPs get blocked.

Document every QoS rule and its purpose.

Content filtering and QoS are cornerstones of modern network management, especially in educational settings where balance between control and flexibility is key. With pfSense, you can implement precise, transparent, and instructive policies to both filter content and manage bandwidth effectively.

Chapter 41: VPNs with pfSense (OpenVPN/IPsec)

Learning Objectives

By the end of this chapter, students and instructors will be able to:

Understand key concepts behind VPNs.

Configure an OpenVPN server and client from scratch using pfSense.

Establish a site-to-site IPsec VPN.

Integrate certificate- and user-based authentication.

Apply practical configurations for remote classrooms or branch interconnection.

1. Introduction to VPNs in Perimeter Security

A VPN (Virtual Private Network) creates encrypted tunnels between remote devices or networks over the Internet.

Common uses:

Secure remote access to an institution’s network.

Interconnect multiple sites or campuses.

Remote cybersecurity labs.

Traffic privacy on public networks.

VPN types covered:

Type | Ideal For | Security | Ease of Use
OpenVPN | Remote user access | High | High
IPsec | Site-to-site network linking | High | Medium

2. Configuring OpenVPN (Server + Remote Client)

Step 1: Prepare pfSense

Ensure pfSense has Internet access.

Go to System > Certificate Manager > CAs and create a new internal CA:

Name: CA_OpenVPN

Key length: 2048

Digest Algorithm: SHA256

Under Certificates, create a server certificate signed by that CA:

Description: Cert_Serv_OpenVPN

Usage: Server Certificate

Signing CA: CA_OpenVPN

Step 2: Use the OpenVPN Wizard

Navigate to VPN > OpenVPN > Wizards.

Select the CA you just created.

Configure:

Server Name: VPN_educativa

Port: 1194

Protocol: UDP

Tunnel Network: 10.8.0.0/24

Local Network: 192.168.1.0/24 (your LAN)

Enable “Client Export Package”

Create a user under System > User Manager > Add and check “Create a certificate for this user.”

Verification

Install the openvpn-client-export package via VPN > OpenVPN > Client Export.

Export the user’s installer (.exe, .ovpn, or .mobileconfig).

Install on a remote device (Windows, Linux, or mobile).

Connect and verify access (e.g. ping 192.168.1.1).

3. Configuring an IPsec VPN (Site-to-Site)

IPsec is ideal for linking two pfSense sites.

Scenario:

Site A LAN: 192.168.1.0/24

Site B LAN: 192.168.2.0/24

Both have fixed or DynDNS public IPs.

Step 1: Configure Site A

Go to VPN > IPsec > Tunnels > Add Phase 1:

Remote Gateway: public IP of Site B

My Identifier: My IP Address

Peer Identifier: Peer IP Address

Pre-Shared Key: a strong secret

Add Phase 2 under that tunnel:

Local Subnet: 192.168.1.0/24

Remote Subnet: 192.168.2.0/24

Step 2: Configure Site B

Perform the mirror configuration on Site B, swapping the LAN subnets and remote gateway IP.

Verification

Check under Status > IPsec that the tunnel shows “Established.”

Ping hosts between 192.168.1.x and 192.168.2.x.

Ensure appropriate firewall rules allow traffic between the two LANs.

4. Classroom Activities and Lab

Activity 1: Remote Access for Students

Each student generates their own certificate.

Instructor verifies they can reach simulated internal servers.

Evaluate what resources they can access with and without VPN.

Activity 2: Site-to-Site Connection

Simulate two pfSense instances in VirtualBox.

Configure IPsec and test file transfer, RDP, or VNC between sites.

Evaluation Rubric

Criterion | Points
Functional OpenVPN deployment | 30
Operational IPsec site-to-site link | 30
Successful client export | 20
Quality of configuration documentation | 20

5. Best Practices

Use strong keys and certificates with expiration.

Organize users into groups (admins vs. students).

Disable or remove inactive/compromised accounts.

Monitor VPN usage via logs (Status > System Logs > OpenVPN).

Apply restrictive firewall rules on VPN interfaces—limit access to only required services.

VPNs are a cornerstone of modern perimeter security. With pfSense, teaching both OpenVPN and IPsec is straightforward, offering hands-on experience in real-world scenarios.

Chapter 42: High Availability (CARP) and Backup

Learning Objectives

By the end of this chapter, the reader will be able to:

Understand key concepts of high availability in perimeter networks.

Implement a redundant firewall pair using CARP in pfSense.

Configure automatic synchronization of settings between firewalls.

Verify active failover and simulate controlled outages.

Apply these practices in a virtualized educational lab.

1. What Is CARP and Why It Matters

CARP (Common Address Redundancy Protocol) allows two or more firewalls to share a virtual IP address. If the master fails, the backup automatically takes over, preventing service interruptions.

Ideal for ensuring availability of critical services (NAT, VPN, DNS, DHCP, filtering, etc.).

High-Availability Components

Component | Brief Description
CARP Virtual IP (VIP) | IP shared between master and backup
pfsync | Real-time synchronization of connection states
XMLRPC Sync | Configuration replication (firewall rules, services)
Automatic Failover | Role switch when active node fails

2. Prerequisites

Two pfSense instances on the same LAN:

pfSense1 (Master): 192.168.100.2

pfSense2 (Backup): 192.168.100.3

At least three interfaces on each box: WAN, LAN, and SYNC (a dedicated sync network).

Both must run the same pfSense version with a matching base configuration.

Disable “Block private networks” on the SYNC interface.

3. Step-by-Step Configuration

Step 1: Configure the SYNC Interface

On both pfSense nodes:

Assign an interface (e.g. em2) for synchronization.

Set IPs:

pfSense1 SYNC: 192.168.200.1/24

pfSense2 SYNC: 192.168.200.2/24

Allow all traffic (permit pings and stateful pass) on that interface in the firewall rules.

Step 2: Create the CARP Virtual IP

On pfSense1 (Master):

Go to Firewall > Virtual IPs > Add.

Type: CARP

Interface: LAN

IP Address: 192.168.1.254/24 (shared VIP)

Virtual Host ID: 1

Skew: 0 (highest priority)

Password: set a strong shared secret

On pfSense2 (Backup):

If XMLRPC Sync is enabled, the VIP is auto-created. Otherwise repeat the above with Skew: 100.

Step 3: Enable pfsync

On both pfSense systems:

Go to System > Advanced > System Tunables.

Enable “Synchronize states” and select the SYNC interface.

Step 4: Configure XMLRPC Configuration Sync

On pfSense1 (Master):

Navigate to System > High Availability Sync.

Enable “Config Sync”, enter the peer’s SYNC IP (192.168.200.2), and admin credentials for pfSense2.

Select which items to sync: firewall rules, NAT, DHCP, OpenVPN, Aliases, Virtual IPs, etc.

4. Failover Simulation and Verification

High-Availability Test

On a LAN client, set the gateway to the VIP (192.168.1.254).

Power off pfSense1; pfSense2 should immediately assume the VIP and maintain connectivity.

Power pfSense1 back on; it should reclaim master role (Skew 0) if healthy.

Useful log: Status > System Logs > System > Gateways

5. VirtualBox Lab Scenario

Classroom Setup:

Two pfSense VMs (master/backup), both on the same LAN and a dedicated SYNC network.

One client VM on the LAN network.

Lab Tasks:

Task | Expected Result
Configure CARP VIP | Client uses shared gateway without downtime
Enable XMLRPC config sync | Rules and settings replicate on backup firewall
Simulate master failure | Client continues browsing uninterrupted
Restore master | Master reclaims VIP and resumes handling traffic

6. Configuration Backup

Manual (Weekly Recommendation):

Go to Diagnostics > Backup & Restore.

Export the XML config file.

Store securely or in your backup system.

Automated (Advanced):

Use a script and cron to SCP the backup offsite. Example /usr/local/bin/backup_pfsense.sh:

bash

#!/bin/sh

DATE=$(date +%F)

scp /cf/conf/config.xml user@backup-server:/backups/pfsense-$DATE.xml

Schedule with cron:

0 2 * * 1 /usr/local/bin/backup_pfsense.sh

7. Best Practices

Use a dedicated sync network to avoid collisions.

Include all services (users, aliases, firewall rules) in XMLRPC sync.

Test failover quarterly.

Ensure certificates (e.g. for OpenVPN) are kept in sync.

Configure email alerts for status changes.

Implementing CARP and synchronization in pfSense builds a resilient, fault-tolerant perimeter. For students, it demonstrates real-world design of high-availability networks.

Chapter 43: Distributed Firewall with pfSense

Chapter Objective

This chapter teaches how to design and implement a distributed firewall using pfSense in medium and large infrastructures, applying segmentation, redundancy, and efficiency principles. You will learn:

The concept and advantages of a distributed firewall.

Recommended architectures.

Practical cases: educational campus, multi-branch enterprise, and lab.

Step-by-step configuration of multiple collaborating pfSense instances.

Best practices for synchronization, monitoring, and distributed management.

1. What Is a Distributed Firewall?

A distributed firewall is an approach in which multiple independent firewalls operate in coordination at different points in the network to:

Enforce security at multiple layers (edge, core, perimeter).

Improve availability and scalability.

Apply segmented policies by area, VLAN, or branch.

Increase fault tolerance and granular monitoring.

Unlike a single centralized firewall, a distributed firewall spreads security enforcement to where it’s most needed.

2. Typical Distributed Architecture

Example Scenario: University or Corporate Campus

Zone / Location | pfSense Role
Perimeter (Internet) | Central pfSense for filtering, NAT, VPN
Core Network | Core pfSense for inter-VLAN routing, QoS, L3 filtering
Departments / Branches | Local pfSense for site-specific policies and redundancy

Each pfSense node may operate standalone or in synchronized HA pairs, depending on design.

3. Technical Requirements

Multiple physical or virtual machines running pfSense (minimum 2, ideally 3–5).

Managed switches or virtualization that support 802.1Q VLAN tagging.

L3 backbone routers or switches.

NTP synchronized across the infrastructure.

Trunked links between sites for interconnection.

4. Hands-On Lab: Basic Distributed Firewall

Objective

Segment security by zone (perimeter, core, department).

Device | Role | LAN IP | WAN / Gateway
pfSense1 | Perimeter | 192.168.10.1/24 | DHCP or public WAN
pfSense2 | Core | 192.168.20.1/24 | Gateway 192.168.10.1
pfSense3 | Department | 192.168.30.1/24 | Gateway 192.168.20.1

5. Step-by-Step Configuration

5.1 pfSense1 (Perimeter)

WAN: Configure for DHCP or a public IP.

LAN: Set to 192.168.10.1/24.

Firewall Rules:

Allow traffic from LAN to 192.168.20.0/24 (Core).

Allow outbound HTTPS and DNS to the Internet.

NAT: Enable outbound NAT for internal networks.

5.2 pfSense2 (Core)

WAN: IP 192.168.10.2/24, gateway 192.168.10.1.

LAN: 192.168.20.1/24.

Firewall Rules:

Allow traffic to 192.168.30.0/24 (Department) and 192.168.10.0/24 (Perimeter).

Optionally deny other inter-VLAN traffic.

Routing: Configure static routes or enable OSPF (optional).

5.3 pfSense3 (Department)

WAN: IP 192.168.20.2/24, gateway 192.168.20.1.

LAN: 192.168.30.1/24.

Firewall Rules:

Department-specific policies (e.g., remote access, internal services).

Enable detailed logging for departmental traffic.

6. Synchronization & Distributed Management

Use pfsync and XMLRPC sync for redundancy within each zone if desired.

Deploy CARP pairs at perimeter and core for high availability.

Adopt a centralized monitoring solution (e.g., Zabbix, LibreNMS, Grafana).

Aggregate logs centrally (e.g., Graylog or remote rsyslog).

7. Use Cases & Exercises

Case 1: University Campus

pfSense1 (Perimeter): Content filtering (Squid, ClamAV).

pfSense2 (Core): Backbone between faculties.

pfSense3–n: One for each faculty or lab with tailored policies and bandwidth controls.

Case 2: Multi-Branch Enterprise

A pfSense at each branch, connected via site-to-site VPN to central office.

Local rules for campus devices and centralized log synchronization.

Perimeter pfSense enforces global policies (email, ERP, web).

Practical Exercise

Task | Expected Outcome
Chain three pfSense nodes | Traffic segmented by security zone
From Department pfSense, reach Internet | Allowed if correct rules are in place
Block cross-department traffic | Department-level isolation enforced
Simulate attack from Dept A | Logged on pfSense2, blocked as configured

8. Best Practices

Use clear hostnames (e.g., pf-perimeter, pf-core, pf-dept).

Define policies top-down (from general to specific).

Sync firewall rules for easier maintenance.

Document and version control rule sets (e.g., export XML to Git).

Secure pfSense management with SSH keys or two-factor authentication.

Implementing a distributed firewall with pfSense empowers organizations to build resilient, scalable, and granular security architectures. Security enforcement is no longer centralized at one chokepoint but distributed logically across the network, aligning with modern Zero Trust and micro-segmentation principles.

Chapter 44: Educational Labs with pfSense

Chapter Objective

This chapter equips instructors and trainers to create functional virtual labs using pfSense, focused on:

Understanding fundamental perimeter security concepts.

Experimenting with real rules, policies, segmentation, NAT, and VPN.

Simulating attacks and defensive responses.

Evaluating students’ practical skills.

We’ll detail configurations from scratch, necessary resources, practice scenarios, and evaluation rubrics.

1. Why Use pfSense in an Educational Lab?

pfSense is ideal for teaching because it is:

Open source and free—no costly licenses.

Extremely flexible and feature-rich.

GUI-driven and intuitive, perfect for students new to CLI.

Based on FreeBSD, offering Unix-like system learning.

Fully compatible with virtual environments for multiple simultaneous simulations.

2. Virtual Lab Requirements

A. Hardware & Software

Resource | Minimum Recommendation
Instructor PC | i5 CPU, 16 GB RAM, SSD
Student PCs | ≥ 8 GB RAM
Hypervisor | VirtualBox, VMware Workstation, or Proxmox
Virtual Networking | VirtualBox Host-only, Internal LAN, NAT
pfSense Image | Official ISO from pfsense.org
Optional | GNS3 or EVE-NG for complex network simulation

3. Basic Lab: Perimeter Security

Scenario: Implement Internet access control from an internal network.

Virtual Device | Role | LAN IP | WAN IP / Gateway
pfSense | Firewall | 192.168.1.1 | NAT or DHCP on NAT
PC1 (client) | User | 192.168.1.10 | 192.168.1.1
PC2 (attacker) | Tester | 192.168.1.20 | 192.168.1.1

Steps:

Install pfSense in VirtualBox with two NICs (NAT + Host-only).

Configure WAN (NAT) and LAN (Host-only).

Attach PC1 and PC2 to the Host-only network.

On pfSense create firewall rules:

Block ICMP from PC2.

Allow only HTTP/HTTPS for PC1.

Verify connectivity and review logs.

Competencies:

Understanding IP-based rules.

Port and protocol control.

Log interpretation.

4. Intermediate Lab: VLAN Segmentation

Scenario: Separate administration network from student network.

VLAN | Description | IP Range
10 | Administration | 192.168.10.0/24
20 | Students | 192.168.20.0/24

Infrastructure:

pfSense with LAN interface attached to a managed (or virtual) switch.

Switch configured for 802.1Q tagging (or simulated in GNS3).

Virtual clients on each VLAN.

Tasks:

Configure VLAN subinterfaces in pfSense.

Create rules to:

Allow Internet access only from VLAN 20.

Allow full access from VLAN 10.

Block inter-VLAN traffic.

Evaluation:

Is VLAN isolation enforced?

Is permitted service access maintained?

5. Advanced Lab: Site-to-Site VPN

Scenario: Connect two sites (pfSense-A and pfSense-B).

Element | Site A (Central) | Site B (Remote)
pfSense | 192.168.1.1 | 10.0.0.1
Internal LAN | 192.168.1.0/24 | 10.0.0.0/24

Objectives:

Configure an IPsec tunnel between the two sites.

Permit traffic only between specific hosts.

Use NAT-T if intermediate firewalls exist.

Evaluation:

Verify tunnel establishment.

Test connectivity between allowed hosts.

Review tunnel logs for errors.

6. Attack Simulation

Suggested Scenario:

Launch an nmap scan from an attacker VM.

Capture the attempt on pfSense with logging enabled.

Automatically block via Snort or manual rules.

Recommended Tools:

Kali Linux or ParrotOS VM for the attacker.

Wireshark for monitoring.

Snort or Suricata integrated into pfSense.

7. Educational Rubrics and Evaluation

Sample Evaluation Rubric

Criterion | Points
Correct implementation of firewall rules | 10
Effective network isolation | 10
Logging and explanation of logs | 10
Clear documentation of configuration | 5
Analysis of rule impact | 5
Total | 40

8. Best Practices for Instructors

Define clear objectives for each lab.

Introduce intentional rule errors to analyze their impact.

Use screenshots or screencasts for feedback.

Encourage thorough documentation as part of technical learning.

Mix GUI-based and CLI/XML exercises to deepen understanding.

9. Supplemental Resources

Pre-configured OVA lab files.

Backup and restore scripts to accelerate setup.

Documentation templates for student submissions.

A Git repository for storing configurations.

A well-designed pfSense lab lets instructors cover everything from basic network security principles to real-world perimeter defense architectures. Its versatility makes pfSense an essential educational tool in technical courses and cybersecurity training.

Chapter 45: How to Teach pfSense in a Virtual Classroom

Chapter Objective

Equip educators with strategies, tools, and methodologies to teach pfSense in a fully virtual setting, integrating simulated labs, hands-on assessments, multimedia materials, and synchronous/asynchronous sessions. The focus is on competency-based, technical, and formative instruction.

1. Why Teach pfSense Virtually?

Teaching pfSense in a virtual classroom allows you to:

Provide universal access regardless of location.

Scale your course more easily.

Leverage reproducible, simulated environments.

Incorporate real-world exercises without risking production infrastructure.

Foster student autonomy and problem-solving skills.

2. Recommended Virtual Classroom Infrastructure

For the Instructor

Solution | Key Advantage
VirtualBox + OVA | Easy to distribute and replicate
Proxmox VE | Centralized lab management
EVE-NG / GNS3 | Integration with broader network topologies
Moodle or other LMS | Organize content and manage assessments

For Students

CPU: minimum 4 cores

RAM: minimum 8 GB

Disk space: 50 GB free

OS: Windows, Linux, or macOS

Course Resources

pfSense ISO

Step-by-step PDF guides

Short video modules

Installation scripts and VM snapshots

3. Preparing the Virtual Lab Environment

Option A: Distribute a Preconfigured VM

Build a VM with pfSense installed and basic setup: WAN & LAN interfaces, default rules, web GUI accessible from another VM.

Export as an OVA or VDI.

Provide import instructions and host-only network configuration.

Option B: Each Student Builds from Scratch

Supply the ISO, installation instructions, and a checklist.

Grade installation errors as part of the exercise.

4. Recommended Course Structure

Week | Main Topic | Practical Deliverable
1 | Introduction to pfSense & Virtualization | Screenshot of the lab environment
2 | GUI Access & Initial Configuration | Basic settings and successful ping
3 | Creating Firewall Rules | Rules that block and allow specified traffic
4 | NAT & Port Forwarding | Access to an internal web server
5 | VLANs & Segmentation | Simulated segmented network
6 | VPN Site-to-Site or Remote Access (OpenVPN) | Functional, verified tunnel
7 | Web Filtering & QoS (optional) | Implemented policies
8 | Final Project (complete firewall with real cases) | Fully documented and functional report

5. Teaching Dynamics: Effective Virtual Sessions

A. Synchronous Classes

Duration: up to 90 minutes

Structure:

25 min theory

50 min live demo

15 min Q&A

B. Asynchronous Components

Recordings of live sessions

Active discussion forums (Discord, Telegram, Moodle)

Short “mini-challenges” with gamified rewards

6. Guided Labs and Assessments

Sample Exercise

Topic: Port Forwarding

Scenario: Internal web server accessible from WAN

Objective: Configure NAT and verify external access

Deliverable:

Screenshot of NAT rule

Successful browser test to <host>:<port>

Brief explanation submitted as PDF or video

Evaluation Rubric (10 points)

Criterion | Points
Working NAT configuration | 4
Clear documentation | 2
Packet-flow explanation | 2
Analysis of potential failures | 2

7. Digital Resources for the Virtual Classroom

pfSense Book: Official documentation

Packet Tracer labs: For logical topology exercises

YouTube videos: Step-by-step visual guides

Discord/Telegram channel: For live support and peer discussion

8. Strategies to Motivate Students

Pose real-world challenges (e.g., “Configure a school’s firewall”).

Assign roles: admin, attacker, auditor.

Offer certificates for completing the final project.

Include peer review as part of the evaluation.

9. Suggested Final Project

Challenge: Build a secure network for a fictitious small business.

Minimum Requirements:

One WAN interface connecting to the Internet

Two VLANs (Administration, Public)

NAT for an internal web server

OpenVPN for remote access

Captive Portal for guest users

Submission:

OVA or VDI of the lab VM

Step-by-step documentation

3–5 minute video walkthrough

Teaching pfSense virtually is not only feasible but highly effective when supported by active learning methodologies, guided labs, multimedia resources, and a well-designed lab architecture. This approach builds both technical proficiency and critical thinking skills required for real-world security solutions.

Chapter 46: Designing an Academic Program in Perimeter Security

Chapter Objective

Provide a step-by-step guide to designing a complete academic program in Perimeter Security, with a special focus on teaching technologies such as firewalls, segmentation, monitoring, and incident response. Incorporate educational standards, active methodologies, hands-on tools, and robust evaluation criteria.

1. What Is an Academic Program in Perimeter Security?

An academic program in perimeter security is a structured teaching plan aimed at equipping students with the competencies to:

Design, implement, and maintain edge-of-network security.

Manage firewalls (iptables, nftables, pfSense).

Apply segmentation, access control, and intrusion-detection policies.

Simulate and mitigate external threats.

Understand relevant legal and ethical frameworks.

A strong program should be modular, progressive, and based on real-world challenges.

2. Student Profile and Learning Outcomes

Target Audience:

Computer science, networking, or cybersecurity students.

Technical professionals seeking upskilling.

Instructors training to teach technical courses.

Expected Learning Outcomes:

By program’s end, students will be able to:

Analyze and design a secure network perimeter architecture.

Configure firewalls via CLI and GUI.

Detect and mitigate network threats through rule-based filtering.

Document and enforce security policies.

Teach perimeter-security concepts to others.

3. Modular Program Structure

Level 1: Fundamentals (Theory & Simulation)

Introduction to Perimeter Security

Types of Firewalls

Network Models & Segmentation

Stateful vs. Stateless Filtering

Level 2: Practical Tools (iptables, nftables, pfSense)

Installation & Basic Configuration

Rule Creation, NAT, Port Forwarding

Protocol-, Port-, and Interface-Based Traffic Control

Full Virtual Lab

Level 3: Advanced Implementation

VLANs, VPNs, QoS, High Availability

Integration with LDAP/RADIUS

Captive Portal, Policy-Based User Access

Capstone Project

Level 4: Applied Pedagogy (for Instructors)

Designing Hands-On Activities & Rubrics

Competency-Based Assessment

Graded Labs & Debugging

Managing Virtual Classrooms

4. Teaching Methodologies

Approach | Practical Application
Problem-Based Learning (PBL) | Simulate network threats to be mitigated via firewall rules
Flipped Classroom | Students study theory at home, practice in synchronous online labs
Formative Assessment | Continuous feedback during progressive lab exercises
Gamification | “Missions” with rewards: e.g., “Protect a school network”

5. Digital & Simulation Tools

Virtualization: VirtualBox, Proxmox

Traffic Analysis: Wireshark

Pen-Testing: nmap, hping3, Metasploit

Firewalls: pfSense, iptables, nftables

Course Management: Google Classroom, Moodle, GitBook

6. Module Design with Hands-On Focus

Each module should include:

Element | Details
Introduction | Context, objectives, real-world application
Guided Activity | Step-by-step lab (virtual or physical)
Use Case | Real scenario, e.g., “Configure a school firewall”
Assessment | Checklist + performance rubric
Additional Media | Videos, readings, review exercises

7. Competency-Based Evaluation Rubrics

Example: “Implement NAT in pfSense”

Criterion | Excellent (4) | Good (3) | Fair (2) | Poor (1)
Correct NAT implementation |  |  |  |
Clear process documentation |  |  |  |
Functional connectivity verification |  |  |  |
Troubleshooting and error resolution |  |  |  |

8. Instructor Resources

Editable PDF lab manuals

Step-by-step configuration videos

Common-error guides

Quizzes and flashcards

Git repository of scripts and configurations

Bank of graded lab exercises

9. Program Capstone Project

Requirements:

Implement a secure network for a fictitious organization.

Segment with VLANs.

Apply department-specific firewall policies.

Enable remote-access VPN.

Simulate an attack and apply dynamic rule blocking.

Deliverables:

Network topology diagram

Configuration screenshots

Technical manual

Project defense presentation or video

10. Accreditation & Certification

Suggestions:

Issue digital-badge certificates (Credly, Badgr)

Offer an optional, proctored practical certification exam

Assess via project rubrics with clear scoring

Designing a perimeter-security academic program requires both technical expertise and pedagogical vision. A well-structured, hands-on, collaborative, and modular course enables students not only to configure firewalls but also to design, defend, and teach secure network infrastructures.

Chapter 47: How to Assess Learning in Firewalls

Chapter Objective

This chapter provides a concrete, methodical guide for educators, technical instructors, or academic coordinators to assess students’ learning in firewall courses—both conceptual knowledge and hands-on skills. It integrates formative and summative assessment techniques, lab-based exercises, and performance-oriented rubrics.

1. Why Is Good Assessment Crucial?

In perimeter security education, proper assessment not only verifies knowledge but also:

Validates real configuration and problem-solving skills.

Checks incident-response capabilities.

Ensures students can safely use tools like iptables, nftables, or pfSense.

Develops critical thinking and decision-making under pressure.

2. Applicable Types of Assessment

a) Diagnostic

Before starting, gauges each student’s baseline (e.g. TCP/IP familiarity, Linux/CLI skills).

Example: 10-question quiz on network models and protocols; mini task interpreting a simple iptables rule.

b) Formative

During the course, provides feedback and correction on lab work.

Example: Observe whether a student correctly sets default-deny policies; give live feedback as they build a port-block rule.

c) Summative

At the end of a module or course, focuses on the final product or overall performance.

Example: Capstone project “Build a working firewall for an educational network”; timed lab exam simulating an attack.

3. Practical Assessment Activities

Activity | Skill Assessed | Tools
Configure iptables from scratch | CLI mastery; rule & chain logic | VirtualBox + Linux VM
Simulate an attack with nmap and block it | Threat detection & filtering | nmap, iptables
Create and apply NAT rules | Address translation concepts | pfSense or nftables
Capstone: Firewall for an SME | Analysis, design, execution | All covered tools
Debug a broken configuration | Troubleshooting using logs | journalctl, tcpdump, system logs

4. Competency-Based Rubrics

A clear rubric improves objectivity. Example for “Implementing a firewall in pfSense”:

Criterion | Excellent (4) | Good (3) | Fair (2) | Poor (1)
Functional WAN/LAN rules | All correct & explained | Functional with minor errors | Several missing or non-working | No correct rules applied
Documentation | Clear, technical, step-by-step | Understandable but incomplete | Confusing or incomplete | Absent
Proof of operation | All tests passed & logged | 1–2 minor test failures | Multiple tests fail | No demonstration
Minimum security measures | Default-deny + port blocking + unknown-traffic drop | Missing 1–2 elements | Only one security measure | System exposed

5. Scenario-Based Challenges

Pose real or simulated scenarios that require students to act as security admins:

Challenge 1: “School Network Under Attack”

The existing firewall lets unauthorized connections through. In iptables, write rules to:

Block all incoming traffic except HTTP and SSH.

Allow only outbound traffic to ports 80, 443, and 53.

Log all denied connection attempts.

Challenge 2: “Design from Scratch”

Student builds a pfSense-based network from zero:

Assign WAN/LAN interfaces.

Establish basic permit/deny rules and NAT.

Enforce default-deny policy.

Enable OpenVPN for remote access.

6. Progress Indicators

Define observable milestones throughout the course:

Indicator | How to Measure
Understanding of default policies | Verbal explanation or written policy statement
Ability to write rules | Completes in class without prompts
CLI proficiency | Uses commands confidently, without copy/paste
Technical autonomy | Fixes common errors independently

7. Automated Assessment (Optional)

For online courses, consider:

LMS quizzes (Moodle/Canvas) with auto-grading.

Interactive labs (e.g. NetAcad, Hack The Box) that validate student configurations.

Scripts (bash) that check a VM’s firewall rules for correctness.

8. Assess the “Why,” Not Just the “How”

Students should explain:

Why a certain port is blocked.

What happens if rule order is reversed.

The impact of an INPUT-DROP policy without exceptions.

This ensures deep understanding rather than rote memorization.

9. Self- and Peer-Assessment

Encourage self-review and peer feedback:

Checklists for students to verify their own configurations.

Group reviews where students evaluate each other’s lab work.

Shared rubrics and anonymous feedback forms.

10. Tools & Templates

Prepare reusable assets:

Rubrics in PDF/Excel.

Editable quiz templates (Google Forms).

Automated test scripts (iptables-test.sh).

Instructor observation checklists.

Minimal-configuration checklists for each lab.

Well-designed assessment reinforces hands-on learning, fosters real-world problem-solving, and ensures students are ready to defend actual networks. Evaluate not only technical execution but also logical reasoning and systemic understanding of perimeter security.

Chapter 48: Creating Exams and Network Tests

Chapter Objective

This chapter provides technical instructors and cybersecurity educators with a practical, methodological guide for designing exams, hands-on network tests, and performance-based assessments in simulated or real environments. It covers theoretical, practical, mixed, automated, and scenario-based tests—all aligned with perimeter security and firewall management learning objectives.

1. Key Principles in Technical Assessment

Before designing a test, clearly define:

Element | Description
Competency to assess | Conceptual knowledge, tool usage, incident response, etc.?
Technical context | Virtual environment, physical lab, online?
Time available | Short quiz, final project, intensive lab?
Student level | Beginner, intermediate, advanced?

2. Types of Technical Assessments in Perimeter Security

a) Theoretical Technical Exams

Multiple-choice, true/false, fill-in-the-blank command snippets, identify errors.

Test terminology and core concepts (connection state, NAT, zones, policies, logic).

Sample questions:

“What is the most secure default policy for an INPUT chain?”

“What does this rule do?

bash

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

```” 

b) Command-Line (CLI) Tests

Students execute specific commands on a Linux or FreeBSD system.

Assess technical precision and understanding of rule structure.

Sample practical:

“Create an nftables rule that blocks all incoming traffic except SSH and HTTP. Apply it and verify with nmap.”

c) Scenario Simulations

Based on real-world situations.

Span multiple layers: firewall configuration, threat detection, documentation.

Sample scenario:

“You are the network administrator of a school. Students are accessing gaming sites during class hours. Implement a pfSense solution that blocks gaming domains while allowing educational browsing.”

d) Final or Certification Projects

Comprehensive assessment at course end.

Include design, documentation, implementation, and testing.

Sample deliverable:

“Design and deploy a complete firewall with default-deny policy, NAT, specific block rules, and logging for a network with three segments (Administration, Students, Wi-Fi). Use iptables or pfSense, and document everything in a technical report.”

3. Designing a Practical Exam Step by Step

Define concrete objectives

e.g. “Create and apply NAT rules in pfSense,” “Analyze logs to detect a port scan,” “Configure VLAN-segmented firewall rules.”

Structure by difficulty levels

Level 1 (Basic): Allow HTTP traffic rule.

Level 2 (Intermediate): Default-deny policy plus exceptions.

Level 3 (Advanced): Simulate and block attacks, enable logging, interpret results.

Prepare the virtual environment

Linux VM with iptables

Linux VM with nftables

pfSense VM in VirtualBox with multiple NICs

Segmented networks, simulated users, attack scripts (hping3, nmap)

4. Tools to Support Network Testing

Tool | Use
nmap | Port scans to validate firewall rules
tcpdump or Wireshark | Packet-level traffic analysis
hping3 | Simulate network attacks (SYN floods, etc.)
iptables-save / nft list ruleset | Verify applied configurations
pfSense logs | Confirm rule matches and blocks via GUI
Moodle + remote VMs | Online test integration

5. Sample Practical Exam Template

Title: Basic Firewall Final Exam

Duration: 90 minutes

Environment: Linux VM with iptables + VirtualBox network scenario

Sections & Points

Firewall Setup (30 pts)

Apply default-deny (DROP) policy on INPUT and FORWARD.

Allow outbound HTTP/HTTPS.

NAT Configuration (20 pts)

Implement NAT for network 192.168.10.0/24 to Internet.

Specific Blocks (30 pts)

Block social networks via DNS and HTTP.

Verification (10 pts)

Use nmap and curl to test rules.

Technical Report (10 pts)

Document steps and include screenshots.

6. Automating Assessment

For large or remote classes, consider:

Validation scripts in bash or Python that check presence of specific rules.

Automated checkpoints in network emulators (GNS3, EVE-NG) or using Ansible.

LMS integrations with per-student VM reset on login.

Example validation script:

bash

#!/bin/bash

# Check SSH rule exists

iptables -C INPUT -p tcp—dport 22 -j ACCEPT && echo "OK" || echo "FAIL"

7. Rubric-Based Assessment

Criterion | Excellent (4) | Good (3) | Fair (2) | Poor (1)
Rule application | Precise, no errors | One minor error | Two or more errors | Incorrect configuration
Security posture | Default-deny, only needed ports open | Missing 1–2 essentials | Too permissive | Firewall ineffective
Verification | Comprehensive tests + logs | Some tests performed | Partial testing | No verification
Documentation | Clear and detailed | Adequate with gaps | Unclear | Absent

8. Final Tips for the Instructor

Provide identical lab environments to ensure fairness.

Time each exercise to gauge realistic exam duration.

Offer minimal hints (“unlock phase”) if students get stuck.

In virtual courses, consider peer review or screen-recorded submissions.

Well-designed exams and network tests do more than grade performance—they foster critical thinking, autonomy, and operational security mindset. Each assessment should mirror real-world challenges, ensuring students not only learn but can apply perimeter defense skills professionally.

Chapter 49: Final Projects — Ideas and Templates

Chapter Objective

Provide instructors with a practical, structured guide to planning, designing, and supervising capstone projects focused on perimeter security. These projects should integrate course knowledge, foster analytical and deployment skills, and emphasize professional documentation.

1. Traits of an Effective Final Project

A strong capstone should:

Apply real technical skills (iptables, nftables, pfSense, VLANs, NAT, policy design).

Be deployable and testable in virtual, simulated, or real environments.

Promote independent problem-solving.

Include clear, professional documentation.

Combine at least two domains (e.g. firewall + segmentation, or NAT + VPN).

2. Assessable Competencies

Secure architecture design

Firewall policy implementation

Rule creation in iptables, nftables or pfSense

Traffic segmentation by zone/VLAN

Log collection and analysis

Configuration documentation

Incident-response to simulated attacks

3. Final Project Ideas

Project 1: Corporate Firewall with iptables

Office-style network (WAN, LAN, DMZ)

iptables deployment:

Default-deny policy

NAT and port forwarding

SSH access only from a specific IP

Logging of failed attempts

Simulate attacks with nmap and hping3

Bonus: Automate with a Bash script

Project 2: Secure Segmentation with pfSense

Three VLANs:

Administration (full access)

Guests (HTTP/HTTPS only)

Students (restricted)

Interface-specific firewall rules

Captive Portal for guests

Access logs, connectivity tests, and Wireshark captures

Project 3: Multisite VPN for an Organization

Two sites connected via OpenVPN or IPsec on pfSense

Firewall and NAT at both locations

Tunnel verification and traffic filtering

Internal segmentation rules

Project 4: Attack and Defense Lab

Simulated network with attacker VM (Kali Linux), server, and firewall

Attacks: port scans, SSH brute force, DNS injection

Reactive firewall: IP blocking, alerts

Logging and automated response

Project 5: Automated nftables Firewall

Build a home-or-SMB rule set with nftables

Create a systemd-driven script to load rules on boot

Log management and integration with fail2ban for SSH attacks

4. Student Submission Template

arduino

/FinalProject_StudentName/

│

├── Technical_Document.pdf

├── Architecture_Diagram.png

├── Firewall_Script.sh  # or .nft

├── Evidence_Screenshots/

│  ├── rules_applied.png

│  ├── logs_block.png

│  └── connectivity_test.png

└── Analysis_Report.txt

Technical Document Sections

Section | Details
Executive Summary | What the project does and which problem it solves
Network Design | Diagram of zones, IPs, devices, firewall
Security Objectives | What is protected and how (e.g. blocking attacks, segmentation, filtering)
Step-by-Step Configuration | Commands or GUI steps detailing each rule or setting
Validation | Tests performed, logs, tools used
Conclusions | Challenges encountered and possible improvements

5. Evaluation Rubric

Criterion | Excellent (4) | Good (3) | Fair (2) | Poor (1)
Network design & documentation | Complete, professional, precise | Minor details missing | Ambiguous or incomplete | Lacks technical depth
Technical implementation | Fully functional, error-free | Works with minor tweaks | Several small errors | Incomplete or non-functional
Applied security | Precise rules, correct blocking | Some rules missing | Too permissive | Insecure
Verification & testing | Clear logs & well-documented tests | Some tests missing | Minimal validation | No testing
Presentation & structure | Clear, well-organized, professional | Some formal errors | Hard to follow | Disorganized

6. Recommended Development Environments

VirtualBox + pfSense + Debian/Kali VMs

GNS3 or EVE-NG for complex topologies

Docker + iptables containers for automated testing

Moodle + Nextcloud for submissions

7. Instructor Tips

Require screenshots, logs, and connectivity proofs.

Share the rubric up front.

Allow paired work only with clearly defined roles (configuration vs. documentation).

If time permits, have students defend their project live or via recording.

Use automated checklists or grading scripts for large classes.

Well-designed capstone projects cement students’ hands-on skills in perimeter security, foster critical thinking, and produce professional portfolios for their future careers.

Chapter 50: Gamification in Teaching Firewalls

Chapter Objective

Transform the traditional teaching of firewalls (iptables, nftables, pfSense) into a more dynamic, engaging, and motivating experience through gamification—an educational methodology that applies game mechanics to learning contexts.

1. What Is Gamification?

Gamification applies typical game elements—points, rewards, missions, levels, competition—to non-game settings (like education) to boost student engagement, motivation, and performance. In perimeter-security training, students “play” at defending a network, attacking simulated environments, and completing technical challenges.

2. Key Gamification Elements in Cybersecurity

Element | Practical Application
Challenges/Missions | Configure rules that block specific simulated attacks.
Difficulty Levels | From simple block rules up to segmented networks with NAT and VPNs.
Rewards | Badges, certificates, extra credit points.
Role-Playing | Red Team (attacker) vs. Blue Team (defender).
Visual Progression | Leaderboards, progress dashboards.
Simulations | Mini attack/defense labs.
Narrative | Story context (“protect a network from ransomware”).

3. Gamified Firewall Activities

Activity 1: The Unbeatable Firewall

Objective: Build a firewall configuration that repels all simulated threats.

Setup: Individual lab in VirtualBox (Debian + Kali + pfSense).

Challenges:

Block port scans.

Allow only outbound HTTPS.

Log SSH connection attempts.

Prevent IP spoofing.

Win Condition: If the Kali attacker cannot penetrate using nmap, hydra, ping, the student succeeds.

Activity 2: Red Team vs. Blue Team

Format: Pair or small-group competition.

Red Team: Launch controlled attacks (DoS, scans, brute-force).

Blue Team: Write iptables/nftables/pfSense rules to detect and block them.

Time: 60–90 minutes per round.

Scoring:

+5 points for each attack blocked.

+3 points for each rule documented.

–2 points for blocking valid services.

Tools: tcpdump, logcheck, Wireshark to demonstrate successes.

Activity 3: Firewall Capture the Flag (CTF)

Structure: Mini-servers on a simulated network each host a “flag” that’s accessible if the firewall is misconfigured.

Example Flags:

On an SSH server accidentally left open.

Accessible only if ICMP is permitted.

Captured by evading a miswritten NAT rule.

Goal: Reconfigure the firewall so no flag can be reached from outside.

Platform: VirtualBox, Vagrant, Docker, or EVE-NG.

4. Supporting Platforms & Tools

Kahoot / Quizizz: Quick theory quizzes and friendly competition.

TryHackMe: Guided Red Team exercises.

Hack The Box Academy: Defensive (Blue Team) labs featuring firewalls.

PicoCTF / CTFd: Build custom challenges with scoring.

Moodle + Gamification Plugins: Track progress with points and badges.

Google Sheets or Grafana: Live leaderboards and progress charts.

5. Sample Points System

Action | Points
Correctly configure default-deny policy | 10
Document a rule with rationale | 5
Detect and block a port scan attempt | 15
Implement functional NAT | 10
Allow necessary traffic while blocking threats | 20
Successfully defend in Red vs. Blue | 25
Active participation and teamwork | 5

Achievement Levels:

Novice: 0–50 points

Guardian: 51–100 points

Firewall Master: 101+ points

6. Best Practices for Instructors

Emphasize that gamification does not compromise rigor.

Encourage collaboration rather than unhealthy competition.

Use mixed rubrics covering both technical skill and teamwork.

Provide immediate feedback (“Why did rule X fail?”).

Scale challenges progressively and fairly.

Prompt critical thinking: “Why does this rule enhance security?”

7. Gamified Challenge Template

Challenge Name: “Defend Agency X’s Network”

Objective: Prevent intruders from accessing sensitive LAN resources.

Scenario: Simulated network with DMZ, LAN, and external attacker.

Duration: 90 minutes

Tools: pfSense, Kali Linux, Wireshark

Deliverables:

Screenshots of the configured firewall

Logs of successful blocks

Network diagram before and after

Technical reflection write-up

Gamification turns the classroom into an exciting, realistic security lab. Students not only learn theory but actively experience defending real systems—boosting motivation, retention, and mastery of complex firewall concepts.

Chapter 51: Integrating with Simulators and Online Platforms (GNS3, EVE-NG, NetLab)

Chapter Objective

In this chapter, we cover how to integrate advanced virtual environments using network simulators like GNS3, EVE-NG, and NetLab for teaching and practicing firewalls and perimeter security. You’ll learn how to build reproducible, realistic labs that students and professionals can access—even without physical hardware.

1. Why Use Simulators?

Perimeter security involves configuring and analyzing devices such as firewalls, routers, switches, and servers. Simulators let you:

Build realistic environments without expensive hardware.

Easily repeat labs.

Capture traffic for analysis.

Encourage hands-on, self-directed learning.

Deploy real firewalls (pfSense, iptables, nftables) inside complex topologies.

2. Key Platforms

GNS3 (Graphical Network Simulator 3)

Designed for complex network simulations.

Uses QEMU, Dynamips, and Docker for virtualization.

Supports pfSense, Linux, MikroTik images, etc.

Ideal for mixed topologies (Cisco + Linux + firewalls).

EVE-NG (Emulated Virtual Environment – Next Generation)

Web-based network lab platform.

Multi-user support.

Runs Linux, Cisco, Fortinet, Palo Alto, pfSense, and more.

Widely used in certification courses and academia.

NetLab+

Cisco/Network Development Group’s educational lab platform.

Centralized remote lab access.

Great for educational institutions.

Less customizable, but very user-friendly.

3. Installing Firewalls in Simulators

A. Installing pfSense in GNS3 or EVE-NG

Requirements: pfSense ISO or QCOW2 image; create a QEMU VM with ≥1 GB RAM and 2 NICs.

EVE-NG Steps:

Upload your ISO to /opt/unetlab/addons/qemu/pfsense-<version>/.

Convert it:

bash

qemu-img convert -f iso -O qcow2 pfSense.iso virtioa.qcow2

Fix permissions:

bash

/opt/unetlab/wrappers/unl_wrapper -a fixpermissions

In the GUI, add a pfSense node, assign WAN/LAN interfaces, and connect.

Initial Tests:

Ping between a Linux client VM and the pfSense gateway.

After allowing HTTP/HTTPS, verify web browsing works.

B. Labs with iptables/nftables on Debian/Ubuntu

Create a minimal Linux VM.

Install tools:

bash

sudo apt install iptables nftables tcpdump net-tools

Add a second interface to simulate NAT or a DMZ.

Apply rules manually or via /etc/nftables.conf.

Example nftables config snippet:

nft

table inet filter {

chain input {

type filter hook input priority 0; policy drop;

ct state established,related accept

iif "lo" accept

ip protocol icmp accept

tcp dport { 22, 443 } accept

}

}

4. Sample Practical Scenario (GNS3 or EVE-NG)

Perimeter network with a DMZ protected by pfSense and internal VLAN segmentation

Topology:

LAN client

Web server in DMZ

pfSense firewall

External attacker (Kali)

Virtual switch with VLANs

Lab Objectives:

Configure pfSense WAN, LAN, and DMZ interfaces.

Apply firewall rules to permit only HTTP to the DMZ.

Block any unauthorized external traffic.

Implement NAT for the web server.

Capture traffic with tcpdump to verify attacks/blocks.

Tools: Wireshark, Kali Linux (nmap, hping3, sqlmap), Apache/nginx web server with logs.

5. Integrating into Educational Settings

In a Virtual Classroom:

Deploy EVE-NG Community or Pro on-premises or in the cloud.

Assign each student their own lab scenario.

Evaluate using rubrics: correct configuration, evidence of blocking, documentation.

For Self-paced Labs:

Package and share .unl (EVE-NG) or .gns3project files.

Provide step-by-step guides in PDF or Markdown.

Set up Red Team vs. Blue Team challenges.

6. Pre-built Lab Libraries

GNS3 Marketplace: Community topologies with firewalls.

GitHub Repositories: e.g. “Awesome GNS3 Labs.”

TryHackMe & Hack The Box Labs: Offensive and defensive scenarios.

NetLab+: Cisco-focused but adaptable for security labs.

7. Platform Comparison

Feature | GNS3 | EVE-NG | NetLab+
Local install required | Yes | No (web-based) | No
Multi-user support | Limited | Yes (Pro) | Yes
pfSense/Linux integration | High | High | Medium
Learning curve | Moderate | Steep | Low
Ideal for | Advanced students/techs | Universities, certification centers | Basic Cisco training
Remote access | Limited | Native | Native
VLAN & real traffic support | Yes | Yes | Partial

8. Best Practices for Your Own Labs

Define clear learning objectives.

Start with simple topologies (LAN ↔ pfSense ↔ WAN).

Gradually add complexity (DMZ, IDS, VPN).

Document everything: diagrams, steps, scripts.

Use captures (tcpdump, Wireshark) as proof of learning.

Version lab scenarios in Git or Nextcloud.

Simulators like GNS3, EVE-NG, and NetLab are essential for teaching perimeter security hands-on and at scale. They let you experiment with real firewall rules, build defensive architectures, analyze malicious traffic, and better prepare students in safe, reproducible, and scalable environments.

Chapter 52: Open Educational Resources for Instructors

Chapter Objective

This chapter guides cybersecurity instructors—especially those teaching perimeter security—in identifying, using, adapting, and creating Open Educational Resources (OER). It also explores collaborative methods for sharing knowledge and building practical, reusable, up-to-date teaching materials.

1. What Are Open Educational Resources (OER)?

OER are teaching and learning materials made freely available under licenses that permit use, modification, and redistribution. In the context of perimeter security, these include:

Hands-on guides for iptables, nftables, pfSense

Virtual labs for GNS3 or EVE-NG

Well-commented scripts and configuration templates

Assessment rubrics

Slide decks, videos, infographics

Key benefits:

Accessibility: No paywalls or proprietary software required.

Adaptability: Materials can be tailored to different skill levels.

Collaboration: Encourage co-creation among instructors.

Continuous update: Leverage community contributions.

2. Types of Useful OER for Perimeter Security

Resource Type | How Instructors Use It | Practical Example
Scripts | Automate firewalls and labs | Bash script of basic iptables or nftables rules
Configuration templates | Standardize lab setups | pfSense LAN/DMZ config template
Step-by-step guides | Guided hands-on activities | “How to block an Nmap scan with nftables”
Virtual topologies | Complete network simulations | GNS3 lab with pfSense and Kali Linux
Assessment rubrics | Objective grading of labs | Criteria for evaluating perimeter security in VMs
Videos | Flipped-classroom content | pfSense installation walkthrough
Slides | Concise theory with examples | Segmented network architecture overview
Quizzes | Rapid knowledge checks | Self-quiz on firewall policy concepts

3. Recommended OER Platforms

GitHub / GitLab
Ideal for sharing scripts, lab definitions, and documentation with version control and collaboration.
Example: “Awesome-Firewalls” repos collecting iptables/nftables/pfSense resources.

Moodle / Canvas Commons
Share complete course modules—including SCORM packages, quizzes, and labs.

LibreTexts / OpenStax / OER Commons
Host open textbook chapters and learning materials for higher ed and technical schools.

NetAcad (Cisco) & NDG
Semi-open networking courses; some labs and materials are freely available.

YouTube / PeerTube
Video demonstrations, packet captures, firewall walkthroughs.

4. Finding Useful OER

Use advanced search strings like:

arduino

"pfSense lab filetype:pdf site:oercommons.org"

"iptables tutorial filetype:md site:github.com"

"nftables classroom OR lab filetype:zip"

Suggested keywords:

“OER firewall”

“open lab nftables”

“GNS3 open source labs”

“pfSense free training material”

5. Creating Your Own OER

Choose a license: e.g. Creative Commons (CC-BY, CC-BY-SA).

Provide editable source: Markdown, ODT/PDF, firewall configs.

Structure clearly:

Learning objectives

Prerequisites

Step-by-step instructions

Screenshots/diagrams

Assessment activities

Host in an open repo: GitHub/GitLab, EVE-NG community, Moodle, etc.

Tag and categorize to ease discovery.

Solicit feedback and encourage community improvements.

6. Practical Example: Publishing an nftables Lab as OER

Scenario: Simple firewall protecting a web server.

Resource structure:

bash

/nftables-web-lab/

├── README.md  # Objectives & overview

├── lab_diagram.png  # Topology diagram

├── firewall_script.sh  # Commented nftables script

├── evaluation_rubric.md

├── setup_guide.pdf  # VM setup instructions

└── LICENSE.txt  # CC BY-SA license

Platform: GitHub or GitLab

Suggested tags: nftables, firewall, linux, lab, educational

7. Collaborative & Community Involvement

Join communities like:

EduGitHub – collaborative teaching materials

LibreSecurity – open cybersecurity resources

Reddit /r/netsecstudents or Stack Exchange sites (Server Fault, Network Engineering)

Collaborative formats:

Multi-institution lab creation projects

Hackathons or lab-hack marathons

Translating/adapting existing OER

8. Evaluating & Improving OER Continuously

Use tools such as:

LimeSurvey / Google Forms for student feedback

Peer reviews among instructors

Version control to manage updates

Suggested OER quality rubric (out of 50):

Criterion | Points
Pedagogical clarity | 10
Reusability (open formats) | 10
Practicality & replicability | 10
Technical correctness | 10
Integrated assessment | 10
Total | 50

9. Highlighted OER to Get Started

Resource | Content | Platform
Awesome GNS3 | Public network lab topologies | GitHub
LibreTexts Cybersecurity | Open textbook chapters on cybersecurity | LibreTexts
pfSense Book (Libre) | Comprehensive technical manual | Netgate Docs
Open Security Training | Free security courses | Web
TryHackMe (Free labs) | Interactive defensive/offensive labs | Web
GitHub: iptables examples | Useful classroom scripts | GitHub

Open Educational Resources empower wider access, enrich teaching practice, and foster collaboration in perimeter security. Mastering their use, creation, and publication builds a more open, up-to-date, and effective educational community—without relying on proprietary or costly solutions.

Chapter 53: How to Keep Technical Content Up to Date

Chapter Objective

This chapter is aimed at instructors, trainers, and professionals who develop or maintain materials on firewalls, packet filtering, segmentation, iptables, nftables, pfSense, and secure networking. It provides a practical approach to ensuring that your materials remain current, applicable, and technically consistent. You will learn to:

Detect when content becomes obsolete.

Establish a regular update cycle.

Use tools to track changes in key technologies.

Keep guides, labs, and scripts in sync with current software versions.

Version and document changes for your students or the community.

1. Why Is Updating Critical?

Perimeter security technologies evolve constantly:

iptables is transitioning toward nftables.

pfSense regularly updates its GUI, underlying OS, and syntax.

New Linux kernel modules can affect rule compatibility.

Best practices shift over time.

If you don’t update regularly, you risk:

Teaching obsolete practices.

Frustrating students when labs break.

Promoting real-world insecure operations.

2. A Practical Content-Update Workflow

Recommended cycle: every 6–12 months

Inventory Your Materials

List all files: PDFs, scripts, lab docs, slide decks.

Tag each with: technology used, software version, last review date.

Monitor Technology Changes

Did pfSense release a new version?

Has iptables/nftables gained new features or modules?

Technical Validation

Spin up a virtual lab and run your old exercises on the latest versions.

Confirm they still work and behave the same way.

Pedagogical Review

Is the example still realistic in 2025?

Could you integrate new technologies (e.g., EDR, zero-trust concepts)?

Update

Revise syntax, screenshots, verification commands, or even entire lesson focus.

Versioning & Publication

Document what changed and why in a changelog.

Push updates to your GitHub repo or LMS.

3. Tools for Tracking Changes

Tool | Use | Example
RSS feeds / Feedly | Follow release notes and changelogs | Subscribe to pfSense Release Notes
GitHub Watch | Get notifications on project updates | Watch nftables/nftables or Netgate/pfsense
Professional networks | Spot shifts in best practices | Twitter/X, Mastodon, Reddit /r/netsec
Security Weekly / ThreatPost | Stay on top of exploit trends | Adapt content when new threats emerge
OS package changelogs | Track distro version updates | apt changelog nftables

4. Practical Example: Updating an iptables Lab to nftables

Original scenario:

A lab that uses iptables to block ICMP from an external network to a server.

What we discovered:

Ubuntu 24.04 now uses nftables by default.

The old command

bash

iptables -A INPUT -p icmp—icmp-type echo-request -j DROP

is no longer persisted under nftables.

Update steps:

Rewrite in modern nftables syntax:

bash

nft add table inet filter

nft add chain inet filter input { type filter hook input priority 0; policy accept; }

nft add rule inet filter input ip protocol icmp drop

Add a pedagogical note:

“iptables remains available as a compatibility layer but is not recommended for new deployments.”

Replace screenshots, verification steps (e.g., ping) and lab instructions.

Save the revised lab as lab_2025_icmp_block_nftables.md.

5. Best Practices for Keeping Content Fresh

Modularize your materials. Keep lessons in small, replaceable files.

Version everything: include version numbers or dates (e.g., v2.1 / Apr 2025).

Maintain a changelog documenting what changed and why.

When possible, offer both iptables and nftables examples side by side.

Collect student feedback—if something consistently breaks, it likely needs updating.

6. Hands-On Lab: Detect and Update

Objective: Take an old iptables script and adapt it to nftables.

Starting script:

bash

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

iptables -A INPUT -j DROP

Student activity:

Test it on a current VM—note any errors or deprecation warnings (dmesg, journalctl).

Rewrite using nftables:

bash

nft add rule inet filter input tcp dport 22 accept

nft add rule inet filter input drop

Document the changes.

Validate with nmap and ping.

7. Collaborative Updates Among Instructors

Host materials on GitHub so multiple teachers can contribute.

Assign roles: technical reviewer, pedagogical editor, lab tester.

Use a shared review checklist:

Item | ✅
Works on latest stable OS |
Uses current tools (iptables vs. nftables) |
Scenario is realistic and up to date |
Outputs and screenshots match real results |
Explanations are pedagogically clear |

8. Continuous Assessment of Content Health

Adopt an internal rubric:

Criterion | Score (1–5)
Technical currency | 5
Clarity of commands and syntax | 5
Relevance of scenario | 5
Alignment with module learning outcomes | 5
Documentation of changes (changelog) | 5

9. Resources for Staying Up to Date

Netgate Blog: https://www.netgate.com/blog

nftables Wiki: https://wiki.nftables.org

LinuxSecurity.expert

firehol/blocklist-ipsets on GitHub

Linux kernel changelogs: https://www.kernel.org/category/changelogs.html

Hacker News (Networking tag): https://news.ycombinator.com/tag/networking

Keeping technical content current is not only a logistical challenge but a professional responsibility. In the fast-moving field of perimeter security, outdated materials can compromise both real networks and effective student learning. With a clear methodology, collaborative tools, and a pedagogical mindset, you can ensure your curriculum always reflects the latest best practices and technologies.

Chapter 54: Ethics and Legality in Teaching Security

Chapter Objective

This chapter aims to establish the ethical, legal, and pedagogical foundations for teaching perimeter security, defensive hacking, firewalls, traffic analysis, and attack simulations. You will learn to:

Understand the ethical and legal frameworks governing cybersecurity in educational settings

Distinguish valid teaching practices from potentially illegal actions

Implement strategies that foster a culture of responsibility

Document and validate security labs to prevent misuse

Design safe, controlled environments for real-world practice without breaking the law

1. Why Is Ethics Crucial in Cybersecurity Education?

Cybersecurity is a double-edged sword: techniques taught to defend networks can also be used to attack them. Therefore, any training in this field must rest on:

A clear code of ethics

Up-to-date legal regulations

Sound educational best practices

Tight control over practical environments

The goal is not just to teach tools like iptables, pfSense, Wireshark, or nmap, but to mold professionals who are responsible, principled, and aware of the impact of their skills.

2. Legal Framework: What You Can—and Cannot—Do

Common legislation in Spanish-speaking countries (overview):

Country | Relevant Law | Prohibits
Spain | Organic Law 10/1995 & LSSI-CE | Unauthorized access, DoS, malware distribution
Mexico | Federal Penal Code (Art. 211 bis) | Interception of communications, illicit system access
Colombia | Law 1273 of 2009 | Damage to computer systems
Argentina | Law 26.388 | Illegitimate access, cyber sabotage
Peru | Law No. 30096 | Cybercrime and illegal interception

Note: Even in simulated labs, teaching offensive techniques without the proper context may be seen as glorifying crime or incitement.

3. Ethical Principles in Teaching Perimeter Security

Informed Consent
Never scan, attack, redirect, or audit any system without explicit permission.

Educational and Defensive Purpose
Exercises must be framed as defensive, vulnerability assessments of one’s own assets, or controlled simulations.

Isolated, Closed Environments
All hands-on must occur in disconnected or simulated labs (GNS3, VirtualBox, EVE-NG, pfSense with NAT/internal networks).

Instructor Responsibility
The teacher must ensure students understand the line between permitted and illicit actions.

Promote the “Ethical Hacker”
Teach the original hacker ethos: problem-solver and defender, not digital criminal.

4. Practical Cases and Ethical Approaches

Case 1: Network Scanning with nmap

Proper: Scan a virtual lab network of VMs owned by the student.

Improper: Scan the school’s Wi-Fi or any production network without permission.

Case 2: Simulated DoS Attack

Proper: Flood a personal VM with hping3 under strict limits.

Improper: Attack any production or public server.

Case 3: Sniffing with Wireshark

Proper: Capture traffic on an isolated virtual link between two VMs.

Improper: Sniff real network traffic of classmates or the institution.

5. Designing Secure Educational Environments

Use NAT-only or host-only networks in VirtualBox/VMware.

If using physical switches, segment labs on dedicated VLANs.

Restrict lab access via virtual firewalls or ACLs.

Display a “legal banner” on lab VMs stating educational use only.

Automate VM resets between exercises (snapshots, rollbacks).

6. Sample Ethics & Legality Statement for Students

“This lab environment is provided solely for educational purposes. Any attempt to apply the techniques demonstrated here outside of an authorized, controlled setting constitutes an ethical breach and may result in administrative, academic, and/or legal consequences. By participating, you commit to using your knowledge to protect and defend systems, not to harm them.”

Include this at the start of each lab, in the LMS, or in the grading rubric.

7. Responding to Misuse of Training

If you suspect a student is applying skills offensively in the wild:

Collect evidence (screenshots, logs, witness statements).

Notify the academic coordinator or legal office.

Do not confront the student alone—always involve institutional support.

If feasible, organize a restorative group discussion on ethical practice.

8. Resources to Foster Professional Ethics

Codes of Conduct:

EC-Council Code of Ethics

SANS Institute Code of Ethics

The Hacker’s Manifesto (for classroom debate)

Real-World Case Studies:

Kevin Mitnick, Anonymous, Stuxnet, LAPSUS$

National CERT reports

Open Ethical Training:

OWASP’s Ethical Hacking Course

Electronic Frontier Foundation resources

9. Assessing Ethical Competence

Criterion | Evaluation
Understands the difference between defensive vs. offensive tactics |
Identifies legal vs. illegal scenarios in common exercises |
Acts responsibly with sensitive information |
Respects network and equipment usage policies |

Use quizzes, role-plays, case studies, or ethical pledges to assess.

Teaching perimeter security is more than configuring firewalls or writing packet-filter rules; it’s about nurturing responsible professionals. A learning environment grounded in critical thinking, legal awareness, and digital empathy is more powerful than any technology. As educators, we are custodians of knowledge—teaching it ethically is the best way to protect it.

Chapter 55: Bibliography and Academic Resources

Chapter Objective

This chapter provides a solid foundation of academic, technical, and pedagogical references to support curriculum design, study guides, research materials, and documentation for classroom projects, vocational training, and teaching in perimeter security.

1. Types of Resources Included

In this chapter you will find:

Technical reference books

Official documentation for key tools (iptables, nftables, pfSense, etc.)

Indexed academic articles

Open Educational Resources (OERs)

MOOCs, free courses, and certification programs

Cybersecurity standards and regulations

Virtual lab and simulator platforms

Relevant GitHub repositories

High-quality audiovisual materials and tutorials

2. Recommended Technical Books

Network Security and Firewalls

Linux Firewalls by Steve Suehring & Michael Rash
A technical reference on Netfilter, iptables, and real-world deployment.

The Book of PF by Peter N. M. Hansteen
Deep dive into OpenBSD’s PF firewall, with many concepts directly applicable to pfSense.

Network Security Assessment by Chris McNab
Practical manual for auditing networks and systems legally.

Mastering pfSense by David Zientara
Comprehensive guide to administering and securing pfSense.

3. Essential Official Documentation

Tool | Official Documentation URL
iptables | https://netfilter.org/documentation/index.html
nftables | https://wiki.nftables.org
pfSense | https://docs.netgate.com/pfsense/en/latest/
Wireshark | https://www.wireshark.org/docs/
OpenVPN | https://openvpn.net/community-resources/
Snort | https://docs.snort.org
Suricata | https://suricata.readthedocs.io

Practical tip: Download and archive PDF versions for offline use in disconnected labs.

4. Academic Articles and Papers

Where to find relevant papers:

IEEE Xplore: Search for “perimeter security,” “firewall performance,” “stateful packet inspection.”

ScienceDirect: Filter under “Computer Networks” and “Cybersecurity.”

Google Scholar: Great for theses, technical publications, and university papers.

ACM Digital Library: Valuable for software-defined networking (SDN) and distributed firewall research.

Example: “Comparative Performance Analysis of iptables vs. nftables under Mixed Traffic,” Polytechnic University of Valencia.

5. Open Educational Resources (OER)

Cybrary (https://www.cybrary.it)
Free and paid courses on cybersecurity, blue teaming, firewalls, and more.

OpenSecurityTraining (https://opensecuritytraining.info)
In-depth technical courses from basics to forensic analysis and advanced exploitation.

edX / Coursera / FutureLearn
Courses from MIT, Stanford, Universidad Carlos III, etc., on networking, security, and cryptography.

6. MOOCs and Official Training

Cisco Networking Academy
CCNA Security, CCNP Security, CyberOps Associate—strong foundation in network policies.

Fortinet NSE Institute
Free NSE 1–4 courses covering enterprise firewalls, segmentation, and perimeter defense.

Red Hat Linux Security & Firewall Management
Focused on iptables/nftables in enterprise environments.

Hack The Box Academy
Offensive and defensive security labs with realistic simulators.

7. Regulations, Standards, and Legal Frameworks

To establish a solid regulatory and procedural base for teaching and practicing perimeter security:

Standard / Regulation | Application
NIST SP 800-41 | Guide to Secure Firewall Configuration
ISO/IEC 27033-6 | Network Security: Firewalls and Gateways
GDPR / RGPD | Personal Data Protection (EU)
National Cybercrime Laws | Criminal statutes in each country

Practical tip: Integrate analysis of one of these standards into a technical class to show real-world impact.

8. GitHub Repositories and Projects

Repository | Description
nftables-examples | Practical rules, templates, and scripts for nftables
awesome-firewall | Curated tools, resources, and articles on firewalls
pfsense-backup | Automation and backup scripts for pfSense
iptables-utilities | Helper scripts, prebuilt rules, monitoring tools for iptables
netfilter-lab | Virtual lab environments for iptables/nftables

Many of these are open-licensed for adaptation in teaching.

9. Practical Platforms and Simulators

GNS3
Powerful network simulator that integrates VMs running pfSense and Linux firewalls.

EVE-NG
Full-featured, web-based lab platform for complex topologies.

NetLab+
Cisco-affiliated academic platform with user management, auto-grading, and rubrics.

TryHackMe / Hack The Box
Interactive offensive and defensive labs, including firewall hardening scenarios.

10. Quality Technical Channels and Tutorials

The Network Chuck (YouTube)
Visual tutorials on VPNs, VLANs, and firewalls.

Chris Greer
Packet analysis and Wireshark deep dives.

S4vitar
Spanish-language ethical hacking and defensive security courses.

Netgate Training
Official pfSense video tutorials.

11. Integrating These Resources into Your Classroom

Tailor learning paths by level (beginner, intermediate, advanced).

Design activities around each resource (e.g., “Summarize RFC 2979 on Stateful Firewalls”).

Use rubrics that reward correct citation of sources and licensing.

Blend technical content with ethical and legal considerations.

Require final projects to include formal bibliographies.

Perimeter security demands multidisciplinary, ongoing education. This curated collection of resources supports high-quality teaching with a strong practical focus and critical perspective. By adapting these materials, instructors can keep content current and elevate academic rigor.

Chapter 56: Essential Command Reference by Technology

Chapter Objective

To provide a quick, operational reference of the most relevant commands for each key perimeter-security technology. These commands are useful for:

Network diagnostics

Applying firewall rules

Traffic monitoring

VPN configuration

Automation and scripting

Managing sessions, NAT, filtering, logging, and more

1. iptables – Essential Commands

The classic Linux firewall tool based on Netfilter.

bash

# List active rules

iptables -L -v -n

# Allow SSH

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

# Drop all incoming traffic

iptables -P INPUT DROP

# Delete a specific rule

iptables -D INPUT -p tcp—dport 22 -j ACCEPT

# Save current rules (Debian/Ubuntu)

iptables-save > /etc/iptables/rules.v4

# Restore rules

iptables-restore < /etc/iptables/rules.v4

# Show rules with line numbers (for deletion)

iptables -L—line-numbers

Tip: Always test new rules using a parallel SSH session to avoid locking yourself out.

2. nftables – Fundamental Commands

The modern iptables successor: modular, structured syntax, script-friendly.

bash

# Create a filter table

nft add table inet firewall

# Add an input chain

nft add chain inet firewall input { type filter hook input priority 0 \; }

# Allow SSH

nft add rule inet firewall input tcp dport 22 accept

# Drop all other input

nft add rule inet firewall input drop

# Show full ruleset

nft list ruleset

# Save to file

nft list ruleset > /etc/nftables.conf

# Load from file

nft -f /etc/nftables.conf

Trick: Use nft -n list ruleset to display numeric ports/interfaces (faster for debugging).

3. pfSense (CLI & GUI) – Key Actions

CLI (console mode)

bash

# Open console menu

pfSense console menu

# Reinitialize interface links

/etc/rc.linkup

# Reload firewall rules

/etc/rc.filter_configure

# Restart web GUI

/etc/rc.restart_webgui

# Restart OpenVPN

/etc/rc.d/openvpn restart

GUI Common Tasks

Firewall → Rules: Create interface-specific rules (WAN, LAN).

Firewall → NAT → Port Forward: Set up port forwarding.

Status → System Logs → Firewall: View blocked attempts.

Diagnostics → Packet Capture: Capture live traffic.

Diagnostics → Command Prompt: Run shell commands in the web UI.

4. OpenVPN – Essential Commands

On the server:

bash

# Start OpenVPN service

systemctl start openvpn@server

# Check status

systemctl status openvpn@server

# View log

cat /var/log/openvpn.log

# Easy-RSA example

./easyrsa init-pki

./easyrsa build-ca

./easyrsa gen-req client1 nopass

./easyrsa sign-req client client1

On the client:

bash

# Connect using a config file

openvpn—config client.ovpn

Tip: Use scripts to batch-generate client certificates and export .ovpn profiles.

5. tcpdump – Traffic Capture & Analysis

bash

# Capture on eth0

tcpdump -i eth0

# Filter by port 80

tcpdump -i eth0 port 80

# Host-specific capture

tcpdump host 192.168.1.100

# Write capture to file

tcpdump -i eth0 -w capture.pcap

# Read a capture file

tcpdump -r capture.pcap

# Less verbose headers only

tcpdump -nn -v

Combine with iptables to verify rule effectiveness.

6. General Networking Commands

bash

# Show interfaces

ip a

# Show routing table

ip r

# List listening ports

netstat -tuln | grep LISTEN

# Show active connections

ss -ant

# Ping test

ping 8.8.8.8

# DNS lookup

dig openai.com

# Ping-scan network

nmap -sP 192.168.1.0/24

7. Combined Commands in Scripts

Automate common setups. Example basic-firewall.sh:

bash

#!/bin/bash

echo "Configuring basic firewall"

iptables -F

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

iptables-save > /etc/iptables/rules.v4

Summary

This catalog of essential commands—along with practical tips—enables efficient operation and teaching of perimeter-security tools. Key takeaways:

Practice in controlled virtual labs

Document every change

Combine CLI tools with GUI analysis

Promote scripting for standardization

Chapter 57: Quick Guides for Students

Chapter Objective

Provide students with concise, structured, and action-oriented guides that will help them:

Review essential fundamentals.

Apply basic configurations without errors.

Quickly resolve common problems.

Develop technical and operational autonomy.

These guides can be printed, integrated into learning management systems (LMS), or distributed in practical labs.

Structure of the Quick Guides

Each guide is designed following this pattern:

Section | Content
Objective | What will be learned or resolved
Pre-requisites | Required tools, packages, or environments
Detailed Steps | Step-by-step commands or configurations
Validation | How to know if you've done it correctly
Common Errors | Frequent mistakes and how to fix them
Expert Tip | Best practices and advanced suggestions

Guide 1: Basic iptables Setup to Protect a Server

Objective

Set up a firewall to allow SSH traffic and reject everything else.

Pre-requisites

Ubuntu/Debian or CentOS with iptables installed.

Root or sudo access.

Steps

bash

# Clear previous rules

iptables -F

# Default policy: deny

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

# Allow established or related connections

iptables -A INPUT -m conntrack—ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH traffic (port 22)

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

Validation

From another machine, check if you can connect via SSH. Try to ping: it should fail (ICMP not allowed).

Common Errors

Not adding a rule for established connections.

Locking yourself out of SSH if connected remotely.

Expert Tip

Use a script to apply rules on restart and test them from a local console before closing the remote session.

Guide 2: Set up NAT and Port Forwarding with pfSense

Objective

Redirect external port 80 to internal port 8080 on a server.

Pre-requisites

pfSense configured and accessible via GUI.

A web server on the LAN (e.g., 192.168.1.100:8080).

Steps

Go to Firewall → NAT → Port Forward.

Click Add (+).

Configure:

Interface: WAN

Protocol: TCP

Destination port range: 80

Redirect target IP: 192.168.1.100

Redirect target port: 8080

Check "NAT Reflection" if accessing from LAN.

Apply the changes.

Validation

From the internet or an external network, access the public IP of the firewall on port 80.

Common Errors

Not having a firewall rule to allow the connection.

Redirecting to the wrong port.

Expert Tip

pfSense automatically creates the associated firewall rule if you check the corresponding box.

Guide 3: Create Access Rules in nftables

Objective

Allow HTTP access and block everything else.

Pre-requisites

nftables installed and active.

Administrative privileges.

Steps

bash

nft flush ruleset

nft add table inet myfilter

nft add chain inet myfilter input { type filter hook input priority 0 \; policy drop \; }

nft add rule inet myfilter input ct state established,related accept

nft add rule inet myfilter input tcp dport 80 accept

Validation

Check with nft list ruleset and access your server via a browser.

Common Errors

Forgetting to set the default policy to drop (policy drop).

Not loading the file into /etc/nftables.conf.

Expert Tip

Define your rules in a .nft file and execute it with nft -f filename.nft to maintain version control.

Guide 4: Quick Network Diagnosis

Objective

Verify connectivity, DNS, and open services.

Steps

bash

ip a  # Show IP interfaces

ip r  # Routing table

ping 8.8.8.8  # External connectivity

dig google.com  # DNS check

ss -tuln  # Listening services

Validation

All commands should return results without errors.

Expert Tip

Integrate these tests into quick audit scripts.

Guide 5: Capture and Analyze Traffic with tcpdump

Objective

Capture network traffic to analyze suspicious behavior.

Steps

bash

# Capture general traffic

tcpdump -i eth0 -nn

# Filter by port

tcpdump -i eth0 port 22

# Save to a file

tcpdump -i eth0 -w ssh_traffic.pcap

# Read the file

tcpdump -r ssh_traffic.pcap

Expert Tip

Open .pcap files with Wireshark for graphical analysis.

Other Suggested Topics for Quick Guides

Topic | Objective
Firewall script with iptables | Create a reusable script
Point-to-point VPN with OpenVPN | Connect two remote networks
Configure VLANs in pfSense | Isolate traffic and segment networks
Apply QoS rules | Prioritize VOIP or video calls
Monitor logs in pfSense | Analyze access attempts and scans

These quick guides condense the essential knowledge needed for students to confidently operate in firewalling environments. Their use in virtual labs, individual exercises, and guided evaluations helps to:

Reduce the learning curve.

Minimize critical errors in real-world testing.

Encourage the systematization of technical procedures.

Chapter 58: Software and Virtual Environments Recommendations

Chapter Objective

Offer a technical and pedagogical guide on recommended tools for implementing perimeter security labs, facilitating firewall practices (iptables, nftables, pfSense, etc.), and simulating realistic network environments. This chapter is key for both teachers and students, as it enables safe, flexible, and risk-free work on physical infrastructure.

1. Essential Software for Firewalls and Perimeter Security

Below are indispensable tools according to their focus and practical use:

iptables / nftables

Function: Configuring firewalls on Linux.

Base System: Any Linux distribution (Debian, Ubuntu, CentOS, etc.).

Suggested Environment: CLI or scripts on Linux VMs.

Pedagogical Use: Detailed teaching of rules, chains, tables, and flows.

pfSense

Function: Complete firewall and router based on FreeBSD.

Advantages: Web GUI, advanced rules, NAT, VLANs, VPNs, high availability.

Suggested Environment: VirtualBox, Proxmox, VMware, or bare-metal.

Ideal For: Business simulations, segmented labs, and GUI-based practices.

OPNsense

Function: A modern alternative to pfSense.

Advantages: More intuitive interface, more frequent updates.

Suggested For: Teachers seeking a pfSense-like experience but more open.

Wireshark

Function: Network traffic analysis.

Relevance: Essential for observing packets, detecting anomalies, and teaching protocols.

Ideal Complement For: tcpdump, pfSense logs, NAT traffic, and debugging.

tcpdump

Function: Traffic capture from CLI.

Pedagogical Advantage: Reinforces understanding of packet flow.

2. Recommended Virtualization Environments

Virtual environments are crucial for deploying firewall labs, network security, and simulating attacks/defenses. Recommended options include:

VirtualBox (Oracle)

Advantages:

Free and cross-platform.

Ideal for classroom environments and local practices.

Supports internal networks (host-only, bridged).

Recommended Uses:

Simulate a LAN with multiple VMs (pfSense + Linux).

Test NAT, port forwarding, and firewall rules.

Proxmox VE

Advantages:

Professional virtualization platform based on Debian.

Supports containers (LXC) and VMs (KVM).

Powerful web interface.

Ideal For:

Educational centers with dedicated physical servers.

More complex simulations with real VLANs.

VMware Workstation / ESXi

Advantages:

Professional, powerful, widely used in companies.

Suggested For:

Advanced professional training.

Certifications or real-world deployments.

GNS3

Function: Simulation of complex networks.

Advantages:

Integrates real or simulated devices.

Allows connection to external VMs (such as pfSense or Kali Linux).

Ideal For:

Network practices, perimeter security, IDS/IPS, and segmentation.

EVE-NG

Function: Collaborative network simulator.

Advantages:

Free and professional versions.

User-friendly web interface.

Integration with images of firewalls, routers, Linux, and more.

Ideal For:

Multi-user labs, remote classes, or complete network practices.

3. Useful System and Distribution Images

Linux (for iptables/nftables practices):

Debian / Ubuntu Server: Lightweight, fully supports iptables/nftables.

Alpine Linux: Very lightweight, ideal for minimalist firewalls.

CentOS / Rocky Linux: Enterprise scenarios.

Security Distributions:

Kali Linux: Pentesting and offensive analysis.

Parrot Security OS: Lightweight alternative for auditing practices.

Security Onion: Network monitoring, IDS, log analysis.

Windows:

Windows Server: To configure Windows firewall rules.

Windows 10/11: Connection tests, client policies.

4. Recommended Virtual Lab Example

Scenario: Firewall practice with pfSense + servers

Machine | OS / Role | Internal IP
VM1 | pfSense | WAN: DHCP / LAN: 192.168.1.1
VM2 | Ubuntu Server (web) | 192.168.1.100
VM3 | Kali Linux (attacks) | 192.168.1.150

Possible Activities:

Create rules to allow only HTTP from specific IPs.

Block scans from Kali.

Redirect incoming traffic to an internal port.

Capture traffic and analyze with Wireshark.

5. Tips for Teachers

Create lab templates with snapshots.

Prepare startup and restore scripts to reset the initial state.

Integrate simulators (EVE-NG/GNS3) with educational platforms (Moodle, Canvas).

Share preconfigured images to speed up learning.

6. Cloud Platforms (Optional)

For remote classes or off-campus practices:

AWS / GCP / Azure: Create isolated environments with VPCs, firewalls, and virtual routers.

TryHackMe / Hack The Box: Reinforce concepts from an offensive perspective.

Netlab+ / CyberRange: Managed educational platforms.

Having a solid software ecosystem and efficient virtual environments is the foundation for quality teaching in Perimeter Security. With these tools, students can make mistakes without real risks, observe the impact of each rule, and deeply understand how network traffic flows and is controlled.

Chapter 59: Practice and Exam Templates

Chapter Objectives

Provide reusable models of practices and exams that cover all key aspects of perimeter security.

Allow educators to evaluate both technical competence and logical reasoning in defensive cybersecurity.

Provide self-assessable or automatable examples in virtual environments (VMs, GNS3, pfSense, etc.).

1. Recommended Structure for a Practice or Exam

Each practice/exam should contain:

Element | Description
Title | Short, clear, and related to the technical content.
Task Objective | What the student must learn or demonstrate.
Topology or Scenario | Brief description of the virtual machines, IPs, and roles involved.
Instructions | Detailed steps to follow for configuration or analysis.
Validation Questions | Questions that demonstrate understanding and correct application of concepts.
Evaluation Criteria | Rubric or scoring table for each section.

2. Basic Practice Template: iptables

Title: Basic iptables Rule Configuration for a Linux Machine

Objective: Apply firewall rules to allow only incoming SSH and web traffic.

Scenario:

VM: Debian or Ubuntu

IP: 192.168.100.10

Interface: eth0

Tasks:

Set the default policy to DROP for INPUT, FORWARD, and OUTPUT.

Allow outgoing traffic in all directions.

Allow incoming SSH connections (port 22) and HTTP (port 80).

Block any other connection attempts.

Save the rules to persist after reboot.

Validation:

From another machine, use telnet 192.168.100.10 80 and telnet 22.

Check logs for blocked attempts if you add LOG.

Evaluation Questions:

Why is it necessary to allow related traffic (RELATED,ESTABLISHED)?

What is the difference between ACCEPT and REJECT?

What would be the risk of leaving the INPUT policy as ACCEPT?

Criteria:

Item | Points
Correct rule application | 5
Functional check with netcat/telnet | 2
Persistent configuration | 2
Theoretical justification | 1

3. Intermediate Practice Template: pfSense

Title: Segmentation Rules Between LAN and DMZ with pfSense

Objective: Configure a DMZ in pfSense with controlled access rules.

Scenario:

pfSense with three interfaces:

WAN (DHCP)

LAN: 192.168.1.1/24

DMZ: 192.168.2.1/24

A web server in the DMZ: 192.168.2.100

A client in the LAN: 192.168.1.50

Tasks:

Create a rule to allow only HTTP from LAN to DMZ.

Block any access from DMZ to LAN.

Enable access from the Internet to the web server using port forwarding (NAT 80 -> 192.168.2.100:80).

Document the rules and justifications.

Validation:

LAN can open a browser to 192.168.2.100:80.

DMZ cannot ping 192.168.1.1.

Internet can access the firewall's public IP on port 80.

Evaluation Questions:

What is a DMZ and why is it isolated?

How does this configuration affect a potential attacker?

What implications would allowing traffic from DMZ to LAN have?

Criteria:

Item | Points
Effective segmentation | 4
NAT functioning correctly | 3
Return traffic blocked | 2
Architectural reasoning | 1

4. Final Practical Exam Template

Title: Design and Defense of a Corporate Network

Objective: Implement a complete perimeter security scheme using combined tools.

Topology:

1 pfSense (border)

1 server in DMZ (web or FTP)

1 LAN client

1 simulated attacker (Kali Linux on an external network)

Requirements:

Strict firewall policies in LAN and DMZ.

Port forwarding from WAN to the server.

Enable logs and analysis in pfSense.

Use Wireshark/tcpdump to check rules.

Written justification of the design.

Comprehensive Evaluation:

Section | Points
Functional configuration | 6
Security applied | 5
Captures and tests | 3
Technical justification | 3
General documentation | 3

5. Suggested Template Repository

You can organize practices and exams into folders classified by level:

bash

/plantillas/

├── basico/

│  ├── iptables_ssh_web.md

│  └── reglas_salida_bloqueo.md

├── intermedio/

│  ├── pfSense_DMZ_HTTP.md

│  └── nftables_basico.md

├── avanzado/

│  ├── proyecto_seguridad_perimetral.md

│  ├── IDS_pfSense_logging.md

│  └── simulacion_ataques_snort.md

All practices can be accompanied by:

Exportable .conf files (pfSense backup).

Screenshots of configurations.

Ready-to-apply iptables or nftables scripts.

YAML or XML files for GNS3/EVE-NG.

6. Tips for Applying Evaluations

Use rubrics with weighted scores for each block (technical, operational, theoretical).

Integrate common error simulations (e.g., opening an unnecessary port).

Evaluate both execution and diagnostic (debugging) skills.

Encourage the use of documentation and technical logs.

Practice and exam templates are essential pedagogical tools for helping students internalize the logic of perimeter defense and develop operational skills with firewalls. A hands-on, critical analysis approach validated with real tools significantly strengthens the learning process.

Chapter 60: Access to the Course GitHub Repository

Chapter Objectives

Teach how to create, maintain, and leverage an educational GitHub repository for Perimeter Security.

Explain how to organize practices, scripts, rubrics, and lab configurations.

Promote a modern, collaborative, and reproducible methodology in technical courses.

1. Why Use GitHub in Perimeter Security Courses?

GitHub is not just for storing code. It is a collaboration platform that offers:

Versioning of configurations (iptables, nftables, pfSense backups, scripts).

Change tracking and traceability of practices.

Quick publication of resources with Markdown documentation.

A collaborative environment with issues and pull requests for feedback between teachers and students.

Possibility for integration with CI/CD and automation (e.g., script validation).

2. Recommended Repository Structure

bash

seguridad-perimetral/

├── README.md

├── .gitignore

├── docs/  # General documentation and syllabus

│  ├── guia_docente.md

│  └── estructura_curso.md

├── iptables/  # iptables practices and scripts

│  ├── basico/

│  │  └── reglas_ssh_http.sh

│  └── avanzado/

│  └── nat_port_forwarding.sh

├── nftables/  # nftables exercises

│  └── reglas_basicas.nft

├── pfsense/  # Configurations and XML backups

│  ├── respaldo_basico.xml

│  └── dmz_nat_export.xml

├── simuladores/

│  └── topologia_gns3.zip

├── examenes/

│  ├── parcial1.md

│  └── final.md

├── rubricas/

│  └── evaluacion_practica.yml

└── recursos/

└── hoja_comandos_rapidos.md

Practical Tip: Use README.md in each subfolder to explain how to use the files. This helps self-taught students understand better.

3. Creating and Configuring the Repository

Step 1: Create the repository

From GitHub:

Suggested name: seguridad-perimetral-curso

Add README

Add .gitignore for Linux or scripts

Suggested license: MIT (if you want it to be freely reusable)

From the terminal (CLI mode):

bash

git init seguridad-perimetral-curso

cd seguridad-perimetral-curso

echo "# Curso Seguridad Perimetral" > README.md

git add .

git commit -m "First commit"

git remote add origin https://github.com/TUUSUARIO/seguridad-perimetral-curso.git

git push -u origin main

4. How to Upload and Maintain Firewall Scripts

Example: Uploading a basic iptables script

Create the file in iptables/basico/reglas_web_ssh.sh:

bash

#!/bin/bash

iptables -F

iptables -P INPUT DROP

iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT

iptables -A INPUT -m state—state ESTABLISHED,RELATED -j ACCEPT

iptables -A INPUT -p tcp—dport 22 -j ACCEPT

iptables -A INPUT -p tcp—dport 80 -j ACCEPT

Upload with git:

bash

git add iptables/basico/reglas_web_ssh.sh

git commit -m "Add basic iptables script for HTTP/SSH"

git push

5. Instructions for Students to Clone and Work with the Repository

Give your students this quick guide:

bash

# Clone the course repository

git clone https://github.com/TUUSUARIO/seguridad-perimetral-curso.git

# Enter the folder

cd seguridad-perimetral-curso

# List contents

ls -la

# Go to a practice and run it (example)

cd iptables/basico

sudo bash reglas_web_ssh.sh

You can add a document in /docs/uso_alumno.md explaining this step-by-step.

6. Best Practices for Teachers and Collaborators

Descriptive commits: Use clear messages like "Add nftables partial exam" or "Fix DMZ rule in pfSense".

Tags: Use tags like v1.0, examen1, pfSense-DMZ to version releases.

Issues: Allow students to report bugs or doubts directly in the repository.

Pull Requests: Advanced students can propose fixes or improvements.

GitHub Pages (optional): You can enable GitHub Pages to automatically generate a course website.

7. Practical Use Cases

Case 1: Automating Tests

With GitHub Actions, you can validate if .sh scripts are syntactically correct:

yaml

name: Validate iptables scripts

on: [push]

jobs:

check-scripts:

runs-on: ubuntu-latest

steps:

- uses: actions/checkout@v2

- name: Validate script syntax

run: |

find . -name "*.sh" -exec bash -n {} \;

Case 2: Managing Submissions

Each student can fork the repository.

They work on their personal copy and submit a pull request with their completed practice.

Pull request comments can be used for direct feedback.

8. How to Integrate GitHub with Educational Platforms

You can embed links to the repository from:

Moodle: with links or GitHub plugin.

Google Classroom / Teams: use direct links to folders or files.

JupyterHub or VSCode Online: open the repo in a coding environment directly.

Using GitHub in perimeter security courses not only modernizes access to materials but also prepares students for real-world teamwork practices and DevSecOps. It also allows for complete traceability in technical learning, promotes self-learning, and fosters collaborative teaching.

Chapter 61: Related Certifications (CompTIA, CEH, Cisco, etc.)

Chapter Objectives

Identify the most relevant certifications for technical and teaching profiles in Perimeter Security.

Connect course content with the skills assessed in official exams.

Provide progressive learning paths and practical recommendations for students.

Establish links between knowledge of iptables, nftables, pfSense, networks, and offensive/defensive security.

1. Why Are Certifications Important?

Certifications:

Validate technical competencies to employers or educational entities.

Serve as a motivator for structured self-learning.

Allow standardization of evaluation criteria.

Strengthen students' employability in a highly competitive and globalized environment.

2. Key Certifications by Professional Profile

A. Entry-Level / Introductory

Certification | Organization | Focus | Relation to this course
CompTIA Security+ | CompTIA | General security | Covers concepts of firewalls, networks, threats
Cisco CyberOps Associate | Cisco | Basic SOC operations | Requires understanding network flows, detection, and response
Fortinet NSE 1-3 | Fortinet | Basic knowledge and configuration | Commercial firewalls, similar to pfSense in approach

Recommended for students in intermediate or vocational education starting in networks and systems.

B. Intermediate / Technical

Certification | Organization | Focus | Relation to this course
Cisco CCNA Security (legacy) / CCST Cybersecurity | Cisco | Firewalls, ACLs, NAT, VPNs | Matches VLAN, NAT, rule practices
CompTIA Linux+ | CompTIA | Linux administration | Strengthens iptables and nftables knowledge
LPIC-2 (Network security) | LPI | Linux networks and servers | Full integration with course practices
pfSense Certified Professional (PCP) | Netgate | Official pfSense certification | 100% aligned with pfSense chapters in the course

Ideal for profiles working or studying in higher cycles, degrees, or professional courses.

C. Advanced / Specialization

Certification | Organization | Focus | Relation to this course
CEH (Certified Ethical Hacker) | EC-Council | Ethical hacking, offensive techniques | Reinforces the defensive view learned with iptables
CompTIA PenTest+ | CompTIA | Penetration testing and red teaming | Evaluating defenses like firewalls in labs
OSCP (Offensive Security) | OffSec | Practical offensive security | Custom firewalls are the basis for realistic environments
CISSP | ISC² | Security management and architecture | Related to security policies and network design

Focused on professionals or educators with experience in IT security or integrative projects.

3. Course Content Linked with Certifications

Course Module | Related Certifications
iptables, nftables, policies | Security+, CCNA, Linux+, LPIC-2
pfSense, rules, VLANs, VPN | PCP, CyberOps, Fortinet NSE 4
Attack simulation and blocking | CEH, PenTest+, OSCP
NAT, segmentation, DMZ | CCNA, CCNP, CISSP (secure network design)
Virtual labs | GNS3/NetLab used in PenTest+ and CEH
Logging and monitoring with firewalls | CompTIA CySA+, SOC Analyst

4. Teaching Strategy to Integrate Certifications

Introduce modules aligned with official exam objectives (e.g., "Port blocking and remote access" as it matches CCNA).

Use terminology and structure similar to the domains of each certification (e.g., "Access Control", "Network Hardening").

Provide mini-quizzes by domain (ideal for Security+ or CEH).

Implement practical evaluation rubrics simulating exam scenarios.

5. Resources for Preparation

Official Sites

CompTIA CertMaster

Offensive Security Trainings

Cisco Networking Academy

Fortinet NSE Training

Netgate pfSense University

GitHub Repositories and Educational Platforms

Public GitHub repositories with firewall labs (iptables, nftables, pfSense)

TryHackMe and HackTheBox (for CEH and OSCP training)

INE Security and Udemy (affordable PenTest+ and Cisco courses)

6. Suggested Practice: Exam Simulation

Design an integrative project or final lab where:

A complete firewall (pfSense or nftables) is configured.

Segmentation, NAT, and traffic control are applied.

Attacks (DoS, scanning) are simulated and logging is configured.

Everything is documented in a format similar to what is required in CEH Practical or PenTest+.

7. Tips for Students

Start with vendor-neutral certifications (CompTIA, LPI).

Don’t just study theory: practice everything in virtual labs.

Use simulators like GNS3 and NetLab to practice secure networks.

Create a personal GitHub with scripts, configurations, and documentation.

Form study groups to simulate real-world scenarios.

Integrating relevant certifications into the Perimeter Security course framework enhances students' employability, motivation, and technical rigor. Additionally, it prepares both educators and professionals to stay aligned with international industry standards.

‍ Chapter 62: Tips for Teaching Perimeter Security Remotely

Chapter Objectives

Share strategies for delivering complex technical content clearly in a virtual setting.

Present effective tools, resources, and methodologies for remote teaching in Perimeter Security.

Encourage active student participation through virtualized and collaborative practices.

Address common challenges when teaching iptables, pfSense, VLANs, NAT, and VPNs remotely.

1. Common Challenges in Online Perimeter Security Classes

Teaching network and security topics remotely presents obstacles such as:

Challenge | Practical Example
Difficulty practicing | Students can't set up physical networks at home.
Demotivation and isolation | Low participation if the class is theoretical.
Technical issues | Firewalls blocking required ports for VPN or NAT.
Unequal infrastructure | Some students lack a powerful PC or stable internet.

Solution: Adapt pedagogy and rely on virtualized environments, simulators, and active learning.

2. Recommended Tools for Teaching Perimeter Security Online

A. Simulation and Practice

Tool | Recommended Use
GNS3 / EVE-NG | Simulate routers, firewalls, networks with multiple VMs.
VirtualBox + pfSense | Complete firewall in a single local machine.
NetLab+ (for institutions) | Cloud-based lab for controlled practices.
TryHackMe / HackTheBox | Pentesting and incident response exercises.

B. Videoconference and Support

Jitsi / Zoom / Google Meet: For synchronous classes and problem-solving.

AnyDesk / RustDesk: For remote student support.

OBS Studio: To record step-by-step technical tutorials.

C. Assessment and Collaboration

Moodle / Google Classroom: Activity management, forums, exams.

GitHub Classroom: Submit and grade firewall scripts.

Padlet / Miro: Collaborative mind maps on packet flow, rules, policies.

3. Suggested Structure for an Effective Online Class

Based on the Flipped Classroom methodology + remote practices.

Before the class (Self-learning)

Provide a short video or PDF explaining basic theory (e.g., how iptables or NAT works).

Link to official documentation + introductory quiz.

Provide a VM ready for practice.

During the class (Practical resolution)

Start with a quick review of concepts (5-10 minutes).

Develop a live-guided practice, e.g.:

Create a default DROP policy in iptables.

Enable traffic from LAN to the internet only in pfSense.

Use breakout rooms for teamwork (if the platform allows).

After the class

Individual or pair-based practical challenge.

Clear evaluation rubric (e.g., "Did they correctly block ports 22 and 3389?").

Forum for questions + collaborative resolution between students.

4. Practical Tips to Energize Remote Classes

Technique | Description
Split-screen | Explain while running real commands (with OBS, two windows, or multiple monitors).
Simulated errors | Create intentional common errors and have students diagnose them.
Quick rounds | Ask rapid-fire questions to maintain attention.
Gamification | Award points, badges, or CTF-style challenges.
Support scripts | Provide base scripts to facilitate initial practice.
GitHub repositories | Create a repository for each topic or unit (e.g., basic blocking rules, NAT, VLAN).

5. Basic Kit for Teaching Perimeter Security Remotely

Element | Content
Virtual machine templates | pfSense, Kali Linux, Ubuntu Server with iptables and nftables preconfigured.
Quick-reference PDFs | Command syntax, rule structures, examples.
Downloadable rubrics | For evaluating practices: "Did they configure correctly?", "Do they document?", "Do they explain their logic?"
Error and troubleshooting guides | To help resolve typical NAT, VPN, port issues.
Pre-configured scripts | Basic iptables and nftables + examples of nft with comments.

6. Best Practices for Online Teachers

Be visible and available: Respond to forums, send feedback, participate in class.

Don’t assume knowledge: In security, many students come from very different backgrounds.

Alternate technical lessons with real-world scenarios (e.g., "A network attack on a school" or "A VPN for remote work").

Encourage self-explanation: Have students describe what each firewall rule does.

Promote technical documentation: Teach how to comment code and generate configuration reports.

7. Remote Evaluation and Monitoring

Types of Evaluation

Formative: Small practices, self-assessments, quizzes.

Summative: Full firewall projects, labs, attack simulations.

Participation: Forums, questions resolved, peer help.

Example of a Rubric

Criterion | Points
Correct application of NAT rules | 20
Clear explanation of packet flow | 20
Security of default policy | 20
Documentation of changes | 20
Participation in forum or class | 20

Teaching Perimeter Security remotely is not only viable but enriching when structured correctly. With a practical approach, the right tools, and motivating dynamics, effective learning can be guaranteed even without physical access to labs.