IT Community - Software Programming, Web Development and Technical Support

Security in PHP

This is a discussion on Security in PHP within the PHP Programming forums, part of the Web Development category; Hi Buddies Numeric Data Validation All data passed to PHP (GET/POST/COOKIE) ends up being a string. Using strings ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #21 (permalink)  
Old 03-21-2008, 02:41 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

Numeric Data Validation
All data passed to PHP (GET/POST/COOKIE) ends up being a string. Using strings where integers are needed is not only inefficient but also dangerous.

Casting is a simple and very efficient way to ensure that variables contain numeric values.

Example of floating point number validation
PHP Code:
     if (!empty($_GET['price']))      {  
                
$price = (float) $_GET['price'];
    }      else     
$price 0
Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #22 (permalink)  
Old 03-21-2008, 03:31 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

String Validation
PHP comes with a ctype, extension that offers a very quick mechanism for validating string content.

PHP Code:
if (!ctype_alnum($_GET['login'])) {
        echo 
"Only A-Za-z0-9 are allowed.";
}
if (!
ctype_alpha($_GET['captcha'])) {
        echo 
"Only A-Za-z are allowed.";
}
if (!
ctype_xdigit($_GET['color'])) {
        echo 
"Only hexadecimal values are allowed";


Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #23 (permalink)  
Old 03-21-2008, 03:32 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

Cross Site Scripting (XSS)
Cross Site Scripting (XSS) is a situation where by attacker injects HTML code, which is then displayed on the page without further validation.

Can lead to embarrassment
Session take-over
Password theft
User tracking by 3rd parties

Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #24 (permalink)  
Old 03-21-2008, 05:04 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

Prevention of XSS is as simple as filtering input data via one of
the following:

htmlspecialchars()
Encodes ‘, “, <, >, &
htmlentities()
Convert anything that there is HTML entity for.
strip_tags()
Strips anything that resembles HTML tag.

Tag allowances in strip_tags() are dangerous, because attributes of those tags are not being validated in any way.
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #25 (permalink)  
Old 03-21-2008, 05:05 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

Prevention of XSS

$str = strip_tags($_POST['message']);

// encode any foreign & special chars
$str = htmlentities($str);

// strip tags can be told to "keep" certain tags
$str = strip_tags($_POST['message'], '<b><p><i><u>');

// tag allowance problems
<u onmouseover="alert('JavaScript is allowed');">
<b style="font-size: 500px">Lot's of text</b>
</u>
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #26 (permalink)  
Old 03-21-2008, 06:31 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

SQL injection is similar to XSS, in the fact that not validated data
is being used. But in this case this data is passed to the database.

Arbitrary query execution
Removal of data.
Modification of existing values.
Denial of service.
Arbitrary data injection.

PHP Code:
// consider this query, it will delete all records from users
$name "ARUN"
DELETE FROM users;&#8221;;
mysql_query(&#8220;SELECT * FROM users WHERE name =’{$name}’”); 
__________________
Regards,
Senraj.A

Last edited by senraj : 03-21-2008 at 06:33 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #27 (permalink)  
Old 03-21-2008, 06:32 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Default Re: Security in PHP

Hi,

If your database extension offers a specific escaping function then always use it; instead of other methods

MySQL
mysql_escape_string()
mysql_real_escape_string()
PostgreSQL
pg_escape_string()
pg_escape_bytea()
SQLite
sqlite_escape_string()
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #28 (permalink)  
Old 03-21-2008, 06:34 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,
Sql Escaping
PHP Code:
// undo magic_quotes_gpc to avoid double 
    
if (get_magic_quotes_gpc()) {
        
$_GET['name'] = stripslashes($_GET['name'];
        
$_POST['binary'] = stripslashes($_GET['binary']);
    }

    
$name pg_escape_string($_GET['name']);
    
$binary pg_escape_bytea($_POST['binary']);

    
pg_query($db"INSERT INTO tbl (name,image)
            VALUES('{$name}', '{$image}')"
); 
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #29 (permalink)  
Old 03-21-2008, 06:36 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

When un-quoted integers are passed to SQL queries, escaping functions won’t save you, since there are no special chars to escape.

http://example.com/db.php?id=0;DELETE%20FROM%20users

PHP Code:
$id sqlite_escape_string($_GET['id']);
// $id is still 0;DELETE FROM users
sqlite_query($db,"SELECT * FROM users WHERE id={$id}");
// Bye Bye user data... 
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #30 (permalink)  
Old 03-21-2008, 06:39 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

Security in PHP Prepared Statements

Prepared statements are a mechanism to secure and optimize execution of repeated queries.

Works by making SQL “compile” the query and then substitute in the changing values for each execution.
Increased performance, one compile vs one per query.
Better security, data is “type set” will never be evaluated as
separate query.
Supported by most database systems.

MySQL users will need to use version 4.1 or higher.
SQLite extension does not support this either.
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #31 (permalink)  
Old 03-21-2008, 10:32 PM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

Security in PHP Prepared Statements

PHP Code:
$data "Here is some text to index";
pg_query($db"PREPARE my_stmt (text) AS
INSERT INTO search_idx (word) VALUES($1)"
);
foreach (
explode(" "$data) as $word
{
// no is escaping needed
pg_query($db"EXECUTE my_stmt({$word})");
}
// de-allocte the prepared statement
pg_query($db"DEALLOCATE my_stmt"); 
Unless explicitly removed, prepared statements “stay alive”
between persistent connections.
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #32 (permalink)  
Old 03-21-2008, 10:34 PM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

Code Injection is the execution of arbitrary local or remote code.

The two of the most common sources of code injection are:
Dynamic paths/files used in require/include statements
eval(): A major source of code injection is the improper validation of eval().
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #33 (permalink)  
Old 03-21-2008, 10:36 PM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

Avoid using dynamic or relative paths/files in your code. Although somewhat less convenient; always use full paths, defined by constants, which will prevent attacks like these:

PHP Code:
//dynamic path
$_GET['path'] = ‘http://test_site.org’;
include "{$_GET['path']}/header.inc";
//dynamic file
$_GET[‘interface’] = ../../../../../etc/passwd’;
require‘home/mbr/profile/templates_c/interfaces/.$_GET[‘interface’]; 
There are some other ways to secure include or require calls...
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #34 (permalink)  
Old 03-21-2008, 10:37 PM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

work with a white-list of acceptable values.
//create an array of acceptable file names
$tmpl = array();

foreach(glob("templates/*.tmpl") as $v)
{
$tmpl[md5($v)] = $v;
}

if (isset($tmpl[$_GET['path']]))
{
$fp = fopen($tmpl[$_GET['path']], "r");
}
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #35 (permalink)  
Old 03-24-2008, 05:19 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

Session Security
  • Sessions are a common tool for user tracking across a web site.
  • For the duration of a visit, the session is effectively the user’s identity.
  • If an active session can be obtained by 3rd party, it can assume the identity of the user who’s session was compromised.
Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #36 (permalink)  
Old 03-24-2008, 05:21 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

Securing Session ID
  • To prevent session id theft, the id can be altered on every request, invalidating old values.
PHP Code:
<?php
session_start
();
if (!empty(
$_SESSION)) { // not a new session
session_regenerate_id(TRUE); // make new session id
}
?>
  • Because the session changes on every request, the “back” button in a browser will no longer work, as it will make a request with the old session id.

Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #37 (permalink)  
Old 03-24-2008, 05:22 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

Session Validation
  • Another session security technique is to compare the browser signature headers.
PHP Code:
session_start();
$chk = @md5(
$_SERVER['HTTP_ACCEPT_CHARSET'] .
$_SERVER['HTTP_ACCEPT_ENCODING'] .
$_SERVER['HTTP_ACCEPT_LANGUAGE'] .
$_SERVER['HTTP_USER_AGENT']);
if (empty(
$_SESSION))
            
$_SESSION['key'] = $chk;
else if (
$_SESSION['key'] != $chk)
            
session_destroy(); 
Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #38 (permalink)  
Old 03-24-2008, 05:25 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 289
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

Safer Session Storage
  • By default PHP sessions are stored as files inside the common /tmp directory.
  • This often means any user on the system could see active sessions and “acquire” them or even modify their content.
  • Solutions?
  • Separate session storage directory via
  • session.save_path
  • Database storage mechanism, mysql, pgsql, oci, sqlite.
  • Custom session handler allowing data storage anywhere.
Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #39 (permalink)  
Old 03-24-2008, 08:21 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

Shared Hosting
  • Most PHP applications run in shared environments where all
    users “share” the same web server instances.
  • This means that all files that are involved in serving content must
    be accessible to the web server (world readable).
  • Consequently it means that any user could read the content of files of all other users.
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #40 (permalink)  
Old 03-24-2008, 08:22 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

The PHP Solution
  • PHP’s solution to this problem are 2 php.ini directives.
  • open_basedir – limits file access to one or more specified directories.
    1. Relatively Efficient.
    2. Uncomplicated.
  • safe_mode – limits file access based on uid/gid of running script
  • and file to be accessed.
    1. Slow and complex approach.
    2. Can be bypassed with little effort.
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post