SlideShare a Scribd company logo
1 of 36
Download to read offline
Secure PHP Coding
Narudom Roongsiriwong, CISSP
WhoAmI
• Lazy Blogger
– Japan, Security, FOSS, Politics, Christian
– http://narudomr.blogspot.com
• Food Mania
– Steak, Yakiniku, BBQ
– Sushi (especially Otoro)
– All Kinds of Noodle
• 16 Years In PHP Coding, Since v4.0
(3rd fluent programming language next to C & C++)
• Consultant for OWASP Thailand Chapter
• Head of IT Security & Solution Architecture,
Kiatnakin Bank PLC (KKP)
How to Secure PHP
Hacker’s 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
ASP.NET
Java
Static Files
Cold Fusion
Ruby
Perl
JavaScript
Python
Erlang
0.0% 10.0% 20.0% 30.0% 40.0% 50.0% 60.0% 70.0% 80.0% 90.0%
81.9%
15.7%
2.9%
1.5%
0.7%
0.6%
0.4%
0.3%
0.2%
0.1%
W3Techs.com, 11 September 2016
Web Apps in PHP are Most Vulnerable
• 86% of applications written in PHP contained at
least one cross-site scripting (XSS) vulnerability.
• 56% of apps included SQLi (SQL injection),
which is one of the dangerous and easy-to-
exploit web application vulnerabilities.
• 67% of apps allowed for directory traversal.
• 61% of apps allowed for code injection.
• 58% of apps had problems with credentials
management
• 73% of apps contained cryptographic issues.
• http://thehackernews.com/2015/12/programming-language-security.html
PHP Characteristics
• Unusual → Language + Web Framework
• A large community of libraries that
contribute to programming in PHP
• All three aspects (language, framework,
and libraries) need to be taken into
consideration when trying to secure a PHP
site
Language Issues
• Weak typing
• Exceptions and error handling
• php.ini
• Unhelpful builtins
Language Issue: Weak Typing
• PHP will automatically convert data of an incorrect
type into the expected type.
$x = 1 + "1"; // x is 2
• Leads to bugs, injections and vulnerabilities if
improperly handles
• Try to use functions and operators that do not do
implicit type conversions (e.g. === and not ==) but
not all operators have strict version (such as < or >)
• 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('7.1');
$exists = in_array('7.10', $a);
var_dump($exists);
// true
// OMG
in_array()
Language Issue: Weak Typing
$a = 0;
$b = 'x';
false == $a;
// true
$a == $b;
// true
$b == true;
// true
// WTF
==
Language Issue:
Exception and Error Handling
• 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.
• Many other languages, error conditions that failed to
anticipate will stop running. → Fail Safe
• 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 — always follow
the warnings and write code that is more robust.
• Try to use set_error_handler function to handle user
defined error handler.
Language Issue:
Exception 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->uid);
$res = mysqli_query($db, "SELECT COUNT(id) FROM blacklist WHERE uid = '$uid';");
$row = mysqli_fetch_array($res);
if ((int)$row[0] > 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: php.ini
• PHP code often depends strongly on the
values of many configuration settings
• Difficult to write code that works correctly in
all circumstances.
• Difficult to correctly use 3rd party code
Language Issue: Unhelpful Builtins
• Built-in functions that appear to provide security,
but buggy and hard to handle security problems
– addslashes
– mysql_escape_string
– mysql_real_escape_string
• 'array' data structure
– Extensively used in all PHP code and internally
– Confusing mix between an array and a dictionary
– Cause even experienced PHP developers to
introduce critical security vulnerabilities such as
Drupal SA-CORE-2014-005 (CVE-2014-3704)
Framework Issues
• URL Routing: “.php” or not
• Input Handling
– Instead of treating HTTP input as simple strings,
PHP will build arrays from HTTP input
• Template Language
– However, it doesn't do HTML escaping by default
– Lead to Cross-Site Scripting
• Other Inadequacies
– No CSRF protection mechanism
https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet#Framework_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:
http://example.com/?nonce[]=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 5
• P1: Remote Code Execution
• P2: Cross-Site Scripting
• P3: SQL Injection
• P4: PHP Configuration
• P5: File System Attacks
https://www.owasp.org/index.php/PHP_Top_5
P1: Remote Code Execution
• 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)
• The most widespread PHP security issue since July 2004
• The root causes of this issue are:
– Insufficient validation of user input prior to dynamic file system calls,
such as require or include or fopen()
– allow_url_fopen and PHP wrappers allow this behavior by default,
which is unnecessary for most applications
$handle = fopen("http://www.example.com/", "r");
– 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 (cont’d)
• Version Affected: PHP 4 (after PHP 4.0.4), 5.x
• CVE/CAN Entries: More than 100 such vulnerabilities reported
since July 30, 2004, for examples:
– Magento < 2.0.6 (popular eCommerce platform) Unauthenticated
Remote Code Execution (CVE-2016-4010)
http://netanelrub.in/2016/05/17/magento-unauthenticated-remote-
code-execution/
– Joomla! 1.5.x, 2.x, and 3.x < 3.4.6 allow remote attackers to conduct
PHP object injection attacks and execute arbitrary PHP code via the
HTTP User-Agent header (CVE-2015-8562)
http://www.securityfocus.com/bid/79195
– vBulletin 5 Connect 5.1.2 through 5.1.9 allows remote attackers to
conduct PHP object injection attacks and execute arbitrary PHP code
(CVE-2015-7808) http://blog.checkpoint.com/2015/11/05/check-point-
discovers-critical-vbulletin-0-day/
How to Determine If You Are Vulnerable
$report = $_POST[‘report_name’];
include $report;
$username = $_POST[‘username’];
eval(“echo $username”);
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 – 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 5.0 and later has limited support for
some URL wrappers for almost all file functions
How to Protect Against Remote Code
Execution
• Developers should
– Review existing code for file operations, include/require, and
eval() statements to ensure that user input is properly validated
prior to first use
– When writing new code, try to limit the use of dynamic inputs
from users to vulnerable functions either directly or via wrappers
• Hosters should:
– Disable allow_url_fopen in php.ini by setting it to 0
– Enable safe_mode and set open_basedir restrictions (if you
know what you're doing - it's not really that safe!)
– Lockdown the server environment to prevent the server from
making new outbound requests
P2: Cross-Site Scripting (XSS)
• Cross-site scripting (aka. HTML injection or user agent
injection) can be in three modes
– 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)
– 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.
– DOM: The attacker uses the victim site’s 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) (cont’d)
• Version Affected: All
• CVE/CAN Entries: More than 100 XSS entries since July
2004.
– WordPress ≤ 4.5.2 Unspecified Cross Site Scripting Vulnerability
(CVE-2016-6634) http://www.securityfocus.com/bid/92390
– Joomla! 3.4.x < 3.4.4 allows remote attackers to inject arbitrary
web script or HTML (CVE-2015-6939)
http://www.securitytracker.com/id/1033541
– VBulletin Cross-site scripting
http://www.securityfocus.com/bid/14874
– Coppermine Display Image Cross-site scripting
http://www.securityfocus.com/bid/14625
– WordPress Edit Cross-site Scripting
http://www.securityfocus.com/bid/13664
How to Determine If You Are Vulnerable
• 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.
• Inspect user input handling code for unsafe inputs:
• If you use Javascript to redirect the user (via
document.location or window.open any similar
means), output to the user via document.write, or
modifies the DOM in any way, you are likely to be at
risk of DOM injection.
echo $_POST[‘input’];
How to Protect Against Cross-site
Scripting
• Turn off register_globals and ensure all variables are properly
initialized
• Obtain user input directly from the correct location ($_POST,
$_GET, etc) rather than relying on register_globals or the request
object ($_REQUEST)
• Validate input properly for type, length, and syntax
• Free text input can only be safely re-displayed to the user after
using HTML entities (htmlentities() function)
• Variables sent back to the user via URLs must be URL encoded
using urlencode()
• Validate JavaScript code against Klein’s DOM Injection paper
(http://crypto.stanford.edu/cs155/CSS.pdf) to ensure that they are
immune from DOM injection attacks
–
•
P3: SQL Injection
• A SQL injection attack consists of insertion or
"injection" of a SQL query via the input data from the
client to the application.
• SQL injection exploits can read sensitive data, modify,
execute administration operations and in some cases
issue commands to the operating system
• 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 (cont’d)
• Version Affected: All
• CVE/CAN Entries: More than 100 CVE / CAN entries from
multiple vendor, for example:
– vBulletin 3.6.x – 4.2.3 allows remote attackers to execute arbitrary
SQL commands via the postids parameter to
forumrunner/request.php (CVE-2016-6195)
https://enumerated.wordpress.com/2016/07/11/1/
– Wordpress < 4.2.4 SQL injection vulnerability (CVE-2015-2213)
https://core.trac.wordpress.org/changeset/33556
– Joomla! 3.x < 3.4.7 allows attackers to execute arbitrary SQL
commands (CVE-2015-8769)
http://www.securityfocus.com/bid/79679
• Bugtraq usually offers up two to three different PHP
applications with SQL injection vulnerabilities per day
vBulletin SQL injection CVE-2016-6195
The root of the vulnerability, /forumrunner/includes/moderation.php:
function do_get_spam_data() {
...
$vbulletin->input->clean_array_gpc('r', array(
'threadid' => TYPE_STRING,
'postids' => TYPE_STRING,
));
…
} else if ($vbulletin->GPC['postids'] != ") {
$postids = $vbulletin->GPC['postids'];
$posts = $db->query_read_slave("SELECT post.postid,
post.threadid, post.visible, post.title, post.userid,
thread.forumid, thread.title AS thread_title, thread.postuserid,
thread.visible AS thread_visible, thread.firstpostid FROM " .
TABLE_PREFIX . "post AS post LEFT JOIN " . TABLE_PREFIX .
"thread AS thread USING (threadid) WHERE postid IN ($postids)");
Wordpress SQL Injection Fixes in 4.2.4
for CVE-2015-2213
How to Determine If You Are Vulnerable
• Find code which calls mysql_query() or similar database
interfaces
• 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 Injection
• Migrate code to PHP 5.1 and use PDO, or if this is not possible, at
least migrate code to safer constructs, such as PEAR::DB’s
parameterized statements or the MySQLi interfaces
• Validate data for correct type, length, and syntax.
• Do not use dynamic table names - escape functions are not designed
for this use and are not safe for this use.
• Use white listing (positive validation) data over black listing, which is
akin to virus patterns – always out of date, and always insufficient
against advanced attacks
• 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.
• 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 Configuration
• PHP Configuration has a direct bearing on the severity of
attacks.
• No agreed "secure" PHP configuration
• Arguments for and against the most common security options:
– register_globals (off by default in PHP ≥ 4.2, should be off, REMOVED
as of PHP 5.4.0)
– allow_url_fopen (enabled by default, should be off, available since PHP
4.0.4)
– magic_quotes_gpc (on by default in modern PHP, should be off,
REMOVED as of PHP 5.4.0)
– magic_quotes_runtime (off by default in modern PHP, should be of,
REMOVED as of PHP 5.4.0)
– safe_mode and open_basedir (disabled by default, should be enabled
and correctly configured. Be aware that safe_mode really isn't safe and
can be worse than useless)
P5: File System Attacks
• PHP developers have many ways to obviate security on shared hosts
with local file system attacks, particularly in shared environments:
– Local file inclusion (such as /etc/passwd, configuration files, or logs)
– Local session tampering (which is usually in /tmp)
– Local file upload injection (usually part of image attachment handling)
• As most hosters run PHP as “nobody” under Apache, local file
system vulnerabilities affect all users within a single host.
• Version Affected: PHP 3, 4, 5
• CVE/CAN Entries: As there have been many examples over years,
for examples:
– 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) https://www.phpmyadmin.net/security/PMASA-2016-35/
– phpMyAdmin Local File Inclusion (CVE-2011-2643)
https://www.phpmyadmin.net/security/PMASA-2011-10/
PhpMyAdmin 3.4.0 – 3.4.3.1
CVE-2011-2643
Source: http://fd.the-wildcat.de/pma_e36a587a73.php
Secure PHP Coding

More Related Content

What's hot

OWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesOWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesSoftware Guru
 
Understanding Cross-site Request Forgery
Understanding Cross-site Request ForgeryUnderstanding Cross-site Request Forgery
Understanding Cross-site Request ForgeryDaniel Miessler
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewMichael Furman
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Codemotion
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaCODE WHITE GmbH
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Moataz Kamel
 
Secure code practices
Secure code practicesSecure code practices
Secure code practicesHina Rawal
 
OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)TzahiArabov
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMMikhail Egorov
 
Secure code
Secure codeSecure code
Secure codeddeogun
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with examplePrateek Chauhan
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySandip Chaudhari
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Brian Huff
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionSina Manavi
 

What's hot (20)

OWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application VulnerabilitiesOWASP Top 10 Web Application Vulnerabilities
OWASP Top 10 Web Application Vulnerabilities
 
Understanding Cross-site Request Forgery
Understanding Cross-site Request ForgeryUnderstanding Cross-site Request Forgery
Understanding Cross-site Request Forgery
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's New
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 
OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)
 
Owasp Top 10 A1: Injection
Owasp Top 10 A1: InjectionOwasp Top 10 A1: Injection
Owasp Top 10 A1: Injection
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORM
 
Secure code
Secure codeSecure code
Secure code
 
Sql injections - with example
Sql injections - with exampleSql injections - with example
Sql injections - with example
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
A Brief Introduction in SQL Injection
A Brief Introduction in SQL InjectionA Brief Introduction in SQL Injection
A Brief Introduction in SQL Injection
 

Viewers also liked

OWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object ReferenceOWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object ReferenceNarudom Roongsiriwong, CISSP
 
Leaflet secure coding in php
Leaflet secure coding in phpLeaflet secure coding in php
Leaflet secure coding in phpSebyde
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Colin O'Dell
 
Secure Coding For Java - Une introduction
Secure Coding For Java - Une introductionSecure Coding For Java - Une introduction
Secure Coding For Java - Une introductionSebastien Gioria
 
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best PracticesSecure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best PracticesWebsecurify
 
Top 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security ProblemsTop 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security ProblemsNarudom Roongsiriwong, CISSP
 
Accelerate your business and reduce cost with OpenStack
Accelerate your business and reduce cost with OpenStackAccelerate your business and reduce cost with OpenStack
Accelerate your business and reduce cost with OpenStackOpsta
 

Viewers also liked (20)

Secure Code Review 101
Secure Code Review 101Secure Code Review 101
Secure Code Review 101
 
AnyID and Privacy
AnyID and PrivacyAnyID and Privacy
AnyID and Privacy
 
Securing the Internet from Cyber Criminals
Securing the Internet from Cyber CriminalsSecuring the Internet from Cyber Criminals
Securing the Internet from Cyber Criminals
 
Secure Software Development Adoption Strategy
Secure Software Development Adoption StrategySecure Software Development Adoption Strategy
Secure Software Development Adoption Strategy
 
OWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object ReferenceOWASP Top 10 A4 – Insecure Direct Object Reference
OWASP Top 10 A4 – Insecure Direct Object Reference
 
