Showing posts with label PHP security. Show all posts
Showing posts with label PHP security. Show all posts

Monday 19 May 2014

PHP Check Mime Type of File - Return Information About A File

PHP Check Mime Type of File - Return Information About A File

Now a days, we are uploading files like Profile images, Video files OR excel files in our web application. 
With uploading these files there are chances some user upload the .exe file (Virus) by renaming the .exe into .jpg, which can damage website.

You might have added the extension check from javaScript as well as PHP. But this is not enough from security end because someone can upload the file after changing the extension of file( ".exe" to ".png"). In this case your security check will be failed.

What to do.
Answer is  check the Mime of file before get uploaded in your web server.

How to do this
"fileinfo" is extension which must be enabled in your php.ini. (for existence you can check  in phpinfo)
If this extension is not enabled ask your server admin, he will do this for you OR you can also do this your self (http://php.net/manual/en/fileinfo.installation.php).


After installing the fileinfo extension, use following code to get the mime type of file before get uploaded in web server.
if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);    

    //file which you want to check the mime of the file
    $file = $_SERVER['DOCUMENT_ROOT'] . '/images/feedback.png';    //file which is going to get uploaded in web server
    try {
        $type = finfo_file($finfo,$file);        
        echo "File Type: ".$type;
    } catch (Exception $e) {
        echo $e->getMessage();
    }
} else {
    echo "'finfo_file' is Not installed";
}


When you execute above code, if will get the mime-type of file. This is directly checking the mime type of already uploaded file.
You can use $type = finfo_file($finfo,$file); for checking the file type, before using move_uploaded_file function.

Friday 14 March 2014

Improve Ajax Performance

Improve Ajax Performance

Following are few steps to Improve Ajax Performance
  1. First try to Reduce the Number of Ajax Call
  2. If same call send again, abort the previous call
  3. If ajax call is executing, and user go for another link, then cancel the previous one.
  4. Use GET Method, As its Fast but less secure
  5. Reduce the Amount of data transmitted
    a. Only Required parameter in Ajax Request
    b. Only Required Response in Ajax Request
  6. Optimize your Server  


Wednesday 12 March 2014

PHP Captcha Code Example Code Snippets

Captcha
CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a type of challenging-response test used in computer field to determine whether user is Human OR robot program. Captcha is used in website to confirm that your website is accessing by a human being not machine. We can add captcha in multiple form/pages of website.

It reduce the risk of hacking/damage of website. It also help to secure the web server.


Follow Simple Steps to add captcha in your website.

1. Copy the following code and put in createCaptch.php
session_start();
//Let's generate a totally random string using md5
$md5_hash_no = md5(rand(0, 999));
//We don't need a 32 character long string so we trim it down to 5
$security_code = substr($md5_hash_no, 15, 5);
$_SESSION['captcha'] = $security_code;

//Set the image width and height
$width = 148;
$height = 37;

//Create the image resource
$image = ImageCreate($width, $height);

//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);

//Make the background black
ImageFill($image, 0, 0, $grey);

//Add randomly generated string in white to the image
ImageString($image, 8, 50, 10, $security_code, $black);

//$font = 'font1.ttf';
//imagettftext($image, 18, 0, 15, 28, $black, $font, $security_code);
//Throw in some lines to make it a little bit harder for any bots to break
ImageRectangle($image, 0, 0, $width - 1, $height - 1, $grey);

// prevent client side  caching
header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");

//Output the newly created image in jpeg format
ImageJpeg($image);

2. In the Form add following

<input name="ccode" type="text" /> <img src="createCaptch.php" title="Captcha Code" />

3
. Validate the captcha
session_start();
if($_POST['ccode']==$_SESSION['captcha']){
    //valid 
}ELSE{
    //Invalid
}



Thursday 6 March 2014

PHP - Secure Ajax Call from Hackers - Example

PHP - Secure Ajax Call from Hackers - Example

Today, In all web application we use Ajax call to get the server data without refresh the full page. In this cases, we get required data from server without refresh the page.

For Example
In Registration Page, We want to validate the unique email address of user


Following the Simple Steps to do more Secure your Ajax Call.

