xref: /linux/security/tomoyo/audit.c (revision 87d03777eb5dff5ea03802933e9045e64ebf004d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * security/tomoyo/audit.c
4  *
5  * Copyright (C) 2005-2011  NTT DATA CORPORATION
6  */
7 
8 #include "common.h"
9 #include <linux/slab.h>
10 
11 /**
12  * tomoyo_print_bprm - Print "struct linux_binprm" for auditing.
13  *
14  * @bprm: Pointer to "struct linux_binprm".
15  * @dump: Pointer to "struct tomoyo_page_dump".
16  *
17  * Returns the contents of @bprm on success, NULL otherwise.
18  *
19  * This function uses kzalloc(), so caller must kfree() if this function
20  * didn't return NULL.
21  */
tomoyo_print_bprm(struct linux_binprm * bprm,struct tomoyo_page_dump * dump)22 static char *tomoyo_print_bprm(struct linux_binprm *bprm,
23 			       struct tomoyo_page_dump *dump)
24 {
25 	static const int tomoyo_buffer_len = 4096 * 2;
26 	char *buffer = kzalloc(tomoyo_buffer_len, GFP_NOFS);
27 	char *cp;
28 	char *last_start;
29 	int len;
30 	unsigned long pos = bprm->p;
31 	int offset = pos % PAGE_SIZE;
32 	int argv_count = bprm->argc;
33 	int envp_count = bprm->envc;
34 	bool truncated = false;
35 
36 	if (!buffer)
37 		return NULL;
38 	len = snprintf(buffer, tomoyo_buffer_len - 1, "argv[]={ ");
39 	cp = buffer + len;
40 	if (!argv_count) {
41 		memmove(cp, "} envp[]={ ", 11);
42 		cp += 11;
43 	}
44 	last_start = cp;
45 	while (argv_count || envp_count) {
46 		if (!tomoyo_dump_page(bprm, pos, dump))
47 			goto out;
48 		pos += PAGE_SIZE - offset;
49 		/* Read. */
50 		while (offset < PAGE_SIZE) {
51 			const char *kaddr = dump->data;
52 			const unsigned char c = kaddr[offset++];
53 
54 			if (cp == last_start)
55 				*cp++ = '"';
56 			if (cp >= buffer + tomoyo_buffer_len - 32) {
57 				/* Reserve some room for "..." string. */
58 				truncated = true;
59 			} else if (c == '\\') {
60 				*cp++ = '\\';
61 				*cp++ = '\\';
62 			} else if (c > ' ' && c < 127) {
63 				*cp++ = c;
64 			} else if (!c) {
65 				*cp++ = '"';
66 				*cp++ = ' ';
67 				last_start = cp;
68 			} else {
69 				*cp++ = '\\';
70 				*cp++ = (c >> 6) + '0';
71 				*cp++ = ((c >> 3) & 7) + '0';
72 				*cp++ = (c & 7) + '0';
73 			}
74 			if (c)
75 				continue;
76 			if (argv_count) {
77 				if (--argv_count == 0) {
78 					if (truncated) {
79 						cp = last_start;
80 						memmove(cp, "... ", 4);
81 						cp += 4;
82 					}
83 					memmove(cp, "} envp[]={ ", 11);
84 					cp += 11;
85 					last_start = cp;
86 					truncated = false;
87 				}
88 			} else if (envp_count) {
89 				if (--envp_count == 0) {
90 					if (truncated) {
91 						cp = last_start;
92 						memmove(cp, "... ", 4);
93 						cp += 4;
94 					}
95 				}
96 			}
97 			if (!argv_count && !envp_count)
98 				break;
99 		}
100 		offset = 0;
101 	}
102 	*cp++ = '}';
103 	*cp = '\0';
104 	return buffer;
105 out:
106 	snprintf(buffer, tomoyo_buffer_len - 1,
107 		 "argv[]={ ... } envp[]= { ... }");
108 	return buffer;
109 }
110 
111 /**
112  * tomoyo_filetype - Get string representation of file type.
113  *
114  * @mode: Mode value for stat().
115  *
116  * Returns file type string.
117  */
tomoyo_filetype(const umode_t mode)118 static inline const char *tomoyo_filetype(const umode_t mode)
119 {
120 	switch (mode & S_IFMT) {
121 	case S_IFREG:
122 	case 0:
123 		return tomoyo_condition_keyword[TOMOYO_TYPE_IS_FILE];
124 	case S_IFDIR:
125 		return tomoyo_condition_keyword[TOMOYO_TYPE_IS_DIRECTORY];
126 	case S_IFLNK:
127 		return tomoyo_condition_keyword[TOMOYO_TYPE_IS_SYMLINK];
128 	case S_IFIFO:
129 		return tomoyo_condition_keyword[TOMOYO_TYPE_IS_FIFO];
130 	case S_IFSOCK:
131 		return tomoyo_condition_keyword[TOMOYO_TYPE_IS_SOCKET];
132 	case S_IFBLK:
133 		return tomoyo_condition_keyword[TOMOYO_TYPE_IS_BLOCK_DEV];
134 	case S_IFCHR:
135 		return tomoyo_condition_keyword[TOMOYO_TYPE_IS_CHAR_DEV];
136 	}
137 	return "unknown"; /* This should not happen. */
138 }
139 
140 /**
141  * tomoyo_print_header - Get header line of audit log.
142  *
143  * @r: Pointer to "struct tomoyo_request_info".
144  *
145  * Returns string representation.
146  *
147  * This function uses kmalloc(), so caller must kfree() if this function
148  * didn't return NULL.
149  */
tomoyo_print_header(struct tomoyo_request_info * r)150 static char *tomoyo_print_header(struct tomoyo_request_info *r)
151 {
152 	struct tomoyo_time stamp;
153 	const pid_t gpid = task_pid_nr(current);
154 	struct tomoyo_obj_info *obj = r->obj;
155 	static const int tomoyo_buffer_len = 4096;
156 	char *buffer = kmalloc(tomoyo_buffer_len, GFP_NOFS);
157 	int pos;
158 	u8 i;
159 
160 	if (!buffer)
161 		return NULL;
162 
163 	tomoyo_convert_time(ktime_get_real_seconds(), &stamp);
164 
165 	pos = snprintf(buffer, tomoyo_buffer_len - 1,
166 		       "#%04u/%02u/%02u %02u:%02u:%02u# profile=%u mode=%s granted=%s (global-pid=%u) task={ pid=%u ppid=%u uid=%u gid=%u euid=%u egid=%u suid=%u sgid=%u fsuid=%u fsgid=%u }",
167 		       stamp.year, stamp.month, stamp.day, stamp.hour,
168 		       stamp.min, stamp.sec, r->profile, tomoyo_mode[r->mode],
169 		       str_yes_no(r->granted), gpid, tomoyo_sys_getpid(),
170 		       tomoyo_sys_getppid(),
171 		       from_kuid(&init_user_ns, current_uid()),
172 		       from_kgid(&init_user_ns, current_gid()),
173 		       from_kuid(&init_user_ns, current_euid()),
174 		       from_kgid(&init_user_ns, current_egid()),
175 		       from_kuid(&init_user_ns, current_suid()),
176 		       from_kgid(&init_user_ns, current_sgid()),
177 		       from_kuid(&init_user_ns, current_fsuid()),
178 		       from_kgid(&init_user_ns, current_fsgid()));
179 	if (!obj)
180 		goto no_obj_info;
181 	if (!obj->validate_done) {
182 		tomoyo_get_attributes(obj);
183 		obj->validate_done = true;
184 	}
185 	for (i = 0; i < TOMOYO_MAX_PATH_STAT; i++) {
186 		struct tomoyo_mini_stat *stat;
187 		unsigned int dev;
188 		umode_t mode;
189 
190 		if (!obj->stat_valid[i])
191 			continue;
192 		stat = &obj->stat[i];
193 		dev = stat->dev;
194 		mode = stat->mode;
195 		if (i & 1) {
196 			pos += snprintf(buffer + pos,
197 					tomoyo_buffer_len - 1 - pos,
198 					" path%u.parent={ uid=%u gid=%u ino=%llu perm=0%o }",
199 					(i >> 1) + 1,
200 					from_kuid(&init_user_ns, stat->uid),
201 					from_kgid(&init_user_ns, stat->gid),
202 					stat->ino, stat->mode & S_IALLUGO);
203 			continue;
204 		}
205 		pos += snprintf(buffer + pos, tomoyo_buffer_len - 1 - pos,
206 				" path%u={ uid=%u gid=%u ino=%llu major=%u minor=%u perm=0%o type=%s",
207 				(i >> 1) + 1,
208 				from_kuid(&init_user_ns, stat->uid),
209 				from_kgid(&init_user_ns, stat->gid),
210 				stat->ino, MAJOR(dev), MINOR(dev),
211 				mode & S_IALLUGO, tomoyo_filetype(mode));
212 		if (S_ISCHR(mode) || S_ISBLK(mode)) {
213 			dev = stat->rdev;
214 			pos += snprintf(buffer + pos,
215 					tomoyo_buffer_len - 1 - pos,
216 					" dev_major=%u dev_minor=%u",
217 					MAJOR(dev), MINOR(dev));
218 		}
219 		pos += snprintf(buffer + pos, tomoyo_buffer_len - 1 - pos,
220 				" }");
221 	}
222 no_obj_info:
223 	if (pos < tomoyo_buffer_len - 1)
224 		return buffer;
225 	kfree(buffer);
226 	return NULL;
227 }
228 
229 /**
230  * tomoyo_init_log - Allocate buffer for audit logs.
231  *
232  * @r:    Pointer to "struct tomoyo_request_info".
233  * @len:  Buffer size needed for @fmt and @args.
234  * @fmt:  The printf()'s format string.
235  * @args: va_list structure for @fmt.
236  *
237  * Returns pointer to allocated memory.
238  *
239  * This function uses kzalloc(), so caller must kfree() if this function
240  * didn't return NULL.
241  */
tomoyo_init_log(struct tomoyo_request_info * r,int len,const char * fmt,va_list args)242 char *tomoyo_init_log(struct tomoyo_request_info *r, int len, const char *fmt,
243 		      va_list args)
244 {
245 	char *buf = NULL;
246 	char *bprm_info = NULL;
247 	const char *header = NULL;
248 	char *realpath = NULL;
249 	const char *symlink = NULL;
250 	int pos;
251 	const char *domainname = r->domain->domainname->name;
252 
253 	header = tomoyo_print_header(r);
254 	if (!header)
255 		return NULL;
256 	/* +10 is for '\n' etc. and '\0'. */
257 	len += strlen(domainname) + strlen(header) + 10;
258 	if (r->ee) {
259 		struct file *file = r->ee->bprm->file;
260 
261 		realpath = tomoyo_realpath_from_path(&file->f_path);
262 		bprm_info = tomoyo_print_bprm(r->ee->bprm, &r->ee->dump);
263 		if (!realpath || !bprm_info)
264 			goto out;
265 		/* +80 is for " exec={ realpath=\"%s\" argc=%d envc=%d %s }" */
266 		len += strlen(realpath) + 80 + strlen(bprm_info);
267 	} else if (r->obj && r->obj->symlink_target) {
268 		symlink = r->obj->symlink_target->name;
269 		/* +18 is for " symlink.target=\"%s\"" */
270 		len += 18 + strlen(symlink);
271 	}
272 	len = kmalloc_size_roundup(len);
273 	buf = kzalloc(len, GFP_NOFS);
274 	if (!buf)
275 		goto out;
276 	len--;
277 	pos = snprintf(buf, len, "%s", header);
278 	if (realpath) {
279 		struct linux_binprm *bprm = r->ee->bprm;
280 
281 		pos += snprintf(buf + pos, len - pos,
282 				" exec={ realpath=\"%s\" argc=%d envc=%d %s }",
283 				realpath, bprm->argc, bprm->envc, bprm_info);
284 	} else if (symlink)
285 		pos += snprintf(buf + pos, len - pos, " symlink.target=\"%s\"",
286 				symlink);
287 	pos += snprintf(buf + pos, len - pos, "\n%s\n", domainname);
288 	vsnprintf(buf + pos, len - pos, fmt, args);
289 out:
290 	kfree(realpath);
291 	kfree(bprm_info);
292 	kfree(header);
293 	return buf;
294 }
295 
296 /* Wait queue for /sys/kernel/security/tomoyo/audit. */
297 static DECLARE_WAIT_QUEUE_HEAD(tomoyo_log_wait);
298 
299 /* Structure for audit log. */
300 struct tomoyo_log {
301 	struct list_head list;
302 	char *log;
303 	int size;
304 };
305 
306 /* The list for "struct tomoyo_log". */
307 static LIST_HEAD(tomoyo_log);
308 
309 /* Lock for "struct list_head tomoyo_log". */
310 static DEFINE_SPINLOCK(tomoyo_log_lock);
311 
312 /* Length of "struct list_head tomoyo_log". */
313 static unsigned int tomoyo_log_count;
314 
315 /**
316  * tomoyo_get_audit - Get audit mode.
317  *
318  * @ns:          Pointer to "struct tomoyo_policy_namespace".
319  * @profile:     Profile number.
320  * @index:       Index number of functionality.
321  * @matched_acl: Pointer to "struct tomoyo_acl_info".
322  * @is_granted:  True if granted log, false otherwise.
323  *
324  * Returns true if this request should be audited, false otherwise.
325  */
tomoyo_get_audit(const struct tomoyo_policy_namespace * ns,const u8 profile,const u8 index,const struct tomoyo_acl_info * matched_acl,const bool is_granted)326 static bool tomoyo_get_audit(const struct tomoyo_policy_namespace *ns,
327 			     const u8 profile, const u8 index,
328 			     const struct tomoyo_acl_info *matched_acl,
329 			     const bool is_granted)
330 {
331 	u8 mode;
332 	const u8 category = tomoyo_index2category[index] +
333 		TOMOYO_MAX_MAC_INDEX;
334 	struct tomoyo_profile *p;
335 
336 	if (!tomoyo_policy_loaded)
337 		return false;
338 	p = tomoyo_profile(ns, profile);
339 	if (tomoyo_log_count >= p->pref[TOMOYO_PREF_MAX_AUDIT_LOG])
340 		return false;
341 	if (is_granted && matched_acl && matched_acl->cond &&
342 	    matched_acl->cond->grant_log != TOMOYO_GRANTLOG_AUTO)
343 		return matched_acl->cond->grant_log == TOMOYO_GRANTLOG_YES;
344 	mode = p->config[index];
345 	if (mode == TOMOYO_CONFIG_USE_DEFAULT)
346 		mode = p->config[category];
347 	if (mode == TOMOYO_CONFIG_USE_DEFAULT)
348 		mode = p->default_config;
349 	if (is_granted)
350 		return mode & TOMOYO_CONFIG_WANT_GRANT_LOG;
351 	return mode & TOMOYO_CONFIG_WANT_REJECT_LOG;
352 }
353 
354 /**
355  * tomoyo_write_log2 - Write an audit log.
356  *
357  * @r:    Pointer to "struct tomoyo_request_info".
358  * @len:  Buffer size needed for @fmt and @args.
359  * @fmt:  The printf()'s format string.
360  * @args: va_list structure for @fmt.
361  *
362  * Returns nothing.
363  */
tomoyo_write_log2(struct tomoyo_request_info * r,int len,const char * fmt,va_list args)364 void tomoyo_write_log2(struct tomoyo_request_info *r, int len, const char *fmt,
365 		       va_list args)
366 {
367 	char *buf;
368 	struct tomoyo_log *entry;
369 	bool quota_exceeded = false;
370 
371 	if (!tomoyo_get_audit(r->domain->ns, r->profile, r->type,
372 			      r->matched_acl, r->granted))
373 		goto out;
374 	buf = tomoyo_init_log(r, len, fmt, args);
375 	if (!buf)
376 		goto out;
377 	entry = kzalloc_obj(*entry, GFP_NOFS);
378 	if (!entry) {
379 		kfree(buf);
380 		goto out;
381 	}
382 	entry->log = buf;
383 	len = kmalloc_size_roundup(strlen(buf) + 1);
384 	/*
385 	 * The entry->size is used for memory quota checks.
386 	 * Don't go beyond strlen(entry->log).
387 	 */
388 	entry->size = len + kmalloc_size_roundup(sizeof(*entry));
389 	spin_lock(&tomoyo_log_lock);
390 	if (tomoyo_memory_quota[TOMOYO_MEMORY_AUDIT] &&
391 	    tomoyo_memory_used[TOMOYO_MEMORY_AUDIT] + entry->size >=
392 	    tomoyo_memory_quota[TOMOYO_MEMORY_AUDIT]) {
393 		quota_exceeded = true;
394 	} else {
395 		tomoyo_memory_used[TOMOYO_MEMORY_AUDIT] += entry->size;
396 		list_add_tail(&entry->list, &tomoyo_log);
397 		tomoyo_log_count++;
398 	}
399 	spin_unlock(&tomoyo_log_lock);
400 	if (quota_exceeded) {
401 		kfree(buf);
402 		kfree(entry);
403 		goto out;
404 	}
405 	wake_up(&tomoyo_log_wait);
406 out:
407 	return;
408 }
409 
410 /**
411  * tomoyo_write_log - Write an audit log.
412  *
413  * @r:   Pointer to "struct tomoyo_request_info".
414  * @fmt: The printf()'s format string, followed by parameters.
415  *
416  * Returns nothing.
417  */
tomoyo_write_log(struct tomoyo_request_info * r,const char * fmt,...)418 void tomoyo_write_log(struct tomoyo_request_info *r, const char *fmt, ...)
419 {
420 	va_list args;
421 	int len;
422 
423 	va_start(args, fmt);
424 	len = vsnprintf(NULL, 0, fmt, args) + 1;
425 	va_end(args);
426 	va_start(args, fmt);
427 	tomoyo_write_log2(r, len, fmt, args);
428 	va_end(args);
429 }
430 
431 /**
432  * tomoyo_read_log - Read an audit log.
433  *
434  * @head: Pointer to "struct tomoyo_io_buffer".
435  *
436  * Returns nothing.
437  */
tomoyo_read_log(struct tomoyo_io_buffer * head)438 void tomoyo_read_log(struct tomoyo_io_buffer *head)
439 {
440 	struct tomoyo_log *ptr = NULL;
441 
442 	if (head->r.w_pos)
443 		return;
444 	kfree(head->read_buf);
445 	head->read_buf = NULL;
446 	spin_lock(&tomoyo_log_lock);
447 	if (!list_empty(&tomoyo_log)) {
448 		ptr = list_entry(tomoyo_log.next, typeof(*ptr), list);
449 		list_del(&ptr->list);
450 		tomoyo_log_count--;
451 		tomoyo_memory_used[TOMOYO_MEMORY_AUDIT] -= ptr->size;
452 	}
453 	spin_unlock(&tomoyo_log_lock);
454 	if (ptr) {
455 		head->read_buf = ptr->log;
456 		head->r.w[head->r.w_pos++] = head->read_buf;
457 		kfree(ptr);
458 	}
459 }
460 
461 /**
462  * tomoyo_poll_log - Wait for an audit log.
463  *
464  * @file: Pointer to "struct file".
465  * @wait: Pointer to "poll_table". Maybe NULL.
466  *
467  * Returns EPOLLIN | EPOLLRDNORM when ready to read an audit log.
468  */
tomoyo_poll_log(struct file * file,poll_table * wait)469 __poll_t tomoyo_poll_log(struct file *file, poll_table *wait)
470 {
471 	if (tomoyo_log_count)
472 		return EPOLLIN | EPOLLRDNORM;
473 	poll_wait(file, &tomoyo_log_wait, wait);
474 	if (tomoyo_log_count)
475 		return EPOLLIN | EPOLLRDNORM;
476 	return 0;
477 }
478