Unlock Security Insight from Machine Data
Unlock Security Insight from Machine DataUnlock Security Insight from Machine Data
Unlock Security Insight from Machine Data
 
Application Security: Last Line of Defense
Application Security: Last Line of DefenseApplication Security: Last Line of Defense
Application Security: Last Line of Defense
 
Payment Card System Overview
Payment Card System OverviewPayment Card System Overview
Payment Card System Overview
 
OWASP Top 10 Proactive Control 2016 (C5-C10)
OWASP Top 10 Proactive Control 2016 (C5-C10)OWASP Top 10 Proactive Control 2016 (C5-C10)
OWASP Top 10 Proactive Control 2016 (C5-C10)
 
AnyID: Security Point of View
AnyID: Security Point of ViewAnyID: Security Point of View
AnyID: Security Point of View
 
Risk Management in Project Management
Risk Management in Project ManagementRisk Management in Project Management
Risk Management in Project Management
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Leaflet secure coding in php
Leaflet secure coding in phpLeaflet secure coding in php
Leaflet secure coding in php
 
Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016Hacking Your Way to Better Security - PHP South Africa 2016
Hacking Your Way to Better Security - PHP South Africa 2016
 
Secure Coding For Java - Une introduction
Secure Coding For Java - Une introductionSecure Coding For Java - Une introduction
Secure Coding For Java - Une introduction
 
PHP Secure Programming
PHP Secure ProgrammingPHP Secure Programming
PHP Secure Programming
 
Secure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best PracticesSecure Coding - Web Application Security Vulnerabilities and Best Practices
Secure Coding - Web Application Security Vulnerabilities and Best Practices
 
Top 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security ProblemsTop 10 Bad Coding Practices Lead to Security Problems
Top 10 Bad Coding Practices Lead to Security Problems
 
Accelerate your business and reduce cost with OpenStack
Accelerate your business and reduce cost with OpenStackAccelerate your business and reduce cost with OpenStack
Accelerate your business and reduce cost with OpenStack
 
