Securing JSON with a codeigniter and jQuery project - php

I would like to use JSON, however, the security issues related to using JSON are holding me back.
There are two main issues CSRF (Cross Site Request Forgery) and the JSON/Array hack.
I have read that Double Submit the Cookie expanding from Secret Hidden Fields are possible solutions to the CSRF problem.
I wonder if there are any codeigniter add-ons to simplify the process of securing a project this way?
Any advice would be appreciated.

To help secure your application against CSRF there is a library http://blog.kylehasegawa.com/codeigniter-csrf-xsrf-library that can help. However, once CI 2 is released you need not worry - it will include CSRF/XSRF protection.
What do you mean by "use JSON"?
JSON in itself is not dangerous, it is just a way to serialize javascript objects. However, when deserializing, I advice you not to use JavaScript's eval() function (That allows for executing arbitrary JS code if used carelessly), but use a dedicated JSON deserializer such as http://www.json.org/js.html. Newer browsers even come with built-in JSON deserializers.
For browser security issues in general, i recommend reading http://code.google.com/p/browsersec/.

It need no addons, just generate an unique string in the hidden form field and also save it in the session, then compare $_POST submitted form value with the session value. Break code if they don't match, otherwise continue script... That's a simple process.

Related

No Script Tag - reliable? Secure?

I have built a small app using javascript. I am using javascript for form validation and i am wondering if by using the "no script" tag if this will protect me against people passing non-clean data into my mysql db? I will deny access to the application to anyone who has it turned off. Is this a secure method or do i have to also do php form validation on top of the js validation?
If not, can someone advise me on what is the best way to ensure that the data submitted to my db is not harmful and clean. Id like to do this using javascipt if possible and not layer it with php but if i have to i will as long as my app is secure.
I know i must do some php cleaning such as htmlentities but want to avoid doing form validation with php.
Thanks.
No, you can never trust the client-side to validate. You must always validate server-side. Client-side validation can improve the user experience, but it gives no security benefit.
As a general rule, you never want to rely on client-side code (javascript in this case) to validate data. The client has full control over anything you would put in javascript, and so it would be pretty easy to bypass. Always validate on the server where you have full control of what is happening.
No, you always need to do serverside validation. You can alter JS even when it's turned on (in Chrome for example, you can just pause script loading, edit the JS then run it), therefore it wouldn't even matter if it's on or not.
This is a good starting point: http://net.tutsplus.com/tutorials/html-css-techniques/build-a-neat-html5-powered-contact-form/ (towards the bottom is the validation examples)
Javascript protection is just "visual". Anyone can bypass it and insert any data he/she wants.
You should always validate user-submitted data server-side.
Basically you can start with mysql_real_escape_string() for preventing mysql injection, and do some tag stripping if you are going to display the inputted data back.

What is the best solution to form spoofing?

What is the best solution to "form spoofing" besides filtering the inputs?
I understand the followings:
Referrer can be spoofed
Telnet can be used to fool the server
Client side filtering can be bypassed
i understand that i should avoid GET
I can use Captcha
How can i prevent somebody to post to my form processing scripts from anywhere?
If someone can manually post a form, they can do it automatically too. There's no way to stop that besides moderation. You can make it harder by using captcha's. But personally I hate captcha's, because they are just a solution made up by lazy moderators to make the users solve their problems.
Here is a way to use tokens.
http://shiflett.org/articles/cross-site-request-forgeries
Not much really. Every client-side check can be spoofed or bypassed. Some authentication method is best, either using HTTP Auth or a simple system you coded yourself with sessions.
I don't know what the best solution is necessarily, but you can use a session variable on the script that should have generated the form and check it in the script that the form POSTs to. You can md5 the variable contents and make it something somewhat random for increased security as well.
The real question is why do you want to prevent people from being able to post to your webpage from anywhere? Your webpage should be prepared to accept any input no matter where it comes from. There are measures you can take to reduce automatic posting such as tokens, but there is no way you can prevent it completely.
Instead of trying to prevent it, though, I would welcome it. Advertise your cross-site post API and profit.
Postel's law:
TCP implementations should follow a general principle of robustness: be conservative in what you do, be liberal in what you accept from others.
Set a hidden input on the form that's equal to the md5 value of a string made up of the session id + a secret "salt" string value. Then, when you process the form, you can get the session id, add the secret value, and compare the mp5 out of that to the value that was passed with the form.

