Author Archives: kumar Deepak :)

PHP Web Applications Security

When it comes to application security, in addition to securing your hardware and platform, you also need to write your code securely. This article will explain how to keep your application secure and less vulnerable to hacking. The following are the best habits that a programmer can develop in order to protect his or her application from attack:

  • Input data validation
  • Guarding against XSS attacks
  • Guarding against CSRF attacks
  • Preventing SQL Injection attacks
  • Protecting the file system
  • Protecting session data
  • Proper error handling
  • Guarding included files

Input Data Validation
While designing your application, you should be striving to guard your app against bad input. The rule of thumb to follow is this: don’t trust user input. Although your app is intended for good people, there is always a chance that some bad user will try to attack your app by entering bad input. If you always validate and filter the incoming data, you can build a secure application.

Always validate data in your PHP code. If you are using JavaScript to validate user input, there is always a chance that the user might have turned off JavaScript in her browser. In this case your app will not be able to validate the input. Validating in JavaScript is okay, but to guard against these types of problems then you should re-validate the data in PHP as well too.

Guarding Against XSS Attacks
Cross-site scripting attack (XSS attack) is an attack based on code injection into vulnerable web pages. The danger is a result of accepting unchecked input data and showing it in the browser.

Suppose you have a comment form in your application that allows users to enter data, and on successful submission it shows all the comments. The user could possibly enter a comment that contains malicious JavaScript code in it. When the form is submitted, the data is sent to the server and stored into the database. Afterward, the comment is fetched from database and shown in the HTML page and the JavaScript code will run. The malicious JavaScript might redirect the user to a bad web page or a phishing website.

To protect your application from these kinds of attacks, run the input data through strip_tags() to remove any tags present in it. When showing data in the browser, apply htmlentities()function on the data.

Guarding Against CSRF Attacks
In a Cross Site Request Forgery (CSRF) attack, the attacker tricks the victim into loading sensitive information or making a transaction without their knowledge. This mainly occurs in web applications that are badly coded to trigger business logic using GET requests.

Ideally, GET requests are Idempotent in nature. Idempotency means the same page can be accessed multiple times without causing any side effects. Therefore, GET requests should be used only for accessing information and not for performing transactions.

The following example shows a how a poorly coded application unknowingly supports CSRF attacks:

<?php
if (isset($_REQUEST[“name”], $_REQUEST[“amount”])) {
// process the request and transfer the amount from
// from the logged in user to the passed name.
}
Let’s assume Bob wants to perform a CSRF attack on Alice, and constructs a URL like the following and sends it to Alice in an email:

<a href=”http://example.com/process.php?name=Bob&amount=1000″>Visit My WebSite</a>
If Alice clicks on this link, and is logged into the website already, this request will deduct $1000 from her account and transfer it to Bob’s! Alternatively, Bob can create an image link whose src attribute points to the URL.

<img src=”http://example.com/process.php?name=Bob&amount=1000″ width=”1″ height=”1″/>
The browser can’t display any image as expected, but it will still make the request using the URL which will make a transaction without notifying Alice.

The solution is to process any function that changes the database state in POST request, and avoid using $_REQUEST. Use $_GET to retrieve GET parameters, and use $_POST to retrieve POST parameters.

In addition, there should be a random token called a CSRF token associated with each POST request. When the user logins into his/her account, the application should generate a random token and store it in the session. Whenever any form is displayed to the user, the token should be present in the page as a hidden input field. Application logic must check for the token and ensure that it matches the token present in the session.

Preventing SQL Injection Attacks
To perform your database queries, you should be using PDO. With parameterized queries and prepared statements, you can prevent SQL injection.

Take a look at the following example:

<?php
$sql = “SELECT * FROM users WHERE name=:name and age=:age”;
$stmt = $db->prepare($sql);
$stmt->execute(array(“:name” => $name, “:age” => $age));
In the above code we provide the named parameters :name and :age to prepare(), which informs the database engine to pre-compile the query and attach the values to the named parameters later. When the call to execute() is made, the query is executed with the actual values of the named parameters. If you code this way, the attacker can’t inject malicious SQL as the query is already compiled and your database will be secure.

Protecting the File System
As a developer you should always write your code in such a way that none of your operations put your file system at risk. Consider the following PHP that downloads a file according to a user supplied parameter:

<?php
if (isset($_GET[‘filename’]) {
$filename = $_GET[‘filename’];
header(‘Content-Type: application/x-octet-stream’);
header(‘Content-Transfer-Encoding: binary’);
header(‘Content-Disposition: attachment; filename=”‘ . $filename . ‘”;’);
echo file_get_contents($filename);
}
The script is very dangerous since it can serve files from any directory that is accessible to it, such as the session directory and system directories. The solution is to ensure the script does not try to access files from arbitrary directories.

Protecting Session Data
By default, session information is written to a temp directory. In the case of a shared hosting server, someone other than you can write a script and read session data easily. Therefore, you should not keep sensitive information like passwords or credit card numbers in a session.

A good way to guard your session data is to encrypt the information stored in the session. This does not solve the problem completely since the encrypted data is not completely safe, but at least the information is not readable. You should also consider keeping your session data stored somewhere else, such as a database. PHP provides a method called session_set_save_handler() which can be used to persist data in session in your own way.

As of PHP 5.4 you can pass an object of type SessionHandlerInterface to session_set_save_handler(). Check out the PHP documentation to learn about implementing custom session persistence by implementing SessionHandlerInterface.

Proper Error Handling
It’s good to know about all the errors that occur while we’re developing an application, but when we make the application accessible to end users we should take care to hide the errors. If errors are shown to users, it may make our application vulnerable. So, the best approach is configuring your server differently for development and production environments.

In production mode we need to turn off display_errors and display_start_up_errors settings. error_reporting and log_errors should be on so that we can log errors while hiding those from end users.

You can use set_error_handler to define custom error handlers. However, it has limitations. The custom error handler bypasses the standard error handling mechanism of PHP. It cannot catch errors like E_CORE_ERROR, E_STRICT or E_COMPILER_ERROR in the same file the error handler is defined in. Furthermore, it will fail to handle errors that might occur within the handler itself.

To handle errors elegantly you should perform exception handling through try/catch blocks. Exceptions are represented by the Exception class and its subclasses. If any error occurs inside the try block you can throw an exception and process it in the catch block.

Guarding Included Files
PHP scripts often include other PHP files that contain code for things like connecting to a database, etc. Some developers give the included files an extension like .inc. Files with this extension are not parsed by PHP by default if called directly and will be served as plain text to the users. If an attacker directly accesses the include file that contains database credentials, he now has access to all of your application’s data. Always use the .php extension for included code files and keep them outside of directories directly accessible to users.

Increasing Crime in India – Slow and liberal Judiciary System

One of the main guideline for our judiciary, “Its better to leave 100 criminals than to punish 1 innocent.” Dont’ you think this has been taken in wrong way or it has lead to wrong way? The core reason of increasing crime in India is just slow judiciary system. The liberal laws defined for crime in India is not affecting Indian society as much the slow system is doing. Thats’ also, but can be ignored right here.

Have you ever thought, why it is said that the child whose parents does not keep a strict eye on him, gets in spoil sport. Our elders generally say such. In our new and advanced generation where our elders are just said they are having old thoughts, we, actually, should never ignore phrases like this.

Lets fall into certain questions..

Why there used to be strict punishments in old day schools? 

All this was just to maintain discipline and righteousness among the growing minds.

Why a child did not dare to steal a penny from his father’s wallet, and even if he knew where the safe is?

Why a toddlers did not fight with each other, in those days?

Why a student kept his homeworks already done, and never copied it from a fellow, in the class?

Just because, “Ma datengi”, “Papa Marenge”, “Masterjee se Sticks Lagenge”.

This was the instant fear among them. Only this used to keep them away from small crimes.

Why a boy never used to tease a fellow girl in school?

Why a child never used to steal books from others bag?

All falls to the same answer…

But, when it comes to the real world, the so-called “Mummy, Papa, Teacher” are either missing or too slow to give punishment to thechild inside.

Today, a rapist has no fear of getting into jail, a murdered has no fear of getting sentenced to death, a corrupt officer has no fear of any legal action. Why, just because of our slow judicial system. If a rapist is even arrested, the next day he gets bail and then the case goes for ever. Both the sides visit the court for years and at last the poor victim has to leave the process after getting disappointed. What about the rapist? He made the crime, just visited jail for a couple of hours and that too in a very few cases and rest nothing… He lives as normal as everyone and searching for the next victim. Why would he fear? Take the example of Saudi Arabia. The rapist is hanged there and in some country, sex organs are cut for the rapist. Just think, if the judiciary is something like this, whether the rate of rape in India will go down, yes obviously, but very little. Why, because the decision will come even after natural death of the victim.

Then, obviously, there is need of speeding up the legal system. I am not blaming the judges, just I want to say that there is need of complete reform in our judicial system, in our judiciary, size of judiciary.

India in 2020 can not run properly with the system defined in 1950. There has to be some change, else this society cant’ be a safe a healthy place to live and develop.

Also, I would like to mention one quote “Prevention is better than cure”. Here, Cure is Judiciary and strict legal actions and Prevention is Education System and Grooming of Child’s intellect in the family. Rest, you can think, what should be done. Also, there used to be a word in news some years ago, and that was Lokpal Bill, but no idea where it went. Bollywood movies like Jolly LLB and sequels have tried to show what should be there in judiciary… but its still loading … !!

Farm Loan Waiver – Good or Bad

One of the important point to think, whether the decision of Farm Loan Waiver by BJP Government in UP is good or bad for UP and finally UP People and ultimately India???

There are several ways of thinking. What I am thinking is that, it should obviously be done, but taking several filters and limitations. Why and how according to me is detailed in the following para.

Farmers and Human Resource – Most important point, do you think all loans were really for farming purposes? Since, it is one of the cheapest loan, several people even having no farming land have taken loan on the name of farming. Next, loan should be given when due to some natural reasons, crops have been destroyed or anything like that. But, rarely there is any reason like that. Don’t you think it is making them more lazy to make effort. If the reason of crop loss is real and satisfactory, then obviously, loan should be waived off. If due to natural reasons, crop price fall, storage issues, etc, they were not able to repay the loan, then it is their right. Just waiving all the loan will obviously make them effortless which obviously is loss of Indian GDP and Indian Human Resource. Just take the example of Bihar. Here, every BPL family gets sufficient amount of serials to eat free of cost since last few years. The difference which came should be noticed with a very investigating eye. Earlier, they used to work in factories, agricultural fields, construction sites. Not all of them, but some of them are not doing anything now, just sitting idle because they are being fed by the free deliverables. It is obviously good as per their thought, but is it really making a healthy and resourceful India. No and never. If same here all loans are waived, why will they make effort, just take farming loan, make some excuse and sit on strike for loan waiver. Done and so easy for them, but who is getting benefited, no one. Neither those farmers, neither taxpayers, neither banks, neither GDP, neither Indian growth.

Banks – One of the main player of this game. On and average, SBI is major victim here. Mostly such loans are issued by SBI and its subsidiaries. What will happen to their reputation and their working. Loan has to be maintained with a good relationship between bank and customer. But, it totally disrupts the credit of banks. Now, firstly, the loan which now government has to pay is not credited directly and the shit which happens in functioning and records of banks takes a long time to settle.

Government – Now, the most important part, the final victim or the one most benefited. In one way, the government is in loss as it has to pay the total loan amount to banks which becomes a major percentage of total revenue. On the other hand, government uses it as a tool to win the election.

Now, the question comes, who got benefited and who is in loss. Whether, the one whose loan was waived is now in good condition. Whether their economic condition improved. Donation to beggars can never lead to their economic growth. As per RBI Ex-Governor, as per last fifty years, not a single farm loan waiving has lead to economic growth or well being condition of the farmers.

So, overall, we cant’ say that farm loan waiver should not be done, because if the natural reasons has led to the crop loss, then there is no any solution to the problem, loan should be waived off. But, in other cases, it has be done very carefully. Because, it is taking down the human resources and the economy of the farmers, banks, tax payers and ultimately the nation.

Workshops – Milestones for my Life

Since my college days, workshops played a great role in my life. It not only improved my techical, communication and management skills but gave my life a new direction. Some workshops proved to be life-changing events for my life. After all, what I want to say is that i learnt a lot from workshops in both modes.

First mode was the one when i used to attend it. During my early college days, i started participating in college workshops. I found it interesting to learn new things. Actually, i discovered “actual me” there. I just went on. I used to go in approx eac and every such technical workshops. Thus went my first year and a half of second year. Then , came mode 2.

In this mode, now i was being shifted or i was shifting myself from participants to organizers. This was quite new experience to me and much more interesting. As I remember, first one was in last days of second year. This was just the starting. I took my route in this direction which led to my present life. These workshops took me to VISION, then BitSprint, then Technical Secretary and a lot more. Now, its CodeAce finally.

After a long time, i am going to take a workshop for me and my company…

Hello to All ! Welcome to my online blog portal…

Hi Guys …

Welcome to all…to my online blog…

I am a Software Developer by profession and geek and business professional by passion. Having completed my default academics like basic studies and B. Tech from NIT Bhopal, I am residing in Gurgaon, an IT Hub of India. Going through my lifestyle of a software professional, I want to keep my thoughts related to the rest of the world on my blog. Frequently, I keep thinking or you can say that several ideas keep striking my mind which I am going to write down here. Just keep visiting it if you are interested in any of the categories like Technology, Education, Travel, Food, Politics, Society, Finance, Entrepreneuship, etc.