如何監控文件變化,比如密碼修改導致 Shadow 文件變化
原始需求是如果系統的密碼被修改,或者創建了新用戶,就告警出來。本質上,只需要監控 /etc/shadow 文件變化即可。但是在指標監控體系里,這個事情就比較棘手,只能把文件的 mtime 作為指標的值上報,服務端再利用 delta 或者 increase 函數來判斷 mtime 是否發生了變化。告警出來的文本也會比較簡陋。
使用 catpaw 搭配 FlashDuty 則可以很好的解決這個問題。告警的樣例效果如下:
下面我們來看看如何實現。
1. 下載 catpaw
最新版本是 0.6.0,下載地址是:https://download.flashcat.cloud/catpaw-v0.6.0-linux-amd64.tar.gz 目前只提供了 linux-amd64 版本,如有其他版本的需求可以聯系我。
解壓后可以看到如下內容:
.
├── catpaw
├── conf.d
│ ├── config.toml
│ ├── p.exec
│ │ └── exec.toml
│ ├── p.filechange
│ │ └── filechange.toml
│ ├── p.http
│ │ └── http.toml
│ ├── p.journaltail
│ │ └── journaltail.toml
│ ├── p.mtime
│ │ └── mtime.toml
│ ├── p.net
│ │ └── net.toml
│ ├── p.ping
│ │ └── ping.toml
│ └── p.sfilter
│ └── sfilter.toml
└── scripts
├── demo.sh
├── df.sh
├── greplog.sh
└── ulimit.sh
11 directories, 14 files
其中 catpaw 是二進制文件,conf.d 目錄下是各個插件的配置文件,scripts 目錄下是一些示例腳本。
2. 主配置
這里最核心的配置是conf.d/config.toml,需要配置一下 flashduty.url,您需要先注冊 FlashDuty,注冊地址是:https://console.flashcat.cloud/signup。
FlashDuty 是一個事件 OnCall 中心,可以聚合各類監控系統的事件,比如 Zabbix、Prometheus、PagerDuty、云監控、藍鯨、Nightingale、Elastalert 等等,然后統一進行事件聚合降噪、排班、認領、升級等等。
注冊 FlashDuty 之后,系統會引導你創建協作空間,您可以在協作空間下面添加一個自定義集成:
完事點擊這個自定義集成,就可以拿到 url 了,拷貝一下 url,貼到 catpaw 的 conf.d/config.toml 中即可。
3. 配置插件
監控文件變化,可以使用 filechange 插件,配置文件在 conf.d/p.filechange/filechange.toml,樣例如下:
[[instances]]
time_span = "3m"
filepaths = ["/etc/shadow"]
check = "file changed"
interval = "30s"
[instances.alerting]
## Enable alerting or not
enabled = true
## Same functionality as Prometheus keyword 'for'
for_duration = 0
## Minimum interval duration between notifications
repeat_interval = "5m"
## Maximum number of notifications
repeat_number = 3
## Whether notify recovery event
recovery_notification = true
## Choice: Critical, Warning, Info
default_severity = "Warning"
4. 啟動 catpaw
我這里簡單測試,使用 nohup 啟動,如果生產環境,自然是建議 systemd 或者 supervisor 托管:
nohup ./catpaw &> stdout.log &
5. 測試
手工創建個用戶,比如 sudo useradd qinxiaohui,就會導致 /etc/shadow 文件發生變化,進而產生告警,大家可以自行嘗試一下。效果如下: