How to Defend Linux Against Common Attacks

⚠️ Safety & Ethics

This post is focused on defense — how to secure Linux systems against the techniques we covered earlier in this series. Use these recommendations to harden lab and production systems, build detections, and reduce attacker opportunity.

🧭 Defense strategy overview

Defending Linux effectively means combining:

  1. Preventive hardening — reduce attack surface and misconfigurations.

  2. Detective controls — log, monitor, and alert on suspicious activity.

  3. Reactive playbooks — have procedures to investigate and remediate incidents.

Below are concrete, prioritized steps with commands, config snippets, and checklists.

— Secure SSH: harden remote access

SSH is the #1 target. Lock it down.

Key recommendations

  • Disable password auth; enforce key-based auth.

  • Disable root login via SSH.

  • Change default port only as security-through-obscurity (not primary defense).

  • Rate-limit/ban brute-force attempts (fail2ban).

  • Use strong key types (ed25519) and disable weak ciphers.

  • Enforce 2FA (Google Authenticator / privacyIDEA) for interactive logins if possible.

Example /etc/ssh/sshd_config snippet

				
					Port 2222
PermitRootLogin no
PasswordAuthentication no
ChallengeResponseAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PermitEmptyPasswords no
AllowUsers alice bob
# Ciphers / Kex / MACs: use vendor-recommended secure lists

				
			

Commands / steps

				
					# restart sshd after changes
sudo systemctl restart sshd

# check sshd config syntax safely
sudo sshd -t

# install fail2ban (Debian/Ubuntu)
sudo apt update && sudo apt install -y fail2ban
# enable a basic jail for ssh
sudo systemctl enable --now fail2ban

				
			

— Least Privilege & Sudo hardening

Sudo is powerful — minimize blast radius.

Best practices

  • Avoid NOPASSWD in sudoers.

  • Use visudo and sudoers.d for controlled rules.

  • Prefer specific command entries over ALL.

  • Audit sudo usage and log all sudo activity to centralized logs.

Example sudoers rule

				
					%pentesters ALL=(ALL) /usr/bin/systemctl, /usr/bin/journalctl

				
			

Audit Commands

				
					# list sudoers and included files
sudo cat /etc/sudoers
ls -la /etc/sudoers.d

# review sudo logs (journalctl on modern systems)
sudo journalctl _COMM=sudo --since "24 hours ago"

				
			

— File system hardening & permissions

Fix weak permissions and control special bits.

Rules of thumb

  • Avoid chmod 777 except for intentionally shared, controlled directories.

  • Limit SUID/SGID to only required binaries; remove SUID from unnecessary files.

  • Use noexec, nosuid, nodev mount options for /tmp and other writable mounts.

  • Use umask & ACLs for finer-grained defaults.

Useful commands

				
					# find world-writable dirs
find / -xdev -type d -perm -0002 -print 2>/dev/null

# find SUID/SGID files
find / -xdev \( -perm -4000 -o -perm -2000 \) -type f -print 2>/dev/null

# set secure permissions on private keys
chmod 600 ~/.ssh/id_rsa
chown root:root /etc/shadow

				
			

/etc/fstab example for /tmp

				
					tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev,mode=1777 0 0

				
			

— Secure services & reduce attack surface

Minimize running services and expose only what’s necessary.

Steps

  • Audit active services: ss -tulwn / systemctl list-units --type=service

  • Disable unused services: sudo systemctl disable --now <service>

  • Harden commonly exposed services (web, DB, SSH) with minimal privileges and restrictive configs.

  • Use firewalls: ufw (simple) or nftables/iptables for more control.

Firewall basics with UFW

				
					sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 2222/tcp    # if SSH on 2222
sudo ufw enable
sudo ufw status verbose

				
			

— Container & Docker security

Containers introduce specific risks — apply strict controls.

Controls

  • Avoid adding users to docker group unless trusted.

  • Run containers with least privileges: --cap-drop ALL --cap-add as needed.

  • Use read-only filesystems: --read-only.

  • Do not bind mount sensitive host paths (/var/run/docker.sock, /etc) unless required and understood.

  • Use image scanning for vulnerabilities and minimal base images.

Example docker run

				
					docker run --rm --read-only --cap-drop ALL --network none myimage

				
			

— Patch management & package hygiene

Keep kernels and packages updated, but test in controlled windows.

Steps

  • Subscribe to vendor security advisories.

  • Use automated patching for non-critical systems; schedule maintenance windows for infra.

  • For critical systems, test patches in staging before production.

