How to recover a site after an xss attack? - security

Recently i was studying about the XSS attacks and how devastating they can be on a website.
What surprised me was that, web (even SO) is full about how to prevent xss attack but there is no relevant resource on how to recover a website, after it has been attacked through xss.
There are some things which i came across like :
upload the backup website code back on server
download the entire site and manually look for any malicious script
but these doesn't sound good enough....i mean, isn't there any other professionaly active method to recover the sites once hacked???

With XSS the code is not actually modified. Instead what usually happens are one of two scenarios: reflected and stored XSS.
In reflected XSS, there is some parameter in the request (usually a query string parameter) that gets echoed onto the page without being sanitized. This could lead to an attacker providing a malicious link to a user, and them clicking and having their session hijacked.
In stored XSS, the attacker finds some way to persist a malicious string (usually stored in a database, in the form of a forum post or website comment) that other users will come across when viewing this site. That script is then executed in the context of the user that viewed the page, and the attacker could again hijack the session.
To "recover" from reflected XSS - you would want to fix the reflected parameter (do something like output encoding) and invalidate all sessions, making users have to log in again.
To "recover" from reflected XSS - you would want to identify where the malicious code was provided, add sanitization of the input and encoding of the output of that data. Then clean the database of these malicious values, then invalidate all sessions, forcing users to log back in again.

