Anti-MySQL Injection function

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

  • something else
    replied
    yeah put them in core well you can put them on other places but better off in core so they are available on every page

    Leave a comment:


  • rayjee
    replied
    Originally posted by riderz View Post
    SQL Injection is security failure of the most hacked sites...

    Here is Anti-MySQL Injection function:

    Code:
    function anti_injection($sql) {
       // removes words that contain sql syntax
       $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$sql);
       $sql = trim($sql); // strip whitespace
       $sql = strip_tags($sql); // strip HTML and PHP tags
       $sql = addslashes($sql); // quote string with slashes
       return $sql;
    }
    How to call the function:
    Code:
    <?php
    $query = anti_injection($query);
    ?>
    ... or when you "post" the data:
    Code:
    <?php
    $query = anti_injection($_POST['something']);
    ?>
    or another one i found

    if the topic was [HOW TO] Anti-SQL Injection Function I might have said that it did not depend on any given db, and there is a use for that, especially if you have SQL compliant functions for flat file, that said lets see what we can do to produce an anti-injection function the allows posting of (legal) SQL code in posts, and works irrelevant of SQL interface..

    .. after a bit of research I have the following, which covers all eventualities
    Code:
    <?php
    
    function anti_injection($sql,$debug=false) {
      if($sql=='') return;
    
      $single = false;   # do single quotes translation
      $double = false;   # do double quotes translation
    
    //  $sql = trim($sql); # strip whitespace *(what if the first line is space indented? ie ascii art)
    //  if (get_magic_quotes_gpc()) $sql = stripslashes($sql); # if you have problems with slashes
      $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters
    
      if(substr_count($sql,"'")==0) $single = false; else $single = true;
      if(substr_count($sql,'"')==0) $double = false; else $double = true;
    
      if($single) $sql = str_replace("'", '& #039;', $sql);  # for single quote characters
      if($double) $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters
    
      return $sql;
    }
    
    
    ?>
    the echo's are just for testing (eg: $safe_sql = anti_injection($data_to_be_sanitized,true);) , as these may be set differently on your PHP installation (not 110mb)

    (NOTE: when copying either of these PHP quoted code functions, change "& #039;" to read "&#039;" - minus space, its a quirk of the PHP code hiliter, it outputs "&#039;" as "&#038;#039;")

    that said, for pure speed I would use the following (less the comments)
    Code:
    <?php
    function anti_injection($sql) {
      $sql = htmlspecialchars($sql); # for < and >, &, single and double quote characters
      $sql = str_replace("'", '& #039;', $sql);  # for single quote characters (just in case)
      $sql = str_replace('"', '&quote;', $sql); # for dpuble quote characters (just in case)
    
      return $sql;
    }
    ?>
    or as antimatter might prefer
    Code:
    function sql_ai($sql){return str_replace('"','&quote;',str_replace("'", '&#039;',htmlspecialchars($sql)));}
    wer i guna put dis code? In the core?

    Leave a comment:


  • subzero
    replied
    i updated mine try that one and see if anyone can add there self owners lol

    Leave a comment:


  • marduck
    replied
    try it

    function anti_sql_injection( $input ) {
    // daftarkan perintah-perintah SQL yang tidak boleh ada
    // dalam query dimana SQL Injection mungkin dilakukan
    $aforbidden = array (
    "insert", "select", "update", "delete", "truncate",
    "replace", "drop", "or", ";", "#", "–", "=" );

    // lakukan cek, input tidak mengandung perintah yang tidak boleh
    $breturn=true;
    foreach($aforbidden as $cforbidden) {
    if(strripos($input, $cforbidden)) {
    $breturn=false;
    break;
    }
    }
    return $breturn;
    }

    Leave a comment:


  • something else
    replied
    Originally posted by BioBeo View Post
    Man.. No Need to Update each and every single POST or GET method

    All you can do this and Prevent Injecting via .htcaccess there you can add the queary string as :


    union|select|insert|cast|set|declare|drop|update|m d5|benchmark
    PHP Code:
    if(isset($_REQUEST)){foreach($_REQUEST as $key=>$value){$_REQUEST[$key]=mysql_real_escape_string(htmlspecialchars($value));}} 
    
    Last edited by something else; 14.08.10, 12:17.

    Leave a comment:


  • BioBeo
    replied
    Man.. No Need to Update each and every single POST or GET method

    All you can do this and Prevent Injecting via .htcaccess there you can add the queary string as :


    union|select|insert|cast|set|declare|drop|update|m d5|benchmark

    Leave a comment:


  • Anshul
    replied
    here is one bt need some editing :P

    PHP Code:
    function minimum_version($vercheck) {
        $minver = (int)str_replace('.', '', $vercheck);
        $curver = (int)str_replace('.', '', phpversion());
        if($curver >= $minver)
            return true;
        return false;
    }
    
    function getvar($var) {
        global $HTTP_GET_VARS;
        global $HTTP_POST_VARS;
        $val = "";
        if (minimum_version('4.1.0')) { // when global variables changed
            if (in_array($var,array_keys($_GET))) {
                $val = $_GET[$var];
            } else if (in_array($var,array_keys($_POST))) {
                $val = $_POST[$var];
            }
        } else {
            if (in_array($var,array_keys($HTTP_GET_VARS))) {
                $val = $HTTP_GET_VARS[$var];
            } else if (in_array($var,array_keys($HTTP_POST_VARS))) {
                $val = $HTTP_POST_VARS[$var];
            }
        }
    
        remove_magic_quotes($val);
        return $val;
    }
    
    /*
     * This function removes slashes that may have been automatically
     * inserted by PHP if one of magic_quotes_* is On.
     *
     * Code by gordon at kanazawa dot ac dot jp as posted on php.net.
     * http://www.php.net/manual/en/function.get-magic-quotes-gpc.php
     */
    function remove_magic_quotes(&$x) {
        if (is_array($x)) {
            while (list($key,$value) = each($x)) {
                if ($value) remove_magic_quotes($x[$key]);
            }
        }else if (ini_get('magic_quotes_sybase')) {
            $x = preg_replace("/''/", "'", $x);
        } else if (get_magic_quotes_runtime()) {
            $x = preg_replace("/\\\"/", '"', $x);
        } else if (get_magic_quotes_gpc()) {
            $x = stripslashes($x);
        }
    } 
    
    $album_id = getvar("album_id");

    Leave a comment:


  • something else
    replied
    try:
    PHP Code:
    function unject($string){
    return mysql_real_escape_string(preg_replace("/(--)|(>)|(<)|(&)/","",$string));
     } 
    

    Leave a comment:


  • nclemale36
    replied
    ave just changed eregi to preg and got errors

    Leave a comment:


  • subzero
    replied
    Updated

    Code:
    //////////////////////// Anti Sql hit...
    function check_injection() 
      { 
        $badchars = array("DROP","TRUNCATE", "SELECT", "UPDATE", "DELETE" , "UNION", "WHERE", "FROM","INSERT","ORDER BY","'","perm","',","validated","',perm='4',validated='1'#"); 
       
        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'); 
    }}}} 
    }
    echo check_injection() or check_injection();

    or this check_injection();

    Leave a comment:


  • ozziemale31
    replied
    yep thats right

    Added after 6 minutes:

    a good read is this link below
    SQL Injection Prevention Cheat Sheet - OWASP

    Last edited by ozziemale31; 13.08.10, 16:10.

    Leave a comment:


  • something else
    replied
    yep but i would recommend using preg_replace instead of eregi_replace as its been deprecated since php 5.3.0

    Leave a comment:


  • nclemale36
    replied
    u can name the function anything u want ? am i right for example
    Code:
    [COLOR=#000000][COLOR=#007700]function [/COLOR][COLOR=#0000BB]cantinjecthere[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]) 
    {
     [/COLOR][COLOR=#0000BB]$badWords [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#DD0000]"(--)|(>)|(<)|(&)"[/COLOR][COLOR=#007700];
     [/COLOR][COLOR=#0000BB]$string [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]eregi_replace[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$badWords[/COLOR][COLOR=#007700], [/COLOR][COLOR=#DD0000]""[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]);
    
     [/COLOR][COLOR=#0000BB]$string [/COLOR][COLOR=#007700]= [/COLOR][COLOR=#0000BB]mysql_real_escape_string[/COLOR][COLOR=#007700]([/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700]); 
    
    return [/COLOR][COLOR=#0000BB]$string[/COLOR][COLOR=#007700];
     }[/COLOR][/COLOR]
    
    usage eg 
    [COLOR=#000000][COLOR=#0000BB]$action [/COLOR][COLOR=#007700]= cantinjecthere[/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][/COLOR][COLOR=#000000][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#0000BB][/COLOR][COLOR=#007700][/COLOR][COLOR=#DD0000][/COLOR][COLOR=#007700][/COLOR][/COLOR][COLOR=#000000][COLOR=#007700]([/COLOR][COLOR=#0000BB]$_GET[/COLOR][COLOR=#007700][[/COLOR][COLOR=#DD0000]"action"[/COLOR][COLOR=#007700]]);[/COLOR][/COLOR]
    am i right ?

    Leave a comment:


  • ozziemale31
    replied
    or a good way is how im doing my new script that means u have to re edit all the posts and gets
    PHP Code:
    
    function cleanQuery($string) 
    {
     $badWords = "(--)|(>)|(<)|(&)";
     $string = eregi_replace($badWords, "", $string);
    
     $string = mysql_real_escape_string($string); 
    
    return $string;
     }
    
    
    example:
    for the gets
    
    
    getbrip($sid);
    $action = cleanQuery($_GET["action"]);
    $sid = cleanQuery($_GET["sid"]);
    $page = cleanQuery($_GET["page"]);
    $who = cleanQuery($_GET["who"]);
    $uid = getuid_sid($sid);
    
    or for post
    
    $staftxt = cleanQuery($_POST["staftxt"]); 
    
    Last edited by ozziemale31; 13.08.10, 14:51.

    Leave a comment:


  • khan
    replied
    Originally posted by wap-lord View Post
    Does this protect you site for the injector.
    It will give you max security from Injection.

    PHP Code:
    $str = mysql_real_escape_string($str); 
    

    Leave a comment:

Working...
X