简体   繁体   English

来自 Linux 中的 shell 脚本的输出重定向一旦从 PHP 的 exec() 调用就被重定向到奇怪的位置

[英]Output redirection from shell script in Linux is redirected to weird location once called from PHP's exec()

There is a shell (bash) script, living on CentOS with SELinux set to Permissive, and it has only one purpose - to write something to file:有一个 shell (bash) 脚本,运行在 CentOS 上,SELinux 设置为 Permissive,它只有一个目的 - 向文件写入一些内容:

[root@centos ~]$ cat /var/www/html/test.php
<?php
$output=shell_exec("/opt/sms/script.sh");
var_dump($output);
?>
[root@centos ~]$ cat /opt/sms/script.sh
#!/bin/bash

whoami > /tmp/a.txt

cat /tmp/a.txt
[root@centos ~]$ php -f /var/www/html/test.php
string(5) "root
"
[root@centos ~]$

All good so far!到目前为止一切都很好! But now let's call it via PHP's exec, using Apache an you'll get in your browser the following:但是现在让我们通过 PHP 的 exec 调用它,使用 Apache,您将在浏览器中获得以下内容:

string(7) "apache "

which is still good until you do this:在你这样做之前这仍然很好:

[root@centos ~]$ cat /tmp/a.txt
root
[root@centos ~]$

what?什么?

And then you do this:然后你这样做:

[root@centos ~]$ find / -name a.txt 2>/dev/null
/tmp/systemd-private-689e87297de1452e98dcfaa5bd686a1f-httpd.service-gMJKi0/tmp/a.txt
/tmp/a.txt
[root@centos ~]$ cat /tmp/systemd-private-689e87297de1452e98dcfaa5bd686a1f-httpd.service- 
gMJKi0/tmp/a.txt
apache
[root@centos ~]$ cat /tmp/a.txt
root
[root@centos ~]$

Question: why is the output being written to that /tmpp/systemd-*/tmp.a.txt file instead of simple /tmp/a.txt ?问题:为什么将输出写入该/tmpp/systemd-*/tmp.a.txt文件而不是简单的/tmp/a.txt I provided ABSOLUTE path, which is supposed to serve the very obvious purpose.我提供了绝对路径,它应该用于非常明显的目的。 How/where is it controlled, that my output is written elsewhere?它是如何/在哪里控制的,我的输出写在其他地方?

This is often known as a "chroot jail", after the chroot syscall (and shell command) that lets you set the root directory of a process to something else.这通常被称为“chroot jail”,在chroot系统调用(和 shell 命令)之后,它允许您将进程的根目录设置为其他内容。 This effectively quarantines the process into a certain subdirectory.这有效地将进程隔离到某个子目录中。 All absolute paths will be interpreted relative to this root directory.所有绝对路径都将相对于该根目录进行解释。

It's a classic and well known security technique.这是一种经典且众所周知的安全技术。 If one of your PHP scripts is exploitable, an attacker will nominally be restricted to messing with files in the chroot jail, while leaving the rest of the system isolated.如果您的某个 PHP 脚本可被利用,攻击者在名义上将被限制在处理 chroot jail 中的文件,同时将系统的其余部分隔离。

( systemd likely uses Linux namespaces rather than chroot itself, but the idea is the same) systemd可能使用 Linux 命名空间而不是chroot本身,但想法是一样的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM