Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Operations 47 min read

Linux Server Pre-Production Hardening: Baseline Config Without Lockout Risk

This guide details a safe, step-by-step process for initializing and hardening Linux servers (Rocky Linux 9/RHEL 9 and Ubuntu 24.04) before production deployment, covering inventory, hostname/time, patches, admin users, SSH hardening, firewall, SELinux/AppArmor, sysctl, service reduction, filesystem mounts, audit/logging, and a read-only validation script, emphasizing verification at each step to avoid lockout.

Overview

The article presents a practical, ordered checklist for taking a fresh Linux server from OS install to production-ready state. The core principle: inventory first, then change one thing at a time, verify immediately, keep a fallback session, and finally run a read-only acceptance script. The guide assumes Rocky Linux 9 / RHEL 9 or Ubuntu 24.04 LTS, headless, SSH-managed, with out-of-band console (IPMI/iDRAC/VNC) available. It does not cover compliance certifications (e.g., PCI DSS) but provides a technical baseline.

1. Before You Start: Avoid Locking Yourself Out

The biggest risk is losing SSH access. Confirm three things:

Out-of-band console works – know the local credentials.

Keep an existing SSH session open – test changes in a new session.

Change only one category at a time – e.g., SSH then firewall, so you know what broke.

The overall sequence:

inventory (read-only)
     |
hostname / time / repo / patch
     |
admin user + sudo  --> test in new session
     |
sshd hardening     --> sshd -t, test in new session
     |
firewall           --> keep old session, test
     |
SELinux/AppArmor, sysctl, services, mounts
     |
audit + journald
     |
acceptance script (read-only)

2. Read-Only Inventory: Record Current State

Before any changes, capture a baseline. Save key outputs to ~/baseline/ for later comparison.

# System & kernel
cat /etc/os-release
uname -r
hostnamectl

# Time
timedatectl

# Accounts: users with login shells, UID 0 users
awk -F: '$7 !~ /(nologin|false)$/ {print $1, $3, $7}' /etc/passwd
awk -F: '$3 == 0 {print $1}' /etc/passwd

# sudo rules
ls -l /etc/sudoers.d/

# SSH effective config (not just file content)
sudo sshd -T | grep -Ei 'permitrootlogin|passwordauthentication|pubkeyauthentication|^port '

# Listening ports
sudo ss -tulpn

# Running & enabled services
systemctl list-units --type=service --state=running
systemctl list-unit-files --state=enabled

# Firewall
sudo firewall-cmd --state 2>/dev/null   # RHEL
sudo ufw status verbose 2>/dev/null     # Ubuntu

# MAC
getenforce 2>/dev/null                  # RHEL
sudo aa-status 2>/dev/null | head       # Ubuntu

# Disks & mounts
lsblk -f
df -hT

Save critical outputs:

mkdir -p ~/baseline
sudo sshd -T > ~/baseline/sshd-T.before.txt
sudo ss -tulpn > ~/baseline/ss.before.txt
systemctl list-unit-files --state=enabled > ~/baseline/enabled.before.txt
sysctl -a 2>/dev/null > ~/baseline/sysctl.before.txt

Three things to scrutinize: sshd -T shows the actual effective config after all includes; sshd_config.d/ fragments can override the main file. ss -tulpn ports on 0.0.0.0 or [::] are exposed – each must be justified.

Only root should have UID 0.

3. Hostname, Timezone & Time Sync

These affect log correlation, TLS, Kerberos.

# Set hostname (immediate & persistent)
sudo hostnamectl set-hostname app01.example.com

# Timezone – cluster-wide consistency (UTC or local)
sudo timedatectl set-timezone Asia/Shanghai

Verify sync:

timedatectl | grep -i synchronized
systemctl status chronyd chrony systemd-timesyncd 2>/dev/null | grep -E 'Loaded|Active'
chronyc sources -v 2>/dev/null

Look for System clock synchronized: yes and a * source in chronyc sources.

4. Repositories & Patches

Patch before other changes; updates may replace config files.

RHEL family

# Read-only: list updates, especially security
sudo dnf check-update
sudo dnf updateinfo list --security

# Apply all updates
sudo dnf upgrade --refresh -y

Ubuntu

# Read-only
sudo apt update
apt list --upgradable

# Apply
sudo apt full-upgrade -y

Key notes:

Kernel updates require reboot. Check with dnf needs-restarting -r (RHEL) or /var/run/reboot-required (Ubuntu). Reboot proactively before production.

