Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitize a PHP password string

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 );
like image 716
JonDrnek Avatar asked Jul 01 '26 17:07

JonDrnek


2 Answers

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

like image 181
MiffTheFox Avatar answered Jul 05 '26 03:07

MiffTheFox


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.

like image 45
PatrikAkerstrand Avatar answered Jul 05 '26 04:07

PatrikAkerstrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!