# Firewall and Security Basics

> Chapter 11 of the Courseiva LINUX-PLUS curriculum — https://courseiva.com/learn/linux-plus/firewall-and-security-basics

**Official objective:** 3.3 — Implement basic firewall and security measures

## Introduction

A firewall is a security system that controls what network traffic is allowed to enter or leave a computer or a network. For the CompTIA Linux+ XK0-006 exam, you need to know how to configure and manage firewalls on a Linux system because they are the first line of defence against unauthorised access. Without this skill, your Linux server is an open door.

## The Country Club Security Gate Analogy

The entrance to a private country club on a busy Saturday afternoon. A guard in a small booth checks every car that approaches.

The guard has a strict list of permissions. A member drives up, shows their membership card, and the guard raises the barrier without hesitation. A delivery van for the club's restaurant arrives; the guard checks the driver's name against a scheduled deliveries list, then waves them through to the service entrance. A car with a non-member driver who claims to be a guest of a member is asked to pull over while the guard phones the member for confirmation. A rental truck with no markings and a driver who cannot name a single member is turned away immediately. The guard's booth also has a logbook. Every vehicle that passes through is recorded: the licence plate, the time, the direction. If a member's car is stolen later, the club can look back at the logbook to see exactly when it left the property.

This country club gate is a firewall and its logbook is the system log. A firewall checks every piece of data trying to enter or leave a computer network against a set of rules. Traffic that matches an allowed rule is let through. Traffic that breaks a rule is dropped. Everything gets logged, so an IT professional can review what happened.

## Core explanation

A firewall is software or hardware that filters network traffic based on a set of rules. Think of it as a security guard for your computer. It sits between your computer and the internet, or between different parts of a network, and decides what data packets are allowed to pass through. A data packet is a small chunk of data sent over a network. Every packet has a source IP address (where it came from), a destination IP address (where it is going), and a port number, which identifies the specific service or application the packet is trying to reach, such as web traffic on port 80 or secure shell on port 22.

On Linux, the most common firewall tool is iptables, though modern distributions are moving to nftables. Both work by inspecting packets as they arrive at network interfaces, which are the physical or virtual network connections on your Linux machine, such as eth0 for a wired Ethernet connection. The firewall processes packets through a series of chains. A chain is an ordered list of rules. The three default chains in iptables are INPUT, for packets destined for the local system, OUTPUT, for packets leaving the local system, and FORWARD, for packets being routed through the system.

Each rule in a chain has a match condition and a target action. A match condition specifies criteria like the source IP address, destination port, or protocol. A target action tells the firewall what to do with a matching packet. The most common target actions are:

- ACCEPT: Allow the packet through.
- DROP: Silently discard the packet.
- REJECT: Discard the packet and send an error message back to the sender.
- LOG: Record the packet details in the system log and continue processing the next rule.

Rules are evaluated in order from top to bottom. Once a packet matches a rule, the associated target action is executed and no further rules in that chain are checked. This is a crucial point: if no rule matches, the default policy for the chain applies. The default policy is usually ACCEPT or DROP. A default policy of DROP means all traffic is blocked unless a specific rule allows it. This is the security principle of whitelisting.

Why does this matter? Before firewalls existed, computers on a network were completely exposed. Anyone who could reach the computer could attempt to connect to any service running on it. This led to countless security breaches. Firewalls solved this by giving administrators a way to explicitly declare which services were allowed to be accessed from outside. For the XK0-006 exam, you will need to understand how to create rules that allow specific services, such as allowing web traffic on port 80 from anywhere, while blocking all other incoming connections.

Firewalls can also perform stateful inspection. A stateful firewall remembers the state of active connections. When you send a request to a web server, the reply from the server is expected. A stateful firewall automatically allows the reply traffic even if there is no explicit rule for it, because it recognises the reply belongs to an established connection. Stateless firewalls do not track connection state and require explicit rules for both directions of traffic. Linux's iptables is stateful and can match packets based on connection state using the conntrack module. Common states include NEW, for a new connection, ESTABLISHED, for an existing connection, and RELATED, for a connection related to an existing one, like an FTP data transfer.

Another key concept is the difference between a host-based firewall and a network firewall. A host-based firewall, like iptables on your Linux machine, protects only that single computer. A network firewall is a dedicated device that protects an entire network of computers. The Linux+ exam focuses on host-based firewalls, because as a Linux administrator, you will configure the firewall on each server you manage.

