I want to pass an e-mail address from a web form to a bash script. I'm using the following regex:


Is this sufficient? Or could one embed an exploit?

The script is called from PHP:

system('/usr/local/bin/script.sh "$email"');
  • 4
    Well done even for asking. I don't see any exploit potential but you may reject some valid email addresses and accept some invalid ones. Oh—and you should anchor your regex. – Wildcard May 20 '16 at 19:55
  • 1
    @Wildcard Indeed the lack of anchoring makes the regexp useless as a security test! – Gilles 'SO- stop being evil' May 21 '16 at 20:47
  • This could be a valid email address "the doctor"@gallifrey.com. Note the quoted space in the username component. – roaima May 21 '16 at 21:14
  • at what point are you worried about an exploit? The subject-line says 'bash', so is the concern around expansion while passing $email as a (quoted) argument to script.sh, or script.sh's handling of the passed value, or the stringency of the (presumably PHP-based) regex, or ??? – Jeff Schaller May 27 '16 at 15:35
  • It is not clear how the regexp is used inside your script. For a good analyses, please provide the relevant parts of your script. – jofel Jun 7 '16 at 15:25

You may sanitize and validate the email address in PHP, which will be quicker and safer than calling a shell script. Calling a shell script with unsanitized data from a web service will just add yet another thing that can break.

$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)) {
    echo "This sanitized email address is considered valid.\n";
    echo "Before: $email\n";
    echo "After:  $sanitized_email\n";    
} else {
    echo "This sanitized email address is considered invalid.\n";

Example above adapted from examples on the PHP.net site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.