Linux Security Fundamentals

Level: Intermediate Module: Security & Authentication 10 min read Lesson 46 of 66

Overview

  • What you will learn: Core security principles including defense in depth, least privilege, attack surface reduction, automatic security updates, system auditing with auditd, PAM configuration, sudo hardening, file integrity monitoring with AIDE, and CIS security benchmarks.
  • Prerequisites: Module 1 (Linux Fundamentals), basic familiarity with systemd and package management
  • Estimated reading time: 25 minutes

Introduction

Security is not a single product or configuration — it is a continuous process that spans every layer of a system. A well-secured Linux server combines multiple overlapping controls so that the failure of any one mechanism does not compromise the entire system. This principle is known as defense in depth.

In this lesson we explore the foundational security concepts that every Linux administrator must understand. We begin with guiding principles, then move into practical tools and configurations available on Ubuntu Server: automatic security patching, kernel-level audit logging, Pluggable Authentication Modules (PAM), sudo hardening, file integrity checking, and industry benchmarks published by the Center for Internet Security (CIS).

By the end of this lesson you will be able to assess a server’s security posture, apply baseline hardening steps, and set up ongoing monitoring to detect unauthorized changes.

Security Principles

Defense in Depth

Defense in depth means layering multiple security controls so that an attacker must defeat several independent mechanisms to reach a target. Layers typically include network firewalls, host firewalls, mandatory access controls, application-level authentication, and encrypted transport.

Principle of Least Privilege

Every user, process, and service should operate with the minimum set of permissions required to complete its task. A web server, for example, should not run as root; it should run under a dedicated service account with access only to its document root and log directory.

# Check which processes run as root
$ ps aux | awk '$1 == "root"' | head -20

# Identify SUID binaries — potential privilege escalation vectors
$ find / -perm -4000 -type f 2>/dev/null

Attack Surface Reduction

Remove or disable anything that is not strictly necessary. Every open port, every installed package, and every running service is a potential entry point for an attacker.

# List listening ports
$ ss -tulnp

# Remove unnecessary packages
$ sudo apt purge telnetd rsh-server

# Disable an unused service
$ sudo systemctl disable --now cups

Automatic Security Updates

Ubuntu provides the unattended-upgrades package to automatically install security patches. On Ubuntu Server it is usually installed by default, but it is important to verify and tune its configuration.

# Install if not present
$ sudo apt install unattended-upgrades

# Enable automatic updates interactively
$ sudo dpkg-reconfigure -plow unattended-upgrades

Configuration Files

# /etc/apt/apt.conf.d/50unattended-upgrades
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-security";
    "${distro_id}ESMApps:${distro_codename}-apps-security";
};
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Mail "admin@example.com";

# /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

If a kernel update requires a reboot, consider using Automatic-Reboot with a maintenance window, or use Canonical Livepatch to apply critical kernel fixes without rebooting.

# Check unattended-upgrades log
$ sudo cat /var/log/unattended-upgrades/unattended-upgrades.log

# Dry run
$ sudo unattended-upgrade --dry-run --debug

System Auditing with auditd

The Linux Audit Framework provides comprehensive logging of security-relevant events at the kernel level. It records system calls, file access, user authentication events, and more.

# Install the audit daemon
$ sudo apt install auditd audispd-plugins

# Check status
$ sudo systemctl status auditd

# View current rules
$ sudo auditctl -l

Writing Audit Rules

Audit rules can watch files for changes or monitor specific system calls.

# Watch /etc/passwd for writes and attribute changes
$ sudo auditctl -w /etc/passwd -p wa -k passwd_changes

# Watch /etc/shadow
$ sudo auditctl -w /etc/shadow -p wa -k shadow_changes

# Monitor all execve system calls by a specific user (UID 1001)
$ sudo auditctl -a always,exit -F arch=b64 -S execve -F uid=1001 -k user_cmds

Persistent Rules

# /etc/audit/rules.d/hardening.rules
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes
-w /var/log/auth.log -p wa -k auth_log

# Reload rules
$ sudo augenrules --load

Searching Audit Logs

# Search by key
$ sudo ausearch -k passwd_changes

# Search by time range
$ sudo ausearch -ts today -k sudoers_changes

# Generate a summary report
$ sudo aureport --summary

