secure php


Published on

Published in: Design, Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

secure php

  1. 1. How things can go wrong? How to prevent the disaster? Writing Secure PHP Applications
  2. 2. Never, ever, trust user inputs
  3. 3. Input Validation <ul><li>Always use server side validation as client side (javascript) validation can easily be bypassed </li></ul><ul><li>Use white-listed values </li></ul><ul><li>Use built-in escape functions </li></ul><ul><li>Validate for correct data types, like numbers </li></ul><ul><li>Don’t expect the return value from selections, radio buttons or check boxes of a form to be the ones you mentioned. So, always revalidate. </li></ul>
  4. 4. PHP Error Messages <ul><li>Great tool for both developer and hacker. </li></ul><ul><li>Can reveal server software and directory structure, even database login information. </li></ul><ul><li>Need to set error_reporting to 0 using php.ini or .htaccess file in production server. </li></ul><ul><li>Should have separate .htaccess files for development and production servers. </li></ul><ul><li>Use proper error handlers when necessary (instead of just showing the error message and die()ing ) </li></ul><ul><li>Further Reading : </li></ul>
  5. 5. Bad Features of PHP <ul><li>Register Globals </li></ul><ul><li>Consider the following code - </li></ul><ul><li>test.php </li></ul><ul><li>if ( $password == &quot;my_password&quot;) { </li></ul><ul><li>$authorized = 1; </li></ul><ul><li>} </li></ul><ul><li>if ( $authorized == 1) { </li></ul><ul><li>echo &quot;Lots of important stuff.&quot;; </li></ul><ul><li>} </li></ul><ul><li>test.php?authorized=1 will produce “Lots of important stuff.” </li></ul><ul><li>To disable register_globals using .htaccess file – </li></ul><ul><li>php_flag register_globals 0 </li></ul><ul><li>To disable register_globals using php.ini – </li></ul><ul><li>register_globals = Off </li></ul>
  6. 6. Bad Features of PHP <ul><li>Magic Quotes </li></ul><ul><li>Originally introduced to save programmers the trouble of using addslashes() </li></ul><ul><li>Major problems associated with it is – </li></ul><ul><li>When both magic quotes and addslashes() are used, you end up with multiple slashes being added, causing errors </li></ul><ul><li>If you think magic quotes is turned on, but actually it is not, then inputs go unchecked. </li></ul><ul><li>It only escapes double and single quote, but there are other database-specific characters that need to be escaped </li></ul>
  7. 7. Bad Features of PHP <ul><li>Magic Quotes </li></ul><ul><li>Disabling using .htaccess – </li></ul><ul><li>php_flag magic_quotes_gpc 0 </li></ul><ul><li>php_flag magic_quotes_runtime 0 </li></ul><ul><li>Disabling using php.ini – </li></ul><ul><li>magic_quotes_gpc = Off </li></ul><ul><li>magic_quotes_runtime = Off </li></ul><ul><li>magic_quotes_sybase = Off </li></ul>
  8. 8. SQL Injection <ul><li>Most common and most destructive security hazard </li></ul><ul><li>Lets see the common way to check username and password entered into a form – </li></ul><ul><li>$check = mysql_query (&quot; SELECT Username, Password, UserLevel FROM Users WHERE Username = ' &quot;. $_POST ['username'].&quot; ' and Password = ' &quot;. $_POST ['password'].&quot; ' &quot;); </li></ul><ul><li>If we enter the following in the “username” input box and submit - </li></ul><ul><li>' OR 1=1 # </li></ul><ul><li>The query that is going to be executed will now look like this – </li></ul><ul><li>SELECT Username, Password FROM Users WHERE Username = '' OR 1 = 1 # ' and Password = '' </li></ul><ul><li>As you can see, this query will return all the users from the database and as generally first user on a user table is the admin, the hacker will easily gain admin privilege. </li></ul><ul><li>We need to either use mysql_real_escape_string() on all database inputs (not just on string types) or use mysqli extension. </li></ul>
  9. 9. File Manipulation <ul><li>Some sites currently running on the web today have URLs that look like this: </li></ul><ul><li>index.php?page=contactus.html </li></ul><ul><li>The user can very easily change the &quot;contactus.html&quot; bit to anything they like. For example, </li></ul><ul><li>index.php?page=.htpasswd </li></ul><ul><li>By changing the URL, on some systems, to reference a file on another server, they could even run PHP that they have written on your site. </li></ul><ul><li>When users download a file from your server, if the file name depends on user input, he can easily manipulate it to download system files by giving inputs like – “../../../etc/passwd” </li></ul>
  10. 10. File Manipulation <ul><li>To prevent remote and system files inclusion, make these changes in your php.ini file – </li></ul><ul><li>Correctly set “open_basedir” </li></ul><ul><li>Set “allow_url_fopen” to Off </li></ul><ul><li>Always validate file names to make sure only valid characters are included – </li></ul><ul><li>function isValidFileName( $file ) { </li></ul><ul><ul><li>/* don't allow .. and allow any &quot;word&quot; character */ </li></ul></ul><ul><li>return preg_match ('/^(((?:.)(?!.))|w)+$/', $file ); </li></ul><ul><li>} </li></ul><ul><li>Use database and hidden, generated file names if possible for file downloads. </li></ul>
  11. 11. Using Defaults <ul><li>MySQL uses default username of “root” and blank password </li></ul><ul><li>SQL Server uses “sa” as default user with a blank password </li></ul><ul><li>Hackers will first try to use the default username, password combination everywhere – be it a MySQL server or CMS like Wordpress, Joomla or Drupal. </li></ul><ul><li>Make sure first thing you do after installing any software on server is to change default username, passwords. </li></ul><ul><li>Also, create separate users other than “root” with appropriate permissions on MySQL. </li></ul>
  12. 12. Leaving Installation Files Online <ul><li>Many PHP programs come with installation files. Many of these are self-deleting once run, and many applications will refuse to run until you delete the installation files. </li></ul><ul><li>Many however, will not pay the blindest bit of attention if the install files are still online. If they are still online, they may still be usable, and someone may be able to use them to overwrite your entire site. </li></ul>
  13. 13. Predictability <ul><li>If a hacker wants to gain admin access of your site, first location they will try to look into may be - </li></ul><ul><li>Make sure your admin area is not predictable. Use something like – </li></ul><ul><li>  </li></ul><ul><li>Same goes with username and password. Don’t use an username ‘admin’ or ‘administrator’. Pick something unusual </li></ul><ul><li>Use a combination of lower and upper case letters along with digits to prevent dictionary attack. </li></ul>
  14. 14. File Systems <ul><li>Always disable directory listing by placing a ‘index.html’ file in every folder. You can also disable by using .htaccess or httpd.conf file, but using ‘index.html’ will make sure you’re protected even if your server settings are changed. </li></ul><ul><li>Don’t place common files in a directory like ‘’. Use something out of web root for that and give it an unusual name. </li></ul><ul><li>Don’t give a file the extension ‘.inc’ as it is usually rendered as text and can reveal the whole source code (and maybe database login information too). If you must use ‘.inc’, use ‘.inc.php’ instead as it will be rendered as php file. </li></ul>
  15. 15. Session Hijacking <ul><li>By default, session information in PHP is written to a temporary directory. The file itself contains the information in a fairly readable format. </li></ul><ul><li>As the file has to be readable and writable by the Web server user, the session files can create a major problem for anyone on a shared server. Someone other than you can write a script that reads these files so they can try to get values out of the session. </li></ul><ul><li>Encrypt everything that you put into session. It is not completely safe though. </li></ul><ul><li>Store session data in a different place, like a database. </li></ul>
  16. 16. Storing Passwords <ul><li>Do not store password as plain text </li></ul><ul><li>Do not try to invent your own password security </li></ul><ul><li>Do not encrypt passwords as they are reversible. Security through obscurity is not sufficient. </li></ul><ul><li>Do not use MD5 – though this cryptographic hashing function is irreversible , it is quite easy to make a list of millions of hashed passwords (a rainbow table) and compare the hashes to find the original passwords. MD5 is also prone to brute forcing (trying out all combinations with an automated script) because of collisions.  </li></ul>
  17. 17. Storing Passwords <ul><li>Do not use a single site-wide salt. A salt is a string that is hashed together with a password so that most rainbow tables (or dictionary attacks) won’t work. </li></ul><ul><li>$password = 'swordfish'; </li></ul><ul><li>$salt = 'something random';   </li></ul><ul><li>$hash = md5 ( $salt . $password ); //Value: db4968a3db5f6ed2f60073c747bb4fb5 </li></ul><ul><li>Use a cryptographically strong hashing function like SHA-1 or even SHA-256 (using PHP’s hash() function). </li></ul><ul><li>Use a long and random salt for each password. </li></ul><ul><li>Use a slow hashing algorithm to make brute force attacks near impossible. </li></ul><ul><li>Regenerate the hash every time a users logs in. </li></ul>
  18. 18. Storing Passwords <ul><li>Code to create the hash and salt </li></ul><ul><li>$username = 'Admin'; $password = 'gf45_gdf#4hg';   // Create a 256 bit (64 characters) long random salt // Let's add 'something random' and the username // to the salt as well for added security $salt = hash('sha256', uniqid ( mt_rand (), true ) . 'something random' . strtolower ( $username ));   // Prefix the password with the salt $hash = $salt . $password ;   // Hash the salted password a bunch of times for ( $i = 0; $i < 100000; $i ++ ) { $hash = hash('sha256', $hash ); }   // Prefix the hash with the salt so we can find it back later $hash = $salt . $hash ; </li></ul>
  19. 19. Storing Passwords <ul><li>Code to validate password </li></ul><ul><li>$username = 'Admin'; $password = 'gf45_gdf#4hg';   $sql = ' SELECT `hash` FROM `users` WHERE `username` = &quot;' . mysql_real_escape_string ( $username ) . '&quot; LIMIT 1 ;';   $r = mysql_fetch_assoc ( mysql_query ( $sql ));   // The first 64 characters of the hash is the salt </li></ul><ul><li>$salt = substr($r[' hash '], 0, 64);   $hash = $salt . $password ;   // Hash the password as we did before for ( $i = 0; $i < 100000; $i ++ ) { </li></ul><ul><li>$hash = hash('sha256', $hash ); </li></ul><ul><li>}   $hash = $salt . $hash ;   if ( $hash == $r ['hash'] ) { </li></ul><ul><li>// Ok! </li></ul><ul><ul><li>} </li></ul></ul>
  20. 20. Login Systems <ul><li>You should add a turing test to your admin login page. Have a randomly generated series of letters and numbers on the page that the user must enter to login. Make sure this series changes each time the user tries to login, that it is an image (rather than simple text), and that it cannot be identified by an optical character recognition script. </li></ul><ul><li>Add in a simple counter. If you detect a certain number of failed logins in a row, disable logging in to the administration area until it is reactivated by someone responsible. If you only allow each potential attacker a small number of attempts to guess a password, they will have to be very lucky indeed to gain access to the protected area. This might be inconvenient for authentic users, however is usually a price worth paying. </li></ul><ul><li>Make sure you track IP addresses of both those users who successfully login and those who don't. If you spot repeated attempts from a single IP address to access the site, you may consider blocking access from that IP address altogether. </li></ul>
  21. 21. Powerful Commands <ul><li>PHP contains a variety of commands with access to the operating system of the server, and that can interact with other programs. Unless you need access to these specific commands, it is highly recommended that you disable them entirely. </li></ul><ul><li>For example, the  eval()  function allows you to treat a string as PHP code and execute it. This can be a useful tool on occasion. However, if using the  eval()  function on any input from the user, the user could cause all sorts of problems. You could be, without careful input validation, giving the user free reign to execute whatever commands he or she wants. For example – </li></ul><ul><li>eval (&quot;shell_exec(&quot;rm -rf { $_SERVER ['DOCUMENT_ROOT']}&quot;);&quot;); </li></ul>
  22. 22. Powerful Commands <ul><li>The php.ini file gives you a way to completely disable certain functions in PHP - &quot;disable_functions&quot;. This directive of the php.ini file takes a comma-separated list of function names, and will completely disable these in PHP. Commonly disabled functions include  ini_set() ,  exec() , fopen() ,  popen() ,  passthru() ,  readfile() ,  file() ,  shell_exec()  and  system() . </li></ul><ul><li>It may be (it usually is) worth enabling safe_mode on your server. This instructs PHP to limit the use of functions and operators that can be used to cause problems. If it is possible to enable safe_mode and still have your scripts function, it is usually best to do so. </li></ul>
  23. 23. Cross-Site Scripting (XSS) <ul><li>Unlike SQL Injection, which relies on the use of delimiters in user-input text to take control of database queries, code injection relies on mistakes in the treatment of text before it is output. </li></ul><ul><li>Let's say you've not added a limit to username lengths. Someone could, if they wanted, create a user with the following username: </li></ul><ul><li>username<script type=&quot;text/javascript&quot; src=&quot;;></script> </li></ul><ul><li>Anyone that then views a page with that username on it will see a normal username, but a JavaScript has been loaded from another site invisibly to the user. </li></ul>
  24. 24. Cross-Site Scripting (XSS) <ul><li>It allows attackers to add keyloggers, tracking scripts or porn banners on your site, or just stop your site working altogether.  </li></ul><ul><li>It can also used for cookie hijacking so that a real user can be faked. </li></ul><ul><li>Always use htmlentities() function to output user-generated texts. </li></ul><ul><li>Limit the character set that can used for a particular text type </li></ul><ul><li>Disallow HTML input if possible. If that is not an option, only allow limited HTML tags </li></ul>
  25. 25. Cross-Site Request Forgery (CSRF) <ul><li>CSRF attacks are exploits that take advantage of user privileges to carry out an attack. In a CSRF attack, your users can easily become unsuspecting accomplices. For example – </li></ul><ul><li><img src=&quot;; /> </li></ul><ul><li>CSRF attacks are often in the form of <img> tags because the browser unwittingly calls the URL to get the image. However, the image source could just as easily be the URL of a page on the same site that does some processing based on the parameters passed into it. When this <img> tag is placed with an XSS attack — which are the most common of the documented attacks — users can easily do something with their credentials without knowing it — thus, the forgery. </li></ul>
  26. 26. Cross-Site Request Forgery (CSRF) <ul><li>Never let the user do anything with a GET request - always use POST.  </li></ul><ul><li>Confirm actions before performing them with a confirmation dialog on a separate page - and make sure both  the original action button or link  and  the confirmation were clicked. </li></ul><ul><li>Add a randomly generated token to forms and verify its presence when a request is made.  </li></ul><ul><li>Time-out sessions with a short timespan (think minutes, not hours). Encourage the user to log out when they've finished.  </li></ul><ul><li>Check the HTTP_REFERER header (it can be hidden, but is still worth checking as if it is a different domain to that expected it is definitely a CSRF request). </li></ul>
  27. 27. References <ul><li>How to store passwords safely with PHP and MySQL – </li></ul><ul><li>Writing secure PHP series – </li></ul><ul><li> </li></ul><ul><li> </li></ul><ul><li> </li></ul><ul><li> </li></ul><ul><li>Seven habits for writing secure PHP applications by IBM - </li></ul><ul><li>5 Helpful Tips for Creating Secure PHP Applications - </li></ul>
  28. 28. <ul><li>Finally, Be Completely and Utterly Paranoid </li></ul>
  29. 29. <ul><li>Thank you </li></ul>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.