1

I'm posting it for a clarification in a specific situation, though user input sanitization/validations is a cliche subject.

A section of the code contain

$haystack=$_GET['user'];

$input is never used for 'echo' or 'print' or in any SQL query or in any such thing. The only further use of the user input ( $haystack ) is to check if the string contains a predefined $needle.

if (preg_match($needle,$haystack)) {
$result="A";
} else {
$result="B";
}

My worry is the execution of a malicious code, rather than the presence of it in the user input.

So the question is, if the user input is used only in the context (no usage in echo,print,SQL etc) mentioned above, is there still a possibility of a malicious code in the user input get executed.

I wanted to add the security measures that is just required for the context than overdoing it.

new_b
  • 33
  • 1
  • 6
  • there is no problem I think, but the biggest problem what if you forgot which variable is sanitized or not. or if some other programmer after you thought it is sanitized. I know that's good way of working (forgetting without checking but could happen), better make a function to sanitize and you can easily apply it to any input. or put your sanitized variables in clearly labeled variable names such as $clean_xxx – Dreaded semicolon Aug 10 '11 at 09:31
  • possible duplicate of [Is using superglobals directly good or bad in PHP?](http://stackoverflow.com/questions/3498207/is-using-superglobals-directly-good-or-bad-in-php) –  Apr 13 '14 at 14:08

4 Answers4

3

If used only in the context, there's no way to execute malicious code from the user input.

You should be careful with eval, preg_replace (with modifier e, thanks Pelshoff), database queries and echo (& print, sprintf…).

olivier
  • 1,007
  • 8
  • 14
0

Its not possible to just execute arbitrary code by being able to alter a string. Only when you output the string directly, or use it in SQL should you be really worried.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
  • 2
    Except if the patterns depended on it :) Off-topic, sorry, but the /e modifier in preg_match can execute code. – Pelshoff Aug 10 '11 at 08:59
0

preg_match won't end up executing your input. It's too simple and straightforward to have a hidden exploitable bug. If you toss $haystack after running preg_match on it, then it can't possibly hurt you.

0

While the $haystack may not be reflected, it can obviously affect program flow. The (extremely short) code you posted certainly doesn't look directly vulnerable, but not sanitizing your input may enable code execution in conjunction with other vulnerabilities.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123