Finally, remember that firewalls are only one part of a security strategy. They do not protect against malware that comes through allowed traffic, like a malicious download from a legitimate website. They do not prevent a user from accidentally exposing a password. But they are an essential tool for reducing the attack surface of your systems.

## Real-world context

Imagine you are a junior Linux administrator for a small e-commerce company. The company runs a web server that hosts their online shop. The server runs on a Linux machine with the public IP address 203.0.113.10. Your manager tells you the server has been scanned by unknown IPs on the internet, and you need to harden it with a firewall before anything gets compromised.

You connect to the server via SSH, a secure remote login protocol that uses port 22. Your first step is to check the current firewall rules. You run sudo iptables -L -n -v to list all current rules with numeric addresses and packet counts. You see that the INPUT chain has a default policy of ACCEPT, meaning all traffic is currently allowed in. This is a problem.

You decide to set a default DROP policy for the INPUT chain. But you must be careful: if you set the default to DROP before adding any allow rules, you will lock yourself out of the server, including your current SSH session. To avoid this, you first add a rule to allow SSH traffic from your office's IP address. The office uses a block of IPs: 198.51.100.0/24. You run:

- sudo iptables -A INPUT -p tcp --dport 22 -s 198.51.100.0/24 -j ACCEPT

This appends a rule to the INPUT chain that matches TCP protocol, destination port 22, and source address 198.51.100.0/24, then jumps to the ACCEPT target. Now you add a rule to allow the web server traffic on ports 80 (HTTP) and 443 (HTTPS) from any source:

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

Next, you add a rule to allow all traffic that is part of an already established connection. Without this, responses to your own outgoing connection would be dropped. You use the conntrack state module:

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

Finally, you set the default policy for the INPUT chain to DROP:

- sudo iptables -P INPUT DROP

Now only SSH from your office, and web traffic from anyone, can reach the server. All other incoming traffic is silently dropped. You test this by trying to ping the server from outside. The ping fails, which is correct because ICMP traffic is now blocked. You also check that your SSH session is still active. It is, because your office IP is allowed.

Later, you add logging to track denied packets. You insert a LOG rule just before the default DROP policy to record all dropped packets to the system log for analysis:

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

This real-world scenario demonstrates the practical steps of setting up a basic firewall: identifying allowed services and sources, adding precise allow rules, setting a restrictive default policy, and adding logging for troubleshooting and security auditing. These are the exact skills the XK0-006 exam tests.

## Exam focus

The XK0-006 exam objective 3.3 'Implement basic firewall and security measures' is a performance-based domain. Expect multiple-choice questions and scenario-based questions where you must select the correct command or interpret a firewall configuration. The exam loves to test your understanding of iptables syntax, rule ordering, and the difference between DROP and REJECT targets.

The specific concepts the exam frequently tests include:

- The default policy of a chain: Understand that if no rule matches, the default policy is applied. A common trap question gives you a set of rules that do not match a particular packet and asks what happens. The answer is the default policy.
- The order of rule evaluation: Rules are evaluated top to bottom. A matching rule stops further processing. Exam questions may present a chain with overlapping rules and ask which rule matches first. The correct answer is the first matching rule in the list.
- The difference between DROP and REJECT: DROP silently discards the packet; REJECT sends an ICMP error message back. DROP is more secure because it does not reveal the existence of a host, but it can make troubleshooting harder.
- Stateful firewall rules: Using -m conntrack --ctstate ESTABLISHED,RELATED is a standard pattern. Exam questions may present a configuration that lacks this rule and ask why legitimate replies are being dropped.
- Common port numbers: Port 22 for SSH, port 80 for HTTP, port 443 for HTTPS, port 25 for SMTP, port 53 for DNS.
- The iptables command options: -A appends a rule, -I inserts a rule at a specific position, -D deletes a rule, -L lists rules, -F flushes all rules, -P sets the default policy.

Traps to watch for:

