# System Security and Sudo Configuration

> Chapter 17 of the Courseiva LPI-LPIC1 curriculum — https://courseiva.com/learn/lpi-lpic1/security-and-sudo

**Official objective:** 102.4 — Manage user privileges with sudo, configure security settings, and understand basic firewall concepts.

## Introduction

How do you let a junior colleague run a critical backup script without handing them the root password to the entire server? That is the problem sudo (short for 'superuser do') solves for Linux administrators. For the LPIC-1 exam, understanding how to grant limited, auditable privileges to users is a core objective because in real IT environments nobody should have unrestricted root access unless absolutely necessary.

## The Shared Student House Kitchen Analogy

Inside a shared student house kitchen on a busy Sunday evening. The house has six housemates, and the kitchen rulebook is strict: only the person whose name is on the weekly cleaning rota is allowed to touch the bleach under the sink, because bleach is dangerous if used incorrectly. 

One housemate (the root user in system terms) has a key to every cupboard, can use the oven, the sharp knives, and the bleach whenever they want. That is total power — and total risk if they burn dinner. The other housemates are normal users who can only use the microwave and the toaster. 

Now, suppose a housemate needs to unlock the oven to bake a birthday cake, but only once. They do not need the bleach key forever. The system administrator (the landlord) creates a special note taped to the fridge that says: "Housemate Alice is permitted to use the oven on Saturday between 2pm and 4pm to bake one cake." That note is the sudo configuration file. It grants temporary, specific, auditable permission to do a single privileged task without handing over the master key. 

If Alice bakes twenty cakes unexpectedly, the landlord checks the digital log (the sudo log) and sees exactly who did what and when. The sudo system is that shared note: precise permission, limited scope, full accountability.

## Core explanation

The Linux permission model starts with two fundamental user types: the root user and all other users. The root user (also called the superuser) has unlimited power — they can read, write, or delete any file, change any system configuration, and install or remove software. Every other user on a Linux system operates with limited privileges, restricted to their own home directory and files they own. That is a good security principle: the least privilege model, meaning users should only have the permissions they need to do their job. 

But here is the practical problem: many legitimate administrative tasks require root-level privileges. For example, installing a package, editing a system configuration file like /etc/hosts, or restarting a system service. Handing out the root password to everyone who needs to do these tasks is dangerous because anyone with the root password can do anything, including accidentally deleting critical files. 

This is where sudo enters. Sudo stands for 'superuser do'. It is a command that allows a permitted user to execute a command as the superuser (or as another user) as specified by a configuration file called /etc/sudoers. The key insight is that the user does not need to know the root password — they only need to know their own password. The system checks the /etc/sudoers file to see if that user is allowed to run that specific command. 

The /etc/sudoers file is not a plain text file you edit with a normal text editor. Instead, you must use a special command called visudo. Visudo opens the sudoers file in a text editor, performs syntax checking before saving, and prevents two administrators from editing the file simultaneously. This is critical because a single syntax error in /etc/sudoers can lock everyone out of sudo access entirely. 

A typical line in /etc/sudoers looks like this:

username ALL=(ALL:ALL) ALL

Let us break that down. The first field is the username. The second field 'ALL' means this rule applies from any host (in a network context). The '(ALL:ALL)' means the user can run commands as any user and any group. The final 'ALL' means any command is allowed. That is a very broad permission. A more restricted rule might look like:

alice ALL=(root) /usr/bin/systemctl restart nginx

This means user alice can, from any host, run only the command /usr/bin/systemctl restart nginx as the root user. She cannot run any other command with sudo. 

You can also create user groups with the % prefix. For example, %admin ALL=(ALL) ALL gives all members of the 'admin' group full sudo access. 

Another important concept is the sudoers alias. You can define lists of users (User_Alias), commands (Cmnd_Alias), and hosts (Host_Alias) to make the configuration file more readable. For example:

User_Alias ADMINS = alice, bob
Cmnd_Alias SERVICES = /usr/bin/systemctl restart nginx, /usr/bin/systemctl restart apache2
ADMINS ALL=(root) SERVICES

This gives alice and bob permission to restart nginx and apache2. 

Sudo also logs every command execution. By default, logs go to syslog (often /var/log/auth.log or /var/log/secure depending on distribution). This creates an audit trail. If something goes wrong, the administrator can check exactly who ran what command and when. 

