How to prevent XSS attack when h:outputFormat is used with escape=false? - xss

Am using JSF 1.2. I want to display a message to User which reads like this
"Please click here to login with your new password."
Code in my xhtml page,
<h:outputFormat value="#{msg.resetBackToLogin}" escape="false"></h:outputFormat>
And below is the code from my Property file.
Please click here to login with your new password.
Since, it contains special characters, am using h:outputFormat with escape=false. I felt, using h:commandLink and calling a bean method and redirecting there will simply add overhead.
As am using h:outputFormat with escape=false, this will lead to XSS attack. How can I prevent this if am sticking to h:outputFormat?

Related

prevent inline java script xss injection

I have a url like this
http://www.example.com/?input=userinput
although i did xss injection filters
strip_tags ();
but look at this , i take this input and put it in a url like this
imagine user could write this code at his user input section
onMouseOver%3dalert%2839793%29%2f%2f
This will add onMouseOver event to my url !!!
Please take a look at the OWASP XSS Prevention Cheat Sheet. It will explain all of this in detail:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
To answer the specific topic mentioned here, you need to url encode the input before printing it in the page as a part of the url. For other data inside HTML attributes you need to apply HTML attribute encoding and possibly javascriot encoding if it's in a event handler like onclick.

Mediawiki mass user delete/merge/block

I have 500 or so spambots and about 5 actual registered users on my wiki. I have used nuke to delete their pages but they just keep reposting. I have spambot registration under control using reCaptcha. Now, I just need a way to delete/block/merge about 500 users at once.
You could just delete the accounts from the user table manually, or at least disable their authentication info with a query such as:
UPDATE /*_*/user SET
user_password = '',
user_newpassword = '',
user_email = '',
user_token = ''
WHERE
/* condition to select the users you want to nuke */
(Replace /*_*/ with your $wgDBprefix, if any. Oh, and do make a backup first.)
Wiping out the user_password and user_newpassword fields prevents the user from logging in. Also wiping out user_email prevents them from requesting a new password via email, and wiping out user_token drops any active sessions they may have.
Update: Since I first posted this, I've had further experience of cleaning up large numbers of spam users and content from a MediaWiki installation. I've documented the method I used (which basically involves first deleting the users from the database, then wiping out up all the now-orphaned revisions, and finally running rebuildall.php to fix the link tables) in this answer on Webmasters Stack Exchange.
Alternatively, you might also find Extension:RegexBlock useful:
"RegexBlock is an extension that adds special page with the interface for blocking, viewing and unblocking user names and IP addresses using regular expressions."
There are risks involved in applying the solution in the accepted answer. The approach may damage your database! It incompletely removes users, doing nothing to preserve referential integrity, and will almost certainly cause display errors.
Here a much better solution is presented (a prerequisite is that you have installed the User merge extension):
I have a little awkward way to accomplish the bulk merge through a
work-around. Hope someone would find it useful! (Must have a little
string concatenation skills in spreadsheets; or one may use a python
or similar script; or use a text editor with bulk replacement
features)
Prepare a list of all SPAMuserIDs, store them in a spreadsheet or textfile. The list may be
prepared from the user creation logs. If you do have the
dB access, the Wiki_user table can be imported into a local list.
The post method used for submitting the Merge & Delete User form (by clicking the button) should be converted to a get method. This
will get us a long URL. See the second comment (by Matthew Simoneau)
dated 13/Jan/2009) at
http://www.mathworks.com/matlabcentral/newsreader/view_thread/242300
for the method.
The resulting URL string should be something like below:
http: //(Your Wiki domain)/Special:UserMerge?olduser=(OldUserNameHere)&newuser=(NewUserNameHere)&deleteuser=1&token=0d30d8b4033a9a523b9574ccf73abad8%2B\
Now, divide this URL into four sections:
A: http: //(Your Wiki domain)/Special:UserMerge?olduser=
B: (OldUserNameHere)
C: &newuser=(NewUserNameHere)&deleteuser=1
D: &token=0d30d8b4033a9a523b9574ccf73abad8%2B\
Now using a text editor or spreadsheet, prefix each spam userIDs with part A and Suffix each with Part C and D. Part C will include the
NewUser(which is a specially created single dummy userID). The Part D,
the Token string is a session-dependent token that will be changed per
user per session. So you will need to get a new token every time a new
session/batch of work is required.
With the above step, you should get a long list of URLs, each good to do a Merge&Delete operation for one user. We can now create a
simple HTML file, view it and use a batch downloader like DownThemAll
in Firefox.
Add two more pieces " Linktext" to each line at
beginning and end. Also add at top and at
bottom and save the file as (for eg:) userlist.html
Open the file in Firefox, use DownThemAll add-on and download all the files! Effectively, you are visiting the Merge&Delete page for
each user and clicking the button!
Although this might look a lengthy and tricky job at first, once you
follow this method, you can remove tens of thousands of users without
much manual efforts.
You can verify if the operation is going well by opening some of the
downloaded html files (or by looking through the recent changes in
another window).
One advantage is that it does not directly edit the
MySQL pages. Nor does it require direct database access.
I did a bit of rewriting to the quoted text, since the original text contains some flaws.

Is htmlspecialchars sufficient against low level XSS in my case?