Verify repo sources: dnf repolist or apt-cache policy; remove unknown third-party repos.

Automatic updates ( dnf-automatic, unattended-upgrades) should be a conscious policy decision, not an accident.

5. Admin User & sudo

Principle: no direct root login; each admin has a personal account, uses sudo for privilege escalation – provides audit trail.

Create admin user

# RHEL (wheel group)
sudo useradd -m -G wheel opsadmin

# Ubuntu (sudo group)
sudo useradd -m -s /bin/bash -G sudo opsadmin

# Set password (for console & sudo)
sudo passwd opsadmin

Deploy SSH public key

sudo install -d -m 700 -o opsadmin -g opsadmin /home/opsadmin/.ssh
# Replace with real public key
echo 'ssh-ed25519 AAAA...example [email protected]' | \
  sudo tee /home/opsadmin/.ssh/authorized_keys >/dev/null
sudo chown opsadmin:opsadmin /home/opsadmin/.ssh/authorized_keys
sudo chmod 600 /home/opsadmin/.ssh/authorized_keys

Permissions are critical: StrictModes (default on) rejects keys if .ssh or authorized_keys are group/other writable. On RHEL with SELinux, wrong context causes same symptom; fix with sudo restorecon -Rv /home/opsadmin/.ssh.

Immediately test in a new terminal:

ssh [email protected]
sudo -v && echo SUDO_OK

Only proceed after public-key login and sudo work.

sudo rules

Place custom rules in /etc/sudoers.d/ (e.g., 90-ops), never edit /etc/sudoers directly. Always use visudo for editing and validation:

sudo visudo -f /etc/sudoers.d/90-ops
sudo visudo -c   # full syntax check

A syntax error disables sudo entirely; if root SSH is also disabled, you need console access. NOPASSWD depends on automation needs – human accounts should require password; automation accounts get restricted command lists.

6. SSH Hardening: Order Matters More Than Parameters

Understand config loading

