client.c: fix TOCTOU for file input

The function cmdline_input_from_file() allocates a chunk of memory
to hold the contents of the given file. As libcoap does not offer
an interface to realloc(), we have to determine the required buffer
size before starting to read from the file, leading to a classical
TOCTOU condition.

This change mitigates the defect by first opening the file and then
calling fstat(). Note that the subsequent fread() call takes the
size of the pre-allocated buffer into account.
This commit is contained in:
Olaf Bergmann committed 2016-12-02 13:43:45 +01:00
1 parent 53183e63b2
commit 6d882f6ed5
1 file changed
+10 -8
+10 -8
View File
@@ -955,20 +955,22 @@ cmdline_input_from_file(char *filename, str *buf) {
inputfile = stdin;
} else {
/* read from specified input file */
if (stat(filename, &statbuf) < 0) {
inputfile = fopen(filename, "r");
if ( !inputfile ) {
perror("cmdline_input_from_file: fopen");
return 0;
}
if (fstat(fileno(inputfile), &statbuf) < 0) {
perror("cmdline_input_from_file: stat");
fclose(inputfile);
return 0;
}
buf->length = statbuf.st_size;
buf->s = (unsigned char *)coap_malloc(buf->length);
if (!buf->s)
return 0;
inputfile = fopen(filename, "r");
if ( !inputfile ) {
perror("cmdline_input_from_file: fopen");
coap_free(buf->s);
if (!buf->s) {
fclose(inputfile);
return 0;
}
}