public static function setuidgid($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})"); } }
function update_user($user) { global $mcm; /* if we ran validate_login(),then the $user_id hasn't been set... */ if (!isset($user['user_id'])) { $user['user_id'] = $mcm['user_id']; } $prefs = mcm_action('lookup_prefs', $user['user_id']); if (isset($user['forced_target'])) { $prefs['pref_target'] = $user['forced_target']; } echo "updating symlinks for user '{$user['user_name']}' on directory '{$prefs['pref_target']}'\n"; if (!($prefs = validate_prefs($prefs))) { return; } posix_seteuid(0); posix_seteuid($prefs['pref_sysid']); echo " - creating virtualfs based on accepted items: "; $params = array('user_id' => $user['user_id'], 'item_status' => 'accepted', 'item_type' => 'MUSIC'); $accepted = mcm_action('lookup_itemlist', $params); $virtualfs = create_virtualfs($accepted, $prefs['pref_extensions']); echo count($accepted) . "\n"; echo " - verifying current symlinks... \n"; $create = mcm_action('verify_symlinks_against_virtualfs', array('path' => $prefs['pref_target'], 'virtualfs' => $virtualfs)); echo " - creating new symlinks: " . count($create) . "\n"; $mcmnew_dir = "{$prefs['pref_target']}/_mcmnew"; if (!make_mcmnew_dir($mcmnew_dir)) { return; } chdir($mcmnew_dir); $prev_dirname = false; foreach ($create as $item) { $source = $item; $dirname = basename(dirname($item)); $filename = basename($item); $dest = $dirname . "/" . $filename; if ($prefs['pref_codepage'] != $mcm['codepage']) { $dest = iconv(strtoupper($mcm['codepage']), strtoupper($prefs['pref_codepage']), $dest); } if ($dirname != $prev_dirname) { mkdir(dirname($dest)); echo " {$dirname}\n"; } echo " {$filename}\n"; symlink($item, $dest); $prev_dirname = $dirname; } }
/** * Helper method which allows to execute a callable as the super user the server got started by. * * @param callable $callable The callable to run * @param array $arguments Arguments to pass to the callable * * @return mixed The callables result */ public static function sudo(callable $callable, array $arguments = array()) { // don't do anything under Windows if (FileSystem::getOsIdentifier() === FileSystem::OS_IDENTIFIER_WIN) { return call_user_func_array($callable, $arguments); } // get the current user user pair (super user and effective user) $currentUserId = (int) posix_geteuid(); $superUserId = (int) posix_getuid(); // temporarily switch to the super user posix_seteuid($superUserId); // execute the callable $result = call_user_func_array($callable, $arguments); // switch back to the effective user posix_seteuid($currentUserId); return $result; }
/** * Handle an event. * * @param \League\Event\EventInterface $event The triggering event * * @return void * @see \League\Event\ListenerInterface::handle() */ public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Appserver\Core\Interfaces\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // don't do anything under Windows if (FileSystem::getOsIdentifier() === 'WIN') { $applicationServer->getSystemLogger()->info('Don\'t switch UID to \'%s\' because OS is Windows'); return; } // initialize the variable for user/group $uid = 0; $gid = 0; // throw an exception if the POSIX extension is not available if (extension_loaded('posix') === false) { throw new \Exception('Can\'t switch user, because POSIX extension is not available'); } // print a message with the old UID/EUID $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid()); // extract the user and group name as variables extract(posix_getgrnam($applicationServer->getSystemConfiguration()->getGroup())); extract(posix_getpwnam($applicationServer->getSystemConfiguration()->getUser())); // switch the effective GID to the passed group if (posix_setegid($gid) === false) { $applicationServer->getSystemLogger()->error(sprintf('Can\'t switch GID to \'%s\'', $gid)); } // print a message with the new GID/EGID $applicationServer->getSystemLogger()->info("Running as group" . posix_getgid() . "/" . posix_getegid()); // switch the effective UID to the passed user if (posix_seteuid($uid) === false) { $applicationServer->getSystemLogger()->error(sprintf('Can\'t switch UID to \'%s\'', $uid)); } // print a message with the new UID/EUID $applicationServer->getSystemLogger()->info("Running as user " . posix_getuid() . "/" . posix_geteuid()); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
/** * Handle an event. * * @param \League\Event\EventInterface $event The triggering event * * @return void * @see \League\Event\ListenerInterface::handle() */ public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Appserver\Core\Interfaces\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // print a message with the old UID/EUID $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid()); // extract the variables $uid = 0; extract(posix_getpwnam('root')); // switcht the effective UID to the passed user if (posix_seteuid($uid) === false) { $applicationServer->getSystemLogger()->error(sprintf('Can\'t switch UID to \'%s\'', $uid)); } // print a message with the new UID/EUID $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid()); // @TODO Switch group also!!!! } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
$fastagi->config['fastagi']['basedir'] = dirname(__FILE__); } // perform some security checks $script = $fastagi->config['fastagi']['basedir'] . DIRECTORY_SEPARATOR . $fastagi->request['agi_network_script']; // in the same directory (or subdirectory) $mydir = dirname($fastagi->config['fastagi']['basedir']) . DIRECTORY_SEPARATOR; $dir = dirname($script) . DIRECTORY_SEPARATOR; if (substr($dir, 0, strlen($mydir)) != $mydir) { $fastagi->conlog("{$script} is not allowed to execute."); exit; } // make sure it exists if (!file_exists($script)) { $fastagi->conlog("{$script} does not exist."); exit; } // drop privileges if (isset($fastagi->config['fastagi']['setuid']) && $fastagi->config['fastagi']['setuid']) { $owner = fileowner($script); $group = filegroup($script); if (!posix_setgid($group) || !posix_setegid($group) || !posix_setuid($owner) || !posix_seteuid($owner)) { $fastagi->conlog("failed to lower privileges."); exit; } } // make sure script is still readable if (!is_readable($script)) { $fastagi->conlog("{$script} is not readable."); exit; } require_once $script;
protected function restoreRootUidGid() { posix_setegid(0); posix_seteuid(0); }
/** * Set the effective UID of the current process * * @param int $uid The user id. * * @return bool */ public function seteuid(int $uid) : bool { return posix_seteuid($uid); }
private function dropPrivileges() { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return; } $user = $this->options->user; if (!extension_loaded("posix")) { if ($user !== null) { throw new \RuntimeException("Posix extension must be enabled to switch to user '{$user}'!"); } } elseif (posix_geteuid() === 0) { if ($user === null) { $this->logger->warning("Running as privileged user is discouraged! Use the 'user' option to switch to another user after startup!"); return; } $info = posix_getpwnam($user); if (!$info) { throw new \RuntimeException("Switching to user '{$user}' failed, because it doesn't exist!"); } $success = posix_seteuid($info["uid"]); if (!$success) { throw new \RuntimeException("Switching to user '{$user}' failed, probably because of missing privileges.'"); } } }
/** * De-escalates privileges */ private function setIds() { posix_seteuid($this->config['daemon']['user']['uid']); posix_setegid($this->config['daemon']['user']['gid']); }
include 'AtomintersoftModule.php'; include 'SamairModule.php'; include 'FreeCheckerModule.php'; include 'NNTimeModule.php'; // set proper permissions if (posix_getgid() != GID) { posix_setgid(GID); } if (posix_getuid() != UID) { posix_setuid(UID); } if (posix_getegid() != GID) { posix_setegid(GID); } if (posix_geteuid() != UID) { posix_seteuid(UID); } // first check that an instance is not already running if (file_exists(PIDFILE)) { $line = file(PIDFILE); $pid = trim($line[0]); if (count(explode("\n", shell_exec("ps --pid " . $pid))) > 2) { die("An instance of the daemon is already running with PID {$pid}\n"); } else { // no process with that PID, can safely remove the existing PID file print "Found dangling PID file, removing...\n"; unlink(PIDFILE); } } // fork the main process $pid = pcntl_fork();
<?php echo "*** Test substituting argument 1 with object values ***\n"; function test_error_handler($err_no, $err_msg, $filename, $linenum, $vars) { if (error_reporting() != 0) { // report non-silenced errors echo "Error: {$err_no} - {$err_msg}, {$filename}({$linenum})\n"; } } set_error_handler('test_error_handler'); class classWithToString { public function __toString() { return "Class A object"; } } class classWithoutToString { } $variation_array = array('instance of classWithToString' => new classWithToString(), 'instance of classWithoutToString' => new classWithoutToString()); foreach ($variation_array as $var) { var_dump(posix_seteuid($var)); }
/** * Close session and return to previous uid */ public static function close() { session_write_close(); // change uid back if (null !== static::$pre_session_uid) { posix_seteuid(static::$pre_session_uid); static::$pre_session_uid = null; } }
echo "posix_getppid succeeded\n"; } else { echo "posix_getppid failed\n"; } $uid = posix_getuid(); echo "uid={$uid}\n"; $euid = posix_geteuid(); echo "euid={$euid}\n"; $gid = posix_getgid(); echo "gid={$gid}\n"; $egid = posix_getegid(); echo "egid={$egid}\n"; posix_setuid(1004); $uid = posix_getuid(); echo "uid={$uid}\n"; posix_seteuid(1004); $euid = posix_geteuid(); echo "euid={$euid}\n"; posix_setgid(1004); $gid = posix_getgid(); echo "gid={$gid}\n"; posix_setegid(1004); $egid = posix_getegid(); echo "egid={$egid}\n"; $groups = posix_getgroups(); echo "groups=\n"; print_r($groups); $login = posix_getlogin(); echo "login={$login}\n"; $pgrp = posix_getpgrp(); echo "pgrp={$pgrp}\n";
<?php echo "*** Test by calling method or function with incorrect numbers of arguments ***\n"; $uid = '123'; $extra_arg = '12312'; var_dump(posix_seteuid($uid, $extra_arg)); var_dump(posix_seteuid());
/** * プロセスを開始させる * @param string $exec_php * @param string $pid_file * @throws \Exception */ public static function start($pid_file = null, $opt = array()) { if (php_sapi_name() !== 'cli') { return; } if (!extension_loaded('pcntl')) { throw new \Exception('require pcntl module'); } $clients = isset($opt['clients']) ? $opt['clients'] : 1; $sleep = isset($opt['sleep']) ? $opt['sleep'] : 0; $exec_php = isset($opt['exec_php']) ? $opt['exec_php'] : null; $action = isset($opt['action']) ? $opt['action'] : null; $args = isset($opt['args']) ? $opt['args'] : array(); $phpcmd = isset($_ENV['_']) ? $_ENV['_'] : (isset($_SERVER['_']) ? $_SERVER['_'] : (isset($cmd['phpcmd']) ? $cmd['phpcmd'] : '/usr/bin/php')); $ref = new \ReflectionClass(new static()); $name = isset($opt['name']) ? $opt['name'] : null; if (isset($opt['dir'])) { chdir($opt['dir']); } if (!empty($exec_php) && !is_file($exec_php)) { throw new \Exception($exec_php . ' not found'); } // PID file if (isset($pid_file)) { $pid_file = self::pid($pid_file, $ref, $name, $exec_php, $action); if (is_file($pid_file)) { if (posix_kill((int) file_get_contents($pid_file), 0)) { throw new \Exception('started PID:' . (int) file_get_contents($pid_file)); } @unlink($pid_file); } if (!is_dir(dirname($pid_file)) || false === file_put_contents($pid_file, '')) { throw new \Exception('permission denied ' . $pid_file); } } // reset gc_enable(); umask(0); clearstatcache(); // start declare (ticks=1) { if (isset($opt['uid']) && !posix_setuid($opt['uid']) || isset($opt['euid']) && !posix_seteuid($opt['euid']) || isset($opt['gid']) && !posix_setgid($opt['gid']) || isset($opt['egid']) && !posix_setegid($opt['egid'])) { throw new \Exception(posix_strerror(posix_get_last_error())); } // parent if (!empty($pid_file)) { if (pcntl_fork() !== 0) { return; } posix_setsid(); } foreach (self::$signal_list as $sig => $dec) { pcntl_signal($sig, array($ref->getName(), 'signal_func')); } // pid self::$pid = posix_getpid(); if (!empty($pid_file)) { file_put_contents($pid_file, self::$pid); } while (self::$state === true) { $pid = pcntl_fork(); self::$child[$pid] = true; if ($pid === -1) { throw new \Exception('Unable to fork'); } if ($pid === 0) { $pid = posix_getpid(); if (empty($exec_php)) { if (empty($action)) { static::main(); } else { list($class, $method) = explode('::', $action); call_user_func_array(array('\\' . str_replace('.', '\\', $class), $method), $args); } exit; } else { pcntl_exec($phpcmd, array($exec_php)); } } if (sizeof(self::$child) >= $clients) { $exist_pid = pcntl_wait($status); if (isset(self::$child[$exist_pid])) { unset(self::$child[$exist_pid]); } if (pcntl_wifexited($status)) { } } if ($sleep > 0) { usleep($sleep * 1000000); } clearstatcache(); } if (!empty($pid_file) && is_file($pid_file)) { @unlink($pid_file); } } }
private static function restore_wp_cli_user() { if (!posix_setegid($original_gid) || $original_gid != posix_getegid()) { AC_Inspector::log('Unable to restore the group of the current process (gid: ' . $original_gid . '). File permissions will have to be repaired manually.', __CLASS__, array('error' => true)); return false; } if (!posix_seteuid($original_uid) || $original_uid != posix_geteuid()) { AC_Inspector::log('Unable to restore the owner of the current process (uid: ' . $original_uid . '). File permissions will have to be repaired manually.', __CLASS__, array('error' => true)); return false; } return true; }
public static function setProcessUid($uid) { posix_seteuid($uid); }
/** * Set the effective user ID for the current process * * @param int $uid The user id. * * @return bool */ public function seteuid($uid) { return posix_seteuid($uid); }
function commandStart() { global $_CONFIG, $_STATE; // Set up the descriptors for the process $descriptors = array(0 => array('pipe', 'r'), 1 => array('file', $_CONFIG['Stdout'], 'a'), 2 => array('file', $_CONFIG['Stderr'], 'a')); // Set the current working directory $cwd = $_CONFIG['WorkingDirectory']; // Set up the environment variables $env = $_CONFIG['Environment']; // Set the effective uid/gid so we spawn the process as the correct user. posix_setegid($_CONFIG['GID']); posix_seteuid($_CONFIG['UID']); $_STATE['ProcessHandle'] = proc_open($_CONFIG['Command'], $descriptors, $_STATE['Descriptors'], $cwd, $env); if (!isset($_STATE['ProcessHandle']) || !is_resource($_STATE['ProcessHandle'])) { throw new Exception("Could not start command."); } // Reset the effective uid/gid posix_setegid(0); posix_seteuid(0); $_STATE['Status'] = proc_get_status($_STATE['ProcessHandle']); if (isset($_CONFIG['Command_Pidfile'])) { file_put_contents($_CONFIG['Command_Pidfile'], $_STATE['Status']['pid']); } if (isset($_CONFIG['AlarmInterval'])) { pcntl_alarm($_CONFIG['AlarmInterval']); } }
/** * Runs seteuid(nUIDToRunUnder), and chowns the PIDFileName * * @return boolean TRUE=Success */ private function _switchUser() { if (empty($this->nUIDToRunUnder) || posix_geteuid() == $this->nUIDToRunUnder) { // Nothing to do! return TRUE; } // Ensure we can delete our own PID file chown($this->sPIDFileName, $this->nUIDToRunUnder); if (!posix_seteuid($this->nUIDToRunUnder)) { // Couldn't change UID, so clean up! unlink($this->sPIDFileName); return FALSE; } return TRUE; }
/** * Запуск сервиса. * * @access protected * @static */ protected static function cmdStart() { echo "Starting Pinger service... "; try { // проверка PID-файла Assets\PID::PreLock(); $ruid = posix_getpwnam(Assets\Config::$exec_user)['uid']; $rgid = posix_getgrnam(Assets\Config::$exec_group)['gid']; if (null === $ruid || null === $rgid) { printf(" [FAIL]\nRequired exec user:group [%s:%s] was not found.\n", Assets\Config::$exec_user, Assets\Config::$exec_group); exit(1); } // попытка запуска Мастер-процесса $pid = @pcntl_fork(); if ($pid == -1) { // ошибка ветвления throw new Assets\Exceptions\Master_Fork_Fail_Exception(); } elseif ($pid) { // // рутины родительского процесса - сценария SBINDIR/pinger // printf(" [OK]\nLooks like Master forked with PID=%d\n", $pid); exit(0); } else { // // рутины дочернего процесса - Мастер-процесса // // переключение группы-владельца процесса // выполняется ДО переключения пользователя-владельца if (!posix_setegid($rgid)) { printf("Failed to posix_setegid(%d) [%s].\n", $rgid, Assets\Config::$exec_group); exit(1); } // переключение пользователя-владельца процесса if (!posix_seteuid($ruid)) { printf("Failed to posix_seteuid(%d) [%s].\n", $ruid, Assets\Config::$exec_user); exit(1); } // открытие журналов TwinLog::init(PINGER_LOGDIR, 'Master'); // закрытие дескрипторов @fclose(STDIN); @fclose(STDOUT); @fclose(STDERR); // вход в Мастер-процесс Daemon\Master::main(); // закрытие журналов TwinLog::kill(); // успешный выход // exit(0) не используется для возможности перезапуска // с применением этого метода } } catch (Assets\Exceptions\PID_Open_Fail_Exception $e) { echo " [FAIL]\n PID-file exists but unreadable\n"; exit(1); } catch (Assets\Exceptions\PID_Lock_Fail_Exception $e) { printf("\n Daemon already running with PID=%d", Assets\PID::$pid); exit(1); } catch (Assets\Exceptions\PID_Read_Fail_Exception $e) { echo " [FAIL]\n PID-file exists and locked\n"; echo " PID-file reading failed!\n"; exit(1); } catch (Assets\Exceptions\PID_Unlink_Fail_Exception $e) { echo " [FAIL]\n PID-file exists but failed to unlink\n"; exit(1); } catch (Assets\Exceptions\Master_Fork_Fail_Exception $e) { echo " [FAIL]\n fork() failed\n"; exit(1); } catch (\Exception $e) { echo " [FAIL]\n Unexpected exception:\n"; var_export($e->getMessage()); var_export($e->getTraceAsString()); exit(1); } }
public function childServer($addr) { $output = $this->output; $bindTo = json_decode($addr, true); $this->childHost = $bindTo['host']; $this->port = $bindTo['port']; cli_set_process_title("mpcmf/console server:run/child -b {$this->childHost} -p {$this->port}"); posix_setgid(99); posix_setuid(99); posix_seteuid(99); posix_setegid(99); $loop = Factory::create(); $socket = new reactSocketServer($loop); $http = new reactHttpServer($socket); $http->on('request', function (reactRequest $request, reactResponse $response) use($output) { //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> New connection"); //MPCMF_DEBUG && $clientName = $request->getRemoteAddress() . '#' . spl_object_hash($request); //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Client connected"); profiler::resetStack(); if (!$this->prepare($request, $response, $output)) { return; } //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Starting application</info>"); try { $app = $this->app(); $slim = $app->slim(); $originApplication = $this->applicationInstance->getCurrentApplication(); $this->applicationInstance->setApplication($app); $slim->call(); } catch (\Exception $e) { $response->writeHead(500); $response->end("Exception: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}\n{$e->getTraceAsString()}"); return; } /** @var int[]|Headers[]|string[] $content */ $content = $slim->response->finalize(); Util::serializeCookies($content[1], $slim->response->cookies, $slim->settings); $content[1] = $content[1]->all(); $this->applicationInstance->setApplication($originApplication); //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Ending application</info>"); //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> Writing data and closing connection"); static $serverSoftware; if ($serverSoftware === null) { $serverSoftware = 'MPCMF Async PHP ' . phpversion(); } if (array_key_exists('HTTP_ACCEPT_ENCODING', $_SERVER) && strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false) { $content[1]['Content-Encoding'] = 'gzip'; $content[2] = gzencode($content[2], 9); } $content[1]['X-PHP-Server'] = $serverSoftware; $content[1]['X-PHP-Server-Addr'] = "{$this->childHost}:{$this->port}"; $response->writeHead($content[0], $content[1]); $response->end($content[2]); //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> Connection closed"); }); $output->writeln("<error>[CHILD]</error> Starting child server on {$this->childHost}:{$this->port}"); $socket->listen($this->port, $this->childHost); $loop->run(); }
public function loop(&$error = false, $user = null) { $this->_socket = stream_socket_server($this->_socket_url, $errno, $errstr, STREAM_SERVER_BIND); if(!$this->_socket) { if($error !== false) $error = "$errno: $errstr"; return false; } if($user != null) { posix_seteuid($user["uid"]); posix_setegid($user["gid"]); } stream_set_blocking($this->_socket, false); return $this->loop_ex(); }
function setuid($cacti_poller_account) { global $config; /* if we are unix, set the effective userid to root and then create */ if ((CACTI_SERVER_OS == "unix") && (function_exists("posix_getuid"))) { posix_seteuid($cacti_poller_account); } }
private function restoreRootUidGid() { posix_setegid(0); posix_seteuid(0); }
function rpc_process_seteuid($args) { return @posix_seteuid(intval($args[0])); }
function setuid($cacti_poller_account) { global $config; /* if we are unix, set the effective userid to root and then create */ if ($config["cacti_server_os"] == "unix" && function_exists("posix_getuid")) { posix_seteuid($cacti_poller_account); } }
<?php $myuid = posix_geteuid(); $uid = var_dump(posix_seteuid($myuid));