So, Where's the Security Hole?
The example shown uses the include
feature the way it is intended to be used. It's very usefulin fact, it's an absolute necessity when building Web sites of more than two or three pages. However its behavior can lead to problems. Look at the following code, which is almost identical to Listing 1
, but has an additional line at the top.
$out = $in + 1;
|Figure 2. Include Files Execute Code!: Note the "Hello World" in page.php's response using the altered include file, proving that code outside of function blocks executes in include files.|
Save the preceding version as inc.php
, and then go back and run page.php
again. You will see that not only did the include
file get included, but all code that was outside of a function block was executed
, resulting in "Hello World" appearing on the page (see Figure 2
The point to remember here is that when you include an external file using the include
keyword, PHP actually executes that file. By itself, this is more of a feature than it is a problem, but when used in conjunction with one more feature of the language in a common programming pattern, you'll see the problem appear.
Possible Include File Locations
You can instruct PHP to include files from locations other than those relative to the current file path. The preceding example used the code:
Although that example references a file stored in the same directory as the executing script, many Web sites sensibly use an include
directory to store common files, so you'd probably write something like
However, PHP has an option called URL_fopen_wrappers
, which allows you to open remote files via a URL. If this option is enabled (and it is
enabled by default) a script such as the following is perfectly valid.
Therefore an evil script such as that at (for example) http://evilservername/evilscript.php
could conceivably be included and executed on your Web server. Remember how you saw earlier that code in a script would execute upon being included? The evil script doesn't need to have functions, it could contain a block of code that could write itself to your machine, rewrite some of your files, plunder your data, or do anything that you can imagine, because once included, it runs on your machine with the same permissions available to your PHP engine.