Database Firewall with Snort
Database Firewall with SnortDatabase Firewall with Snort
Database Firewall with Snort
 

Similar to Secure PHP Coding

Similar to Secure PHP Coding (20)

Php manish
Php manishPhp manish
Php manish
 
Session10-PHP Misconfiguration
Session10-PHP MisconfigurationSession10-PHP Misconfiguration
Session10-PHP Misconfiguration
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
php 1
php 1php 1
php 1
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
PHP ITCS 323
PHP ITCS 323PHP ITCS 323
PHP ITCS 323
 
Securing Your Web Server
Securing Your Web ServerSecuring Your Web Server
Securing Your Web Server
 
Anatomy of PHP Shells
Anatomy of PHP ShellsAnatomy of PHP Shells
Anatomy of PHP Shells
 
Php
PhpPhp
Php
 
Unit 1
Unit 1Unit 1
Unit 1
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
PHP
PHPPHP
PHP
 
Php unit i
Php unit iPhp unit i
Php unit i
 
PHP Unit-1 Introduction to PHP
PHP Unit-1 Introduction to PHPPHP Unit-1 Introduction to PHP
PHP Unit-1 Introduction to PHP
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
 
Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8
 
[Php Camp]Owasp Php Top5+Csrf
[Php Camp]Owasp Php Top5+Csrf[Php Camp]Owasp Php Top5+Csrf
[Php Camp]Owasp Php Top5+Csrf
 

More from Narudom Roongsiriwong, CISSP

How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19Narudom Roongsiriwong, CISSP
 
Embedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment IndustryEmbedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment IndustryNarudom Roongsiriwong, CISSP
 
Application Security Verification Standard Project
Application Security Verification Standard ProjectApplication Security Verification Standard Project
Application Security Verification Standard ProjectNarudom Roongsiriwong, CISSP
 
Business continuity & disaster recovery planning (BCP & DRP)
Business continuity & disaster recovery planning (BCP & DRP)Business continuity & disaster recovery planning (BCP & DRP)
Business continuity & disaster recovery planning (BCP & DRP)Narudom Roongsiriwong, CISSP
 

More from Narudom Roongsiriwong, CISSP (16)

Biometric Authentication.pdf
Biometric Authentication.pdfBiometric Authentication.pdf
Biometric Authentication.pdf
 
Security Shift Leftmost - Secure Architecture.pdf
Security Shift Leftmost - Secure Architecture.pdfSecurity Shift Leftmost - Secure Architecture.pdf
Security Shift Leftmost - Secure Architecture.pdf
 
Secure Design: Threat Modeling
Secure Design: Threat ModelingSecure Design: Threat Modeling
Secure Design: Threat Modeling
 
Security Patterns for Software Development
Security Patterns for Software DevelopmentSecurity Patterns for Software Development
Security Patterns for Software Development
 
How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19How Good Security Architecture Saves Corporate Workers from COVID-19
How Good Security Architecture Saves Corporate Workers from COVID-19
 
Secure Software Design for Data Privacy
Secure Software Design for Data PrivacySecure Software Design for Data Privacy
Secure Software Design for Data Privacy
 
Blockchain and Cryptocurrency for Dummies
Blockchain and Cryptocurrency for DummiesBlockchain and Cryptocurrency for Dummies
Blockchain and Cryptocurrency for Dummies
 
DevSecOps 101
DevSecOps 101DevSecOps 101
DevSecOps 101
 
National Digital ID Platform Technical Forum
National Digital ID Platform Technical ForumNational Digital ID Platform Technical Forum
National Digital ID Platform Technical Forum
 
IoT Security
IoT SecurityIoT Security
IoT Security
 
Embedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment IndustryEmbedded System Security: Learning from Banking and Payment Industry
Embedded System Security: Learning from Banking and Payment Industry
 
Secure Your Encryption with HSM
Secure Your Encryption with HSMSecure Your Encryption with HSM
Secure Your Encryption with HSM
 
Application Security Verification Standard Project
Application Security Verification Standard ProjectApplication Security Verification Standard Project
Application Security Verification Standard Project
 
Coding Security: Code Mania 101
Coding Security: Code Mania 101Coding Security: Code Mania 101
Coding Security: Code Mania 101
 
