SlideShare a Scribd company logo
PHP and MySQL Web App Security Laura Thomson (laura@omniti.com)
Why is web application security important?
Overview What do I mean by security? Specifically security of web apps Not how to secure your install Not the security of MySQL or PHP Programmers’ perspective Why is this important? Basic principles Common attacks and how to defend against them Big picture prevention Resources
Rationale Before the last couple of years nobody thought about this stuff, like many web related security issues.  Lots of programmers drift along blissfully unaware of what can go wrong until something bad happens Some well known recent problems with popular web apps (large install base) and well known sites This talk: Learn the basics (mostly applicable regardless of implementation language) Motivate you to learn more Far, far too much to cover in the time.  This is just an introduction.
Who am I, and why should you listen to me? Principal at OmniTI Used MySQL and PHP since last century More than a decade of web development experience in a range of languages, using a range of databases Long term developer and architect What we will cover is not guru level knowledge, but information that  every web developer working with MySQL and PHP should know like the back of their hand.
MySQL Security Basics
Basic principles Configure MySQL securely Understand the privilege system, and use it appropriately  Use encryption when needed Don’t trust user data (more on this later)
Secure your configuration Simple principles: Don’t run mysqld as (Unix)  root .  Run it as a user created specifically for this purpose, e.g.  mysql .  Don’t use this account for anything else.  (Note that the MySQL  root  user has nothing to do with Unix users so this doesn’t affect MySQL internally at all.) Set permissions on the database directories so that only your mysqld user (e.g.  mysql ) can access them. Disable symlinks to tables with  --skip-symbolic-links . Disallow access to port 3306 (or whatever port you have MySQL running on) except from trusted hosts
Accounts and Privileges All MySQL accounts need a password, especially  root .  (Don’t forget anonymous users, either.) Grant users the minimum level of privilege required to do their job.  (Principle of Least Privilege) Some privileges require special attention: Only the root user should have access to the mysql database, which contains privilege information Keep FILE, PROCESS, and SUPER for administrative users.  FILE enables file creation, PROCESS allows you to see executing processes (including passwords in plaintext), and SUPER can be allowed to e.g. terminate client connections. Avoid wildcards in hostnames in the host table. Use IPs instead of hostnames in the host table if you don’t trust your DNS
Using encryption Don’t store application passwords in plaintext in the database.  (Use one way hashing) Require database connections to be via ssh or tunneled through it Avoid old MySQL passwords (pre 4.1).  (Disable with  --secure-auth , and avoid use of  --old-passwords .)
PHP Security Basics
Basic principles Consider illegitimate uses of your application Educate yourself If nothing else, filter all external data (From the PHP Security Guide at  http:// phpsec.org /projects/guide/ )
External Data External data is not to be trusted. What’s external data? Anything from a form Anything from $_GET, $_POST, $_REQUEST Cookies Some server variables (e.g. $_SERVER['SERVER_NAME']) Database query results Web services data Files The basic principle is to filter input and escape output Filter input using whitelisting where possible Escape output according to where it’s going.
Attacks
Attacks Let’s consider some common problems: SQL/Command/code Injection XSS (Cross Site Scripting) Session fixation Session hijacking Cross site request forgeries (CSRF)
SQL Injection Enter SQL in e.g. form fields in such a way that it is executed on the web app database. A variation is command injection, where user data is passed through system() or exec(). It’s basically the same attack. (Code injection is also a variation, but we’ll talk about that separately)
Example $username = $_POST['username']; $password = $_POST['password']; $query = &quot;select * from auth where username = '&quot;.$username .&quot;' and password = sha1('&quot;.$password.&quot;')&quot;; echo $query;  $db = new mysqli('localhost', 'demo',  'secret', 'security_demo'); $result = $db->query($query); if ($result && $result->num_rows) { echo &quot;<br />Logged in successfully&quot;; } else { echo &quot;<br />Login failed&quot;; }
Preventing SQL injection Options: Filter data using mysql[i]_real_escape_string()  Manually check each piece of data is the right type Use prepared statements and bind variables I recommend the use of prepared statements. You don’t have to worry about filtering data Used as a coding standard, helps to limit problems caused by novice or naïve developers within your organization. Gives you other advantages: where queries will be performed multiple times, allows reuse of query plan; uses binary protocol Tip: use PDO with prepared statement emulation turned on to leverage MySQL’s query cache Note that prepared statements don’t protect you against everything (column/table name injection)
Prepared statements mysqli $query = 'select name, district from city  where countrycode=?'; if ($stmt = $db->prepare($query) ) {  $countrycode = 'AUS';  $stmt->bind_param(&quot;s&quot;, $countrycode);  $stmt->execute();  $stmt->bind_result($name, $district);  while ($stmt->fetch())  {  echo $name.', '.$district; echo '<br />'; }  $stmt->close();  }  $db->close();
Prepared statements PDO try { $db = new PDO($dsn,  $user, $password); } catch (PDOException $e) { echo 'Connect failed:'. $e->getMessage(); } $stmt = $db->prepare(“insert into customers (name, address) values (:name, :address)&quot;); $stmt->bindParam(‘:name’, $name); $stmt->bindParam(‘:address’, $address); $stmt->execute();
XSS XSS = Cross Site Scripting An attack by a malicious user where they enter some data to your web application that includes a client side script (generally JavaScript).  If you output this data to a web page without filtering it, this script will be executed.
Example – part 1 <?php  if (file_exists('comments')) { $comments = file_get_contents('comments'); } else { $comments = ''; } if (isset($_POST['comment'])) { $comments .= '<br />' . $_POST['comment']; file_put_contents('comments', $comments); } ?>
Example – part 2  <form action='xss.php' method='POST'> Enter your comments here: <br /> <textarea name='comment'></textarea> <br /> <input type='submit' value='Post comment' /> </form><hr /><br /> <?php echo $comments; ?>
So what? So it’s JavaScript (or even plain old HTML), I hear you saying, so what?  What can I do with that? Heaps of badness: Annoying popups  Meta-refresh Dubious forms Steal cookies (which can then set up a session attack) AJAX (XMLHttpRequest)
How do I prevent this? Basically: Filter output to the browser through htmlentities(). Not that basic See the XSS Cheatsheet: http://ha.ckers.org/xss.html
Session fixation Session security works on the basis that a PHPSESSID is hard to guess.  If you don’t have to guess it life is much easier. PHP can either accept a session id through a cookie or through the URL Typically this appears as a phishing attack “ Go to this cool site: http:// www.example.com/fixate.php?PHPSESSID =...” Solution: use session_regenerate_id() whenever a user logs in or changes their level of privilege.
Session hijacking Same idea but involves somehow obtaining the session id. Refer back to XSS and stealing cookies through JavaScript Session ids can be sniffed, or obtained from proxy servers if contained in the URL Solutions: Regenerate ids If using sessions, always use SSL Use configuration directive session.use_only_cookies (which will irritate some users)
CSRF CSRF = Cross Site Request Forgeries A request for a page that looks as though it was initiated by a site's trusted user, but wasn't (deliberately).  Many, many variations. Example:  <img src='http://example.com/single_click_to_buy.php?item=12345'> Avoid using GET for actions that cause any kind of change to data In general, make sure that users come through your forms, and each form submission is matched to an individual form that you send out. Generate a one-time token and embed it in the form, save it in the session, and check it on submission. Not trivial to protect against
Code injection While this can be grouped with SQL injection and command injection, it’s a serious enough and common enough problem to merit its own slide Problem occurs when you accidentally execute arbitrary code, typically via file inclusion Poorly written code can allow a remote file to be included and executed as though it were a trusted local file Remember that many PHP functions such as require can take an URL or a filename. Passing user input as a filename or part of a filename invites users to start filenames with http …
Example: Theme Selector <form>Choose Theme: <select name = theme> <option value = blue>Blue</option> <option value = green>Green</option> <option value = red>Red</option> </select> <input type = submit> </form> <?php  if($theme) { require($theme.'.txt'); } ?>
Prevention Filter user input Disable  allow_url_fopen  and/or  allow_url_include  setting in php.ini.  This disables require/include/fopen of remote files. (allow_url_include new in 5.2.0)
Big picture prevention Some basic principles (again): Don’t rely on server configuration to protect you (e.g. magic quotes) (always/especially) if you are writing distributable apps Design your application with security from the ground up: for example, use a single line of execution that begins with a single point of data cleaning. Review your colleagues’ code and have them review yours Seek advice from experts where possible (scanning / auditing) Educate yourself and your developers and where possible make it easy for your staff to do the right thing.  Keep your code up to date.  Stay on top of patches and advisories.
Resources Open Web Application Security Project  http://www.owasp.org PHP Security Consortium Guide  http://phpsec.org/projects/guide/ Hardened PHP Patch / Suhosin http://www.hardened-php.net/ Chris Shiflett’s “Essential Security” from O’Reilly (2005)
Final words Slides available for download (after the talk) http://omniti.com/resources/talks These slides are available for use under a Creative Commons license.  You may use them for any purpose, but must give credit http://creativecommons.org/licenses/by/1.0/
Questions? ?

More Related Content

What's hot (18)

Practical django secuirty
Practical django secuirtyPractical django secuirty
Practical django secuirty
Andy Dai
 
Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by Default
Mohammed ALDOUB
 
Securing Your WordPress Website by Vlad Lasky
Securing Your WordPress Website by Vlad LaskySecuring Your WordPress Website by Vlad Lasky
Securing Your WordPress Website by Vlad Lasky
wordcampgc
 
Make profit with UI-Redressing attacks.
Make profit with UI-Redressing attacks.Make profit with UI-Redressing attacks.
Make profit with UI-Redressing attacks.
n|u - The Open Security Community
 
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesXXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
Abraham Aranguren
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
Kazuho Oku
 
Securing WordPress
Securing WordPressSecuring WordPress
Securing WordPress
Shawn Hooper
 
Php
PhpPhp
Php
Yesha kapadia
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Security.ppt
Security.pptSecurity.ppt
Security.ppt
webhostingguy
 
New web attacks-nethemba
New web attacks-nethembaNew web attacks-nethemba
New web attacks-nethemba
OWASP (Open Web Application Security Project)
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Ivan Ortega
 
Ekoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's MethodologyEkoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's Methodology
bugcrowd
 
Practical web-attacks2
Practical web-attacks2Practical web-attacks2
Practical web-attacks2
OWASP (Open Web Application Security Project)
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
Wim Godden
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakes
kuza55
 
Xss is more than a simple threat
Xss is more than a simple threatXss is more than a simple threat
Xss is more than a simple threat
Avădănei Andrei
 
Practical django secuirty
Practical django secuirtyPractical django secuirty
Practical django secuirty
Andy Dai
 
Case Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by DefaultCase Study of Django: Web Frameworks that are Secure by Default
Case Study of Django: Web Frameworks that are Secure by Default
Mohammed ALDOUB
 
Securing Your WordPress Website by Vlad Lasky
Securing Your WordPress Website by Vlad LaskySecuring Your WordPress Website by Vlad Lasky
Securing Your WordPress Website by Vlad Lasky
wordcampgc
 
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesXXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
Abraham Aranguren
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
Kazuho Oku
 
Securing WordPress
Securing WordPressSecuring WordPress
Securing WordPress
Shawn Hooper
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Ivan Ortega
 
Ekoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's MethodologyEkoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's Methodology
bugcrowd
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
Wim Godden
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakes
kuza55
 
Xss is more than a simple threat
Xss is more than a simple threatXss is more than a simple threat
Xss is more than a simple threat
Avădănei Andrei
 

Viewers also liked (8)

Charla jornadas-tic-normal2-091204050439-phpapp01
Charla jornadas-tic-normal2-091204050439-phpapp01Charla jornadas-tic-normal2-091204050439-phpapp01
Charla jornadas-tic-normal2-091204050439-phpapp01
Liliana Bonin
 
Dia de la Bandera
Dia de la BanderaDia de la Bandera
Dia de la Bandera
sanrafael
 
Historia De La Bandera
Historia De La BanderaHistoria De La Bandera
Historia De La Bandera
sanrafael
 
Presentacion power point belgrano
Presentacion power point belgranoPresentacion power point belgrano
Presentacion power point belgrano
Emii Del Pozo
 
Dia de la Bandera Argentina para el 2º ciclo.
Dia de la Bandera Argentina para el 2º ciclo.Dia de la Bandera Argentina para el 2º ciclo.
Dia de la Bandera Argentina para el 2º ciclo.
carolinadiaz28
 
Homenaje a Manuel Belgrano
Homenaje a Manuel BelgranoHomenaje a Manuel Belgrano
Homenaje a Manuel Belgrano
Emii Del Pozo
 
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
PRESENTACION SOBRE LOS SIMBOLOS PATRIOSPRESENTACION SOBRE LOS SIMBOLOS PATRIOS
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
frazuwi
 
La bandera .ppt [autoguardado]
La bandera .ppt [autoguardado]La bandera .ppt [autoguardado]
La bandera .ppt [autoguardado]
culturas y estéticas contemporáneas Colegios
 
Charla jornadas-tic-normal2-091204050439-phpapp01
Charla jornadas-tic-normal2-091204050439-phpapp01Charla jornadas-tic-normal2-091204050439-phpapp01
Charla jornadas-tic-normal2-091204050439-phpapp01
Liliana Bonin
 
Dia de la Bandera
Dia de la BanderaDia de la Bandera
Dia de la Bandera
sanrafael
 
Historia De La Bandera
Historia De La BanderaHistoria De La Bandera
Historia De La Bandera
sanrafael
 
Presentacion power point belgrano
Presentacion power point belgranoPresentacion power point belgrano
Presentacion power point belgrano
Emii Del Pozo
 
Dia de la Bandera Argentina para el 2º ciclo.
Dia de la Bandera Argentina para el 2º ciclo.Dia de la Bandera Argentina para el 2º ciclo.
Dia de la Bandera Argentina para el 2º ciclo.
carolinadiaz28
 
Homenaje a Manuel Belgrano
Homenaje a Manuel BelgranoHomenaje a Manuel Belgrano
Homenaje a Manuel Belgrano
Emii Del Pozo
 
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
PRESENTACION SOBRE LOS SIMBOLOS PATRIOSPRESENTACION SOBRE LOS SIMBOLOS PATRIOS
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
frazuwi
 

Similar to Php My Sql Security 2007 (20)

Website Security
Website SecurityWebsite Security
Website Security
Carlos Z
 
Web Security
Web SecurityWeb Security
Web Security
Rene Churchill
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
jemond
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
Wildan Maulana
 
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven PignataroJoomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Steven Pignataro
 
Web application security
Web application securityWeb application security
Web application security
Ravi Raj
 
Web Bugs
Web BugsWeb Bugs
Web Bugs
Dr Rushi Raval
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
olegmmiller
 
XSS
XSSXSS
XSS
Hrishikesh Mishra
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
Anil Kumar Panigrahi
 
Joomla security nuggets
Joomla security nuggetsJoomla security nuggets
Joomla security nuggets
guestbd1cdca
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
hruth
 
Php security3895
Php security3895Php security3895
Php security3895
PrinceGuru MS
 
PHP Security
PHP SecurityPHP Security
PHP Security
manugoel2003
 
WordPress End-User Security
WordPress End-User SecurityWordPress End-User Security
WordPress End-User Security
Dre Armeda
 
Fortress SQL Server
Fortress SQL ServerFortress SQL Server
Fortress SQL Server
webhostingguy
 
Download It
Download ItDownload It
Download It
webhostingguy
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
Instrumenting plugins for Performance Schema
Instrumenting plugins for Performance SchemaInstrumenting plugins for Performance Schema
Instrumenting plugins for Performance Schema
Mark Leith
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHP
Dave Ross
 
Website Security
Website SecurityWebsite Security
Website Security
Carlos Z
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
jemond
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
Wildan Maulana
 
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven PignataroJoomla! Day Chicago 2011 Presentation - Steven Pignataro
Joomla! Day Chicago 2011 Presentation - Steven Pignataro
Steven Pignataro
 
Web application security
Web application securityWeb application security
Web application security
Ravi Raj
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
olegmmiller
 
Joomla security nuggets
Joomla security nuggetsJoomla security nuggets
Joomla security nuggets
guestbd1cdca
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
hruth
 
WordPress End-User Security
WordPress End-User SecurityWordPress End-User Security
WordPress End-User Security
Dre Armeda
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
sekar c
 
Instrumenting plugins for Performance Schema
Instrumenting plugins for Performance SchemaInstrumenting plugins for Performance Schema
Instrumenting plugins for Performance Schema
Mark Leith
 
SQL Injection in PHP
SQL Injection in PHPSQL Injection in PHP
SQL Injection in PHP
Dave Ross
 

More from Aung Khant (20)

Introducing Msd
Introducing MsdIntroducing Msd
Introducing Msd
Aung Khant
 
Securing Php App
Securing Php AppSecuring Php App
Securing Php App
Aung Khant
 
Securing Web Server Ibm
Securing Web Server IbmSecuring Web Server Ibm
Securing Web Server Ibm
Aung Khant
 
Security Design Patterns
Security Design PatternsSecurity Design Patterns
Security Design Patterns
Aung Khant
 
Security Code Review
Security Code ReviewSecurity Code Review
Security Code Review
Aung Khant
 
Security Engineering Executive
Security Engineering ExecutiveSecurity Engineering Executive
Security Engineering Executive
Aung Khant
 
Security Engineeringwith Patterns
Security Engineeringwith PatternsSecurity Engineeringwith Patterns
Security Engineeringwith Patterns
Aung Khant
 
Security Web Servers
Security Web ServersSecurity Web Servers
Security Web Servers
Aung Khant
 
Security Testing Web App
Security Testing Web AppSecurity Testing Web App
Security Testing Web App
Aung Khant
 
Session Fixation
Session FixationSession Fixation
Session Fixation
Aung Khant
 
Sql Injection Paper
Sql Injection PaperSql Injection Paper
Sql Injection Paper
Aung Khant
 
Sql Injection Adv Owasp
Sql Injection Adv OwaspSql Injection Adv Owasp
Sql Injection Adv Owasp
Aung Khant
 
Php Security Iissues
Php Security IissuesPhp Security Iissues
Php Security Iissues
Aung Khant
 
Sql Injection White Paper
Sql Injection White PaperSql Injection White Paper
Sql Injection White Paper
Aung Khant
 
S Shah Web20
S Shah Web20S Shah Web20
S Shah Web20
Aung Khant
 
S Vector4 Web App Sec Management
S Vector4 Web App Sec ManagementS Vector4 Web App Sec Management
S Vector4 Web App Sec Management
Aung Khant
 
Php Security Value1
Php Security Value1Php Security Value1
Php Security Value1
Aung Khant
 
Privilege Escalation
Privilege EscalationPrivilege Escalation
Privilege Escalation
Aung Khant
 
Php Security Workshop
Php Security WorkshopPhp Security Workshop
Php Security Workshop
Aung Khant
 
Preventing Xs Sin Perl Apache
Preventing Xs Sin Perl ApachePreventing Xs Sin Perl Apache
Preventing Xs Sin Perl Apache
Aung Khant
 
Introducing Msd
Introducing MsdIntroducing Msd
Introducing Msd
Aung Khant
 
Securing Php App
Securing Php AppSecuring Php App
Securing Php App
Aung Khant
 
Securing Web Server Ibm
Securing Web Server IbmSecuring Web Server Ibm
Securing Web Server Ibm
Aung Khant
 
Security Design Patterns
Security Design PatternsSecurity Design Patterns
Security Design Patterns
Aung Khant
 
Security Code Review
Security Code ReviewSecurity Code Review
Security Code Review
Aung Khant
 
Security Engineering Executive
Security Engineering ExecutiveSecurity Engineering Executive
Security Engineering Executive
Aung Khant
 
Security Engineeringwith Patterns
Security Engineeringwith PatternsSecurity Engineeringwith Patterns
Security Engineeringwith Patterns
Aung Khant
 
Security Web Servers
Security Web ServersSecurity Web Servers
Security Web Servers
Aung Khant
 
Security Testing Web App
Security Testing Web AppSecurity Testing Web App
Security Testing Web App
Aung Khant
 
Session Fixation
Session FixationSession Fixation
Session Fixation
Aung Khant
 
Sql Injection Paper
Sql Injection PaperSql Injection Paper
Sql Injection Paper
Aung Khant
 
Sql Injection Adv Owasp
Sql Injection Adv OwaspSql Injection Adv Owasp
Sql Injection Adv Owasp
Aung Khant
 
Php Security Iissues
Php Security IissuesPhp Security Iissues
Php Security Iissues
Aung Khant
 
Sql Injection White Paper
Sql Injection White PaperSql Injection White Paper
Sql Injection White Paper
Aung Khant
 
S Vector4 Web App Sec Management
S Vector4 Web App Sec ManagementS Vector4 Web App Sec Management
S Vector4 Web App Sec Management
Aung Khant
 
Php Security Value1
Php Security Value1Php Security Value1
Php Security Value1
Aung Khant
 
Privilege Escalation
Privilege EscalationPrivilege Escalation
Privilege Escalation
Aung Khant
 
Php Security Workshop
Php Security WorkshopPhp Security Workshop
Php Security Workshop
Aung Khant
 
Preventing Xs Sin Perl Apache
Preventing Xs Sin Perl ApachePreventing Xs Sin Perl Apache
Preventing Xs Sin Perl Apache
Aung Khant
 

Recently uploaded (20)

SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Salesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docxSalesforce AI Associate 2 of 2 Certification.docx
Salesforce AI Associate 2 of 2 Certification.docx
José Enrique López Rivera
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Datastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptxDatastucture-Unit 4-Linked List Presentation.pptx
Datastucture-Unit 4-Linked List Presentation.pptx
kaleeswaric3
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
 

Php My Sql Security 2007

  • 1. PHP and MySQL Web App Security Laura Thomson ([email protected])
  • 2. Why is web application security important?
  • 3. Overview What do I mean by security? Specifically security of web apps Not how to secure your install Not the security of MySQL or PHP Programmers’ perspective Why is this important? Basic principles Common attacks and how to defend against them Big picture prevention Resources
  • 4. Rationale Before the last couple of years nobody thought about this stuff, like many web related security issues. Lots of programmers drift along blissfully unaware of what can go wrong until something bad happens Some well known recent problems with popular web apps (large install base) and well known sites This talk: Learn the basics (mostly applicable regardless of implementation language) Motivate you to learn more Far, far too much to cover in the time. This is just an introduction.
  • 5. Who am I, and why should you listen to me? Principal at OmniTI Used MySQL and PHP since last century More than a decade of web development experience in a range of languages, using a range of databases Long term developer and architect What we will cover is not guru level knowledge, but information that every web developer working with MySQL and PHP should know like the back of their hand.
  • 7. Basic principles Configure MySQL securely Understand the privilege system, and use it appropriately Use encryption when needed Don’t trust user data (more on this later)
  • 8. Secure your configuration Simple principles: Don’t run mysqld as (Unix) root . Run it as a user created specifically for this purpose, e.g. mysql . Don’t use this account for anything else. (Note that the MySQL root user has nothing to do with Unix users so this doesn’t affect MySQL internally at all.) Set permissions on the database directories so that only your mysqld user (e.g. mysql ) can access them. Disable symlinks to tables with --skip-symbolic-links . Disallow access to port 3306 (or whatever port you have MySQL running on) except from trusted hosts
  • 9. Accounts and Privileges All MySQL accounts need a password, especially root . (Don’t forget anonymous users, either.) Grant users the minimum level of privilege required to do their job. (Principle of Least Privilege) Some privileges require special attention: Only the root user should have access to the mysql database, which contains privilege information Keep FILE, PROCESS, and SUPER for administrative users. FILE enables file creation, PROCESS allows you to see executing processes (including passwords in plaintext), and SUPER can be allowed to e.g. terminate client connections. Avoid wildcards in hostnames in the host table. Use IPs instead of hostnames in the host table if you don’t trust your DNS
  • 10. Using encryption Don’t store application passwords in plaintext in the database. (Use one way hashing) Require database connections to be via ssh or tunneled through it Avoid old MySQL passwords (pre 4.1). (Disable with --secure-auth , and avoid use of --old-passwords .)
  • 12. Basic principles Consider illegitimate uses of your application Educate yourself If nothing else, filter all external data (From the PHP Security Guide at http:// phpsec.org /projects/guide/ )
  • 13. External Data External data is not to be trusted. What’s external data? Anything from a form Anything from $_GET, $_POST, $_REQUEST Cookies Some server variables (e.g. $_SERVER['SERVER_NAME']) Database query results Web services data Files The basic principle is to filter input and escape output Filter input using whitelisting where possible Escape output according to where it’s going.
  • 15. Attacks Let’s consider some common problems: SQL/Command/code Injection XSS (Cross Site Scripting) Session fixation Session hijacking Cross site request forgeries (CSRF)
  • 16. SQL Injection Enter SQL in e.g. form fields in such a way that it is executed on the web app database. A variation is command injection, where user data is passed through system() or exec(). It’s basically the same attack. (Code injection is also a variation, but we’ll talk about that separately)
  • 17. Example $username = $_POST['username']; $password = $_POST['password']; $query = &quot;select * from auth where username = '&quot;.$username .&quot;' and password = sha1('&quot;.$password.&quot;')&quot;; echo $query; $db = new mysqli('localhost', 'demo', 'secret', 'security_demo'); $result = $db->query($query); if ($result && $result->num_rows) { echo &quot;<br />Logged in successfully&quot;; } else { echo &quot;<br />Login failed&quot;; }
  • 18. Preventing SQL injection Options: Filter data using mysql[i]_real_escape_string() Manually check each piece of data is the right type Use prepared statements and bind variables I recommend the use of prepared statements. You don’t have to worry about filtering data Used as a coding standard, helps to limit problems caused by novice or naïve developers within your organization. Gives you other advantages: where queries will be performed multiple times, allows reuse of query plan; uses binary protocol Tip: use PDO with prepared statement emulation turned on to leverage MySQL’s query cache Note that prepared statements don’t protect you against everything (column/table name injection)
  • 19. Prepared statements mysqli $query = 'select name, district from city where countrycode=?'; if ($stmt = $db->prepare($query) ) { $countrycode = 'AUS'; $stmt->bind_param(&quot;s&quot;, $countrycode); $stmt->execute(); $stmt->bind_result($name, $district); while ($stmt->fetch()) { echo $name.', '.$district; echo '<br />'; } $stmt->close(); } $db->close();
  • 20. Prepared statements PDO try { $db = new PDO($dsn, $user, $password); } catch (PDOException $e) { echo 'Connect failed:'. $e->getMessage(); } $stmt = $db->prepare(“insert into customers (name, address) values (:name, :address)&quot;); $stmt->bindParam(‘:name’, $name); $stmt->bindParam(‘:address’, $address); $stmt->execute();
  • 21. XSS XSS = Cross Site Scripting An attack by a malicious user where they enter some data to your web application that includes a client side script (generally JavaScript). If you output this data to a web page without filtering it, this script will be executed.
  • 22. Example – part 1 <?php if (file_exists('comments')) { $comments = file_get_contents('comments'); } else { $comments = ''; } if (isset($_POST['comment'])) { $comments .= '<br />' . $_POST['comment']; file_put_contents('comments', $comments); } ?>
  • 23. Example – part 2 <form action='xss.php' method='POST'> Enter your comments here: <br /> <textarea name='comment'></textarea> <br /> <input type='submit' value='Post comment' /> </form><hr /><br /> <?php echo $comments; ?>
  • 24. So what? So it’s JavaScript (or even plain old HTML), I hear you saying, so what? What can I do with that? Heaps of badness: Annoying popups Meta-refresh Dubious forms Steal cookies (which can then set up a session attack) AJAX (XMLHttpRequest)
  • 25. How do I prevent this? Basically: Filter output to the browser through htmlentities(). Not that basic See the XSS Cheatsheet: http://ha.ckers.org/xss.html
  • 26. Session fixation Session security works on the basis that a PHPSESSID is hard to guess. If you don’t have to guess it life is much easier. PHP can either accept a session id through a cookie or through the URL Typically this appears as a phishing attack “ Go to this cool site: http:// www.example.com/fixate.php?PHPSESSID =...” Solution: use session_regenerate_id() whenever a user logs in or changes their level of privilege.
  • 27. Session hijacking Same idea but involves somehow obtaining the session id. Refer back to XSS and stealing cookies through JavaScript Session ids can be sniffed, or obtained from proxy servers if contained in the URL Solutions: Regenerate ids If using sessions, always use SSL Use configuration directive session.use_only_cookies (which will irritate some users)
  • 28. CSRF CSRF = Cross Site Request Forgeries A request for a page that looks as though it was initiated by a site's trusted user, but wasn't (deliberately). Many, many variations. Example: <img src='http://example.com/single_click_to_buy.php?item=12345'> Avoid using GET for actions that cause any kind of change to data In general, make sure that users come through your forms, and each form submission is matched to an individual form that you send out. Generate a one-time token and embed it in the form, save it in the session, and check it on submission. Not trivial to protect against
  • 29. Code injection While this can be grouped with SQL injection and command injection, it’s a serious enough and common enough problem to merit its own slide Problem occurs when you accidentally execute arbitrary code, typically via file inclusion Poorly written code can allow a remote file to be included and executed as though it were a trusted local file Remember that many PHP functions such as require can take an URL or a filename. Passing user input as a filename or part of a filename invites users to start filenames with http …
  • 30. Example: Theme Selector <form>Choose Theme: <select name = theme> <option value = blue>Blue</option> <option value = green>Green</option> <option value = red>Red</option> </select> <input type = submit> </form> <?php if($theme) { require($theme.'.txt'); } ?>
  • 31. Prevention Filter user input Disable allow_url_fopen and/or allow_url_include setting in php.ini. This disables require/include/fopen of remote files. (allow_url_include new in 5.2.0)
  • 32. Big picture prevention Some basic principles (again): Don’t rely on server configuration to protect you (e.g. magic quotes) (always/especially) if you are writing distributable apps Design your application with security from the ground up: for example, use a single line of execution that begins with a single point of data cleaning. Review your colleagues’ code and have them review yours Seek advice from experts where possible (scanning / auditing) Educate yourself and your developers and where possible make it easy for your staff to do the right thing. Keep your code up to date. Stay on top of patches and advisories.
  • 33. Resources Open Web Application Security Project http://www.owasp.org PHP Security Consortium Guide http://phpsec.org/projects/guide/ Hardened PHP Patch / Suhosin http://www.hardened-php.net/ Chris Shiflett’s “Essential Security” from O’Reilly (2005)
  • 34. Final words Slides available for download (after the talk) http://omniti.com/resources/talks These slides are available for use under a Creative Commons license. You may use them for any purpose, but must give credit http://creativecommons.org/licenses/by/1.0/