Both distros include Include /etc/ssh/sshd_config.d/*.conf early in sshd_config. OpenSSH uses first-match-wins for most parameters; fragments load in filename order.

Consequences:

A PasswordAuthentication no at the end of sshd_config may be ignored if a fragment earlier sets yes (common in cloud images via cloud-init).

Best practice: create a fragment named to sort first, e.g., 00-baseline.conf, and always verify with sshd -T.

Inspect existing fragments

ls -l /etc/ssh/sshd_config.d/
sudo grep -RHiE 'passwordauth|permitroot|pubkey|kbdinter' \
  /etc/ssh/sshd_config /etc/ssh/sshd_config.d/

Baseline fragment

# /etc/ssh/sshd_config.d/00-baseline.conf
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
AllowGroups wheel sudo

Per-parameter rationale: PermitRootLogin no – upstream default is prohibit-password (allow root with key); no is stricter. Risk: if root is your only account, you lock yourself out. PasswordAuthentication no + KbdInteractiveAuthentication no – both must be off; PAM keyboard-interactive can bypass the first. Older name: ChallengeResponseAuthentication – check man sshd_config. MaxAuthTries 3 – each key tried counts; with many keys in ssh-agent you may hit Too many authentication failures. Client fix: -o IdentitiesOnly=yes -i key_path. AllowGroups wheel sudo – only members of these groups can log in. High lockout risk: if your admin user isn’t in either group, nobody gets in. RHEL lacks sudo group, Ubuntu lacks wheel; both listed for cross-distro fragment. Verify with id opsadmin before enabling. If unsure, omit this line initially.

Changing port is not a real security control; it adds SELinux/firewalld complexity and on newer Ubuntu may require editing ssh.socket instead of sshd_config.

Validate, reload, verify

# 1. Syntax check
sudo sshd -t && echo SYNTAX_OK

# 2. Check effective values
sudo sshd -T | grep -Ei 'permitrootlogin|passwordauthentication|kbdinteractive|allowgroups'

Expected output:

SYNTAX_OK
permitrootlogin no
passwordauthentication no
kbdinteractiveauthentication no
allowgroups wheel
allowgroups sudo

Reload without dropping existing sessions:

# RHEL
sudo systemctl reload sshd
# Ubuntu (service name is ssh)
sudo systemctl reload ssh

Keep old session; in a new terminal verify:

# Should succeed
ssh [email protected] 'sudo -v && echo OK'
# Should be rejected
ssh [email protected]
# Should be rejected (force password)
ssh -o PubkeyAuthentication=no [email protected]

All three as expected → close old session.

Rollback

If new session fails, in old session:

sudo mv /etc/ssh/sshd_config.d/00-baseline.conf /root/
sudo sshd -t && sudo systemctl reload sshd   # Ubuntu: ssh

If old session also dead, use out-of-band console.

7. Firewall: Default-Deny Inbound, Allow Only Needed

Principle: inbound default deny, explicit allow; outbound usually unrestricted unless egress control required.

RHEL: firewalld

Check default zone & current rules:

sudo firewall-cmd --get-default-zone
sudo firewall-cmd --list-all

firewalld has runtime and permanent configs. Safe workflow: modify runtime, test, then persist . Mistake? firewall-cmd --reload or reboot reverts to permanent.

# Runtime: allow business port, remove unneeded service
sudo firewall-cmd --add-port=8080/tcp
sudo firewall-cmd --remove-service=cockpit

# Test SSH & business port from new session
# If OK, persist
sudo firewall-cmd --runtime-to-permanent

Restrict SSH to a CIDR (high risk – test in runtime first):

sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.0.2.0/24" service name="ssh" accept'
sudo firewall-cmd --remove-service=ssh
# Test from 192.0.2.0/24, then --runtime-to-permanent

Ubuntu: ufw

ufw disabled by default. Must allow SSH before enabling or current session may drop:

sudo ufw status verbose          # read-only
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH           # or ufw allow 22/tcp
sudo ufw allow 8080/tcp
sudo ufw show added              # preview before enable
sudo ufw enable

ufw has no runtime/permanent split; enable is immediate and persistent. Mistake? sudo ufw disable from console or old session.

Docker host caveat

Docker’s -p publishes ports by writing its own firewall rules, which may bypass ufw . On container hosts, scan from outside with nmap -Pn -p- 192.0.2.10 rather than trusting firewall config alone. Kubernetes nodes have distinct port requirements – follow CNI/K8s docs.

8. SELinux & AppArmor: Don’t Disable

RHEL uses SELinux, Ubuntu uses AppArmor. Common mistake: disable on first permission error. That removes a defense-in-depth layer; re-enabling SELinux from disabled requires full relabel (slow, risky).

SELinux (RHEL)

getenforce          # expect Enforcing
sestatus

If “Permission denied” but file perms look right, check SELinux denials:

sudo ausearch -m AVC,USER_AVC -ts recent
# With setroubleshoot-server:
sudo sealert -a /var/log/audit/audit.log

Fix priority:

Wrong file context: restorecon -Rv path; for custom dirs, semanage fcontext then restorecon.

Existing boolean: getsebool -a | grep keyword, then setsebool -P bool on.

Non-standard port: semanage port -a -t type -p tcp port.

Temporary diagnosis: setenforce 0 (Permissive – logs but doesn’t block), reproduce, then setenforce 1. Never set disabled.

AppArmor (Ubuntu)

sudo aa-status

Profiles in enforce mode block violations; denials appear in kernel log:

sudo journalctl -k | grep -i apparmor | grep -i denied

9. Security-Relevant Kernel & Network sysctl

Only security-related params shown; performance tuning referenced elsewhere.

Read current values:

sysctl net.ipv4.ip_forward \
  net.ipv4.conf.all.accept_redirects \
  net.ipv4.conf.all.send_redirects \
  net.ipv4.conf.all.accept_source_route \
  net.ipv4.conf.all.rp_filter \
  net.ipv4.tcp_syncookies \
  kernel.kptr_restrict \
  kernel.dmesg_restrict \
  fs.protected_symlinks fs.protected_hardlinks

Create /etc/sysctl.d/90-security-baseline.conf:

# /etc/sysctl.d/90-security-baseline.conf
# No ICMP redirects – prevent route hijacking
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
# Hosts don’t send redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# No source-routed packets
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Log martian packets
net.ipv4.conf.all.log_martians = 1
# SYN flood protection
net.ipv4.tcp_syncookies = 1
# Restrict kernel address & log exposure
kernel.kptr_restrict = 1
kernel.dmesg_restrict = 1

Critical caveats:

ip_forward – do not blindly set 0. Container hosts, K8s nodes, VPN gateways need forwarding; decide per role.

rp_filter strict (1) breaks asymmetric routing / multi-homed setups. Use loose (2) or per-interface. fs.protected_symlinks / fs.protected_hardlinks usually default to 1 – just verify. kernel.dmesg_restrict = 1 blocks dmesg for non-root; monitoring scripts must use sudo or journald.

Apply & verify:

sudo sysctl --system
sysctl net.ipv4.conf.all.accept_redirects kernel.dmesg_restrict
sysctl --system

loads all sysctl.d directories; later files override earlier. If value wrong, find culprit:

grep -R accept_redirects /etc/sysctl.d /usr/lib/sysctl.d \
  /run/sysctl.d /etc/sysctl.conf 2>/dev/null

Rollback: delete the file; active values persist until reboot or manual sysctl -w using saved sysctl.before.txt.

10. Remove Unneeded Services

Every listening port / persistent service is attack surface. Cross-reference inventory:

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

Decision rule: if you can explain “what it does & who needs it”, keep; else investigate with systemctl status unit → unit file path → rpm -qf path (RHEL) or dpkg -S path (Ubuntu) to find package.

Common candidates to disable (business-dependent): cups (no printing) avahi-daemon (no local service discovery) cockpit.socket (no web console – RHEL) bluetooth (server)

Disable:

sudo systemctl disable --now avahi-daemon.service avahi-daemon.socket

Socket-activated services need both .service and .socket stopped. Uncertain? disable --now first, observe, then consider mask (prevents pull-in) or package removal.

11. Filesystem Mount Options

For writable directories that shouldn’t execute code, add nodev, nosuid, noexec to block “download to temp & execute” attacks. nodev – ignore device files nosuid – ignore setuid/setgid bits noexec – forbid direct execution

Prerequisite: separate mount points. Check:

findmnt /tmp /var/tmp /dev/shm /home
/dev/shm

is always a tmpfs; add to /etc/fstab:

tmpfs  /dev/shm  tmpfs  defaults,nodev,nosuid,noexec  0 0
/tmp

independence varies; can use systemd’s tmp.mount to make it tmpfs (consumes RAM, clears on reboot) – verify no app relies on persistent /tmp data.

noexec side-effect: installers, package scripts, JIT compilers write executables to temp dirs and run them; noexec causes Permission denied. Workaround: mount -o remount,exec /tmp temporarily; long-term: set TMPDIR to an exec-allowed location.

Before editing fstab:

sudo cp -a /etc/fstab /etc/fstab.bak.$(date +%F)
sudo vi /etc/fstab
sudo findmnt --verify          # syntax & device check
sudo systemctl daemon-reload
sudo mount -o remount /dev/shm
findmnt /dev/shm               # confirm options

Bad fstab = emergency mode on boot; findmnt --verify catches most errors pre-reboot.

12. Auditing & Logging

journald persistence

Storage=auto

(default) writes to disk only if /var/log/journal exists; otherwise logs stay in /run/log/journal (memory) and are lost on reboot . Common post-incident surprise: no pre-reboot logs.

Check:

ls -ld /var/log/journal 2>/dev/null || echo NOT_PERSISTENT
journalctl --list-boots | tail -3

Multiple boots listed = persistent. If not, configure:

# /etc/systemd/journald.conf.d/90-baseline.conf
[Journal]
Storage=persistent
SystemMaxUse=2G
SystemMaxUse

caps disk usage; tune after observing journalctl --disk-usage.

Apply:

sudo systemctl restart systemd-journald
journalctl --disk-usage

auditd

Records kernel-level security events (logins, sudo, file changes). RHEL installs & enables by default; Ubuntu may need sudo apt install auditd.

systemctl is-active auditd
sudo auditctl -s   # status
sudo auditctl -l   # loaded rules

Rules in /etc/audit/rules.d/, merged by augenrules. Minimal starter set (monitor identity/privilege files):

# /etc/audit/rules.d/50-baseline.rules
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/sudoers -p wa -k privilege
-w /etc/sudoers.d/ -p wa -k privilege
-w /etc/ssh/sshd_config -p wa -k sshd
-w /etc/ssh/sshd_config.d/ -p wa -k sshd
-w

watch path, -p wa watch write & attribute change, -k key for search. Load & test:

sudo augenrules --check
sudo augenrules --load
sudo auditctl -l | grep -E 'identity|privilege|sshd'

# Trigger & verify
sudo touch /etc/sudoers.d
sudo ausearch -k privilege -ts recent

Notes: -e 2 (immutable config) requires reboot to change rules – omit during initial setup.

Overly broad rules (e.g., all syscalls) flood logs & hurt performance; expand incrementally. Reference distro-provided examples: rpm -ql audit | grep rules or dpkg -L auditd | grep rules.

Central log collection (rsyslog, Loki, ELK) is a next step, not covered here.

13. Acceptance: Read-Only Validation Script

After all changes, run a script that only checks , outputs PASS/WARN/FAIL, exits 0 if no FAIL – suitable for CI/CD gate.

Script highlights (full script in article):

Requires admin username argument – avoids false “all pass” on empty check.

Checks: admin user exists + authorized_keys; only root UID 0; sshd -T syntax & key params (PermitRootLogin no, PasswordAuthentication no, etc.); visudo -c; firewall active (firewalld/ufw); SELinux Enforcing or AppArmor enabled; time synchronized; /var/log/journal exists; auditd active; security sysctl values; /dev/shm mount options; lists listening sockets for manual review.

FAIL = baseline gap, must fix before production; WARN = role-dependent (e.g., container host network params).

Example output snippet:

PASS  user opsadmin exists
PASS  authorized_keys present
PASS  only root has uid 0
PASS  sshd config syntax ok
PASS  PermitRootLogin no
PASS  PasswordAuthentication no
...
WARN  /dev/shm missing noexec
---- listening sockets (review manually) ----
tcp 0.0.0.0:22 users:(("sshd",...))
...
FAIL count: 0

14. Common Lockout / Failure Scenarios & Fixes

SSH – nobody can log in

AllowGroups

/ AllowUsers missing your account.

Key file permissions/ownership wrong – rejected by StrictModes.

RHEL: .ssh SELinux context wrong.

Disabled password auth but key never deployed.

Diagnose: old session or console → journalctl -u sshd -n 50 (RHEL) or journalctl -u ssh -n 50 (Ubuntu). Client ssh -vvv shows offered auth methods & key rejections.

PasswordAuthentication not taking effect

Almost always a fragment in sshd_config.d/ set it first. Use sshd -T to see final value, grep -R to locate conflicting fragment.

sudo breaks

Syntax error in sudoers. If root session exists: visudo -c to find bad file, fix. Else console/rescue mode. Why visudo is mandatory.

Firewall enable cuts access

ufw: enabled before allowing SSH. Fix: console → ufw disable. firewalld: removed ssh service; if only runtime changed, firewall-cmd --reload reverts; if persisted, manually re-add ssh service.

Boot into emergency mode

Typically bad fstab. In emergency shell:

mount -o remount,rw /
cp -a /etc/fstab.bak.YYYY-MM-DD /etc/fstab
systemctl daemon-reload
reboot

SELinux permission denied

Don’t disable. ausearch -m AVC -ts recent, then fix context/boolean/port label per section 8.

15. Production Go-Live Checklist

Inventory archived; pre/post sshd -T, ss -tulpn comparable.

Hostname per naming standard; timezone cluster-consistent; time synced.

Patches applied; reboot-if-needed done & verified clean boot.

Each admin has personal account + key; sudo works; visudo -c passes. sshd -T shows root login & password auth disabled; new session test passes.

Firewall enabled; inbound only explicit ports; external scan matches expectation.

SELinux Enforcing or AppArmor active.

Security sysctl set per role.

Unneeded services stopped; every listening port explained. /dev/shm etc. have proper mount options; findmnt --verify passes.

journald persistent; auditd running with base rules loaded.

Validation script: zero FAIL; every WARN has documented human decision.

Baseline is not one-off: codify config fragments in Ansible (or similar), run validation script in pipeline, schedule periodic re-runs to detect drift.

References

OpenSSH sshd_config manual: https://man.openbsd.org/sshd_config RHEL 9 Security Hardening:

https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/security_hardening/index

RHEL 9 Using SELinux:

https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/using_selinux/index

RHEL 9 Configuring firewalls:

https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/configuring_firewalls_and_packet_filters/index

Ubuntu Server docs (OpenSSH, firewall, AppArmor): https://documentation.ubuntu.com/server/ firewalld docs: https://firewalld.org/documentation/ systemd journald.conf manual:

https://www.freedesktop.org/software/systemd/man/latest/journald.conf.html

Kernel IP sysctl docs: https://docs.kernel.org/networking/ip-sysctl.html Docker packet filtering & firewalls:

https://docs.docker.com/engine/network/packet-filtering-firewalls/

CIS Benchmarks (registration required):

https://www.cisecurity.org/cis-benchmarks
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

OperationsfirewallLinuxsysctlserver-hardeningselinuxsshsecurity-baseline

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion