There is a replacement for innerHtml in react: dangerouslySetInnerHTML.
Its name scares me.
In the React documents I read that:
In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.
But I sanitized my html with dompurify.
Does this completely protect me from XSS attacks?
But I sanitized my html with dompurify. Does this completely protect me from XSS attacks?
Likely yes, but it's not 100% guaranteed. If DOMPurify doesn't have bugs that will let XSS through, setting innerHTML or dangerouslySetInnerHTML with its results will be safe. DOMPurify is open-source and relatively popular, so if it did have such vulnerabilities, they would probably have been seen by now.
But, like with everything humans do, mistakes and coincidences that result in vulnerabilities not being seen are still possible.
Its name scares me.
It's supposed to. :-)
But I sanitized my html with dompurify. Does this completely protect me from XSS attacks?
It claims to:
DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML. DOMPurify will strip out everything that contains dangerous HTML and thereby prevent XSS attacks and other nastiness.
Whether you believe the claim is really your call to make. That said, sanitizing HTML is a well-studied problem so it's certainly possible to do. I make no claims for that particular library, which I haven't used or audited.
Related
I've question about dangerouslySetInnerHTML, is it dangerous to use it, when the html comes from my api or there is no difference and maybe attacked anyway? Thanks
When the HTML comes from any API is when it's most dangerous to use dangerouslySetInnerHTML.
This is covered in the docs:
In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.
Essentially, the issue is that if your server doesn't properly sanitise user input, you open your site up to attacks that React protects you from by default. For example, lets say you allow users to write comments on your website, and your API sends back those comments in HTML. If a user writes a comment like e.g.
my comment <img src="./404" onerror="alert('test')" />
then e.g. that JavaScript code might be executed whenever someone else views that comment, unless you remember to protect against that when processing the comments.
I'd recommend returning your data from your API in a different format (e.g. JSON), and then processing it into React elements on the frontend.
DangerouslySetInnerHTML
Yes, there's potential concern. Although, you'll gain some extra performance, since react doesn't compare the dangerouslySetInnerHTML field with Virtual DOM.
HOW EXACTLTY IT'S DANGEROUS?
If user add some malicious code into the comments / other inputs and this data renders on the dangerouslySetInnerHTML field via API, your application deal with XSS Attack ([https://owasp.org/www-community/attacks/xss/][1]).
HOW CAN POTENTIAL XSS BE PREVENTED?
Based on the best practices, it's best to sanitize the dangerouslySetInnerHTML element with some external modules like: DOMPurify (https://github.com/cure53/DOMPurify). It will remove/filter out the potentially malicious code from the HTML and prevent XSS.
According to some React documentation:
Improper use of the innerHTML can open you up to a cross-site
scripting (XSS) attack. Sanitizing user input for display is
notoriously error-prone, and failure to properly sanitize is one of
the leading causes of web vulnerabilities on the internet.
It seems that improper usage of the sanitizers and the innerHTML can expose the site XSS (Cross-Site Scripting) attacks.
On the other hand, according to other documentation (such as Gatsby or sanitizers itself), they are recommended:
The most straightforward way to prevent a XSS attack is to sanitize
the innerHTML string before dangerously setting it. Fortunately, there
are npm packages that can accomplish this; packages like sanitize-html
and DOMPurify.
What's the best and safest approach to avoid exposing an application to XSS attacks in React while also avoiding improper usage of sanitizers?
The two options are not in contrast with each other:
Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack
Emphasis on 'improper'.
sanitize the innerHTML string before dangerously setting it
Using an established and well-known library to sanitize the input before setting it is safe, because it is not an improper use of innerHTML.
I think the best, safest, and optimal approach, as it has been said through comments (especially by Corey Ward) is to avoid the usage of the dangerouslySetInnerHtml as long as it is possible prior to sanitizers. There are some amazing libraries such as markdown-to-jsx that extends the benefits of dangerouslySetInnerHtml (rendering HTML) without exposing the web to XSS attacks.
If the only solution for the use-case is to usedangerouslySetInnerHtml, then the solution must be using sanitizers, keeping in mind that it should be configured to keep styles, classes, and other desired behavior to avoid losing changes.
Are all known javascript framekillers vulnerable to XSS?
If yes, whould it be enough to sanitize window.location before breaking out of an iframe?
What would be the best way to do it?
Could you please give an example of possible XSS attack?
Thanks!
UPD: The reason I'm asking is because I got a vulnerability scan alert saying that JS framekiller code containing top.location.replace(document.location) is XSS vulnerable as document.location is controlled by the user.
What was right in their description: variables like 'document.location', 'window.location', 'self.location' are (partially) controlled by non-trusted user. This is because the choice of (sub)string in non-trusted domain and page location ('http://non.trusted.domain.com/mypage') and non-trusted request string ('http://my.domain.com/?myrequest') are formed according to user's intention that may not always be good for you.
What was wrong: this user-dependency is not necessarily XSS vulnerability. In fact, to form XSS you would need to have some code that effectively uses the content controlled by non-trusted user somewhere in your output stream for your page. In the example of simple framekiller like top.location.replace(window.location) there's no danger of XSS.
One example where we could talk about XSS would be code like
document.write('Click here')
Constructing URI like http://test.com/?dummy"<script>alert("Test")</script>"dummy and substituting instead of document.location by you code will trigger non-trusted script in trusted webpage's context. As constructing such URI and passing it unescaped is a challenge, real XSS would work in some more complex scenarios involving inserting non-trusted variables verbatim into flow of language directives, be it HTML, CSS, JS, PHP, etc.
Another well-known example of XSS-unaware development was history of inventing JSON. While JSON has got strong popularity (having me among its proponents too), initially it was intended as "quick-n-dirty" way of storing JS data as pieces of plain JS-formatted data structures. In order to "parse" JSON blocks, it was enough just to eval() them. Fortunately, people quickly recognised how flawed was this whole idea, so nowadays any knowledgeable developer in sane mind will always use proper safe JSON parser instead.
I am currently doing some research into XSS prevention but I am a bit confused about DOM based attacks. Most papers I have read about the subject give the example of injecting JavaScript through URL parameters to modify the DOM if the value is rendered in the page by JavaScript instead of server-side code.
However, it appears that all modern browsers encode all special characters given through URL parameters if rendered by JavaScript.
Does this mean DOM based XSS attacks cannot be performed unless against older browsers such as IE6?
They are absolutely possible. If you don't filter output that originated from your users, that output can be anything, including scripts. The browser doesn't have a way to know whether it is a legitimate script controlled by you or not.
It's not a matter of modern browsers, it's the basic principle that the browser treats every content that comes from your domain as legitimate to execute.
There are other aspects that are indeed blocked (sometimes, not always) by modern browsers (although security flaws always exist) like cross-domain scripting, 3rd party access to resources etc.
Forget about those old-school XSS exampls from 10 years ago. Programmers who write javascript to render page by taking something unescaped from query params have either been fired or switched to frameworks like angular/backbone a long time ago.
However, reflected/stored XSS still widely exists. This requires proper escaping from both server side and client side. Modern frameworks all provide good support for escaping sensitive characters when rendering the HTML. For example, when rendering views from model data, angular has $sce(strict contextual escaping) service (https://docs.angularjs.org/api/ng/service/$sce) to address possible XSS threats. backbone models also have methods like "model.escape(attribute)" (http://backbonejs.org/#Model-escape) to eliminate the XSS threats.
During a recient PCI audit the auditor said that we had major security risks because
It was possible to download static resources from our website such as images css and javascript without prior authentication.
Our javascript had comments in it.
Personally I think that this is not a security risk at all. The images css and javascript where not dynamically created and they contained no data on our backend, our customer details and on mechanisms.
The comments within the javascript were just simply explaining what the methods in the javascript file did. Which anyone who reads JS could have found out anyway.
How does that show "information leakage"?
Are comments within javascript really a security risk?
Depending on how strict the audit, downloading images etc without authentication COULD be seen as a security risk (think diagrams, charts, graphs...).
Removing comments in the javascript is like obfuscating the code: it makes it a bit harder, but still not impossible to understand what's going on. JavaScript should be seen as enhancing-only anyway, all your security should be (duplicated) at server-side. Having anyone understand what the JS does should not be considered a risk.
It depends on the content of the commentary. Because there is no way, without human intervention, to examine the content of comments to determine whether they are risky, the most efficient way to audit this is to declare all comments in client-facing source code to be risky.
The following are examples of potentially risky comments.
// doesn't really authenticate, placeholder for when we implement it.
myServer.authenticate(user,pass);
or
// don't forget to include the length,
//the server complains if it gets NaN or undefined.
function send_stuff(stuff, length) {
...
}
or
function doSomething() {
querystring = ""
//querystring = "?TRACING_MODE=true&"
...
//print_server_trace();
}
Another example might be if you include a source code history header, someone might be able to find some security weakness by examining the kinds of bugs that have been fixed. At least, a cracker might be able to better target his attacks, if he knows which attack vectors have already been closed.
Now, all of these examples are bad practices anyway (both the comments and the code), and the best way to prevent it is by having code reviews and good programmers. The first example is particularly bad, but innocent warnings to your team mates, like the second example, or commented-out debugging code, like the third, are the kinds of security holes that could slip through the net.
Without getting into if they are a security risk or not, minify your JS on production environment, this will prevent the "information leakage" and help (in some way at least) to secure the information of your website.
regarding the security risk, I don't think JS comments are a risk at all, every website content (static) can be downloaded without authentication. (unless defined otherwise)
Not if they only reveal how the code works. Any sufficiently determined person could find that out anyway.
That said, it is probably a good idea to minify the JavaScript; not because of security, but because it will reduce download times and therefore make your site a bit more responsive.
JavaScript comments can be. depends on your logic, but certainly as it is publically available, you are giving more visibility to the workings of your code.
There are other reasons for removing this as as well, such as file size, and as a result download size.
Tools such asd JSMin can help you remove the comments and perfrom a crude obfuscation of the code.