Secure database entry against XSS - javascript

I'm creating an app that retrieves the text within a tweet, store it in the database and then display it on the browser.
The problem is that I'm thinking if the text has PHP tags or HTML tags it might be a security breach there.
I looked into strip_tags() but saw some bad reviews. I also saw suggestions to HTML Purifier but it was last updated years ago.
So my question is how can I be 100% secure that if the tweet text is "<script> something_bad() </script>" it won't matter?
To state the obvious the tweets are sent to the database from users so I don't want to check all individually before displaying them.

You are NEVER 100% secure, however you should take a look at this. If you use ENT_QUOTES parameter too, currently there are no ways to inject ANY XSS on your website if you're using valid charset (and your users don't use outdated browsers). However, if you want to allow people to only post SOME html tags into their "Tweet" (for example <b> for bold text), you will need to take a deep look at EACH whitelisted tag.

You've passed the first stage which is to recognise that there is a potential issue and skipped straight to trying to find a solution, without stopping to think about how you want to deal the scenario of the content. This is a critical pre-cusrsor to solving the problem.
The general rule is that you validate input and escape output
validate input
- decide whether to accept or reject it it in its entirety)
if (htmlentities($input) != $input) {
die "yuck! that tastes bad";
}
escape output
- transform the data appropriately according to where its going.
If you simply....
print "<script> something_bad() </script>";
That would be bad, but....
print JSONencode(htmlentities("<script> something_bad() </script>"));
...then you'd would have done something very strange at the front end to make the client susceptivble to a stored XSS attack.

If you're outputting to HTML (and I recommend you always do), simply HTML encode on output to the page.
As client script code is only dangerous when interpreted by the browser, it only needs to be encoded on output. After all, to the database <script> is just text. To the browser <script> tells the browser to interpret the following text as executable code, which is why you should encode it to <script>.
The OWASP XSS Prevention Cheat Sheet shows how you should do this properly depending on output context. Things get complicated when outputting to JavaScript (you may need to hex encode and HTML encode in the right order), so it is often much easier to always output to a HTML tag and then read that tag using JavaScript in the DOM rather than inserting dynamic data in scripts directly.
At the very minimum you should be encoding the < & characters and specifying the charset in metatag/HTTP header to avoid UTF7 XSS.

You need to convert the HTML characters <, > (mainly) into their HTML equivalents <, >.
This will make a < and > be displayed in the browser, but not executed - ie: if you look at the source an example may be <script>alert('xss')</script>.
Before you input your data into your database - or on output - use htmlentities().
Further reading: https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

Related

Exploit an XSS when injected Javascript code is returned capitalized

I have found an XSS vulnerability in a piece of code, as I'm able to inject Javascript code in it.
I want to generate the simple alert PoC, but I'm not able to do so as the JS code returned by the server is always capitalized. For example, when I inject the following code:
Text sample <script>alert(document.cookie)</script>
The server respond with the page containing the following:
Text sample <script>ALERT(DOCUMENT.COOKIE)</script>
Which obviously does not print the cookie as JS is case sensitive.
Is there a way to transform the code injected in lowercase before it gets rendered or a similar solution?
Note: Javascript is enabled and if I modify manually the code in the browser console transforming it in lowercase, I'm getting the cookie printed.
No, you do not have control over the transformation and you cannot somehow change it back to lowercase before execution.
However, you can inject JavaScript code which is not affected by the capitalisation of the characters. See jsfuck, which doesn't need alphanumeric source characters at all, and use a similar approach (you can actually use digits and some characters).

How to check if a string contains JavaScript code?

I'm doing a forum like web app. Users are allowed to submit rich html text to server such as p tag, div tag, etc. In order to keep the format, server will write these tags back to the users' browser directly(without html encoded). So, I must do a potential dangerous script check to avoid XSS. Any JavaScript code is supposed to be dangerous and not allowed. So, How to detect them or any other better solution?
dangerous example 1:
<script>alert('1')</script>
dangerous example 2:
<script src="..."></script>
dangerous example 3:
click me
Use an HTML Parser
Your requirements are straightforward:
You must disallow all <script> tags, but keep certain rich HTML tags.
You must be able to escape inline Javascript in links. i.e. stringify it or strip the unsafe attributes altogether.
The correct way to handle all of these is to employ a modern standards-compliant HTML parser that is able to syntactically analyse the structure of the rich HTML sent over, identifying the tags sent over and discovering the raw values in attributes. This is, in fact, how sanitisation, as one of the comments mentions, is done.
There are a number of pre-existing HTML parsers that are designed to target XSS-unsafe input. The npm library js-xss, for example, appears to be able to do exactly what you want:
Whitelisting only specific tags
Modify unsafe attributes to return a default value
You can even run this server-side as a command line utility.
Similar libraries already exist for most languages, and you should do a thorough search of your preferred language's package repository. Alternatively, you can launch a subprocess and collect your results directly from js-xss from the command line.
Avoid using regular expressions to parse HTML naively - while it is true most HTML parsers end up using regular expressions under the hood, they do so in a fairly limited fashion for strictly well-defined grammars after correctly lexing them.
Use this regex
<script([^'"]|"(\\.|[^"\\])*"|'(\\.|[^'\\])*')*?<\/script>
for detecting all types of <script> tag
but I suggest using a iframe in sandbox mode to show ALL html code, by doing that you prevent javascript code from being able to do anything bad.
http://www.w3schools.com/tags/att_iframe_sandbox.asp
I hope this helps!

What HTML tags would be considered dangerous if stored in SQL Server?

Considering issues like CSRF, XSS, SQL Injection...
Site: ASP.net, SQL Server 2012
I'm reading a somewhat old page from MS: https://msdn.microsoft.com/en-us/library/ff649310.aspx#paght000004_step4
If I have a parametrized query, and one of my fields is for holding HTML, would a simple replace on certain tags do the trick?
For example, a user can type into a WYSIWYG textarea, make certain things bold, or create bullets, etc.
I want to be able to display the results from a SELECT query, so even if I HTMLEncoded it, it'll have to be HTMLDecoded.
What about a UDF that cycles through a list of scenarios? I'm curious as to the best way to deal with the seemingly sneaky ones mentioned on that page:
Quote:
An attacker can use HTML attributes such as src, lowsrc, style, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the tag can be a source of injection, as shown in the following examples.
<img src="javascript:alert('hello');">
<img src="java
script:alert('hello');">
<img src="java
script:alert('hello');">
An attacker can also use the <style> tag to inject a script by changing the MIME type as shown in the following.
<style TYPE="text/javascript">
alert('hello');
</style>
So ultimately two questions:
Best way to deal with this from within the INSERT statement itself.
Best way to deal with this from code-behind.
Best way to deal with this from within the INSERT statement itself.
None. That's not where you should do it.
Best way to deal with this from code-behind.
Use a white-list, not a black-list. HTML encode everything, then decode specific tags that are allowed.
It's reasonable to be able to specify some tags that can be used safely, but it's not reasonable to be able to catch every possible exploit.
What HTML tags would be considered dangerous if stored in SQL Server?
None. SQL Server does not understand, nor try to interpret HTML tags. A HTML tag is just text.
However, HTML tags can be dangerous if output to a HTML page, because they can contain script.
If you want a user to be able to enter rich text, the following approaches should be considered:
Allow users (or the editor they are using) to generate BBCode, not HTML directly. When you output their BBCode markup, you convert any recognised tags to HTML without attributes that contain script, and any HTML to entities (& to &, etc).
Use a tried and tested HTML sanitizer to remove "unsafe" markup from your stored input in combination with a Content Security Policy. You must do both otherwise any gaps (and there will be gaps) in the sanitizer could allow an attack, and not all browsers full support CSP yet (IE).
Note that these should be both be done on point of output. Store the text "as is" in your database, simply encode and process for the correct format when output to the page.
Sanitize html both on the client and on the server before you stuff any strings into SQL.
Client side:
TinyMCE - does this automatically
CKEditor - does this automatically
Server side:
Pretty easy to do this with Node, or the language/platform of your choice.
https://www.realwebsite.com
the link above shows www.realwebsite.com while it actually takes you to www.dangerouswebsite.com...
<a '
href="https://www.dangerouswebsite.com">
https://www.realwebsite.com
<'/a>
do not include the random ' in the code I put it there to bypass activating the code so you can see the code instead of just the link. (btw most websites block this or anything if you add stuff like onload="alert('TEXT')" but it can still be used to trick people into going to dangerous websites... (although its real website pops up on the bottom of your browser, some people don't check it or don't understand what it means.))

I am getting a JavaScript alert in my project that I didn't create, threatening me?

This morning I woke up to a JavaScript alert on a project of mine that runs KnockoutJS, jQuery, and Underscore.js. It says "I can run any JavaScript of my choice on your users' browsers". The only third-party JavaScript I am downloading is Typekit, and removing that does not make this go away. I've searched my JavaScript and vendor JavaScript and this string does not come back up matching anything.
How would you troubleshoot this and/or is this something that is known to occur?
If you have a database for your application, that would be the next place to check. I'm guessing somebody found and exploited an Injection vulnerability (either un-sanitized HTML input or SQL) and injected the script into a page via the database.
The last place would be to look at the ruby code to see if somehow a malicious user modified your source.
You obviously take an input from user and then outputting it back as part of HTML without quoting or sanitizing. There's two quick checks to do:
1) Open source of page that outputs this alert and search inside source for exact text of alert - this should give you clear indication of what user-filled field is compromised.
2) To be sure, search all other fields in your database generated by users (login names, text of comments, etc.) for words "script" and "alert".
For future: always sanitize your input (remove HTML tags) before inserting it in HTML page OR escape symbols as entities according to standards OR explicitly treat is a plain text by assigning it to value of text node in DOM.
It sounds like a hack attempt on your site. Check any databases, text files, etc. that are being used that are receiving user input. It sounds like you're not checking what's being posted to your server I'm guessing.

Preventing Javascript and XSS attacks

I'm xss-proofing my web site for javascript and xss attacks. It's written in ASP.NET Webforms.
The main part I'd like to test is a user control that has a textbox (tinyMCE attached to it).
Users can submit stories to site by writing in this textbox. I had to set validateRequest to false since I want to get users' stories in HMTL (tinyMCE).
How should I prevent javascript-xss attacks? Since users' stories are HMTL texts, I cannot use Server.HtmlEncode on their stories. In general, what's the safe way to receive HTML content from user, save and then display it to users?
If one user puts malicious code in the textbox and submits it, is there a chance that this could harm other people who view that text?
Thanks.
If you don't clean what the user puts in the textbox and submits, then yes, there is a chance for harm to be done.
You might want to check out the Microsoft Anti-Cross Site Scripting Library, as it is designed to help developers prevent just such attacks.
Also worth taking a look at is OWASP's Cross-site Scripting (XSS)
You might want to look into HttpUtility.HtmlEncode and HttpUtility.HtmlDecode as well. I just wrote a quick test, and it looks like it might address your concern in the comment below (about how to display the data to other users in the right format):
string htmlString = "<b>This is a test string</b><script>alert(\"alert!\")</script> and some other text with markup <ol><li>1234235</li></ol>";
string encodedString = HttpUtility.HtmlEncode(htmlString);
// result = <b>This is a test string</b><script>alert("alert!")</script> and some other text with markup <ol><li>1234235</li></ol>
string decodedString = HttpUtility.HtmlDecode(encodedString);
// result = <b>This is a test string</b><script>alert("alert!")</script> and some other text with markup <ol><li>1234235</li></ol>
ASP.NET Controls and HTMLEncode
I was going to post the information I had from my class, but I found a link that lists the exact same thing (for 1.1 and 2.0), so I'll post the link for easier reference. You can probably get more information on a specific control not listed (or 3.0/3.5/4.0 versions if they've changed) by looking on MSDN, but this should serve as a quick start guide for you, at least. Let me know if you need more information and I'll see what I can find.
ASP.NET Controls Default HTML Encoding
Here's a more comprehensive list from one of the MSDN blogs: Which ASP.NET Controls Automatically Encodes?
I would go with storing it encoded in database, then when showing Decode it and replace only the < with < if you say you need to preserve other things.
As far as I know, if you replace the < XSS is not really possible as any JS code must be inside <script> tags to be executed and by replacing, you'll get this in the HTML source:
<script> and the user will see <script> on the screen as the browser will parse the < entity.
This said, if you allow users to post "raw" HTML e.g. <b>this section is bolded</b> then you'll have to create "white list" of allowed tags then manually replace the < with the proper HTML for example:
string[] allowedTags = new string[] { "a", "b", "img" };
foreach (allowedTag in allowedTags)
output = output.Replace("<" + allowedTag, "<" + allowedTag);
Have you seen the OWASP guide on this
The best way would be to have an white list of allowed tags instead of a trying to come up with a way to prevent all script tags.
One solution on how to do this is here How do I filter all HTML tags except a certain whitelist?
But you also need to be aware people might have a link to external script via an image tag with a URL to their own server. See examples here http://ha.ckers.org/xss.html of the different types of attacks you need to defend against

Categories