I have a PHP page that allows people to run htpasswd to update their password. What is the best way to sanitize their input. I don't want to restrict the input to much because I want to allow for secure passwords. This is what I have. How can it be improved?
$newPasswd = preg_replace('/[^a-z0-9~!()_+=[]{}<>.\\\/?:@#$%^&*]/is', '', $inputPasswd);
$cmdline = $htpasswd . " " . $passwd_file . " " . escapeshellarg($username) . " " .escapeshellarg($newpasswd);
exec( $cmdline, $output, $return_var );
The ecscapeshellarg function is built-in to PHP, and differs across systems based on the shell to sanitize the text so that no "unsafe" characters can be passed into exec.
https://www.php.net/manual/en/function.escapeshellarg.php
I would not use preg_replace with empty string on "dangerous characters", since that will make the user believe he changed the password into something, but you exec something else.. So the user will set the password to something different than he put in... It would be better to give feedback to the user telling him that some characters (preferably capture and display the offending characters) did not pass through validation.
Other than that, I think it looks pretty good. I think it provides the user with a wide range of possible character, and he doesn't need more than those to create a secure password. It might also be useful to tell the user which characters that are allowed in the password so he doesn't have to guess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With