Chapter 6. Files and Commands
This chapter discusses the risks associated with the use of files and shell commands. PHP has a rich collection of filesystem functions, as well as a few different options for issuing shell commands. In this chapter, I highlight the most common mistakes that developers tend to make regarding the use of these features.
In general, the risks associated with these features resemble many of the risks already covered in this book—using tainted data can have disastrous side effects. Although the vulnerabilities themselves are unique, the practices that you can use to protect your applications are practices that you have already learned.
Traversing the Filesystem
Whenever you use a file in any way, you must indicate the filename at some point. In many cases, the filename is given as an argument to fopen()
, and other functions use the handle that it returns:
<?php $handle = fopen('/path/to/myfile.txt', 'r'); ?>
A vulnerability exists when you use tainted data as part of the filename:
<?php $handle = fopen("/path/to/{$_GET['filename']}.txt", 'r'); ?>
Because the leading and trailing parts of the full path and filename cannot be manipulated by an attacker in this example, the exploit possibilities are somewhat limited. However, keep in mind that some attacks use a NULL
(%00
when passed in the query string) to terminate a string, avoiding any filename extension limitations. In this case, the most dangerous exploit is one in which the attacker traverses the filesystem ...
Get Essential PHP Security now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.