How to Implement Generic CSRF Tokens with JQuery AJAX?

I am currently developing jquery code that sends data to the server via ajax that is then inserted into the database based on the request parameters.
However, I am rather concerned that this could be abused by CSRF attacks which would make things rather insecure. I have tried to research this and only find answers for specific frameworks such as django and rails where I am only after a generic implementation for use with PHP.
I have read that you can use the JQuery.ajaxsend() function to implement the code so that a token is sent with EVERY AJAX request however I have no idea how this can be implemented as JavaScript obviously has no access to the PHP session variables. Would the use of cookies be secure enough?
Basically I need to be able to check the origin of the request to ensure that the request is genuine and not a forged request used to take advantage of the system.
If anyone can point me in the right direction that would be most appreciated!
Well, do know that $.ajax seems to send the cookies, including the PHP session cookie, with its request. Using that feature changes your attack from CSRF to session hijacking, but it's a start. Next, run your service over SSL if you can to avoid the session hijacking.
I'm sure there are other ways to do this as well, but for vanilla PHP, this seems to work. Someone correct me if I'm wrong, please.
Here's how it's done in Django, but there's nothing that's framework specific (besides setting the CSRF token in the cookie as 'csrftoken'): https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax

php cookie injection vulnerability?

I have a website, on one page it reads a cookie from the users computer and uses that as a variable in the php code, for example in echo statments.
I am not currently cleaning the cooking any way.
2 questions:
can someone hack their cookie to put stuff into my php code?
if yes, how can i prevent this? HOW can I clean it?
Thanks!
Yes, it's very very easy to edit the cookies on the client.You should handle the values of the cookies as any other user generated input: don't trust it and validate it.
Yes, one could very easily exploit this depending on how it's used in the code. One could for instance, forge the entire request and provide any desired value for the cookie.
The question of how to prevent this depends on what values you are expecting the cookie to contain. All you need to do is make sure that the value of the cookie fits within your specification. Without knowing what this specification is or how the value is being used, there is not much more to say.
If you are only echoing the cookie, then the vulnerability that the user can explode is called "XSS" that stands for Cross Site Scripting. Basically he would insert <script> tags in the website to execute javascript.
You can prevent this by using the function strip_tags in php to clean tags from the cookie.
If you use the cookie in some other way, there could be new security issues, please specify if that is the case.
Strip_tags does not protect you from being hacked nor does it strip XSS. It only strips the HTML and you don't need HTML to XSS a site.
The problem is not in the input per se, it's in how you output it. If you echo it directly into an HTML page then you need to HTML-encode it; that's true of all strings you include in an HTML page, not just cookies. If you are as a habit outputting unescaped strings into HTML then you probably have much easier to exploit XSS bugs than this(*).
The way to handle variable text properly for output into HTML is to wrap every variable in htmlspecialchars() at the point you echo it into HTML (not as an input handling step). Do not use strip_tags()—it is not designed as a security measure and it fails in a variety of circumstances. If you need to accept limited user-input markup use an HTML purifier library.
(*: how exploitable an HTML-injection-from-cookie is depends largely on how that cookie gets set. If there is any way an attacker can persuade your application to set another user's cookie to a specific value, it'll be easily exploitable; otherwise, in order to exploit the HTML injection they would have to find a cookie-fixation bug. That could be a header-injection bug in your app, or it could be any vulnerable application in a ‘neighbour domain’—an application at a.example.com can set a cookie that will be read by an application at b.example.com.)
As people have posted a cookie is super easy to manipulate on the client side. It's basicly just a text file. If you only echo and don't depend on the data in the cookie for db calls, function calls or file includes you pribably don't need to care becasue the user would only affect what's displayd on his local machine. On public computers this could ofcourse be a problem though.
If you want more controll handle the data using serverside sessions. Or if you really need the data in the cookie, store a hash of the cookue values serverside so you can determine if it has bern tampered with

Passing base64_encoded serialized data between form submissions

I'm creating a wizard-based series of forms for taking user inputs. One of the requirements for that wizard is that the script (PHP) cannot save the inputs into the database (MySQL) until the user clicks the 'Save' button, so I have to device a mechanism to transport user inputs in one form to another when the user clicks 'Previous' or 'Next' buttons. I looked into using various methods including cookies, sessions, temporary files etc, but I settled for embedding base64_encoded serialize data in a hidden field that exists in all the forms in the series. The value in this field will be decoded on form submissions and re-encoded for putting in the next form after other values from the current form are inserted.
Here is a sample of how the hidden field looks:
<input type="hidden" name="wizard:presave" value="YTo2OntzOjU6InRpdGxlIjtzOjEwOiJRdWVzdGlvbiAyIjtzOjQ6InRleHQiO3M6MTk6IlllcyBpdCdzIGEgcXVlc3Rpb24iO3M6NDoidHlwZSI7czo2OiJjaG9pY2UiO3M6NzoiY2hvaWNlcyI7YTowOnt9czo1OiJwb2ludCI7aToxO3M6Mjoib3AiO3M6MTM6ImVkaXRfZXhlcmNpc2UiO30=" />
So the questions are:
Is it considered a good/bad practice?
Is there any length limit of hidden fields in HTMLform?
What are the possible security issues?
And are there better alternatives? (with explanations, preferably without using javascript)
Thanks in advance!
I've never seen this particular method of parameter passing in my career, so I can't say whether it's good or bad. It's certainly not "standard". Standard methods would either be passing the submitted method along (unencoded/normally) using hidden inputs, or storing in session. I think you might be making work for yourself, so in that sense it would lean towards "not ideal".
As long as you are using POST for your forms, there is no defined limit for data sizes that I'm aware of in the HTTP specifications. Older servers may have practical limits, but unless you're doing something extreme such as media file uploads, they shouldn't be a worry.
Possible security issues are the normal web security flaws. Anything you take from a user and re-output to a page could contain cross-site scripting vulnerabilities and would have to be properly sanitized (this is somewhat moot if you're encoding everything). Users can craft their own data and submit it if they like. Basically, assume all the data you handle is unsafe and tainted.
Sessions would work much better here. The data the user submits wouldn't have to go through a lengthy encoding process. As well, you'd only have to validate it once. After it's been submitted and validated, you can simply store it on the server in $_SESSION and leave it alone until the final button is clicked. Otherwise, you have to worry about re-outputting it, re-receiving it, and re-validating it at each step. A malicious user could submit one set of data, have it checked and re-output as encoded data, but then craft the next form submission by unencoding, changing data, and re-encoding.
I would highly recommend that you reconsider sessions, as it simplifies all your data operations into a "do-once" scenario.
Is it considered a good/bad practice?
Depends on the purpose. As far I've only seen such constructs as a client side URL hash to remember the state of the selections in large ajax-based applications (so that they are bookmarkable) and then often also Gzipped to make it shorter. In your speficic case I'd say: make use of the HTTP session and only pass a request based identifier (also called token) in the hidden field so that you can get the associated information from the session.
Is there any length limit of hidden fields in HTMLform?
In GET the complete query string (all parameter names and values and separators together) is usually limited to 2048 characters, but you can better adhere an officious limit of 256 chars. In POST it is dependent on server configuration. Often this defaults around 2GB.
What are the possible security issues?
Well, it is obviously decode-able.
And are there better alternatives? (with explanations, preferably without using javascript)
You could Gzip it to make it shorter and less obvious. Or, as already said, make use of the session in combination with a request based identifier.
Well, you can store into the session either by serializing or just simply store it the way it is for each step. When the user clicks Save, you grab and validate the data from all the steps in the session.
tsk tsk :)
Is it considered a good/bad practice?
subjectively - bad practice..you're using the wrong hammer for the job.
Is there any length limit of hidden fields in HTMLform? - Not sure if there is a limit.
What are the possible security issues? - Possibly, quite a few, but you can sanitize the data received for every request. Besides, the data is pretty easy to decode and can be easily modified on the client side (I can see that its some sort of json that you are using :) )
And are there better alternatives? (with explanations, preferably without using javascript) - Use the right tool .. sessions perhaps?
And yes... You are most likely going to face performance and scalability issues (should you have a substantial user load) with all that sanitizing, parsing, formatting and security code running for every request.

Categories