LESSON 23 · BEGINNER7 min read

Linux Hardening and Shell Scripting for Security

Harden a Linux server with SSH, firewall, patching, auditing, and least privilege, then automate the checks with safe, defensive shell scripts.

OWASP Top 10 · MITRE ATT&CK · NIST CSF 2.0Free to readModule 5 of 14
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Harden SSH, host firewalls, patching, and scheduled tasks on a lab Linux server.
  • Use auditd, journald, AIDE, fail2ban, and Lynis to detect and review host activity.
  • Audit SUID binaries, Linux capabilities, file permissions, cron, and systemd timers.
  • Write a defensive shell script with strict mode, arguments, functions, pipelines, and safe temporary files.

01Hardening Starts With a Threat Model

A default Linux installation is designed to be useful, not secure. It may allow password logins, run services you did not choose, keep logs only in memory, and give every administrator the same account. Hardening is the deliberate process of reducing that default attack surface until the host matches its job. A public web server, a build agent, and a developer laptop need different rules.

Start with a simple threat model. Who can reach the host? Which accounts can log in? What could an attacker do with a stolen password, a local shell, or a compromised service? Where would they persist, and what evidence would they leave? On a lab virtual machine, snapshot the clean state first. On a real host, confirm that you have written authorisation and a console or out-of-band recovery path.

Change one control at a time, verify it, and record the before and after state. Hardening is not a score you achieve once. It is a maintenance loop: apply a baseline, monitor drift, review exceptions, and repeat after upgrades. The goal is a host you can explain, not a long list of commands you copied from a blog.

02Close the Front Door: SSH and the Firewall

SSH is usually the most valuable remote door on a Linux server. Direct root login removes accountability and gives an attacker a known, privileged target. Password authentication allows unlimited guessing and credential stuffing. Key-based authentication with a named account, sudo for privilege, and a restricted source network is a much smaller door.

Edit sshd_config carefully. Set PermitRootLogin no, PasswordAuthentication no, PubkeyAuthentication yes, and an explicit AllowUsers or AllowGroups list. Reduce MaxAuthTries and LoginGraceTime. Keep at least one working session open while you reload the service, and test from a second terminal before you close the first. If the change is wrong, the console or snapshot is your recovery path.

A host firewall is the second layer. The Uncomplicated Firewall (UFW) is a friendly front end for nftables on Ubuntu; nftables is the underlying packet filter. Default-deny inbound, allow only the management network to reach SSH, and allow the application ports the service actually needs. Fail2ban can slow repeated authentication failures, but it is a compensating control, not a replacement for keys and a restricted network.

ssh-and-firewall.shShell
# Back up before editing, then review the effective settings.sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.baksudoedit /etc/ssh/sshd_config# In sshd_config:# PermitRootLogin no# PasswordAuthentication no# PubkeyAuthentication yes# AllowUsers analyst deploy# MaxAuthTries 3# LoginGraceTime 30sudo sshd -tsudo systemctl reload sshsudo sshd -T | grep -E "permitrootlogin|passwordauthentication|allowusers"sudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw allow from 10.10.10.0/24 to any port 22 proto tcpsudo ufw enablesudo ufw status verbosesudo nft list rulesetsudo fail2ban-client status sshd
Outputstdout
permitrootlogin no
passwordauthentication no
allowusers analyst deploy
Status: active
To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       10.10.10.0/24

03Patch, Audit, and Keep the Record

Unpatched software is a reliable path to compromise. Enable unattended security upgrades, define a reboot window, and verify that the service is running. Kernel updates usually need a reboot unless you use live patching. Track the package versions that matter and test critical services after an upgrade. Automatic updates reduce the window of exposure; they do not remove the need to review what changed.

auditd records security-relevant system calls and file changes. Watch identity files, sudoers, SSH configuration, and privileged execution. Use aureport and ausearch to review events by key. Rules can be made immutable until reboot, which raises the cost of tampering. Audit rules are not a substitute for remote log collection, because an attacker with root can still interfere with the local host.

journald stores service logs. Make the journal persistent, cap its disk use, and forward important events to a remote collector. Check time synchronisation, because correlation across hosts depends on accurate clocks. The Advanced Intrusion Detection Environment (AIDE) takes a baseline of file hashes and reports changes; Lynis runs a broad configuration audit; both are most useful on a schedule with a named owner who reviews the output.

patch-audit-log.shShell
sudo apt updatesudo apt install -y unattended-upgrades auditd audispd-plugins aide lynis fail2bansudo dpkg-reconfigure --priority=low unattended-upgrades# Runtime audit rules. Persist them in /etc/audit/rules.d/ for reboots.sudo systemctl enable --now auditdsudo auditctl -w /etc/passwd -p wa -k identitysudo auditctl -w /etc/sudoers -p wa -k privilegesudo auditctl -w /etc/ssh/sshd_config -p wa -k ssh_configsudo ausearch -k identity -ts recentsudo aureport --auth --summary# Persistent journal storage.sudo journalctl --disk-usagesudo mkdir -p /var/log/journalsudo systemd-tmpfiles --create --prefix /var/log/journalsudo systemctl restart systemd-journald# File-integrity baseline and a broad configuration review.sudo aideinitsudo aide --checksudo lynis audit system
Outputstdout
New rules loaded.
identity: 3 events
Authentication summary: 12 failures, 4 successes
Journal size: 48.0M
AIDE found differences in 2 files.
Lynis hardening index: 68

04Privilege, Capabilities, and Scheduled Persistence

A setuid (SUID) root binary runs with the file owner's privilege. That is sometimes necessary, but every unexpected SUID binary is a potential privilege-escalation path. Compare the list with the package manager's records, investigate anything local or unfamiliar, and remove the bit when the program does not need it. Linux capabilities offer a narrower alternative: grant only the specific capability a service needs instead of full root.

File permissions are part of the same story. Private keys should be 0600, /etc/shadow should not be world-readable, home directories should not be world-writable, and a sensible umask such as 027 keeps new files private by default. Audit world-writable files and directories without the sticky bit. A shared directory such as /tmp needs the sticky bit so users cannot delete each other's files.

Attackers persist through cron jobs, systemd timers, shell profiles, and service unit files. List every user's crontab, the system cron directories, enabled timers, and recently modified unit files. Check who can write the script a timer runs, because a writable script turns a benign schedule into privilege escalation. Review the environment and PATH used by scheduled jobs, and alert on new or changed entries.

privilege-review.shShell
# Unexpected privilege and capabilities.sudo find / -xdev -type f -perm -4000 -print 2>/dev/nullsudo getcap -r / 2>/dev/null# Grant one narrow capability instead of setuid root.sudo setcap cap_net_bind_service=+ep /usr/local/bin/lab-servicegetcap /usr/local/bin/lab-service# Identity and permission checks.getent passwd | awk -F: '$3 == 0 {print $1}'stat -c "%A %a %U:%G %n" /etc/shadow /etc/ssh/ssh_host_ed25519_keysudo find /etc -type f -perm -0002 -print 2>/dev/null# Scheduled execution.sudo crontab -lsudo ls -la /etc/cron.d /etc/cron.dailysudo systemctl list-timers --all --no-pagersudo systemd-analyze security ssh.service
Outputstdout
/usr/bin/passwd
/usr/bin/sudo
/usr/local/bin/lab-service cap_net_bind_service=ep
root
-rw-r----- 640 root:shadow /etc/shadow
-rw------- 600 root:root /etc/ssh/ssh_host_ed25519_key
0 timers listed.

05Shell Scripting That Does Not Betray You

Security work involves repetitive inspection: count failures, compare hosts, collect evidence, and produce a report. Shell scripting is the fastest way to automate those tasks on Linux. The language is small, but it is full of sharp edges. Quote variables, check arguments, avoid eval, and prefer small functions with clear names. A script that fails loudly is safer than one that continues after an error.

Start every defensive script with set -euo pipefail. The -e option stops on an unhandled command failure, -u treats an unset variable as an error, and pipefail makes a pipeline fail when any stage fails. Use getopts or explicit arguments, validate paths, and print usage to stderr. Use grep for literal matching, awk for fields and arithmetic, and sed for controlled substitution. Do not parse ls output, and do not build commands by concatenating untrusted strings.

Temporary files need unpredictable names. mktemp creates a file or directory with safe permissions; a fixed path in /tmp invites collisions and symlink attacks. Set a trap to remove the workspace on exit, keep evidence in a dated directory, and write a summary that includes the input, threshold, and timestamp. Run shellcheck and test with empty, malformed, and large inputs before you trust the script.

The script below reads an authentication log, extracts source addresses from failed-password lines, and prints sources at or above a threshold. It demonstrates strict mode, argument parsing, functions, a pipeline, a loop, and safe temporary files. It is deliberately read-only. Point it at a synthetic lab log, not a production system, until you have reviewed every path and permission.

failed-login-report.shShell
#!/usr/bin/env bashset -euo pipefailusage() {  echo "usage: $0 -f auth.log [-t 10]" >&2}log_file=""threshold=10while getopts "f:t:h" option; do  case "$option" in    f) log_file="$OPTARG" ;;    t) threshold="$OPTARG" ;;    h) usage; exit 0 ;;    *) usage; exit 2 ;;  esacdoneif [[ -z "$log_file" || ! -r "$log_file" ]]; then  echo "error: provide a readable log with -f" >&2  exit 1fiif ! [[ "$threshold" =~ ^[0-9]+$ ]]; then  echo "error: threshold must be a number" >&2  exit 1fiworkdir="$(mktemp -d)"trap 'rm -rf "$workdir"' EXITumask 077parse_failures() {  local input="$1"  { grep -F "Failed password" "$input" || true; } \    | awk '{for (i = 1; i <= NF; i++) if ($i == "from") print $(i + 1)}' \    | sort | uniq -c | sort -nr}parse_failures "$log_file" > "$workdir/all.txt"while read -r count source; do  if (( count >= threshold )); then    echo "$count failures from $source"  fidone < "$workdir/all.txt" > "$workdir/suspects.txt"# Create a short redacted sample for sharing; sed performs a controlled substitution.sed -E 's/user [^ ]+/user REDACTED/' "$log_file" | head -n 3 > "$workdir/sample.txt"echo "log: $log_file"echo "threshold: $threshold"echo "suspects: $(wc -l < "$workdir/suspects.txt")"cat "$workdir/suspects.txt"
Outputstdout
log: /var/log/auth.log
threshold: 10
suspects: 2
18 failures from 203.0.113.77
11 failures from 198.51.100.22
LET IT CLICK

The ideas worth keeping.

  • Harden to a role-based baseline, change one control at a time, and always keep a recovery path.
  • SSH keys, a named administrative account, and a default-deny firewall remove the most common remote attack path.
  • Patching, auditd, persistent journald, AIDE, and Lynis turn a host into something you can observe and verify.
  • Audit SUID, capabilities, permissions, cron, and timers, then automate repeatable checks with strict-mode shell scripts.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Write the SSH and firewall change

Starting from a default Ubuntu lab VM, write the exact changes and verification steps to disable direct root login and password authentication, allow SSH only from 10.10.10.0/24, and prove the rules are active. Include a recovery step in case the change locks you out.

Explore a worked solution
one_possible_solution.mdCybersecurity
Back up the configuration, then set PermitRootLogin no, PasswordAuthentication no, PubkeyAuthentication yes, and AllowUsers analyst deploy in /etc/ssh/sshd_config. Run sudo sshd -t to validate the syntax, reload with sudo systemctl reload ssh, and keep an existing session open while you test from a second terminal. Configure the firewall with sudo ufw default deny incoming, sudo ufw default allow outgoing, sudo ufw allow from 10.10.10.0/24 to any port 22 proto tcp, and sudo ufw enable. Verify with sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication|allowusers' and sudo ufw status verbose. Test password login explicitly with ssh -o PreferredAuthentications=password analyst@host and confirm it is rejected. Recovery: use the hypervisor console or restore the VM snapshot, then fix the configuration locally. On a physical host, keep an out-of-band console or a scheduled rollback before changing SSH.

The change must be validated before the reload, tested from a separate session, and reversible without relying on the door you just closed. Verification proves effective configuration, not just the text in the file.

02

Exercise 2: Extend the report script

Modify the failed-login script to accept multiple log files, write a CSV summary with the source, failure count, and log filename, and redact usernames. Explain how you keep temporary files safe and why set -euo pipefail changes how you handle grep finding no matches.

Explore a worked solution
one_possible_solution.mdCybersecurity
Accept files with -f file1 -f file2 or with remaining arguments after the options. Loop over the list, call parse_failures for each file, and write rows with printf '%s,%s,%s' or a small CSV function that quotes fields. Redact usernames before output by replacing the account portion with a stable hash or the word redacted, and never include passwords or full command lines. Keep the work directory from mktemp, set umask 077, and install a trap that removes it on EXIT. With set -euo pipefail, a grep that finds no matches returns 1 and can abort the script, so wrap it as { grep -F 'Failed password' "$input" || true; } before the pipeline. Test empty files, files with no matches, malformed lines, and very large inputs.

Safe temporary files and explicit no-match handling prevent both data leaks and false failures. CSV quoting matters because log fields can contain commas.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Which sshd_config setting disables direct root login over SSH?
02What does the auditd rule -w /etc/passwd -p wa -k identity record?
03Why is mktemp preferred over a fixed filename in /tmp?

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Completion is saved in this browser. It records reading and hands-on practice progress.