Home > Software design >  strip all scheme parts in a URL in php
strip all scheme parts in a URL in php

Time:09-10

I want to fix this vulnerability, where the URL part of a PHP redirect is given by the query-string like

https://test.dev/test.php?return_page=contact.php

which will redirect to the other site contact.php.

An attacker could use this like:

https://test.dev/test.php?return_page=http://attack.hack

My idea is to strip double slashes in the function so the resulting redirect will be internal again and probably faulty:

$_GET['url']=str_replace("//","",$_GET['url']);

But maybe there is a better way to solve this with regex?

CodePudding user response:

Just clean the URL of all possible scheme parts with

$url=preg_replace('/^([a-z0-9] :\/\/ ) /i','',$_GET['url']);
header('Location: ' . $url)

CodePudding user response:

Have whitelist of allowed return-page parameters. If one is given which is it not allowed throw a 404 or forward to index.

$whitelist = ['contact.php', 'about.php'];

$returnPage = $_GET['return_page'] ?? '';

if (in_array($returnPage, $whitelist)) {
    header("Location: $returnPage");
    exit;
}

http_response_code(404)
exit;
  • Related