Beyond sudo, this chapter introduces basic firewall concepts. A firewall is a system that controls incoming and outgoing network traffic based on predetermined security rules. In Linux, the most common firewall tool is iptables (older) and its successor nftables (modern). The LPIC-1 exam focuses on iptables concepts. 

The fundamental building block of iptables is a rule. Rules are organised into chains, and chains belong to tables. The three default tables are: filter (for packet filtering decisions), nat (for network address translation), and mangle (for specialised packet alterations). The filter table has three built-in chains: INPUT (traffic destined for the local system), FORWARD (traffic passing through the system), and OUTPUT (traffic originating from the local system). 

A simple iptables rule looks like:

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

This appends (-A) a rule to the INPUT chain that accepts (-j ACCEPT) incoming TCP traffic on port 22 (SSH). The default policy for a chain is usually ACCEPT or DROP. A DROP policy means any packet that does not match a specific ACCEPT rule is discarded. 

For the LPIC-1 exam, you need to understand the basic syntax: iptables -A (append), -I (insert at the top), -D (delete), -L (list rules), -F (flush all rules). You also need to know how to save rules with iptables-save and restore them with iptables-restore, because iptables rules are not persistent by default across reboots. 

Firewall rules are processed in order. The first matching rule determines the action. That means if you have a rule that accepts all traffic at the top, then a later rule that blocks a specific port will never be reached. This is a common trap beginners fall into.

## Real-world context

Imagine you are the sole IT administrator for a small e-commerce company with five web servers and a database server. Your company has three junior developers who need to restart the web server service after deploying code updates, but you absolutely do not want them to be able to shut down the database server or modify firewall rules. 

Step one: you create a Linux group called 'web-devs' and add the three developers to it. Step two: you use visudo to edit /etc/sudoers. You add a line: %web-devs ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl restart apache2. Now each developer can run 'sudo systemctl restart nginx' when needed. They are prompted for their own password, which logs the action. 

Next, your senior database administrator (DBA) needs to run database backup scripts that require root access. You create a User_Alias called DBA and a Cmnd_Alias called DB_BACKUP. You grant the DBA group permission to run only the backup script. You also set a NOPASSWD tag so the DBA does not have to enter a password each time (since the backup runs via cron at 2am). The line looks like: %dba ALL=(root) NOPASSWD: /usr/local/bin/db_backup.sh 

Now, a real-world problem: a junior developer accidentally runs 'sudo systemctl restart nginx' twice in a minute, causing a brief service interruption. You check /var/log/auth.log and see exactly that developer's session timestamp and the command. You have an audit trail. 

For firewall management, your company has a public-facing web server. You need to allow HTTP (port 80) and HTTPS (port 443) traffic from anywhere, SSH (port 22) only from the company's office IP range, and block everything else. You create the following iptables rules: 
- iptables -A INPUT -p tcp --dport 80 -j ACCEPT 
- iptables -A INPUT -p tcp --dport 443 -j ACCEPT 
- iptables -A INPUT -p tcp --dport 22 -s 203.0.113.0/24 -j ACCEPT 
- iptables -P INPUT DROP 

The default DROP policy ensures that any other incoming connection is silently rejected. You then use iptables-save > /etc/iptables/rules.v4 to make the rules persistent across reboots. 

Six months later, a security audit reveals that port 22 was briefly exposed to the entire internet because a junior admin accidentally deleted the SSH rule while troubleshooting. Because you have logs and a documented sudo configuration, you can trace the exact command and time. The lesson: sudo restrictions and firewall rules work together to maintain security boundaries.

## Exam focus

The LPIC-1 exam objective 102.4 specifically tests your ability to configure and manage sudo, and to understand basic firewall concepts with iptables. Here is exactly what to expect:

- The exam will ask you to interpret sudoers file syntax. You will be given a line like 'bob ALL=(root) /usr/bin/less, /usr/bin/more' and you must know that bob can run only those two commands as root. They love testing the alias syntax (User_Alias, Cmnd_Alias, Host_Alias).

- They will present a scenario where a user cannot run sudo, and you must identify the cause: perhaps the user is not in the sudoers file, or the hostname does not match the ALL entry, or there is a syntax error preventing visudo from loading.