- A question that shows a rule with -i eth0 (input interface) but the packet arrives on eth1. The rule will not match.
- A question where the default policy is ACCEPT but a specific DROP rule is added last. The packet will be dropped only if it matches the DROP rule before any ACCEPT rules. If the DROP rule is after an ACCEPT rule that matches, the packet is accepted.
- Misunderstanding the source and destination in OUTPUT chain rules. Remember: for output traffic, the source is your machine and the destination is the remote host.
- Confusing iptables with firewalld. While firewalld is a front-end for nftables on RHEL/CentOS/Fedora, the XK0-006 exam still tests iptables. If a question mentions firewalld, it will likely ask about zones or services.

Key definitions to memorise:

- Chain: An ordered list of firewall rules.
- Rule: A condition and an action.
- Target: The action taken when a rule matches (ACCEPT, DROP, REJECT, LOG).
- Stateful firewall: Tracks connection state.
- Stateless firewall: Does not track connection state.
- Default policy: The action taken when no rule matches.
- Whitelisting: Allowing only explicitly permitted traffic.
- Blacklisting: Blocking explicitly forbidden traffic.

Practice by writing iptables rules on paper. For example: 'Write a rule that allows SSH from the 10.0.0.0/8 network on the enp0s3 interface.' The answer: iptables -A INPUT -i enp0s3 -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT. Being able to compose rules from memory is a strong indicator of exam readiness.

## Step by step

1. **Assess current firewall state** — Run sudo iptables -L -n -v to list all current rules with numeric IPs and packet counters. This shows you the existing configuration before making changes.
2. **Identify required services and sources** — Determine which services your server must offer (e.g., web on port 80, SSH on port 22) and which source IP ranges are allowed (e.g., your office network for SSH). This step prevents accidental lockouts.
3. **Add allow rules before setting a restrictive default** — Use iptables -A INPUT to append rules for allow access, such as SSH from your office and web traffic from anywhere. Always add these before changing the default policy.
4. **Add a rule for established connections** — Add iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT so that responses to your own outbound connections are not blocked.
5. **Set the default policy to DROP** — Run iptables -P INPUT DROP to change the default policy. Any traffic not matching an allow rule is now silently dropped, reducing the attack surface.
6. **Add logging for dropped packets** — Insert a LOG rule before the default DROP with iptables -A INPUT -j LOG --log-prefix "FW-DROP: ". This writes dropped packet details to /var/log/syslog for troubleshooting and security auditing.
7. **Test the firewall rules** — Verify access by attempting to connect from allowed and disallowed sources. Check that SSH still works and that a ping from an untrusted source is blocked. Also examine the syslog to confirm logging works.

## Comparisons

### DROP vs REJECT

**DROP:**
- Silently discards the packet
- No response sent to the sender
- More secure because it hides the host's existence

**REJECT:**
- Discards the packet but sends an ICMP error
- Sender gets 'port unreachable' message
- Less secure because it reveals a firewall is present

### Whitelisting vs Blacklisting

**Whitelisting:**
- Allows only explicitly permitted traffic
- Default policy is DROP
- Requires you to know exactly what you need

**Blacklisting:**
- Blocks only explicitly forbidden traffic
- Default policy is ACCEPT
- Requires you to know every possible threat

### Stateless Firewall vs Stateful Firewall

**Stateless Firewall:**
- Treats each packet in isolation
- Must define rules for both request and reply
- Simpler but less effective for complex protocols

**Stateful Firewall:**
- Tracks connection state (NEW, ESTABLISHED, RELATED)
- Automatically allows reply traffic for established connections
- More complex but more secure and efficient

### iptables vs nftables

**iptables:**
- Uses separate commands for IPv4 and IPv6
- Rules are stored in a single chain hierarchy
- Older, but still widely used and tested on XK0-006

**nftables:**
- Unified framework for IPv4 and IPv6
- Uses a simpler, native syntax
- Modern replacement, default on newer distributions

## Diagram

_Flow of an incoming packet through the iptables INPUT chain with three allow rules and a default DROP policy._

```mermaid
graph TD
    A[Internet Traffic] --> B[Firewall INPUT Chain]
    B --> C{Rule 1: Allow SSH from Office?}
    C -->|Yes| D[ACCEPT]
    C -->|No| E{Rule 2: Allow Web on port 80/443?}
    E -->|Yes| F[ACCEPT]
    E -->|No| G{Rule 3: Established Connection?}
    G -->|Yes| H[ACCEPT]
    G -->|No| I[Default Policy: DROP]
```

## Common misconceptions

