shell_exec("sudo useradd -m $username");
shell_exec("yes $password | sudo passwd $username");
The code snippet above successfully creates the user but it does not set the password, am I doing something wrong?
The $username is the megan user at the bottom of the shadow file
You cannot invoke passwd
non-interactively. Period.
You can supply useradd
with a pre-computed password hash with the -p
option, though. [See: man useradd
]
function os_pw_hash($password) {
$salt = base64_encode(random_bytes(12)); // 16-byte salt
return crypt('hunter2', '$6$'.$salt.'$');
}
var_dump( os_pw_hash('hunter2') );
Output:
string(106) "$6$0LIJoQz2W0vP35Ej$kg75OyhAZb9iAbqa/sO56pXs/peA8wPd4DKv5Al0FllBApBe7BvXUA6Q6fQ3bqpxfz.XH6GWnI.mH6yLfTQil1"
You're also going to want to run this [and honestly all your shell parameters] through escapeshellarg()
to make sure metacharacters are properly escaped.
Lastly:
for this use case security is not a concern
Security is always a concern. This is usually doubly true for cases when you don't think it should be. I have had users that I unfortunately trusted to know better exploit security holes in internal applications to execute commands with root privileges in order to avoid simply having to make a ticket.