# 用 Linux Auditd 監控系統檔案變更:Step-by-Step 實戰教學
做 IT 嘅你一定明,伺服器上面啲 config file 無啦啦俾人改咗、或者有可疑嘅檔案變動,但係又揾唔到邊個做嘅——呢種感覺真係好鬼頭痕。今日就同大家分享一個 Linux 內置嘅神器:**auditd**(Linux Audit Daemon),教你點樣 set 好佢嚟監控關鍵檔案嘅變更,仲會 send 去 centralized log server 做分析。
## Auditd 係乜嘢嚟?
Auditd 係 Linux kernel 內置嘅審計子系統,可以記錄系統上面嘅 security-relevant events,包括檔案存取、系統呼叫、使用者登入等等。佢唔使裝額外 agent,基本上所有主流 Linux distro 都內置咗,係 compliance(例如 PCI-DSS、ISO 27001)嘅基本要求之一。
## Step 1:安裝同啟用 Auditd
大部分 Linux distro 都已經預裝咗 auditd,如果冇嘅話:
# Ubuntu/Debian
sudo apt update && sudo apt install auditd -y
# RHEL/CentOS/Rocky Linux
sudo dnf install audit -y
裝完之後啟動同 enable:
sudo systemctl start auditd
sudo systemctl enable auditd
sudo systemctl status auditd
見到 `active (running)` 就代表 OK。
## Step 2:設定檔案監控規則
Auditd 嘅核心係 rules,放喺 `/etc/audit/rules.d/` 目錄。我哋建立一個新嘅 rule file:
sudo nano /etc/audit/rules.d/file-monitor.rules
加入以下規則:
# 監控 /etc 目錄下所有檔案嘅寫入同屬性變更
-w /etc/passwd -p wa -k identity_changes
-w /etc/shadow -p wa -k identity_changes
-w /etc/sudoers -p wa -k sudo_changes
-w /etc/ssh/sshd_config -p wa -k sshd_changes
# 監控 web server config
-w /etc/nginx/ -p wa -k nginx_changes
-w /etc/apache2/ -p wa -k apache_changes
# 監控 cron jobs
-w /etc/crontab -p wa -k cron_changes
-w /var/spool/cron/ -p wa -k cron_changes
**參數解釋:**
– `-w`:watch,指定要監控嘅檔案或目錄
– `-p wa`:監控 write (w) 同 attribute change (a);仲可以用 `r` (read)、`x` (execute)
– `-k`:key,幫呢組規則加個標籤,方便之後 search log
重新載入規則:
sudo augenrules --load
sudo systemctl restart auditd
## Step 3:驗證規則係咪生效
sudo auditctl -l
你應該見到頭先加嘅所有規則。然後做個測試:
# 改嚇 /etc/passwd(放心,用 comment 唔會真係改內容)
sudo touch /etc/passwd
## Step 4:搜尋審計記錄
用 `ausearch` 搜尋相關 event:
# 按 key 搜尋
sudo ausearch -k identity_changes
# 按時間範圍搜尋(最近 10 分鐘)
sudo ausearch -ts recent
# 睇詳細輸出
sudo ausearch -k identity_changes --format text
輸出會顯示邊個 user、邊個 process、咩時間、做咗咩操作——非常詳細。
## Step 5:將 Audit Log 轉發去 Centralized Log Server
單機睇 log 冇意思,要 centralized 先有用。用 `audisp-remote` plugin:
sudo nano /etc/audit/plugins.d/au-remote.conf
active = yes
direction = out
path = /sbin/audisp-remote
type = always
args = /etc/audit/audisp-remote.conf
format = string
再設定 remote server:
sudo nano /etc/audit/audisp-remote.conf
remote_server = 192.168.1.100
port = 60
transport = tcp
Restart:
sudo systemctl restart auditd
## 實戰貼士
1. **唔好 monitor 太多嘢**:auditd 會產生大量 log,monitor 太多 directory 會拖慢系統同塞爆 disk
2. **Set log rotation**:`/etc/audit/auditd.conf` 入面有 `max_log_file` 同 `num_logs` 參數
3. **配合 SIEM**:將 audit log forward 去 Splunk、ELK 或者 Wazuh 做 correlation analysis
4. **定期 review rules**:server role 變咗就要 update rules
## 總結
Auditd 係一個好 powerful 嘅內置工具,唔使錢、唔使裝 agent,已經做到基本嘅檔案完整性監控(File Integrity Monitoring)。對於 compliance 要求同 security hardening 嚟講,呢個係必做嘅一步。下次如果有人問你「Linux 點做 file monitoring」,你識做啦!
—
🔗 參考資料:NVD NIST 漏洞資料庫
_想知更多 Linux security hardening 技巧?記得 bookmark 我哋 Molious Cyber World,仲有更多實戰教學等緊你!_
#監控 #IT教學 #Linux #ssh #security




