Skip to content
RankCore.AI
← All posts

Defend Your Linux Server: From Five Incident Checks to a Full Hardening Tutorial

· linux, security, hardening, ssh, devops

The short video above is a 60-second triage: five commands to run when you wonder whether a Linux server is already under attack. They are a good first pass. They are not a defense. This tutorial keeps those checks, tightens a few loose lines in the narration, and then hardens a Debian, Ubuntu, or RHEL-family box: updates, users, SSH, the firewall, fail2ban, unused services, permissions, logging, MAC, sysctl, integrity, scanners, backups, and a short incident-response path.

References: the OpenSSH sshd_config and ssh-keygen manuals, Ubuntu Server and Red Hat documentation, and CIS Benchmarks where a baseline helps. Test every SSH change in a second session before you close the first one.

Related reading: five Linux power commands (rsync, strace), the Linux file system guide, the Nginx six-roles guide if this host terminates HTTP, and the ethical hacking lab for offense only in a lab you own.

The video’s five checks, with official nuance

Run these as a first look, then keep going. They answer “what is happening right now,” not “is this host clean.”

1. who — who is logged in this moment. who (and the fuller w) reads the utmp file and lists users with a current session, including source host or device. An account you do not recognize, or a pts from an IP you did not open, deserves a session hunt: ps -u thatuser, loginctl, and the SSH logs below. who will not show a backdoor that never created a login session.

2. last -a — recent successful logins, with the source at the end. The video’s “last-a” is last -a. The last(1) manual says -a puts the hostname in the last column, which is how you see the IP. This reads wtmp (logins, logouts, reboots) — not failed passwords. Failed attempts live in btmp and show up with sudo lastb (and in journalctl). A 3 a.m. login from a country you do not use is a lead, not a conviction. Empty wtmp after a wipe is itself a lead.

3. sudo ss -tunap — sockets plus the process, when you are allowed to see it. The on-screen command is ss -tunap (TCP, UDP, numeric, all states, process). That is broader than the common listening-only form ss -tulpn (-l = listening). Use -tunap when you also want established connections, as the video says; use -tulpn when you are closing unused listeners. The process column often needs root or CAP_NET_ADMIN/CAP_SYS_PTRACE — that is why the clip prefixes sudo. A port you never opened, or a binary you do not recognize talking outbound, is a red flag. After you install Nginx, 80 and 443 should be among the expected listeners.

4. ps aux --sort=-%cpu | head — the busiest processes, not specifically 15. The official head default is 10 lines, and the first line is the ps header, so a bare head shows nine processes, not “your 15 busiest.” Use an explicit count:

ps aux --sort=-%cpu | head -n 16
# or: ps -eo user,pid,pcpu,pmem,stat,start,cmd --sort=-pcpu | head -n 16

An unknown process pinned at high CPU can be a miner, a stuck backup, or a compile. Investigate with ps and, if needed, strace from the power-commands post. Do not kill PID 1 because it looks busy.

5. SSH logs for the last hour. The narration is “journalctl for the SSH service since one hour ago.” On Debian and Ubuntu the unit is usually ssh.service (with an sshd alias on current releases). On RHEL, Fedora, and most Alma/Rocky systems the unit is sshd.service. Use the name your host actually has:

# Debian / Ubuntu
sudo journalctl -u ssh --since "1 hour ago"
# RHEL family
sudo journalctl -u sshd --since "1 hour ago"

Hundreds of Failed password or Invalid user lines in a short window are a classic password-guessing spray — often because password logins are still on.

The video’s closing warning is the one to take most seriously: if the attacker already has root, they can replace binaries, hook the kernel, and wipe or alter logs. These five commands are first checks, not proof that you are safe. The rest of this article shrinks the chance they get that far.

Standing rule: do not lock yourself out of SSH

Every section that touches sshd or the firewall can drop your only path into a cloud VM. Before you change anything:

  • Keep your current SSH session open until a second session logs in with the new settings.
  • Run sudo sshd -t after every sshd_config edit. Fix syntax before you reload.
  • Reload, do not restart, when you can: sudo systemctl reload ssh (Debian/Ubuntu) or sudo systemctl reload sshd (RHEL). Reload applies the new config to new connections and leaves the existing one up.
  • Allow SSH in the firewall before you enable the firewall.
  • Know how you would use the provider’s serial or console access if a reload goes badly.
  • Prefer drop-in files (/etc/ssh/sshd_config.d/99-hardening.conf) over rewriting the distro file, so a package upgrade does not surprise you.

