Tainted string in C

Abhi V picture Abhi V · Feb 11, 2014 · Viewed 12.6k times · Source

I'm running Coverity tool in my file operation function and getting the following error.

As you can see below, I'm using an snprintf() before passing this variable in question to the line number shown in the error message. I guess that some sanitization of the string has to be done as a part of that snprintf(). But still the warning is shown.

Error:TAINTED_STRING (TAINTED string "fn" was passed to a tainted string sink content.) [coverity]

char fn[100]; int id = 0;
char* id_str = getenv("ID");
if (id_str) {
    id = atoi(id_str);
}
memset(fn, '\0', sizeof(fn));
snprintf(fn, 100, LOG_FILE, id);
if(fn[100-1] != '\0') {
     fn[100-1] = '\0';
}
log_fp = fopen (fn, "a");

Any help would be highly appreciated.

Answer

manuell picture manuell · Feb 11, 2014

Try the following:

char* id_str = getenv("ID");
if (id_str) {
   id_str = strdup(id_str);
   id = atoi(id_str);
   free( id_str );
}

The fn string passed to fopen is tainted by an environment variable. Using strdup may act as "sanitizing".