3
\$\begingroup\$

I'd like to ask if this PHP/HTML code has any flaws which can be exploited by the potential aggressor:

<form method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<input type='text' name='foo' value='<?php echo htmlspecialchars($_POST['foo']); ?>' /> 
<input type='submit' value='bar' />
</form>

I'm aware that it can be exploited by calling script like this http://foo.bar/baz.php/'><script>alert('xss')</script><foo' and

<?php echo $_SERVER['PHP_SELF']; ?>

should be replaced with

<?php echo htmlentities($_SERVER['PHP_SELF']); ?> or <?php echo htmlspecialshars($_SERVER['PHP_SELF']); ?>

Are there any other possible ways to conduct XSS attack on this piece of code? If so, how can I secure this form?

@Update: Ok, I've just found another possible attack - entering code like ' onmouseover='alert(String.fromCharCode(88,83,83,33)); (with the apostrophe in the beginning) into the text field, which causes simple 'XSS!' alert. It can be avoided by changing <?php echo htmlspecialchars($_POST['foo']); ?> to <?php echo str_replace('\'', '&#39;', htmlspecialchars($_POST['foo'])); ?>

\$\endgroup\$
2
  • 2
    \$\begingroup\$ You've answered your own question... Though I think __FILE__ is the preferred way, rather than $_SERVER[ 'PHP_SELF' ] although I may be mistaken. Only other thing I can think to suggest is that you take a look at filter_input() for that post variable that you also never verified was set. \$\endgroup\$
    – mseancole
    Jul 3, 2012 at 15:50
  • \$\begingroup\$ Amendment: $_SERVER[ 'SCRIPT_NAME' ] is the preferred way, not __FILE__, not sure what I was thinking... Though the latter should work too. \$\endgroup\$
    – mseancole
    Jul 3, 2012 at 15:57

1 Answer 1

2
\$\begingroup\$

For single-quoted attributes, use htmlspecialchars($text, ENT_QUOTES).

Depending on what this does, you might want to implement some sort of protection against CSRF attacks.

You might also want to check $_SERVER['SCRIPT_NAME'].

Other than that, this code seems reasonable.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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