skip to Main Content
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?

enter image description here

The $username is the megan user at the bottom of the shadow file

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Don’t do this.

    You want as much isolation from the outward facing parts of your system (web pages) from the internal administration. To that end your script should only be able to create users within the constraints you set. Write a separate script which takes 2 arguments – a username and a password (although for preference it should generate a random password) which applies THOROUGH validation of the inputs (e.g. no ‘/’ in user name) and give your webserver uid sudo provileges on that script only (it could be iwritten n PHP calling adduser directly).

    The reason your code isn’t working is that passwd clears the input buffer before reading the password. And typically it asks for the new password twice – but the prompts and replies vary by context. There are other programs you can use for setting passswords which are more consistent – chpasswd is fairly standard on Linux systems – and as Sammitch says some versions of useradd allow the password to be specified at the time the user is created.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search