What are the risks of using Javascript and how to avoid them?
Javascript runs on the client side so the biggest risk is for the client. An example of a risk is that their cookie could be stolen so that another user can impersonate them. A common method of attack is to inject Javascript into the page via a form submission. To prevent this you should ensure that you always properly escape HTML output.
Your server side security should not depend on the security of the Javascript. You should assume that your attacker can and will change the HTML/CSS/Javascript on your pages to try to view information that is not normally visible, and they will send data to your server that shouldn't be possible to send via the normal interface. To protect against this you should always validate all user inputs - treat it as completely untrusted data. Don't rely on assumptions about the content your users will send you - always explicitly check the assumptions you require to be true.
There are no risks. Just possible programmer's errors. One error I can think of is to forget to url encode parameters sent to the server and it gets the wrong values. But the real security risk is in the server side code, not javascript.
One of the most common errors is HTML injection, allowing third parties to inject JavaScript into your security context. That allows an attacker to control what a user does on your site, completely breaking account security.
Whilst there has been some slow progress trying to get web authors to remember to HTML-encode strings they output into web pages at the server side (eg htmlspecialchars
in PHP), a new generation of webapps are using the same dumb string-concatenation hacks to create content at the client-side using JavaScript:
somediv.innerHTML= '<p>Hello, '+name+'</p>';
often using jQuery:
$('table').append('<tr title="'+row.title+'"><td>'+row.description+'</td></tr>');
This is just as vulnerable as server-side HTML injection and authors really need to stop building content this way. You can HTML-encode text content at the client side, but since JS doesn't have a built-in HTML encoder you'd have to do it yourself:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
somediv.innerHTML= '<p>Hello, '+encodeHTML(name)+'</p>';
However it's usually much better to use the available DOM methods and properties that obviate the need for escaping:
var p= document.createElement('p');
p.appendChild(document.createTextNode('Hello, '+name);
and with jQuery use attr()
, text()
and the creation shortcuts:
$('table').append(
$('<tr>', {title: row.title}).append(
$('<td>', {text: row.description})
)
);