2

I have a few questions on encoding/escaping characters to protect against cross site scripting ( XSS ).

  1. Can the same character encoding used for HTML encoding be used for JavaScript ? For eg ..in HTML encoding < gets encoded as &lt; Can I use the same for JavaScript? Are there any built in JavaScript encoding apis?

  2. Apart from the characters < , > , ' , " , & what other characters should I consider for output encoding?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
RJD
  • 135
  • 3
  • 14

2 Answers2

3

Can the same character encoding used for html encoding be used for javascript?

No. HTML is not JavaScript.

are there any built in javascript encoding apis?

The only languages mentioned in the question tags are JavaScript and HTML. You should never generate JavaScript source code programatically from inside JS (there is always a better way to solve a problem where that is a possible solution).

For other languages, JSON encoding libraries are usually the way forward.

If you're generating HTML from JS then, again, you shouldn't be generating raw HTML. Use DOM (createTextNode, createElement, appendChild and friends) instead.

Apart from the characters < , > , ' , " , & what other characters should I consider for output encoding

For HTML text nodes and safe HTML attributes, that is all you need to worry about.

For other places in HTML, it depends on the place.

Protecting against XSS when you are taking a URL as user input and putting it in an href attribute has its own set of problems.

Protecting against XSS when you are putting user input inside an onclick attribute (generally not a good idea) has another set of problems.

OWASP is a good starting point.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for the response and sharing the links.Can you please share a sample of javascript encoding ? – RJD Aug 05 '15 at 19:54
  • No. "javascript encoding" is too vague a term. Encoding for JavaScript? If so, which bit of JavaScript? From what language? Encoding from JavaScript? What's the target? – Quentin Aug 05 '15 at 23:13
0

Encoding to prevent attacks in the XSS family depends on the contextual syntax into which you're injecting user-supplied content. If you're dropping content into JavaScript source, then no, you cannot use HTML escapes because HTML syntax is completely different than JavaScript syntax. Similarly, if you're including user-supplied content in HTML, you can't use JavaScript syntax to escape it.

Probably the best way to include user-supplied content in JavaScript source is to use a JSON encoding tool.

Pointy
  • 405,095
  • 59
  • 585
  • 614