Search code examples
regexpreg-replacestrpos

What is wrong with check_referrer function that i use for CSFR/XSFR protection?


i have his code in php file and i want to know how that code work. can you please explain this to me by an example (all code)?

if (strpos(preg_replace('/^.+:\/\/(www\.)?/','',$_SERVER['HTTP_REFERER']).'/',preg_replace('/^.+:\/\/(www\.)?/','',$my_base_url))!==0)

what is the meaning of

'/^.+:\/\/(www\.)?/'

in 1st () ?

the all fuction code :

function check_referrer($post_url=false){
    global $my_base_url, $my_website_base, $xsfr_first_page, $_GET, $_POST;

    if (sizeof($_GET)>0 || sizeof($_POST)>0)
    {

        if ($_SERVER['HTTP_REFERER'])
        {
            $base = $my_website_base;

            if (!$base) $base = '/';
            $_SERVER['HTTP_REFERER'] = sanitize($_SERVER['HTTP_REFERER'],3);

            // update checks if HTTP_REFERER and posted url are the same!
            if(strpos(urldecode($_SERVER['HTTP_REFERER']),$post_url)!==false) return true;


            //if (strpos(preg_replace('/^.+:\/\/(www\.)?/','',$_SERVER['HTTP_REFERER']).'/',preg_replace('/^.+:\/\/(www\.)?/','',$my_base_url).$base)!==0)
            if (strpos(preg_replace('/^.+:\/\/(www\.)?/','',$_SERVER['HTTP_REFERER']).'/',preg_replace('/^.+:\/\/(www\.)?/','',$my_base_url))!==0)
            {
                unset($_SESSION['xsfr']);
                $wrongurlrefforme=urldecode($_SERVER['HTTP_REFERER']);
                die("");
            }
        }
        elseif ($xsfr_first_page)
        {
            unset($_SESSION['xsfr']);
            die("");
        }
    }
}

Solution

  • '/^.+:\/\/(www\.)?/' is a regular expression.

    It means:

     /^        "Starting from the beginning of the string..."
      .+        "... match any string that has at least one character"
      :\/\/     "... followed by a colon followed by two foward slashes"
      (www\.)?/ "... and if there is 'www.' after those, call that "group one""
    

    So ...

    preg_replace('/^.+:\/\/(www\.)?/','',$_SERVER['HTTP_REFERER'])

    means

    "look in the 'HTTP_REFERER' element of the $_SERVER array, and see if it matches the description above. If it does, replace the 'www.' part of it with nothing."

    Whatever the result of that is, becomes the first argument to strpos().

    The second argument to strpos() is constructed similarly.

    Then strpos() tells you where the second string is found in the first. Thus the if statement is asking if the output of strpos() is the same value and type as zero.

    A safer comparison would be !=, because you don't care about the types.