title: Change Linux User password from PHP script
body: <p>I have a "simple" question:  How can I securely change a user's password from within a PHP script, without granting Apache root privileges or introducing other crazy security holes?</p>
  
  <p>Background:
  CentOS 6, Apache 2.2.13, PHP 5.3.3</p>
  
  <p>I am aware of the pam_chpasswd() command, which is part of the PECL PAM library.  However, this function fails unless the host process (httpd) has read access to the /etc/shadow file. (BAD IDEA! Not sure how this library helps if it requires such high privileges...)</p>
  
  <p>The ideal situation, as far as I can see, is to have PHP call a shell script with 'sudo -u[username of user changing his password]'
  This would run the script "AS" the user, so he should have permission to change his own password.  And sudo would require that the user send along his existing password in order to be authenticated, thus preventing one user from changing another user's password.</p>
  
  <p>But this doesn't work for some reason...  when opening the process with popen, the process never executes.  I have the shell script set up to dump some text into a publicly writable file in /tmp.  But it never gets to that point.</p>
  
  <pre><code>$cmd = "/usr/bin/sudo -S -u$username /file_to_execute.sh";
  $handle = popen ($cmd, "w");   // Open the process for writing
  fwrite ($handle, "$current_password\n");  // Send the user's current password to sudo (-S option)
  fwrite  .... (write the username, current password, and new password, so the script can change it)
  $result = pclose($handle);
  </code></pre>
  
  <p>If I access this php script (http://server/script.php), the function immediately fails, and $result = 1</p>
  
  <p>If I modify the sudoers file (visudo) and add a line:<br>
      <code>$</code>Defaults:apache !requiretty</p>
  
  <p>The script freezes for about 10 seconds, then fails ($result = 1)</p>
  
  <p>Any suggestions for doing this are greatly appreciated!</p>