Skip to content

Instantly share code, notes, and snippets.

@ngyuki
Last active December 11, 2015 11:19
Show Gist options
  • Save ngyuki/4593155 to your computer and use it in GitHub Desktop.
Save ngyuki/4593155 to your computer and use it in GitHub Desktop.
PHP setuidgid.php
<?php
/*
* example)
* sudo php setuidgid.php apache test.php
*
*/
try
{
if ($argc <= 2)
{
$name = basename(__FILE__);
throw new RuntimeException("Usage: php $name <user> <script.php>");
}
list (, $user, $script) = $argv;
call_user_func(function() {
global $user;
$uid = posix_getuid();
if ($uid !== 0)
{
throw new RuntimeException("setuidgid is only root");
}
$nam = posix_getpwnam($user);
if (!$nam)
{
throw new RuntimeException("unkonwn user \"$user\"");
}
$uid = $nam['uid'];
$gid = $nam['gid'];
if (!posix_setgid($gid))
{
throw new RuntimeException("unable setgid($gid)");
}
if (!posix_setegid($gid))
{
throw new RuntimeException("unable setegid($gid)");
}
if (!posix_setuid($uid))
{
throw new RuntimeException("unable setuid($uid)");
}
if (!posix_seteuid($uid))
{
throw new RuntimeException("unable seteuid($uid)");
}
});
require_once $script;
}
catch (Exception $ex)
{
fputs(STDERR, $ex->getMessage() . PHP_EOL);
exit(-1);
}
<?php
file_put_contents("/tmp/hoge", "hoge");
echo `ls -l /tmp/hoge`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment