SQL Injection Attack – Examples and Preventions in PHP

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    SQL Injection Attack – Examples and Preventions in PHP

    What is SQL injection?

    It is a basically a trick to inject SQL command or query as a input mainly in the form of the POST or GET method in the web pages. Most of the websites takes parameter from the form and make SQL query to the database. For a example, in a product detail page of php, it basically takes a parameter product_id from a GET method and get the detail from database using SQL query. With SQL injection attack, a intruder can send a crafted SQL query from the URL of the product detail page and that could possibly do lots of damage to the database. And even in worse scenario, it could even drop the database table as well.

    Examples of SQL Injection Attack in PHP:

    Let’s look at the usual query for user login in PHP,
    Code:
    $sql=”SELECT * FROM tbl_user WHERE username= ‘”.$_POST['username'].”‘ AND password= ‘”.$_POST['password'].”‘”;
    $result=mysql_query($sql);
    Well, lots of people thinks that only the valid user can log in inside the system but that’s not true.Well anybody can log in to that website with a simple trick.

    Let’s suppose that a intruder called SAM injected x’ OR ‘x’='x in the username field and x’ OR ‘x’='x in the password field. Then the final query will become like this
    Code:
    SELECT * FROM tbl_user WHERE username=’x’ OR ‘x’='x’ AND password=’x’ OR ‘x’='x’;
    Well you can see that query is always true and returns the row from the database. As the result , the malicious guy could log in to the system.

    Now even let’s look at the worst scenario of the SQL injection attack example. A intruder can even drop a table if the database user has drop privilege into that database.

    Let’s suppose a query in a product detail page
    Code:
    $sql=”SELECT * FROM product WHERE product_id= ‘”.$_GET['product_id'].”‘”;
    Now its turn of intruder to inject SQL command in the URL of the page, the code might be like this 10′; DROP TABLE product; # and the URL looks like this

    http://xyz.com/product.php?id=10′; DROP TABLE product; #

    Now query becomes like this
    Code:
    SELECT * FROM product WHERE product_id=’10′; DROP TABLE product; #’;
    You might be wondering what is the meaning of hash “#”, it tell MYSQL server to ignore the rest of the query.In this query, it simply ignore the last single quote (‘) of the query.
    Prevention from Sql Injection Attack in PHP

    To avoid the sql injection attack, please follow the following simple mechanisms in PHP

    1) Always restrict the length of the fields of form such as don’t allow more than 20 characters in the fields like username and password with the “maxlength” property available in the html form.

    2) Always validate for the proper input like weather the value is valid email or not, is numeric or not , valid date or not etc.

    3) Finally, Always use mysql_real_escape_string() function before sending the variable to the SQL query, it ad. For example
    Code:
    //note you must be connected to the database for using this function
    $username=mysql_real_escape_string($_POST['username']);
    $password=mysql_real_escape_string($_POST['password']);
    if a intruder inject ‘ OR 1 in the user name and password field then the value of the $username and $password will become \’ OR 1 which is not going to harm us anymore.
    ________________
    Jacques
    jacques@gw-designs.co.za
    http://coding.biz.tm
    Come join and lets make it a place to learn all the noobies how to code
    __________________

    NEVER FORGET TO CLICK THE TANX BUTTON IF U LIKE WHAT IM SHARING OR HELPING WITH

    #2
    Thats Cool........
    But I got A Problem Using mysql_real_escape_string()....That is it wont work in some numeric value and some of intejar.
    I Don't Know Why...............!

    Comment


      #3
      Originally posted by khan89 View Post
      Thats Cool........
      But I got A Problem Using mysql_real_escape_string()....That is it wont work in some numeric value and some of intejar.
      I Don't Know Why...............!
      my_sql_real_escape_string requires connection to database, if database is not connected - it wont work, then you will need to use an escape function instead.
      All of php functions can be reconstructed in various ways, however efficiency and speed become a factor
      tinyurl.com/earnbymobile
      Easy earning for Indians
      ---------------------
      Alternative mobile advertising network .. Minimum 100 USD pay / NET15 pay cycle, Good Brand, Best targeting for Android
      goo.gl/6vub3

      Comment


        #4
        Originally posted by morse View Post
        my_sql_real_escape_string requires connection to database, if database is not connected - it wont work, then you will need to use an escape function instead.
        All of php functions can be reconstructed in various ways, however efficiency and speed become a factor
        Yeah..........I know that pretty well. But again what escape function i should use if it wont workd!!
        Lacking Of Information Of mine.

        Comment


          #5
          Thanks for this useful theard!

          Comment


            #6
            Originally posted by khan89 View Post
            Yeah..........I know that pretty well. But again what escape function i should use if it wont workd!!
            Lacking Of Information Of mine.
            Code:
            function escape($str)
              {
               $search=array("\\","\0","\n","\r","\x1a","'",'"');
               $replace=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
               return str_replace($search,$replace,$str);
              }
            tinyurl.com/earnbymobile
            Easy earning for Indians
            ---------------------
            Alternative mobile advertising network .. Minimum 100 USD pay / NET15 pay cycle, Good Brand, Best targeting for Android
            goo.gl/6vub3

            Comment


              #7
              Originally posted by morse View Post
              Code:
              function escape($str)
                {
                 $search=array("\\","\0","\n","\r","\x1a","'",'"');
                 $replace=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
                 return str_replace($search,$replace,$str);
                }
              How could i call that!!

              Comment


                #8
                $search=array("\\","\0","\n","\r","\x1a","'",'"'); <--- last array value needs double quoted thats ,""");
                Originally posted by khan89 View Post
                How could i call that!!
                usage

                escape ("it's a string.");

                Comment


                  #9
                  you can prevent the sql injection just simple create an0nym0us table name tnt

                  Comment


                    #10
                    Place this into your core.php

                    Code:
                    //////////////////////// Anti Sql hit...
                    function check_injection() 
                      { 
                        $badchars = array("DROP","TRUNCATE", "SELECT", "UPDATE", "DELETE" , "UNION", "WHERE", "FROM","INSERT","ORDER BY"); 
                       
                        foreach($_REQUEST  as $value) 
                        { 
                          if(in_array(strtoupper($value), $badchars)) 
                          { 
                          $logfile= 'logs/log.txt'; //chmod 777 
                    $IP = $_SERVER['REMOTE_ADDR']; 
                    $logdetails= date("F j, Y, g:i a") . ': ' . '<a href=http://dnsstuff.com/tools/city.ch?ip='.$_SERVER['REMOTE_ADDR'].' target=_blank>'.$_SERVER['REMOTE_ADDR'].'</a>'; 
                    $fp = fopen($logfile, "r+"); 
                    fwrite($fp, $logdetails, strlen($logdetails)); 
                    fclose($fp); 
                    
                           header('Location:antihack.fbi'); 
                    
                          } 
                          else 
                          { 
                            $check = preg_split("//", $value, -1, PREG_SPLIT_OFFSET_CAPTURE); 
                    foreach($check as $char)
                    {
                    if(in_array(strtoupper($char), $badchars))
                    {
                          $logfile= 'logs/log.txt'; 
                    $IP = $_SERVER['REMOTE_ADDR']; 
                    $logdetails= date("F j, Y, g:i a") . ': ' . '<a href=http://dnsstuff.com/tools/city.ch?ip='.$_SERVER['REMOTE_ADDR'].' target=_blank>'.$_SERVER['REMOTE_ADDR'].'</a>'; 
                    $fp = fopen($logfile, "r+"); 
                    fwrite($fp, $logdetails, strlen($logdetails)); 
                    fclose($fp); 
                    
                                header('Location:http://go-to-hell.com'); 
                    }}}} 
                    }
                    Place this under include("core.php");

                    Code:
                    check_injection();
                    Still get a error ??

                    This means your not doing it right.

                    Other words go back and learn php coding......
                    Visit: Chat4u.mobi - The New Lay Of being a site of your dreams!
                    Visit: WapMasterz Coming Back Soon!
                    _______
                    SCRIPTS FOR SALE BY SUBZERO
                    Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders.
                    FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others...
                    _______
                    Info & Tips
                    php.net
                    w3schools.com

                    Comment


                      #11
                      Originally posted by rukiya View Post
                      $search=array("\\","\0","\n","\r","\x1a","'",'"'); <--- last array value needs double quoted thats ,""");
                      Hello rukiya sir
                      Thanks for correcting it, but it kinda works fine for me somehow, I haven't succeeded in injecting anything tho in the script where am using it. but then again the database is not compromised as there is no db connection at all.
                      tinyurl.com/earnbymobile
                      Easy earning for Indians
                      ---------------------
                      Alternative mobile advertising network .. Minimum 100 USD pay / NET15 pay cycle, Good Brand, Best targeting for Android
                      goo.gl/6vub3

                      Comment


                        #12
                        Originally posted by morse View Post
                        Hello rukiya sir
                        Thanks for correcting it, but it kinda works fine for me somehow, I haven't succeeded in injecting anything tho in the script where am using it. but then again the database is not compromised as there is no db connection at all.
                        That function was taken from PHP: mysql_real_escape_string - Manual

                        mysql_real_escape_string should be used in a mysql_query else use addslashes, strip_tags

                        Comment


                          #13
                          Originally posted by rukiya View Post
                          That function was taken from PHP: mysql_real_escape_string - Manual
                          mysql_real_escape_string should be used in a mysql_query else use addslashes, strip_tags
                          how about usage like this?
                          PHP Code:
                          $something mysql_real_escape_string(strip_tags(htmlspecialchars($_POST['something']))); 
                          would this be any good ?
                          It's better to keep your mouth shut and give the impression that you're stupid, than to open it and remove all doubt.
                          ⓣⓗⓔ ⓠⓤⓘⓔⓣⓔⓡ ⓨⓞⓤ ⓑⓔ©ⓞⓜⓔ, ⓣⓗⓔ ⓜⓞⓡⓔ ⓨⓞⓤ ⓐⓡⓔ ⓐⓑⓛⓔ ⓣⓞ ⓗⓔⓐⓡ !
                          ιη тнєσяу, тнє ρяα¢тι¢є ιѕ α яєѕυℓт σƒ тнє тнєσяу, вυт ιη ρяα¢тι¢є ιѕ тнє σρρσѕιтє.
                          キノgんイノ刀g 4 ア乇ムc乇 ノ丂 レノズ乇 キucズノ刀g 4 √ノ尺gノ刀ノイリ!

                          Comment


                            #14
                            Originally posted by metulj View Post
                            how about usage like this?
                            PHP Code:
                            $something mysql_real_escape_string(strip_tags(htmlspecialchars($_POST['something']))); 
                            would this be any good ?
                            unless its on a mysql_query it causes errors but only causes silent warning so nearly everyone on here doesnt seem to worry about it.. however this could slow your script down

                            eg: try it on a script with no connection to database and see what happens lol

                            Comment

                            Working...
                            X