- A common trap: the exam shows a sudoers line with a typo like 'alice ALL=(ALL) ALL' missing the colon. That line is invalid and visudo would reject it. The correct syntax requires the colon after the user specification, so 'ALL=(ALL:ALL)' or 'ALL=(ALL)'.

- Another trap: forgetting that sudo prompts for the user's own password, not root's password. The exam might ask what happens when you run 'sudo command' as a user who is in the sudoers file with the NOPASSWD tag: they do not get prompted at all.

- For iptables, the exam expects you to know the basic commands: -A (append), -I (insert), -D (delete), -L (list), -F (flush), -P (set default policy). They will ask which command adds a rule to the INPUT chain that drops traffic from a specific IP. The correct answer uses -A INPUT -s source_ip -j DROP.

- They love the concept of rule order. A question may present a set of iptables rules where a DROP rule appears before an ACCEPT rule for the same traffic, and you must recognise that the first matching rule takes effect, so traffic is dropped.

- The exam will test the three default chains (INPUT, FORWARD, OUTPUT) and the three default tables (filter, nat, mangle). You do not need to memorise every mangle option, but you must know which table is used for basic packet filtering (filter).

- They will ask about persistence: how do you save iptables rules so they survive a reboot? The answer is iptables-save > filename and then restore with iptables-restore, or using distribution-specific tools like iptables-persistent.

- Another common question: what happens when the default policy is set to DROP and no rules match a packet? The packet is dropped. If the policy is ACCEPT, it is accepted.

- For sudo, the exam tests the difference between visudo and directly editing the /etc/sudoers file. They want to know that visudo performs syntax checking and prevents simultaneous edits. A trap question might suggest editing with vi directly, which is dangerous.

- Memorise the sudoers line syntax precisely: username hostname=(runas_user:runas_group) [TAGS:] command. Tags include NOPASSWD, PASSWD, NOEXEC, and others.

- They occasionally test that % means a group, not a user. So %admin ALL=(ALL) ALL applies to all users in the admin group.

- For logging, know that sudo logs to the auth facility by default, which is typically /var/log/auth.log or /var/log/secure. A question might ask which log file shows sudo commands.

- There is no need to memorise every iptables module, but know what -p (protocol), --dport (destination port), -s (source IP), -j (jump to target) mean.

## Step by step

1. **Identify the user and the required command** — Determine which user or group needs elevated privileges and exactly which command they need to run. For example, a developer needs to restart the nginx service. This specificity is crucial because the entire sudo configuration is built on granting minimal necessary permissions, not blanket access.
2. **Launch visudo to edit the sudoers file** — Run the command 'visudo' as root. This opens the /etc/sudoers file in a safe editing environment. Visudo locks the file to prevent two admins from editing it at the same time and checks the syntax before saving. If you made a typo, visudo will refuse to save and will ask you to fix it, preventing a catastrophic lockout.
3. **Add the sudoers rule with correct syntax** — Write the rule using the format: username hostname=(runas_user) [TAGS:] command. For a group, use %groupname. For example, '%webdevs ALL=(root) /usr/bin/systemctl restart nginx'. This allows every member of the webdevs group to restart nginx as root from any host.
4. **Save and exit visudo** — Visudo validates the syntax. If there are no errors, it writes the changes to /etc/sudoers. If there is an error, visudo prompts you to edit again or discard changes. After saving, the new rules take effect immediately for any new sudo commands. There is no need to restart a service.
5. **Test the sudo configuration** — Log in as the user (without root access) and run the permitted command with sudo, for example 'sudo systemctl restart nginx'. The user will be prompted for their own password (unless the NOPASSWD tag is used). The command should execute successfully. Then test a forbidden command like 'sudo rm /etc/passwd' to confirm it is denied.
6. **Verify the audit log** — Check /var/log/auth.log or /var/log/secure to see the logged sudo command. The log entry includes the username, the command run, the time, and the terminal. This verifies that auditing is working and provides a record for security review.

## Comparisons

### su vs sudo

**su:**
- Requires the target user's password (usually root's password) to switch to that user.
- Gives you a full interactive shell as the target user until you exit.
- Does not log individual commands; it only logs the su invocation itself.
- Legacy tool, less granular control over permissions.

