Linux 时间戳克隆:touch -r 用正常业务文件覆盖后门 atime/mtime,伪装文件年龄
pentest/persistence · verified
一句话结论
防守方常按文件修改时间判断 webshell 落地时间;攻击者用 touch shell.php -r index.php 把后门的 atime/mtime 克隆成同目录正常业务文件的时间,使 ls -lt、按 mtime 排序和 find -newer 看起来像老文件;但 ctime 会更新为当前时间,stat 对比 mtime/ctime 即可识破。
原理
touch -r <参考文件> <目标>读取参考文件的 atime/mtime 并写入目标,目标时间与正常文件一致,基于 mtime 的异常时间线排查被绕过。touch只改 atime/mtime,不改 inode change time(ctime);写入时间戳本身会让 ctime 变为当前时间,形成“mtime 很老、ctime 很新”的矛盾。部分文件系统还有无法用 touch 修改的 btime(创建时间)。- 只加
-a或-m可单独改访问时间/修改时间;touch -d可指定任意时间。目录也可作为目标,用于对齐整个目录的时间。
触发条件
- 攻击者对后门文件有写权限(文件所有者或 root),且能读取参考文件的时间戳。
- 防守方依赖
ls -l/ls -lt/find -newer的 mtime 判断文件新旧,未检查 ctime/btime,也未使用文件完整性基线。
利用步骤
- 落地后门(如
shell.php),在同目录选定正常参考文件(如index.php)。 - 执行
touch shell.php -r index.php,把后门 atime/mtime 克隆为参考文件的值。 - 可选:对同目录的多个后门/配置逐一克隆同一参考时间,形成一致时间线;也可对目录执行以对齐目录时间。
- 用
stat对比 atime/mtime 与 ctime,确认 mtime 已对齐但 ctime 为当前,评估被发现的剩余风险。
PoC
touch shell.php -r index.php
stat shell.php index.php
ls -l --time=ctime shell.php
# 变体:指定任意时间
touch -d "2022-01-01 00:00:00" shell.php
变体与关联
- 变体:
touch -d指定伪造时间;touch -a/-m单独修改 atime 或 mtime;对目录执行以对齐整目录时间。 - 关联:原文 PAM 后门替换
pam_unix.so后同样用touch pam_unix.so -r pam_unix.so.src克隆时间,见 [[pentest-persistence-linux-pam-unix-magic-password-dns-exfil]]。 - 关联:[[pentest-persistence-linux-sshd-perl-wrapper-getpeername-sourceport]] 也用
touch -r对齐替换后的 sshd 时间戳。 - 关联:[[pentest-persistence-linux-chattr-immutable-file-lock]] 是原文相邻章节的不可变属性原子,二者分别解决“时间线伪装”和“删除保护”。
检测与防御
- 检测:
stat对比 mtime 与 ctime/btime;按 ctime 排序(ls -lc、find -newerct)找近期变化文件;文件完整性工具(AIDE/Tripwire)记录 mtime、ctime 与 inode;关注 mtime 早于目录/同批文件但 ctime 很新的异常。 - 防御:auditd 监控
touch/utimensat调用;Web 目录做哈希与时间基线并定期比对;上线流程记录文件哈希/时间;不要只凭 mtime 判断文件是否为后门。