I have added functionality to my admin so it preserves the URL which you tried to access before it asked you to login. So, if you go to:
/admin/foo/bar?baz
It'll redirect you to:
/admin/auth/login
After you login, before my function add-on you always went to /admin/user/profile. Right now, I save /admin/foo/bar?baz in a session variable, $_SESSION['from'].
In the login <form>, the hidden value takes the value of the session:
<input type="hidden" name="from" value="<?php echo htmlspecialchars($_SESSION['from'];)?>">
Then, after the form is submitted a redirect takes place:
header('Location: ' . $_POST['from'] );
I have seen other questions relating to XSS and htmlspecialchars and am aware it won't fix all possible XSS attempts, but would this work successfully against "low level" XSS attempts?
While there's no XSS attack here, if you're using a slightly older version of PHP, you'll open yourself up to HTTP header injection, which can be worse in some cases.
If you're fetching the URL-to-be-returned-to from the HTTP referrer, then you should be protected well enough by making sure the URL is one that you control by parsing it, then only storing the return path and query string. When performing the final redirect, you should make sure that the components of the path are properly URL encoded. You can store the return URL entirely in the session instead of punting it back out to the user to possibly manipulate during the login.

Externally linked images - How to prevent cross site scripting

On my site, I want to allow users to add reference to images which are hosted anywhere on the internet. These images can then be seen by all users of my site. As far as I understand, this could open the risk of cross site scripting, as in the following scenario:
User A adds a link to a gif which he hosts on his own webserver. This webserver is configured in such a way, that it returns javascript instead of the image.
User B opens the page containg the image. Instead of seeing the image, javascript is executed.
My current security messures are currently such, that both on save and open, all content is encoded.
I am using asp.net(c#) on the server and a lot of jquery on the client to build ui elements, including the generation of image tags.
Is this fear of mine correct? Am I missing any other important security loopholes here? And most important of all, how do I prevent this attack? The only secure way I can think of right now, is to webrequest the image url on the server and check if it contains anything else than binary data...
Checking the file is indeed an image won't help. An attacker could return one thing when the server requests and another when a potential victim makes the same request.
Having said that, as long as you restrict the URL to only ever be printed inside the src attribute of an img tag, then you have a CSRF flaw, but not an XSS one.
Someone could for instance create an "image" URL along the lines of:
http://yoursite.com/admin/?action=create_user&un=bob&pw=alice
Or, more realistically but more annoyingly; http://yoursite.com/logout/
If all sensitive actions (logging out, editing profiles, creating posts, changing language/theme) have tokens, then an attack vector like this wouldn't give the user any benefit.
But going back to your question; unless there's some current browser bug I can't think of you won't have XSS. Oh, remember to ensure their image URL doesn't include odd characters. ie: an image URL of "><script>alert(1)</script><!-- may obviously have bad effects. I presumed you know to escape that.
Your approach to security is incorrect.
Don't approach the topic as "I have a user input, so how can I prevent XSS". Rather approach it like it this: "I have user input - it should be restrictive as possible - i.e. allowing nothing through". Then based on that allow only what's absolutely essential - plain-text strings thoroughly sanitized to prevent anything but a URL, and the specific, necessary characters for URLS only. Then Once it is sanitized I should only allow images. Testing for that is hard because it can be easily tricked. However, it should still be tested for. Then because you're using an input field you should make sure that everything from javascript scripts and escape characters, HTML, XML and SQL injections are all converted to plaintext and rendered harmless and useless. Consider your users as being both idiots and hackers - that they'll input everything incorrectly and try to hack something into your input space.
Aside from that you may run into som legal issues with regard to copyright. Copyrighted images generally may not be used on other people's sites without the copyright owner's consent and permission - usually obtained in writing (or email). So allowing users the opportunity to simply lift images from a site could run the risk of allowing them to take copyrighted material and reposting it on your site without permission which is illegal. Some sites are okay with citing the source, others require a fee to be paid, and others will sue you and bring your whole domain down for copyright infringement.

Measures to prevent XSS vulnerability (like Twitter's one a few days before)

Even famous sites like Twitter are suffering from XSS vulnerability, what should we do to prevent this kind of attack?
The #1 Thing you can do is set your cookies to HTTP Only ... which at least protects against session cookie hijacking. Like someone stealing your cookie when you are likely admin of your own site.
The rest comes down to validating all user input.
RULE #0 - Never Insert Untrusted Data Except in Allowed Locations
RULE #1 - HTML Escape Before Inserting Untrusted Data into HTML Element Content
RULE #2 - Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes
RULE #3 - JavaScript Escape Before Inserting Untrusted Data into HTML JavaScript Data Values
RULE #4 - CSS Escape Before Inserting Untrusted Data into HTML Style Property Values
RULE #5 - URL Escape Before Inserting Untrusted Data into HTML URL Attributes
Very lengthy subject discussed in detail here:
http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
http://www.owasp.org/index.php/Cross_site_scripting
XSS is only one of many exploits and every web dev should learn the top 10 OWASP by heart imho
http://www.owasp.org/index.php/Top_10_2007
Just like you can make SQL injection a non-issue by using prepared statements, you can make XSS non-issue by using templating engine (DOM serializer) that does similar thing.
Design your application so that all output goes via templating engine. Make that templating engine HTML-escapes all data by default. This way you'll have system that's secure by default and does not rely on humans (and rest of the large system) being diligent in escaping of HTML.
I don't what you write your code with, but if your use asp.net, you are partly covered.
asp.net has what they call request validation that when enabled, it prevent malicious script to be introduced via user input.
But sometimes, you'll have to allow some kind of text editor like the one you typed in this question. In this case, you'll have to partly disable request validation to allow some "rich text" html to be input by the end user. In this case you will have to build some kind of white list filtering mechanism.
FYI, I don't know about others but Microsft has library called Anti-Xss.