From 67c9b30cf8b0957e5178bc7c0ce38f3ae7eefb1b Mon Sep 17 00:00:00 2001 From: Catena cyber <35799796+catenacyber@users.noreply.github.com> Date: Thu, 19 Mar 2020 17:32:38 +0100 Subject: [PATCH] [binutils] Use mkstemp in binutils fuzz target (#3508) * Use mkstemp in binutils fuzz target * Adding License * Remove file and do not abort --- projects/binutils/fuzz_bfd.c | 49 +++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/projects/binutils/fuzz_bfd.c b/projects/binutils/fuzz_bfd.c index 0afe728c0..e42799c41 100644 --- a/projects/binutils/fuzz_bfd.c +++ b/projects/binutils/fuzz_bfd.c @@ -1,28 +1,37 @@ +/* Copyright 2020 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + #include "sysdep.h" #include "bfd.h" #include #include +#include - -static int bufferToFile(const char * name, const uint8_t *Data, size_t Size) { - FILE * fd; - if (remove(name) != 0) { - if (errno != ENOENT) { - printf("failed remove, errno=%d\n", errno); - return -1; - } - } - fd = fopen(name, "wb"); - if (fd == NULL) { - printf("failed open, errno=%d\n", errno); +static int bufferToFile(char * name, const uint8_t *Data, size_t Size) { + int fd = mkstemp(name); + if (fd < 0) { + printf("failed mkstemp, errno=%d\n", errno); return -2; } - if (fwrite (Data, 1, Size, fd) != Size) { - fclose(fd); + if (write (fd, Data, Size) != Size) { + printf("failed write, errno=%d\n", errno); + close(fd); return -3; } - fclose(fd); + close(fd); return 0; } @@ -31,6 +40,7 @@ static int initialized = 0; char *target = NULL; int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { + char tmpfilename[32]; if (initialized == 0) { if (bfd_init () != BFD_INIT_MAGIC) { abort(); @@ -38,17 +48,20 @@ int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { initialized = 1; } - if (bufferToFile("/tmp/fuzz.bfd", Data, Size) < 0) { - abort(); + strncpy(tmpfilename, "/tmp/fuzz.bfd-XXXXXX", 31); + if (bufferToFile(tmpfilename, Data, Size) < 0) { + return 0; } - bfd *file = bfd_openr ("/tmp/fuzz.bfd", target); + bfd *file = bfd_openr (tmpfilename, target); if (file == NULL) { + remove(tmpfilename); return 0; } bfd_check_format (file, bfd_archive); //TODO loop over subfiles and more processing bfd_close (file); + remove(tmpfilename); return 0; }