secure php coding

36
Secure PHP Coding Narudom Roongsiriwong, CISSP

Upload: narudom-roongsiriwong-cissp

Post on 23-Jan-2018

3.959 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Secure PHP Coding

Secure PHP CodingNarudom Roongsiriwong CISSP

WhoAmIbull Lazy Blogger

ndash Japan Security FOSS Politics Christianndash httpnarudomrblogspotcom

bull Food Maniandash Steak Yakiniku BBQndash Sushi (especially Otoro)ndash All Kinds of Noodle

bull 16 Years In PHP Coding Since v40 (3rd fluent programming language next to C amp C++)

bull Consultant for OWASP Thailand Chapterbull Head of IT Security amp Solution Architecture

Kiatnakin Bank PLC (KKP)

How to Secure PHPHackerrsquos Recommendation

Is this believable

WTF

Any programming languages are the same secure coding or not

depends on programmers

Usage of Server-Side Programming Languages for Websites

PHP

ASPNET

Java

Static Files

Cold Fusion

Ruby

Perl

JavaScript

Python

Erlang

00 100 200 300 400 500 600 700 800 900

819

157

29

15

07

06

04

03

02

01

W3Techscom 11 September 2016

Web Apps in PHP are Most Vulnerablebull 86 of applications written in PHP contained at

least one cross-site scripting (XSS) vulnerability

bull 56 of apps included SQLi (SQL injection) which is one of the dangerous and easy-to-exploit web application vulnerabilities

bull 67 of apps allowed for directory traversal

bull 61 of apps allowed for code injection

bull 58 of apps had problems with credentials management

bull 73 of apps contained cryptographic issues

bull httpthehackernewscom201512programming-language-securityhtml

PHP Characteristicsbull Unusual rarr Language + Web Framework

bull A large community of libraries that contribute to programming in PHP

bull All three aspects (language framework and libraries) need to be taken into consideration when trying to secure a PHP site

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 2: Secure PHP Coding

WhoAmIbull Lazy Blogger

ndash Japan Security FOSS Politics Christianndash httpnarudomrblogspotcom

bull Food Maniandash Steak Yakiniku BBQndash Sushi (especially Otoro)ndash All Kinds of Noodle

bull 16 Years In PHP Coding Since v40 (3rd fluent programming language next to C amp C++)

bull Consultant for OWASP Thailand Chapterbull Head of IT Security amp Solution Architecture

Kiatnakin Bank PLC (KKP)

How to Secure PHPHackerrsquos Recommendation

Is this believable

WTF

Any programming languages are the same secure coding or not

depends on programmers

Usage of Server-Side Programming Languages for Websites

PHP

ASPNET

Java

Static Files

Cold Fusion

Ruby

Perl

JavaScript

Python

Erlang

00 100 200 300 400 500 600 700 800 900

819

157

29

15

07

06

04

03

02

01

W3Techscom 11 September 2016

Web Apps in PHP are Most Vulnerablebull 86 of applications written in PHP contained at

least one cross-site scripting (XSS) vulnerability

bull 56 of apps included SQLi (SQL injection) which is one of the dangerous and easy-to-exploit web application vulnerabilities

bull 67 of apps allowed for directory traversal

bull 61 of apps allowed for code injection

bull 58 of apps had problems with credentials management

bull 73 of apps contained cryptographic issues

bull httpthehackernewscom201512programming-language-securityhtml

PHP Characteristicsbull Unusual rarr Language + Web Framework

bull A large community of libraries that contribute to programming in PHP

bull All three aspects (language framework and libraries) need to be taken into consideration when trying to secure a PHP site

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 3: Secure PHP Coding

How to Secure PHPHackerrsquos Recommendation

Is this believable

WTF

Any programming languages are the same secure coding or not

depends on programmers

Usage of Server-Side Programming Languages for Websites

PHP

ASPNET

Java

Static Files

Cold Fusion

Ruby

Perl

JavaScript

Python

Erlang

00 100 200 300 400 500 600 700 800 900

819

157

29

15

07

06

04

03

02

01

W3Techscom 11 September 2016

Web Apps in PHP are Most Vulnerablebull 86 of applications written in PHP contained at

least one cross-site scripting (XSS) vulnerability

bull 56 of apps included SQLi (SQL injection) which is one of the dangerous and easy-to-exploit web application vulnerabilities

bull 67 of apps allowed for directory traversal

bull 61 of apps allowed for code injection

bull 58 of apps had problems with credentials management

