21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

not be allocated, the function will call abort( ) to terminate the program<br />

immediately. Otherwise, it will then build the new environment and replace the old<br />

environ pointer with a pointer to the newly allocated one. Note that the memory is<br />

allocated in one chunk rather than in smaller pieces for the individual strings. While<br />

this is not strictly necessary (and it does not provide any specific security benefit), it’s<br />

faster and places less strain on memory allocation. Note, however, that you should<br />

be performing this operation early in your program, so heap fragmentation shouldn’t<br />

be much of an issue.<br />

#include <br />

#include <br />

#include <br />

#include <br />

extern char **environ;<br />

/* These arrays are both NULL-terminated. */<br />

static char *spc_restricted_environ[ ] = {<br />

"IFS= \t\n",<br />

"PATH=" _PATH_STDPATH,<br />

0<br />

};<br />

static char *spc_preserve_environ[ ] = {<br />

"TZ",<br />

0<br />

};<br />

void spc_sanitize_environment(int preservec, char **preservev) {<br />

int i;<br />

char **new_environ, *ptr, *value, *var;<br />

size_t arr_size = 1, arr_ptr = 0, len, new_size = 0;<br />

for (i = 0; (var = spc_restricted_environ[i]) != 0; i++) {<br />

new_size += strlen(var) + 1;<br />

arr_size++;<br />

}<br />

for (i = 0; (var = spc_preserve_environ[i]) != 0; i++) {<br />

if (!(value = getenv(var))) continue;<br />

new_size += strlen(var) + strlen(value) + 2; /* include the '=' */<br />

arr_size++;<br />

}<br />

if (preservec && preservev) {<br />

for (i = 0; i < preservec && (var = preservev[i]) != 0; i++) {<br />

if (!(value = getenv(var))) continue;<br />

new_size += strlen(var) + strlen(value) + 2; /* include the '=' */<br />

arr_size++;<br />

}<br />

}<br />

new_size += (arr_size * sizeof(char *));<br />

if (!(new_environ = (char **)malloc(new_size))) abort( );<br />

new_environ[arr_size - 1] = 0;<br />

6 | Chapter 1: Safe Initialization<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!