is there any HTTP-header to disable Javascript for a specific page?
My website delivers user-generated HTML-content (that is why I cannot just use htmlenitities) and I would like to prevent scripting (JavaScript injections).
I already use HttpOnly-cookies being set for authentication on the main domain only, while user content is only displayed on subdomains where the cookie cannot be read.
The problem is that there are still too many possibilities to execute JavaScript - for example using event attributes like onclick and Internet Explorer has even a property in CSS to allow JavaScript executions (expression) which I had never heard of before. Another interesting idea I have read of, was about throwing an exception in order to block the code following.
One more idea would be defining a list containing all allowed tags and additionally an array with each allowed attribute name but this is very hard work and I guess this would not cover all possible injections.
I guess I am not the only person having this problem, so does anybody know a possiblility covering all possible harmful code - at least in modern browsers?
A simple imaginary header similar to X-Scripting: disabled would make life so much easier!
Yes, there is an experimental HTTP header called the Content Security Policy that allows you to control where JavaScript comes from, which can make XSS impossible. However it is currently only supported by Chrome and Firefox.
It is a good idea to enable HttpOnly-cookies, however this will prevent exactly ZERO attacks. You can still exploit XSS by reading CSRF tokens, and carrying out requests with an XHR.
There are many ways of obtaining XSS, and a Vulnerability Scanner like ShieldSeal (down) will find (nearly) all of them. Skipfish is an open source vulnerability scanner that is very primitive, but its free. This is how most web applications deal with wide spread vulnerabilities. (I work for ShieldSeal and I help build their vulnerability scanner and I love my job.)
When an issue is found you should use htmlspecialchars($var) or htmlspecialchars($var, ENT_QUOTES) to sanitize input. ENT_QUOTES can prevent an attacker from introducing an onclick or other JavaScript event.
Related
I'm using Symfony2 / Twig / Doctrine.
I'm looking at security on my site and in particular preventing XSS attacks, but I can't see what more I can do.
Persistent
I use Doctrine and always ensure I make user input safe, refusing HTML, web addresses and email addresses etc. (if applicable, e.g. a comment box). I also use Twig (which I believe escapes output).
Reflective
My understanding is that anyone could send an email to someone with a link to any website that also injects JavaScript. That JS can of course do anything. That JS could have a login form be submitted to any web address and there is nothing you can do (other than hope stupid people don't click links from random people to my site's login page).
So unless you can prevent JS being injected, then what more can I do?
I don't believe you can prevent a site from running a JS script on another server (my valid JS comes from a CDN anyway which is on another server) and I don't think you can prevent a HTML form being submitted to another server.
I do believe that cross domain protection does prevent the injected JS calling an Ajax request though - but I haven't done anything about this, I just think that is how modern browsers work.
Is anything else in my hands? As long as I have done eveything else possible that's enough for me.
I suppose I'm wondering why there isn't much I can do about this when some people make a living out of advising on XSS protection. Maybe it's because I use Symfony2 / Twig / Doctrine?
Just looking for help to clarify my understanding.
Content Security Policy solves the problem of injected javascript by banning any inline javascript and validating content sources.
Info: https://developer.mozilla.org/en-US/docs/Security/CSP/Using_Content_Security_Policy
Browser support: http://caniuse.com/contentsecuritypolicy
I'm finishing up my first "real" PHP application and I am trying to make sure it is secure. I'm kind of afraid that since I'm not an "expert" PHP programmer that I might be missing something huge, so I would like to give you some information about my application and hopefully you can tell me whether or not that is the case. So here we go:
I'm using a CMS to handle user authentication, so I don't have to
worry about that.
After discovering PDO shortly after starting work
on my application, I ported all of my code over to using prepared
statements with PDO.
I am escaping all form and database data (even stuff I think is safe) which is being output with htmlentities().
My application does use a session variable and cookie variable, but the function of both is very unimportant.
I have designed my form processing functions in such a way that it doesn't matter if the form were somehow altered, or submitted from off-server (i.e. I always check the data submitted to ensure it's valid).
I have done my best to make all error messages and exception messages polite but very obscure.
I'm forcing pages with sensitive information (such as the login page) to be served over https.
When I first starting writing my application, I didn't know about prepared statements, which is kind of a huge deal. Have I missed anything else?
OWASP maintains a list of the Top 10 Most Critical Web Application Security Risks (warning, PDF download). This is from 2010, but I think it still applies, perhaps even moreso now.
Injection and XSS are the top two, but you should certainly be aware of the other 8. If you are using an existing CMS, many of these may already be considered, but the more popular the CMS the more you risk running into vulnerabilities because of black hats trying to find holes in it.
If you are not storing critical data like credit cards, order history, addresses, and even emails, then I wouldn't worry too much about your site being affected as long as you are taking the basic precautionary measures (and it sounds like you are).
If you are concerned about security issues, a good resource is the OWASP - Top 10 Application Security Risks
The most important thing to take care in web applications(specially PHPs') is Data Validation of all the inputs taken from the user which are further saved in your database.
For a secure application, all the transactions should be done on HTTPS. For a secure cookie management Secure and HTTPOnly cookie should be implemented.
Some more points I don't see mentioned yet. Most of these are not related to code - I am not sure if you only wished for things related to code, but I'll mention them anyway.
Backups (user data). should be self-evident
Version control. If you have a big bug, you want to have access to the previous version.
Audit trail, alarms and logging. If you do get into trouble, how will you find out? Are you able to track down what happened? if you know something is wrong but don't fully know what, are you able to diagnoze the issue?
Hosting. Where are you hosting? Do you have adequade bandwidth and monitoring? What happens if you get DOSed? Are you able to block out unwanted traffic?
Caching. Can you change it if needed?
There's always one thing left. Availability :) There are three aspects of security:
Confidentiality (Noone can read what they don't have access to)
Integrity (Noone can change any data what they should have to and you have to be able to detect if it happened even so)
Availability (The data, application whatever has to be available)
You pretty much did a nice job and took care of the first two (credentials, prepared statements, htmlentities...) but none of them will help against a DoS attack. You should be able to detect if someone slaps your site and ban the attackers ip from your server. Although this can be done in PHP (still much better to kick the attacker at the first line of php than let them initialize the framework, database connections etv.) it can be done mre effectively in lower layers (for example: nginx/apache, iptables, snort).
However what you're asking for that usually comes to the matter of risk management. In a real application you're not able to be prepared for all the possible attacks, edge cases etc. What you need to do is classify all the risks by the probability and the impact ( http://www.jiscinfonet.ac.uk/InfoKits/infokit-related-files/Resources/Images/risk-matrix ). With this you can focus on the most important (highest) risks first and probably you can completely ignore the lower bottom part.
SQL Injection and XSS are the most prominent Hacking methods.
You are covered from SQL Injections if you use prepared statements.
Also, if htmlentities() on everywhere you display HTML you should be safe.
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.
I'm a bit behind the times when it comes to website security. I know the basics - validate all incoming data, escape data being saved to the db, use a salt for passwords, etc. But I feel like there's a lot I'm missing that can bite me in the butt. This is especially true with my slow migration to .NET. I'm just not sure how to replicate what I know in PHP in .NET. So, below are some things I've been thinking about that I'm sure I need help with.
Problem: Securing sessions
PHP: Use session_regenerate_id() whenever a user does something important.
.NET: No idea how to replicate that here.
General: What else am I missing?
Problem: XSS
PHP: Use htmlentities() to convert potentially dangerous code into something that can be rendered (mostly) harmlessly.
.NET: I believe in MVC, using <%: %> tags in a view does the same thing.
General: Is there more I can do to block JavaScript? What about denying HTML entirely? How would one secure a textarea?
Problem: Remote Execution
PHP: Use regEx to find and remove eval() function calls.
.NET: Unsurprisingly, no idea.
General: Again, is there more I should look for?
Problem: Directory Traversal (probably related to the above)
I'm just not sure how worried I should be about this. Nor am I sure how to block it.
Suggestions, links to articles (with code examples), etc. are most welcome, and would be greatly appreciated.
session_regenerate_id
I don't think there is an equivalent. Sessions are short lived, so if the attacker will get into the session in time, that should also happen after you change the access level.
Something additional is that sessions aren't meant to authenticate the user in asp.net. When using custom authentication you use Forms Authentication.
Above said, anything you do is subject to a man in the middle attack. This is the case for lots of sites, so cookie hijacking is a problem all around.
When doing anything special, require the user to enter their password again / which should be done over https. If you need to do a series of special operations, you can do that once but from then on requests/cookies need to be sent over https. In this context, you could emit a modified forms authentication cookie, that allows access to the special operations and has require https on.
I believe in MVC, using <%: %> tags in a view does the same thing.
Yes, that's kind of the equivalent to <%= Html.HtmlEncode(someString) %> / with something extra to prevent double encoding (should look into that).
Use regEx to find and remove eval() function calls.
In .net you don't have such a shorthand with so broad access. If you are not explicitly doing anything out of the ordinary, you are likely ok.
Directory Traversal (probably related to the above)
Use MapPath and similar. It actually prevents going outside of the site folder. This said, avoid receiving paths altogether, as you can still give unintended access to special files inside the asp.net folder. In fact, this is part of what happened to a Microsoft handler in the padding oracle vulnerability out there - more on my blog
You can add CSRF to the list.
Use the anti forgery token: http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/
padding oracle attack:
Apply the work arounds & then the patch as soon as its out.
Learn about all that I mention here: asp.net padding oracle: how it relates to getting the web.config, forging authentication cookies and reading other sensitive data. Understanding all that's in there is important, specially if you use any of the features i.e. you don't want to be the one putting sensitive data in the view state :)
You can add CSRF to the list. They tend to be prevented by adding a hidden token in the form of your application, possibly matching a cookie, and then checking they both match when processing the form data submitted.
I just starting out learning PHP, I've been developing web apps in ASP.Net for a long time. I was wondering if there are any PHP specific security mistakes that I should be looking out for.
So, my question is what are the top security tips that every PHP developer should know?
Please keep it to one tip per answer so people can vote up/down effectively.
(In no particular order)
Always check that register globals are OFF
Always check that magic quotes are OFF
Make sure you understand SQL injection attacks
Turn OFF error reporting in production
EDIT: For the "newbies" out there this is a basic why (and since I have time to explain this):
Register globals is an aberration. It's the ultimate security hole ever. For example, if register_globals is on, the url http://www.yourdomain.com/foo.php?isAdmin=1 will declare $isAdmin as a global variable with no code required. I don't know why this "feature" has made it's way to PHP, but the people behind this should have the following tattooed on their forehead: "I invented PHP Register Globals" so we can flee them like pest when we see them!
Magic quotes is another dumb idea that has made it's way to PHP. Basically, when ON PHP will escape quotes automatically (' become \' and " become \") to help with SQL injection attacks. The concept is not bad (help avoid injection attacks), but escaping all GET, POST and COOKIE values make your code so much complex (for example, have to unescape everytime when displaying and data). Plus if one day you switch this setting OFF without doing any change to your code, all your code and/or data is broken and (even more) vulnerable to injection attacks (yes even when ON you are vulnerable).
Your databse data is your most valuable thing on your site. You don't want people to mess with it, so protect yourself and read things about it and code with this in mind.
Again this can lead to security concerns. The error message can give hints to hackes on how your code works. Also these messages don't mean anything to your visitors, so why show them?
Avoid using register_globals.
Warning: This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Cross Site Scripting (XSS) Wiki, Google
Cross Site Request Forgery (XSRF/CSRF) Wiki, Google (thanks Rook)
Session Fixation Wiki, Google
SQL Injection (SQLi) Wiki, Google
Turn off error messages in Production environments
Keep any "include" code in a directory that is not web-accessible (either deny access or keep it outside of the webroot)
Here's an article I wrote about storing passwords in a secure way, and if you don't feel like taking my word for it, check the links at the bottom.
Also linked in my article, but given its own separate link here, is a paper published by M.I.T. called The DOs and DON'Ts of Client Authentication on the Web [PDF]. While some of its info (recommendation to use MD5 hash, for one) is somewhat out of date simply because of what-we-know-now versus what-we-knew-then, the overall principles are very strong and should be considered.
One of Rooks' links reminded me of another important set of restrictions
Turn off Register Globals (This is the default now, so I hadn't mentioned it before)
When dealing with file uploads, be sure to use is_uploaded_file() to validate that a file was uploaded and move_uploaded_file() instead of copy() or rename().
Read this section of the PHP Manual if you need to know why (and you do).
Since I've now mentioned him twice, check out Rooks's Answer (https://stackoverflow.com/questions/2275771/what-are-the-most-important-safety-precautions-that-a-php-developer-needs-to-know#2275788) as it includes a link to a document which contains (Non-PHP-Specific) information on the most important security concerns (and this therefore probably the right answer).
here is a link of good PHP security programming practices.
http://phpsec.org/
Most of the security issues revolve around user input (naturally) and making sure they don't screw you over. Always make sure you validate your input.
http://htmlfixit.com/cgi-tutes/tutorial_PHP_Security_Issues.php
Always sanitize and validate data passed from the page
In conjunction with #1, always properly escape your output
Always turn display_errors off in production
If using a DB backend use a driver that supports/emulates prepared statements and use without prejudice :-)
don't use "Register Global Variables" and filter user input for xss and injections
Language Vs Programmer. You can write the most serious vulnerability and you won't get a warning or error message. Vulnerabilities can be as simple as adding or removing 2 characters in your code. There are hundreds of different types of vulnerabilities that affect PHP applications. Most people think of XSS and Sql Injection because they are the most popular.
Read the OWASP top 10.
If you're using a mysql database make sure you call mysql_real_escape_string when sending data to the database
There are tons of safety precautions. I can recommend a book Chris Shiflett: PHP and Web Application Security.
http://phpsecurity.org/
Have a look at the Suhosin Hardening Patch, and check out the security vulnerabilities that it addresses.
The PHPSec Guide gives a good overview.
Most of the security issues related to PHP come from using unparsed "outside" (GET/POST/COOKIE) variables. People put that kind of data directly into file paths or sql queries, resulting in file leakage or sql injections.
OWASP provides a lot of insight into security issues that are the biggest problems in applications today. It is nice to see that they have a PHP dedicated page available
http://www.owasp.org/index.php/PHP_Top_5
Always Close you SQL Connection.
Always Release SQL results.
Always Scrub all variables your putting into a database.
When deleteing or dropping from sql use limit 1 just in case.
When developing make sure you have a lock on things to keep the undesirable out. If its open and you know not to load the page right now because it could break something, doesn't mean other people do.
Never use Admin or Root as your server log in name.
Whenever possible, use prepared statements (tutorial. It's almost a must whenever dealing with user input (I say "almost" because there are a few use cases where they don't work), and even when not dealing with input, they keep you in the habit. Not to mention they can lead to better performance, and are a LOT easier, once you get into the swing of things, than piecemeal sanitizing.
Often introductory tutorials don't talk at all about checking data from users. Like all programming environments, never trust the data you get from users. Learn to use functions like is_numeric(), isset(), and mysql_real_escape_string() to protect your system.
There are also features that allow you to access remote files, and other creative things. I'd avoid those until you have a good understand of how and when they work (often they are disabled for security reasons).
Use POST method for data passing from one page to another.
Use trim while getting data like trim($_POST).
Also, use strip_tags for variables before you passing into the queries.
I am suggesting you use any framework link Codeigniter, Laravel, YII, Cake PHP because they maid framework with all securities
I suggest Codeigniter for small projects and Laravel for big projects.
Always use POST and not GET for important Data...