Php web app security (eng)
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

Php web app security (eng)

  • 4,027 views
Uploaded on

● PHP and the OWASP Top Ten Security ...

● PHP and the OWASP Top Ten Security
Vulnerabilities
● Secure Programming With The Zend
Framework
● Apache HTTPD
Security
● MySQL Security
● PHP Security Tools

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
4,027
On Slideshare
4,027
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
14
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. PHP Web Application Security28/03/2012
  • 2. Softjourn Inc.PHP Web Application Security Anatoliy Okhotnikov Softjourn Inc.
  • 3. PHP Web Application Security
  • 4. 3/27/12 Agenda ● PHP and the OWASP Top Ten Security Vulnerabilities ● Secure Programming With The Zend Framework ● Apache HTTPD Security ● MySQL Security ● PHP Security Tools
  • 5. PHP and the OWASP Top 10 The Open Web Application Security Project released a helpful document that lists what they think are the top ten security vulnerabilities in web applications These vulnerabilities can, of course, exist in PHP applications
  • 6. 1. Unvalidated Parameters Turn off register_globals. Access values from URLs, forms, and cookies through the superglobal arrays $_GET, $_POST, and $_COOKIE Before you use values from the superglobal arrays, validate them Regular expressions are the easiest way Make sure data from client hasnt been tampered with by sending a hash of the data PHP Cookbook: Recipe 9.7 ("Securing PHPs Form Processing"), Recipe 14.3 ("Verifying Data with Hashes")
  • 7. 2. Broken Access Control Instead of rolling your own access control solution, use PEAR modules Auth does cookie-based authentication and Auth_HTTP does browser- based authentication. PEAR Packages: Auth, Auth_HTTP.
  • 8. 3. Broken Account and Session Management  Use PHPs built-in session management functions for secure, standardized session management  Be careful how your server is configured to store session information  Session-specific traffic should be sent over SSL  PHP Cookbook: Recipe 8.5 ("Using Session Tracking"), Recipe 8.6 ("Storing Sessions in a Database")
  • 9. 4. Cross-Site Scripting (XSS) Flaws Filter variables(outside data) before including them in hidden form fields, in query strings, or just plain page output PHP Manual: htmlspecialchars(), strtr(), strip_tags(), utf8_decode() PHP Cookbook: Recipe 8.8 ("Building a GET Query String"), Recipe 9.8 ("Escaping Control Characters from User Data")
  • 10. 5. Buffer Overflows No runtime memory allocation No pointers like in C No buffer overflows in your PHP code Watch out for buffer overflows in PHP itself (and its extensions) Subscribe to the php-announce mailing list PHP Mailing Lists: http://php.net/mailing-lists.php
  • 11. 6. Command Injection Flaws Dont pass unfiltered, unescaped malicious commands to an external process or database Always escape user input before passing it Use escapeshellcmd() and escapeshellarg() Canonicalize pathnames with realpath() addslashes(), mysql_real_escape_string(), DB::quote() PHP Cookbook: Recipe 18.20 ("Escaping Shell Metacharacters"), Recipe 10.9 ("Escaping Quotes")
  • 12. 7. Error Handling Problems Error messages shouldnt contain any descriptive system information Tell PHP to put error messages in your servers error log instead of displaying them to a user “log_errors=On” and “display_errors=Off” PHP Cookbook: Recipe 8.14 ("Hiding Error Messages from Users")
  • 13. 8. Insecure Use of Cryptography The mcrypt extension provides a standardized interface to cryptographic algorithms Be careful about where (if anywhere) you store encryption keys Store keys apart from encrypted data Use SSL for prompts and replies for sensetive data, like encryption keys PHP Cookbook: Recipe 14.7 ("Encrypting and Decrypting Data")
  • 14. 9. Remote Administration Flaws When possible, run remote administration tools over SSL Change the default administrative user names and passwords Change the default administrative URL as well Run administrative tools on a different web server than the public web server
  • 15. 10. Web and Application Server Misconfiguration Keep on top of PHP patches and security problems Stay away from the automatic PHP source display handler Use php.ini-recommended as a base for your site configuration rather then php.ini-dist PHP Mailing Lists: http://www.php.net/mailing- lists.php
  • 16. Secure Programming With The Zend Framework Authentication Input Validation & Filtering SQL Security Cross-Site Request Forgery (CSRF) Protection Session Management Security Cross-Site Scripting (XSS) Protection
  • 17. ZF: Authentication
  • 18. ZF: Authentication Zend-Framework applications usually a MVC with dispatcher With dispatcher every reachable script doesnt need to implement or embed authentication Deriving the Zend_Controller_Action Authentication implemented in init() method Attention: if a controller has an own init() method then method of the parent class must be called
  • 19. ZF: Input Validation & Filtering Access via request object Zend_Controller_Request_Http Either via methods or magic properties Access is unfiltered - only raw data Access via magic property in the following order: internal parameter array, $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV
  • 20. ZF: Accessing Request Parameters
  • 21. ZF: Validation Validation with Zend_Validate Zend-Framework comes with a set of validators  Alnum, Alpha, Barcode, Between, Ccnum, Date, Digits, EmailAddress, Float, GraterThen, Hex, Hostname, Iban, InArray, Int, Ip, LessThen, NotEmpty, Regex, StringLength For complex validations own validators can be implemented It is possible to combine validators in chains
  • 22. ZF: Filtering Filtering with Zend_Filter Zend-Framework comes with a set of pre defined filters  Alnum, Alpha, BaseName, Callback, Digits, Dir, Encrypt, Htmlentities, Int, StripNewlines, RealPath, StringToUpper, StringToLower, StringTrim, StripTags For complex filtering own filters can be implemented It is possible to combine filters in chains
  • 23. ZF: ...in Forms ZF-Forms use validators and filters automatically They are attached to Zend_Form_Element objects And can be chained as wished Form is validated in the action handler
  • 24. ZF: Zend_Filter_Input Is a framework for validation and filtering complete arrays Applies defined filter and validation ruleset to supplied data Allows validation of all user input automatically
  • 25. ZF: SQL Security Zend-Framework offers different APIs for handling queries  Zend_Db  Zend_Db_Statement  Zend_Db_Select  Zend_Db_Table
  • 26. ZF: Queries & Escaping Be aware: both put strings in quotes* SQL-injection is still possible
  • 27. ZF: Zend_Db_Select Used to dynamically build SELECT statements Uses partially prepared statements SQL-injection still possible when wrongly used  Vulnerable through: WHERE / ORDER BY
  • 28. ZF: Cross Site Request Forgery (CSRF) Protection Zend Framework offers Zend_Form_Element_Hash which is a secret token with built-in validator Normally protection must be added manually By deriving Zend_Form it is possible to create an own form class that automatically comes with CSRF protection
  • 29. ZF: Token Algorithm Token algorithm could be improved  Avoid mt_rand()  More entropy But it is safe enough (for now)
  • 30. ZF: Session Management Security Configuration has big influence on security For SSL applications set the secure flag Use own session id for each application Harden the session cookie against XSS with the httpOnly flag Define the maximal lifetime Zend_Session::setOptions(...); Zend_Session::start();
  • 31. ZF: Session Fixation & Hijacking Session Fixation  Is harder in case of session validation / strict session handling  But it only stopped by regenerating the session id after each change in status  Zend_Session::regenerateId();  Should be added directly into login Session Hijacking  There is onle one real protection — SSL  HttpOnly cookies protect against session id theft by XSS  Session validation only of limited use
  • 32. ZF: Session Validation Zend-Framework supports session validators to validate sessions, like:  Zend_Session_Validator_HttpUserAgent Be aware of troubles  UA HTTP header check dead Since IE 8  Accept HTTP header always been a problem with MS IE  Client IP is a problem on big proxy farms Possible to limit to C/B/A networks But useful for SSL applications
  • 33. ZF: Cross Site Scripting (XSS) Protection  Zend-Framework does not support automatic output escaping  Preventing XSS is the job of the programmer  XSS occurs in the “view” part  Encoding before echoing  Encoding when assigning template variables
  • 34. ZF: Protecting with Zend_View_Helper  Preventing XSS is error prone — one XSS for every forgotten encoding  Automatically scanning for forgotten escaping is hard  Directly echoing variables should be forbidden (eg. With Bytekit + pre-commit- hook)  Output only viz Zend_View_Helper  Preventing XSS becomes a job of Zend_View_Helper
  • 35. ZF: Automatic Escaping with Zend_View  All output goes through Zend_View  Deriving Zend_View allows automatic encoding  eg. by overloading __set() and __get()  Be aware: Encoding must be context sensitive (eg.: javascript: links)
  • 36. Apache HTTPD Security Keep up to date Permissions on ServerRoot Directories Server Side Includes CGI in General Non Script Aliased CGI Script Aliased CGI Other sources of dynamic content Protect System Settings Protect Server Files by Default Watch Your Logs
  • 37. Apache: Keep Up to Date Apache HTTP Server Announcements List  http://httpd.apache.org/lists.html#http-announce Use the service of your Apache distributor Monitor for problems in  add-on code  CGI scripts  underlying Operating System  etc. Keep your system software updated
  • 38. Apache: Permissions Apache is started by the root user, and it switches to the user defined by the User directive to serve hits Protect from modification by non-root users: configuration, binary, logs files & directories Htdocs directory may be modifiable by non-root users since root never executes any files out of there
  • 39. Apache: Server Side Includes Potential security risks  increased load on the server  using the exec cmd element Ways to enhance the security of SSI  enable suexec to isolate the damage  SSI-enabled files should have a separate extension, such as the conventional .shtml  disable the ability to run scripts and programs from SSI pages
  • 40. Apache: CGI In General You always have to remember that you must trust the writers of the CGI scripts/programs or your ability to spot potential security holes in CGI, whether they were deliberate or accidental Use suEXEC to allow scripts to run as different users so they dont conflict CGIWrap will help to avoid conflict problems as well
  • 41. Apache: Non Script Aliased CGI Allowing users to execute CGI scripts in any directory should only be considered if  You trust your users not to write scripts which will deliberately or accidentally expose your system to an attack  You consider security at your site to be so feeble in other areas, as to make one more potential hole irrelevant  You have no users, and nobody ever visits your server
  • 42. Apache: Script Aliased CGI Limiting CGI to special directories gives the admin control over what goes into those directories This is inevitably more secure than non script aliased CGI  but only if users with write access to the directories are trusted or the admin is willing to test each new CGI script/program for potential security holes Most sites choose this option over the non script aliased CGI approach
  • 43. Apache: Other sources of dynamic content Embedded scripting options  mod_php, mod_perl, mod_tcl, mod_python, etc. Run under the identity of the server itself Scripts executed by these engines potentially can access anything the server user can Some scripting engines may provide restrictions, but it is better to be safe and assume not
  • 44. Apache: Protecting Settings & Filesystem  Stop users from setting up .htaccess files  can override security features youve configured  Forbid default access to filesystem locations  Add appropriate Directory blocks to allow access only in those areas you wish  Pay particular attention to the interactions of Location and Directory directives  Also be wary of playing games with the UserDir directive
  • 45. Apache: Watching Your Logs Even though the log files only reports what has already happened, they will give you some understanding of what attacks is thrown against the server and allow you to check if the necessary level of security is present, for example:[Thu Jul 11 17:18:39 2002] [error] [clientfoo.example.com] client denied by serverconfiguration: /usr/local/apache/htdocs/.htpasswdfoo.example.com - - [12/Jul/2002:01:59:13 +0200]"GET /.htpasswd HTTP/1.1"
  • 46. Apache: modSecurity ModSecurity is a web application firewall that can work either embedded or as a reverse proxy Provides protection from a range of attacks against web applications and allows for HTTP traffic monitoring, logging and real- time analysis
  • 47. MySQL Security General Security Guidelines Password Security in MySQL Making MySQL Secure Against Attackers Security-Related mysqld Options Security Issues with LOAD DATA LOCAL How to Run MySQL as a Normal User
  • 48. MySQL: General Security Guidelines Do not ever give anyone access to the user table Learn the MySQL access privilege system Do not store any plaintext passwords in your DB Do not choose passwords from dictionaries Invest in a firewall Do not trust any data entered by users Escape special characters in data values Do not transmit plain (unencrypted) data over the Internet Learn to use the tcpdump and strings utilities
  • 49. MySQL: Password Security in MySQL Protect mysql.user, my.cnf, master.info Watch for passwords in SQL logs and backup dumps Do not specify password in the cmd line Use an option file or MYSQL_PWD The Password column must be wide enough to hold long hashes (41 bytes)
  • 50. MySQL: Making Secure Against Attackers  Require all MySQL accounts to have a password  Never run the MySQL server as the Unix root user  Do not permit the use of symlinks to tables  Only mysqld user account allowed to read and write  Do not grant the PROCESS, SUPER, FILE privileges to non-administrative users  Make plugin_dir read only
  • 51. MySQL: Security-Related mysqld Options  http://dev.mysql.com/doc/refman /5.1/en/privileges-options.html  allow-suspicious-udfs, automatic_sp_privileges, chroot, des-key-file, local-infile, old-passwords, safe-show- database, safe-user-create, secure-auth, secure-file-priv, skip-grant-tables, skip-name- resilve, skip-networking, skip- show-database
  • 52. MySQL: Security Issues with LOAD DATA LOCAL  The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed  The LOAD DATA statement can load a file that is located on the server host, or it can load a file that is located on the client host when the LOCAL keyword is specified  Disable if dont need it with --local-infile=0  Use [client] loose-local-infile=1
  • 53. MySQL: How to Run as a Normal User On Windows, you can run the server as a Windows service using a normal user account On Unix change data dir ownership to selected user  chown -R user_name /path/to/mysql/datadir Start server a selected user  --user=user_name option  [mysqld] user=user_name
  • 54. PHP Security Tools Pixy Suhosin PHP-IDS Sandcat Code OWASP WebScarab Spike PHP Security Audit PHPSecInfo General purpose security tools
  • 55. Tools: Pixy XSS and SQLI Scanner for PHP Programs with full include file resolution Pixy takes a PHP program as input, and creates a report that lists possible vulnerable points in the program Provides additional information for understanding the vulnerability Source code analyzer, static analyzer, PHP security analysis
  • 56. Tools: Suhosin Is an advanced protection system for PHP installations Designed to protect servers and users from known and unknown flaws in PHP applications and the PHP core in 2 parts: A small patch against the PHP core, that implements a few low-level protections against bufferoverflows or format string vulnerabilities A powerful PHP extension that implements all the other protections
  • 57. Tools: PHP-IDS Is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application Recognizes when an attacker tries to break your site and reacts in exactly the way you want it to Could range from simple logging to sending out an emergency mail, displaying a warning for the attacker or ending session
  • 58. Tools: SandCat Code Source code security scanner (commercial) Enables developers and QA testers to automatically scan any kind of PHP application source code for potential security vulnerabilities Scans for Cross-Site Scripting (XSS), File Inclusion, SQL Injection, Command Execution and weak validation Helps auditors to perform code reviews by identifying key areas of the code
  • 59. Tools: OWASP WebScarab Is a framework for analysing applications that communicate using the HTTP and HTTPS An intercepting proxy, allowing the operator to review and modify requests created by the browser before they are sent to the server Review and modify responses returned from the server before they are received by the browser
  • 60. Tools: Spike PHPSecAudit Tool is an OSS solution for doing static analysis of PHP code — search for exploits
  • 61. Tools: PhpSecInfo PhpSecInfo provides an equivalent to the phpinfo() Reports security information about the PHP environment Offers suggestions for improvement It is not a replacement for secure development techniques It does not do any kind of code or app auditing A bit outdated, but still useful
  • 62. Tools: Security Tests Metasploit — framework for exploits Nessus — active vulnerability scanner Nikto — web server scanner Oedipus — offline log parser Paros — all HTTP and HTTPS data can be intercepted and modified Vega — finds SQL injection, cross-site scripting (XSS), etc. Wireshark — protocol analyzer for troubleshooting, analysis, software and protocol development and education
  • 63. Links• http://www.sklar.com/page/article/owasp-top-ten• http://www.sitepoint.com/php-security-blunders/• http://www.phpwact.org/security/web_application_security• http://www.suspekt.org/downloads/DPC_Secure_Program ming_With_The_Zend_Framework.pdf• http://www.php.net/manual/en/security.php• http://httpd.apache.org/docs/2.2/misc/security_tips.html• http://dev.mysql.com/doc/refman/5.1/en/security.html• http://www.hotscripts.com/blog/6-free-php-security- auditing-tools/• http://www.open-source-developers.com/blog/php- debugging-testing-tools#security-tools• http://www.opensourcetesting.org/security.php• http://www.noupe.com/php/php-security-tips.html• http://www.syhunt.com/?n=Sandcat.Code? Copyright © 2000-2011 Softjourn, Inc. All rights reserved from=Sandcat.4PHP
  • 64. Questions & discussion“Anatoliy Okhotnikov”<aokhotnikov@softjourn.com> Copyright © 2000-2011 Softjourn, Inc. All rights reserved