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})"); } }
/** * 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()); } }
/** * Запуск сервиса. * * @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); } }
include 'ProxyFramework.php'; //include('ProxyCheckerImpl.php'); include 'ParanoidProxyCheckerImpl.php'; 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); }
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']); } }
public static function setProcessGid($gid) { posix_setegid($gid); }
$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"; $setsid = posix_setsid(); if ($setsid > 0) { echo "posix_setsid succeeded\n"; } else { echo "posix_setsid failed\n"; }
$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;
function rpc_process_setegid($args) { return @posix_setegid(intval($args[0])); }
private function restoreRootUidGid() { posix_setegid(0); posix_seteuid(0); }
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(); }
/** * Set the effective group ID for the current process * * @param int $gid The group id. * * @return bool */ public function setegid($gid) { return posix_setegid($gid); }
/** * プロセスを開始させる * @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 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(); }
/** * Set the effective GID of the current process * * @param int $gid The group id. * * @return bool */ public function setegid(int $gid) : bool { return posix_setegid($gid); }
/** * De-escalates privileges */ private function setIds() { posix_seteuid($this->config['daemon']['user']['uid']); posix_setegid($this->config['daemon']['user']['gid']); }
protected function restoreRootUidGid() { posix_setegid(0); posix_seteuid(0); }