# Authentication report
$ sudo aureport -au

Pluggable Authentication Modules (PAM)

PAM provides a flexible framework for authentication on Linux. Every service that requires user authentication (login, ssh, sudo) uses PAM configuration files in /etc/pam.d/.

PAM Configuration Structure

# /etc/pam.d/common-auth (simplified)
auth    required    pam_faildelay.so    delay=2000000
auth    required    pam_unix.so         nullok
auth    optional    pam_permit.so

# Module types:
#   auth       — verify identity (password, token, biometric)
#   account    — authorization checks (account expiry, time-of-day)
#   password   — update authentication tokens
#   session    — setup/teardown session (mount home, set ulimits)

# Control flags:
#   required   — must succeed; continue checking other modules
#   requisite  — must succeed; fail immediately if not
#   sufficient — if succeeds and no prior required failed, stop
#   optional   — result only matters if it is the only module

Password Quality with pam_pwquality

# Install
$ sudo apt install libpam-pwquality

# /etc/security/pwquality.conf
minlen = 12
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
maxrepeat = 3
reject_username
enforce_for_root

Account Lockout with pam_faillock

# /etc/pam.d/common-auth — add before pam_unix
auth    required    pam_faillock.so preauth silent deny=5 unlock_time=900
auth    required    pam_unix.so     nullok
auth    [default=die] pam_faillock.so authfail deny=5 unlock_time=900

# Check failed attempts
$ sudo faillock --user jdoe

# Reset lockout
$ sudo faillock --user jdoe --reset

Sudo Hardening

The sudo command allows designated users to run commands as root. Proper configuration is critical for both usability and security.

# Always edit sudoers with visudo (syntax checking)
$ sudo visudo

# /etc/sudoers best practices
Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Defaults    logfile="/var/log/sudo.log"
Defaults    log_input, log_output
Defaults    passwd_timeout=1
Defaults    timestamp_timeout=5

# Grant specific commands instead of ALL
admin   ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/journalctl

Drop-in Files

# /etc/sudoers.d/dev-team
%developers ALL=(ALL) NOPASSWD: /usr/bin/docker ps, /usr/bin/docker logs *

# Verify syntax before saving
$ sudo visudo -cf /etc/sudoers.d/dev-team

File Integrity Monitoring with AIDE

AIDE (Advanced Intrusion Detection Environment) creates a database of file checksums and attributes. Periodic checks detect unauthorized modifications to critical system files.

# Install
$ sudo apt install aide aide-common

# Initialize the database
$ sudo aideinit
$ sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# Run a check
$ sudo aide --check

# After legitimate changes, update the database
$ sudo aide --update
$ sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

AIDE Configuration

# /etc/aide/aide.conf (key excerpts)
database_in=file:/var/lib/aide/aide.db
database_out=file:/var/lib/aide/aide.db.new

# Define what to monitor
/etc    p+i+u+g+sha256
/bin    p+i+u+g+sha256
/sbin   p+i+u+g+sha256
/usr/bin  p+i+u+g+sha256
/usr/sbin p+i+u+g+sha256

# Exclude noisy directories
!/var/log
!/var/cache
!/tmp

Automated Daily Check

# /etc/cron.daily/aide-check
#!/bin/bash
/usr/bin/aide --check | mail -s "AIDE Report $(hostname)" admin@example.com

CIS Security Benchmarks

The Center for Internet Security (CIS) publishes detailed hardening guides for Ubuntu and other operating systems. These benchmarks provide hundreds of specific recommendations organized by category.

Key CIS Recommendations

  • Filesystem: Ensure /tmp, /var, and /home are on separate partitions with appropriate mount options (nodev, nosuid, noexec).
  • Services: Disable unnecessary services (avahi-daemon, cups, rpcbind) and ensure NTP is configured.
  • Network: Disable IP forwarding, ICMP redirects, and source routing unless explicitly needed.
  • Logging: Ensure rsyslog or journald is configured, log files have correct permissions, and remote logging is enabled.
  • Access control: Ensure password expiration policies are set, root login is restricted, and SSH is hardened.
# Example: Harden mount options for /tmp
# /etc/fstab
tmpfs   /tmp    tmpfs   defaults,nodev,nosuid,noexec    0 0

# Example: Disable IP forwarding
$ sudo sysctl -w net.ipv4.ip_forward=0
$ echo "net.ipv4.ip_forward = 0" | sudo tee /etc/sysctl.d/60-cis.conf

# Audit with OpenSCAP (CIS content)
$ sudo apt install libopenscap8 ssg-debderived
$ sudo oscap xccdf eval --profile cis 
    /usr/share/xml/scap/ssg/content/ssg-ubuntu2204-xccdf.xml

Key Takeaways

  • Defense in depth layers multiple independent controls — firewalls, MAC, authentication, encryption — so no single failure compromises the system.
  • The principle of least privilege limits users, processes, and services to only the permissions they need.
  • Automatic security updates via unattended-upgrades keep the system patched with minimal administrator intervention.
  • The Linux Audit Framework (auditd) provides kernel-level event logging; use ausearch and aureport to query logs.
  • PAM controls authentication, account, password, and session behavior through stackable modules in /etc/pam.d/.
  • Sudo should be configured with specific command grants, logging, and secure defaults rather than blanket ALL=(ALL) ALL.
  • AIDE detects unauthorized file modifications by comparing current checksums against a known-good database.
  • CIS benchmarks provide a comprehensive, auditable hardening checklist for Ubuntu Server.

What’s Next

In the next lesson you will learn how to configure OpenSSH for secure remote access, including key-based authentication, server hardening, and advanced features like SSH tunneling and jump hosts.

繁體中文

概述

  • 學習目標:核心安全原則,包括縱深防禦、最小權限、攻擊面縮減、自動安全更新、使用 auditd 進行系統稽核、PAM 設定、sudo 強化、使用 AIDE 進行檔案完整性監控,以及 CIS 安全基準。
  • 先決條件:模組 1(Linux 基礎),熟悉 systemd 和套件管理
  • 預計閱讀時間:25 分鐘

簡介

安全不是單一產品或設定——它是一個貫穿系統每一層的持續過程。一台安全的 Linux 伺服器結合了多重重疊的控制措施,使得任何一個機制的失敗都不會危及整個系統。這個原則稱為縱深防禦

本課程探討每位 Linux 管理員都必須了解的基礎安全概念。我們從指導原則開始,然後進入 Ubuntu Server 上可用的實用工具和設定:自動安全修補、核心層級稽核日誌、可插拔認證模組(PAM)、sudo 強化、檔案完整性檢查,以及網際網路安全中心(CIS)發布的業界基準。

安全原則

縱深防禦

縱深防禦意味著分層多重安全控制,使攻擊者必須突破多個獨立機制才能達到目標。層級通常包括網路防火牆、主機防火牆、強制存取控制、應用程式層級認證和加密傳輸。

最小權限原則

每個使用者、行程和服務都應該以完成其任務所需的最小權限集運作。例如,網頁伺服器不應以 root 身分運行;它應在專用服務帳戶下運行,只能存取其文件根目錄和日誌目錄。

攻擊面縮減

移除或停用非嚴格必要的任何東西。每個開放的連接埠、每個已安裝的套件和每個運行的服務都是攻擊者的潛在入口。

自動安全更新

Ubuntu 提供 unattended-upgrades 套件來自動安裝安全修補程式。在 Ubuntu Server 上,它通常預設已安裝,但驗證和調整其設定很重要。

# 安裝(如果不存在)
$ sudo apt install unattended-upgrades

# 檢查日誌
$ sudo cat /var/log/unattended-upgrades/unattended-upgrades.log

# 模擬執行
$ sudo unattended-upgrade --dry-run --debug

使用 auditd 進行系統稽核

Linux 稽核框架在核心層級提供全面的安全相關事件日誌記錄。它記錄系統呼叫、檔案存取、使用者認證事件等。

# 安裝稽核守護程式
$ sudo apt install auditd audispd-plugins

# 監視 /etc/passwd 的寫入和屬性變更
$ sudo auditctl -w /etc/passwd -p wa -k passwd_changes

# 依關鍵字搜尋
$ sudo ausearch -k passwd_changes

# 產生摘要報告
$ sudo aureport --summary

可插拔認證模組(PAM)

PAM 為 Linux 上的認證提供靈活的框架。每個需要使用者認證的服務(login、ssh、sudo)都使用 /etc/pam.d/ 中的 PAM 設定檔。

模組類型包括:auth(驗證身分)、account(授權檢查)、password(更新認證憑證)和 session(設定/清除工作階段)。

控制旗標包括:required(必須成功,繼續檢查)、requisite(必須成功,否則立即失敗)、sufficient(如果成功且之前沒有 required 失敗,則停止)和 optional(結果僅在它是唯一模組時才重要)。

Sudo 強化

sudo 命令允許指定的使用者以 root 身分執行命令。正確的設定對於可用性和安全性都至關重要。

# 始終使用 visudo 編輯 sudoers(語法檢查)
$ sudo visudo

# 授予特定命令而非 ALL
admin   ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/journalctl

# 驗證語法
$ sudo visudo -cf /etc/sudoers.d/dev-team

使用 AIDE 進行檔案完整性監控

AIDE(進階入侵偵測環境)建立檔案校驗碼和屬性的資料庫。定期檢查可偵測對關鍵系統檔案的未授權修改。

# 安裝
$ sudo apt install aide aide-common

# 初始化資料庫
$ sudo aideinit

# 執行檢查
$ sudo aide --check

CIS 安全基準

網際網路安全中心(CIS)發布了 Ubuntu 和其他作業系統的詳細強化指南。這些基準提供了按類別組織的數百項具體建議。

  • 檔案系統:確保 /tmp/var/home 在獨立分割區上,並具有適當的掛載選項。
  • 服務:停用不必要的服務並確保已設定 NTP。
  • 網路:除非明確需要,否則停用 IP 轉發、ICMP 重導向和來源路由。
  • 日誌:確保已設定 rsyslog 或 journald,日誌檔具有正確的權限。
  • 存取控制:確保已設定密碼過期策略,限制 root 登入,並強化 SSH。

重點摘要

  • 縱深防禦分層多重獨立控制——防火牆、MAC、認證、加密——使單一失敗不會危及系統。
  • 最小權限原則將使用者、行程和服務限制為僅需的權限。
  • 透過 unattended-upgrades 自動安全更新以最少的管理員介入保持系統修補。
  • Linux 稽核框架(auditd)提供核心層級事件日誌;使用 ausearchaureport 查詢日誌。
  • PAM 透過 /etc/pam.d/ 中的可堆疊模組控制認證、帳戶、密碼和工作階段行為。
  • Sudo 應使用特定命令授權、日誌和安全預設值進行設定,而非全面的 ALL=(ALL) ALL
  • AIDE 透過將當前校驗碼與已知良好資料庫進行比較來偵測未授權的檔案修改。
  • CIS 基準為 Ubuntu Server 提供全面、可稽核的強化檢查清單。

下一步

在下一課中,您將學習如何設定 OpenSSH 以進行安全遠端存取,包括金鑰認證、伺服器強化,以及 SSH 通道和跳板主機等進階功能。

日本語

概要

  • 学習内容:多層防御、最小権限、攻撃面の縮小、自動セキュリティアップデート、auditd によるシステム監査、PAM 設定、sudo の強化、AIDE によるファイル整合性監視、CIS セキュリティベンチマークを含むコアセキュリティ原則。
  • 前提条件:モジュール1(Linux基礎)、systemd とパッケージ管理の基本的な知識
  • 推定読了時間:25分

はじめに

セキュリティは単一の製品や設定ではなく、システムのすべての層にわたる継続的なプロセスです。適切に保護された Linux サーバーは、複数の重複する制御を組み合わせて、いずれか一つのメカニズムの失敗がシステム全体を危険にさらさないようにします。この原則は多層防御として知られています。

このレッスンでは、すべての Linux 管理者が理解すべき基本的なセキュリティ概念を探ります。指導原則から始め、Ubuntu Server で利用可能な実用的なツールと設定に進みます:自動セキュリティパッチ、カーネルレベルの監査ログ、PAM、sudo の強化、ファイル整合性チェック、CIS ベンチマーク。

セキュリティ原則

多層防御

多層防御とは、複数のセキュリティ制御を階層化して、攻撃者がターゲットに到達するために複数の独立したメカニズムを突破しなければならないようにすることです。

最小権限の原則

すべてのユーザー、プロセス、サービスは、タスクを完了するために必要な最小限の権限セットで動作すべきです。

