PHP Security

Steven Roddis

The Geek Guys

Covering

Also Covering

Flaw vs Exploit

Flaw: –noun a feature that mars the perfection of something; defect; fault…
Exploit: –verb to utilize, esp. for profit; turn to practical account…

Example Code

<?php
include($foo,'.php');
?>

Register globals

<?php
$l 
$db->query($sql'array_assoc');
if(
$l)
{
$userid intval($l['id']);
}
/* SQL Query
involving the raw
$userid */
?>

Allow_url_fopen


include($foo,'.php');

http://www.example.org/evil?
../../ -> needs arbitary code already on server.

include('/a/'.$x.'.x');
%00 NULL Bytes -> Truncate String

You can turn allow_url_fopen in: .htaccess and php.ini

Error Reporting

Valuable information
Aids in exploitation


php_flag display_errors Off
set_error_handler('foo');
error_reporting(0);

Session Attacks

Session Fixation
http://www.example.org/?PHPSESSID=18a2d0e80c717f32e829100e09fb0d9b
session_start();
if(authenticate())
{
session_regenerate_id();
}

Cross Site Scripting (XSS)

htmlentities($str, ENT_QUOTES, 'UTF-8');
urlencode()
<img src="javascript: alert('a');" alt="" />

<img src="http://www.example.org/shop/cart.php?buy=32" style="display:none;" />

Nonce

A nonce is a number used once
<img src="http://www.example.org/shop/cart.php?buy=32" style="display:none;" />

Referers do not work!

SQL Injections

<?php
$baz 
"A' OR 1=1 –– "//User supplied input
$sql "SELECT * FROM `foo` WHERE bar='$baz'";
?>

Prevention:


N.B. Specify Database Connection Resource
to protect against Multibyte Character Exploits.

Shared Hosts

Hide PHP and Apache versions

Apache:

ServerTokens ProductOnly
ServerSignature Off

PHP:

expose_php = Off

These help prevent automated scanners. And may hinder some attackers.

Mail()

Ye Old Mail()

Header Splitting means spam.

Prevention

str_replace("\r\n", '', $foo); will not fix it completely.
Validate email addresses.

Validate Email Address

<?php
function goodemail($email) {
if (
eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)
(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" 
$email))
{
    return 
true;
}
return 
false;
}
?>

Automated Testing


Suhosin

Suhosin is an advanced protection system for PHP installations.

Small overhead (~2% in real world)

Protects against attacks

PHP Engine Protection, Filtering, Session and Logging Features


Hardened PHP Project

Hardened PHP Project & Zend Optimiser do not mix.

Faster than Suhosin, at the expense of less protection.

MySQL LIKE Quandary


How:

<?php
$title 
addcslashes(mysql_real_escape_string(
"%evilness_"), "%_");
// $title == \%evilness\_
mysql_query("SELECT * FROM books WHERE title LIKE
 '$title%'"
);
?>

Web Application Firewalls (modSecurity)

Provides additional protection against attacks, such as NULL Bytes, Mail() Injection, disables bad configurations such as allow_url_fopen.

Link: modSecurity (FOSS)

Shameless Plug

stevenroddis.com.au






bye