首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Linux find 命令安全最佳實踐:棄用 -exec 改用 -execdir 避免競態漏洞

     編輯:Java 綜合教學

man 手冊揭示的隱患

閱讀 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.

核心區別

參數執行工作目錄安全風險
-execfind 命令啟動目錄路徑解析與命令執行目錄一致,易發生競態條件(TOCTOU),攻擊者可通過構造文件名劫持執行流
-execdir匹配文件所在子目錄每次在文件所在目錄執行,避免路徑解析競態,顯著提升安全性

同理:-ok 替換為 -okdir

-ok 需交互確認,同樣存在上述風險,應改用 -okdir。

實戰示例

# 不安全:在 /home/user 目錄下執行,命令在 /home/user 運行
find /var/log -name "*.log" -exec rm -f {} \;

# 安全:命令在各 .log 文件所在目錄運行
find /var/log -name "*.log" -execdir rm -f {} \;

使用 -execdir 的前置條件

  • 確保 $PATH 不包含 .(當前目錄)或相對路徑,否則攻擊者可在目標目錄放置同名惡意腳本劫持執行;
  • 建議在腳本/命令中使用絕對路徑調用工具(如 /bin/rm)。

總結

養成查閱 man 手冊習慣,-execdir/-okdir 是 find 進行文件操作的安全首選,請在所有腳本與運維操作中全面替換。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved