Karlth
Karlth

Reputation: 3275

XSS prevention. Handling <script is enough?

I was wondering if checking for and removing "<script" from text entry fields would be enough to stop javascript code injection attacks?

Upvotes: 14

Views: 2103

Answers (6)

Kornel
Kornel

Reputation: 100080

<s<scriptcript after one removal becomes <script.

If you block that, there are plenty of others. It's much simpler and more correct to escape (not remove) all occurances <, " and &.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816232

It depends also on what you are doing with the input. Here is a simplified example I found on a real website of some greeting card service:

It contained a select field with which you were able to select the color of the text:

<select name="color">
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
</select>

The value was used unfiltered on the greeting card page. So it is easy to tamper the POST data sent, and change

color=red

to something like

color=red%22+onload%3D%22alert(%27foo%27)

which would result in

<font color="red" onload="alert('foo')">

instead of <font color="red">.


So the point is never trust any input from the user, not even predefined values you define.

Upvotes: 9

Piskvor left the building
Piskvor left the building

Reputation: 92752

No, blocking specific cases is not enough - sooner or later, someone will come up with a contrived case you didn't think of.

See this list of XSS attacks for the most common ones (other, still more exotic, may exist). You need to whitelist the allowed syntax instead of assuming that everything beside the known vectors should be OK.

Upvotes: 18

dan_waterworth
dan_waterworth

Reputation: 6441

myspace was hacked because of css expressions. Blacklisting won't work, Whitelisting is the only route.

Upvotes: 2

icanhasserver
icanhasserver

Reputation: 1064

In addition to those mentioned by Nick, you should also be on the look-out for JavaScript events, such as: "onload", "onclick",...

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630339

Unfortunately not, there are a variety of attacks available, for example executing JavaScript via the <img> element as well. I recommend using a XSS library for whatever platform you're on server-side.

Here's an example of what I mean:

<img src="javascript:alert('hi');">
<input type="image" src="javascript:alert('hi');">

...not those examples themselves are harmless, but you see how there are others ways to execute JavaScript. Which exploits work depends on the browser, but just be aware there are other methods out there.

Upvotes: 4

Related Questions