Code Injection via the PHP Data Stream Wrapper
On a recent speech over at Mayflower Munich, I was told about an interesting new way to hack PHP web Apps developers should think about: Code injection via the PHP stream wrapper.
This way of injecting your own PHP code makes use of the data stream wrapper, feature which came in PHP 5.2 and which is a feature most developers will probably yet have to learn about. It is basically a way to give PHP a string which it then interprets as a file. Thus, it may contain PHP code. Here is a modified example of the PHP manual:
Output:
This opens a whole new world of possibilities to attackers who try to inject their own PHP code into your site, even if you deny off-site inclusions with allow_url_fopen and allow_url_include set to ‘0′.
Once the attacker has found a weak point in your code, say something like
he can inject his own code. For that, he does not necessarily be able to include off-site files. One example: By taking the following string
Which is in Base64 encoding
he would be able to execute shell commands. Base64 is necessary at this point, as it bypasses the URL-enoding. So, the finished URL would look somethink like the following:
which executes the UNIX-command
The output would just be the free disk space, but as the hacker can now inject any code he like by just adding a GET parameter to his URL, which opens up a range of malicious possibilities without having to include files from a different site.
Why is that? As include() is not binary safe, the PHP interpreter takes the GET parameter ‘lang’, puts it into the include, which sees the string as a file (remember, we use the data stream wrapper basically simulating a file). After the null character (%00), PHP ignores the rest of the string. That makes the ‘.php’ at the inclusion point disappear, effectively handing over the code the attacker injected via the ‘lang’ parameter as a PHP file. In worst case scenarios, the attacker has now complete control over the system. Of course, he can execute shell commands only if PHP’s safe mode is disabled, but still, executing PHP commands gives a lot of opportunities as well.
Granted, the attack point was a bit easy in my example, as I wanted to keep it simple, but still, in standard software, security issues are found on a daily basis. If the software is not updated frequently, the attacker can take any known exploit to take over the system this way.
Again, we are left with the usual conclusions:
- Keep your software up to date
- Don’t trust any user input
- Make you php.ini as safe as possible
Comments and suggestions appreciated.
Comments (1)


Kinda funny that you misdirected your tweet to me because now I’m interested in this article as I’ve been a long time PHP developer and pay a lot of attention to PHP security stuff. I’ll have to try this out when I have a moment.