攻撃面の縮小

厳密に必要でないものはすべて削除または無効化します。開いているポート、インストールされたパッケージ、実行中のサービスはすべて攻撃者の潜在的な侵入口です。

自動セキュリティアップデート

Ubuntu は unattended-upgrades パッケージを提供して、セキュリティパッチを自動的にインストールします。

# インストール
$ sudo apt install unattended-upgrades

# ログの確認
$ sudo cat /var/log/unattended-upgrades/unattended-upgrades.log

# ドライラン
$ sudo unattended-upgrade --dry-run --debug

auditd によるシステム監査

Linux 監査フレームワークは、カーネルレベルでセキュリティ関連イベントの包括的なログを提供します。

# 監査デーモンのインストール
$ sudo apt install auditd audispd-plugins

# /etc/passwd の書き込みと属性変更を監視
$ sudo auditctl -w /etc/passwd -p wa -k passwd_changes

# キーで検索
$ sudo ausearch -k passwd_changes

# サマリーレポートの生成
$ sudo aureport --summary

PAM(プラグイン可能な認証モジュール)

PAM は Linux での認証に柔軟なフレームワークを提供します。ユーザー認証を必要とするすべてのサービスは /etc/pam.d/ の PAM 設定ファイルを使用します。

モジュールタイプ:auth(ID検証)、account(認可チェック)、password(認証トークンの更新)、session(セッションのセットアップ/終了)。

制御フラグ:required(成功必須、チェック継続)、requisite(成功必須、失敗時即時終了)、sufficient(成功し先行 required が失敗していなければ停止)、optional(唯一のモジュールの場合のみ結果が重要)。

Sudo の強化

sudo コマンドは指定されたユーザーが root としてコマンドを実行できるようにします。適切な設定は使いやすさとセキュリティの両方にとって重要です。

# 常に visudo で sudoers を編集(構文チェック)
$ sudo visudo

# ALL ではなく特定のコマンドを付与
admin   ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/journalctl

# 構文の検証
$ sudo visudo -cf /etc/sudoers.d/dev-team

AIDE によるファイル整合性監視

AIDE はファイルのチェックサムと属性のデータベースを作成します。定期的なチェックにより、重要なシステムファイルへの不正な変更を検出します。

# インストール
$ sudo apt install aide aide-common

# データベースの初期化
$ sudo aideinit

# チェックの実行
$ sudo aide --check

CIS セキュリティベンチマーク

Center for Internet Security(CIS)は、Ubuntu やその他の OS の詳細な強化ガイドを公開しています。

  • ファイルシステム:/tmp/var/home を適切なマウントオプション付きの別パーティションに配置。
  • サービス:不要なサービスを無効化し、NTP を設定。
  • ネットワーク:明示的に必要でない限り、IP転送、ICMPリダイレクト、ソースルーティングを無効化。
  • ログ:rsyslog または journald を設定し、ログファイルの権限を確認。
  • アクセス制御:パスワード有効期限ポリシーを設定し、root ログインを制限し、SSH を強化。

重要ポイント

  • 多層防御は複数の独立した制御を階層化し、単一の失敗がシステムを危険にさらさないようにする。
  • 最小権限の原則はユーザー、プロセス、サービスを必要な権限のみに制限する。
  • unattended-upgrades による自動セキュリティアップデートで管理者の介入を最小限にシステムをパッチ。
  • Linux 監査フレームワーク(auditd)はカーネルレベルのイベントログを提供。ausearchaureport でログを照会。
  • PAM は /etc/pam.d/ のスタック可能なモジュールで認証、アカウント、パスワード、セッション動作を制御。
  • Sudo は包括的な ALL=(ALL) ALL ではなく、特定のコマンド付与、ログ、安全なデフォルトで設定すべき。
  • AIDE は現在のチェックサムを既知の正常なデータベースと比較して不正なファイル変更を検出。
  • CIS ベンチマークは Ubuntu Server の包括的で監査可能な強化チェックリストを提供。

次のステップ

次のレッスンでは、鍵ベースの認証、サーバーの強化、SSH トンネリングやジャンプホストなどの高度な機能を含む、安全なリモートアクセスのための OpenSSH の設定方法を学びます。

You Missed