joequery
12/11/2012 - 8:37 PM

Safely using getenv with snprintf in C

Safely using getenv with snprintf in C

#include <stdlib.h>
#include <stdio.h>
#define BUFSIZE 80

int main(){
    char *cwd1;
    char cwd2[BUFSIZE];
    int result;

    // Get the current working directory. This is vulnerable to buffer
    // overflows!
    cwd1 = getenv("PWD");
    printf("cwd1: %s\n", cwd1);

    // We use snprintf to prevent buffer overflows. According to the man pages,
    // if the return value of snprintf is >= BUFSIZE, the string was truncated,
    // indicating the buffer was not big enough. Resize BUFSIZE to something
    // extremely small to watch this in action.
    result = snprintf(cwd2, BUFSIZE, "%s", getenv("PWD"));
    if(result >= BUFSIZE){
        fprintf(stderr, "BUFSIZE of %d was too small. Aborting\n", BUFSIZE);
        exit(1);
    }

    printf("cwd2: %s\n", cwd2);
    return 0;
}