September 2012

Web Services



Web service are applications using open protocols and standards to exchange data between applications or systems.Software applications written in various programming languages(Php, Python, Java etc.) and running on various platforms(Linux, Windows etc.) can use web services to exchange data over computer networks(Internet, Intranet, etc) in a manner similar to inter-process communication on a single computer.

Security


1. Avoid using uninitialized variable. 
If the register_globals(php.ini) is turned on , the uninitialized variable can cause security breach.

Example:


Following code is used to recognize admin in 'test.php' script.

<?php
    if($user==0) {
          $admin = true;
    }
?>

If register_globals is on, the url http://www.testdomain.com/test.php?user=0 will declare $user as a global variable with no code required and thus provide admin status.




2. Never trust user data

Example:

<?php
    readfile($_POST['filename']);
?>

In this case if you really want the user to be able to specify a filename that gets used in any of PHP's file functions, do something like this:

<?php
    $doc_root = $_SERVER['DOCUMENT_ROOT'];
    $filename = realpath($filename);
    readfile($doc_root.$filename);
?>

You may also want to strip out any path and only take the filename component. An easy way to do that is to use the basename() function. Or perhaps check the extension of the file. You can get the extension using this code:

<?php
$ext = substr($str,strrpos($str,'.'));
?>


3. Make sure users can't pass in arguments that executes other system calls, make sure that the argument itself is ok and only accesses data you want the users to have access to.

Example:

<?php
system("ls $dir");
?>

In this example you want to make sure that the user can't pass in $dir set to something like: ".;cat/etc/passwd". The remedy is to use escapeshellarg() which places the argument inside single quotes and escapes any single quote characters in the string.

<?php
$dir=escapeshellarg($dir);
system("ls $dir");
?>


4. Place included files outside of the DOCUMENT_ROOT directory.

Many users place code in multiple files and include these files:
<?php
require 'functions.inc';
?>

Or perhaps

<?php
require 'functions.php';
?>

Both of these can be problematic if the included file is accessible somewhere under the DOCUMENT_ROOT directory. The best solution is to place these files outside of the DOCUMENT_ROOT directory where they are not accessible directly. You can add this external directory to your include_path configuration setting. Another option is to reject any direct requests for these files in your Apache configuration. You can use a rule like this in your "httpd.conf" file:

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

Register Globals

PHP automatically creates global variables containing data from a variety of external sources EGPCS (Environment, GET, POST, Cookie, Server).register_globals setting in PHP's configuration file (php.ini)(which can be either On or Off) tells whether or not to register the contents of the EGPCS variables as global variables.

Example 1:
To start a session use session_start() and to register a variable in this session use the $_SESSION array.

<?php
session_start();
$_SESSION['my_var'] = 'Hello World';
?>
If register_globals is enabled then your session variables will be available as normal variables on subsequent pages.
<?php
session_start();
echo $my_var;
?>
And If register_globals is enabled, then it will only be in the $_SESSION array.
<?php
session_start();
echo $_SESSION['my_var'];
?>


Example 2:

If register_globals is on, the url http://www.testdomain.com/test.php?id=3 will declare $id as a global variable with no code required.


Note : This feature is a great security risk, and you should ensure that register_globals is Off for all scripts (as of PHP 4.2.0 this is the default).

PHP Opcode Caches

Opcode (operation codes) caching is used to accelerate execution of browser request by caching the operational code. Caching the compiled bytecode(Opcode) of php script avoid the overhead of parsing & compiling code every time.
           The cached code is stored in shared memory or ram and directly is available for execution, without spending time for slow disk reads and memory copying at runtime.



Fig 1 : Execution of PHP script without an Opcode Cache


Execution of PHP script with an Opcode Cache


Fig 2: Execution of PHP script with an Opcode Cache 


There are number of Opcode Caches available. Some of them are :

  1. APC (Alternative PHP Cache) is a free and open opcode cache for PHP. APC framework optimizes PHP intermediate code and caches data and compiled code from the PHP bytecode compiler in memory.
  2. Zend Cache - commercial (developed by zend the php company).
  3. IonCube Accelerator - free, but closed source, Launched in 2001.
  4. XCache is a fast, stable PHP opcode cacher that has been tested and is now running on production servers under high load.



Best practice (optimization)

1. References
Use of references are slower than making copies of original data and than manipulate it. So use references only when you have large data structs to save memory. The use of references depends on your system, if your system is CPU bound avoid using the references and if your system is memory bound use references.

2. Persistent Database connections
Generally databases are slower to establish connections so it is better to use persistent db connection. But persistent connections will consume and tie up resources even when not in use so watch your resource limits before making tradeoff.

3. Avoid using regex
Php have good sets of string manipulation functions:

    <?php ereg_replace("-","_",$str); ?>Bad
    <?php str_replace("-", "_", $str);?>Good


4. mysql_unbuffered_query()
The function mysql_unbuffered_query() is same as mysql_query() except that instead of waiting for the entire query to execute and storing the result in the client API, it makes results available to you as soon as possible and they are not allocated in the client API. So you get access to data quicker and uses less memory. You can't use mysql_num_rows() on the result resource and it is likely to be slightly slower for small selects.

Sessions

Sessions are used to store data on server and retrieve it for a user while they travel through a series of pages, or page iterations, on your site. They are same as cookie , the only difference is that they are stored at server while cookie stored at client machine.

To start session
<?php
    session_start();
    $_SESSION['variable1'] = 'value1';
?>

To retrieve variable on other script/page use
<?php
    session_start();
    echo $_SESSION['variable1'];
?>

Cookies

Storing data at client machine.The expires time is in seconds.

Setting a session cookie
<?php
setcookie('Cookie_name','value','expire_time');
// If expire_time set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
?>

Setting a persistant cookie
<?php
setcookie('Cookie_name','value',mktime.time()+60*60); // Expires after 60 min.
?>

Reading a cookie
<?php
echo $_COOKIE['Cookie_name'];
?>

Deleting the Cookies
<?php
setcookie('Cookie_name','',mktime.time()-60); // Set expire time to negative time deletes a cookie.
?>

Other Optional Parameters
Path, Domain, and Secure parameters can also be set to restrict a cookie to a certain path, domain or
in the case of the Secure parameter, limit the cookie to only be set if the request came in over an SSL
connection.

Common Problem : Short expiry cookies depend on users having their system clocks set correctly.
Solution : Don't depend on the users having their clocks set right. Embed the timeout based on your server's
clock in the cookie.
Example:
At the cookie setting script :
<?php
$variable = 'Data to be stored in cookie'; // Data to be store
$value = time()+60 .':'.$varaible; // Concatenate the current(server) time + Data to be store
setcookie('Cookie_name',$value);
?>
At the receiving (getting cookie)script :
<?php
$value = $_COOKIE['Cookie_name']; // Getting the whole string stored in cookie
$valueArray = explode(':',$value);

if($valueArray[0]<=time()){ // Is valid cookie
    $variable = $valueArray[1];
}else{ // Expired cookie
    setcookie('Cookie_name','',mktime.time()-60); // deleting the cookie
}
?>

HTTP Headers

You can add headers to the HTTP response in PHP using the Header() function. Since the response
headers are sent before any of the actual response data, you have to send these headers before
outputting any data.
Examples :

Example 1. Prompt user to save a generated PDF file.
<?php
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='downloaded.pdf'");
?>

Example 2. Redirect browser
<?php
header("Location: http://www.example.com/");
?>

Example 3. Hide away your environment information (if you cannot do this at server level)
<?php
header('Server: ');
header('X-Powered-By: ');
?>

Removing Cache from the page

There are two methods of avoiding a page to be stored in browser cache. 1st method is better because each browser interprete Meta tag differently.

1. Using the PHP Header. Use the following code before rendering any output to the browser.
    <?php
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header("Cache-Control: post-check=0, pre-check=0", false);
    header('Pragma: no-cache');
    header('Expires: Mon,26 Jul 1980 05:00:00 GMT');
    header("Last-Modified: Tue,01 Jan 2000 00:00:00 GMT");
    ?>

2. Using the HTML Meta tag.
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

Newer Posts

Related Posts Plugin for WordPress, Blogger...
Powered by Blogger.