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? ?
Ad

Recommended

Website Security
Website Security
MODxpo
 
Intro to Php Security
Intro to Php Security
Dave Ross
 
Security In PHP Applications
Security In PHP Applications
Aditya Mooley
 
secure php
secure php
Riyad Bin Zaman
 
PHP Security
PHP Security
Mindfire Solutions
 
Unusual Web Bugs
Unusual Web Bugs
amiable_indian
 
Django Web Application Security
Django Web Application Security
levigross
 
Cross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with Java
Jim Manico
 
Practical 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 Default
Mohammed ALDOUB
 
Securing 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.
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 Services
Abraham Aranguren
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
Kazuho Oku
 
Securing WordPress
Securing WordPress
Shawn Hooper
 
Php
Php
Yesha kapadia
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Security.ppt
Security.ppt
webhostingguy
 
New 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 XSS
Ivan Ortega
 
Ekoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's Methodology
bugcrowd
 
Practical web-attacks2
Practical web-attacks2
OWASP (Open Web Application Security Project)
 
My app is secure... I think
My app is secure... I think
Wim Godden
 
Web Browsers And Other Mistakes
Web Browsers And Other Mistakes
kuza55
 
Xss is more than a simple threat
Xss is more than a simple threat
Avădănei Andrei
 
Charla jornadas-tic-normal2-091204050439-phpapp01
Charla jornadas-tic-normal2-091204050439-phpapp01
Liliana Bonin
 
Dia de la Bandera
Dia de la Bandera
sanrafael
 
Historia De La Bandera
Historia De La Bandera
sanrafael
 
Presentacion power point belgrano
Presentacion power point belgrano
Emii Del Pozo
 

More Related Content

What's hot (18)

Practical 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 Default
Mohammed ALDOUB
 
Securing 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.
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 Services
Abraham Aranguren
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
Kazuho Oku
 
Securing WordPress
Securing WordPress
Shawn Hooper
 
Php
Php
Yesha kapadia
 
12-security.ppt - PHP and Arabic Language - Index
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Security.ppt
Security.ppt
webhostingguy
 
New 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 XSS
Ivan Ortega
 
Ekoparty 2017 - The Bug Hunter's Methodology
Ekoparty 2017 - The Bug Hunter's Methodology
bugcrowd
 
Practical web-attacks2
Practical web-attacks2
OWASP (Open Web Application Security Project)
 
My app is secure... I think
My app is secure... I think
Wim Godden
 
Web Browsers And Other Mistakes
Web Browsers And Other Mistakes
kuza55
 
Xss is more than a simple threat
Xss is more than a simple threat
Avădănei Andrei
 
Practical 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 Default
Mohammed ALDOUB
 
Securing 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 Services
Abraham Aranguren
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
mirahman
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
Kazuho Oku
 
Securing WordPress
Securing WordPress
Shawn Hooper
 
12-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 XSS
Ivan Ortega
 
Ekoparty 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 think
Wim Godden
 
Web Browsers And Other Mistakes
Web Browsers And Other Mistakes
kuza55
 
Xss 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-phpapp01
Liliana Bonin
 
Dia de la Bandera
Dia de la Bandera
sanrafael
 
Historia De La Bandera
Historia De La Bandera
sanrafael
 
Presentacion 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.
carolinadiaz28
 
Homenaje a Manuel Belgrano
Homenaje a Manuel Belgrano
Emii Del Pozo
 
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
frazuwi
 
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-phpapp01
Liliana Bonin
 
Dia de la Bandera
Dia de la Bandera
sanrafael
 
Historia De La Bandera
Historia De La Bandera
sanrafael
 
Presentacion 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.
carolinadiaz28
 
Homenaje a Manuel Belgrano
Homenaje a Manuel Belgrano
Emii Del Pozo
 
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
PRESENTACION SOBRE LOS SIMBOLOS PATRIOS
frazuwi
 
Ad

Similar to Php My Sql Security 2007 (20)

PHPUG Presentation
PHPUG Presentation
Damon Cortesi
 
Secure Programming In Php
Secure Programming In Php
Akash Mahajan
 
Website Security
Website Security
Carlos Z
 
Web Security
Web Security
Supankar Banik
 
My app is secure... I think
My app is secure... I think
Wim Godden
 
Database security for PHP
Database security for PHP
Rohan Faye
 
null Bangalore meet - Php Security
null Bangalore meet - Php Security
n|u - The Open Security Community
 
Secure programming with php
Secure programming with php
Mohmad Feroz
 
Php Security By Mugdha And Anish
Php Security By Mugdha And Anish
OSSCube
 
