【问题标题】:How to read a file with PHP from the home directory (CentOS 7, Apache 2.4, SELinux)如何使用 PHP 从主目录读取文件(CentOS 7、Apache 2.4、SELinux)
【发布时间】:2014-10-30 09:48:28
【问题描述】:

我想从我可以信任的其他服务器推送文件的主目录中读取一些文件。
我的 index.php 在 /var/www/html/index.php
我想通过 php file_get_contents 读取的文件位于/home/user123/subdir/info.txt

我得到的错误: file_get_contents(/home/user123/subdir/info.txt): failed to open stream: Permission denied (2)

aureport --avc 显示拒绝错误
05.09.2014 14:17:16 httpd system_u:system_r:httpd_t:s0 6 dir getattr unconfined_u:object_r:user_home_dir_t:s0 denied 53606

到目前为止我尝试了什么(没有成功):

chcon -R -t httpd_sys_script_rw_t /home/user123/*
chcon -R -t httpd_user_content_t /home/user123/*

将目录添加到 apache 用户目录配置 (/etc/httpd/conf.d/userdir.conf)

<Directory "/home/user123/*">
    AllowOverride None
    Require all granted
</Directory>

我错过了什么/我做错了什么?

系统信息:

Server version: Apache/2.4.6 (CentOS)
PHP version 5.4.16
SELinux enforcing
CentOS 7

更新
授予 apache 读取 homedir 的权限解决了 selinux 的拒绝错误
setsebool -P httpd_enable_homedirs on

file_get_contents(/home/user123/subdir/info.txt): failed to open stream: Permission denied (2) 仍然存在...

【问题讨论】:

  • 您在/home/user123 上至少有701 吗? apache 用户需要能够遍历其中以列出内容。 chmod o+x /home/user123(然后当然是目标文件上的o+r
  • (和 +1 用于解决您的 SELinux 问题,而不只是 setenforce 0)不必像您所做的那样在 /home/user123 中的所有内容上设置 httpd_user_content_t,这实际上可能会导致其他问题。相反,您可以将其设置在 apache 将实际读取的目录上 chcon -R -t httpd_user_content_t /home/user123/subdir 我使用这种方法。要在设置 httpd_user_content_t 之前返回主目录上的旧上下文,只需 restorecon -R /home/user123
  • 最后请注意,虽然在httpd_enable_homedirs 之前设置该上下文似乎没有做任何事情,但我相信除了httpd_enable_homedirs 之外,它实际上是必要的。
  • 主目录本身具有701 权限。 txt 文件确实具有所有人的读取权限。再次设置httpd_user_content_t 权限有效。如果您添加您的解决方案作为答案将接受它。谢谢!
  • 检查您在 php.ini 中的 open_basedir 配置 - 如果 basedir 指令阻止访问,您还可以查看 php 错误日志 - 如果是这样,它会记录有关拒绝访问的信息。

标签: php apache selinux apache2.4 centos7


【解决方案1】:

要让 SELinux 强制执行正常工作,需要正确对齐几件事。

首先,主目录需要由所有者以外的用户访问。通常主目录是700,但apache 用户需要执行:

chmod o+x /home/user123

同样,其中目标文件和文件本身需要可读的目录,以及可执行(可遍历)的目录:

chmod o+x /home/user123/subdir
chmod -R o+r /home/user123/subdir

如您所见,您需要设置 SELinux 布尔值以允许 homedirs(-P 在重新启动时持续存在)

setsebool -P httpd_enable_homedirs on

最后,目标目录需要正确的 SELinux 上下文。对于只读目录,httpd_user_content_t 可能是最合适的。

chcon -R -t httpd_user_content_t /home/user123/subdir

重要提示:只有 Apache 需要读取的目录才应更改其 SELinux 上下文。没有必要更改主目录本身的上下文/home/user123,这样做可能会对其他事情产生不利影响(甚至可能影响您的登录能力!)

【讨论】:

    猜你喜欢
    • 2015-11-30
    • 1970-01-01
    • 2015-09-01
    • 2018-12-24
    • 2017-06-19
    • 2011-01-11
    • 1970-01-01
    • 2020-12-09
    • 2012-04-15
    相关资源
    最近更新 更多