summaryrefslogtreecommitdiff
path: root/fuzz/preload-fuzz.c
blob: efcb8c632605d4150d1bc1a0fbf4b2008448255b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
 * Copyright (c) 2019 Yubico AB. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

/*
 * cc -fPIC -D_GNU_SOURCE -shared -o preload-fuzz.so preload-fuzz.c
 * LD_PRELOAD=$(realpath preload-fuzz.so)
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <dlfcn.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define FUZZ_DEV_PREFIX	"nodev"

static int               fd_fuzz = -1;
static int              (*open_f)(const char *, int, mode_t);
static int              (*close_f)(int);
static ssize_t          (*write_f)(int, const void *, size_t);

int
open(const char *path, int flags, ...)
{
	va_list	ap;
	mode_t	mode;

	va_start(ap, flags);
	mode = va_arg(ap, mode_t);
	va_end(ap);

	if (open_f == NULL) {
		open_f = dlsym(RTLD_NEXT, "open");
		if (open_f == NULL) {
			warnx("%s: dlsym", __func__);
			errno = EACCES;
			return (-1);
		}
	}

	if (strncmp(path, FUZZ_DEV_PREFIX, strlen(FUZZ_DEV_PREFIX)) != 0)
		return (open_f(path, flags, mode));

	if (fd_fuzz != -1) {
		warnx("%s: fd_fuzz != -1", __func__);
		errno = EACCES;
		return (-1);
	}

	if ((fd_fuzz = dup(STDIN_FILENO)) < 0) {
		warn("%s: dup", __func__);
		errno = EACCES;
		return (-1);
	}

	return (fd_fuzz);
}

int
close(int fd)
{
	if (close_f == NULL) {
		close_f = dlsym(RTLD_NEXT, "close");
		if (close_f == NULL) {
			warnx("%s: dlsym", __func__);
			errno = EACCES;
			return (-1);
		}
	}

	if (fd == fd_fuzz)
		fd_fuzz = -1;

	return (close_f(fd));
}

ssize_t
write(int fd, const void *buf, size_t nbytes)
{
	if (write_f == NULL) {
		write_f = dlsym(RTLD_NEXT, "write");
		if (write_f == NULL) {
			warnx("%s: dlsym", __func__);
			errno = EBADF;
			return (-1);
		}
	}

	if (fd != fd_fuzz)
		return (write_f(fd, buf, nbytes));

	return (nbytes);
}