430 likes | 571 Views
Secure and High Performance web applications with PHP. Security. Developing Secure PHP Applications Securing the Server Secure Programming Simple Steps First - Configurations Don't Trust your Inputs XSS Uploads SQL Injection exec and file operations sessions.
E N D
Security • Developing Secure PHP Applications • Securing the Server • Secure Programming • Simple Steps First - Configurations • Don't Trust your Inputs • XSS • Uploads • SQL Injection • exec and file operations • sessions
Securing the Server and Apache • File permissions – never use 777 ! It's an invitation for disaster. • Change file ownership to apache user or group and remove write access to files • Hardening Apache and PHP Installations • Suhosin Patch, mod_security
Simple Stuff first – register_globals • register_globals = Off in php.ini • register_globals automatically initializes a variable from $_POST, $_GET and $_COOKIE data. • This is usually turned on in older versions of PHP <5. • It's off by default in PHP 5+
Simple Stuff first – register_globals • How is it bad? • Example : http://xyz.com/admin.php?admin_user=true <?php if (admin_user) { //do secure stuff } ?>
Simple Stuff first – error display • Turn of display errors in • display_errors = Off • Log errors instead of showing them on screen • log_errors = On • Users get information about your webserver through these errors – handle errors! Fatal error: Call to undefined function view_details() in D:\wamp\www\security\fatal.php on line 2
Simple Stuff first – magic_quotes_gpc • Turn off magic_quotes_gpc in php.ini • magic_quotes_gpc = off • Why? • Problematic adds extra slashes in most cases • Requires more processing power and memory if turned on • mysql_real_escape_string is better
File Extension for your code • Don't use .inc to save php code • Must end in .php • Most default installations are geared interpret only .php files • .inc files may show up your php code as text in the browser
Don't Trust your Inputs • https is not the solution to all your security problems! • Users on your application are also suspects! • Data Inputs $_GET, $_POST, $_COOKIE, $_SERVER
Don't Trust your Inputs • $_REQUEST • Collision of Data • Order set in php.ini • Defaults to GPCS – GET, POST, COOKIE, SERVER
XSS • Cross Site Scripting • Code Injection • Improper Input Handling • Example
XSS • Fixing XSS • Htmlentities() • Converts all possible characters to html entities < > .... • Htmlspecialchars() • Converts only <,>,',”,$ to html entities • Striptags() • Removes all tags or retains only selective tags • Partial Removal of tags still cause problems
File Uploads • Be careful with what you let users upload • Disable directory browsing using htaccess • Use htaccess to deny access to php, pl or other executable scripts in upload directories
SQL Injection • The ability of a user to change the SQL generated in your application and exploit it. • Example • Prevention • Type cast inputs • Use mysql_real_escape_string() • Using mysqli and prepared statements
exec and fopen • Clean your inputs before using them in exec and fopen • exec allows php to run system level commands! • fopen / file_get_contents allow opening of files from external urls!
Sessions – secure them • Sessions can be spoofed or stolen • Use session_regenerate_id to generate a new id • session_destroy does not change the session id ! • Prompt for user's password on any critical changes
https - finally • Use https where required • User logins • User Profile • E-Commerce Transactions • Plain http susceptible to packet sniffers on the network • Replay attack – even if you use Javascript to encrypt passwords on http pages
Software Updates • Keep your software up to date • Older Un-patched Software potentially missing out on security bug fixes • If you are using an open source framework or CMS, get the latest patches
Performance • Server Optimization • Caching • Database optimizations • Profile your code • Browser Cache Control • Scaling
Performance -Server Optimization • Apache Tuning • Remove Apache and PHP modules which are not required • PHP Extensions have to be initialized and destroyed on every request – so have just the minimum required extensions. • Other Apache configurations in httpd.conf
Performance - Application • Caching • PHP Accelerator • Application Level Caching • Caching Data • Caching HTML • File based cache • Shared memory cache • memcached
Performance - Caching • PHP Accelerator • Interpreted Language • Most PHP accelerators work by caching the compiled bytecode of PHP scripts to avoid the overhead of parsing and compiling source code on each request.-Wikipedia • APC, XCache , eAccelerator, Zend Platform, .. • General performance gains using PHP accelerators range from 2x to 10x
Performance - Caching • Application Level Caching • What data can you cache? • Cache results from a database query • Results from a web-service call • Cache data objects from config or xml file read • Cache Generated HTML • Reduces the processing required to generate the html • If a page requires 1 database query and if 100 people hit the page per second – caching the page for even 1 second saves 99 database queries!!
Performance - Caching • How to cache? • Zend Cache • http://framework.zend.com/manual/en/zend.cache.html • Allows multiple backends to store cache • Other cache classes • http://www.phpguru.org/static/Caching.html • PEAR Cache and Cache_Lite
Performance - Caching • Cache Invalidation • Time based Invalidation • Invoke cache invalidation on change of data
Performance - Caching • Memcached • is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications • Caches data in memory • Simple – Key Value • Can spread cache across multiple servers in a pool • PHP memcached • http://in.php.net/memcache
Performance - Caching $memcache_obj = new Memcache; $memcache_obj->connect('memcache_host', 11211); $memcache_obj->set('mydata', $data, MEMCACHE_COMPRESSED, 50); echo $memcache_obj->get('mydata');
Performance - Caching • Memcached - Cache Invalidation • Based on expiry time • If memory is full, when adding a new value, the least recently used keys are removed to make space for new data • No guarantee that data will presist even if you set the expiry time to 0
Performance – Caching • Cache Invalidation • Based on expiry time • If memory is full, when adding a new value, the least recently used data is removed and the new one takes it's place • No guarantee that data will persist even if you set the expiry time to 0
Performance – Database • Too many connections errors! • Using pconnect generally causes this error • Make sure you disconnect from the database when you finish your scripts • PHP does clean up database connections when the script execution is complete • If the PHP encounters a fatal error while execution, the cleanup doesn't happen – so handle exceptions!
Performance – Database • Lazy Connections • Database connections open on all pages even if the page is loading cached or static content • Implement Lazy Connections • Open a Connection to the database only on first query • This will conserve the number of connections on the database server
Performance – Database • Indexing ! • Index your tables • Use composite indexes where required • Can drastically reduce database load • Explain your select queries • Find bottlenecks • See if your indexes work
Performance – Database • Indexing !
Performance – Code Profiling • Use a code profiler to check for bottlenecks in your php code • IDE which support debugging and profiling • Zend Studio • Komodo • PHP Edit • Netbeans PHP
Performance – Code Profiling • Xdebug • kcachegrind • wincachegrind • webgrind • FirePHP – Firebug meets PHP
Performance – Browser • Get the browser to cache your content • Remove Etags in Apache • Set Expiry headers • Cache Control • Zip your html content using mod_deflate • YSlow!
Performance – • Load Balancing • Sticky Sessions • Round Robin • Load Based
Performance – • Load Balancing • Mysql Replication
Performance – • Sharding of data
Performance – • Issues in scaling up • Session Management • Synchronizing scripts & file uploads to all the app servers • File Server – NFS for scripts/sessions • Custom session management engines (using memcache) • Consolidation of Logs ( each server, NFS, logging server)
Q&A • me@vinuthomas.com
Links • Hardening PHP with Suhosin • http://advosys.ca/viewpoints/2006/11/hardening-php-servers-with-suhosin/ • FirePHP • http://www.firephp.org/ • Htaccess caching • http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html
Links • Memcache • http://www.danga.com/memcached/ • http://in.php.net/memcache • Xdebug • http://www.xdebug.org/ • Yslow • http://developer.yahoo.com/yslow/ • Highscalability Blog • http://highscalability.com/digg-architecture