bull 73 of apps contained cryptographic issues

bull httpthehackernewscom201512programming-language-securityhtml

PHP Characteristicsbull Unusual rarr Language + Web Framework

bull A large community of libraries that contribute to programming in PHP

bull All three aspects (language framework and libraries) need to be taken into consideration when trying to secure a PHP site

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 4: Secure PHP Coding

Is this believable

WTF

Any programming languages are the same secure coding or not

depends on programmers

Usage of Server-Side Programming Languages for Websites

PHP

ASPNET

Java

Static Files

Cold Fusion

Ruby

Perl

JavaScript

Python

Erlang

00 100 200 300 400 500 600 700 800 900

819

157

29

15

07

06

04

03

02

01

W3Techscom 11 September 2016

Web Apps in PHP are Most Vulnerablebull 86 of applications written in PHP contained at

least one cross-site scripting (XSS) vulnerability

bull 56 of apps included SQLi (SQL injection) which is one of the dangerous and easy-to-exploit web application vulnerabilities

bull 67 of apps allowed for directory traversal

bull 61 of apps allowed for code injection

bull 58 of apps had problems with credentials management

bull 73 of apps contained cryptographic issues

bull httpthehackernewscom201512programming-language-securityhtml

PHP Characteristicsbull Unusual rarr Language + Web Framework

bull A large community of libraries that contribute to programming in PHP

bull All three aspects (language framework and libraries) need to be taken into consideration when trying to secure a PHP site

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 5: Secure PHP Coding

Usage of Server-Side Programming Languages for Websites

PHP

ASPNET

Java

Static Files

Cold Fusion

Ruby

Perl

JavaScript

Python

Erlang

00 100 200 300 400 500 600 700 800 900

819

157

29

15

07

06

04

03

02

01

W3Techscom 11 September 2016

Web Apps in PHP are Most Vulnerablebull 86 of applications written in PHP contained at

least one cross-site scripting (XSS) vulnerability

bull 56 of apps included SQLi (SQL injection) which is one of the dangerous and easy-to-exploit web application vulnerabilities

bull 67 of apps allowed for directory traversal

bull 61 of apps allowed for code injection

bull 58 of apps had problems with credentials management

bull 73 of apps contained cryptographic issues

bull httpthehackernewscom201512programming-language-securityhtml

PHP Characteristicsbull Unusual rarr Language + Web Framework

bull A large community of libraries that contribute to programming in PHP

bull All three aspects (language framework and libraries) need to be taken into consideration when trying to secure a PHP site

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 6: Secure PHP Coding

Web Apps in PHP are Most Vulnerablebull 86 of applications written in PHP contained at

least one cross-site scripting (XSS) vulnerability

bull 56 of apps included SQLi (SQL injection) which is one of the dangerous and easy-to-exploit web application vulnerabilities

bull 67 of apps allowed for directory traversal

bull 61 of apps allowed for code injection

bull 58 of apps had problems with credentials management

bull 73 of apps contained cryptographic issues

bull httpthehackernewscom201512programming-language-securityhtml

PHP Characteristicsbull Unusual rarr Language + Web Framework

bull A large community of libraries that contribute to programming in PHP

bull All three aspects (language framework and libraries) need to be taken into consideration when trying to secure a PHP site

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 7: Secure PHP Coding

PHP Characteristicsbull Unusual rarr Language + Web Framework

bull A large community of libraries that contribute to programming in PHP

bull All three aspects (language framework and libraries) need to be taken into consideration when trying to secure a PHP site

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 8: Secure PHP Coding

Language Issuesbull Weak typing

bull Exceptions and error handling

bull phpini

bull Unhelpful builtins

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 9: Secure PHP Coding

Language Issue Weak Typingbull PHP will automatically convert data of an incorrect

type into the expected type $x = 1 + 1 x is 2

bull Leads to bugs injections and vulnerabilities if improperly handles

bull Try to use functions and operators that do not do implicit type conversions (eg === and not ==) but not all operators have strict version (such as lt or gt)

bull Many built-in functions (like in_array) use weakly typed comparison functions by default making it difficult to write correct code

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 10: Secure PHP Coding

Language Issue Weak Typing

$a = array(71)$exists = in_array(710 $a)var_dump($exists) true OMG

in_array()

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 11: Secure PHP Coding

Language Issue Weak Typing

$a = 0$b = xfalse == $a true$a == $b true$b == true true WTF

==

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 12: Secure PHP Coding