**sudo:**
- Requires only the user's own password to run a single command.
- Runs only the specific command defined in the sudoers file, then returns to the original user.
- Logs every command executed via sudo, including the exact command line and timestamp.
- Allows precise per-user, per-command, per-host privilege delegation.

### iptables filter table vs iptables nat table

**iptables filter table:**
- Used for basic packet filtering: accept, drop, or reject traffic.
- Operates on the INPUT, FORWARD, and OUTPUT chains.
- Does not modify packet addresses; only decides whether the packet passes.
- The default table when no table is specified in an iptables command.

**iptables nat table:**
- Used for Network Address Translation (NAT): changing source or destination IP addresses.
- Operates on the PREROUTING, POSTROUTING, and OUTPUT chains.
- Modifies the source or destination IP address of packets, typically for masquerading or port forwarding.
- Rarely used for simple allow/deny decisions; primarily for routing and public IP sharing.

### User alias in sudoers vs User group in sudoers

**User alias in sudoers:**
- Defined using User_Alias keyword (e.g. User_Alias ADMINS = alice, bob).
- Aliases are only valid inside the sudoers file and can group non-existent or local users.
- Can include usernames or other User_Alias names.

**User group in sudoers:**
- Referenced with a % prefix (e.g. %admin).
- Refers to an actual system group defined in /etc/group.
- Automatically includes any user added to the system group via useradd or usermod.

### Default iptables policy ACCEPT vs Default iptables policy DROP

**Default iptables policy ACCEPT:**
- Any packet not matched by a specific rule is accepted by default.
- Simpler initial configuration because you only need to block specific traffic.
- Less secure because a missing explicit rule inadvertently allows traffic through.

**Default iptables policy DROP:**
- Any packet not matched by a specific rule is dropped by default.
- Requires you to explicitly allow only the traffic you want, following the principle of least privilege.
- More secure but requires careful rule management to avoid accidentally blocking legitimate traffic.

## Diagram

_The flow of a sudo command from user request to execution, including authentication and logging._

```mermaid
flowchart TD
    A[User runs 'sudo command'] --> B{Is user in /etc/sudoers?}
    B -->|No| C[Command denied: access log recorded]
    B -->|Yes| D{Does the rule match this command?}
    D -->|No| C
    D -->|Yes| E[User enters own password (unless NOPASSWD)]
    E --> F{Password correct?}
    F -->|No| C
    F -->|Yes| G[Command executed as root]
    G --> H[Action logged to /var/log/auth.log]
```

## Common misconceptions

- **Misconception:** Sudo allows a user to do anything as root, just like logging in as root. **Reality:** Sudo only allows a user to run specific commands that are explicitly listed in the /etc/sudoers file. By default, a user can run absolutely nothing with sudo until granted permission. (Many beginners see the 'sudo -i' command that opens a root shell and assume that all sudo access is unlimited. They confuse the wide-open default configuration on personal Linux desktop distributions (where the first user often gets full sudo) with the locked-down configuration required in enterprise environments.)
- **Misconception:** The /etc/sudoers file can be edited with a normal text editor like vi or nano, just like any other configuration file. **Reality:** The /etc/sudoers file must always be edited using the visudo command, which checks syntax and prevents simultaneous edits. Editing it directly can result in a syntax error that permanently breaks sudo access for all users, including root. (On a personal computer, editing sudoers directly often works without immediate visible consequences because the syntax happens to be correct. Beginners do not experience the risk until they accidentally introduce a typo and lock themselves out of sudo entirely, which is a catastrophic failure in a production environment.)
- **Misconception:** Iptables rules automatically persist across reboots, so once you add a rule, it stays forever. **Reality:** Iptables rules are stored only in kernel memory and are lost on every reboot. You must explicitly save them to a file using iptables-save and restore them on boot using iptables-restore or a distribution-specific tool like iptables-persistent. (The manual configuration of iptables feels immediate and permanent when you run the command and see the rule take effect. Beginners do not realise that the kernel is volatile, so testing a firewall rule and then rebooting without saving can lead to unintended full network access.)
- **Misconception:** The order of iptables rules does not matter because the firewall will eventually match the right rule. **Reality:** Iptables processes rules in order, from top to bottom. The first rule that matches a packet determines the action. If a DROP rule appears before an ACCEPT rule for the same traffic, the packet is dropped and the later ACCEPT rule is never evaluated. (Beginners often think of firewall rules like a checklist where all rules are evaluated simultaneously. The idea of sequential processing is counter-intuitive because it means placing a broad deny rule at the top can accidentally block traffic that a later rule would have permitted.)
- **Misconception:** The root user is the only user who can use sudo. **Reality:** The root user does not need sudo because root already has all privileges. Sudo is designed for non-root users who need temporary elevated privileges. In fact, trying to use sudo as root is unnecessary and the system typically ignores it because root already has full access. (The word 'superuser' in 'sudo' implies the root user. Beginners logically assume that sudo is a tool for root. They do not grasp that sudo bridges the gap between normal users and root, rather than being a feature of the root account itself.)