#Stefan_H got it right. (+1)
Indeed you only need to recover from stored XSS.
However, what you also need to consider, is that store XSS attack is often just a symptom of the actual illness.
Simply put, to execute such XSS attacks, an attacker must have high-level access to your website/server resources. This means that - besides the malicious XSS code - your site also holds a backdoor shell which allows the attacker that level of access.
And so, in fact, you don't need to recover from XSS but from the backdoor shell. Failing to do so will allow the hacker to re-inject your site, even once the code was sanitized.
Some backdoors exist on a site level, others will affect whole servers. The type of control they provide will vary but - in most cases - they will allow total access to most website resources. This will lead to:
XSS and other malware injection
Hijacking the site/server for the purpose of DDoS (joining a Botnet)
Data theft
Eventual defacement
To prevent re-occurring attacks you`ll need to:
Use some very early backup (you don't know how long the backdoor was present in your file system)
Better yet, use some kind of backdoor detection tool (there are some free ones but few are actually good)
Understanding how the shell got there in the 1st place (RFI and password hacks are the two prime suspects)
GL

Related

Understanding Blind Vulnerabilities

There is something i wonder. I am giving an example of XSS. We say it is divided into 3 types. Blind, Reflected and stored. There is no one who does not know reflected and stored. We say that the attacker is not informed about the vulnerable with a blind at the beginning of it's name, but if there is no information, how does the attacker understand that there is any vulnerable?
Thank you from now.
In blind XSS the attacker typically doesn't know if his attack will succeed at first.
You can think of it like setting up a trap. You don't know if it will succeed, or if the victim has protection, you are blind.
Actually, blind XSS vulnerabilities are a variant of stored (persistent) XSS vulnerabilities. The attacker's input is saved by a web server and then executed as a malicious script in another application or in another part of the application.
For example, an attacker injects a malicious payload into a contact/feedback form and POST it (setting up a trap). Let's say the info sent is then served by another application or in another part of the app:
The admin is opening his admin panel/dashboard to view feedback from his users. When the administrator of the application is reviewing the feedback entries - the attacker’s payload will be loaded and executed.
The attacker was blind - he didn't know if the server side of that form sanitize the input, or if the "admin panel" of the application has any protection against JS execution.
Example of web applications and web pages where blind XSS attacks can occur:
Contact/Feedback pages
Log viewers
Exception handlers
Chat applications / forums
Customer ticket applications
Web Application Firewalls
Any application that requires user moderation
In the case of blind XSS, the payload can be executed after a long period of time when the administrator visits the vulnerable page. It can take hours, days, or even weeks until the payload is executed.
Therefore, this type of vulnerability is much harder to detect compared to other reflected XSS vulnerabilities where the input is reflected immediately.

Why do some consider 2nd-order (aka persistent) XSS to not be true XSS?

I'm reading "The Web Application Hacker's Handbook", and it talks about the differences between 1st-order (aka reflected) XSS and 2nd-order (aka persistent) XSS. It mentions how reflected XSS takes advantage of incomplete or nonexistent sanitization of query string params to execute arbitrary scripts into the user's DOM without persisting any malicious code to the application's database, and how 2nd-order XSS does in fact persist that malicious code, to be executed in the user's DOM at some later time.
My question relates to the author's desription of 2nd-order XSS (on page 438, if you've got a copy handy). The description from the book states that:
Attacks against stored XSS vulnerabilities typically involve at least
two requests to the application. In the first, the attacker posts some
crafted data containing malicious code that the application stores. In
the second, a victim views a page containing the attacker’s data, and
the malicious code is executed when the script is executed in the
victim’s browser. For this reason, the vulnerability is also sometimes
called second-order cross-site scripting. (In this instance, “XSS” is
really a misnomer, because the attack has no cross-site element. [emphasis mine] The
name is widely used, however, so we will retain it here.)
In 2nd-order XSS, the malicious code that the attacker still injects is (presumably) still some arbitrary script pointing to an external server (for example, injecting an img tag with a src attribute of "http://www.malicioussite.dom" + document.cookie). I'm confused why the author then states that this attack has no cross-site element. Making a request to the malicious external server seems to me like a proper cross-site element. Am I missing something?
To me, 'cross-site' in XSS means that the malicious script itself is directly sent from another site. Like for example in case of reflected XSS on an url parameter, a malicious website A.com can craft a link to the victim website B.com with its attack in a vulnerable parameter of B, and when a user visits A and clicks the link, he will execute the script on B.
So I think it's not about what the malicious script is doing, it's where it comes from (and how).
In case of stored XSS, the script is usually entered on the vulnerable website directly, however that may not always be the case, such maintaining the original 'cross-site' element. But it doesn't matter, the name is the same, because the underlying problem and also the solution in code are the same, so the name of the vulnerability is the same too. :)
Whatever people call it though, the important thing is to avoid it. :)

When to use random tokens to prevent XSS?

This isn't a language specific question, but I am using PHP5.
I am working on a project that has some amount of PII. Legally we are required to secure this data from hacking attempts, and because of that I have been researching best practices for defending common attack types. Obviously all database calls are using parameterized queries, and all data provided by the user is sanitized to prevent injection. I have also implemented sessions and methods to prevent session hijacking.
When it comes to defending against XSS attacks on forms, best practice seems to be to include a hidden input with a form token, then after the post to check the tokens match. There are further ways to make this more secure.
I have imagined one type of attack and haven't found a solution for it. What if a malicious site loads a hidden iframe pointed at my site (eg, view-member.php?id=1234) and because the victim user is logged into my site, their session continues in that iframe. What is stopping this malicious site from iterating through the IDs and ripping the data to get ahold of PII? Should I be creating a unique token for each page view, and checking that token when the page loads?
I am not 100% sure, but assuming my site is using HTTPS, the browser should warn the user and/or prevent the connection. Is that correct? Is that enough security?
In fact, everytime you present a form or any kind of interaction, you should include a randomized, verifiable piece of information that changes every time. This is not for preventing XSS but CSRF: https://en.wikipedia.org/wiki/Cross-site_request_forgery
The main problem is: An attacker can just send automated requests to your input-handling script without going through the "pain" of filling in your form manually (or even visit your page).
However, you won't prevent XSS attacks with this technique, as XSS attacks are mainly user input containing executable code (javascript) that is not filtered by the input validation. So to prevent XSS as well, you should always make sure not to deliver unfiltered user-generated content anywhere.
HTTPS won't help you in either case unless you use client-side certificates that allow access to your website only from trusted clients. HTTPS mainly acts as a transmission scrambler and identity verifier but does not prevent a bot from sending valid (but malicious) data to your form.
Hosting a website in an iFrame does not grant the attacker the permission to read cookies or information from the target page (that would be awful) as long as you follow the same-origin policy: https://en.wikipedia.org/wiki/Same-origin_policy
With this, only domains you whitelist will get access to information hosted on your page.

How do I protect sensitive information from cross site access?

My web application displays some sensitive information to a logged in user. The user visits another site without explicitly logging out of my site first. How do I ensure that the other site can not access the sensitive information without accept from me or the user?
If for example my sensitive data is in JavaScript format, the other site can include it in a script tag and read the side effects. I could continue on building a blacklist, but I do not want to enumerate what is unsafe. I want to know what is safe, but I can not find any documentation of this.
UPDATE: In my example JavaScript from the victim site was executed on the attacker's site, not the other way around, which would have been Cross Site Scripting.
Another example is images, where any other site can read the width and height, but I don't think they can read the content, but they can display it.
A third example is that everything without an X-Frame-Options header can be loaded into an iframe, and from there it is possible to steal the data by tricking the user into doing drag-and-drop or copy-and-paste.
The key point of Cross Site Attack is to ensure that your input from user which is going to be displayed, is legal, not containing some scripts. You may stop it at the beginning.
If for example my sensitive data is in JavaScript format, the other site can include it in a script tag
Yep! So don't put it in JavaScript/JSONP format.
The usual fix for passing back JSON or JS code is to put something unexecutable at the front to cause a syntax error or a hang (for(;;); is popular). So including the resource as a <script> doesn't get the attacker anywhere. When you access it from your own site you can fetch it with an XMLHttpRequest and chop off the prefix before evaluating it.
(A workaround that doesn't work is checking window.location in the returned script: when you're being included in an attacker's page they have control of the JavaScript environment and could sabotage the built-in objects to do unexpected things.)
Since I did not get the answer I was looking for here, I asked in another forum an got the answer. It is here:
https://groups.google.com/forum/?fromgroups=#!topic/mozilla.dev.security/9U6HTOh-p4g
I also found this page which answers my question:
http://code.google.com/p/browsersec/wiki/Part2#Life_outside_same-origin_rules
First of all like superpdm states, design your app from the ground up to ensure that either the sensitive information is not stored on the client side in the first place or that it is unintelligible to a malicious users.
Additionally, for items of data you don't have much control over, you can take advantage of inbuilt HTTP controls like HttpOnly that tries to ensure that client-side scripts will not have access to cookies like your session token and so forth. Setting httpOnly on your cookies will go a long way to ensure malicious vbscripts, javascripts etc will not read or modify your client-side tokens.
I think some confusion is still in our web-security knowledge world. You are afraid of Cross Site Request Forgery, and yet describing and looking for solution to Cross Site Scripting.
Cross Site Scripting is a vulnerability that allows malicious person to inject some unwanted content into your site. It may be some text, but it also may be some JS code or VB or Java Applet (I mentioned applets because they can be used to circumvent protection provided by the httpOnly flag). And thus if your aware user clicks on the malicious link he may get his data stolen. It depends on amount of sensitive data presented to the user. Clicking on a link is not only attack vector for XSS attack, If you present to users unfiltered contents provided by other users, someone may also inject some evil code and do some damage. He does not need to steal someone's cookie to get what he wants. And it has notnig to do with visiting other site while still being logged to your app. I recommend:XSS
Cross Site Request Forgery is a vulnerability that allows someone to construct specially crafted form and present it to Logged in user, user after submitting this form may execute operation in your app that he didin't intended. Operation may be transfer, password change, or user add. And this is the threat you are worried about, if user holds session with your app and visits site with such form which gets auto-submited with JS such request gets authenticated, and operation executed. And httpOnly will not protect from it because attacker does not need to access sessionId stored in cookies. I recommend: CSRF

What common web exploits should I know about? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm pretty green still when it comes to web programming, I've spent most of my time on client applications. So I'm curious about the common exploits I should fear/test for in my site.
I'm posting the OWASP Top 2007 abbreviated list here so people don't have to look through to another link and in case the source goes down.
Cross Site Scripting (XSS)
XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute script in the victim's browser which can hijack user sessions, deface web sites, possibly introduce worms, etc.
Injection Flaws
Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the interpreter into executing unintended commands or changing data.
Malicious File Execution
Code vulnerable to remote file inclusion (RFI) allows attackers to include hostile code and data, resulting in devastating attacks, such as total server compromise. Malicious file execution attacks affect PHP, XML and any framework which accepts filenames or files from users.
Insecure Direct Object Reference
A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. Attackers can manipulate those references to access other objects without authorization.
Cross Site Request Forgery (CSRF)
A CSRF attack forces a logged-on victim's browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim's browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks.
Information Leakage and Improper Error Handling
Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Attackers use this weakness to steal sensitive data, or conduct more serious attacks.
Broken Authentication and Session Management
Account credentials and session tokens are often not properly protected. Attackers compromise passwords, keys, or authentication tokens to assume other users' identities.
Insecure Cryptographic Storage
Web applications rarely use cryptographic functions properly to protect data and credentials. Attackers use weakly protected data to conduct identity theft and other crimes, such as credit card fraud.
Insecure Communications
Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications.
Failure to Restrict URL Access
Frequently, an application only protects sensitive functionality by preventing the display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized operations by accessing those URLs directly.
The Open Web Application Security Project
-Adam
OWASP keeps a list of the Top 10 web attacks to watch our for, in addition to a ton of other useful security information for web development.
These three are the most important:
Cross Site Request Forgery
Cross Site Scripting
SQL injection
Everyone's going to say "SQL Injection", because it's the scariest-sounding vulnerability and the easiest one to get your head around. Cross-Site Scripting (XSS) is going to come in second place, because it's also easy to understand. "Poor input validation" isn't a vulnerability, but rather an evaluation of a security best practice.
Let's try this from a different perspective. Here are features that, when implemented in a web application, are likely to mess you up:
Dynamic SQL (for instance, UI query builders). By now, you probably know that the only reliably safe way to use SQL in a web app is to use parameterized queries, where you explicitly bind each parameter in the query to a variable. The places where I see web apps most frequently break this rule is when the malicious input isn't an obvious parameter (like a name), but rather a query attribute. An obvious example are the iTunes-like "Smart Playlist" query builders you see on search sites, where things like where-clause operators are passed directly to the backend. Another great rock to turn over are table column sorts, where you'll see things like DESC exposed in HTTP parameters.
File upload. File upload messes people up because file pathnames look suspiciously like URL pathnames, and because web servers make it easy to implement the "download" part just by aiming URLs at directories on the filesystem. 7 out of 10 upload handlers we test allow attackers to access arbitrary files on the server, because the app developers assumed the same permissions were applied to the filesystem "open()" call as are applied to queries.
Password storage. If your application can mail me back my raw password when I lose it, you fail. There's a single safe reliable answer for password storage, which is bcrypt; if you're using PHP, you probably want PHPpass.
Random number generation. A classic attack on web apps: reset another user's password, and, because the app is using the system's "rand()" function, which is not crypto-strong, the password is predictable. This also applies anywhere you're doing cryptography. Which, by the way, you shouldn't be doing: if you're relying on crypto anywhere, you're very likely vulnerable.
Dynamic output. People put too much faith in input validation. Your chances of scrubbing user inputs of all possible metacharacters, especially in the real world, where metacharacters are necessary parts of user input, are low. A much better approach is to have a consistent regime of filtering database outputs and transforming them into HTML entities, like quot, gt, and lt. Rails will do this for you automatically.
Email. Plenty of applications implement some sort of outbound mail capability that enable an attacker to either create an anonymous account, or use no account at all, to send attacker-controlled email to arbitrary email addresses.
Beyond these features, the #1 mistake you are likely to make in your application is to expose a database row ID somewhere, so that user X can see data for user Y simply by changing a number from "5" to "6".
bool UserCredentialsOK(User user)
{
if (user.Name == "modesty")
return false;
else
// perform other checks
}
SQL INJECTION ATTACKS. They are easy to avoid but all too common.
NEVER EVER EVER EVER (did I mention "ever"?) trust user information passed to you from form elements. If your data is not vetted before being passed into other logical layers of your application, you might as well give the keys to your site to a stranger on the street.
You do not mention what platform you are on but if on ASP.NET get a start with good ol' Scott Guthrie and his article "Tip/Trick: Guard Against SQL Injection Attacks".
After that you need to consider what type of data you will permit users to submit into and eventually out of your database. If you permit HTML to be inserted and then later presented you are wide-open for Cross Site Scripting attacks (known as XSS).
Those are the two that come to mind for me, but our very own Jeff Atwood had a good article at Coding Horror with a review of the book "19 Deadly Sins of Software Security".
Most people here have mentioned SQL Injection and XSS, which is kind of correct, but don't be fooled - the most important things you need to worry about as a web developer is INPUT VALIDATION, which is where XSS and SQL Injection stem from.
For instance, if you have a form field that will only ever accept integers, make sure you're implementing something at both the client-side AND the server-side to sanitise the data.
Check and double check any input data especially if it's going to end up in an SQL query. I suggest building an escaper function and wrap it around anything going into a query. For instance:
$query = "SELECT field1, field2 FROM table1 WHERE field1 = '" . myescapefunc($userinput) . "'";
Likewise, if you're going to display any user-inputted information onto a webpage, make sure you've stripped any <script> tags or anything else that might result in Javascript execution (such as onLoad= onMouseOver= etc. attributes on tags).
This is also a short little presentation on security by one of wordpress's core developers.
Security in wordpress
it covers all of the basic security problems in web apps.
The most common are probably database injection attacks and cross-site scripting attacks; mainly because those are the easiest to accomplish (that's likely because those are the ones programmers are laziest about).
You can see even on this site that the most damaging things you'll be looking after involve code injection into your application, so XSS (Cross Site Scripting) and SQL injection (#Patrick's suggestions) are your biggest concerns.
Basically you're going to want to make sure that if your application allows for a user to inject any code whatsoever, it's regulated and tested to be sure that only things you're sure you want to allow (an html link, image, etc) are passed, and nothing else is executed.
SQL Injection. Cross Site Scripting.
Using stored procedures and/or parameterized queries will go a long way in protecting you from sql injection. Also do NOT have your web app access the database as sa or dbo - set a up a standard user account and set the permissions.
AS for XSS (cross site scripting) ASP.NET has some built in protections. The best thing is to filter input using validation controls and Regex.
I'm no expert, but from what I learned so far the golden rule is not to trust any user data (GET, POST, COOKIE). Common attack types and how to save yourself:
SQL Injection Attack: Use prepared queries
Cross Site Scripting: Send no user data to browser without filtering/escaping first. This also includes user data stored in database, which originally came from users.

Resources