閱讀 man find 發現關鍵告誡:
-exec command ; ... The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
-execdir command {} + ... This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files.
| 參數 | 執行工作目錄 | 安全風險 |
|---|---|---|
-exec | find 命令啟動目錄 | 路徑解析與命令執行目錄一致,易發生競態條件(TOCTOU),攻擊者可通過構造文件名劫持執行流 |
-execdir | 匹配文件所在子目錄 | 每次在文件所在目錄執行,避免路徑解析競態,顯著提升安全性 |
-ok 需交互確認,同樣存在上述風險,應改用 -okdir。
# 不安全:在 /home/user 目錄下執行,命令在 /home/user 運行
find /var/log -name "*.log" -exec rm -f {} \;
# 安全:命令在各 .log 文件所在目錄運行
find /var/log -name "*.log" -execdir rm -f {} \;
$PATH 不包含 .(當前目錄)或相對路徑,否則攻擊者可在目標目錄放置同名惡意腳本劫持執行;/bin/rm)。養成查閱 man 手冊習慣,-execdir/-okdir 是 find 進行文件操作的安全首選,請在所有腳本與運維操作中全面替換。