File: grlearn.c

package info (click to toggle)
gradm2 3.1~201709030627-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 852 kB
  • sloc: ansic: 10,798; lex: 1,248; yacc: 1,212; makefile: 1,178; sh: 15; cs: 9
file content (396 lines) | stat: -rw-r--r-- 8,712 bytes parent folder | download | duplicates (4)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/*
 * Copyright (C) 2002-2014 Bradley Spengler, Open Source Security, Inc.
 *        http://www.grsecurity.net spender@grsecurity.net
 *
 * This file is part of gradm.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "gradm.h"
#include <signal.h>

static struct always_reduce_entry {
	char *str;
	unsigned int len;
} *always_reduce_paths;

#define LEARN_BUFFER_SIZE (512 * 1024)
#define MAX_ENTRY_SIZE 16384
#define NUM_CACHE_ENTRIES 640

static char *writebuf;
static char *writep;
static int fd2 = -1;

extern FILE *grlearn_configin;
extern int grlearn2_configparse(void);

static void parse_learn2_config(void)
{
        grlearn_configin = fopen(GR_LEARN_CONFIG_PATH, "r");
        if (grlearn_configin == NULL) {
                fprintf(stdout, "Unable to open %s: %s\n", GR_LEARN_CONFIG_PATH, strerror(errno));
                exit(EXIT_FAILURE);
        }
        grlearn2_configparse();
	fclose(grlearn_configin);
        return;
}

void add_always_reduce(char *str)
{
        unsigned int size = 0;
        if (always_reduce_paths == NULL)
                always_reduce_paths = calloc(2, sizeof(struct always_reduce_entry));
        if (always_reduce_paths == NULL)
		exit(EXIT_FAILURE);
        while (always_reduce_paths[size].str)
                size++;

	always_reduce_paths = realloc(always_reduce_paths, (size + 2) * sizeof(struct always_reduce_entry));
        if (always_reduce_paths == NULL)
		exit(EXIT_FAILURE);
	memset(always_reduce_paths + size, 0, 2 * sizeof(struct always_reduce_entry));
	always_reduce_paths[size].str = str;
	always_reduce_paths[size].len = strlen(str);

	return;
}

/* handle flushing of buffer when grlearn is stopped */
void term_handler(int sig)
{
	int ignore_ret;

	signal(sig, SIG_IGN);
	if (fd2 >= 0)
		ignore_ret = write(fd2, writebuf, writep - writebuf);
	exit(0);
}

int stop_daemon(void)
{
	int fd;
	int ignore_ret;
	pid_t learn_pid;

	fd = open(GR_LEARN_PID_PATH, O_RDONLY);

	if (fd < 0)
		exit(EXIT_FAILURE);

	ignore_ret = read(fd, &learn_pid, sizeof(learn_pid));

	/* send SIGTERM, will be handled */
	kill(learn_pid, 15);

	close(fd);

	unlink(GR_LEARN_PID_PATH);

	return 0;
}

int write_pid_log(pid_t pid)
{
	struct stat fstat;
	int fd;
	pid_t learn_pid;
	char pathname[PATH_MAX] = {0};
	char procname[64] = {0};
	int ignore_ret;
	char *grlearn_path;

	if (bikeshedding_detected())
		grlearn_path = get_bikeshedded_path(GRLEARN_PATH);
	else
		grlearn_path = GRLEARN_PATH;

	if (!stat(GR_LEARN_PID_PATH, &fstat)) {
		fd = open(GR_LEARN_PID_PATH, O_RDONLY);

		if (fd < 0) {
			fprintf(stdout, "Unable to open %s:\n"
				"%s\n", GR_LEARN_PID_PATH, strerror(errno));
			kill(pid, 9);
			exit(EXIT_FAILURE);
		}

		ignore_ret = read(fd, &learn_pid, sizeof(learn_pid));
		close(fd);
		unlink(GR_LEARN_PID_PATH);

		snprintf(procname, sizeof(procname) - 1, "/proc/%d/exe", learn_pid);
		if (readlink(procname, pathname, PATH_MAX - 1) < 0)
			goto start;
		if (strcmp(pathname, grlearn_path))
			goto start;
		fprintf(stdout, "Learning daemon possibly running already...killing process.\n");

		kill(learn_pid, 15);
	}
start:
	fd = open(GR_LEARN_PID_PATH, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);

	if (fd < 0) {
		fprintf(stdout, "Unable to open %s:\n"
			"%s\n", GR_LEARN_PID_PATH, strerror(errno));
		kill(pid, 9);
		exit(EXIT_FAILURE);
	}

	ignore_ret = write(fd, &pid, sizeof(pid));

	close(fd);

	return 0;
}

struct cache_entry {
	char *entryname;
	unsigned long used;
	unsigned long checked;
	unsigned int len;
	unsigned char taken;
} *cache[NUM_CACHE_ENTRIES];
static unsigned long check_count = 0;

/* maintain a cache of most recently used items */
int check_cache(char *str, unsigned int len)
{
	int i;
	check_count++;
	for (i = 0; i < NUM_CACHE_ENTRIES; i++) {
		if (cache[i]->taken && cache[i]->len == len &&
		    !strcmp(cache[i]->entryname, str)) {
			cache[i]->used++;
			return 1;
		}
	}

	return 0;
}

void insert_into_cache(char *str, unsigned int len)
{
	int i;
	struct cache_entry *least;
	int start = random() % (NUM_CACHE_ENTRIES - 1);

	least = cache[start];

	for (i = start + 1; i != start; i = (i + 1) % NUM_CACHE_ENTRIES) {
		if (!cache[i]->taken) {
			cache[i]->taken = 1;
			least = cache[i];
			break;
		}
		if (cache[i]->used < least->used && (cache[i]->checked + (NUM_CACHE_ENTRIES * 2)) < check_count)
			least = cache[i];
	}

	strcpy(least->entryname, str);
	least->used = 0;
	least->len = len;
	least->checked = check_count;

	return;
}

char * rewrite_learn_entry(char *p)
{
	int i;
	char *tmp = p;
	char *endobj;
	char *next;
	unsigned int len;
	struct always_reduce_entry *arep;

	for (i = 0; i < 8; i++) {
		tmp = strchr(tmp, '\t');
		if (!tmp)
			return p;
		tmp++;
	}
	/* now we have a pointer to the object name */
	endobj = strchr(tmp, '\t');
	if (!endobj)
		return p;
	*endobj = '\0';
	/* now we have separated the string */

	if (!strncmp(tmp, "/proc/", 6) && (*(tmp + 6) >= '1') &&
	    (*(tmp + 6) <= '9')) {
		*endobj = '\t';
		next = endobj;
		while (*next++);
		len = next - endobj;
		memmove(tmp + 5, endobj, len);
		return next;
	}

	if (always_reduce_paths) {
		arep = always_reduce_paths;
		while (arep && arep->str) {
			if (!strncmp(tmp, arep->str, arep->len) &&
			    (*(tmp + arep->len) == '/')) {
				*endobj = '\t';
				next = endobj;
				while (*next++);
				len = next - endobj;
				memmove(tmp + arep->len, endobj, len);
				return next;
			}
			arep++;
		}
	}

	*endobj = '\t';
	return p;
}

int main(int argc, char *argv[])
{
	char *buf;
	char *next;
	char *p;
	ssize_t retval;
	struct pollfd fds;
	int fd;
	pid_t pid;
	struct sched_param schedulerparam;
	unsigned int len;
	int i;
	int ignore_ret;

	if (argc != 2)
		return 1;

	if (!strcmp(argv[1], "-stop"))
		return stop_daemon();

	signal(SIGTERM, term_handler);

	parse_learn2_config();

	/* perform various operations to make us act in near real-time */

	srandom(getpid());

	mlockall(MCL_CURRENT | MCL_FUTURE);

	buf = calloc(1, LEARN_BUFFER_SIZE);
	if (!buf)
		return 1;
	writebuf = calloc(1, 4 * MAX_ENTRY_SIZE);
	if (!writebuf)
		return 1;
	writep = writebuf;
	for(i = 0; i < NUM_CACHE_ENTRIES; i++) {
		cache[i] = calloc(1, sizeof(struct cache_entry));
		if (!cache[i])
			return 1;
		cache[i]->entryname = calloc(1, MAX_ENTRY_SIZE);
		if (!cache[i]->entryname)
			return 1;
	}

	setpriority(PRIO_PROCESS, 0, -20);
	ignore_ret = nice(-19);
	schedulerparam.sched_priority = sched_get_priority_max(SCHED_FIFO);
	sched_setscheduler(0, SCHED_FIFO, &schedulerparam);

	fd = open(GRDEV_PATH, O_RDONLY);

	if (fd < 0) {
		fprintf(stdout, "Error opening %s:\n"
			"%s\n", GRDEV_PATH, strerror(errno));
		exit(EXIT_FAILURE);
	}

	fd2 = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);

	if (fd2 < 0) {
		fprintf(stdout, "Error opening %s\n"
			"%s\n", argv[1], strerror(errno));
		exit(EXIT_FAILURE);
	}

	fcntl(fd, F_SETFD, FD_CLOEXEC);
	fcntl(fd2, F_SETFD, FD_CLOEXEC);

	pid = fork();

	if (pid > 0) {
		exit(EXIT_SUCCESS);
	} else if (!pid) {
		char b = 0;
		int pipefd;

		write_pid_log(getpid());
		pipefd = open(GR_LEARN_PIPE_PATH, O_WRONLY);
		if (pipefd >= 0) {
			ignore_ret = write(pipefd, &b, 1);
			close(pipefd);
		}
		close(0);
		close(1);
		close(2);
	} else {
		char b = 0;
		int pipefd;
		pipefd = open(GR_LEARN_PIPE_PATH, O_WRONLY);
		if (pipefd >= 0) {
			ignore_ret = write(pipefd, &b, 1);
			close(pipefd);
		}
		fprintf(stdout, "Unable to fork.\n");
		exit(EXIT_FAILURE);
	}

	fds.fd = fd;
	fds.events = POLLIN;

	while (poll(&fds, 1, -1) > 0) {
		retval = read(fd, buf, LEARN_BUFFER_SIZE - 1);
		if (retval > 0) {
			p = buf;
			while (p < (buf + retval)) {
				next = rewrite_learn_entry(p);
				len = strlen(p);
				if (!check_cache(p, len)) {
					insert_into_cache(p, len);
					if (((4 * MAX_ENTRY_SIZE) - (writep - writebuf)) > len) {
						memcpy(writep, p, len);
						writep += len;
					} else {
						ignore_ret = write(fd2, writebuf, writep - writebuf);
						memset(writebuf, 0, 4 * MAX_ENTRY_SIZE);
						writep = writebuf;
					}
				}
				if (next == p)
					p += len + 1;
				else
					p = next;
			}
		}
	}

	close(fd);
	close(fd2);

	return 0;
}