...
| Code Block | ||
|---|---|---|
| ||
#include <string.h>
/* ... */
char* search_command; /* provided by the user, looks like 'grep -e...' */
if (strlen( search_command) < strlen("xgrep")) {
/* handle too-short-command error */
}
{
/* Make sure command is actually a grep variant
* by ensuring command starts with "grep" or "*grep" */
char* location = strstr( search_command, "grep");
if (location != search_command && location != search_command+1) {
/* handle not-a-grep-command error */
}
}
{
/* Eliminate bad chars */
static char bad_chars[] = "$|&>;`";
if (strcspn(cp, bad_chars) == strlen(cp)) {
/* handle naughty-chars-in-command error */
}
}
/* Sanitize current environment, using spc_sanitize_environment
from previous compliant example */
spc_sanitize_environment(0, NULL);
if (system( search_cmmand) != 0) {
/* handle system error */
}
|
...
Note that this example specifies nothing about privileges. If run with root privileges (eg in a setuid-root context), this example would permit the user to access files readable only by root. A program with elevated privileges should drop them before executing this code.
This example actually lets the user invoke any program consisting of a single character plus grep. If the average user has access to possibly dangerous programs such as ngrep, you may wish to disallow such commands from executing.
Finally, this example indiscriminately assumes the presence of certain characters like | and $ indicates malice on the part of the user, and refuses to execute the command. While secure, this reduces the power of the command considerably (since these characters serve useful functions in egrep expressions). Ideally, the program would do some more intelligent parsing of the command to allow good uses of these characters while preventing bad uses. At the very least, the program should warn the user that those characters are forbidden.
...