Commands (Debian/Ubuntu)

				
					sudo apt update && sudo apt upgrade -y
# list packages with available updates
apt list --upgradable

				
			

— Monitoring & detection (log aggregation + alerts)

You can’t defend what you don’t see.

Core telemetry to collect

  • Authentication logs (/var/log/auth.log, /var/log/secure)

  • Sudo and shell command logs

  • Systemd/journal logs

  • File integrity alerts (AIDE/Tripwire)

  • Network flow logs (Zeek, Suricata)

  • Process creation and unusual sockets

Tools

  • Auditd: kernel-level syscall auditing (watch file accesses, execve events).

  • Osquery: query system state and schedule checks.

  • AIDE/Tripwire: file integrity monitoring.

  • ELK/Graylog or Splunk: centralized logging & alerting.

  • Security Onion / Suricata / Zeek: network IDS and packet analytics.

Example auditd rule (watch sudoers)

Create /etc/audit/rules.d/10-sudo.rules:

				
					-w /etc/sudoers -p wa -k sudoers_change
-w /etc/sudoers.d/ -p wa -k sudoers_change

				
			

Reload rules:

				
					sudo augenrules --load
sudo systemctl restart auditd

				
			

— Automated baseline scans & periodic audits

Schedule regular checks to detect drift and regressions.

Recommended scans

  • Weekly permission audits (SUID, world-writable)

  • Daily failed auth attempts summary

  • Monthly package vuln scans (e.g., lynis, debsecan, oscap)

  • Continuous file integrity monitoring

Example cron job (weekly permission scan)

				
					# /etc/cron.weekly/permission_audit
#!/bin/bash
OUT=/var/log/permission_audit_$(date +%F).log
find / -xdev \( -perm -4000 -o -perm -2000 \) -type f > "$OUT" 2>/dev/null
find / -xdev -type d -perm -0002 >> "$OUT" 2>/dev/null
gzip "$OUT"

				
			

— Incident response & playbooks

Have simple, tested playbooks for common incidents.

Example playbook skeleton

  1. Detect — alert triggered (failed sudo spike, new SUID added).

  2. Triage — gather host info: whoami, id, ps aux, ss -tulwn, /var/log/auth.log tail.

  3. Isolate — remove network-facing interface or firewall block (if containment needed).

  4. Preserve — snapshot VM or collect forensic artifacts (logs, memory) — do not re-run destructive commands.

  5. Remediate — remove malicious persistence, rotate creds, patch vuln.

  6. Recover — rebuild from clean image if needed.

  7. Review — post-incident review and improve detection.

— Developer & deployment practices

Security starts with development and deployment pipelines.

  • Use CI/CD gates with security scans (SAST/DAST).

  • Avoid committing secrets to repos; use vaults (HashiCorp Vault, AWS Secrets Manager).

  • Harden containers and avoid running as root inside container.

  • Use least-privilege IAM roles for cloud services.

🧪 Practical checklist (copy-paste for ops)

  • SSH: disable password auth, disable root login, enable fail2ban.

  • Sudo: remove NOPASSWD, audit sudoers.d.

  • Permissions: remove 777, audit SUIDs, secure sensitive files.

  • Services: stop unused, enable firewall, restrict exposure.

  • Containers: avoid docker group for untrusted users; use minimal images.

  • Patching: schedule and test updates; patch kernel promptly.

  • Monitoring: deploy auditd/osquery, forward logs to SIEM.

  • Backups: test restores and protect backup files.

  • Incident playbook: document, test, and train.

  • Least privilege: users, services, keys.

🧪 Lab exercises (apply defenses in your lab)

  • Harden SSH on your attacker VM (or a dedicated management VM) and test connections. Monitor logs for failed auth.

  • Sudo audit: add a narrow sudoers rule for a test user and verify sudo logs and sudo -l.

  • Filesystem audit: run SUID/world-writable searches before and after hardening; document changes.

  • Deploy auditd and create rules to watch /etc/sudoers and /etc/ssh/sshd_config. Trigger a change and confirm alerts.

  • Container practice: run a container with --read-only and try writing to filesystem; validate expected failures.

🎯 Coming Up Next

Part 14: Ethics, Reporting, and the Hacker Mindset — how to responsibly disclose vulnerabilities, write professional reports, and build a sustainable, ethical career in security.

💬 Got Questions?

Drop them in the comments or join our community on Discord for exclusive hacking tips and resources.


Don’t worry — mastery comes with practice.
Just open your terminal and hack your brain into CLI mode daily.

Let’s keep building. 💻⚔️

Leave a comment

Index