Language IssueException and Error Handlingbull Almost all PHP builtins and many PHP libraries do not

use exceptions but instead report errors then allow the faulty code to carry on running

bull Many other languages error conditions that failed to anticipate will stop running rarr Fail Safe

bull It is often best to turn up error reporting as high as possible using the error_reporting function and never attempt to suppress error messages mdash always follow the warnings and write code that is more robust

bull Try to use set_error_handler function to handle user defined error handler

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 13: Secure PHP Coding

Language IssueException and Error Handling

What is wrong with this code to check blacklist user

$db = mysqli_connect(localhost dbuser dbpassword dbname)

function can_access_feature($current_user) global $db$uid = mysqli_real_escape_string($db $current_user-gtuid)$res = mysqli_query($db SELECT COUNT(id) FROM blacklist WHERE uid = $uid)$row = mysqli_fetch_array($res)if ((int)$row[0] gt 0)

return false else

return true

if (can_access_feature($current_user)) exit()

Code for feature here

What happens if db connection is failed

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 14: Secure PHP Coding

Language Issue phpinibull PHP code often depends strongly on the

values of many configuration settings

bull Difficult to write code that works correctly in all circumstances

bull Difficult to correctly use 3rd party code

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 15: Secure PHP Coding

Language Issue Unhelpful Builtinsbull Built-in functions that appear to provide security

but buggy and hard to handle security problemsndash addslashes

ndash mysql_escape_stringndash mysql_real_escape_string

bull array data structurendash Extensively used in all PHP code and internally

ndash Confusing mix between an array and a dictionary ndash Cause even experienced PHP developers to

introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 16: Secure PHP Coding

Framework Issuesbull URL Routing ldquophprdquo or not

bull Input Handlingndash Instead of treating HTTP input as simple strings

PHP will build arrays from HTTP input

bull Template Languagendash However it doesnt do HTML escaping by defaultndash Lead to Cross-Site Scripting

bull Other Inadequaciesndash No CSRF protection mechanism

httpswwwowasporgindexphpPHP_Security_Cheat_SheetFramework_issues

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 17: Secure PHP Coding

Input Handling Example

$supplied_nonce = $_GET[nonce]$correct_nonce = get_correct_value_somehow() if (strcmp($supplied_nonce $correct_nonce) == 0) Go ahead and reset the password else echo Sorry incorrect link

A password reset code

If an attacker uses a query string like this httpexamplecomnonce[]=a Then $supplied_nonce is an array The function strcmp() will then return NULL Due to weak typing and the use of the == (equality) operator instead of the

=== (identity) operator the expression NULL == 0 The attacker will be able to reset the password without providing a correct

nonce

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 18: Secure PHP Coding

OWASP PHP Top 5bull P1 Remote Code Execution

bull P2 Cross-Site Scripting

bull P3 SQL Injection

bull P4 PHP Configuration

bull P5 File System Attacks

httpswwwowasporgindexphpPHP_Top_5

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 19: Secure PHP Coding

P1 Remote Code Executionbull Remote Code Execution or Arbitrary Code Execution is the

ability to trigger arbitrary code execution from one machine on another (especially via a wide-area network such as the Internet)

bull The most widespread PHP security issue since July 2004

bull The root causes of this issue arendash Insufficient validation of user input prior to dynamic file system calls

such as require or include or fopen()

ndash allow_url_fopen and PHP wrappers allow this behavior by default which is unnecessary for most applications

$handle = fopen(httpwwwexamplecom r)

ndash Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 20: Secure PHP Coding

P1 Remote Code Execution (contrsquod)bull Version Affected PHP 4 (after PHP 404) 5x

bull CVECAN Entries More than 100 such vulnerabilities reported since July 30 2004 for examplesndash Magento lt 206 (popular eCommerce platform) Unauthenticated

Remote Code Execution (CVE-2016-4010) httpnetanelrubin20160517magento-unauthenticated-remote-code-execution

ndash Joomla 15x 2x and 3x lt 346 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) httpwwwsecurityfocuscombid79195

ndash vBulletin 5 Connect 512 through 519 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) httpblogcheckpointcom20151105check-point-discovers-critical-vbulletin-0-day

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 21: Secure PHP Coding

How to Determine If You Are Vulnerable

$report = $_POST[lsquoreport_namersquo]include $report

$username = $_POST[lsquousernamersquo]eval(ldquoecho $usernamerdquo)

Inspect your code for constructs like

or