1. Ajax Check - Ajax url must give Response when request is from ajax.
 
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
echo "Ajax Call";
} else{
echo "No Ajax Call";
}

2. Domain Check - Ajax url must give response, when request from your own server.
if(!empty($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="WWW.mydomain.com/url")
{
 //Request from my server
}

3. Always use post Method 

4. Token System
 a) Create a token and encrypt  the data.
 b) Send with Ajax
 c) Before giving the result check the request with de-crypt

Saturday 22 February 2014

htaccess code snippets example

htaccess code snippets example

.htaccess file is used for configuration on File Level/Directory Level and its supported by all webserver. Today all types of websites use htaccess technology.



Following are Benefits of .htaccess
  • Mange Error Pages for Better SEO
  • Set PHP Config variable
  • Set Environment variable
  • Password protection for File/Directory
  • Allow/Deny visitors by IP Address
  • Detect OS (like Mobile/Laptop/Ios/Android)
  • Redirection pages 
  • Optimize Performance of website
  • Improve Site Security


Following are Few Example of .htaccess

Redirect Home page to Another Website
Redirect / http://php-tutorial-php.blogspot.in/


Redirect Home page to Another another Directory(i.e newdir)
Redirect / /newdir


Redirect about.html to Another another Directory(i.e /pages/about)
Redirect /about.html /pages/about


Redirect old file to New Path
Redirect /oldfile.html /newfile.html


Set PHP Environment
SetEnv APPLICATION_ENV development


Set max_filesize in php
php_value upload_max_filesize 32M


Set off error in PHP
php_flag display_errors off
php_flag display_startup_errors off


Dedect mobile/laptop and redirect to mobile site
RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ipad|ipod|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ http://mobile.domain.com/ [R,L]


Block IP Address
order allow,deny
deny from xxx.xxx.xxx.xxx #specify a specific address
deny from xxx.xxx.xxx.xxx/30 #specify a subnet range
deny from xxx.xxx.* #specify an IP address wildcard
allow from all


Allow IP Address
order allow,deny
allow from xxx.xxx.xxx.xxx #specify a specific address
allow from xxx.xxx.xxx.xxx/30 #specify a subnet range
allow from xxx.xxx.* #specify an IP address wildcard
allow from all


Redirect to 400.html, If 400 error comes
ErrorDocument 400 /errorpages/400.html


Redirect to 403.html, If 403 error comes
ErrorDocument 403 /errorpages/403.html


Redirect to 404.html, If 404 error comes
ErrorDocument 404 /errorpages/404.html


Redirect to 500.html, If 500 error comes
ErrorDocument 500 /errorpages/500.html


Disable Directory Listing
Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes


Enable Directory Listing
 Options All +Indexes


Password Protection
AuthName "Authentication Section"
AuthType Basic
AuthUserFile /home/username/.htpasswds #Here your password will be stored
#htpasswds file format username:password
Require valid-user


Password Protection but Google can Crawl
AuthName "Under Development"
AuthUserFile /home/website/.htpasswd
AuthType basic
Require valid-user
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx w3.org htmlhelp.com googlebot.com
Satisfy Any


Set Timezone of the Server
SetEnv TZ America/Indianapolis


301 Redirect Old File
Redirect 301 /old/file.html http://php-tutorial-php.blogspot.in/2013/12/curl-example.html


301 Redirect Entire Directory
Redirect 301 /old/ /new/



301 redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


301 redirect https to http://www
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


301 redirect non www to www with htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


Set Caching for javascript/image/css
ExpiresActive On
ExpiresByType application/javascript "now plus 3 day"
ExpiresByType application/x-javascript "now plus 3 day"
ExpiresByType image/jpg "now plus 1 week"
ExpiresByType image/jpeg "now plus 1 week"
ExpiresByType image/png "now plus 1 week"
ExpiresByType image/pjpeg "now plus 1 week"
ExpiresByType image/gif "now plus 1 week"
ExpiresByType text/css "now plus 3 day"


Error Codes - Defination
301 - Permanent movement(redirection)
302 - Temporary movement(redirection)
400 - Bad request
401 - Authorization Required
403 - Forbidden
404 - Page Not Found
500 - Internal Server Error


Wednesday 22 January 2014

Manage Cron Job with PHP - SSH2 Connection

Manage Cron Job with PHP - SSH2 Connection

Today, Cron play very vital role in our website. It reduce the lots of manual work like update the record, Caching the pages, Remove not-required data etc.


Following are use of Cron Job
  1. Update Database records
  2. Copy/Move data from one server to another server
  3. Caching the data for enhance the website performance
  4. Remove the Redundancy data
  5. Remove the un-necessary data.


If there are too-many cron jobs in our web application that its hard to manage the cron jobs through crontabs. Also sometimes Compmay Owner/Manger wants to mange the cron jobs through the Admin Panel.  

Here is sample code with use of which you can mange the cron jobs from PHP. Now you can add/update/delete the cron job from PHP.



        /** check ssh2 connection**/
        if (!function_exists("ssh2_connect")){
            die('ssh2 is not installed');
        }
        /** check ssh2 connection**/
        
        if (!($con = ssh2_connect("www.example.com", 22))) {
            echo "Domain Not exist";
        } else {
            // try to authenticate with username root, password secretpassword
            if (!ssh2_auth_password($con, "username", "password")) {
                echo "credentials is In-Correct";
            } else {
                // execute a command
                if (!($stream = ssh2_exec($con, "ls -al"))) {
                    echo "Execution Failed";
                } else {
                    /** Read output */
                    stream_set_blocking($stream, true);
                    $data = "";
                    while ($buf = fread($stream, 4096)) {
                        $data .= $buf;
                    }
                    fclose($stream);
                    
                    echo $data;
                     /** Read output */
                }
            }
        }



Wednesday 22 May 2013

Spoofed Forms - Stop Spoofed Form Submissions

Spoofed Forms - Stop Spoofed Form Submissions

It is method in which attacker create a copy of html form of another website, fill the data whatever he want to sent and submit the form.

There are various ways to spoof forms, the easiest of which is to simply copy a target form and
execute it from a different location. Spoofing a form makes it possible for an attacker
to remove all client-side validations/restrictions imposed upon the form in order to submit the form.


Street:
City:
State:
Zip:


See in above form, here form's action is of another website.


How to Protect your website from spoofed forms

  • Add client side and server side validation
  • Use token system
  • Use captcha

Thursday 4 October 2012

Session Fixation

Session Fixation

In this an attacker explicitly sets the session identifier of a session for a user. Typically in PHP it's done by giving them a url like http://www.mysite.com/index.php?session_name=session_id. Once the attacker gives the url to the client, the attack is the same as a session hijacking attack.
Default session_name is PHPSESSID
session_id is a unique string  and it is in the range a-z A-Z 0-9 , (comma) and - (minus)!

The most crucial piece of information for an attacker is the session identifier, because this is required for any impersonation attack. There are three common methods used to obtain a valid session identifier:

  1.     Prediction: Guessing a valid session identifier. With PHP's native session mechanism, the session identifier is extremely random, and this is unlikely to be the weakest point.
  2.     Capture: Capturing a valid session identifier is the most common type of session attack, and there are numerous approaches for capturing session_id,  because session identifiers are typically propagated in cookies or as GET variables.
  3.     Fixation:  Fixation is the simplest method of obtaining a valid session identifier by using session_id() after session_start()


What to do
By default session_name is PHPSESSID, so this session name either from php.ini file OR  with use of php function session_name. For example session_name('new_session_name')
Set session.use_trans_sid = 0 in your php.ini file. This will tell PHP not to include the identifier in the URL, and not to read the URL for identifiers.
Set session.use_only_cookies = 1 in your php.ini file. This will tell PHP to never use URLs with session identifiers.
Regenerate the session ID anytime the session's status changes. That means any of the following:
User authentication
  • Storing sensitive info in the session
  • Changing anything about the session




Session Hijacking in PHP

Session Hijacking

Session Hijacking is term where attackers hold of a session identifier and is able to send requests as if they were that user.
In particular, it is used to refer to the theft of a magic cookie used to authenticate a user to a remote server.
It has particular relevance to web developers, as the HTTP cookies used to maintain a session on many web sites can be easily stolen by an attacker using an intermediary computer or with access to the saved cookies on the victim's computer (see HTTP cookie theft).


How to prevent your data from Session Hijacking
1) In php.ini set session.hash_function = sha256 or session.hash_function = sha512.
2) In php.ini set  session.hash_bits_per_character = 5
3) Add "user agent" (browser) in session  & check each subsequent request.
4) Add IP Address in session  & check each subsequent request.
5) Change the name of the session from the default PHPSESSID
6) In secure pages ask for reenter the password.




Thursday 12 July 2012

Cross Site Request Forgery

Cross Site Request Forgery

Cross Site Request Forgery ( CSRF ) is a type of website exploit carried out by issuing unauthorized commands from a trusted website user.  CSRF exploits a website’s trust for a particular user's browser, as opposed to cross-site scripting, which exploits the user’s trust for a website.

A CSRF usually uses a browser's "GET" command as the exploit point. CSR forgers use HTML tags such as "IMG" to inject commands into a specific website. A particular user of that website is then used as a host and an unwitting accomplice. Often the website does not know that it is under attack, since a legitimate user is sending the commands. The attacker might issue a request to transfer funds to another account.
e.g
amanvera send some html having below img. unforunately at that time both user (poonm & amanvera) are login to their bank(i.e yourbank). whenever poonam execute the html code send by amanverma. following img src will execute self, and tranfer money from poonam to amanverma account.
<img src="http://www.yourbank.com/transfer?from=poonam&to=amanverma&amount=1000000">


A CSRF attack is hard to execute because a number of things have to happen in order for it to succeed:

  • The attacker must target either a website that does not check the referrer header (HTTP_REFERER) or a user/victim with a browser or plug-in bug that allows referrer spoofing (which is rare).
  • The attacker must locate a form submission at the target website, which must be capable of something like changing the victim's email address login credentials or doing money transfers.
  • The attacker must determine the correct values for all of the form's or URL's inputs. If any of them are required to be secret values or IDs that the attacker cannot accurately guess, the attack will fail.
  • The attacker must lure the user/victim to a Web page with malicious code while the victim is logged in to the target site.
For example, suppose that Person A is browsing his bank account while also in a chat room. There is an attacker (Person B) in the chat room who learns that Person A is also logged in to bank.com. Person B lures Person A to click on a link for a funny image. The "IMG" tag contains values for bank.com’s form inputs, which will effectively transfer a certain amount from Person A’s account into Person B’s account. If bank.com does not have secondary authentication for Person A before the funds are transferred, the attack will be successful.






Tuesday 10 July 2012

SQL Injection Attack - PHP & MySQL


In this attack, a  hacker is able to execute SQL queries in your website's database. This attack is usually performed by entering text into a form field which causes a subsequent SQL query, generated from the PHP form processing code, to execute part of the content of the form field as though it were SQL. The effects of this attack range from the harmless (simply using SELECT to pull another data set) to the devastating (DELETE, for instance).

It is a basically a trick to inject SQL command or query as a input mainly in the form of the POST or GET method in the web pages. Most of the websites takes parameter from the form and make SQL query to the database.
For a example, in a product detail page of php, it basically takes a parameter product_id from a GET method and get the product detail from database using SQL query. With SQL injection attack, a intruder can send a crafted SQL query from the URL of the product detail page and that could possibly do lots of damage to the database. And even in worse scenario, it could even drop the database table as well.


For Example
you have login page and ask user to login via putting username & password into form.
suppose that a intruder called user injected x’ OR ‘x’='x in the username field and x’ OR ‘x’='x in the password field. Then the final query will become like this.

SELECT * FROM users WHERE username=’x’ OR ‘x’='x’ AND password=’x’ OR ‘x’='x’;

Now what happen, it will return the first record of table users 
&
user who is not authorize, will be able to login in website.

use mysql_real_escape_string function to avoid the problem.




http://dev.mysql.com/tech-resources/articles/guide-to-php-security-ch3.pdf


How can I prevent SQL-injection in PHP?
1. USe PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
    /* Do your Action **/

    /* Do your Action **/
}


2. USe MySqlI instead of MySQL. MySQLI is far better than MySql
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    /* Do your Action **/

    /* Do your Action **/
}

3. Use framework and execute the query with framework like zend, cakephp and magento etc. But for this you must install the framework.