0

I am having a problem. I have this code:

$theUrl = $_GET["url"];
include("$theUrl.php");

This gets the url, for example: http://mywebsite.com/index.php?url=test

But what if someone puts in:

http://mywebsite.com/index.php?url=http://theirwebsite.com/someEvilscript

How to avoid this? I want only scripts that i have on my server to be executed and not from other websites. Thanks for help.

HoLyVieR
  • 10,985
  • 5
  • 42
  • 67
Moussa
  • 1
  • what do u mean this won't happen? – Moussa Dec 10 '10 at 19:26
  • 2
    Basically the answer is simple. Don't do things like that. Don't trust user input EVER... – ircmaxell Dec 10 '10 at 19:29
  • 1
    @ajreal: it will happen. In the very docs you posted: `if "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL`... – ircmaxell Dec 10 '10 at 19:30
  • yes, but there must be some way to solve the problem... – Moussa Dec 10 '10 at 19:30
  • `$theUrl.php = http://theirwebsite.com/someEvilscript.php` - provided your secret ending of php is identified by the Evilscript – ajreal Dec 10 '10 at 19:36
  • 4
    Basically the answer is simple. include over HTTP is a **stupidest thing ever** – Your Common Sense Dec 10 '10 at 19:38
  • You're probably doing this backwards. Put your header/footer into their own files, and include those from `test.php`, and link the user directly to `mywebsite.com/test.php` rather than 'routing' everything through index.php – user229044 Dec 10 '10 at 19:39

3 Answers3

2

One of the good way to handle this is to define a white list of file that can be included. If anything isn't in that list, it should be considered evil and never included.

For example :

<?php
$allowed = array('file1', 'file2', 'file3');

if (in_array($_GET["url"], $allowed)) {
    // You can include
} else {
   // Error message and dont include
}
?>

Note : As suggested in the comment, the allowed list can be populated dynamically by scanning allowed directory.

HoLyVieR
  • 10,985
  • 5
  • 42
  • 67
  • 1
    One option would be to scan the directory and get a list of all files first, then check to see if the requested file is in that list... That way you don't need to hard-code the links in... – ircmaxell Dec 10 '10 at 19:34
0

You really shouldn't have any code that looks like that. And I mean really. What are you trying to achieve with this? I'm sure there's another way to the same without the risks (and let's say general uglyness).

Like HoLyVieR suggests, whitelisting what can be included is the key to making your current code safe.

Juan
  • 3,433
  • 29
  • 32
0

Why don't you just create test.php on your site, and use http://mywebsite.com/test.php in the link? This way you can include your initialization script in test.php (and in the other scripts) if needed.

István Ujj-Mészáros
  • 3,228
  • 1
  • 27
  • 46