538Part IIIAdvanced Features and (Web design) TechniquesPHP has several program
538Part IIIAdvanced Features and TechniquesPHP has several program execution functions: system(), exec(), popen(), passthru(), andthe back-tick (`) operator. As an example of the use of one of these functions, the followingpage returns the Unix fingerinformation for a visitor specified through an HTML form:
Results for
The program, as given, takes a user name from the HTML form and executes the Unix programfingerto look up information about that user. You should hear Don t trust the networkrepeat- ing loudly in your head. Unix commands are separated by a semicolon, so anything followinga semicolon in the string passed to system()is treated as a new command. This new commandis executed with all the permissions of the user under which the Web server is running. Under Unix, the command rm-rf / will delete all files on the server. Imagine the damage ifan ill-intentioned visitor typed ;rm-rf / into the form and clicked Please. The best solution to this problem is to filter out everything but valid user names beforeinvoking finger. This requires specific knowledge about user name formats on your server, so we do not present an example here. PHP presents a solution that is almost as good. Thefunction escapeshellcmd()will sanitize a string for use in a program execution command, rendering harmless any special characters such as the semicolon. We replace the line invok- ing system()in the preceding code snippet with:
Magically, no value the visitor may enter can result in arbitrary programs being executed. This does not, however, prevent the visitor from providing unexpected input to finger. Although fingerdoes no harm if given incorrect input, other programs may not be so forgiv- ing. If in doubt, err on the side of caution! To minimize the damageof a compromise of this sort, most modern Web servers run as adummy user (often called nobodyon Unix systems). This user has only the permissionsrequired to run the Web server (and any PHP scripts) and read and write the necessary files. But remember, any databases or files that your scripts can modify are modifiable by this user, and thus they are vulnerable if an attacker can run arbitrary programs. Viruses and other e-crittersVisitors trust software coming from a trusted site. If your site allows visitors to download filesuploaded by other visitors, you should warn your visitors to check files for viruses before run- ning them, and you should consider periodically scanning the files on your server for virusesas well. This is a hard problem to solve, particularly with the possibility of embedding viruses33