From 6d882f6ed5dc28598d18e58005684fa14323cbdf Mon Sep 17 00:00:00 2001 From: Olaf Bergmann Date: Fri, 2 Dec 2016 13:43:45 +0100 Subject: [PATCH] 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. --- examples/client.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/examples/client.c b/examples/client.c index 102de938..c5457a7a 100644 --- a/examples/client.c +++ b/examples/client.c @@ -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; } }