## Key takeaways

- The /etc/sudoers file controls which users can run which commands with elevated privileges, and it must always be edited with visudo to prevent syntax errors.
- Sudo logs every executed command to the auth facility, typically found in /var/log/auth.log or /var/log/secure, creating an audit trail for security.
- Iptables firewall rules are processed sequentially — the first matching rule determines the action, so rule order is critically important.
- Iptables rules are not persistent across reboots; you must use iptables-save and iptables-restore to save and load them.
- In the sudoers file, %groupname grants permissions to all members of a group, while a plain username applies only to that single user.
- The default iptables policy for a chain (ACCEPT or DROP) handles traffic that does not match any specific rule in that chain.
- A sudoers line like 'alice ALL=(root) /usr/bin/systemctl' means alice can run only that exact command as root from any host.
- The visudo command locks the /etc/sudoers file to prevent simultaneous edits and performs syntax validation before saving.

## FAQ

**I accidentally broke the /etc/sudoers file and now I cannot use sudo at all. How do I fix it without root access?**

If you still have physical or console access to the machine, reboot into single-user mode (by adding 'single' to the kernel boot parameters in GRUB) which gives you a root shell without requiring sudo. Then fix the file with visudo. If you cannot reboot, you are likely locked out and will need to boot from a live USB to mount the filesystem and correct the typo.

**What is the difference between visudo and editing /etc/sudoers directly with vi?**

Visudo performs syntax checking before saving and locks the file to prevent concurrent edits. Editing directly with vi skips both checks, so a typo can render sudo unusable for everyone, including root. Always use visudo.

**Why does sudo ask for my password and not root's password?**

Sudo authenticates the user running the command, not the target user. It asks for your own password to confirm you are who you say you are. The root password is never exposed. This is a security design to keep the root password secret.

**Iptables rules disappear after I reboot. How do I make them permanent?**

Use iptables-save to write the current rules to a file, such as /etc/iptables/rules.v4. Then configure the system to run iptables-restore from that file at boot. On Debian-based systems, install the iptables-persistent package which automates this.

**What does the NOPASSWD tag do in the sudoers file?**

NOPASSWD allows a user to run specified commands with sudo without being prompted for a password. This is useful for automated scripts or cron jobs that need to run commands as root, but it should be used sparingly because it weakens security.

**Can I use sudo to run a command as a user other than root?**

Yes. In the sudoers file, the (runas_user) field specifies which user the command should run as. For example, 'alice ALL=(bob) /usr/bin/less' allows alice to run the less command as bob. By default, it runs as root.

## Check your understanding

1. **What command should you use to safely edit the /etc/sudoers file?**

   Answer: The visudo command, because it locks the file and performs syntax checking before saving.

2. **In an iptables command, what does the '-P' flag do?**

   Answer: It sets the default policy (e.g., ACCEPT or DROP) for a specific chain, such as INPUT, FORWARD, or OUTPUT.

3. **A user is in the sudoers file but still gets 'permission denied' when running a command with sudo. What is the most likely cause?**

   Answer: The command is not listed in the user's sudoers entry, or the hostname in the rule does not match the current host (e.g., using 'ALL' incorrectly).

4. **What happens to iptables rules after the system is rebooted if you have not saved them?**

   Answer: All iptables rules are lost because they exist only in kernel memory. You must use iptables-save to persist them.

5. **If the sudoers file contains the line '%wheel ALL=(ALL) ALL', who is affected by this rule?**

   Answer: All members of the system group 'wheel' are allowed to run any command as any user from any host.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/lpi-lpic1/security-and-sudo
