PHP Deployment Scripts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

102 lines
3.1 KiB

<?php
namespace traits;
trait su {
/**
* Returns which if found or command -v to give Executable
* details such as path detected for program.
*
* @return string /usr/bin/which or command -v
*/
public static function getExecutableDetails(): string
{
$witch_exec = \neato::get_user_bin . "which";
if (file_exists($witch_exec) && is_executable($witch_exec)) {
return $witch_exec;
}
return "command -v";
}
/**
* gets BIN paths that are trusted by the system
*
* @param string $executable_file path+executable
*
* @return string|false trusted bin or false is not trustworthy
*/
public static function getTrustedPath(string $executable_file): string|false
{
$dir = dirname($executable_file);
$prog = basename($executable_file);
return match($dir."/") {
\neato::get_user_bin => \neato::get_user_bin.$prog,
\neato::get_super_user_bin => \neato::get_super_user_bin.$prog,
\neato::get_bin => \neato::get_bin.$prog,
\neato::get_super_bin => \neato::get_super_bin.$prog,
default => false,
};
}
/**
* becomeRoot user
*
* @return string|bool sudo or doas, or true is root, false unknown su root
*
* @throws \Exception upon un-trusted BIN path
*/
public static function becomeRoot(): string|bool
{
if (posix_getuid() === 0) {
return true;
}
$use_find_exec = self::getExecutableDetails();
exec($use_find_exec . ' doas', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted;
}
unset($output);
exec($use_find_exec . ' sudo', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted;
}
return false;
}
public static function becomeNormal(string $username): string|bool
{
if (posix_getuid() > 0) {
return true;
}
$use_find_exec = self::getExecutableDetails();
exec($use_find_exec . ' doas', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted . " -u " .$username;
}
unset($output);
exec($use_find_exec . ' sudo', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted . " -u " .$username;
}
return false;
}
}