如何监控文件变化,比如密码修改导致 shadow 文件变化

秦晓辉@快猫星云 2023年6月25日

原始需求是如果系统的密码被修改,或者创建了新用户,就告警出来。本质上,只需要监控 /etc/shadow 文件变化即可。但是在指标监控体系里,这个事情就比较棘手,只能把文件的 mtime 作为指标的值上报,服务端再利用 delta 或者 increase 函数来判断 mtime 是否发生了变化。告警出来的文本也会比较简陋。

使用 catpaw 搭配 FlashDuty 则可以很好的解决这个问题。告警的样例效果如下:

20230625181626

下面我们来看看如何实现。

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 之后,系统会引导你创建协作空间,您可以在协作空间下面添加一个自定义集成:

20230625182506

完事点击这个自定义集成,就可以拿到 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 文件发生变化,进而产生告警,大家可以自行尝试一下。效果如下:

20230625181626

扩展阅读

开源版
Flashcat
Flashduty