Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

完整記錄 Linux 用戶登入與操作日誌:比 history 更可靠的稽核方案

一、為什麼 history 不夠用

伺服器上出現檔案被竄改、卻查不到紀錄的情況,才會意識到稽核的重要性。多數人會想到 history,但它有兩個先天限制:預設只留 1000 行;即使把 /etc/profile 裡的 1000 改成一百萬,內容仍然過於粗略——看不到來源 IP、操作時間與操作者身份。要滿足真正的追溯需求,只能自己動手。

二、自動記錄腳本

history
USER=`whoami`
USER_IP=`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`
if [ "$USER_IP" = "" ]; then USER_IP=`hostname`; fi
if [ ! -d /var/log/history ]; then mkdir /var/log/history; chmod 777 /var/log/history; fi
if [ ! -d /var/log/history/${LOGNAME} ]; then mkdir /var/log/history/${LOGNAME}; chmod 300 /var/log/history/${LOGNAME}; fi
export HISTSIZE=4096
DT=`date +"%Y%m%d_%H:%M:%S"`
export HISTFILE="/var/log/history/${LOGNAME}/${USER}@${USER_IP}_$DT"
chmod 600 /var/log/history/${LOGNAME}/*history* 2>/dev/null

把這段貼到 /etc/profile 的最後。它的關鍵是改寫 HISTFILE:每次登入到登出都會產生一個以「用戶@來源IP_時間」命名的檔案,內容就是這次操作的所有指令。

三、初始化各用戶目錄

先到 /home 看有哪些用戶,再逐一建立並歸還擁有者:

[root@host log]# mkdir /var/log/history/fastdfs
[root@host history]# chown -R fastdfs:fastdfs /var/log/history/fastdfs
[root@host log]# mkdir /var/log/history/tomcat
[root@host log]# chown -R tomcat:tomcat /var/log/history/tomcat
[root@host log]# mkdir /var/log/history/zabbix
[root@host log]# chown -R zabbix:zabbix /var/log/history/zabbix

有多少個用戶就建多少個目錄,權限也要對應,否則用戶寫不進自己的紀錄。

四、驗證效果

切換到 fastdfs 用戶做幾個動作:

[fastdfs@host ~]$ cp test1.log test3.log
[fastdfs@host ~]$ echo "test 1"> test3.log
[fastdfs@host ~]$ echo "1" >> test3.log
[fastdfs@host ~]$ more test3.log

登出後回到日誌目錄查看:

[root@host fastdfs]# cd /var/log/history/fastdfs/
[root@host fastdfs]# ll
-rw------- 1 fastdfs fastdfs 83 Nov 17 21:53 fastdfs@192.168.120.103_20161117_21:53:16
-rw------- 1 fastdfs fastdfs 139 Nov 17 21:59 fastdfs@192.168.120.103_20161117_21:56:47
[root@host fastdfs]# more fastdfs@192.168.120.103_20161117_21:56:47
cp test1.log test3.log
echo "test 1"> test3.log
echo "1" >> test3.log
more test3.log
exit

紀錄與實際操作完全一致,目標達成。

補充一點防禦思維:這套方案能記錄「下過什麼指令」,但使用者若刻意清 history 或改 HISTFILE 仍可能規避,因此高安全場景建議再搭配 auditd 做檔案層級的監控,並把日誌即時送到遠端主機,避免本地被清掉就無從追查。

Copyright © Linux教程網 All Rights Reserved