2

After scanning through our code using Acunetix for vunerabilities, we had an issue with the following script which said:

"An HTTP request was initiated for the domain hit0yPI7kOCzl.bxss.me which indicates that this script is vulnerable to SSRF (Server Side Request Forgery)."

How can I prevent this?

<?php
$filename = strip_tags($_GET['url']);

if (substr($filename,0,4) !== 'http') {
    die("Need a valid URL...");
}

$ext = pathinfo($filename, PATHINFO_EXTENSION);


switch ($ext) {
    case "gif":
        header('Content-Type: image/gif');
        readfile($filename);
        break;
    case "png":
        header('Content-Type: image/png');
        readfile($filename);
        break;
    case "jpg":
    default:
        header('Content-Type: image/jpeg');
        readfile($filename);
        break;
}
?>
chris
  • 585
  • 1
  • 7
  • 25

1 Answers1

3

Source if issue in your case is that with your server will try to fetch data from any passed url. Given it has http://google.com inside url parameter, script will respond with actual google website contents.

Why its bad? That, for example, could be exploited to circumvent your firewall settings, access internal network of your server or pollute socket connections so your server will be unable to connect or be connected to and will become unresponsive.

First of all you should think if you really want to serve your static files with PHP. Most likely this responsibility could be delegated to web server. Its even possible to "serve" static from 3rd party website with current webservers, so you should seriously consider getting rid of that code.

If you 100% sure you want to use with PHP in that case, you should add restrictions to your code.

  1. add domain whitelist, so that will allow usage of trusted domain list only inside url variable;
  2. do not process files with unknown extensions.

In that case code will look like this:

<?php

$whitelist = [
    'some.whitelisted.com',
    'other.whitelisted.com'
];

$extensionMap = [
    'gif'  => 'image/gif',
    'png'  => 'image/png',
    'jpg'  => 'image/jpeg',
    'jpeg' => 'image/jpeg'
];

$filename = strip_tags($_GET['url']);

$host = parse_url($filename, PHP_URL_HOST);

if(empty($host) || !in_array($host, $whitelist)) {
    header('HTTP/1.1 404 Not Found');
    exit;
}

$ext = pathinfo($filename, PATHINFO_EXTENSION);

if(!isset($extensionMap[$ext])) {
    header('HTTP/1.1 404 Not Found');
    exit;
}

header(sprintf('Content-Type: %s', $extensionMap[$ext]));
readfile($filename);
Evgeny Soynov
  • 694
  • 3
  • 13