Other code constructs to look for include fopen() fsockopen() Direct command execution - popen() system() ` (backtick operator) Allows remote

attackers to execute code on the system without necessarily introducing remote code Direct PHP code execution via eval() Limited evaluation if the attacker supplied PHP code is then used within double

quotes in the application code ndash most useful as an information disclosure include include_once require require_once with dynamic inputs file_get_contents() imagecreatefromXXX() mkdir() unlink() and rmdir() and so on - PHP 50 and later has limited support for

some URL wrappers for almost all file functions

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 22: Secure PHP Coding

How to Protect Against Remote Code Execution bull Developers should

ndash Review existing code for file operations includerequire and eval() statements to ensure that user input is properly validated prior to first use

ndash When writing new code try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers

bull Hosters shouldndash Disable allow_url_fopen in phpini by setting it to 0

ndash Enable safe_mode and set open_basedir restrictions (if you know what youre doing - its not really that safe)

ndash Lockdown the server environment to prevent the server from making new outbound requests

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 23: Secure PHP Coding

P2 Cross-Site Scripting (XSS)bull Cross-site scripting (aka HTML injection or user agent

injection) can be in three modesndash Reflected The attacker provides a link or other payload

containing embedded malicious content which the application immediately displays back to the victim This is the primary form of phishing via e-mail (such as eBay scams bank scams etc)

ndash Persistent The attacker stores malicious content within a database which is then exposed to victims at a later time This is the most common form of XSS attack against forum and web mail software

ndash DOM The attacker uses the victim sitersquos JavaScript code to perform reflected XSS This technique is not widely used as yet but it is just as devastating as any form of cross-site scripting

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 24: Secure PHP Coding

P2 Cross-Site Scripting (XSS) (contrsquod)bull Version Affected Allbull CVECAN Entries More than 100 XSS entries since July

2004ndash WordPress le 452 Unspecified Cross Site Scripting Vulnerability

(CVE-2016-6634) httpwwwsecurityfocuscombid92390

ndash Joomla 34x lt 344 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) httpwwwsecuritytrackercomid1033541

ndash VBulletin Cross-site scripting httpwwwsecurityfocuscombid14874

ndash Coppermine Display Image Cross-site scripting httpwwwsecurityfocuscombid14625

ndash WordPress Edit Cross-site Scripting httpwwwsecurityfocuscombid13664

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 25: Secure PHP Coding

How to Determine If You Are Vulnerablebull Does the application rely upon register_globals to

work If so your application is at a slightly higher risk particularly if you do not validate input correctly

bull Inspect user input handling code for unsafe inputs

bull If you use Javascript to redirect the user (via documentlocation or windowopen any similar means) output to the user via documentwrite or modifies the DOM in any way you are likely to be at risk of DOM injection

echo $_POST[lsquoinputrsquo]

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 26: Secure PHP Coding

How to Protect Against Cross-site Scripting bull Turn off register_globals and ensure all variables are properly

initialized

bull Obtain user input directly from the correct location ($_POST $_GET etc) rather than relying on register_globals or the request object ($_REQUEST)

bull Validate input properly for type length and syntax

bull Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function)

bull Variables sent back to the user via URLs must be URL encoded using urlencode()

bull Validate JavaScript code against Kleinrsquos DOM Injection paper (httpcryptostanfordeducs155CSSpdf) to ensure that they are immune from DOM injection attacksndash

bull

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 27: Secure PHP Coding

P3 SQL Injectionbull A SQL injection attack consists of insertion or

injection of a SQL query via the input data from the client to the application

bull SQL injection exploits can read sensitive data modify execute administration operations and in some cases issue commands to the operating system

bull Most of PHP programmers use input parameters as concatenated strings to SQL statements$sql = SELECT FROM users WHERE username =

$username

What if $username is DROP TABLE users --

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 28: Secure PHP Coding

P3 SQL Injection (contrsquod)bull Version Affected All

bull CVECAN Entries More than 100 CVE CAN entries from multiple vendor for examplendash vBulletin 36x ndash 423 allows remote attackers to execute arbitrary

SQL commands via the postids parameter to forumrunnerrequestphp (CVE-2016-6195) httpsenumeratedwordpresscom201607111

ndash Wordpress lt 424 SQL injection vulnerability (CVE-2015-2213) httpscoretracwordpressorgchangeset33556

ndash Joomla 3x lt 347 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) httpwwwsecurityfocuscombid79679

bull Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 29: Secure PHP Coding

vBulletin SQL injection CVE-2016-6195The root of the vulnerability forumrunnerincludesmoderationphp

function do_get_spam_data() $vbulletin-gtinput-gtclean_array_gpc(r array(threadid =gt TYPE_STRINGpostids =gt TYPE_STRING))hellip

else if ($vbulletin-gtGPC[postids] = ) $postids = $vbulletin-gtGPC[postids]

$posts = $db-gtquery_read_slave(SELECT postpostid postthreadid postvisible posttitle postuserid threadforumid threadtitle AS thread_title threadpostuserid threadvisible AS thread_visible threadfirstpostid FROM TABLE_PREFIX post AS post LEFT JOIN TABLE_PREFIX thread AS thread USING (threadid) WHERE postid IN ($postids))

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 30: Secure PHP Coding

Wordpress SQL Injection Fixes in 424 for CVE-2015-2213

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 31: Secure PHP Coding

How to Determine If You Are Vulnerablebull Find code which calls mysql_query() or similar database

interfacesbull Inspect if any calls create dynamic queries using user input

$query = SELECT id name inserted size FROM products WHERE size = $size$result = odbc_exec($conn $query)

union select 1 concat(uname||-||passwd) as name 1971-01-01 0 from usertable

What if $size is

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 32: Secure PHP Coding

How to Protect Against SQL Injectionbull Migrate code to PHP 51 and use PDO or if this is not possible at

least migrate code to safer constructs such as PEARDBrsquos parameterized statements or the MySQLi interfaces

bull Validate data for correct type length and syntax

bull Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use

bull Use white listing (positive validation) data over black listing which is akin to virus patterns ndash always out of date and always insufficient against advanced attacks

bull As a last resort code should be using mysql_real_escape_string() (but not addslashes() which is insufficient) This provides limited protection to simple SQL injections

bull Provide a htaccess file to ensure that register_globals and magic_quotes are forced off and that all variables are properly initialized and validated

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 33: Secure PHP Coding

P4 PHP Configurationbull PHP Configuration has a direct bearing on the severity of

attacksbull No agreed secure PHP configurationbull Arguments for and against the most common security options

ndash register_globals (off by default in PHP ge 42 should be off REMOVED as of PHP 540)

ndash allow_url_fopen (enabled by default should be off available since PHP 404)

ndash magic_quotes_gpc (on by default in modern PHP should be off REMOVED as of PHP 540)

ndash magic_quotes_runtime (off by default in modern PHP should be of REMOVED as of PHP 540)

ndash safe_mode and open_basedir (disabled by default should be enabled and correctly configured Be aware that safe_mode really isnt safe and can be worse than useless)

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 34: Secure PHP Coding

P5 File System Attacksbull PHP developers have many ways to obviate security on shared hosts

with local file system attacks particularly in shared environmentsndash Local file inclusion (such as etcpasswd configuration files or logs)

ndash Local session tampering (which is usually in tmp)

ndash Local file upload injection (usually part of image attachment handling)

bull As most hosters run PHP as ldquonobodyrdquo under Apache local file system vulnerabilities affect all users within a single host

bull Version Affected PHP 3 4 5

bull CVECAN Entries As there have been many examples over years for examplesndash phpMyAdmin Local file exposure able to exploit the LOAD LOCAL INFILE

functionality to expose files on the server to the database system (CVE-2016-6612) httpswwwphpmyadminnetsecurityPMASA-2016-35

ndash phpMyAdmin Local File Inclusion (CVE-2011-2643) httpswwwphpmyadminnetsecurityPMASA-2011-10

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 35: Secure PHP Coding

PhpMyAdmin 340 ndash 3431CVE-2011-2643

Source httpfdthe-wildcatdepma_e36a587a73php

  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions
Page 36: Secure PHP Coding
  • Scripting The Web
  • Slide 2
  • Slide 3
  • Slide 4
  • Slide 5
  • Slide 6
  • Slide 7
  • Slide 8
  • Slide 9
  • Slide 10
  • Slide 11
  • Slide 12
  • Slide 13
  • Slide 14
  • Slide 15
  • Slide 16
  • Slide 17
  • Slide 18
  • Slide 19
  • Slide 20
  • Slide 21
  • Slide 22
  • Slide 23
  • Slide 24
  • Slide 25
  • Slide 26
  • Slide 27
  • Slide 28
  • Slide 29
  • Slide 30
  • Slide 31
  • Slide 32
  • Slide 33
  • Slide 34
  • Slide 35
  • Questions