Skip to content
Advertisement

Can’t run PHP exec() on command line

Hoping someone can help me out here. Trying to run any command using exec() returns 126 and displays the same error message. I’ve narrowed it down to this pretty minimal test case.

root@test:~ $ sudo -u asterisk php -r 'exec("ls /", $out, $result); var_dump($result);'
sh: /bin/ls: Permission denied
int(126)

root@test:~ $ sudo -u asterisk ls /
bin  boot  dev  etc  home  lib  lib64  lost+found  media  mnt   opt   proc  root  sbin  selinux  srv  sys  tmp  usr  var

root@test:~ $ su -lc 'php -r '''exec("ls /", $out, $result); var_dump($result);'' asterisk
This account is currently not available.
  • SELinux and PHP safe mode are not enabled
  • permissions are fine on /, /bin/, and /bin/ls
  • asterisk is a system user created with this command: adduser -d /var/lib/asterisk -M -r -s /sbin/nologin asterisk
  • it works fine via Apache, which runs as this user

Every attempt to run any command returns permission denied and 126 as $?. The PHP config is pretty much as it shipped (Scientific Linux 6.7, PHP 5.4 via Remi package.)

Would appreciate some assistance (preferably the kind that would require some arcane knowledge, not the kind that means I missed something blindingly obvious!)

Edit: I can get it to work using su if I give the user a login shell:

root@test:~ $ usermod -s /bin/bash asterisk
root@test:~ $ su -c 'php -r '''exec("ls /", $out, $result); var_dump($result);'' asterisk
int(0)

However, this isn’t my code so changing all the use of sudo to su is not likely to happen. Also, there shouldn’t be anything stopping PHP from running this without a login shell.

Advertisement

Answer

You probably have enabled sudo option NOEXEC.

When this option is active, you can run command with high privilege, but cannot spawn other commands. This is (AFAIK) required to avoid an exploiter to gain a shell. Since you are using the asterisk user, this also makes much sense.

In your case, PHP command is granted the execution as asterisk user, but when it tries to spawn with exec, the command cannot be executed and it returns 126.

EDIT (as in comment below)

Adding this line to sudoers will solve this issue:

root ALL = (ALL) EXEC: ALL
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement