在開啟selinux時_增加規則_允許httpd_php-fpm執行iptables命令
轉載注明來源: 本文鏈接 來自osnosn的博客,寫於 2020-01-04.
起因
- 寫了個php的頁面,經過一番驗證之后,要調用iptables 添加或修改一條記錄。
- 我的環境是centos7,nginx+php7-fpm,開啟了selinux。
- nginx 和 php-fpm 都是以apache用戶身份運行。且運行在 httpd_t 標簽下。
- 因為 iptables的命令比較固定。所以寫了個簡單的 C 程序,在 C 程序內用execl()執行iptables語句(為了安全,所有參數寫死在程序中)。
然后把這個 C 程序編譯為執行文件myrule
,設置myrule文件的ower為root,設置myrule可執行,並設SUIDchmod u+s myrule
。 - 在php程序中用 exec()調用這個myrule程序。
臨時關閉selinux
setenforce 0
- 測試,一切OK,php成功調用myrule程序,用
iptables -nL
見到了加入的記錄。
恢復selinux
setenforce 1
- php執行失敗,沒看到有新記錄加入到iptables表中。
- /var/log/message 中出現 audit 錯誤。
- 上網搜索,比較容易解決。通過
tail /var/log/message | audit2allow -M myrule-se
生成需要的規則。
然后semodule -i myrule-se.pp
導入這個規則即可。 - 設置
chcon -t bin_t myrule
可以讓message中少點錯誤,audit2allow就能少生成點規則。 - 根據
tail /var/log/message | audit2why
提示,設置setsebool -P httpd_execmem on
。 - 生成規則,導入規則 的過程可能要搞好幾次。
semodule -i myrule-se.pp
后,又會發現有新的錯誤。
只好semodule -r myrule-se
卸載這個規則。 然后重新從message中(新舊信息一起)生成一個更完整的規則。再導入試試。 - 折騰的幾次,終於把se的規則搞完整了。並且導入了這個規則。在我的機子里,這部分的規則是:
module myrule-se 1.0;
require {
type httpd_t;
type iptables_var_run_t;
class capability net_raw;
class file { lock open read };
class rawip_socket { create getopt setopt };
}
#============= httpd_t ==============
allow httpd_t iptables_var_run_t:file { lock open read };
allow httpd_t self:capability net_raw;
allow httpd_t self:rawip_socket { create getopt setopt };
發現新問題
- /var/log/message 不再有錯誤信息,php-fpm的log中也無錯誤信息。
- 從php程序中看,myrule程序調用成功,返回碼也正常。
- 但
iptables -nL
中,就是看不到新增的記錄。
解決問題
- 上網搜索了好幾個小時,包括度娘,bing,甚至去google搜英文。也沒找到什么有用的。但多多少少總有一點提示。
- 解決過程不寫了,試了好多辦法。
- 下面貼出最終結果,給大家參考。
創建文件myrule-se2.te
module myrule-se2 1.0;
require {
type httpd_t;
type iptables_exec_t;
type iptables_t;
class process transition;
class process iptables_t;
}
#============= httpd_t ==============
allow httpd_t iptables_t: process transition;
type_transition httpd_t iptables_exec_t : process iptables_t;
執行以下命令:
checkmodule -m -M -o myrule-se2.mod myrule-se2.te
semodule_package -o myrule-se2.pp -m myrule-se2.mod
semodule -i myrule-se2.pp
再測試,成功。
---end---