Cakephp Security - security

I am new to Security of Web apps. I am developing an application in Cakephp and one of my friends told me about the Cross-site request forgery (CSRF) and cross-site scripting (XSS) attacks etc. not sure how many more are there.
I need some help in understanding how to make Cakephp defend my web app against these. we are low budget and we cant hire a security consulant as of now. We are still developing the app and plan to release in by the end of the month. so wanna take care of the initial stuff that can help me stand un hacked ;)

There is not (and cannot be) one tool you can deploy and then never have to think about security again. Deploying ‘anti-XSS’ hacks like CakePHP's Sanitize::clean will get in users' way by blocking valid input, whilst still not necessarily making the app secure. Input filtering hacks are at best an obfuscation measure, not a fix for security holes.
To have a secure web application, you must write a secure web application, from the ground up. That means, primarily, attention to detail when you are putting strings from one context into another. In particular:
any time you write a string to HTML text content or attribute value, HTML-escape it (htmlspecialchars()) to avoid HTML-injection leading to XSS. This isn't just a matter of user input that might contain attacks, it's the correct way to put plain text into HTML.
Where you are using HTML helper methods, they should take care of HTML-escaping of those elements by default (unless you turn off escape); it is very unfortunate that the CakePHP tutorial includes the bad practice of echoing unescaped strings into HTML for text outside of HTML helpers.
any time you create SQL queries with string values, SQL-escape it (with an appropriate function for your database such as mysql_real_escape_string).
If you are using CakePHP's ORM and not writing your own SQL you don't have to worry about this.
avoid using user input (eg file upload names) to name files on the filesystem (generate clean unique IDs instead) or as any part of a system() command.
include the Security component to add a form submission token scheme that will prevent XSRF on forms generated by CakePHP.

Cake can be secured relatively easy (compared to self written php scripts):
http://www.dereuromark.de/2010/10/05/cakephp-security/

Related

Node JS - How can I process UGC to prevent any attack/site vulnerability?

We are working on a new feature within Node JS application, where the user can upload any document (pdf, excel, img, etc) and we'll process it in order to show it to other users. Process- I mean to get it's text, generate thumbnail, count pages and more.
While doing it we have a very important point to think of - how can we make sure that no attackers are using this feature to atack our site or even our users?
While the XSS is very poplar point- I'm sure there are other vulnerabilities we should prevent.
I'm sure this subject is a main point of any site/tool that manipulates UGC,
but I was not able to find any standards/cheat-sheats/even a bullets list that describes the process of protect my site while manipulating UGC.
Any reference, link, knowledge share or even an example of another dev language will be appreciate!
Web security has a big scope but you're right, XSS is the most popular but it has a few types:
Reflected XSS - where the malicious script comes from the current HTTP request.
Stored XSS - where the malicious script comes from the website's database.
DOM-based XSS - where the vulnerability exists in client-side code rather than server-side code
In my opinion, the third one (Dom-based) is the most actual for your app because people can upload some script that will be located in the IMG SRC and when the user loads this image - the malicious script could steal sensitive data such as Cookies/auth tokens, etc.
The most popular protection, in this case, is just to sanitize the special symbols during the "handling process". Sanitize is when you replace the HTML symbols into HTML entities such as: < to < etc.
You can manually create some Regexp to do it but I'd rather suggest using something like that: dompurify it has many useful features such as:
Supports HTML, MathML, and SVG
Supports the usual tag/attribute whitelisting/blacklisting and URL regex whitelisting
Has special options to sanitize further for certain common types of HTML template metacharacters
and many others
About Web Security whitelists and other possible vulnerabilities.
Please, check these ones, I think they might be useful for you
Web Security OWASP cheatsheet - This resource contains a very detailed list with all possible web security rules with examples and solutions
OWASP XSS Filter cheatsheet - The document especially for XSS as the most common one

Validating inputted strings as URLs - worth it for security?

