2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP で setuidgid

Posted at

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);
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?