On a lab VM, snapshot first. On a single production host, typo-resistant changes beat clever ones.

1. Patch, then keep patching

Most mass incidents start with a known CVE, not a novel exploit. On Debian and Ubuntu:

sudo apt update
sudo apt upgrade
sudo apt install --only-upgrade unattended-upgrades apt-listchanges
sudo dpkg-reconfigure -plow unattended-upgrades

Ubuntu’s Server docs recommend unattended-upgrades for unattended security updates. Review /etc/apt/apt.conf.d/50unattended-upgrades and 20auto-upgrades. Leave Automatic-Reboot off until you have a maintenance window.

On RHEL, Alma, Rocky, or Fedora:

sudo dnf upgrade
sudo dnf install dnf-automatic
sudo systemctl enable --now dnf-automatic.timer

Red Hat documents dnf-automatic (and, on older releases, yum-cron) for automatic updates. Choose apply_updates versus download-only in /etc/dnf/automatic.conf deliberately. Kernel updates still need a reboot; needs-restarting -r (from yum-utils / dnf-utils) tells you when.

2. Users, sudo, and least privilege

Create a named admin, give it sudo, and stop living as root. Debian/Ubuntu:

sudo adduser alice
sudo usermod -aG sudo alice

RHEL family (the admin group is wheel):

sudo useradd -m alice
sudo passwd alice
sudo usermod -aG wheel alice
# confirm wheel is enabled in visudo (the default %wheel ALL=(ALL) ALL line)

Log in as alice, prove sudo -l works, then disable remote root (next section). Use visudo only — a broken sudoers file is another lock-out. Prefer group-based sudo over alice ALL=(ALL) NOPASSWD: ALL. If a command must be passwordless, name that command, not the whole world. Remove leftover users with sudo deluser / userdel only after you have checked crontab -u, systemd user units, and lingering processes.

Password quality belongs in PAM (pam_pwquality). That is separate from SSH keys; both matter if a local console or su is possible.

3. SSH hardening: keys, Ed25519, no root, no passwords

Generate a key on your workstation, not on the server:

ssh-keygen -t ed25519 -a 100 -C "alice@workstation"

The OpenSSH ssh-keygen manual documents -t ed25519 and -a as the KDF rounds for the private-key passphrase. Use a passphrase. Install the public key with ssh-copy-id alice@server (while password login still works), then log in with the key in a second window.

A conservative drop-in, after that second login works:

# /etc/ssh/sshd_config.d/99-hardening.conf
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthenticationMethods publickey
MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
DebianBanner no

Official nuances that bite people:

  • Current OpenSSH’s default PermitRootLogin is prohibit-password, not no. Root can still log in with a key until you set no. Older manuals said yes. Distros may override the default; read sshd -T | grep -i permitrootlogin.
  • PasswordAuthentication no is not always enough. If PAM and keyboard-interactive stay on, a password prompt can still appear. Setting KbdInteractiveAuthentication no (the modern name; older configs used ChallengeResponseAuthentication) and, if you want a single door, AuthenticationMethods publickey, closes that gap.
  • Debian/Ubuntu reload ssh; RHEL reloads sshd. Always sshd -t first, then reload, then test a new login before you disconnect.

Do not treat a non-default port as your only control. If you do change it, allow the new port in the firewall first — the OpenSSH / ssh service definitions expect 22.

4. Firewall: UFW, firewalld, or nftables

A firewall’s job is default-deny inbound, allow only what you intend, and allow the SSH path first.

Ubuntu and Debian, with UFW (a frontend over nftables or iptables, depending on the release):

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
# if this host serves HTTP(S), as in the Nginx guide:
# sudo ufw allow 80/tcp
# sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

If you skip ufw allow OpenSSH (or 22/tcp) and then ufw enable, you can drop yourself. ufw will warn; take the warning seriously.

RHEL family, with firewalld (also a frontend over nftables):

sudo firewall-cmd --permanent --add-service=ssh
# sudo firewall-cmd --permanent --add-service=http
# sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

Direct nft rules are fine if you already manage /etc/nftables.conf. Do not run UFW, firewalld, and handwritten nftables at once — they will fight. Cloud security groups are a second filter, not a substitute.

5. fail2ban (and what it is not)

fail2ban reads logs, and bans repeat offenders at the firewall for a time. It slows password-guessing; it does not replace key-only SSH.

# Debian / Ubuntu
sudo apt install fail2ban
# RHEL family (often from EPEL)
sudo dnf install epel-release
sudo dnf install fail2ban

Create /etc/fail2ban/jail.local so package updates do not clobber you:

[sshd]
enabled = true
backend = auto
maxretry = 5
findtime = 10m
bantime = 1h

Then sudo systemctl enable --now fail2ban and sudo fail2ban-client status sshd. Jail names and log paths vary by release — trust fail2ban-client for that host. Whitelist your jump host with ignoreip if a flaky link could ban you. fail2ban is not an IDS; the real fix is PasswordAuthentication no.

6. Close unused services

List what is listening, then what is enabled:

sudo ss -tulpn
systemctl list-unit-files --state=enabled
systemctl list-units --type=service --state=running

Disable only what you have identified: sudo systemctl disable --now cups.service is a reasonable example on a headless VM that will never print; it is a disaster if you disable sshd, systemd-networkd, or your cloud agent. When a package is truly unused, uninstall it (apt purge / dnf remove) so it does not return on the next enablement binge. Re-check ss -tulpn after each change.

7. File permissions and a SUID audit

SSH private keys must be 600 and ~/.ssh must be 700. World-writable web roots and 0777 upload directories are how web bugs become system bugs.

sudo find / -xdev -perm /4000 -type f 2>/dev/null | sort
sudo find / -xdev -perm /2000 -type f 2>/dev/null | sort
sudo find / -xdev -perm -0002 -type d 2>/dev/null | sort

-xdev stays on one filesystem so you do not walk /proc and network mounts. SUID on the stock passwd, sudo, and su binaries is expected. SUID on a binary under /tmp, a user’s home, or a long-forgotten admin tool is not. Compare the list to a fresh install or to your AIDE baseline (below) instead of deleting files you do not recognize in the middle of an incident.

8. journald and auditd

journalctl only helps if logs persist and rotate sanely. In /etc/systemd/journald.conf (or a drop-in):

[Journal]
Storage=persistent
SystemMaxUse=500M
ForwardToSyslog=no

Then sudo mkdir -p /var/log/journal && sudo systemctl restart systemd-journald. Persistent storage survives reboot; /run/log/journal does not.

For a real audit trail of syscalls and policy, install the Linux Audit daemon:

# Debian / Ubuntu
sudo apt install auditd audispd-plugins
# RHEL family (often already present)
sudo dnf install audit
sudo systemctl enable --now auditd
sudo auditctl -l
ausearch -m USER_LOGIN -ts recent

Red Hat’s audit docs are the best map for rules in /etc/audit/rules.d/. Start with identity, privileged commands, and changes to /etc/ssh, /etc/passwd, and /etc/sudoers. Measure load before you paste a huge rule set.

9. AppArmor or SELinux — leave it on

Ubuntu and Debian ship AppArmor; RHEL, Fedora, Alma, and Rocky ship SELinux. These are mandatory access controls. They are not interchangeable, and “turning it off to make the app work” is a common way to undo the distro’s hardest default.

# AppArmor (Ubuntu / Debian)
sudo aa-status
# SELinux (RHEL family)
getenforce
sestatus

getenforce should say Enforcing on a RHEL-style server that was installed in the default target. If a service fails, use ausearch / audit2allow or aa-logprof to write a tight exception, not SELINUX=disabled in /etc/selinux/config and a reboot. Disabled SELinux stays disabled after you forget why you did it.

10. Kernel hardening with sysctl

Put durable settings in /etc/sysctl.d/99-hardening.conf, then sudo sysctl --system. A conservative, generally safe starting point for a single-host server that is not a router, Kubernetes node, or container engine host:

net.ipv4.ip_forward = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.rp_filter = 1
net.ipv4.tcp_syncookies = 1
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1
kernel.unprivileged_bpf_disabled = 1
fs.protected_hardlinks = 1
fs.protected_symlinks = 1

Nuance: ip_forward=0 will break a host that must route, NAT, or run some CNI plugins. rp_filter=1 can surprise asymmetric routing. CIS and vendor guides go further (ASLR, unprivileged_userdir, IPv6 RA, and more); apply those only if they match how the machine is used, and keep a console session while you test.

11. Integrity with AIDE

AIDE (Advanced Intrusion Detection Environment) checksums the files you tell it to, then reports drift. Official packages:

# Debian / Ubuntu
sudo apt install aide aide-common
sudo aideinit
# RHEL family
sudo dnf install aide
sudo aide --init
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

Run sudo aide --check (or aide.wrapper) on a schedule and ship the result to mail or your log pipeline. Rebuild the database only after a deliberate, reviewed change. AIDE will not catch an attacker who is already in at the moment of aideinit, and it will not watch a directory you omitted from the config. It is a baseline, not a time machine.

12. Lynis and rkhunter: scanners, not guardians

sudo apt install lynis rkhunter    # or: sudo dnf install lynis rkhunter
sudo lynis audit system
sudo rkhunter --update
sudo rkhunter --check

Lynis is a host auditor: it walks configuration and prints a hardening report with suggestions. It is not a CIS Benchmark run by itself, but many findings overlap with CIS and vendor guides — treat the report as a work queue, not a score to game. rkhunter looks for known rootkit fingerprints and suspicious properties. It produces false positives, especially right after a kernel or glibc upgrade; official advice is to inspect, then rkhunter --propupd only when you understand the change. Neither tool is a substitute for patching, SSH key-only access, or AIDE.

13. Backups you have actually restored

A hardened host that cannot be rebuilt is still fragile. Use rsync for a simple tree, or Borg / restic for encrypted, versioned backups, and keep at least one copy off the server (the usual 3-2-1 idea: three copies, two media, one off-site). The power-commands article shows rsync flags worth using (-a, --delete only when you mean it). Encrypt the remote copy. Test a restore onto a throwaway VM on a schedule — an untested backup is a rumor. Include /etc, the AIDE database, SSH host keys only if you have a plan for key reuse, and the data your application actually needs.

14. Incident-response basics

When the five commands, fail2ban, or a user report says something is wrong:

  1. Do not panic-reboot. You will lose memory-resident tools and volatile sockets.
  2. Preserve a copy. Snapshot the VM, or copy journalctl, ps, ss, last, and relevant files to a write-once location you trust.
  3. Contain. Tighten the firewall or security group to known admin IPs; if you must isolate, do it from the console so you do not cut your own session mid-collection.
  4. Identify. Re-run the five checks, lynis / AIDE against the last known-good database, and package verification (dpkg -V, rpm -Va). Assume user-space tools can lie if root is gone; a live image or provider snapshot reviewed offline is more honest.
  5. Eradicate and recover. Rotate keys and passwords, rebuild from known-good images when you cannot trust the host, restore data from backups, and patch the hole that let them in (often a weak SSH setting, an unpatched service, or a web app).
  6. Write down what you did. Times, commands, IPs. Future you, and anyone you hire, will need it.

On a customer or production system, follow your legal and notification process before you wipe anything.

A practical checklist

  • apt / dnf current; unattended security updates or dnf-automatic configured on purpose
  • Named sudo user; no daily root SSH; sudo -l proven
  • Ed25519 (or another modern) key; sshd -t clean; PermitRootLogin no; password and keyboard-interactive SSH off; a second session works
  • Firewall default-deny inbound; SSH allowed before enable; only the ports you serve (80/443 if Nginx is intentional)
  • fail2ban on sshd, or an equivalent control, with your jump host not banned
  • ss -tulpn reviewed; unused units disabled or removed
  • Home and ~/.ssh modes correct; SUID list understood
  • Persistent journald; auditd running with a small, deliberate rule set
  • AppArmor running, or SELinux Enforcing — not disabled
  • sysctl drop-in applied and compatible with the host’s role
  • AIDE baseline built on a trusted day; scheduled --check
  • Lynis report filed as tickets, not wallpaper
  • Backup restored once on a spare host
  • Console / serial access documented for the day SSH goes wrong

Recap

The video is a pocket card: who, last -a, sudo ss -tunap, ps aux --sort=-%cpu | head, and journalctl -u ssh since one hour ago. Use it when something feels wrong. Remember that last is not failed logins, that head is ten lines unless you say otherwise, and that the SSH unit name differs on RHEL. Then do the slower work in this article so those checks stay boring.

Six jobs, one habit: patch, least privilege, key-only SSH, a default-deny firewall, visibility (logs, AIDE, Lynis), and backups you have restored. Follow @rankcore.ai, and read more on blog.rankcore.ai.

Want to go deeper?

Our step-by-step video courses turn these ideas into results.

See courses

Comments

Sign in or create a free account to join the discussion.

No comments yet — be the first.