How to Secure Your PHP Script (PHP SECURITY)

Collapse
This is a sticky topic.
X
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • info How to Secure Your PHP Script (PHP SECURITY)

    When offering an Internet service, you must always keep security in mind as you develop your code. It may appear that most PHP scripts aren't sensitive to security concerns; this is mainly due to the large number of inexperienced programmers working in the language. However, there is no reason for you to have an inconsistent security policy based on a rough guess at your code's significance. The moment you put anything financially interesting on your server, it becomes likely that someone will try to casually hack it. Create a forum program or any sort of shopping cart, and the probability of attack rises to a dead certainty.

    Here are a few general security guidelines, I've found from internet for my next .mobi product.


    Don't trust forms.

    Hacking forms is trivial. Yes, by using a silly JavaScript trick, you may be able to limit your form to allow only the numbers 1 through 5 in a rating field. The moment someone turns JavaScript off in their browser or posts custom form data, your client-side validation flies out the window.

    Users interact with your scripts primarily through form parameters, and therefore they're the biggest security risk. What's the lesson? Always validate the data that gets passed to any PHP script in the PHP script.

    Don't trust users.
    Assume that every piece of data your website gathers is laden with harmful code. Sanitize every piece, even if you're positive that nobody would ever try to attack your site. Paranoia pays off.

    Turn off global variables.
    The biggest security hole you can have is having the register_globals configuration parameter enabled. Mercifully, it's turned off by default in PHP 4.2 and later.
    Novice programmers view registered globals as a convenience, but they don't realize how dangerous this setting is. A server with global variables enabled automatically assigns global variables to any form parameters. For an idea of how this works and why this is dangerous, let's look at an example.
    Let's say that you have a script named process.php that enters form data into your user database. The original form looked like this:
    PHP Code:
    <input name="username" type="text" size="15" maxlength="64"
    PHP Code:
    <?php
    // Define $authorized = true only if user is authenticated
    if (authenticated_user()) {
        
    $authorized true;
    }
    ?>
    Recommended Security Configuration Options

    There are several PHP configuration settings that affect security features. Here are the ones that I use for production servers:In general, if you find code that wants to use these features, you shouldn't trust it. Be especially careful of anything that wants to use a function such as system,it's almost certainly flawed.

    With these settings now behind us, let's look at some specific attacks and the methods that will help you protect your server.
    Last edited by firemax; 04.03.10, 08:07.

  • #2
    SQL Injection Attacks

    Because the queries that PHP passes to MySQL databases are written in the powerful SQL programming language, you run the risk of someone attempting an SQL injection attack by using MySQL in web query parameters. By inserting malicious SQL code fragments into form parameters, an attacker attempts to break into (or disable) your server.

    Let's say that you have a form parameter that you eventually place into a variable named $product, and you create some SQL like this:

    $sql = "select * from pinfo where product = '$product'";


    If that parameter came straight from the form, use database-specific escapes with PHP's native functions, like this:

    $sql = 'Select * from pinfo where product = '"'
    mysql_real_escape_string($product) . '"';


    If you don't, someone might just decide to throw this fragment into the form parameter:

    39'; DROP pinfo; SELECT 'FOO


    Then the result of $sql is:

    select product from pinfo where product = '39'; DROP pinfo; SELECT 'FOO'


    Because the semicolon is MySQL's statement delimiter, the database processes these three statements:

    select * from pinfo where product = '39'
    DROP pinfo
    SELECT 'FOO'


    Well, there goes your table.

    Note that this particular syntax won't actually work with PHP and MySQL, because the mysql_query() function allows just one statement to be processed per request. However, a subquery will still work.

    To prevent SQL injection attacks, do two things:

    Always validate all parameters. For example, if something needs to be a number, make sure that it's a number.

    Always use the mysql_real_escape_string() function on data to escape any quotes or double quotes in your data.


    --------------------------------------------------------------------------------
    Note: To automatically escape any form data, you can turn on Magic Quotes.
    --------------------------------------------------------------------------------

    Some MySQL damage can be avoided by restricting your MySQL user privileges. Any MySQL account can be restricted to only do certain kinds of queries on selected tables. For example, you could create a MySQL user who can select rows but nothing else. However, this is not terribly useful for dynamic data, and, furthermore, if you have sensitive customer information, it might be possible for someone to have access to some data that you didn't intend to make available. For example, a user accessing account data could try to inject some code that accesses another account number instead of the one assigned to the current session.
    Last edited by firemax; 04.03.10, 07:56.

    Comment


    • #3
      Preventing Basic XSS Attacks[b]
      Last edited by firemax; 04.03.10, 07:58.

      Comment


      • #4
        Using SafeHTML

        The problem with the previous script is that it is simple, and it does not allow for any kind of user markup. Unfortunately, there are hundreds of ways to try to sneak JavaScript past someone's filters, and short of stripping all HTML from someone's input, there's no way of stopping it.

        Currently, there's no single script that's guaranteed to be unbreakable, though there are some that are better than most.

        One whitelisting solution is the SafeHTML anti-XSS parser from PixelApes.

        SafeHTML is smart enough to recognize valid HTML, so it can hunt and strip any dangerous tags. It does its parsing with another package called HTMLSax.

        To install and use SafeHTML, do the following:

        Go to http://pixel-apes.com/safehtml/?page=safehtml and download the latest version of SafeHTML.

        Put the files in the classes directory on your server. This directory contains everything that SafeHTML and HTMLSax need to function.

        Include the SafeHTML class file (safehtml.php) in your script.

        Create a new SafeHTML object called $safehtml.

        Sanitize your data with the $safehtml->parse() method.

        Here's a complete example:

        Code View:
        PHP Code:
        <?php
        /* If you're storing the HTMLSax3.php in the /classes directory, along
           with the safehtml.php script, define XML_HTMLSAX3 as a null string. */
        define(XML_HTMLSAX3'');
        // Include the class file.
        require_once('classes/safehtml.php');
        // Define some sample bad code.
        $data "This data would raise an alert <script>alert('XSS Attack')</script>";
        // Create a safehtml object.
        $safehtml = new safehtml();
        // Parse and sanitize the data.
        $safe_data $safehtml->parse($data);
        // Display result.
        echo 'The sanitized data is <br />' $safe_data;
        ?>
        If you want to sanitize any other data in your script, you don't have to create a new object; just use the $safehtml->parse() method throughout your script.

        What Can Go Wrong?
        The biggest mistake you can make is assuming that this class completely shuts down XSS attacks. SafeHTML is a fairly complex script that checks for almost everything, but nothing is guaranteed. You still want to do the parameter validation that applies to your site. For example, this class doesn't check the length of a given variable to ensure that it fits into a database field. It doesn't check for buffer overflow problems.

        XSS hackers are creative and use a variety of approaches to try to accomplish their objectives. Just look at RSnake's XSS tutorial at XSS (Cross Site Scripting) Cheat Sheet to see how many ways there are to try to sneak code past someone's filters. The SafeHTML project has good programmers working overtime to try to stop XSS attacks, and it has a solid approach, but there's no guarantee that someone won't come up with some weird and fresh approach that could short-circuit its filters.


        --------------------------------------------------------------------------------
        Note: For an example of the powerful effects of XSS attacks, check out MySpace Worm Explanation, which shows a step-by-step approach to creating the JavaScript XSS worm that overloaded the MySpace servers.
        Last edited by firemax; 04.03.10, 07:59.

        Comment


        • #5
          Protecting Data with a One-Way Hash


          Hacking the Script
          Last edited by firemax; 04.03.10, 08:01.

          Comment


          • #6
            Encrypting Data with Mcrypt
            PHP Code:
            <?php

            $data 
            "Stuff you want encrypted";
            $key "Secret passphrase used to encrypt your data";
            $cipher "MCRYPT_SERPENT_256";
            $mode "MCRYPT_MODE_CBC";

            function 
            encrypt($data$key$cipher$mode) {
            // Encrypt data

            return (string)
                        
            base64_encode
                            
            (
                            
            mcrypt_encrypt
                                
            (
                                
            $cipher,
                                
            substr(md5($key),0,mcrypt_get_key_size($cipher$mode)),
                                
            $data,
                                
            $mode,
                                
            substr(md5($key),0,mcrypt_get_block_size($cipher$mode))
                                )
                            );
            }

            function 
            decrypt($data$key$cipher$mode) {
            // Decrypt data
                
            return (string)
                        
            mcrypt_decrypt
                            
            (
                            
            $cipher,
                            
            substr(md5($key),0,mcrypt_get_key_size($cipher$mode)),
                            
            base64_decode($data),
                            
            $mode,
                            
            substr(md5($key),0,mcrypt_get_block_size($cipher$mode))
                            );
            }

            ?>
            Hacking the Script
            In addition to experimenting with various encryption methods, you can add some convenience to this script. For example, rather than providing the key and mode every time, you could declare them as global constants in an included file.

            Comment


            • #7
              i believe this thread deserves to be sticky

              Comment


              • #8
                PHP File Upload Security &amp; Risks

                Why File Upload Forms are a major security threatCase 1: Simple file upload form with no validation
                A simple file upload form usually consists of a HTML form and a PHP script. The HTML form, is the form presented to the user, while the PHP script contains the code that takes care of the file upload. Below is an example of such form and PHP script:
                HTML Form:
                PHP Code:
                <form enctype="multipart/form-data" action="uploader.php" method="POST">
                <
                input type="hidden" name="MAX_FILE_SIZE" value="100000" />
                Choose a file to upload: <input name="uploadedfile" type="file" /><br />
                <
                input type="submit" value="Upload File" /> 
                PHP Code:
                PHP Code:
                <?php     
                $target_path 
                "uploads/";
                $target_path $target_path basename$_FILES['uploadedfile']['name']); 
                if(
                move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
                    echo 
                "The file ".  basename$_FILES['uploadedfile']['name']).  
                    
                " has been uploaded"
                } else{
                    echo 
                "There was an error uploading the file, please try again!"
                }
                 
                ?>
                When PHP receives a POST request with encoding type multipart/form-data, it will create a temporary file with a random name in a temp directory (e.g. /var/tmp/php6yXOVs). PhP will also populate the global array $_FILES with the information about the uploaded file:

                The PHP function move_uploaded_file will move the temporary file to a location provided by the user. In this case, the destination is below the server root. Therefore the files can be accessed using a URL like: http://www.domain.tld/uploads/uploadedfile.extCase 2: Mime Type validationtypeHTTP POST requests, which allow him to send a fake mime-type.


                Case 3: Block dangerous extensions
                Case 4: Double extensions (part 1)

                Case 5: Double extensions (part 2)
                A better approach to securing file upload forms is the white list approach. In this case, the developer defines a list of known/accepted extensions and does not allow extensions that are not specified in the list.
                AddHandler php5-script .php
                Case 6: Checking the image header
                When images only are allowed to be uploaded, developers usually validate the image header by using the PHP function called getimagesizegetimagesize PHP check. As seen in the screen shot below, the PHP code inserted in the image comments still gets executed when the image is requested from a normal web browser:





                Case 7: Protecting the upload folder with .htaccess
                Another popular way of securing file upload forms, is to protect the folder where the files are uploaded using .htaccess file. The idea is to restrict execution of script files in this folder. A .htaccess file typically contains the below code when used in this kind of scenario:
                If the destination file already exists, it will be overwritten.
                Because uploaded files can and will overwrite the existing ones, a malicious user can easily replace the .htaccess file with his own modified version. This will allows him to execute specific scripts which can help him compromise the server.

                Case 8: Client-side validation
                Another common type of security used in file upload forms, is client-side validation of files to be uploaded. Typically, such approach is more common in ASP.NET applications, since ASP.NET offers easy to use validation controls.
                PHP Code:
                [LEFT]
                [/
                LEFT]
                <
                asp:FileUpload ID="FileUpload1" runat="server" /><br /> 
                 <
                br />
                 <
                asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload File" />&nbsp;<br />
                 <
                br />
                 <
                asp:Label ID="Label1" runat="server"></asp:Label>
                 <
                asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server"
                 
                ErrorMessage="Only mp3, m3u or mpeg files are allowed!"
                 
                ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))
                 +(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$" 
                ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>
                 <
                br />
                 <
                asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
                 
                ErrorMessage="This is a required field!"
                 
                ControlToValidate="FileUpload1"></asp:RequiredFieldValidator
                Because this type of validation is done on the client side, a malicious user can easily bypass this type of validation. It is possible to write a short client side script that will do the validation instead of the script provided by the web application. Without using a web browser, the attacker can use an application that allows sending of HTTP POST requests to be able to upload the file.

                Suggested Solution
                Below is a list of best practices that should be enforced when file uploads are allowed on websites and web applications. These practices will help you securing file upload forms used in web applications;
                • Define a .htaccess file that will only allow access to files with allowed extensions.
                • Do not place the .htaccess file in the same directory where the uploaded files will be stored. It should be placed in the parent directory.
                • A typical .htaccess which allows only gif, jpg, jpeg and png files should include the following (adapt it for your own need). This will also prevent double extension attacks.


                PHP Code:
                deny from all
                 
                <Files "^\w+\.(gif|jpe?g|png)$">
                 
                order deny,allow
                 allow from all
                 
                </Files
                • If possible, upload the files in a directory outside the server root.
                • Prevent overwriting of existing files (to prevent the .htaccess overwrite attack).
                • Create a list of accepted mime-types (map extensions from these mime types).
                • Generate a random file name and add the previously generated extension.

                Conclusion
                As seen above, there are many ways how a malicious user can bypass file upload form security. For this reason, when implementing a file upload form in a web application, one should make sure to follow correct security guidelines and test them properly. Unfortunately, to perform the number of tests required, can take a lot of time and require a good amount of web security expertise.
                Though with Acunetix WVS, one can automatically perform file upload forms vulnerability tests without the need of web security expertise. Acunetix WVS provides the developer with extensive amount of information to be able to trace and fix the problem in the least possible time.

                More This Articale : Why File Upload Forms are a major security threat

                Summmary of mysql-apache-php.com's article


                1. Assign 775 permission to upload folder
                2. Check the file using PHP functions (if its photo upload)

                for the codes and details: PHP File Upload Security

                3. Disable Script Execution an Hide Indexes with .htaccess
                PHP Code:
                Options -Indexes
                Options 
                -ExecCGI
                AddHandler cgi
                -script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi 
                PHP Code:
                <Files ^(*.jpeg|*.jpg|*.png|*.gif)>
                order deny,allow
                deny from all
                </Files
                4. Place the upload folder outside WWW root.
                ex:
                PHP Code:
                ./uploads

                <img src="./uploads/photo.gif> 
                Read All @ : PHP File Upload Security

                Other Most Imported Articles :


                Extarnal:

                use this attachment to hide files path in your file download site.also you can use this with your autoindex program.
                Attached Files
                Last edited by firemax; 05.03.10, 11:49.

                Comment


                • #9
                  How to find PHP Shell on your server

                  In most of the hacking or defacing the most common tool used is PHP Shell. If you scan your server regularly for php shell and delete them you can avoid many hacking and defacing attempt on your server.

                  PHP Code:
                  #!/bin/bash
                  #Scanning all users directory for various php shell
                  # Below command is one line so see that its one line in your script or else it will generate error

                  echo "No PHP Shell was Found" > /root/scan.txt
                  /bin/egrep "cgitelnet|webadmin|PHPShell|tryag|r57shell|c99she ll|noexecshell|/etc/passwd|revengans|myshellexec" /home/*/public_html -R | cut -d: -f1 | uniq > /root/scan.txt

                  /bin/cat /root/scan.txt | mail -s "PHP Shell Scan" user@domain.com

                  #Replace your email address above

                  #Cron Settings
                  # 0 6 * * * PATH TO SCRIPT 
                  The above script is a very simple shell script which will scan all public_html directories of all cpanel accounts for various php shell. Then the script will mail you the locations of PHP Shell. You can set cron for this script to run once a day. If you check the code I have added a cron for it which you can use which will execute the script on 6th hour daily.

                  PHP Functions which help hackers to hack your server


                  I am listing below some PHP Functions which you should keep disabled if you dont need them as they help hackers to deface your websites or hack the server:

                  PHP Code:
                  dl
                  exec
                  shell_exec
                  system
                  passthru
                  popen
                  pclose
                  proc_open
                  proc_nice
                  proc_terminate
                  proc_get_status
                  proc_close
                  leak
                  apache_child_terminate
                  posix_kill
                  posix_mkfifo
                  posix_setpgid
                  posix_setsid
                  posix_setuid
                  escapeshellcmd
                  escapeshellarg
                  shell
                  -exec
                  fpassthru
                  crack_check
                  crack_closedict
                  crack_getlastmessage
                  crack_opendict
                  psockopen
                  php_uname
                  symlink
                  mkdir
                  ini_restore
                  posix_getpwuid
                  error_log
                  print_r
                  scandir
                  copy
                  phpinfo
                  ini_set 
                  To disable these functions you can add following line to /usr/local/lib/php.ini

                  PHP Code:
                  disable_functions "dl,exec,shell_exec,system,passthru,popen,pclose,p roc_open,proc_nice,proc_terminate,proc_get_status, proc_close,leak,
                  apache_child_terminate,posix_kill,posix_mkfifo,pos ix_setpgid,posix_setsid,posix_setuid,escapeshellcm d,escapeshellarg,shell-exec,fpassthru,crack_check,crack_closedict,crack_g etlastmessage,crack_opendict,psockopen,php_uname,s ymlink,mkdir
                  ,ini_restore,posix_getpwuid,error_log,print_r,scan dir,copy,phpinfo,ini_set" 
                  Then restart the apache server that is httpd service.

                  Please note: Doing this will break some of the php scripts on your clients. I would suggest you to block above functions first and then when you come to know which php scripts are breaking by this, at that time you can remove that particular function needed by the script. This way your disable function list will be perfect as required by your server

                  Hope this helps you all.

                  Comment


                  • #10
                    Well, guys, thank you all. I suggest you this tutorial:
                    Attached Files

                    Comment


                    • #11
                      great post friendz. tnx

                      Comment


                      • #12
                        very helpful article double thanks to the firemax.

                        Comment

                        Working...
                        X