Security in PHP Applications: An absolute must!
Security in PHP Applications: An absolute must!
Mark Niebergall
 
Php security3895
Php security3895
PrinceGuru MS
 
PHP Security
PHP Security
manugoel2003
 
Concern of Web Application Security
Concern of Web Application Security
Mahmud Ahsan
 
PHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
My app is secure... I think
My app is secure... I think
Wim Godden
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
Aleksandr Yampolskiy
 
Joomla security nuggets
Joomla security nuggets
guestbd1cdca
 
Php security common 2011
Php security common 2011
10n Software, LLC
 
Php Security3895
Php Security3895
Aung Khant
 
Php security
Php security
ssrajsathya
 
Secure Programming In Php
Secure Programming In Php
Akash Mahajan
 
Website Security
Website Security
Carlos Z
 
My app is secure... I think
My app is secure... I think
Wim Godden
 
Database security for PHP
Database security for PHP
Rohan Faye
 
Secure programming with php
Secure programming with php
Mohmad Feroz
 
Php Security By Mugdha And Anish
Php Security By Mugdha And Anish
OSSCube
 
Security in PHP Applications: An absolute must!
Security in PHP Applications: An absolute must!
Mark Niebergall
 
Concern of Web Application Security
Concern of Web Application Security
Mahmud Ahsan
 
PHP Database Programming Basics -- Northeast PHP
PHP Database Programming Basics -- Northeast PHP
Dave Stokes
 
My app is secure... I think
My app is secure... I think
Wim Godden
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
Aleksandr Yampolskiy
 
Joomla security nuggets
Joomla security nuggets
guestbd1cdca
 
Php Security3895
Php Security3895
Aung Khant
 
Ad

More from Aung Khant (20)

Introducing Msd
Introducing Msd
Aung Khant
 
Securing Php App
Securing Php App
Aung Khant
 
Securing Web Server Ibm
Securing Web Server Ibm
Aung Khant
 
Security Design Patterns
Security Design Patterns
Aung Khant
 
Security Code Review
Security Code Review
Aung Khant
 
Security Engineering Executive
Security Engineering Executive
Aung Khant
 
Security Engineeringwith Patterns
Security Engineeringwith Patterns
Aung Khant
 
Security Web Servers
Security Web Servers
Aung Khant
 
Security Testing Web App
Security Testing Web App
Aung Khant
 
Session Fixation
Session Fixation
Aung Khant
 
Sql Injection Paper
Sql Injection Paper
Aung Khant
 
Sql Injection Adv Owasp
Sql Injection Adv Owasp
Aung Khant
 
Php Security Iissues
Php Security Iissues
Aung Khant
 
Sql Injection White Paper
Sql Injection White Paper
Aung Khant
 
S Shah Web20
S Shah Web20
Aung Khant
 
S Vector4 Web App Sec Management
S Vector4 Web App Sec Management
Aung Khant
 
Php Security Value1
Php Security Value1
Aung Khant
 
Privilege Escalation
Privilege Escalation
Aung Khant
 
Php Security Workshop
Php Security Workshop
Aung Khant
 
Preventing Xs Sin Perl Apache
Preventing Xs Sin Perl Apache
Aung Khant
 
Introducing Msd
Introducing Msd
Aung Khant
 
Securing Php App
Securing Php App
Aung Khant
 
Securing Web Server Ibm
Securing Web Server Ibm
Aung Khant
 
Security Design Patterns
Security Design Patterns
Aung Khant
 
Security Code Review
Security Code Review
Aung Khant
 
Security Engineering Executive
Security Engineering Executive
Aung Khant
 
Security Engineeringwith Patterns
Security Engineeringwith Patterns
Aung Khant
 
Security Web Servers
Security Web Servers
Aung Khant
 
Security Testing Web App
Security Testing Web App
Aung Khant
 
Session Fixation
Session Fixation
Aung Khant
 
Sql Injection Paper
Sql Injection Paper
Aung Khant
 
Sql Injection Adv Owasp
Sql Injection Adv Owasp
Aung Khant
 
Php Security Iissues
Php Security Iissues
Aung Khant
 
Sql Injection White Paper
Sql Injection White Paper
Aung Khant
 
S Vector4 Web App Sec Management
S Vector4 Web App Sec Management
Aung Khant
 
Php Security Value1
Php Security Value1
Aung Khant
 
Privilege Escalation
Privilege Escalation
Aung Khant
 
Php Security Workshop
Php Security Workshop
Aung Khant
 
Preventing Xs Sin Perl Apache
Preventing Xs Sin Perl Apache
Aung Khant
 

Recently uploaded (20)

WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 

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/