In a web application I'm writing, I give logged-in visitors the opportunity to enter a URL to go with their uploaded picture, as a link back to their site.
I was going to validate the string entered to make sure it was a URL, but after mulling the complexity of the solutions out there, I thought maybe it's not necessary.
However, are there any security implications that I might be missing by not doing so? (I'm thinking of situations where a valid URL might include some malicious scripting, or similar.)
The security issue with URLs is less to do with their validity (though it's good to have basic checks in order to catch mistakes, and naturally you need to use the same input validation and output escaping code as you use for data in general); it's more to do with dangerous URL schemes.
Most notably javascript: URLs aren't really locations at all, but script content to inject into the page that links them, resulting in cross-site scripting vulnerabilities. There are other schemes with similar issues. Best is to allow only known-good schemes, for example by checking that the string begins with http:// or https://.
This feature seems to be a perfect example for a Cross-Site Request Forgery (CSRF) attack where the uploader links to a web page that triggers the CSRF attack.
To mitigate the risk of CSRF attacks, make sure that actions with site effects cannot be predicted by the attacking site. This is generally done by a so called token, a random value that is only known to your site and the logged-in visitors.
Correctly validating a URL is not trivial. You can get close, but it still won't necessarily cover everything allowed by the RFCs. As long as you aren't evaluating the URLs as input, running html_escape() or your framework's equivalent should be a sufficient precaution to protect your site from casual string mischief.
You may need to research your framework to understand what precautions, if any, you need to make against cross-site scripting, SQL injection, and other related issues. Most things that can go wrong will relate to unsanitized input, but your mileage may vary quite a bit.
Protecting the user is probably not a reasonable design goal if you expect 100% safety. The web is not a protected sandbox, after all.

Safe implementation of script tag hack to do XSS?

Like a lot of developers, I want to make JavaScript served up by Server "A" talk to a web service on Server "B" but am stymied by the current incarnation of same origin policy. The most secure means of overcoming this (that I can find) is a server script that sits on Server "A" and acts as a proxy between it and "B". But if I want to deploy this JavaScript in a variety of customer environments (RoR, PHP, Python, .NET, etc. etc.) and can't write proxy scripts for all of them, what do I do?
Use JSONP, some people say. Well, Doug Crockford pointed out on his website and in interviews that the script tag hack (used by JSONP) is an unsafe way to get around the same origin policy. There's no way for the script being served by "A" to verify that "B" is who they say they are and that the data it returns isn't malicious or will capture sensitive user data on that page (e.g. credit card numbers) and transmit it to dastardly people. That seems like a reasonable concern, but what if I just use the script tag hack by itself and communicate strictly in JSON? Is that safe? If not, why not? Would it be any more safe with HTTPS? Example scenarios would be appreciated.
Addendum: Support for IE6 is required. Third-party browser extensions are not an option. Let's stick with addressing the merits and risks of the script tag hack, please.
Currently browser venders are split on how cross domain javascript should work. A secure and easy to use optoin is Flash's Crossdomain.xml file. Most languages have a Cross Domain Proxies written for them, and they are open source.
A more nefarious solution would be to use xss how the Sammy Worm used to spread. XSS can be used to "read" a remote domain using xmlhttprequest. XSS isn't required if the other domains have added a <script src="https://YOUR_DOMAIN"></script>. A script tag like this allows you to evaluate your own JavaScript in the context of another domain, which is identical to XSS.
It is also important to note that even with the restrictions on the same origin policy you can get the browser to transmit requests to any domain, you just can't read the response. This is the basis of CSRF. You could write invisible image tags to the page dynamically to get the browser to fire off an unlimited number of GET requests. This use of image tags is how an attacker obtains documnet.cookie using XSS on another domain. CSRF POST exploits work by building a form and then calling .submit() on the form object.
To understand the Same Orgin Policy, CSRF and XSS better you must read the Google Browser Security Handbook.
Take a look at easyXDM, it's a clean javascript library that allows you to communicate across the domain boundary without any server side interaction. It even supports RPC out of the box.
It supports all 'modern' browser, as well as IE6 with transit times < 15ms.
A common usecase is to use it to expose an ajax endpoint, allowing you to do cross-domain ajax with little effort (check out the small sample on the front page).
What if I just use the script tag hack by itself and communicate strictly in JSON? Is that safe? If not, why not?
Lets say you have two servers - frontend.com and backend.com. frontend.com includes a <script> tag like this - <script src="http://backend.com/code.js"></script>.
when the browser evaluates code.js is considered a part of frontend.com and NOT a part of backend.com. So, if code.js contained XHR code to communicate with backend.com, it would fail.
Would it be any more safe with HTTPS? Example scenarios would be appreciated.
If you just converted your <script src="https://backend.com/code.js> to https, it would NOT be any secure. If the rest of your page is http, then an attacker could easily man-in-the-middle the page and change that https to http - or worse, include his own javascript file.
If you convert the entire page and all its components to https, it would be more secure. But if you are paranoid enough to do that, you should also be paranoid NOT to depend on an external server for you data. If an attacker compromises backend.com, he has effectively got enough leverage on frontend.com, frontend2.com and all of your websites.
In short, https is helpful, but it won't help you one bit if your backend server gets compromised.
So, what are my options?
Add a proxy server on each of your client applications. You don't need to write any code, your webserver can automatically do that for you. If you are using Apache, look up mod_rewrite
If your users are using the latest browsers, you could consider using Cross Origin Resource Sharing.
As The Rook pointed out, you could also use Flash + Crossdomain. Or you could use Silverlight and its equivalent of Crossdomain. Both technologies allow you to communicate with javascript - so you just need to write a utility function and then normal js code would work. I believe YUI already provides a flash wrapper for this - check YUI3 IO
What do you recommend?
My recommendation is to create a proxy server, and use https throughout your website.
Apologies to all who attempted to answer my question. It proceeded under a false assumption about how the script tag hack works. The assumption was that one could simply append a script tag to the DOM and that the contents of that appended script tag would not be restricted by the same origin policy.
If I'd bothered to test my assumption before posting the question, I would've known that it's the source attribute of the appended tag that's unrestricted. JSONP takes this a step further by establishing a protocol that wraps traditional JSON web service responses in a callback function.
Regardless of how the script tag hack is used, however, there is no way to screen the response for malicious code since browsers execute whatever JavaScript is returned. And neither IE, Firefox nor Webkit browsers check SSL certificates in this scenario. Doug Crockford is, so far as I can tell, correct. There is no safe way to do cross domain scripting as of JavaScript 1.8.5.

Checklist for Web Site Programming Vulnerabilities

Watching SO come online has been quite an education for me. I'd like to make a checklist of various vunerabilities and exploits used against web sites, and what programming techniques can be used to defend against them.
What categories of vunerabilities?
crashing site
breaking into server
breaking into other people's logins
spam
sockpuppeting, meatpuppeting
etc...
What kind of defensive programming techniques?
etc...
From the Open Web Application Security Project:
The OWASP Top Ten vulnerabilities (pdf)
For a more painfully exhaustive list: Category:Vulnerability
The top ten are:
Cross-site scripting (XSS)
Injection flaws (SQL injection, script injection)
Malicious file execution
Insecure direct object reference
Cross-site request forgery (XSRF)
Information leakage and improper error handling
Broken authentication and session management
Insecure cryptographic storage
Insecure communications
Failure to restrict URL access
I second the OWASP info as being a valuable resource. The following may be of interest as well, notably the attack patterns:
CERT Top 10 Secure Coding Practices
Common Attack Pattern Enumeration and Classification
Attack Patterns
Secure Programming for Linux and Unix
A Taxonomy of Coding Errors that Affect Security
Secure Programming with Static Analysis Presentation
Obviously test every field for vulnerabilities:
SQL - escape strings (e.g. mysql_real_escape_string)
XSS
HTML being printed from input fields (a good sign of XSS usually)
Anything else thatis not the specific purpose that field was created for
Search for infinite loops (the only indirect thing (if a lot of people found it accidentally) that could kill a server really).
Some prevention techniques:
XSS
If you take any parameters/input from the user and ever plan on outputting it, whether in a log or a web page, sanitize it (strip/escape anything resembling HTML, quotes, javascript...) If you print the current URI of a page within itself, sanitize! Even printing PHP_SELF, for example, is unsafe. Sanitize! Reflective XSS comes mostly from unsanitized page parameters.
If you take any input from the user and save it or print it, warn them if anything dangerous/invalid is detected and have them re-input. an IDS is good for detection (such as PHPIDS.) Then sanitize before storage/printing. Then when you print something from storage/database, sanitize again!
Input -> IDS/sanitize -> store -> sanitize -> output
use a code scanner during development to help spot potentially vulnerable code.
XSRF
Never use GET request for
destructive functionality, i.e.
deleting a post. Instead, only
accept POST requests. GET makes it extra easy for hackery.
Checking the
referrer to make sure the request
came from your site does not
work. It's not hard to spoof the
referrer.
Use a random hash as a token that must be present and valid in every request, and that will expire after a while. Print the token in a hidden form field and check it on the server side when the form is posted. Bad guys would have to supply the correct token in order to forge a request, and if they managed to get the real token, it would need to be before it expired.
SQL injection
your ORM or db abstraction class should have sanitizing methods - use them, always. If you're not using an ORM or db abstraction class... you should be.
SQL injection
XSS (Cross Site Scripting) Attacks
Easy to oversee and easy to fix: the sanitizing of data received from the client side. Checking for things such as ';' can help in preventing malicious code being injected into your application.
G'day,
A good static analysis tool for security is FlawFinder written by David Wheeler. It does a good job looking for various security exploits,
However, it doesn't replace having a knowledgable someone read through your code. As David says on his web page, "A fool with a tool is still a fool!"
HTH.
cheers,
Rob
You can get good firefox addons to test multiple flaws and vulnerabilities like xss and sql injections from Security Compass. Too bad they doesn't work on firefox 3.0. I hope that those will be updated soon.

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