Path: blob/main/contrib/libfido2/fuzz/preload-fuzz.c
39586 views
/*1* Copyright (c) 2019 Yubico AB. All rights reserved.2* Use of this source code is governed by a BSD-style3* license that can be found in the LICENSE file.4* SPDX-License-Identifier: BSD-2-Clause5*/67/*8* cc -fPIC -D_GNU_SOURCE -shared -o preload-fuzz.so preload-fuzz.c9* LD_PRELOAD=$(realpath preload-fuzz.so)10*/1112#include <sys/types.h>13#include <sys/stat.h>1415#include <dlfcn.h>16#include <err.h>17#include <errno.h>18#include <fcntl.h>19#include <limits.h>20#include <stdarg.h>21#include <stdio.h>22#include <stdlib.h>23#include <string.h>24#include <unistd.h>2526#define FUZZ_DEV_PREFIX "nodev"2728static int fd_fuzz = -1;29static int (*open_f)(const char *, int, mode_t);30static int (*close_f)(int);31static ssize_t (*write_f)(int, const void *, size_t);3233int34open(const char *path, int flags, ...)35{36va_list ap;37mode_t mode;3839va_start(ap, flags);40mode = va_arg(ap, mode_t);41va_end(ap);4243if (open_f == NULL) {44open_f = dlsym(RTLD_NEXT, "open");45if (open_f == NULL) {46warnx("%s: dlsym", __func__);47errno = EACCES;48return (-1);49}50}5152if (strncmp(path, FUZZ_DEV_PREFIX, strlen(FUZZ_DEV_PREFIX)) != 0)53return (open_f(path, flags, mode));5455if (fd_fuzz != -1) {56warnx("%s: fd_fuzz != -1", __func__);57errno = EACCES;58return (-1);59}6061if ((fd_fuzz = dup(STDIN_FILENO)) < 0) {62warn("%s: dup", __func__);63errno = EACCES;64return (-1);65}6667return (fd_fuzz);68}6970int71close(int fd)72{73if (close_f == NULL) {74close_f = dlsym(RTLD_NEXT, "close");75if (close_f == NULL) {76warnx("%s: dlsym", __func__);77errno = EACCES;78return (-1);79}80}8182if (fd == fd_fuzz)83fd_fuzz = -1;8485return (close_f(fd));86}8788ssize_t89write(int fd, const void *buf, size_t nbytes)90{91if (write_f == NULL) {92write_f = dlsym(RTLD_NEXT, "write");93if (write_f == NULL) {94warnx("%s: dlsym", __func__);95errno = EBADF;96return (-1);97}98}99100if (fd != fd_fuzz)101return (write_f(fd, buf, nbytes));102103return (nbytes);104}105106107