to prevent XSS attacks, using inline onclick="..." is trickier...

Discussion in 'PHP' started by winterheat, Apr 6, 2009.

  1. #1
    it seems that to prevent XSS attacks (Cross site scripting), using

    <a href="#" onclick="change('<?= htmlspecialchars($title) ?>'); return false;">Click me</a>

    is trickier. The reason is that if $title has something malicious, and htmlspecialchars() changes that to &lt; But then, since the value part of onclick is parsed first as HTML, so it can very well become:

    change('<script> do something bad </script>'); return false;

    (that is, the "<" was changed to &lt; by htmlspecialchars() but changed back to "<" by the browser.

    Now, if change() actually does something like

    document.getElementById('divForTitle').innerHTML = title;

    then the XSS attack can occur.
     
    winterheat, Apr 6, 2009 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    then always add spaces, like <[space] or [space]>
     
    EricBruggema, Apr 15, 2009 IP
  3. winterheat

    winterheat Peon

    Messages:
    125
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    that seems like a good idea... change all <tag> into < tag > and there will be no XSS attack.
     
    winterheat, Apr 15, 2009 IP