הוסטס - פורום אחסון האתרים הגדול בישראל

הוסטס - פורום אחסון האתרים הגדול בישראל (https://hosts.co.il/forums/index.php)
-   פורום תיכנות (https://hosts.co.il/forums/forumdisplay.php?f=14)
-   -   פונקציית אבטחה נגד הזרקות PHP (https://hosts.co.il/forums/showthread.php?t=69628)

dudu 21-11-08 11:02

פונקציית אבטחה נגד הזרקות PHP
 
שלום חבר'ה,
אני רוצה להציג מס פונקציות שגיבשתי למניעת הזרקות.
אשמח לדעת אם יש עוד פונקציות לאבטח את המידע המתקבל מידי הגולש.

PHP קוד:

function String($string){
        
$string mysql_real_escape_string($string);
        
$string htmlspecialchars($string); 
        
$string trim($string); 
        return 
$string;
    } 


תודה על תשומת הלב!|קורץ|

ibmod 21-11-08 11:09

חסימת מילים מסויימות.

dabi 21-11-08 11:16

אשמח להסבר בבקשה
htmlspecialchars אני משתמש תמיד שאני מקבל מידע ממשתמש דרך ולפיו שולף מהמסד או שאני מקבל מידע מטופס ומכניס למסד-זה מנטל הזרקות XSS וכל מיני סקריפטים שאנשים ינסו להחדיר לי

אשמח להסבר מה הפונקציה mysql_real_escape_string עושה ומתי משתמש בה
ומה הפונקציה trim עושה ומתי משתמשים בה
תודה רבה

vadimg88 21-11-08 11:32

הנה חלק מהדברים שאני משתמש יש כאן כמעט הכל, XSS, SQL INJ, ניקוי טקסט רגיל, אבטחת GET POST COOKIE REQUEST , בדיקת אימייל, ניקיון טקסט עם פסיקים, בדיקה לקוד לא חוקי כמו EXEC , פונקציות להמרה מ NL ל BR וההפך, מציאת דפדפן המשתמש ומערכת ההפעלה שלו, ועוד...

PHP קוד:

<?php

    
/**
    * Checks for executable code
    *
    * @param    string    Input String
    * @return    boolean 
    * @since    2.2.0
    */

    
function hax_check_for_executable_code$text='' )
    {
        
//-----------------------------------------
        // Test
        //-----------------------------------------

        
if ( preg_match"#include|require|include_once|require_once|exec|system|passthru|`#si"$text ) )
        {
            return 
TRUE;
        }

        return 
FALSE;
    }

    
/**
    * Check a URL to make sure it's not all hacky
    *
    * @param    string    Input String
    * @return    boolean 
    * @since    2.1.0
    */

    
function xss_check_url$url )
    {
        
$url trimurldecode$url ) );

        if ( ! 
preg_match"#^https?://(?:[^<>*\"]+|[a-z0-9/\._\- !]+)$#iU"$url ) )
        {
            return 
FALSE;
        }

        return 
TRUE;
    }

    function 
xss_html_clean$html )
    {
        
//-----------------------------------------
        // Opening script tags...
        // Check for spaces and new lines...
        //-----------------------------------------

        
$html preg_replace"#<(\s+?)?s(\s+?)?c(\s+?)?r(\s+?)?i(\s+?)?p(\s+?)?t#is"        "&lt;script" $html );
        
$html preg_replace"#<(\s+?)?/(\s+?)?s(\s+?)?c(\s+?)?r(\s+?)?i(\s+?)?p(\s+?)?t#is""&lt;/script"$html );

        
//-----------------------------------------
        // Basics...
        //-----------------------------------------

        
$html preg_replace"/javascript/i" "javascript"$html );
        
$html preg_replace"/alert/i"      "alert"          $html );
        
$html preg_replace"/behavior/i"   "behavior"          $html );
        
$html preg_replace"/e((\/\*.*?\*\/)*)x((\/\*.*?\*\/)*)p((\/\*.*?\*\/)*)r((\/\*.*?\*\/)*)e((\/\*.*?\*\/)*)s((\/\*.*?\*\/)*)s((\/\*.*?\*\/)*)i((\/\*.*?\*\/)*)o((\/\*.*?\*\/)*)n/i" "exp​ression"     $html );
        
$html preg_replace"/e((\\\|\)*)x((\\\|\)*)p((\\\|\)*)r((\\\|\)*)e((\\\|\)*)s((\\\|\)*)s((\\\|\)*)i((\\\|\)*)o((\\\|\)*)n/i"       "exp​ression"           $html );
        
$html preg_replace"/m((\\\|\)*)o((\\\|\)*)z((\\\|\)*)\-((\\\|\)*)b((\\\|\)*)i((\\\|\)*)n((\\\|\)*)d((\\\|\)*)i((\\\|\)*)n((\\\|\)*)g/i"       "moz-​binding"           $html );
        
$html preg_replace"/about:/i"     "about:"         $html );
        
$html preg_replace"/<body/i"      "&lt;body"            $html );
        
$html preg_replace"/<html/i"      "&lt;html"            $html );
        
$html preg_replace"/document\./i" "document."      $html );
        
$html preg_replace"/window\./i"   "window."      $html );

        
$event_handlers    = array( 'mouseover''mouseout''mouseup''mousemove''mousedown''mouseenter''mouseleave''mousewheel',
        
'contextmenu''click''dblclick''load''unload''submit''blur''focus''resize''scroll',
        
'change''reset''select''selectionchange''selectstart''start''stop''keydown''keyup',
        
'keypress''abort''error''dragdrop''move''moveend''movestart''activate''afterprint',
        
'afterupdate''beforeactivate''beforecopy''beforecut''beforedeactivate''beforeeditfocus',
        
'beforepaste''beforeprint''beforeunload''begin''bounce''cellchange''controlselect',
        
'copy''cut''paste''dataavailable''datasetchanged''datasetcomplete''deactivate''drag',
        
'dragend''dragleave''dragenter''dragover''drop''end''errorupdate''filterchange''finish',
        
'focusin''focusout''help''layoutcomplete''losecapture''mediacomplete''mediaerror''outofsync',
        
'pause''propertychange''progress''readystatechange''repeat''resizeend''resizestart''resume',
        
'reverse''rowsenter''rowexit''rowdelete''rowinserted''seek''syncrestored''timeerror',
        
'trackchange''urlflip',
        );

        
$html preg_replace"/on(" implode'|'$event_handlers ) . ")/i""on\\1"    $html );

        return 
$html;
    }
    
        
/**
    * <br /> Safe nl2br (Buggy on old PHP builds)
    *
    * @param    string    Input text
    * @return    string    Parsed text
    * @since    2.0
    */
    
function my_nl2br($t="")
    {
        return 
str_replace"\n""<br />"$t );
    }

    
/*-------------------------------------------------------------------------*/
    //
    // Convert <br /> to newlines
    //
    /*-------------------------------------------------------------------------*/

    /**
    * <br /> Safe br2nl
    *
    * @param    string    Input text
    * @return    string    Parsed text
    * @since    2.0
    */
    
function my_br2nl($t="")
    {
        
$t preg_replace"#(?:\n|\r)?<br />(?:\n|\r)?#""\n"$t );
        
$t preg_replace"#(?:\n|\r)?<br>(?:\n|\r)?#"  "\n"$t );

        return 
$t;
    }

    
/**
    * Clean email address
    *
    * @param    string    Email address
    * @return    mixed
    * @since    2.0
    */
    
function clean_email($email "")
    {
        
$email trim($email);

        
$email str_replace" """$email );

        
//-----------------------------------------
        // Check for more than 1 @ symbol
        //-----------------------------------------

        
if ( substr_count$email'@' ) > )
        {
            return 
FALSE;
        }

        
$email preg_replace"#[\;\#\n\r\*\'\"<>&\%\!\(\)\{\}\[\]\?\\/\s]#"""$email );

        if ( 
preg_match"/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/"$email) )
        {
            return 
$email;
        }
        else
        {
            return 
FALSE;
        }
    }
    
    
/**
    * Remove leading comma from comma delim string
    *
    * @param    string    Input String
    * @return    string    Parsed string
    */
    
function trim_leading_comma($t)
    {
        return 
preg_replace"/^,/"""$t );
    }

    
/**
    * Remove trailing comma from comma delim string
    *
    * @param    string    Input String
    * @return    string    Parsed string
    */
    
function trim_trailing_comma($t)
    {
        return 
preg_replace"/,$/"""$t );
    }

    
/**
    * Remove dupe commas from comma delim string
    *
    * @param    string    Input String
    * @return    string    Parsed string
    */
    
function clean_comma($t)
    {
        return 
preg_replace"/,{2,}/"","$t );
    }

    
/**
    * Clean perm string (wrapper for comma cleaners)
    *
    * @param    string    Input String
    * @return    string    Parsed string
    */
    
function clean_perm_string($t)
    {
        
$t $this->clean_comma($t);
        
$t $this->trim_leading_comma($t);
        
$t $this->trim_trailing_comma($t);

        return 
$t;
    }
    
        
/**
    * Fetches the user's operation system
    *
    * @return    string
    */

    
function fetch_os()
    {
        
$useragent strtolower($this->my_getenv('HTTP_USER_AGENT'));

        if ( 
strstr$useragent'mac' ) )
        {
            return 
'mac';
        }

        if ( 
preg_match'#wi(n|n32|ndows)#'$useragent ) )
        {
            return 
'windows';
        }

        return 
'unknown';
    }

    
/**
    * Fetches the user's browser from their user-agent
    *
    * @return    array [ browser, version ]
    */

    
private function fetch_browser()
    {
        
$version   0;
        
$browser   "unknown";
        
$useragent strtolower($this->my_getenv('HTTP_USER_AGENT'));

        
//-----------------------------------------
        // Opera...
        //-----------------------------------------

        
if ( strstr$useragent'opera' ) )
        {
            
preg_match"#opera[ /]([0-9\.]{1,10})#"$useragent$ver );

            return array( 
'browser' => 'opera''version' => $ver[1] );
        }

        
//-----------------------------------------
        // IE...
        //-----------------------------------------

        
if ( strstr$useragent'msie' ) )
        {
            
preg_match"#msie[ /]([0-9\.]{1,10})#"$useragent$ver );

            return array( 
'browser' => 'ie''version' => $ver[1] );
        }

        
//-----------------------------------------
        // Safari...
        //-----------------------------------------

        
if ( strstr$useragent'safari' ) )
        {
            
preg_match"#safari/([0-9.]{1,10})#"$useragent$ver );

            return array( 
'browser' => 'safari''version' => $ver[1] );
        }

        
//-----------------------------------------
        // Mozilla browsers...
        //-----------------------------------------

        
if ( strstr$useragent'gecko' ) )
        {
            
preg_match"#gecko/(\d+)#"$useragent$ver );

            return array( 
'browser' => 'gecko''version' => $ver[1] );
        }

        
//-----------------------------------------
        // Older Mozilla browsers...
        //-----------------------------------------

        
if ( strstr$useragent'mozilla' ) )
        {
            
preg_match"#^mozilla/[5-9]\.[0-9.]{1,10}.+rv:([0-9a-z.+]{1,10})#"$useragent$ver );

            return array( 
'browser' => 'mozilla''version' => $ver[1] );
        }

        
//-----------------------------------------
        // Konqueror...
        //-----------------------------------------

        
if ( strstr$useragent'konqueror' ) )
        {
            
preg_match"#konqueror/([0-9.]{1,10})#"$useragent$ver );

            return array( 
'browser' => 'konqueror''version' => $ver[1] );
        }

        
//-----------------------------------------
        // Still here?
        //-----------------------------------------

        
return array( 'browser' => $browser'version' => $version );
    }

    
/**
    * Gets user environment 
    *
    * @param string user browser
    * @return    user environment
    */

    
public function my_getenv($key)
    {
        
$return = array();

        if ( 
is_array$_SERVER ) AND count$_SERVER ) )
        {
            if( isset( 
$_SERVER[$key] ) )
            {
                
$return $_SERVER[$key];
            }
        }

        if ( ! 
$return )
        {
            
$return getenv($key);
        }

        return 
$return;
    }

    
/**
    * Clean globals to avoid to deep iteration
    *
    * @param string $data 
    * @param int $iteration
    */

    
private function clean_globals( &$data$iteration )
    {
        
// Crafty hacker could send something like &foo[][][][][][]....to kill Apache process
        // We should never have an globals array deeper than 10..

        
if( $iteration >= 10 )
        {
            return 
$data;
        }

        if( 
count$data ) )
        {
            foreach( 
$data as $k => $v )
            {
                if ( 
is_array$v ) )
                {
                    
$this->clean_globals$data$k ], $iteration+);
                }
                else
                {
                    
# Null byte characters
                    
$v preg_replace'/\\\0/' '\0'$v );
                    
$v preg_replace'/\\x00/''\x00'$v );
                    
$v str_replace'%00'     '%00'$v );

                    
# File traversal
                    
$v str_replace'../'    '../'$v );

                    
$data$k ] = $v;
                }
            }
        }
    }

    
/**
    * define_indexes
    *
    * Define empty indexes to avoid user warnings
    */

    
private function define_indexes()
    {

        if( !isset(
$this->input['area']) )
        {
            
$this->input['area'] = '';
        }

    }


    
/**
    * parse_incoming_recursively
    *
    * @param string $data 
    * @param array inputed content to be cleaned
    * @param int $iteration
    * @return    cleaned input
    */

    
private function parse_incoming_recursively( &$data$input=array(), $iteration )
    {
        
// Crafty hacker could send something like &foo[][][][][][]....to kill Apache process
        // We should never have an input array deeper than 10..

        
if( $iteration >= 10 )
        {
            return 
$input;
        }

        if( 
count$data ) )
        {
            foreach( 
$data as $k => $v )
            {
                if ( 
is_array$v ) )
                {
                    
//$input = $this->parse_incoming_recursively( $data[ $k ], $input );
                    
$input$k ] = $this->parse_incoming_recursively$data$k ], array(), $iteration+);
                }
                else
                {
                    
$k $this->parse_clean_key$k );
                    
$v $this->parse_clean_value$v );

                    
$input$k ] = $v;
                }
            }
        }

        return 
$input;
    }

    
/**
    * parse_incoming
    *
    * Cleanes all $_GET $_POST $_REQUEST $COOKIE global vars
    * 
    * @return    cleaned input
    */

    
public function parse_incoming()
    {
        
//-----------------------------------------
        // Attempt to switch off magic quotes
        //-----------------------------------------

        
@set_magic_quotes_runtime(0);

        
$this->get_magic_quotes = @get_magic_quotes_gpc();

        
//-----------------------------------------
        // Clean globals, first.
        //-----------------------------------------

        
$this->clean_globals$_GET );
        
$this->clean_globals$_POST );
        
$this->clean_globals$_COOKIE );
        
$this->clean_globals$_REQUEST );

        
# GET first
        
$input $this->parse_incoming_recursively$_GET, array() );

        
# Then overwrite with POST
        
$input $this->parse_incoming_recursively$_POST$input );

        
$this->input $input;

        
$this->define_indexes();

        
//-----------------------------------------
        // Sort out the accessing IP
        // (Thanks to Cosmos and schickb)
        //-----------------------------------------

        
$addrs = array();


        foreach( 
array_reverseexplode','$this->my_getenv('HTTP_X_FORWARDED_FOR') ) ) as $x_f )
        {
            
$x_f trim($x_f);

            if ( 
preg_match'/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/'$x_f ) )
            {
                
$addrs[] = $x_f;
            }
        }

        
$addrs[] = $this->my_getenv('HTTP_CLIENT_IP');
        
$addrs[] = $this->my_getenv('HTTP_X_CLUSTER_CLIENT_IP');
        
$addrs[] = $this->my_getenv('HTTP_PROXY_USER');


        
$addrs[] = $this->my_getenv('REMOTE_ADDR');

        
//-----------------------------------------
        // Do we have one yet?
        //-----------------------------------------

        
foreach ( $addrs as $ip )
        {
            if ( 
$ip )
            {
                
preg_match"/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/"$ip$match );

                
$this->ip_address $match[1].'.'.$match[2].'.'.$match[3].'.'.$match[4];

                if ( 
$this->ip_address AND $this->ip_address != '...' )
                {
                    break;
                }
            }
        }

        
//-----------------------------------------
        // Make sure we take a valid IP address
        //-----------------------------------------

        
if ( ( ! $this->ip_address OR $this->ip_address == '...' ) AND !$this->my_getenv('SHELL') )
        {
            print 
"Could not determine your IP address";
            exit();
        }

        
#Backwards compat:
        
$this->input["IP_ADDRESS"] = $this->ip_address;

        
//-----------------------------------------
        // Make a safe query string
        //-----------------------------------------

        
$this->query_string_safe str_replace'&amp;amp;''&amp;'$this->parse_clean_valueurldecode($this->my_getenv('QUERY_STRING')) ) );
        
$this->query_string_real str_replace'&amp;'    '&'    $this->query_string_safe );

        
//-----------------------------------------
        // Format it..
        //-----------------------------------------

        
$this->query_string_formatted str_replace$this->vars['baseurl'] . '/index.'.$this->vars['php_ext'].'?'''$this->query_string_safe );
        
$this->query_string_formatted preg_replace"#s=([a-z0-9]){32}#"''$this->query_string_formatted );

        
# Assign request method
        
$this->input['request_method'] = strtolower($this->my_getenv('REQUEST_METHOD'));

        return 
$this->input;
    }

    
/**
    * parse_clean_value
    *
    * Cleanes all value
    * 
    * @return    cleaned value
    */

    
public function parse_clean_value($val)
    {
        if ( 
$val == "" )
        {
            return 
"";
        }

        
$val str_replace" "" "$this->txt_stripslashes($val) );

        
// As cool as this entity is...

        
$val str_replace""        ''              $val );

        
$val str_replace"&"                "&amp;"         $val );
        
$val str_replace"<!--"            "<!--"  $val );
        
$val str_replace"-->"            "-->"       $val );
        
$val preg_replace"/<script/i"    "<script"   $val );
        
$val str_replace">"                "&gt;"          $val );
        
$val str_replace"<"                "&lt;"          $val );
        
$val str_replace'"'                "&quot;"        $val );
        
$val str_replace"\n"            "<br />"        $val ); // Convert literal newlines
        
$val str_replace"$"                "$"        $val );
        
$val str_replace"\r"            ""              $val ); // Remove literal carriage returns
        
$val str_replace"!"                "!"         $val );
        
$val str_replacechr(0xCA), ""$val );  //Remove sneaky spaces
        
$val str_replace"'"                "'"         $val ); // IMPORTANT: It helps to increase sql query safety.

        // Ensure unicode chars are OK

        
$val preg_replace("/&amp;#([0-9]+);/s""&#\\1;"$val );

        
//-----------------------------------------
        // Try and fix up HTML entities with missing ;
        //-----------------------------------------

        
$val preg_replace"/&#(\d+?)([^\d;])/i""&#\\1;\\2"$val );

        return 
$val;
    }

    
/**
    * txt_stripslashes
    *
    * strip slashes
    * 
    * @return    stripped value
    */

    
public function txt_stripslashes($t)
    {
        if ( 
$this->get_magic_quotes )
        {
            
$t stripslashes($t);
        }

        return 
$t;
    }

    
/**
    * parse_clean_key
    *
    * clean array key
    * 
    * @return    cleaned key
    */

    
function parse_clean_key($key)
    {
        if (
$key == "")
        {
            return 
"";
        }

        
$key htmlspecialchars(urldecode($key));
        
$key str_replace".."           ""  $key );
        
$key preg_replace"/\_\_(.+?)\_\_/"  ""  $key );
        
$key preg_replace"/^([\w\.\-\_]+)$/""$1"$key );

        return 
$key;
    }


?>


GalN 21-11-08 12:10

vadimg88,
עזרת לי מאוד! תודה רבה (:

Elad-A 21-11-08 12:37

יפה מאוד ואדים!
אחלה רשימת פונקציות!

DvirCohen 21-11-08 17:37

זה הכל פונקציות מIPB 2.3..

vadimg88 22-11-08 10:16

נכון...לא אומר שאסור להשתמש בהם.

DanStyle 22-11-08 14:07

אף אחד לא אמר להעתיק את זה, הוא נתן את זה כדי ללמוד (אני מאמין), ותודה.


כל הזמנים הם GMT +2. הזמן כעת הוא 12:57.

מופעל באמצעות VBulletin גרסה 3.8.6
כל הזכויות שמורות ©
כל הזכויות שמורות לסולל יבוא ורשתות (1997) בע"מ