- **Misconception:** A firewall blocks all malicious traffic automatically. **Reality:** A firewall only filters traffic based on rules you create. It cannot identify or block malware inside allowed traffic, like a malicious download from a legitimate website. (People often think firewalls are 'smart' and can detect attacks like an antivirus. In reality, they are simple rule enforcers.)
- **Misconception:** Setting the default policy to DROP is enough; you do not need to add any accept rules. **Reality:** A default DROP policy without any accept rules will block all traffic, including your own SSH session, effectively locking you out of the server. (New administrators assume a 'block everything' approach is safest without considering the need for legitimate administrative access.)
- **Misconception:** Adding a DROP rule will send a rejection notice to the sender. **Reality:** DROP silently discards the packet. The sender sees no response and typically retries until timeout. REJECT sends an ICMP error back. (The terms 'drop' and 'reject' are often used interchangeably in everyday language.)
- **Misconception:** Firewall rules are always evaluated from the last rule to the first. **Reality:** Rules are evaluated from the first rule to the last. Once a packet matches a rule, no further rules are checked. (This is a common confusion because some other system configurations (like routing tables) may use longest-prefix matching, not sequential order.)
- **Misconception:** If I flush the firewall (iptables -F), all traffic is immediately allowed. **Reality:** Flushing removes all rules but does not change the default policy. If the default policy is DROP, flushing the rules leaves no allow rules, so all traffic is still dropped. (Beginners think 'flush' means 'reset to safe defaults', but the default policy persists independently.)

## Key takeaways

- A firewall filters network packets based on a set of ordered rules, using source IP, destination IP, port, and protocol as match criteria.
- The three default iptables chains are INPUT (incoming), OUTPUT (outgoing), and FORWARD (routed through the system).
- Rules are evaluated from top to bottom; once a packet matches a rule, no further rules are processed.
- The default policy for a chain applies when no rule matches; set it to DROP for a whitelisting approach.
- Use -m conntrack --ctstate ESTABLISHED,RELATED to allow reply traffic for established connections.
- DROP silently discards a packet, while REJECT sends an ICMP error back to the sender.
- Flushing rules with iptables -F does not change the default policy, so a DROP default still blocks all traffic.

## FAQ

**What is the difference between iptables and nftables?**

iptables is the older firewall tool using separate commands for IPv4 and IPv6. nftables is its modern replacement that consolidates both into a single framework with simpler syntax. The XK0-006 exam tests both, but iptables is the primary focus.

**Can a firewall protect against viruses?**

No. A firewall controls network traffic based on addresses and ports. It cannot inspect the contents of packets for viruses or malware. You need antivirus software for that.

**What happens if I set the default policy to DROP before adding any allow rules?**

You will instantly lose all connectivity, including your current SSH session, because no traffic is allowed in or out. This is why you always add allow rules first.

**How do I make my firewall rules permanent after a reboot?**

iptables rules are volatile and lost on reboot. Use iptables-save to export rules to a file, then restore them with iptables-restore. Many distributions also have iptables-persistent or firewalld for persistence.

**What is the difference between REJECT and DROP?**

DROP silently discards the packet and sends no response. REJECT discards the packet but sends an ICMP error message back to the sender, telling them the port is unreachable.

**Why do I need a rule for established connections?**

Without it, when your server sends a reply to a legitimate request, that reply appears as new incoming traffic and could be dropped by the firewall. The ESTABLISHED rule tells the firewall to allow traffic that belongs to an ongoing conversation.

## Check your understanding

1. **What command lists all iptables rules in the INPUT chain with numeric IP addresses and packet counts?**

   Answer: sudo iptables -L INPUT -n -v

2. **What is the default policy of a chain in iptables, and what action does it perform?**

   Answer: The default policy is the action taken when no rule in the chain matches the packet. It can be either ACCEPT or DROP.

3. **Why must you add an ESTABLISHED,RELATED rule to your firewall when using a default DROP policy?**

   Answer: Without it, reply packets for legitimate outgoing connections would be treated as new incoming traffic and dropped by the default DROP policy.

4. **What is the difference between the DROP and REJECT targets?**

   Answer: DROP silently discards the packet and sends no response. REJECT discards the packet and sends an ICMP error message back to the sender.

5. **What happens to a packet that does not match any rule in a chain?**

   Answer: It is subject to the default policy of that chain, either ACCEPT or DROP.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/linux-plus/firewall-and-security-basics
