xref: /openbmc/linux/security/tomoyo/common.c (revision c71bb9f8)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * security/tomoyo/common.c
4  *
5  * Copyright (C) 2005-2011  NTT DATA CORPORATION
6  */
7 
8 #include <linux/uaccess.h>
9 #include <linux/slab.h>
10 #include <linux/security.h>
11 #include "common.h"
12 
13 /* String table for operation mode. */
14 const char * const tomoyo_mode[TOMOYO_CONFIG_MAX_MODE] = {
15 	[TOMOYO_CONFIG_DISABLED]   = "disabled",
16 	[TOMOYO_CONFIG_LEARNING]   = "learning",
17 	[TOMOYO_CONFIG_PERMISSIVE] = "permissive",
18 	[TOMOYO_CONFIG_ENFORCING]  = "enforcing"
19 };
20 
21 /* String table for /sys/kernel/security/tomoyo/profile */
22 const char * const tomoyo_mac_keywords[TOMOYO_MAX_MAC_INDEX
23 				       + TOMOYO_MAX_MAC_CATEGORY_INDEX] = {
24 	/* CONFIG::file group */
25 	[TOMOYO_MAC_FILE_EXECUTE]    = "execute",
26 	[TOMOYO_MAC_FILE_OPEN]       = "open",
27 	[TOMOYO_MAC_FILE_CREATE]     = "create",
28 	[TOMOYO_MAC_FILE_UNLINK]     = "unlink",
29 	[TOMOYO_MAC_FILE_GETATTR]    = "getattr",
30 	[TOMOYO_MAC_FILE_MKDIR]      = "mkdir",
31 	[TOMOYO_MAC_FILE_RMDIR]      = "rmdir",
32 	[TOMOYO_MAC_FILE_MKFIFO]     = "mkfifo",
33 	[TOMOYO_MAC_FILE_MKSOCK]     = "mksock",
34 	[TOMOYO_MAC_FILE_TRUNCATE]   = "truncate",
35 	[TOMOYO_MAC_FILE_SYMLINK]    = "symlink",
36 	[TOMOYO_MAC_FILE_MKBLOCK]    = "mkblock",
37 	[TOMOYO_MAC_FILE_MKCHAR]     = "mkchar",
38 	[TOMOYO_MAC_FILE_LINK]       = "link",
39 	[TOMOYO_MAC_FILE_RENAME]     = "rename",
40 	[TOMOYO_MAC_FILE_CHMOD]      = "chmod",
41 	[TOMOYO_MAC_FILE_CHOWN]      = "chown",
42 	[TOMOYO_MAC_FILE_CHGRP]      = "chgrp",
43 	[TOMOYO_MAC_FILE_IOCTL]      = "ioctl",
44 	[TOMOYO_MAC_FILE_CHROOT]     = "chroot",
45 	[TOMOYO_MAC_FILE_MOUNT]      = "mount",
46 	[TOMOYO_MAC_FILE_UMOUNT]     = "unmount",
47 	[TOMOYO_MAC_FILE_PIVOT_ROOT] = "pivot_root",
48 	/* CONFIG::network group */
49 	[TOMOYO_MAC_NETWORK_INET_STREAM_BIND]       = "inet_stream_bind",
50 	[TOMOYO_MAC_NETWORK_INET_STREAM_LISTEN]     = "inet_stream_listen",
51 	[TOMOYO_MAC_NETWORK_INET_STREAM_CONNECT]    = "inet_stream_connect",
52 	[TOMOYO_MAC_NETWORK_INET_DGRAM_BIND]        = "inet_dgram_bind",
53 	[TOMOYO_MAC_NETWORK_INET_DGRAM_SEND]        = "inet_dgram_send",
54 	[TOMOYO_MAC_NETWORK_INET_RAW_BIND]          = "inet_raw_bind",
55 	[TOMOYO_MAC_NETWORK_INET_RAW_SEND]          = "inet_raw_send",
56 	[TOMOYO_MAC_NETWORK_UNIX_STREAM_BIND]       = "unix_stream_bind",
57 	[TOMOYO_MAC_NETWORK_UNIX_STREAM_LISTEN]     = "unix_stream_listen",
58 	[TOMOYO_MAC_NETWORK_UNIX_STREAM_CONNECT]    = "unix_stream_connect",
59 	[TOMOYO_MAC_NETWORK_UNIX_DGRAM_BIND]        = "unix_dgram_bind",
60 	[TOMOYO_MAC_NETWORK_UNIX_DGRAM_SEND]        = "unix_dgram_send",
61 	[TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_BIND]    = "unix_seqpacket_bind",
62 	[TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_LISTEN]  = "unix_seqpacket_listen",
63 	[TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_CONNECT] = "unix_seqpacket_connect",
64 	/* CONFIG::misc group */
65 	[TOMOYO_MAC_ENVIRON] = "env",
66 	/* CONFIG group */
67 	[TOMOYO_MAX_MAC_INDEX + TOMOYO_MAC_CATEGORY_FILE] = "file",
68 	[TOMOYO_MAX_MAC_INDEX + TOMOYO_MAC_CATEGORY_NETWORK] = "network",
69 	[TOMOYO_MAX_MAC_INDEX + TOMOYO_MAC_CATEGORY_MISC] = "misc",
70 };
71 
72 /* String table for conditions. */
73 const char * const tomoyo_condition_keyword[TOMOYO_MAX_CONDITION_KEYWORD] = {
74 	[TOMOYO_TASK_UID]             = "task.uid",
75 	[TOMOYO_TASK_EUID]            = "task.euid",
76 	[TOMOYO_TASK_SUID]            = "task.suid",
77 	[TOMOYO_TASK_FSUID]           = "task.fsuid",
78 	[TOMOYO_TASK_GID]             = "task.gid",
79 	[TOMOYO_TASK_EGID]            = "task.egid",
80 	[TOMOYO_TASK_SGID]            = "task.sgid",
81 	[TOMOYO_TASK_FSGID]           = "task.fsgid",
82 	[TOMOYO_TASK_PID]             = "task.pid",
83 	[TOMOYO_TASK_PPID]            = "task.ppid",
84 	[TOMOYO_EXEC_ARGC]            = "exec.argc",
85 	[TOMOYO_EXEC_ENVC]            = "exec.envc",
86 	[TOMOYO_TYPE_IS_SOCKET]       = "socket",
87 	[TOMOYO_TYPE_IS_SYMLINK]      = "symlink",
88 	[TOMOYO_TYPE_IS_FILE]         = "file",
89 	[TOMOYO_TYPE_IS_BLOCK_DEV]    = "block",
90 	[TOMOYO_TYPE_IS_DIRECTORY]    = "directory",
91 	[TOMOYO_TYPE_IS_CHAR_DEV]     = "char",
92 	[TOMOYO_TYPE_IS_FIFO]         = "fifo",
93 	[TOMOYO_MODE_SETUID]          = "setuid",
94 	[TOMOYO_MODE_SETGID]          = "setgid",
95 	[TOMOYO_MODE_STICKY]          = "sticky",
96 	[TOMOYO_MODE_OWNER_READ]      = "owner_read",
97 	[TOMOYO_MODE_OWNER_WRITE]     = "owner_write",
98 	[TOMOYO_MODE_OWNER_EXECUTE]   = "owner_execute",
99 	[TOMOYO_MODE_GROUP_READ]      = "group_read",
100 	[TOMOYO_MODE_GROUP_WRITE]     = "group_write",
101 	[TOMOYO_MODE_GROUP_EXECUTE]   = "group_execute",
102 	[TOMOYO_MODE_OTHERS_READ]     = "others_read",
103 	[TOMOYO_MODE_OTHERS_WRITE]    = "others_write",
104 	[TOMOYO_MODE_OTHERS_EXECUTE]  = "others_execute",
105 	[TOMOYO_EXEC_REALPATH]        = "exec.realpath",
106 	[TOMOYO_SYMLINK_TARGET]       = "symlink.target",
107 	[TOMOYO_PATH1_UID]            = "path1.uid",
108 	[TOMOYO_PATH1_GID]            = "path1.gid",
109 	[TOMOYO_PATH1_INO]            = "path1.ino",
110 	[TOMOYO_PATH1_MAJOR]          = "path1.major",
111 	[TOMOYO_PATH1_MINOR]          = "path1.minor",
112 	[TOMOYO_PATH1_PERM]           = "path1.perm",
113 	[TOMOYO_PATH1_TYPE]           = "path1.type",
114 	[TOMOYO_PATH1_DEV_MAJOR]      = "path1.dev_major",
115 	[TOMOYO_PATH1_DEV_MINOR]      = "path1.dev_minor",
116 	[TOMOYO_PATH2_UID]            = "path2.uid",
117 	[TOMOYO_PATH2_GID]            = "path2.gid",
118 	[TOMOYO_PATH2_INO]            = "path2.ino",
119 	[TOMOYO_PATH2_MAJOR]          = "path2.major",
120 	[TOMOYO_PATH2_MINOR]          = "path2.minor",
121 	[TOMOYO_PATH2_PERM]           = "path2.perm",
122 	[TOMOYO_PATH2_TYPE]           = "path2.type",
123 	[TOMOYO_PATH2_DEV_MAJOR]      = "path2.dev_major",
124 	[TOMOYO_PATH2_DEV_MINOR]      = "path2.dev_minor",
125 	[TOMOYO_PATH1_PARENT_UID]     = "path1.parent.uid",
126 	[TOMOYO_PATH1_PARENT_GID]     = "path1.parent.gid",
127 	[TOMOYO_PATH1_PARENT_INO]     = "path1.parent.ino",
128 	[TOMOYO_PATH1_PARENT_PERM]    = "path1.parent.perm",
129 	[TOMOYO_PATH2_PARENT_UID]     = "path2.parent.uid",
130 	[TOMOYO_PATH2_PARENT_GID]     = "path2.parent.gid",
131 	[TOMOYO_PATH2_PARENT_INO]     = "path2.parent.ino",
132 	[TOMOYO_PATH2_PARENT_PERM]    = "path2.parent.perm",
133 };
134 
135 /* String table for PREFERENCE keyword. */
136 static const char * const tomoyo_pref_keywords[TOMOYO_MAX_PREF] = {
137 	[TOMOYO_PREF_MAX_AUDIT_LOG]      = "max_audit_log",
138 	[TOMOYO_PREF_MAX_LEARNING_ENTRY] = "max_learning_entry",
139 };
140 
141 /* String table for path operation. */
142 const char * const tomoyo_path_keyword[TOMOYO_MAX_PATH_OPERATION] = {
143 	[TOMOYO_TYPE_EXECUTE]    = "execute",
144 	[TOMOYO_TYPE_READ]       = "read",
145 	[TOMOYO_TYPE_WRITE]      = "write",
146 	[TOMOYO_TYPE_APPEND]     = "append",
147 	[TOMOYO_TYPE_UNLINK]     = "unlink",
148 	[TOMOYO_TYPE_GETATTR]    = "getattr",
149 	[TOMOYO_TYPE_RMDIR]      = "rmdir",
150 	[TOMOYO_TYPE_TRUNCATE]   = "truncate",
151 	[TOMOYO_TYPE_SYMLINK]    = "symlink",
152 	[TOMOYO_TYPE_CHROOT]     = "chroot",
153 	[TOMOYO_TYPE_UMOUNT]     = "unmount",
154 };
155 
156 /* String table for socket's operation. */
157 const char * const tomoyo_socket_keyword[TOMOYO_MAX_NETWORK_OPERATION] = {
158 	[TOMOYO_NETWORK_BIND]    = "bind",
159 	[TOMOYO_NETWORK_LISTEN]  = "listen",
160 	[TOMOYO_NETWORK_CONNECT] = "connect",
161 	[TOMOYO_NETWORK_SEND]    = "send",
162 };
163 
164 /* String table for categories. */
165 static const char * const tomoyo_category_keywords
166 [TOMOYO_MAX_MAC_CATEGORY_INDEX] = {
167 	[TOMOYO_MAC_CATEGORY_FILE]    = "file",
168 	[TOMOYO_MAC_CATEGORY_NETWORK] = "network",
169 	[TOMOYO_MAC_CATEGORY_MISC]    = "misc",
170 };
171 
172 /* Permit policy management by non-root user? */
173 static bool tomoyo_manage_by_non_root;
174 
175 /* Utility functions. */
176 
177 /**
178  * tomoyo_yesno - Return "yes" or "no".
179  *
180  * @value: Bool value.
181  */
182 const char *tomoyo_yesno(const unsigned int value)
183 {
184 	return value ? "yes" : "no";
185 }
186 
187 /**
188  * tomoyo_addprintf - strncat()-like-snprintf().
189  *
190  * @buffer: Buffer to write to. Must be '\0'-terminated.
191  * @len:    Size of @buffer.
192  * @fmt:    The printf()'s format string, followed by parameters.
193  *
194  * Returns nothing.
195  */
196 static void tomoyo_addprintf(char *buffer, int len, const char *fmt, ...)
197 {
198 	va_list args;
199 	const int pos = strlen(buffer);
200 
201 	va_start(args, fmt);
202 	vsnprintf(buffer + pos, len - pos - 1, fmt, args);
203 	va_end(args);
204 }
205 
206 /**
207  * tomoyo_flush - Flush queued string to userspace's buffer.
208  *
209  * @head:   Pointer to "struct tomoyo_io_buffer".
210  *
211  * Returns true if all data was flushed, false otherwise.
212  */
213 static bool tomoyo_flush(struct tomoyo_io_buffer *head)
214 {
215 	while (head->r.w_pos) {
216 		const char *w = head->r.w[0];
217 		size_t len = strlen(w);
218 
219 		if (len) {
220 			if (len > head->read_user_buf_avail)
221 				len = head->read_user_buf_avail;
222 			if (!len)
223 				return false;
224 			if (copy_to_user(head->read_user_buf, w, len))
225 				return false;
226 			head->read_user_buf_avail -= len;
227 			head->read_user_buf += len;
228 			w += len;
229 		}
230 		head->r.w[0] = w;
231 		if (*w)
232 			return false;
233 		/* Add '\0' for audit logs and query. */
234 		if (head->poll) {
235 			if (!head->read_user_buf_avail ||
236 			    copy_to_user(head->read_user_buf, "", 1))
237 				return false;
238 			head->read_user_buf_avail--;
239 			head->read_user_buf++;
240 		}
241 		head->r.w_pos--;
242 		for (len = 0; len < head->r.w_pos; len++)
243 			head->r.w[len] = head->r.w[len + 1];
244 	}
245 	head->r.avail = 0;
246 	return true;
247 }
248 
249 /**
250  * tomoyo_set_string - Queue string to "struct tomoyo_io_buffer" structure.
251  *
252  * @head:   Pointer to "struct tomoyo_io_buffer".
253  * @string: String to print.
254  *
255  * Note that @string has to be kept valid until @head is kfree()d.
256  * This means that char[] allocated on stack memory cannot be passed to
257  * this function. Use tomoyo_io_printf() for char[] allocated on stack memory.
258  */
259 static void tomoyo_set_string(struct tomoyo_io_buffer *head, const char *string)
260 {
261 	if (head->r.w_pos < TOMOYO_MAX_IO_READ_QUEUE) {
262 		head->r.w[head->r.w_pos++] = string;
263 		tomoyo_flush(head);
264 	} else
265 		WARN_ON(1);
266 }
267 
268 static void tomoyo_io_printf(struct tomoyo_io_buffer *head, const char *fmt,
269 			     ...) __printf(2, 3);
270 
271 /**
272  * tomoyo_io_printf - printf() to "struct tomoyo_io_buffer" structure.
273  *
274  * @head: Pointer to "struct tomoyo_io_buffer".
275  * @fmt:  The printf()'s format string, followed by parameters.
276  */
277 static void tomoyo_io_printf(struct tomoyo_io_buffer *head, const char *fmt,
278 			     ...)
279 {
280 	va_list args;
281 	size_t len;
282 	size_t pos = head->r.avail;
283 	int size = head->readbuf_size - pos;
284 
285 	if (size <= 0)
286 		return;
287 	va_start(args, fmt);
288 	len = vsnprintf(head->read_buf + pos, size, fmt, args) + 1;
289 	va_end(args);
290 	if (pos + len >= head->readbuf_size) {
291 		WARN_ON(1);
292 		return;
293 	}
294 	head->r.avail += len;
295 	tomoyo_set_string(head, head->read_buf + pos);
296 }
297 
298 /**
299  * tomoyo_set_space - Put a space to "struct tomoyo_io_buffer" structure.
300  *
301  * @head: Pointer to "struct tomoyo_io_buffer".
302  *
303  * Returns nothing.
304  */
305 static void tomoyo_set_space(struct tomoyo_io_buffer *head)
306 {
307 	tomoyo_set_string(head, " ");
308 }
309 
310 /**
311  * tomoyo_set_lf - Put a line feed to "struct tomoyo_io_buffer" structure.
312  *
313  * @head: Pointer to "struct tomoyo_io_buffer".
314  *
315  * Returns nothing.
316  */
317 static bool tomoyo_set_lf(struct tomoyo_io_buffer *head)
318 {
319 	tomoyo_set_string(head, "\n");
320 	return !head->r.w_pos;
321 }
322 
323 /**
324  * tomoyo_set_slash - Put a shash to "struct tomoyo_io_buffer" structure.
325  *
326  * @head: Pointer to "struct tomoyo_io_buffer".
327  *
328  * Returns nothing.
329  */
330 static void tomoyo_set_slash(struct tomoyo_io_buffer *head)
331 {
332 	tomoyo_set_string(head, "/");
333 }
334 
335 /* List of namespaces. */
336 LIST_HEAD(tomoyo_namespace_list);
337 /* True if namespace other than tomoyo_kernel_namespace is defined. */
338 static bool tomoyo_namespace_enabled;
339 
340 /**
341  * tomoyo_init_policy_namespace - Initialize namespace.
342  *
343  * @ns: Pointer to "struct tomoyo_policy_namespace".
344  *
345  * Returns nothing.
346  */
347 void tomoyo_init_policy_namespace(struct tomoyo_policy_namespace *ns)
348 {
349 	unsigned int idx;
350 
351 	for (idx = 0; idx < TOMOYO_MAX_ACL_GROUPS; idx++)
352 		INIT_LIST_HEAD(&ns->acl_group[idx]);
353 	for (idx = 0; idx < TOMOYO_MAX_GROUP; idx++)
354 		INIT_LIST_HEAD(&ns->group_list[idx]);
355 	for (idx = 0; idx < TOMOYO_MAX_POLICY; idx++)
356 		INIT_LIST_HEAD(&ns->policy_list[idx]);
357 	ns->profile_version = 20150505;
358 	tomoyo_namespace_enabled = !list_empty(&tomoyo_namespace_list);
359 	list_add_tail_rcu(&ns->namespace_list, &tomoyo_namespace_list);
360 }
361 
362 /**
363  * tomoyo_print_namespace - Print namespace header.
364  *
365  * @head: Pointer to "struct tomoyo_io_buffer".
366  *
367  * Returns nothing.
368  */
369 static void tomoyo_print_namespace(struct tomoyo_io_buffer *head)
370 {
371 	if (!tomoyo_namespace_enabled)
372 		return;
373 	tomoyo_set_string(head,
374 			  container_of(head->r.ns,
375 				       struct tomoyo_policy_namespace,
376 				       namespace_list)->name);
377 	tomoyo_set_space(head);
378 }
379 
380 /**
381  * tomoyo_print_name_union - Print a tomoyo_name_union.
382  *
383  * @head: Pointer to "struct tomoyo_io_buffer".
384  * @ptr:  Pointer to "struct tomoyo_name_union".
385  */
386 static void tomoyo_print_name_union(struct tomoyo_io_buffer *head,
387 				    const struct tomoyo_name_union *ptr)
388 {
389 	tomoyo_set_space(head);
390 	if (ptr->group) {
391 		tomoyo_set_string(head, "@");
392 		tomoyo_set_string(head, ptr->group->group_name->name);
393 	} else {
394 		tomoyo_set_string(head, ptr->filename->name);
395 	}
396 }
397 
398 /**
399  * tomoyo_print_name_union_quoted - Print a tomoyo_name_union with a quote.
400  *
401  * @head: Pointer to "struct tomoyo_io_buffer".
402  * @ptr:  Pointer to "struct tomoyo_name_union".
403  *
404  * Returns nothing.
405  */
406 static void tomoyo_print_name_union_quoted(struct tomoyo_io_buffer *head,
407 					   const struct tomoyo_name_union *ptr)
408 {
409 	if (ptr->group) {
410 		tomoyo_set_string(head, "@");
411 		tomoyo_set_string(head, ptr->group->group_name->name);
412 	} else {
413 		tomoyo_set_string(head, "\"");
414 		tomoyo_set_string(head, ptr->filename->name);
415 		tomoyo_set_string(head, "\"");
416 	}
417 }
418 
419 /**
420  * tomoyo_print_number_union_nospace - Print a tomoyo_number_union without a space.
421  *
422  * @head: Pointer to "struct tomoyo_io_buffer".
423  * @ptr:  Pointer to "struct tomoyo_number_union".
424  *
425  * Returns nothing.
426  */
427 static void tomoyo_print_number_union_nospace
428 (struct tomoyo_io_buffer *head, const struct tomoyo_number_union *ptr)
429 {
430 	if (ptr->group) {
431 		tomoyo_set_string(head, "@");
432 		tomoyo_set_string(head, ptr->group->group_name->name);
433 	} else {
434 		int i;
435 		unsigned long min = ptr->values[0];
436 		const unsigned long max = ptr->values[1];
437 		u8 min_type = ptr->value_type[0];
438 		const u8 max_type = ptr->value_type[1];
439 		char buffer[128];
440 
441 		buffer[0] = '\0';
442 		for (i = 0; i < 2; i++) {
443 			switch (min_type) {
444 			case TOMOYO_VALUE_TYPE_HEXADECIMAL:
445 				tomoyo_addprintf(buffer, sizeof(buffer),
446 						 "0x%lX", min);
447 				break;
448 			case TOMOYO_VALUE_TYPE_OCTAL:
449 				tomoyo_addprintf(buffer, sizeof(buffer),
450 						 "0%lo", min);
451 				break;
452 			default:
453 				tomoyo_addprintf(buffer, sizeof(buffer), "%lu",
454 						 min);
455 				break;
456 			}
457 			if (min == max && min_type == max_type)
458 				break;
459 			tomoyo_addprintf(buffer, sizeof(buffer), "-");
460 			min_type = max_type;
461 			min = max;
462 		}
463 		tomoyo_io_printf(head, "%s", buffer);
464 	}
465 }
466 
467 /**
468  * tomoyo_print_number_union - Print a tomoyo_number_union.
469  *
470  * @head: Pointer to "struct tomoyo_io_buffer".
471  * @ptr:  Pointer to "struct tomoyo_number_union".
472  *
473  * Returns nothing.
474  */
475 static void tomoyo_print_number_union(struct tomoyo_io_buffer *head,
476 				      const struct tomoyo_number_union *ptr)
477 {
478 	tomoyo_set_space(head);
479 	tomoyo_print_number_union_nospace(head, ptr);
480 }
481 
482 /**
483  * tomoyo_assign_profile - Create a new profile.
484  *
485  * @ns:      Pointer to "struct tomoyo_policy_namespace".
486  * @profile: Profile number to create.
487  *
488  * Returns pointer to "struct tomoyo_profile" on success, NULL otherwise.
489  */
490 static struct tomoyo_profile *tomoyo_assign_profile
491 (struct tomoyo_policy_namespace *ns, const unsigned int profile)
492 {
493 	struct tomoyo_profile *ptr;
494 	struct tomoyo_profile *entry;
495 
496 	if (profile >= TOMOYO_MAX_PROFILES)
497 		return NULL;
498 	ptr = ns->profile_ptr[profile];
499 	if (ptr)
500 		return ptr;
501 	entry = kzalloc(sizeof(*entry), GFP_NOFS);
502 	if (mutex_lock_interruptible(&tomoyo_policy_lock))
503 		goto out;
504 	ptr = ns->profile_ptr[profile];
505 	if (!ptr && tomoyo_memory_ok(entry)) {
506 		ptr = entry;
507 		ptr->default_config = TOMOYO_CONFIG_DISABLED |
508 			TOMOYO_CONFIG_WANT_GRANT_LOG |
509 			TOMOYO_CONFIG_WANT_REJECT_LOG;
510 		memset(ptr->config, TOMOYO_CONFIG_USE_DEFAULT,
511 		       sizeof(ptr->config));
512 		ptr->pref[TOMOYO_PREF_MAX_AUDIT_LOG] =
513 			CONFIG_SECURITY_TOMOYO_MAX_AUDIT_LOG;
514 		ptr->pref[TOMOYO_PREF_MAX_LEARNING_ENTRY] =
515 			CONFIG_SECURITY_TOMOYO_MAX_ACCEPT_ENTRY;
516 		mb(); /* Avoid out-of-order execution. */
517 		ns->profile_ptr[profile] = ptr;
518 		entry = NULL;
519 	}
520 	mutex_unlock(&tomoyo_policy_lock);
521  out:
522 	kfree(entry);
523 	return ptr;
524 }
525 
526 /**
527  * tomoyo_profile - Find a profile.
528  *
529  * @ns:      Pointer to "struct tomoyo_policy_namespace".
530  * @profile: Profile number to find.
531  *
532  * Returns pointer to "struct tomoyo_profile".
533  */
534 struct tomoyo_profile *tomoyo_profile(const struct tomoyo_policy_namespace *ns,
535 				      const u8 profile)
536 {
537 	static struct tomoyo_profile tomoyo_null_profile;
538 	struct tomoyo_profile *ptr = ns->profile_ptr[profile];
539 
540 	if (!ptr)
541 		ptr = &tomoyo_null_profile;
542 	return ptr;
543 }
544 
545 /**
546  * tomoyo_find_yesno - Find values for specified keyword.
547  *
548  * @string: String to check.
549  * @find:   Name of keyword.
550  *
551  * Returns 1 if "@find=yes" was found, 0 if "@find=no" was found, -1 otherwise.
552  */
553 static s8 tomoyo_find_yesno(const char *string, const char *find)
554 {
555 	const char *cp = strstr(string, find);
556 
557 	if (cp) {
558 		cp += strlen(find);
559 		if (!strncmp(cp, "=yes", 4))
560 			return 1;
561 		else if (!strncmp(cp, "=no", 3))
562 			return 0;
563 	}
564 	return -1;
565 }
566 
567 /**
568  * tomoyo_set_uint - Set value for specified preference.
569  *
570  * @i:      Pointer to "unsigned int".
571  * @string: String to check.
572  * @find:   Name of keyword.
573  *
574  * Returns nothing.
575  */
576 static void tomoyo_set_uint(unsigned int *i, const char *string,
577 			    const char *find)
578 {
579 	const char *cp = strstr(string, find);
580 
581 	if (cp)
582 		sscanf(cp + strlen(find), "=%u", i);
583 }
584 
585 /**
586  * tomoyo_set_mode - Set mode for specified profile.
587  *
588  * @name:    Name of functionality.
589  * @value:   Mode for @name.
590  * @profile: Pointer to "struct tomoyo_profile".
591  *
592  * Returns 0 on success, negative value otherwise.
593  */
594 static int tomoyo_set_mode(char *name, const char *value,
595 			   struct tomoyo_profile *profile)
596 {
597 	u8 i;
598 	u8 config;
599 
600 	if (!strcmp(name, "CONFIG")) {
601 		i = TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX;
602 		config = profile->default_config;
603 	} else if (tomoyo_str_starts(&name, "CONFIG::")) {
604 		config = 0;
605 		for (i = 0; i < TOMOYO_MAX_MAC_INDEX
606 			     + TOMOYO_MAX_MAC_CATEGORY_INDEX; i++) {
607 			int len = 0;
608 
609 			if (i < TOMOYO_MAX_MAC_INDEX) {
610 				const u8 c = tomoyo_index2category[i];
611 				const char *category =
612 					tomoyo_category_keywords[c];
613 
614 				len = strlen(category);
615 				if (strncmp(name, category, len) ||
616 				    name[len++] != ':' || name[len++] != ':')
617 					continue;
618 			}
619 			if (strcmp(name + len, tomoyo_mac_keywords[i]))
620 				continue;
621 			config = profile->config[i];
622 			break;
623 		}
624 		if (i == TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX)
625 			return -EINVAL;
626 	} else {
627 		return -EINVAL;
628 	}
629 	if (strstr(value, "use_default")) {
630 		config = TOMOYO_CONFIG_USE_DEFAULT;
631 	} else {
632 		u8 mode;
633 
634 		for (mode = 0; mode < 4; mode++)
635 			if (strstr(value, tomoyo_mode[mode]))
636 				/*
637 				 * Update lower 3 bits in order to distinguish
638 				 * 'config' from 'TOMOYO_CONFIG_USE_DEAFULT'.
639 				 */
640 				config = (config & ~7) | mode;
641 		if (config != TOMOYO_CONFIG_USE_DEFAULT) {
642 			switch (tomoyo_find_yesno(value, "grant_log")) {
643 			case 1:
644 				config |= TOMOYO_CONFIG_WANT_GRANT_LOG;
645 				break;
646 			case 0:
647 				config &= ~TOMOYO_CONFIG_WANT_GRANT_LOG;
648 				break;
649 			}
650 			switch (tomoyo_find_yesno(value, "reject_log")) {
651 			case 1:
652 				config |= TOMOYO_CONFIG_WANT_REJECT_LOG;
653 				break;
654 			case 0:
655 				config &= ~TOMOYO_CONFIG_WANT_REJECT_LOG;
656 				break;
657 			}
658 		}
659 	}
660 	if (i < TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX)
661 		profile->config[i] = config;
662 	else if (config != TOMOYO_CONFIG_USE_DEFAULT)
663 		profile->default_config = config;
664 	return 0;
665 }
666 
667 /**
668  * tomoyo_write_profile - Write profile table.
669  *
670  * @head: Pointer to "struct tomoyo_io_buffer".
671  *
672  * Returns 0 on success, negative value otherwise.
673  */
674 static int tomoyo_write_profile(struct tomoyo_io_buffer *head)
675 {
676 	char *data = head->write_buf;
677 	unsigned int i;
678 	char *cp;
679 	struct tomoyo_profile *profile;
680 
681 	if (sscanf(data, "PROFILE_VERSION=%u", &head->w.ns->profile_version)
682 	    == 1)
683 		return 0;
684 	i = simple_strtoul(data, &cp, 10);
685 	if (*cp != '-')
686 		return -EINVAL;
687 	data = cp + 1;
688 	profile = tomoyo_assign_profile(head->w.ns, i);
689 	if (!profile)
690 		return -EINVAL;
691 	cp = strchr(data, '=');
692 	if (!cp)
693 		return -EINVAL;
694 	*cp++ = '\0';
695 	if (!strcmp(data, "COMMENT")) {
696 		static DEFINE_SPINLOCK(lock);
697 		const struct tomoyo_path_info *new_comment
698 			= tomoyo_get_name(cp);
699 		const struct tomoyo_path_info *old_comment;
700 
701 		if (!new_comment)
702 			return -ENOMEM;
703 		spin_lock(&lock);
704 		old_comment = profile->comment;
705 		profile->comment = new_comment;
706 		spin_unlock(&lock);
707 		tomoyo_put_name(old_comment);
708 		return 0;
709 	}
710 	if (!strcmp(data, "PREFERENCE")) {
711 		for (i = 0; i < TOMOYO_MAX_PREF; i++)
712 			tomoyo_set_uint(&profile->pref[i], cp,
713 					tomoyo_pref_keywords[i]);
714 		return 0;
715 	}
716 	return tomoyo_set_mode(data, cp, profile);
717 }
718 
719 /**
720  * tomoyo_print_config - Print mode for specified functionality.
721  *
722  * @head:   Pointer to "struct tomoyo_io_buffer".
723  * @config: Mode for that functionality.
724  *
725  * Returns nothing.
726  *
727  * Caller prints functionality's name.
728  */
729 static void tomoyo_print_config(struct tomoyo_io_buffer *head, const u8 config)
730 {
731 	tomoyo_io_printf(head, "={ mode=%s grant_log=%s reject_log=%s }\n",
732 			 tomoyo_mode[config & 3],
733 			 tomoyo_yesno(config & TOMOYO_CONFIG_WANT_GRANT_LOG),
734 			 tomoyo_yesno(config & TOMOYO_CONFIG_WANT_REJECT_LOG));
735 }
736 
737 /**
738  * tomoyo_read_profile - Read profile table.
739  *
740  * @head: Pointer to "struct tomoyo_io_buffer".
741  *
742  * Returns nothing.
743  */
744 static void tomoyo_read_profile(struct tomoyo_io_buffer *head)
745 {
746 	u8 index;
747 	struct tomoyo_policy_namespace *ns =
748 		container_of(head->r.ns, typeof(*ns), namespace_list);
749 	const struct tomoyo_profile *profile;
750 
751 	if (head->r.eof)
752 		return;
753  next:
754 	index = head->r.index;
755 	profile = ns->profile_ptr[index];
756 	switch (head->r.step) {
757 	case 0:
758 		tomoyo_print_namespace(head);
759 		tomoyo_io_printf(head, "PROFILE_VERSION=%u\n",
760 				 ns->profile_version);
761 		head->r.step++;
762 		break;
763 	case 1:
764 		for ( ; head->r.index < TOMOYO_MAX_PROFILES;
765 		      head->r.index++)
766 			if (ns->profile_ptr[head->r.index])
767 				break;
768 		if (head->r.index == TOMOYO_MAX_PROFILES) {
769 			head->r.eof = true;
770 			return;
771 		}
772 		head->r.step++;
773 		break;
774 	case 2:
775 		{
776 			u8 i;
777 			const struct tomoyo_path_info *comment =
778 				profile->comment;
779 
780 			tomoyo_print_namespace(head);
781 			tomoyo_io_printf(head, "%u-COMMENT=", index);
782 			tomoyo_set_string(head, comment ? comment->name : "");
783 			tomoyo_set_lf(head);
784 			tomoyo_print_namespace(head);
785 			tomoyo_io_printf(head, "%u-PREFERENCE={ ", index);
786 			for (i = 0; i < TOMOYO_MAX_PREF; i++)
787 				tomoyo_io_printf(head, "%s=%u ",
788 						 tomoyo_pref_keywords[i],
789 						 profile->pref[i]);
790 			tomoyo_set_string(head, "}\n");
791 			head->r.step++;
792 		}
793 		break;
794 	case 3:
795 		{
796 			tomoyo_print_namespace(head);
797 			tomoyo_io_printf(head, "%u-%s", index, "CONFIG");
798 			tomoyo_print_config(head, profile->default_config);
799 			head->r.bit = 0;
800 			head->r.step++;
801 		}
802 		break;
803 	case 4:
804 		for ( ; head->r.bit < TOMOYO_MAX_MAC_INDEX
805 			      + TOMOYO_MAX_MAC_CATEGORY_INDEX; head->r.bit++) {
806 			const u8 i = head->r.bit;
807 			const u8 config = profile->config[i];
808 
809 			if (config == TOMOYO_CONFIG_USE_DEFAULT)
810 				continue;
811 			tomoyo_print_namespace(head);
812 			if (i < TOMOYO_MAX_MAC_INDEX)
813 				tomoyo_io_printf(head, "%u-CONFIG::%s::%s",
814 						 index,
815 						 tomoyo_category_keywords
816 						 [tomoyo_index2category[i]],
817 						 tomoyo_mac_keywords[i]);
818 			else
819 				tomoyo_io_printf(head, "%u-CONFIG::%s", index,
820 						 tomoyo_mac_keywords[i]);
821 			tomoyo_print_config(head, config);
822 			head->r.bit++;
823 			break;
824 		}
825 		if (head->r.bit == TOMOYO_MAX_MAC_INDEX
826 		    + TOMOYO_MAX_MAC_CATEGORY_INDEX) {
827 			head->r.index++;
828 			head->r.step = 1;
829 		}
830 		break;
831 	}
832 	if (tomoyo_flush(head))
833 		goto next;
834 }
835 
836 /**
837  * tomoyo_same_manager - Check for duplicated "struct tomoyo_manager" entry.
838  *
839  * @a: Pointer to "struct tomoyo_acl_head".
840  * @b: Pointer to "struct tomoyo_acl_head".
841  *
842  * Returns true if @a == @b, false otherwise.
843  */
844 static bool tomoyo_same_manager(const struct tomoyo_acl_head *a,
845 				const struct tomoyo_acl_head *b)
846 {
847 	return container_of(a, struct tomoyo_manager, head)->manager ==
848 		container_of(b, struct tomoyo_manager, head)->manager;
849 }
850 
851 /**
852  * tomoyo_update_manager_entry - Add a manager entry.
853  *
854  * @manager:   The path to manager or the domainnamme.
855  * @is_delete: True if it is a delete request.
856  *
857  * Returns 0 on success, negative value otherwise.
858  *
859  * Caller holds tomoyo_read_lock().
860  */
861 static int tomoyo_update_manager_entry(const char *manager,
862 				       const bool is_delete)
863 {
864 	struct tomoyo_manager e = { };
865 	struct tomoyo_acl_param param = {
866 		/* .ns = &tomoyo_kernel_namespace, */
867 		.is_delete = is_delete,
868 		.list = &tomoyo_kernel_namespace.policy_list[TOMOYO_ID_MANAGER],
869 	};
870 	int error = is_delete ? -ENOENT : -ENOMEM;
871 
872 	if (!tomoyo_correct_domain(manager) &&
873 	    !tomoyo_correct_word(manager))
874 		return -EINVAL;
875 	e.manager = tomoyo_get_name(manager);
876 	if (e.manager) {
877 		error = tomoyo_update_policy(&e.head, sizeof(e), &param,
878 					     tomoyo_same_manager);
879 		tomoyo_put_name(e.manager);
880 	}
881 	return error;
882 }
883 
884 /**
885  * tomoyo_write_manager - Write manager policy.
886  *
887  * @head: Pointer to "struct tomoyo_io_buffer".
888  *
889  * Returns 0 on success, negative value otherwise.
890  *
891  * Caller holds tomoyo_read_lock().
892  */
893 static int tomoyo_write_manager(struct tomoyo_io_buffer *head)
894 {
895 	char *data = head->write_buf;
896 
897 	if (!strcmp(data, "manage_by_non_root")) {
898 		tomoyo_manage_by_non_root = !head->w.is_delete;
899 		return 0;
900 	}
901 	return tomoyo_update_manager_entry(data, head->w.is_delete);
902 }
903 
904 /**
905  * tomoyo_read_manager - Read manager policy.
906  *
907  * @head: Pointer to "struct tomoyo_io_buffer".
908  *
909  * Caller holds tomoyo_read_lock().
910  */
911 static void tomoyo_read_manager(struct tomoyo_io_buffer *head)
912 {
913 	if (head->r.eof)
914 		return;
915 	list_for_each_cookie(head->r.acl, &tomoyo_kernel_namespace.policy_list[TOMOYO_ID_MANAGER]) {
916 		struct tomoyo_manager *ptr =
917 			list_entry(head->r.acl, typeof(*ptr), head.list);
918 
919 		if (ptr->head.is_deleted)
920 			continue;
921 		if (!tomoyo_flush(head))
922 			return;
923 		tomoyo_set_string(head, ptr->manager->name);
924 		tomoyo_set_lf(head);
925 	}
926 	head->r.eof = true;
927 }
928 
929 /**
930  * tomoyo_manager - Check whether the current process is a policy manager.
931  *
932  * Returns true if the current process is permitted to modify policy
933  * via /sys/kernel/security/tomoyo/ interface.
934  *
935  * Caller holds tomoyo_read_lock().
936  */
937 static bool tomoyo_manager(void)
938 {
939 	struct tomoyo_manager *ptr;
940 	const char *exe;
941 	const struct task_struct *task = current;
942 	const struct tomoyo_path_info *domainname = tomoyo_domain()->domainname;
943 	bool found = false;
944 
945 	if (!tomoyo_policy_loaded)
946 		return true;
947 	if (!tomoyo_manage_by_non_root &&
948 	    (!uid_eq(task->cred->uid,  GLOBAL_ROOT_UID) ||
949 	     !uid_eq(task->cred->euid, GLOBAL_ROOT_UID)))
950 		return false;
951 	exe = tomoyo_get_exe();
952 	if (!exe)
953 		return false;
954 	list_for_each_entry_rcu(ptr, &tomoyo_kernel_namespace.policy_list[TOMOYO_ID_MANAGER], head.list) {
955 		if (!ptr->head.is_deleted &&
956 		    (!tomoyo_pathcmp(domainname, ptr->manager) ||
957 		     !strcmp(exe, ptr->manager->name))) {
958 			found = true;
959 			break;
960 		}
961 	}
962 	if (!found) { /* Reduce error messages. */
963 		static pid_t last_pid;
964 		const pid_t pid = current->pid;
965 
966 		if (last_pid != pid) {
967 			pr_warn("%s ( %s ) is not permitted to update policies.\n",
968 				domainname->name, exe);
969 			last_pid = pid;
970 		}
971 	}
972 	kfree(exe);
973 	return found;
974 }
975 
976 static struct tomoyo_domain_info *tomoyo_find_domain_by_qid
977 (unsigned int serial);
978 
979 /**
980  * tomoyo_select_domain - Parse select command.
981  *
982  * @head: Pointer to "struct tomoyo_io_buffer".
983  * @data: String to parse.
984  *
985  * Returns true on success, false otherwise.
986  *
987  * Caller holds tomoyo_read_lock().
988  */
989 static bool tomoyo_select_domain(struct tomoyo_io_buffer *head,
990 				 const char *data)
991 {
992 	unsigned int pid;
993 	struct tomoyo_domain_info *domain = NULL;
994 	bool global_pid = false;
995 
996 	if (strncmp(data, "select ", 7))
997 		return false;
998 	data += 7;
999 	if (sscanf(data, "pid=%u", &pid) == 1 ||
1000 	    (global_pid = true, sscanf(data, "global-pid=%u", &pid) == 1)) {
1001 		struct task_struct *p;
1002 
1003 		rcu_read_lock();
1004 		if (global_pid)
1005 			p = find_task_by_pid_ns(pid, &init_pid_ns);
1006 		else
1007 			p = find_task_by_vpid(pid);
1008 		if (p)
1009 			domain = tomoyo_task(p)->domain_info;
1010 		rcu_read_unlock();
1011 	} else if (!strncmp(data, "domain=", 7)) {
1012 		if (tomoyo_domain_def(data + 7))
1013 			domain = tomoyo_find_domain(data + 7);
1014 	} else if (sscanf(data, "Q=%u", &pid) == 1) {
1015 		domain = tomoyo_find_domain_by_qid(pid);
1016 	} else
1017 		return false;
1018 	head->w.domain = domain;
1019 	/* Accessing read_buf is safe because head->io_sem is held. */
1020 	if (!head->read_buf)
1021 		return true; /* Do nothing if open(O_WRONLY). */
1022 	memset(&head->r, 0, sizeof(head->r));
1023 	head->r.print_this_domain_only = true;
1024 	if (domain)
1025 		head->r.domain = &domain->list;
1026 	else
1027 		head->r.eof = 1;
1028 	tomoyo_io_printf(head, "# select %s\n", data);
1029 	if (domain && domain->is_deleted)
1030 		tomoyo_io_printf(head, "# This is a deleted domain.\n");
1031 	return true;
1032 }
1033 
1034 /**
1035  * tomoyo_same_task_acl - Check for duplicated "struct tomoyo_task_acl" entry.
1036  *
1037  * @a: Pointer to "struct tomoyo_acl_info".
1038  * @b: Pointer to "struct tomoyo_acl_info".
1039  *
1040  * Returns true if @a == @b, false otherwise.
1041  */
1042 static bool tomoyo_same_task_acl(const struct tomoyo_acl_info *a,
1043 				 const struct tomoyo_acl_info *b)
1044 {
1045 	const struct tomoyo_task_acl *p1 = container_of(a, typeof(*p1), head);
1046 	const struct tomoyo_task_acl *p2 = container_of(b, typeof(*p2), head);
1047 
1048 	return p1->domainname == p2->domainname;
1049 }
1050 
1051 /**
1052  * tomoyo_write_task - Update task related list.
1053  *
1054  * @param: Pointer to "struct tomoyo_acl_param".
1055  *
1056  * Returns 0 on success, negative value otherwise.
1057  *
1058  * Caller holds tomoyo_read_lock().
1059  */
1060 static int tomoyo_write_task(struct tomoyo_acl_param *param)
1061 {
1062 	int error = -EINVAL;
1063 
1064 	if (tomoyo_str_starts(&param->data, "manual_domain_transition ")) {
1065 		struct tomoyo_task_acl e = {
1066 			.head.type = TOMOYO_TYPE_MANUAL_TASK_ACL,
1067 			.domainname = tomoyo_get_domainname(param),
1068 		};
1069 
1070 		if (e.domainname)
1071 			error = tomoyo_update_domain(&e.head, sizeof(e), param,
1072 						     tomoyo_same_task_acl,
1073 						     NULL);
1074 		tomoyo_put_name(e.domainname);
1075 	}
1076 	return error;
1077 }
1078 
1079 /**
1080  * tomoyo_delete_domain - Delete a domain.
1081  *
1082  * @domainname: The name of domain.
1083  *
1084  * Returns 0 on success, negative value otherwise.
1085  *
1086  * Caller holds tomoyo_read_lock().
1087  */
1088 static int tomoyo_delete_domain(char *domainname)
1089 {
1090 	struct tomoyo_domain_info *domain;
1091 	struct tomoyo_path_info name;
1092 
1093 	name.name = domainname;
1094 	tomoyo_fill_path_info(&name);
1095 	if (mutex_lock_interruptible(&tomoyo_policy_lock))
1096 		return -EINTR;
1097 	/* Is there an active domain? */
1098 	list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
1099 		/* Never delete tomoyo_kernel_domain */
1100 		if (domain == &tomoyo_kernel_domain)
1101 			continue;
1102 		if (domain->is_deleted ||
1103 		    tomoyo_pathcmp(domain->domainname, &name))
1104 			continue;
1105 		domain->is_deleted = true;
1106 		break;
1107 	}
1108 	mutex_unlock(&tomoyo_policy_lock);
1109 	return 0;
1110 }
1111 
1112 /**
1113  * tomoyo_write_domain2 - Write domain policy.
1114  *
1115  * @ns:        Pointer to "struct tomoyo_policy_namespace".
1116  * @list:      Pointer to "struct list_head".
1117  * @data:      Policy to be interpreted.
1118  * @is_delete: True if it is a delete request.
1119  *
1120  * Returns 0 on success, negative value otherwise.
1121  *
1122  * Caller holds tomoyo_read_lock().
1123  */
1124 static int tomoyo_write_domain2(struct tomoyo_policy_namespace *ns,
1125 				struct list_head *list, char *data,
1126 				const bool is_delete)
1127 {
1128 	struct tomoyo_acl_param param = {
1129 		.ns = ns,
1130 		.list = list,
1131 		.data = data,
1132 		.is_delete = is_delete,
1133 	};
1134 	static const struct {
1135 		const char *keyword;
1136 		int (*write)(struct tomoyo_acl_param *param);
1137 	} tomoyo_callback[5] = {
1138 		{ "file ", tomoyo_write_file },
1139 		{ "network inet ", tomoyo_write_inet_network },
1140 		{ "network unix ", tomoyo_write_unix_network },
1141 		{ "misc ", tomoyo_write_misc },
1142 		{ "task ", tomoyo_write_task },
1143 	};
1144 	u8 i;
1145 
1146 	for (i = 0; i < ARRAY_SIZE(tomoyo_callback); i++) {
1147 		if (!tomoyo_str_starts(&param.data,
1148 				       tomoyo_callback[i].keyword))
1149 			continue;
1150 		return tomoyo_callback[i].write(&param);
1151 	}
1152 	return -EINVAL;
1153 }
1154 
1155 /* String table for domain flags. */
1156 const char * const tomoyo_dif[TOMOYO_MAX_DOMAIN_INFO_FLAGS] = {
1157 	[TOMOYO_DIF_QUOTA_WARNED]      = "quota_exceeded\n",
1158 	[TOMOYO_DIF_TRANSITION_FAILED] = "transition_failed\n",
1159 };
1160 
1161 /**
1162  * tomoyo_write_domain - Write domain policy.
1163  *
1164  * @head: Pointer to "struct tomoyo_io_buffer".
1165  *
1166  * Returns 0 on success, negative value otherwise.
1167  *
1168  * Caller holds tomoyo_read_lock().
1169  */
1170 static int tomoyo_write_domain(struct tomoyo_io_buffer *head)
1171 {
1172 	char *data = head->write_buf;
1173 	struct tomoyo_policy_namespace *ns;
1174 	struct tomoyo_domain_info *domain = head->w.domain;
1175 	const bool is_delete = head->w.is_delete;
1176 	bool is_select = !is_delete && tomoyo_str_starts(&data, "select ");
1177 	unsigned int idx;
1178 
1179 	if (*data == '<') {
1180 		int ret = 0;
1181 
1182 		domain = NULL;
1183 		if (is_delete)
1184 			ret = tomoyo_delete_domain(data);
1185 		else if (is_select)
1186 			domain = tomoyo_find_domain(data);
1187 		else
1188 			domain = tomoyo_assign_domain(data, false);
1189 		head->w.domain = domain;
1190 		return ret;
1191 	}
1192 	if (!domain)
1193 		return -EINVAL;
1194 	ns = domain->ns;
1195 	if (sscanf(data, "use_profile %u", &idx) == 1
1196 	    && idx < TOMOYO_MAX_PROFILES) {
1197 		if (!tomoyo_policy_loaded || ns->profile_ptr[idx])
1198 			if (!is_delete)
1199 				domain->profile = (u8) idx;
1200 		return 0;
1201 	}
1202 	if (sscanf(data, "use_group %u\n", &idx) == 1
1203 	    && idx < TOMOYO_MAX_ACL_GROUPS) {
1204 		if (!is_delete)
1205 			set_bit(idx, domain->group);
1206 		else
1207 			clear_bit(idx, domain->group);
1208 		return 0;
1209 	}
1210 	for (idx = 0; idx < TOMOYO_MAX_DOMAIN_INFO_FLAGS; idx++) {
1211 		const char *cp = tomoyo_dif[idx];
1212 
1213 		if (strncmp(data, cp, strlen(cp) - 1))
1214 			continue;
1215 		domain->flags[idx] = !is_delete;
1216 		return 0;
1217 	}
1218 	return tomoyo_write_domain2(ns, &domain->acl_info_list, data,
1219 				    is_delete);
1220 }
1221 
1222 /**
1223  * tomoyo_print_condition - Print condition part.
1224  *
1225  * @head: Pointer to "struct tomoyo_io_buffer".
1226  * @cond: Pointer to "struct tomoyo_condition".
1227  *
1228  * Returns true on success, false otherwise.
1229  */
1230 static bool tomoyo_print_condition(struct tomoyo_io_buffer *head,
1231 				   const struct tomoyo_condition *cond)
1232 {
1233 	switch (head->r.cond_step) {
1234 	case 0:
1235 		head->r.cond_index = 0;
1236 		head->r.cond_step++;
1237 		if (cond->transit) {
1238 			tomoyo_set_space(head);
1239 			tomoyo_set_string(head, cond->transit->name);
1240 		}
1241 		/* fall through */
1242 	case 1:
1243 		{
1244 			const u16 condc = cond->condc;
1245 			const struct tomoyo_condition_element *condp =
1246 				(typeof(condp)) (cond + 1);
1247 			const struct tomoyo_number_union *numbers_p =
1248 				(typeof(numbers_p)) (condp + condc);
1249 			const struct tomoyo_name_union *names_p =
1250 				(typeof(names_p))
1251 				(numbers_p + cond->numbers_count);
1252 			const struct tomoyo_argv *argv =
1253 				(typeof(argv)) (names_p + cond->names_count);
1254 			const struct tomoyo_envp *envp =
1255 				(typeof(envp)) (argv + cond->argc);
1256 			u16 skip;
1257 
1258 			for (skip = 0; skip < head->r.cond_index; skip++) {
1259 				const u8 left = condp->left;
1260 				const u8 right = condp->right;
1261 
1262 				condp++;
1263 				switch (left) {
1264 				case TOMOYO_ARGV_ENTRY:
1265 					argv++;
1266 					continue;
1267 				case TOMOYO_ENVP_ENTRY:
1268 					envp++;
1269 					continue;
1270 				case TOMOYO_NUMBER_UNION:
1271 					numbers_p++;
1272 					break;
1273 				}
1274 				switch (right) {
1275 				case TOMOYO_NAME_UNION:
1276 					names_p++;
1277 					break;
1278 				case TOMOYO_NUMBER_UNION:
1279 					numbers_p++;
1280 					break;
1281 				}
1282 			}
1283 			while (head->r.cond_index < condc) {
1284 				const u8 match = condp->equals;
1285 				const u8 left = condp->left;
1286 				const u8 right = condp->right;
1287 
1288 				if (!tomoyo_flush(head))
1289 					return false;
1290 				condp++;
1291 				head->r.cond_index++;
1292 				tomoyo_set_space(head);
1293 				switch (left) {
1294 				case TOMOYO_ARGV_ENTRY:
1295 					tomoyo_io_printf(head,
1296 							 "exec.argv[%lu]%s=\"",
1297 							 argv->index, argv->is_not ? "!" : "");
1298 					tomoyo_set_string(head,
1299 							  argv->value->name);
1300 					tomoyo_set_string(head, "\"");
1301 					argv++;
1302 					continue;
1303 				case TOMOYO_ENVP_ENTRY:
1304 					tomoyo_set_string(head,
1305 							  "exec.envp[\"");
1306 					tomoyo_set_string(head,
1307 							  envp->name->name);
1308 					tomoyo_io_printf(head, "\"]%s=", envp->is_not ? "!" : "");
1309 					if (envp->value) {
1310 						tomoyo_set_string(head, "\"");
1311 						tomoyo_set_string(head, envp->value->name);
1312 						tomoyo_set_string(head, "\"");
1313 					} else {
1314 						tomoyo_set_string(head,
1315 								  "NULL");
1316 					}
1317 					envp++;
1318 					continue;
1319 				case TOMOYO_NUMBER_UNION:
1320 					tomoyo_print_number_union_nospace
1321 						(head, numbers_p++);
1322 					break;
1323 				default:
1324 					tomoyo_set_string(head,
1325 					       tomoyo_condition_keyword[left]);
1326 					break;
1327 				}
1328 				tomoyo_set_string(head, match ? "=" : "!=");
1329 				switch (right) {
1330 				case TOMOYO_NAME_UNION:
1331 					tomoyo_print_name_union_quoted
1332 						(head, names_p++);
1333 					break;
1334 				case TOMOYO_NUMBER_UNION:
1335 					tomoyo_print_number_union_nospace
1336 						(head, numbers_p++);
1337 					break;
1338 				default:
1339 					tomoyo_set_string(head,
1340 					  tomoyo_condition_keyword[right]);
1341 					break;
1342 				}
1343 			}
1344 		}
1345 		head->r.cond_step++;
1346 		/* fall through */
1347 	case 2:
1348 		if (!tomoyo_flush(head))
1349 			break;
1350 		head->r.cond_step++;
1351 		/* fall through */
1352 	case 3:
1353 		if (cond->grant_log != TOMOYO_GRANTLOG_AUTO)
1354 			tomoyo_io_printf(head, " grant_log=%s",
1355 					 tomoyo_yesno(cond->grant_log ==
1356 						      TOMOYO_GRANTLOG_YES));
1357 		tomoyo_set_lf(head);
1358 		return true;
1359 	}
1360 	return false;
1361 }
1362 
1363 /**
1364  * tomoyo_set_group - Print "acl_group " header keyword and category name.
1365  *
1366  * @head:     Pointer to "struct tomoyo_io_buffer".
1367  * @category: Category name.
1368  *
1369  * Returns nothing.
1370  */
1371 static void tomoyo_set_group(struct tomoyo_io_buffer *head,
1372 			     const char *category)
1373 {
1374 	if (head->type == TOMOYO_EXCEPTIONPOLICY) {
1375 		tomoyo_print_namespace(head);
1376 		tomoyo_io_printf(head, "acl_group %u ",
1377 				 head->r.acl_group_index);
1378 	}
1379 	tomoyo_set_string(head, category);
1380 }
1381 
1382 /**
1383  * tomoyo_print_entry - Print an ACL entry.
1384  *
1385  * @head: Pointer to "struct tomoyo_io_buffer".
1386  * @acl:  Pointer to an ACL entry.
1387  *
1388  * Returns true on success, false otherwise.
1389  */
1390 static bool tomoyo_print_entry(struct tomoyo_io_buffer *head,
1391 			       struct tomoyo_acl_info *acl)
1392 {
1393 	const u8 acl_type = acl->type;
1394 	bool first = true;
1395 	u8 bit;
1396 
1397 	if (head->r.print_cond_part)
1398 		goto print_cond_part;
1399 	if (acl->is_deleted)
1400 		return true;
1401 	if (!tomoyo_flush(head))
1402 		return false;
1403 	else if (acl_type == TOMOYO_TYPE_PATH_ACL) {
1404 		struct tomoyo_path_acl *ptr =
1405 			container_of(acl, typeof(*ptr), head);
1406 		const u16 perm = ptr->perm;
1407 
1408 		for (bit = 0; bit < TOMOYO_MAX_PATH_OPERATION; bit++) {
1409 			if (!(perm & (1 << bit)))
1410 				continue;
1411 			if (head->r.print_transition_related_only &&
1412 			    bit != TOMOYO_TYPE_EXECUTE)
1413 				continue;
1414 			if (first) {
1415 				tomoyo_set_group(head, "file ");
1416 				first = false;
1417 			} else {
1418 				tomoyo_set_slash(head);
1419 			}
1420 			tomoyo_set_string(head, tomoyo_path_keyword[bit]);
1421 		}
1422 		if (first)
1423 			return true;
1424 		tomoyo_print_name_union(head, &ptr->name);
1425 	} else if (acl_type == TOMOYO_TYPE_MANUAL_TASK_ACL) {
1426 		struct tomoyo_task_acl *ptr =
1427 			container_of(acl, typeof(*ptr), head);
1428 
1429 		tomoyo_set_group(head, "task ");
1430 		tomoyo_set_string(head, "manual_domain_transition ");
1431 		tomoyo_set_string(head, ptr->domainname->name);
1432 	} else if (head->r.print_transition_related_only) {
1433 		return true;
1434 	} else if (acl_type == TOMOYO_TYPE_PATH2_ACL) {
1435 		struct tomoyo_path2_acl *ptr =
1436 			container_of(acl, typeof(*ptr), head);
1437 		const u8 perm = ptr->perm;
1438 
1439 		for (bit = 0; bit < TOMOYO_MAX_PATH2_OPERATION; bit++) {
1440 			if (!(perm & (1 << bit)))
1441 				continue;
1442 			if (first) {
1443 				tomoyo_set_group(head, "file ");
1444 				first = false;
1445 			} else {
1446 				tomoyo_set_slash(head);
1447 			}
1448 			tomoyo_set_string(head, tomoyo_mac_keywords
1449 					  [tomoyo_pp2mac[bit]]);
1450 		}
1451 		if (first)
1452 			return true;
1453 		tomoyo_print_name_union(head, &ptr->name1);
1454 		tomoyo_print_name_union(head, &ptr->name2);
1455 	} else if (acl_type == TOMOYO_TYPE_PATH_NUMBER_ACL) {
1456 		struct tomoyo_path_number_acl *ptr =
1457 			container_of(acl, typeof(*ptr), head);
1458 		const u8 perm = ptr->perm;
1459 
1460 		for (bit = 0; bit < TOMOYO_MAX_PATH_NUMBER_OPERATION; bit++) {
1461 			if (!(perm & (1 << bit)))
1462 				continue;
1463 			if (first) {
1464 				tomoyo_set_group(head, "file ");
1465 				first = false;
1466 			} else {
1467 				tomoyo_set_slash(head);
1468 			}
1469 			tomoyo_set_string(head, tomoyo_mac_keywords
1470 					  [tomoyo_pn2mac[bit]]);
1471 		}
1472 		if (first)
1473 			return true;
1474 		tomoyo_print_name_union(head, &ptr->name);
1475 		tomoyo_print_number_union(head, &ptr->number);
1476 	} else if (acl_type == TOMOYO_TYPE_MKDEV_ACL) {
1477 		struct tomoyo_mkdev_acl *ptr =
1478 			container_of(acl, typeof(*ptr), head);
1479 		const u8 perm = ptr->perm;
1480 
1481 		for (bit = 0; bit < TOMOYO_MAX_MKDEV_OPERATION; bit++) {
1482 			if (!(perm & (1 << bit)))
1483 				continue;
1484 			if (first) {
1485 				tomoyo_set_group(head, "file ");
1486 				first = false;
1487 			} else {
1488 				tomoyo_set_slash(head);
1489 			}
1490 			tomoyo_set_string(head, tomoyo_mac_keywords
1491 					  [tomoyo_pnnn2mac[bit]]);
1492 		}
1493 		if (first)
1494 			return true;
1495 		tomoyo_print_name_union(head, &ptr->name);
1496 		tomoyo_print_number_union(head, &ptr->mode);
1497 		tomoyo_print_number_union(head, &ptr->major);
1498 		tomoyo_print_number_union(head, &ptr->minor);
1499 	} else if (acl_type == TOMOYO_TYPE_INET_ACL) {
1500 		struct tomoyo_inet_acl *ptr =
1501 			container_of(acl, typeof(*ptr), head);
1502 		const u8 perm = ptr->perm;
1503 
1504 		for (bit = 0; bit < TOMOYO_MAX_NETWORK_OPERATION; bit++) {
1505 			if (!(perm & (1 << bit)))
1506 				continue;
1507 			if (first) {
1508 				tomoyo_set_group(head, "network inet ");
1509 				tomoyo_set_string(head, tomoyo_proto_keyword
1510 						  [ptr->protocol]);
1511 				tomoyo_set_space(head);
1512 				first = false;
1513 			} else {
1514 				tomoyo_set_slash(head);
1515 			}
1516 			tomoyo_set_string(head, tomoyo_socket_keyword[bit]);
1517 		}
1518 		if (first)
1519 			return true;
1520 		tomoyo_set_space(head);
1521 		if (ptr->address.group) {
1522 			tomoyo_set_string(head, "@");
1523 			tomoyo_set_string(head, ptr->address.group->group_name
1524 					  ->name);
1525 		} else {
1526 			char buf[128];
1527 
1528 			tomoyo_print_ip(buf, sizeof(buf), &ptr->address);
1529 			tomoyo_io_printf(head, "%s", buf);
1530 		}
1531 		tomoyo_print_number_union(head, &ptr->port);
1532 	} else if (acl_type == TOMOYO_TYPE_UNIX_ACL) {
1533 		struct tomoyo_unix_acl *ptr =
1534 			container_of(acl, typeof(*ptr), head);
1535 		const u8 perm = ptr->perm;
1536 
1537 		for (bit = 0; bit < TOMOYO_MAX_NETWORK_OPERATION; bit++) {
1538 			if (!(perm & (1 << bit)))
1539 				continue;
1540 			if (first) {
1541 				tomoyo_set_group(head, "network unix ");
1542 				tomoyo_set_string(head, tomoyo_proto_keyword
1543 						  [ptr->protocol]);
1544 				tomoyo_set_space(head);
1545 				first = false;
1546 			} else {
1547 				tomoyo_set_slash(head);
1548 			}
1549 			tomoyo_set_string(head, tomoyo_socket_keyword[bit]);
1550 		}
1551 		if (first)
1552 			return true;
1553 		tomoyo_print_name_union(head, &ptr->name);
1554 	} else if (acl_type == TOMOYO_TYPE_MOUNT_ACL) {
1555 		struct tomoyo_mount_acl *ptr =
1556 			container_of(acl, typeof(*ptr), head);
1557 
1558 		tomoyo_set_group(head, "file mount");
1559 		tomoyo_print_name_union(head, &ptr->dev_name);
1560 		tomoyo_print_name_union(head, &ptr->dir_name);
1561 		tomoyo_print_name_union(head, &ptr->fs_type);
1562 		tomoyo_print_number_union(head, &ptr->flags);
1563 	} else if (acl_type == TOMOYO_TYPE_ENV_ACL) {
1564 		struct tomoyo_env_acl *ptr =
1565 			container_of(acl, typeof(*ptr), head);
1566 
1567 		tomoyo_set_group(head, "misc env ");
1568 		tomoyo_set_string(head, ptr->env->name);
1569 	}
1570 	if (acl->cond) {
1571 		head->r.print_cond_part = true;
1572 		head->r.cond_step = 0;
1573 		if (!tomoyo_flush(head))
1574 			return false;
1575 print_cond_part:
1576 		if (!tomoyo_print_condition(head, acl->cond))
1577 			return false;
1578 		head->r.print_cond_part = false;
1579 	} else {
1580 		tomoyo_set_lf(head);
1581 	}
1582 	return true;
1583 }
1584 
1585 /**
1586  * tomoyo_read_domain2 - Read domain policy.
1587  *
1588  * @head: Pointer to "struct tomoyo_io_buffer".
1589  * @list: Pointer to "struct list_head".
1590  *
1591  * Caller holds tomoyo_read_lock().
1592  *
1593  * Returns true on success, false otherwise.
1594  */
1595 static bool tomoyo_read_domain2(struct tomoyo_io_buffer *head,
1596 				struct list_head *list)
1597 {
1598 	list_for_each_cookie(head->r.acl, list) {
1599 		struct tomoyo_acl_info *ptr =
1600 			list_entry(head->r.acl, typeof(*ptr), list);
1601 
1602 		if (!tomoyo_print_entry(head, ptr))
1603 			return false;
1604 	}
1605 	head->r.acl = NULL;
1606 	return true;
1607 }
1608 
1609 /**
1610  * tomoyo_read_domain - Read domain policy.
1611  *
1612  * @head: Pointer to "struct tomoyo_io_buffer".
1613  *
1614  * Caller holds tomoyo_read_lock().
1615  */
1616 static void tomoyo_read_domain(struct tomoyo_io_buffer *head)
1617 {
1618 	if (head->r.eof)
1619 		return;
1620 	list_for_each_cookie(head->r.domain, &tomoyo_domain_list) {
1621 		struct tomoyo_domain_info *domain =
1622 			list_entry(head->r.domain, typeof(*domain), list);
1623 		u8 i;
1624 
1625 		switch (head->r.step) {
1626 		case 0:
1627 			if (domain->is_deleted &&
1628 			    !head->r.print_this_domain_only)
1629 				continue;
1630 			/* Print domainname and flags. */
1631 			tomoyo_set_string(head, domain->domainname->name);
1632 			tomoyo_set_lf(head);
1633 			tomoyo_io_printf(head, "use_profile %u\n",
1634 					 domain->profile);
1635 			for (i = 0; i < TOMOYO_MAX_DOMAIN_INFO_FLAGS; i++)
1636 				if (domain->flags[i])
1637 					tomoyo_set_string(head, tomoyo_dif[i]);
1638 			head->r.index = 0;
1639 			head->r.step++;
1640 			/* fall through */
1641 		case 1:
1642 			while (head->r.index < TOMOYO_MAX_ACL_GROUPS) {
1643 				i = head->r.index++;
1644 				if (!test_bit(i, domain->group))
1645 					continue;
1646 				tomoyo_io_printf(head, "use_group %u\n", i);
1647 				if (!tomoyo_flush(head))
1648 					return;
1649 			}
1650 			head->r.index = 0;
1651 			head->r.step++;
1652 			tomoyo_set_lf(head);
1653 			/* fall through */
1654 		case 2:
1655 			if (!tomoyo_read_domain2(head, &domain->acl_info_list))
1656 				return;
1657 			head->r.step++;
1658 			if (!tomoyo_set_lf(head))
1659 				return;
1660 			/* fall through */
1661 		case 3:
1662 			head->r.step = 0;
1663 			if (head->r.print_this_domain_only)
1664 				goto done;
1665 		}
1666 	}
1667  done:
1668 	head->r.eof = true;
1669 }
1670 
1671 /**
1672  * tomoyo_write_pid: Specify PID to obtain domainname.
1673  *
1674  * @head: Pointer to "struct tomoyo_io_buffer".
1675  *
1676  * Returns 0.
1677  */
1678 static int tomoyo_write_pid(struct tomoyo_io_buffer *head)
1679 {
1680 	head->r.eof = false;
1681 	return 0;
1682 }
1683 
1684 /**
1685  * tomoyo_read_pid - Get domainname of the specified PID.
1686  *
1687  * @head: Pointer to "struct tomoyo_io_buffer".
1688  *
1689  * Returns the domainname which the specified PID is in on success,
1690  * empty string otherwise.
1691  * The PID is specified by tomoyo_write_pid() so that the user can obtain
1692  * using read()/write() interface rather than sysctl() interface.
1693  */
1694 static void tomoyo_read_pid(struct tomoyo_io_buffer *head)
1695 {
1696 	char *buf = head->write_buf;
1697 	bool global_pid = false;
1698 	unsigned int pid;
1699 	struct task_struct *p;
1700 	struct tomoyo_domain_info *domain = NULL;
1701 
1702 	/* Accessing write_buf is safe because head->io_sem is held. */
1703 	if (!buf) {
1704 		head->r.eof = true;
1705 		return; /* Do nothing if open(O_RDONLY). */
1706 	}
1707 	if (head->r.w_pos || head->r.eof)
1708 		return;
1709 	head->r.eof = true;
1710 	if (tomoyo_str_starts(&buf, "global-pid "))
1711 		global_pid = true;
1712 	if (kstrtouint(buf, 10, &pid))
1713 		return;
1714 	rcu_read_lock();
1715 	if (global_pid)
1716 		p = find_task_by_pid_ns(pid, &init_pid_ns);
1717 	else
1718 		p = find_task_by_vpid(pid);
1719 	if (p)
1720 		domain = tomoyo_task(p)->domain_info;
1721 	rcu_read_unlock();
1722 	if (!domain)
1723 		return;
1724 	tomoyo_io_printf(head, "%u %u ", pid, domain->profile);
1725 	tomoyo_set_string(head, domain->domainname->name);
1726 }
1727 
1728 /* String table for domain transition control keywords. */
1729 static const char *tomoyo_transition_type[TOMOYO_MAX_TRANSITION_TYPE] = {
1730 	[TOMOYO_TRANSITION_CONTROL_NO_RESET]      = "no_reset_domain ",
1731 	[TOMOYO_TRANSITION_CONTROL_RESET]         = "reset_domain ",
1732 	[TOMOYO_TRANSITION_CONTROL_NO_INITIALIZE] = "no_initialize_domain ",
1733 	[TOMOYO_TRANSITION_CONTROL_INITIALIZE]    = "initialize_domain ",
1734 	[TOMOYO_TRANSITION_CONTROL_NO_KEEP]       = "no_keep_domain ",
1735 	[TOMOYO_TRANSITION_CONTROL_KEEP]          = "keep_domain ",
1736 };
1737 
1738 /* String table for grouping keywords. */
1739 static const char *tomoyo_group_name[TOMOYO_MAX_GROUP] = {
1740 	[TOMOYO_PATH_GROUP]    = "path_group ",
1741 	[TOMOYO_NUMBER_GROUP]  = "number_group ",
1742 	[TOMOYO_ADDRESS_GROUP] = "address_group ",
1743 };
1744 
1745 /**
1746  * tomoyo_write_exception - Write exception policy.
1747  *
1748  * @head: Pointer to "struct tomoyo_io_buffer".
1749  *
1750  * Returns 0 on success, negative value otherwise.
1751  *
1752  * Caller holds tomoyo_read_lock().
1753  */
1754 static int tomoyo_write_exception(struct tomoyo_io_buffer *head)
1755 {
1756 	const bool is_delete = head->w.is_delete;
1757 	struct tomoyo_acl_param param = {
1758 		.ns = head->w.ns,
1759 		.is_delete = is_delete,
1760 		.data = head->write_buf,
1761 	};
1762 	u8 i;
1763 
1764 	if (tomoyo_str_starts(&param.data, "aggregator "))
1765 		return tomoyo_write_aggregator(&param);
1766 	for (i = 0; i < TOMOYO_MAX_TRANSITION_TYPE; i++)
1767 		if (tomoyo_str_starts(&param.data, tomoyo_transition_type[i]))
1768 			return tomoyo_write_transition_control(&param, i);
1769 	for (i = 0; i < TOMOYO_MAX_GROUP; i++)
1770 		if (tomoyo_str_starts(&param.data, tomoyo_group_name[i]))
1771 			return tomoyo_write_group(&param, i);
1772 	if (tomoyo_str_starts(&param.data, "acl_group ")) {
1773 		unsigned int group;
1774 		char *data;
1775 
1776 		group = simple_strtoul(param.data, &data, 10);
1777 		if (group < TOMOYO_MAX_ACL_GROUPS && *data++ == ' ')
1778 			return tomoyo_write_domain2
1779 				(head->w.ns, &head->w.ns->acl_group[group],
1780 				 data, is_delete);
1781 	}
1782 	return -EINVAL;
1783 }
1784 
1785 /**
1786  * tomoyo_read_group - Read "struct tomoyo_path_group"/"struct tomoyo_number_group"/"struct tomoyo_address_group" list.
1787  *
1788  * @head: Pointer to "struct tomoyo_io_buffer".
1789  * @idx:  Index number.
1790  *
1791  * Returns true on success, false otherwise.
1792  *
1793  * Caller holds tomoyo_read_lock().
1794  */
1795 static bool tomoyo_read_group(struct tomoyo_io_buffer *head, const int idx)
1796 {
1797 	struct tomoyo_policy_namespace *ns =
1798 		container_of(head->r.ns, typeof(*ns), namespace_list);
1799 	struct list_head *list = &ns->group_list[idx];
1800 
1801 	list_for_each_cookie(head->r.group, list) {
1802 		struct tomoyo_group *group =
1803 			list_entry(head->r.group, typeof(*group), head.list);
1804 
1805 		list_for_each_cookie(head->r.acl, &group->member_list) {
1806 			struct tomoyo_acl_head *ptr =
1807 				list_entry(head->r.acl, typeof(*ptr), list);
1808 
1809 			if (ptr->is_deleted)
1810 				continue;
1811 			if (!tomoyo_flush(head))
1812 				return false;
1813 			tomoyo_print_namespace(head);
1814 			tomoyo_set_string(head, tomoyo_group_name[idx]);
1815 			tomoyo_set_string(head, group->group_name->name);
1816 			if (idx == TOMOYO_PATH_GROUP) {
1817 				tomoyo_set_space(head);
1818 				tomoyo_set_string(head, container_of
1819 					       (ptr, struct tomoyo_path_group,
1820 						head)->member_name->name);
1821 			} else if (idx == TOMOYO_NUMBER_GROUP) {
1822 				tomoyo_print_number_union(head, &container_of
1823 							  (ptr,
1824 						   struct tomoyo_number_group,
1825 							   head)->number);
1826 			} else if (idx == TOMOYO_ADDRESS_GROUP) {
1827 				char buffer[128];
1828 				struct tomoyo_address_group *member =
1829 					container_of(ptr, typeof(*member),
1830 						     head);
1831 
1832 				tomoyo_print_ip(buffer, sizeof(buffer),
1833 						&member->address);
1834 				tomoyo_io_printf(head, " %s", buffer);
1835 			}
1836 			tomoyo_set_lf(head);
1837 		}
1838 		head->r.acl = NULL;
1839 	}
1840 	head->r.group = NULL;
1841 	return true;
1842 }
1843 
1844 /**
1845  * tomoyo_read_policy - Read "struct tomoyo_..._entry" list.
1846  *
1847  * @head: Pointer to "struct tomoyo_io_buffer".
1848  * @idx:  Index number.
1849  *
1850  * Returns true on success, false otherwise.
1851  *
1852  * Caller holds tomoyo_read_lock().
1853  */
1854 static bool tomoyo_read_policy(struct tomoyo_io_buffer *head, const int idx)
1855 {
1856 	struct tomoyo_policy_namespace *ns =
1857 		container_of(head->r.ns, typeof(*ns), namespace_list);
1858 	struct list_head *list = &ns->policy_list[idx];
1859 
1860 	list_for_each_cookie(head->r.acl, list) {
1861 		struct tomoyo_acl_head *acl =
1862 			container_of(head->r.acl, typeof(*acl), list);
1863 		if (acl->is_deleted)
1864 			continue;
1865 		if (!tomoyo_flush(head))
1866 			return false;
1867 		switch (idx) {
1868 		case TOMOYO_ID_TRANSITION_CONTROL:
1869 			{
1870 				struct tomoyo_transition_control *ptr =
1871 					container_of(acl, typeof(*ptr), head);
1872 
1873 				tomoyo_print_namespace(head);
1874 				tomoyo_set_string(head, tomoyo_transition_type
1875 						  [ptr->type]);
1876 				tomoyo_set_string(head, ptr->program ?
1877 						  ptr->program->name : "any");
1878 				tomoyo_set_string(head, " from ");
1879 				tomoyo_set_string(head, ptr->domainname ?
1880 						  ptr->domainname->name :
1881 						  "any");
1882 			}
1883 			break;
1884 		case TOMOYO_ID_AGGREGATOR:
1885 			{
1886 				struct tomoyo_aggregator *ptr =
1887 					container_of(acl, typeof(*ptr), head);
1888 
1889 				tomoyo_print_namespace(head);
1890 				tomoyo_set_string(head, "aggregator ");
1891 				tomoyo_set_string(head,
1892 						  ptr->original_name->name);
1893 				tomoyo_set_space(head);
1894 				tomoyo_set_string(head,
1895 					       ptr->aggregated_name->name);
1896 			}
1897 			break;
1898 		default:
1899 			continue;
1900 		}
1901 		tomoyo_set_lf(head);
1902 	}
1903 	head->r.acl = NULL;
1904 	return true;
1905 }
1906 
1907 /**
1908  * tomoyo_read_exception - Read exception policy.
1909  *
1910  * @head: Pointer to "struct tomoyo_io_buffer".
1911  *
1912  * Caller holds tomoyo_read_lock().
1913  */
1914 static void tomoyo_read_exception(struct tomoyo_io_buffer *head)
1915 {
1916 	struct tomoyo_policy_namespace *ns =
1917 		container_of(head->r.ns, typeof(*ns), namespace_list);
1918 
1919 	if (head->r.eof)
1920 		return;
1921 	while (head->r.step < TOMOYO_MAX_POLICY &&
1922 	       tomoyo_read_policy(head, head->r.step))
1923 		head->r.step++;
1924 	if (head->r.step < TOMOYO_MAX_POLICY)
1925 		return;
1926 	while (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP &&
1927 	       tomoyo_read_group(head, head->r.step - TOMOYO_MAX_POLICY))
1928 		head->r.step++;
1929 	if (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP)
1930 		return;
1931 	while (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP
1932 	       + TOMOYO_MAX_ACL_GROUPS) {
1933 		head->r.acl_group_index = head->r.step - TOMOYO_MAX_POLICY
1934 			- TOMOYO_MAX_GROUP;
1935 		if (!tomoyo_read_domain2(head, &ns->acl_group
1936 					 [head->r.acl_group_index]))
1937 			return;
1938 		head->r.step++;
1939 	}
1940 	head->r.eof = true;
1941 }
1942 
1943 /* Wait queue for kernel -> userspace notification. */
1944 static DECLARE_WAIT_QUEUE_HEAD(tomoyo_query_wait);
1945 /* Wait queue for userspace -> kernel notification. */
1946 static DECLARE_WAIT_QUEUE_HEAD(tomoyo_answer_wait);
1947 
1948 /* Structure for query. */
1949 struct tomoyo_query {
1950 	struct list_head list;
1951 	struct tomoyo_domain_info *domain;
1952 	char *query;
1953 	size_t query_len;
1954 	unsigned int serial;
1955 	u8 timer;
1956 	u8 answer;
1957 	u8 retry;
1958 };
1959 
1960 /* The list for "struct tomoyo_query". */
1961 static LIST_HEAD(tomoyo_query_list);
1962 
1963 /* Lock for manipulating tomoyo_query_list. */
1964 static DEFINE_SPINLOCK(tomoyo_query_list_lock);
1965 
1966 /*
1967  * Number of "struct file" referring /sys/kernel/security/tomoyo/query
1968  * interface.
1969  */
1970 static atomic_t tomoyo_query_observers = ATOMIC_INIT(0);
1971 
1972 /**
1973  * tomoyo_truncate - Truncate a line.
1974  *
1975  * @str: String to truncate.
1976  *
1977  * Returns length of truncated @str.
1978  */
1979 static int tomoyo_truncate(char *str)
1980 {
1981 	char *start = str;
1982 
1983 	while (*(unsigned char *) str > (unsigned char) ' ')
1984 		str++;
1985 	*str = '\0';
1986 	return strlen(start) + 1;
1987 }
1988 
1989 /**
1990  * tomoyo_add_entry - Add an ACL to current thread's domain. Used by learning mode.
1991  *
1992  * @domain: Pointer to "struct tomoyo_domain_info".
1993  * @header: Lines containing ACL.
1994  *
1995  * Returns nothing.
1996  */
1997 static void tomoyo_add_entry(struct tomoyo_domain_info *domain, char *header)
1998 {
1999 	char *buffer;
2000 	char *realpath = NULL;
2001 	char *argv0 = NULL;
2002 	char *symlink = NULL;
2003 	char *cp = strchr(header, '\n');
2004 	int len;
2005 
2006 	if (!cp)
2007 		return;
2008 	cp = strchr(cp + 1, '\n');
2009 	if (!cp)
2010 		return;
2011 	*cp++ = '\0';
2012 	len = strlen(cp) + 1;
2013 	/* strstr() will return NULL if ordering is wrong. */
2014 	if (*cp == 'f') {
2015 		argv0 = strstr(header, " argv[]={ \"");
2016 		if (argv0) {
2017 			argv0 += 10;
2018 			len += tomoyo_truncate(argv0) + 14;
2019 		}
2020 		realpath = strstr(header, " exec={ realpath=\"");
2021 		if (realpath) {
2022 			realpath += 8;
2023 			len += tomoyo_truncate(realpath) + 6;
2024 		}
2025 		symlink = strstr(header, " symlink.target=\"");
2026 		if (symlink)
2027 			len += tomoyo_truncate(symlink + 1) + 1;
2028 	}
2029 	buffer = kmalloc(len, GFP_NOFS);
2030 	if (!buffer)
2031 		return;
2032 	snprintf(buffer, len - 1, "%s", cp);
2033 	if (realpath)
2034 		tomoyo_addprintf(buffer, len, " exec.%s", realpath);
2035 	if (argv0)
2036 		tomoyo_addprintf(buffer, len, " exec.argv[0]=%s", argv0);
2037 	if (symlink)
2038 		tomoyo_addprintf(buffer, len, "%s", symlink);
2039 	tomoyo_normalize_line(buffer);
2040 	if (!tomoyo_write_domain2(domain->ns, &domain->acl_info_list, buffer,
2041 				  false))
2042 		tomoyo_update_stat(TOMOYO_STAT_POLICY_UPDATES);
2043 	kfree(buffer);
2044 }
2045 
2046 /**
2047  * tomoyo_supervisor - Ask for the supervisor's decision.
2048  *
2049  * @r:   Pointer to "struct tomoyo_request_info".
2050  * @fmt: The printf()'s format string, followed by parameters.
2051  *
2052  * Returns 0 if the supervisor decided to permit the access request which
2053  * violated the policy in enforcing mode, TOMOYO_RETRY_REQUEST if the
2054  * supervisor decided to retry the access request which violated the policy in
2055  * enforcing mode, 0 if it is not in enforcing mode, -EPERM otherwise.
2056  */
2057 int tomoyo_supervisor(struct tomoyo_request_info *r, const char *fmt, ...)
2058 {
2059 	va_list args;
2060 	int error;
2061 	int len;
2062 	static unsigned int tomoyo_serial;
2063 	struct tomoyo_query entry = { };
2064 	bool quota_exceeded = false;
2065 
2066 	va_start(args, fmt);
2067 	len = vsnprintf((char *) &len, 1, fmt, args) + 1;
2068 	va_end(args);
2069 	/* Write /sys/kernel/security/tomoyo/audit. */
2070 	va_start(args, fmt);
2071 	tomoyo_write_log2(r, len, fmt, args);
2072 	va_end(args);
2073 	/* Nothing more to do if granted. */
2074 	if (r->granted)
2075 		return 0;
2076 	if (r->mode)
2077 		tomoyo_update_stat(r->mode);
2078 	switch (r->mode) {
2079 	case TOMOYO_CONFIG_ENFORCING:
2080 		error = -EPERM;
2081 		if (atomic_read(&tomoyo_query_observers))
2082 			break;
2083 		goto out;
2084 	case TOMOYO_CONFIG_LEARNING:
2085 		error = 0;
2086 		/* Check max_learning_entry parameter. */
2087 		if (tomoyo_domain_quota_is_ok(r))
2088 			break;
2089 		/* fall through */
2090 	default:
2091 		return 0;
2092 	}
2093 	/* Get message. */
2094 	va_start(args, fmt);
2095 	entry.query = tomoyo_init_log(r, len, fmt, args);
2096 	va_end(args);
2097 	if (!entry.query)
2098 		goto out;
2099 	entry.query_len = strlen(entry.query) + 1;
2100 	if (!error) {
2101 		tomoyo_add_entry(r->domain, entry.query);
2102 		goto out;
2103 	}
2104 	len = tomoyo_round2(entry.query_len);
2105 	entry.domain = r->domain;
2106 	spin_lock(&tomoyo_query_list_lock);
2107 	if (tomoyo_memory_quota[TOMOYO_MEMORY_QUERY] &&
2108 	    tomoyo_memory_used[TOMOYO_MEMORY_QUERY] + len
2109 	    >= tomoyo_memory_quota[TOMOYO_MEMORY_QUERY]) {
2110 		quota_exceeded = true;
2111 	} else {
2112 		entry.serial = tomoyo_serial++;
2113 		entry.retry = r->retry;
2114 		tomoyo_memory_used[TOMOYO_MEMORY_QUERY] += len;
2115 		list_add_tail(&entry.list, &tomoyo_query_list);
2116 	}
2117 	spin_unlock(&tomoyo_query_list_lock);
2118 	if (quota_exceeded)
2119 		goto out;
2120 	/* Give 10 seconds for supervisor's opinion. */
2121 	while (entry.timer < 10) {
2122 		wake_up_all(&tomoyo_query_wait);
2123 		if (wait_event_interruptible_timeout
2124 		    (tomoyo_answer_wait, entry.answer ||
2125 		     !atomic_read(&tomoyo_query_observers), HZ))
2126 			break;
2127 		entry.timer++;
2128 	}
2129 	spin_lock(&tomoyo_query_list_lock);
2130 	list_del(&entry.list);
2131 	tomoyo_memory_used[TOMOYO_MEMORY_QUERY] -= len;
2132 	spin_unlock(&tomoyo_query_list_lock);
2133 	switch (entry.answer) {
2134 	case 3: /* Asked to retry by administrator. */
2135 		error = TOMOYO_RETRY_REQUEST;
2136 		r->retry++;
2137 		break;
2138 	case 1:
2139 		/* Granted by administrator. */
2140 		error = 0;
2141 		break;
2142 	default:
2143 		/* Timed out or rejected by administrator. */
2144 		break;
2145 	}
2146 out:
2147 	kfree(entry.query);
2148 	return error;
2149 }
2150 
2151 /**
2152  * tomoyo_find_domain_by_qid - Get domain by query id.
2153  *
2154  * @serial: Query ID assigned by tomoyo_supervisor().
2155  *
2156  * Returns pointer to "struct tomoyo_domain_info" if found, NULL otherwise.
2157  */
2158 static struct tomoyo_domain_info *tomoyo_find_domain_by_qid
2159 (unsigned int serial)
2160 {
2161 	struct tomoyo_query *ptr;
2162 	struct tomoyo_domain_info *domain = NULL;
2163 
2164 	spin_lock(&tomoyo_query_list_lock);
2165 	list_for_each_entry(ptr, &tomoyo_query_list, list) {
2166 		if (ptr->serial != serial)
2167 			continue;
2168 		domain = ptr->domain;
2169 		break;
2170 	}
2171 	spin_unlock(&tomoyo_query_list_lock);
2172 	return domain;
2173 }
2174 
2175 /**
2176  * tomoyo_poll_query - poll() for /sys/kernel/security/tomoyo/query.
2177  *
2178  * @file: Pointer to "struct file".
2179  * @wait: Pointer to "poll_table".
2180  *
2181  * Returns EPOLLIN | EPOLLRDNORM when ready to read, 0 otherwise.
2182  *
2183  * Waits for access requests which violated policy in enforcing mode.
2184  */
2185 static __poll_t tomoyo_poll_query(struct file *file, poll_table *wait)
2186 {
2187 	if (!list_empty(&tomoyo_query_list))
2188 		return EPOLLIN | EPOLLRDNORM;
2189 	poll_wait(file, &tomoyo_query_wait, wait);
2190 	if (!list_empty(&tomoyo_query_list))
2191 		return EPOLLIN | EPOLLRDNORM;
2192 	return 0;
2193 }
2194 
2195 /**
2196  * tomoyo_read_query - Read access requests which violated policy in enforcing mode.
2197  *
2198  * @head: Pointer to "struct tomoyo_io_buffer".
2199  */
2200 static void tomoyo_read_query(struct tomoyo_io_buffer *head)
2201 {
2202 	struct list_head *tmp;
2203 	unsigned int pos = 0;
2204 	size_t len = 0;
2205 	char *buf;
2206 
2207 	if (head->r.w_pos)
2208 		return;
2209 	kfree(head->read_buf);
2210 	head->read_buf = NULL;
2211 	spin_lock(&tomoyo_query_list_lock);
2212 	list_for_each(tmp, &tomoyo_query_list) {
2213 		struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
2214 
2215 		if (pos++ != head->r.query_index)
2216 			continue;
2217 		len = ptr->query_len;
2218 		break;
2219 	}
2220 	spin_unlock(&tomoyo_query_list_lock);
2221 	if (!len) {
2222 		head->r.query_index = 0;
2223 		return;
2224 	}
2225 	buf = kzalloc(len + 32, GFP_NOFS);
2226 	if (!buf)
2227 		return;
2228 	pos = 0;
2229 	spin_lock(&tomoyo_query_list_lock);
2230 	list_for_each(tmp, &tomoyo_query_list) {
2231 		struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
2232 
2233 		if (pos++ != head->r.query_index)
2234 			continue;
2235 		/*
2236 		 * Some query can be skipped because tomoyo_query_list
2237 		 * can change, but I don't care.
2238 		 */
2239 		if (len == ptr->query_len)
2240 			snprintf(buf, len + 31, "Q%u-%hu\n%s", ptr->serial,
2241 				 ptr->retry, ptr->query);
2242 		break;
2243 	}
2244 	spin_unlock(&tomoyo_query_list_lock);
2245 	if (buf[0]) {
2246 		head->read_buf = buf;
2247 		head->r.w[head->r.w_pos++] = buf;
2248 		head->r.query_index++;
2249 	} else {
2250 		kfree(buf);
2251 	}
2252 }
2253 
2254 /**
2255  * tomoyo_write_answer - Write the supervisor's decision.
2256  *
2257  * @head: Pointer to "struct tomoyo_io_buffer".
2258  *
2259  * Returns 0 on success, -EINVAL otherwise.
2260  */
2261 static int tomoyo_write_answer(struct tomoyo_io_buffer *head)
2262 {
2263 	char *data = head->write_buf;
2264 	struct list_head *tmp;
2265 	unsigned int serial;
2266 	unsigned int answer;
2267 
2268 	spin_lock(&tomoyo_query_list_lock);
2269 	list_for_each(tmp, &tomoyo_query_list) {
2270 		struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
2271 
2272 		ptr->timer = 0;
2273 	}
2274 	spin_unlock(&tomoyo_query_list_lock);
2275 	if (sscanf(data, "A%u=%u", &serial, &answer) != 2)
2276 		return -EINVAL;
2277 	spin_lock(&tomoyo_query_list_lock);
2278 	list_for_each(tmp, &tomoyo_query_list) {
2279 		struct tomoyo_query *ptr = list_entry(tmp, typeof(*ptr), list);
2280 
2281 		if (ptr->serial != serial)
2282 			continue;
2283 		ptr->answer = answer;
2284 		/* Remove from tomoyo_query_list. */
2285 		if (ptr->answer)
2286 			list_del_init(&ptr->list);
2287 		break;
2288 	}
2289 	spin_unlock(&tomoyo_query_list_lock);
2290 	return 0;
2291 }
2292 
2293 /**
2294  * tomoyo_read_version: Get version.
2295  *
2296  * @head: Pointer to "struct tomoyo_io_buffer".
2297  *
2298  * Returns version information.
2299  */
2300 static void tomoyo_read_version(struct tomoyo_io_buffer *head)
2301 {
2302 	if (!head->r.eof) {
2303 		tomoyo_io_printf(head, "2.6.0");
2304 		head->r.eof = true;
2305 	}
2306 }
2307 
2308 /* String table for /sys/kernel/security/tomoyo/stat interface. */
2309 static const char * const tomoyo_policy_headers[TOMOYO_MAX_POLICY_STAT] = {
2310 	[TOMOYO_STAT_POLICY_UPDATES]    = "update:",
2311 	[TOMOYO_STAT_POLICY_LEARNING]   = "violation in learning mode:",
2312 	[TOMOYO_STAT_POLICY_PERMISSIVE] = "violation in permissive mode:",
2313 	[TOMOYO_STAT_POLICY_ENFORCING]  = "violation in enforcing mode:",
2314 };
2315 
2316 /* String table for /sys/kernel/security/tomoyo/stat interface. */
2317 static const char * const tomoyo_memory_headers[TOMOYO_MAX_MEMORY_STAT] = {
2318 	[TOMOYO_MEMORY_POLICY] = "policy:",
2319 	[TOMOYO_MEMORY_AUDIT]  = "audit log:",
2320 	[TOMOYO_MEMORY_QUERY]  = "query message:",
2321 };
2322 
2323 /* Timestamp counter for last updated. */
2324 static unsigned int tomoyo_stat_updated[TOMOYO_MAX_POLICY_STAT];
2325 /* Counter for number of updates. */
2326 static time64_t tomoyo_stat_modified[TOMOYO_MAX_POLICY_STAT];
2327 
2328 /**
2329  * tomoyo_update_stat - Update statistic counters.
2330  *
2331  * @index: Index for policy type.
2332  *
2333  * Returns nothing.
2334  */
2335 void tomoyo_update_stat(const u8 index)
2336 {
2337 	/*
2338 	 * I don't use atomic operations because race condition is not fatal.
2339 	 */
2340 	tomoyo_stat_updated[index]++;
2341 	tomoyo_stat_modified[index] = ktime_get_real_seconds();
2342 }
2343 
2344 /**
2345  * tomoyo_read_stat - Read statistic data.
2346  *
2347  * @head: Pointer to "struct tomoyo_io_buffer".
2348  *
2349  * Returns nothing.
2350  */
2351 static void tomoyo_read_stat(struct tomoyo_io_buffer *head)
2352 {
2353 	u8 i;
2354 	unsigned int total = 0;
2355 
2356 	if (head->r.eof)
2357 		return;
2358 	for (i = 0; i < TOMOYO_MAX_POLICY_STAT; i++) {
2359 		tomoyo_io_printf(head, "Policy %-30s %10u",
2360 				 tomoyo_policy_headers[i],
2361 				 tomoyo_stat_updated[i]);
2362 		if (tomoyo_stat_modified[i]) {
2363 			struct tomoyo_time stamp;
2364 
2365 			tomoyo_convert_time(tomoyo_stat_modified[i], &stamp);
2366 			tomoyo_io_printf(head, " (Last: %04u/%02u/%02u %02u:%02u:%02u)",
2367 					 stamp.year, stamp.month, stamp.day,
2368 					 stamp.hour, stamp.min, stamp.sec);
2369 		}
2370 		tomoyo_set_lf(head);
2371 	}
2372 	for (i = 0; i < TOMOYO_MAX_MEMORY_STAT; i++) {
2373 		unsigned int used = tomoyo_memory_used[i];
2374 
2375 		total += used;
2376 		tomoyo_io_printf(head, "Memory used by %-22s %10u",
2377 				 tomoyo_memory_headers[i], used);
2378 		used = tomoyo_memory_quota[i];
2379 		if (used)
2380 			tomoyo_io_printf(head, " (Quota: %10u)", used);
2381 		tomoyo_set_lf(head);
2382 	}
2383 	tomoyo_io_printf(head, "Total memory used:                    %10u\n",
2384 			 total);
2385 	head->r.eof = true;
2386 }
2387 
2388 /**
2389  * tomoyo_write_stat - Set memory quota.
2390  *
2391  * @head: Pointer to "struct tomoyo_io_buffer".
2392  *
2393  * Returns 0.
2394  */
2395 static int tomoyo_write_stat(struct tomoyo_io_buffer *head)
2396 {
2397 	char *data = head->write_buf;
2398 	u8 i;
2399 
2400 	if (tomoyo_str_starts(&data, "Memory used by "))
2401 		for (i = 0; i < TOMOYO_MAX_MEMORY_STAT; i++)
2402 			if (tomoyo_str_starts(&data, tomoyo_memory_headers[i]))
2403 				sscanf(data, "%u", &tomoyo_memory_quota[i]);
2404 	return 0;
2405 }
2406 
2407 /**
2408  * tomoyo_open_control - open() for /sys/kernel/security/tomoyo/ interface.
2409  *
2410  * @type: Type of interface.
2411  * @file: Pointer to "struct file".
2412  *
2413  * Returns 0 on success, negative value otherwise.
2414  */
2415 int tomoyo_open_control(const u8 type, struct file *file)
2416 {
2417 	struct tomoyo_io_buffer *head = kzalloc(sizeof(*head), GFP_NOFS);
2418 
2419 	if (!head)
2420 		return -ENOMEM;
2421 	mutex_init(&head->io_sem);
2422 	head->type = type;
2423 	switch (type) {
2424 	case TOMOYO_DOMAINPOLICY:
2425 		/* /sys/kernel/security/tomoyo/domain_policy */
2426 		head->write = tomoyo_write_domain;
2427 		head->read = tomoyo_read_domain;
2428 		break;
2429 	case TOMOYO_EXCEPTIONPOLICY:
2430 		/* /sys/kernel/security/tomoyo/exception_policy */
2431 		head->write = tomoyo_write_exception;
2432 		head->read = tomoyo_read_exception;
2433 		break;
2434 	case TOMOYO_AUDIT:
2435 		/* /sys/kernel/security/tomoyo/audit */
2436 		head->poll = tomoyo_poll_log;
2437 		head->read = tomoyo_read_log;
2438 		break;
2439 	case TOMOYO_PROCESS_STATUS:
2440 		/* /sys/kernel/security/tomoyo/.process_status */
2441 		head->write = tomoyo_write_pid;
2442 		head->read = tomoyo_read_pid;
2443 		break;
2444 	case TOMOYO_VERSION:
2445 		/* /sys/kernel/security/tomoyo/version */
2446 		head->read = tomoyo_read_version;
2447 		head->readbuf_size = 128;
2448 		break;
2449 	case TOMOYO_STAT:
2450 		/* /sys/kernel/security/tomoyo/stat */
2451 		head->write = tomoyo_write_stat;
2452 		head->read = tomoyo_read_stat;
2453 		head->readbuf_size = 1024;
2454 		break;
2455 	case TOMOYO_PROFILE:
2456 		/* /sys/kernel/security/tomoyo/profile */
2457 		head->write = tomoyo_write_profile;
2458 		head->read = tomoyo_read_profile;
2459 		break;
2460 	case TOMOYO_QUERY: /* /sys/kernel/security/tomoyo/query */
2461 		head->poll = tomoyo_poll_query;
2462 		head->write = tomoyo_write_answer;
2463 		head->read = tomoyo_read_query;
2464 		break;
2465 	case TOMOYO_MANAGER:
2466 		/* /sys/kernel/security/tomoyo/manager */
2467 		head->write = tomoyo_write_manager;
2468 		head->read = tomoyo_read_manager;
2469 		break;
2470 	}
2471 	if (!(file->f_mode & FMODE_READ)) {
2472 		/*
2473 		 * No need to allocate read_buf since it is not opened
2474 		 * for reading.
2475 		 */
2476 		head->read = NULL;
2477 		head->poll = NULL;
2478 	} else if (!head->poll) {
2479 		/* Don't allocate read_buf for poll() access. */
2480 		if (!head->readbuf_size)
2481 			head->readbuf_size = 4096 * 2;
2482 		head->read_buf = kzalloc(head->readbuf_size, GFP_NOFS);
2483 		if (!head->read_buf) {
2484 			kfree(head);
2485 			return -ENOMEM;
2486 		}
2487 	}
2488 	if (!(file->f_mode & FMODE_WRITE)) {
2489 		/*
2490 		 * No need to allocate write_buf since it is not opened
2491 		 * for writing.
2492 		 */
2493 		head->write = NULL;
2494 	} else if (head->write) {
2495 		head->writebuf_size = 4096 * 2;
2496 		head->write_buf = kzalloc(head->writebuf_size, GFP_NOFS);
2497 		if (!head->write_buf) {
2498 			kfree(head->read_buf);
2499 			kfree(head);
2500 			return -ENOMEM;
2501 		}
2502 	}
2503 	/*
2504 	 * If the file is /sys/kernel/security/tomoyo/query , increment the
2505 	 * observer counter.
2506 	 * The obserber counter is used by tomoyo_supervisor() to see if
2507 	 * there is some process monitoring /sys/kernel/security/tomoyo/query.
2508 	 */
2509 	if (type == TOMOYO_QUERY)
2510 		atomic_inc(&tomoyo_query_observers);
2511 	file->private_data = head;
2512 	tomoyo_notify_gc(head, true);
2513 	return 0;
2514 }
2515 
2516 /**
2517  * tomoyo_poll_control - poll() for /sys/kernel/security/tomoyo/ interface.
2518  *
2519  * @file: Pointer to "struct file".
2520  * @wait: Pointer to "poll_table". Maybe NULL.
2521  *
2522  * Returns EPOLLIN | EPOLLRDNORM | EPOLLOUT | EPOLLWRNORM if ready to read/write,
2523  * EPOLLOUT | EPOLLWRNORM otherwise.
2524  */
2525 __poll_t tomoyo_poll_control(struct file *file, poll_table *wait)
2526 {
2527 	struct tomoyo_io_buffer *head = file->private_data;
2528 
2529 	if (head->poll)
2530 		return head->poll(file, wait) | EPOLLOUT | EPOLLWRNORM;
2531 	return EPOLLIN | EPOLLRDNORM | EPOLLOUT | EPOLLWRNORM;
2532 }
2533 
2534 /**
2535  * tomoyo_set_namespace_cursor - Set namespace to read.
2536  *
2537  * @head: Pointer to "struct tomoyo_io_buffer".
2538  *
2539  * Returns nothing.
2540  */
2541 static inline void tomoyo_set_namespace_cursor(struct tomoyo_io_buffer *head)
2542 {
2543 	struct list_head *ns;
2544 
2545 	if (head->type != TOMOYO_EXCEPTIONPOLICY &&
2546 	    head->type != TOMOYO_PROFILE)
2547 		return;
2548 	/*
2549 	 * If this is the first read, or reading previous namespace finished
2550 	 * and has more namespaces to read, update the namespace cursor.
2551 	 */
2552 	ns = head->r.ns;
2553 	if (!ns || (head->r.eof && ns->next != &tomoyo_namespace_list)) {
2554 		/* Clearing is OK because tomoyo_flush() returned true. */
2555 		memset(&head->r, 0, sizeof(head->r));
2556 		head->r.ns = ns ? ns->next : tomoyo_namespace_list.next;
2557 	}
2558 }
2559 
2560 /**
2561  * tomoyo_has_more_namespace - Check for unread namespaces.
2562  *
2563  * @head: Pointer to "struct tomoyo_io_buffer".
2564  *
2565  * Returns true if we have more entries to print, false otherwise.
2566  */
2567 static inline bool tomoyo_has_more_namespace(struct tomoyo_io_buffer *head)
2568 {
2569 	return (head->type == TOMOYO_EXCEPTIONPOLICY ||
2570 		head->type == TOMOYO_PROFILE) && head->r.eof &&
2571 		head->r.ns->next != &tomoyo_namespace_list;
2572 }
2573 
2574 /**
2575  * tomoyo_read_control - read() for /sys/kernel/security/tomoyo/ interface.
2576  *
2577  * @head:       Pointer to "struct tomoyo_io_buffer".
2578  * @buffer:     Poiner to buffer to write to.
2579  * @buffer_len: Size of @buffer.
2580  *
2581  * Returns bytes read on success, negative value otherwise.
2582  */
2583 ssize_t tomoyo_read_control(struct tomoyo_io_buffer *head, char __user *buffer,
2584 			    const int buffer_len)
2585 {
2586 	int len;
2587 	int idx;
2588 
2589 	if (!head->read)
2590 		return -EINVAL;
2591 	if (mutex_lock_interruptible(&head->io_sem))
2592 		return -EINTR;
2593 	head->read_user_buf = buffer;
2594 	head->read_user_buf_avail = buffer_len;
2595 	idx = tomoyo_read_lock();
2596 	if (tomoyo_flush(head))
2597 		/* Call the policy handler. */
2598 		do {
2599 			tomoyo_set_namespace_cursor(head);
2600 			head->read(head);
2601 		} while (tomoyo_flush(head) &&
2602 			 tomoyo_has_more_namespace(head));
2603 	tomoyo_read_unlock(idx);
2604 	len = head->read_user_buf - buffer;
2605 	mutex_unlock(&head->io_sem);
2606 	return len;
2607 }
2608 
2609 /**
2610  * tomoyo_parse_policy - Parse a policy line.
2611  *
2612  * @head: Poiter to "struct tomoyo_io_buffer".
2613  * @line: Line to parse.
2614  *
2615  * Returns 0 on success, negative value otherwise.
2616  *
2617  * Caller holds tomoyo_read_lock().
2618  */
2619 static int tomoyo_parse_policy(struct tomoyo_io_buffer *head, char *line)
2620 {
2621 	/* Delete request? */
2622 	head->w.is_delete = !strncmp(line, "delete ", 7);
2623 	if (head->w.is_delete)
2624 		memmove(line, line + 7, strlen(line + 7) + 1);
2625 	/* Selecting namespace to update. */
2626 	if (head->type == TOMOYO_EXCEPTIONPOLICY ||
2627 	    head->type == TOMOYO_PROFILE) {
2628 		if (*line == '<') {
2629 			char *cp = strchr(line, ' ');
2630 
2631 			if (cp) {
2632 				*cp++ = '\0';
2633 				head->w.ns = tomoyo_assign_namespace(line);
2634 				memmove(line, cp, strlen(cp) + 1);
2635 			} else
2636 				head->w.ns = NULL;
2637 		} else
2638 			head->w.ns = &tomoyo_kernel_namespace;
2639 		/* Don't allow updating if namespace is invalid. */
2640 		if (!head->w.ns)
2641 			return -ENOENT;
2642 	}
2643 	/* Do the update. */
2644 	return head->write(head);
2645 }
2646 
2647 /**
2648  * tomoyo_write_control - write() for /sys/kernel/security/tomoyo/ interface.
2649  *
2650  * @head:       Pointer to "struct tomoyo_io_buffer".
2651  * @buffer:     Pointer to buffer to read from.
2652  * @buffer_len: Size of @buffer.
2653  *
2654  * Returns @buffer_len on success, negative value otherwise.
2655  */
2656 ssize_t tomoyo_write_control(struct tomoyo_io_buffer *head,
2657 			     const char __user *buffer, const int buffer_len)
2658 {
2659 	int error = buffer_len;
2660 	size_t avail_len = buffer_len;
2661 	char *cp0 = head->write_buf;
2662 	int idx;
2663 
2664 	if (!head->write)
2665 		return -EINVAL;
2666 	if (!access_ok(buffer, buffer_len))
2667 		return -EFAULT;
2668 	if (mutex_lock_interruptible(&head->io_sem))
2669 		return -EINTR;
2670 	head->read_user_buf_avail = 0;
2671 	idx = tomoyo_read_lock();
2672 	/* Read a line and dispatch it to the policy handler. */
2673 	while (avail_len > 0) {
2674 		char c;
2675 
2676 		if (head->w.avail >= head->writebuf_size - 1) {
2677 			const int len = head->writebuf_size * 2;
2678 			char *cp = kzalloc(len, GFP_NOFS);
2679 
2680 			if (!cp) {
2681 				error = -ENOMEM;
2682 				break;
2683 			}
2684 			memmove(cp, cp0, head->w.avail);
2685 			kfree(cp0);
2686 			head->write_buf = cp;
2687 			cp0 = cp;
2688 			head->writebuf_size = len;
2689 		}
2690 		if (get_user(c, buffer)) {
2691 			error = -EFAULT;
2692 			break;
2693 		}
2694 		buffer++;
2695 		avail_len--;
2696 		cp0[head->w.avail++] = c;
2697 		if (c != '\n')
2698 			continue;
2699 		cp0[head->w.avail - 1] = '\0';
2700 		head->w.avail = 0;
2701 		tomoyo_normalize_line(cp0);
2702 		if (!strcmp(cp0, "reset")) {
2703 			head->w.ns = &tomoyo_kernel_namespace;
2704 			head->w.domain = NULL;
2705 			memset(&head->r, 0, sizeof(head->r));
2706 			continue;
2707 		}
2708 		/* Don't allow updating policies by non manager programs. */
2709 		switch (head->type) {
2710 		case TOMOYO_PROCESS_STATUS:
2711 			/* This does not write anything. */
2712 			break;
2713 		case TOMOYO_DOMAINPOLICY:
2714 			if (tomoyo_select_domain(head, cp0))
2715 				continue;
2716 			/* fall through */
2717 		case TOMOYO_EXCEPTIONPOLICY:
2718 			if (!strcmp(cp0, "select transition_only")) {
2719 				head->r.print_transition_related_only = true;
2720 				continue;
2721 			}
2722 			/* fall through */
2723 		default:
2724 			if (!tomoyo_manager()) {
2725 				error = -EPERM;
2726 				goto out;
2727 			}
2728 		}
2729 		switch (tomoyo_parse_policy(head, cp0)) {
2730 		case -EPERM:
2731 			error = -EPERM;
2732 			goto out;
2733 		case 0:
2734 			switch (head->type) {
2735 			case TOMOYO_DOMAINPOLICY:
2736 			case TOMOYO_EXCEPTIONPOLICY:
2737 			case TOMOYO_STAT:
2738 			case TOMOYO_PROFILE:
2739 			case TOMOYO_MANAGER:
2740 				tomoyo_update_stat(TOMOYO_STAT_POLICY_UPDATES);
2741 				break;
2742 			default:
2743 				break;
2744 			}
2745 			break;
2746 		}
2747 	}
2748 out:
2749 	tomoyo_read_unlock(idx);
2750 	mutex_unlock(&head->io_sem);
2751 	return error;
2752 }
2753 
2754 /**
2755  * tomoyo_close_control - close() for /sys/kernel/security/tomoyo/ interface.
2756  *
2757  * @head: Pointer to "struct tomoyo_io_buffer".
2758  */
2759 void tomoyo_close_control(struct tomoyo_io_buffer *head)
2760 {
2761 	/*
2762 	 * If the file is /sys/kernel/security/tomoyo/query , decrement the
2763 	 * observer counter.
2764 	 */
2765 	if (head->type == TOMOYO_QUERY &&
2766 	    atomic_dec_and_test(&tomoyo_query_observers))
2767 		wake_up_all(&tomoyo_answer_wait);
2768 	tomoyo_notify_gc(head, false);
2769 }
2770 
2771 /**
2772  * tomoyo_check_profile - Check all profiles currently assigned to domains are defined.
2773  */
2774 void tomoyo_check_profile(void)
2775 {
2776 	struct tomoyo_domain_info *domain;
2777 	const int idx = tomoyo_read_lock();
2778 
2779 	tomoyo_policy_loaded = true;
2780 	pr_info("TOMOYO: 2.6.0\n");
2781 	list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
2782 		const u8 profile = domain->profile;
2783 		struct tomoyo_policy_namespace *ns = domain->ns;
2784 
2785 		if (ns->profile_version == 20110903) {
2786 			pr_info_once("Converting profile version from %u to %u.\n",
2787 				     20110903, 20150505);
2788 			ns->profile_version = 20150505;
2789 		}
2790 		if (ns->profile_version != 20150505)
2791 			pr_err("Profile version %u is not supported.\n",
2792 			       ns->profile_version);
2793 		else if (!ns->profile_ptr[profile])
2794 			pr_err("Profile %u (used by '%s') is not defined.\n",
2795 			       profile, domain->domainname->name);
2796 		else
2797 			continue;
2798 		pr_err("Userland tools for TOMOYO 2.6 must be installed and policy must be initialized.\n");
2799 		pr_err("Please see https://tomoyo.osdn.jp/2.6/ for more information.\n");
2800 		panic("STOP!");
2801 	}
2802 	tomoyo_read_unlock(idx);
2803 	pr_info("Mandatory Access Control activated.\n");
2804 }
2805 
2806 /**
2807  * tomoyo_load_builtin_policy - Load built-in policy.
2808  *
2809  * Returns nothing.
2810  */
2811 void __init tomoyo_load_builtin_policy(void)
2812 {
2813 	/*
2814 	 * This include file is manually created and contains built-in policy
2815 	 * named "tomoyo_builtin_profile", "tomoyo_builtin_exception_policy",
2816 	 * "tomoyo_builtin_domain_policy", "tomoyo_builtin_manager",
2817 	 * "tomoyo_builtin_stat" in the form of "static char [] __initdata".
2818 	 */
2819 #include "builtin-policy.h"
2820 	u8 i;
2821 	const int idx = tomoyo_read_lock();
2822 
2823 	for (i = 0; i < 5; i++) {
2824 		struct tomoyo_io_buffer head = { };
2825 		char *start = "";
2826 
2827 		switch (i) {
2828 		case 0:
2829 			start = tomoyo_builtin_profile;
2830 			head.type = TOMOYO_PROFILE;
2831 			head.write = tomoyo_write_profile;
2832 			break;
2833 		case 1:
2834 			start = tomoyo_builtin_exception_policy;
2835 			head.type = TOMOYO_EXCEPTIONPOLICY;
2836 			head.write = tomoyo_write_exception;
2837 			break;
2838 		case 2:
2839 			start = tomoyo_builtin_domain_policy;
2840 			head.type = TOMOYO_DOMAINPOLICY;
2841 			head.write = tomoyo_write_domain;
2842 			break;
2843 		case 3:
2844 			start = tomoyo_builtin_manager;
2845 			head.type = TOMOYO_MANAGER;
2846 			head.write = tomoyo_write_manager;
2847 			break;
2848 		case 4:
2849 			start = tomoyo_builtin_stat;
2850 			head.type = TOMOYO_STAT;
2851 			head.write = tomoyo_write_stat;
2852 			break;
2853 		}
2854 		while (1) {
2855 			char *end = strchr(start, '\n');
2856 
2857 			if (!end)
2858 				break;
2859 			*end = '\0';
2860 			tomoyo_normalize_line(start);
2861 			head.write_buf = start;
2862 			tomoyo_parse_policy(&head, start);
2863 			start = end + 1;
2864 		}
2865 	}
2866 	tomoyo_read_unlock(idx);
2867 #ifdef CONFIG_SECURITY_TOMOYO_OMIT_USERSPACE_LOADER
2868 	tomoyo_check_profile();
2869 #endif
2870 }
2871