Business continuity & disaster recovery planning (BCP & DRP)
Business continuity & disaster recovery planning (BCP & DRP)Business continuity & disaster recovery planning (BCP & DRP)
Business continuity & disaster recovery planning (BCP & DRP)
 
CarbonCredit-V4
CarbonCredit-V4CarbonCredit-V4
CarbonCredit-V4
 

Recently uploaded

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Recently uploaded (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Secure PHP Coding

  • 1. Secure PHP Coding Narudom Roongsiriwong, CISSP
  • 2. WhoAmI • Lazy Blogger – Japan, Security, FOSS, Politics, Christian – http://narudomr.blogspot.com • Food Mania – Steak, Yakiniku, BBQ – Sushi (especially Otoro) – All Kinds of Noodle • 16 Years In PHP Coding, Since v4.0 (3rd fluent programming language next to C & C++) • Consultant for OWASP Thailand Chapter • Head of IT Security & Solution Architecture, Kiatnakin Bank PLC (KKP)
  • 3. How to Secure PHP Hacker’s Recommendation
  • 4. Is this believable? WTF Any programming languages are the same, secure coding or not depends on programmers.
  • 5. Usage of Server-Side Programming Languages for Websites PHP ASP.NET Java Static Files Cold Fusion Ruby Perl JavaScript Python Erlang 0.0% 10.0% 20.0% 30.0% 40.0% 50.0% 60.0% 70.0% 80.0% 90.0% 81.9% 15.7% 2.9% 1.5% 0.7% 0.6% 0.4% 0.3% 0.2% 0.1% W3Techs.com, 11 September 2016
  • 6. Web Apps in PHP are Most Vulnerable • 86% of applications written in PHP contained at least one cross-site scripting (XSS) vulnerability. • 56% of apps included SQLi (SQL injection), which is one of the dangerous and easy-to- exploit web application vulnerabilities. • 67% of apps allowed for directory traversal. • 61% of apps allowed for code injection. • 58% of apps had problems with credentials management • 73% of apps contained cryptographic issues. • http://thehackernews.com/2015/12/programming-language-security.html
  • 7. PHP Characteristics • Unusual → Language + Web Framework • A large community of libraries that contribute to programming in PHP • All three aspects (language, framework, and libraries) need to be taken into consideration when trying to secure a PHP site
  • 8. Language Issues • Weak typing • Exceptions and error handling • php.ini • Unhelpful builtins
  • 9. Language Issue: Weak Typing • PHP will automatically convert data of an incorrect type into the expected type. $x = 1 + "1"; // x is 2 • Leads to bugs, injections and vulnerabilities if improperly handles • Try to use functions and operators that do not do implicit type conversions (e.g. === and not ==) but not all operators have strict version (such as < or >) • Many built-in functions (like in_array) use weakly typed comparison functions by default, making it difficult to write correct code.
  • 10. Language Issue: Weak Typing $a = array('7.1'); $exists = in_array('7.10', $a); var_dump($exists); // true // OMG in_array()
  • 11. Language Issue: Weak Typing $a = 0; $b = 'x'; false == $a; // true $a == $b; // true $b == true; // true // WTF ==
  • 12. Language Issue: Exception and Error Handling • 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. • Many other languages, error conditions that failed to anticipate will stop running. → Fail Safe • 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 — always follow the warnings and write code that is more robust. • Try to use set_error_handler function to handle user defined error handler.
  • 13. Language Issue: Exception 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->uid); $res = mysqli_query($db, "SELECT COUNT(id) FROM blacklist WHERE uid = '$uid';"); $row = mysqli_fetch_array($res); if ((int)$row[0] > 0) { return false; } else { return true; } } if (!can_access_feature($current_user)) { exit(); } // Code for feature here What happens if db connection is failed?
  • 14. Language Issue: php.ini • PHP code often depends strongly on the values of many configuration settings • Difficult to write code that works correctly in all circumstances. • Difficult to correctly use 3rd party code
  • 15. Language Issue: Unhelpful Builtins • Built-in functions that appear to provide security, but buggy and hard to handle security problems – addslashes – mysql_escape_string – mysql_real_escape_string • 'array' data structure – Extensively used in all PHP code and internally – Confusing mix between an array and a dictionary – Cause even experienced PHP developers to introduce critical security vulnerabilities such as Drupal SA-CORE-2014-005 (CVE-2014-3704)
  • 16. Framework Issues • URL Routing: “.php” or not • Input Handling – Instead of treating HTTP input as simple strings, PHP will build arrays from HTTP input • Template Language – However, it doesn't do HTML escaping by default – Lead to Cross-Site Scripting • Other Inadequacies – No CSRF protection mechanism https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet#Framework_issues
  • 17. 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: http://example.com/?nonce[]=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
  • 18. OWASP PHP Top 5 • P1: Remote Code Execution • P2: Cross-Site Scripting • P3: SQL Injection • P4: PHP Configuration • P5: File System Attacks https://www.owasp.org/index.php/PHP_Top_5
  • 19. P1: Remote Code Execution • 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) • The most widespread PHP security issue since July 2004 • The root causes of this issue are: – Insufficient validation of user input prior to dynamic file system calls, such as require or include or fopen() – allow_url_fopen and PHP wrappers allow this behavior by default, which is unnecessary for most applications $handle = fopen("http://www.example.com/", "r"); – Poor permissions and planning by many hosters allowing excessive default privileges and wide ranging access to what should be off limits areas.
  • 20. P1: Remote Code Execution (cont’d) • Version Affected: PHP 4 (after PHP 4.0.4), 5.x • CVE/CAN Entries: More than 100 such vulnerabilities reported since July 30, 2004, for examples: – Magento < 2.0.6 (popular eCommerce platform) Unauthenticated Remote Code Execution (CVE-2016-4010) http://netanelrub.in/2016/05/17/magento-unauthenticated-remote- code-execution/ – Joomla! 1.5.x, 2.x, and 3.x < 3.4.6 allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via the HTTP User-Agent header (CVE-2015-8562) http://www.securityfocus.com/bid/79195 – vBulletin 5 Connect 5.1.2 through 5.1.9 allows remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code (CVE-2015-7808) http://blog.checkpoint.com/2015/11/05/check-point- discovers-critical-vbulletin-0-day/
  • 21. How to Determine If You Are Vulnerable $report = $_POST[‘report_name’]; include $report; $username = $_POST[‘username’]; eval(“echo $username”); 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 – 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 5.0 and later has limited support for some URL wrappers for almost all file functions
  • 22. How to Protect Against Remote Code Execution • Developers should – Review existing code for file operations, include/require, and eval() statements to ensure that user input is properly validated prior to first use – When writing new code, try to limit the use of dynamic inputs from users to vulnerable functions either directly or via wrappers • Hosters should: – Disable allow_url_fopen in php.ini by setting it to 0 – Enable safe_mode and set open_basedir restrictions (if you know what you're doing - it's not really that safe!) – Lockdown the server environment to prevent the server from making new outbound requests
  • 23. P2: Cross-Site Scripting (XSS) • Cross-site scripting (aka. HTML injection or user agent injection) can be in three modes – 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) – 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. – DOM: The attacker uses the victim site’s 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.
  • 24. P2: Cross-Site Scripting (XSS) (cont’d) • Version Affected: All • CVE/CAN Entries: More than 100 XSS entries since July 2004. – WordPress ≤ 4.5.2 Unspecified Cross Site Scripting Vulnerability (CVE-2016-6634) http://www.securityfocus.com/bid/92390 – Joomla! 3.4.x < 3.4.4 allows remote attackers to inject arbitrary web script or HTML (CVE-2015-6939) http://www.securitytracker.com/id/1033541 – VBulletin Cross-site scripting http://www.securityfocus.com/bid/14874 – Coppermine Display Image Cross-site scripting http://www.securityfocus.com/bid/14625 – WordPress Edit Cross-site Scripting http://www.securityfocus.com/bid/13664
  • 25. How to Determine If You Are Vulnerable • 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. • Inspect user input handling code for unsafe inputs: • If you use Javascript to redirect the user (via document.location or window.open any similar means), output to the user via document.write, or modifies the DOM in any way, you are likely to be at risk of DOM injection. echo $_POST[‘input’];
  • 26. How to Protect Against Cross-site Scripting • Turn off register_globals and ensure all variables are properly initialized • Obtain user input directly from the correct location ($_POST, $_GET, etc) rather than relying on register_globals or the request object ($_REQUEST) • Validate input properly for type, length, and syntax • Free text input can only be safely re-displayed to the user after using HTML entities (htmlentities() function) • Variables sent back to the user via URLs must be URL encoded using urlencode() • Validate JavaScript code against Klein’s DOM Injection paper (http://crypto.stanford.edu/cs155/CSS.pdf) to ensure that they are immune from DOM injection attacks – •
  • 27. P3: SQL Injection • A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. • SQL injection exploits can read sensitive data, modify, execute administration operations and in some cases issue commands to the operating system • 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; --
  • 28. P3: SQL Injection (cont’d) • Version Affected: All • CVE/CAN Entries: More than 100 CVE / CAN entries from multiple vendor, for example: – vBulletin 3.6.x – 4.2.3 allows remote attackers to execute arbitrary SQL commands via the postids parameter to forumrunner/request.php (CVE-2016-6195) https://enumerated.wordpress.com/2016/07/11/1/ – Wordpress < 4.2.4 SQL injection vulnerability (CVE-2015-2213) https://core.trac.wordpress.org/changeset/33556 – Joomla! 3.x < 3.4.7 allows attackers to execute arbitrary SQL commands (CVE-2015-8769) http://www.securityfocus.com/bid/79679 • Bugtraq usually offers up two to three different PHP applications with SQL injection vulnerabilities per day
  • 29. vBulletin SQL injection CVE-2016-6195 The root of the vulnerability, /forumrunner/includes/moderation.php: function do_get_spam_data() { ... $vbulletin->input->clean_array_gpc('r', array( 'threadid' => TYPE_STRING, 'postids' => TYPE_STRING, )); … } else if ($vbulletin->GPC['postids'] != ") { $postids = $vbulletin->GPC['postids']; $posts = $db->query_read_slave("SELECT post.postid, post.threadid, post.visible, post.title, post.userid, thread.forumid, thread.title AS thread_title, thread.postuserid, thread.visible AS thread_visible, thread.firstpostid FROM " . TABLE_PREFIX . "post AS post LEFT JOIN " . TABLE_PREFIX . "thread AS thread USING (threadid) WHERE postid IN ($postids)");
  • 30. Wordpress SQL Injection Fixes in 4.2.4 for CVE-2015-2213
  • 31. How to Determine If You Are Vulnerable • Find code which calls mysql_query() or similar database interfaces • 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
  • 32. How to Protect Against SQL Injection • Migrate code to PHP 5.1 and use PDO, or if this is not possible, at least migrate code to safer constructs, such as PEAR::DB’s parameterized statements or the MySQLi interfaces • Validate data for correct type, length, and syntax. • Do not use dynamic table names - escape functions are not designed for this use and are not safe for this use. • Use white listing (positive validation) data over black listing, which is akin to virus patterns – always out of date, and always insufficient against advanced attacks • 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. • Provide a .htaccess file to ensure that register_globals and magic_quotes are forced off, and that all variables are properly initialized and validated
  • 33. P4: PHP Configuration • PHP Configuration has a direct bearing on the severity of attacks. • No agreed "secure" PHP configuration • Arguments for and against the most common security options: – register_globals (off by default in PHP ≥ 4.2, should be off, REMOVED as of PHP 5.4.0) – allow_url_fopen (enabled by default, should be off, available since PHP 4.0.4) – magic_quotes_gpc (on by default in modern PHP, should be off, REMOVED as of PHP 5.4.0) – magic_quotes_runtime (off by default in modern PHP, should be of, REMOVED as of PHP 5.4.0) – safe_mode and open_basedir (disabled by default, should be enabled and correctly configured. Be aware that safe_mode really isn't safe and can be worse than useless)
  • 34. P5: File System Attacks • PHP developers have many ways to obviate security on shared hosts with local file system attacks, particularly in shared environments: – Local file inclusion (such as /etc/passwd, configuration files, or logs) – Local session tampering (which is usually in /tmp) – Local file upload injection (usually part of image attachment handling) • As most hosters run PHP as “nobody” under Apache, local file system vulnerabilities affect all users within a single host. • Version Affected: PHP 3, 4, 5 • CVE/CAN Entries: As there have been many examples over years, for examples: – 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) https://www.phpmyadmin.net/security/PMASA-2016-35/ – phpMyAdmin Local File Inclusion (CVE-2011-2643) https://www.phpmyadmin.net/security/PMASA-2011-10/
  • 35. PhpMyAdmin 3.4.0 – 3.4.3.1 CVE-2011-2643 Source: http://fd.the-wildcat.de/pma_e36a587a73.php