common.c revision f23571e866309a2048030ef6a5f0725cf139d4c9
1/*
2 * security/tomoyo/common.c
3 *
4 * Common functions for TOMOYO.
5 *
6 * Copyright (C) 2005-2010  NTT DATA CORPORATION
7 */
8
9#include <linux/uaccess.h>
10#include <linux/slab.h>
11#include <linux/security.h>
12#include "common.h"
13
14static struct tomoyo_profile tomoyo_default_profile = {
15	.learning = &tomoyo_default_profile.preference,
16	.permissive = &tomoyo_default_profile.preference,
17	.enforcing = &tomoyo_default_profile.preference,
18	.preference.enforcing_verbose = true,
19	.preference.learning_max_entry = 2048,
20	.preference.learning_verbose = false,
21	.preference.permissive_verbose = true
22};
23
24/* Profile version. Currently only 20090903 is defined. */
25static unsigned int tomoyo_profile_version;
26
27/* Profile table. Memory is allocated as needed. */
28static struct tomoyo_profile *tomoyo_profile_ptr[TOMOYO_MAX_PROFILES];
29
30/* String table for functionality that takes 4 modes. */
31static const char *tomoyo_mode[4] = {
32	"disabled", "learning", "permissive", "enforcing"
33};
34
35/* String table for /sys/kernel/security/tomoyo/profile */
36static const char *tomoyo_mac_keywords[TOMOYO_MAX_MAC_INDEX
37				       + TOMOYO_MAX_MAC_CATEGORY_INDEX] = {
38	[TOMOYO_MAC_FILE_EXECUTE]    = "file::execute",
39	[TOMOYO_MAC_FILE_OPEN]       = "file::open",
40	[TOMOYO_MAC_FILE_CREATE]     = "file::create",
41	[TOMOYO_MAC_FILE_UNLINK]     = "file::unlink",
42	[TOMOYO_MAC_FILE_MKDIR]      = "file::mkdir",
43	[TOMOYO_MAC_FILE_RMDIR]      = "file::rmdir",
44	[TOMOYO_MAC_FILE_MKFIFO]     = "file::mkfifo",
45	[TOMOYO_MAC_FILE_MKSOCK]     = "file::mksock",
46	[TOMOYO_MAC_FILE_TRUNCATE]   = "file::truncate",
47	[TOMOYO_MAC_FILE_SYMLINK]    = "file::symlink",
48	[TOMOYO_MAC_FILE_REWRITE]    = "file::rewrite",
49	[TOMOYO_MAC_FILE_MKBLOCK]    = "file::mkblock",
50	[TOMOYO_MAC_FILE_MKCHAR]     = "file::mkchar",
51	[TOMOYO_MAC_FILE_LINK]       = "file::link",
52	[TOMOYO_MAC_FILE_RENAME]     = "file::rename",
53	[TOMOYO_MAC_FILE_CHMOD]      = "file::chmod",
54	[TOMOYO_MAC_FILE_CHOWN]      = "file::chown",
55	[TOMOYO_MAC_FILE_CHGRP]      = "file::chgrp",
56	[TOMOYO_MAC_FILE_IOCTL]      = "file::ioctl",
57	[TOMOYO_MAC_FILE_CHROOT]     = "file::chroot",
58	[TOMOYO_MAC_FILE_MOUNT]      = "file::mount",
59	[TOMOYO_MAC_FILE_UMOUNT]     = "file::umount",
60	[TOMOYO_MAC_FILE_PIVOT_ROOT] = "file::pivot_root",
61	[TOMOYO_MAX_MAC_INDEX + TOMOYO_MAC_CATEGORY_FILE] = "file",
62};
63
64/* Permit policy management by non-root user? */
65static bool tomoyo_manage_by_non_root;
66
67/* Utility functions. */
68
69/**
70 * tomoyo_yesno - Return "yes" or "no".
71 *
72 * @value: Bool value.
73 */
74static const char *tomoyo_yesno(const unsigned int value)
75{
76	return value ? "yes" : "no";
77}
78
79static void tomoyo_addprintf(char *buffer, int len, const char *fmt, ...)
80{
81	va_list args;
82	const int pos = strlen(buffer);
83	va_start(args, fmt);
84	vsnprintf(buffer + pos, len - pos - 1, fmt, args);
85	va_end(args);
86}
87
88/**
89 * tomoyo_flush - Flush queued string to userspace's buffer.
90 *
91 * @head:   Pointer to "struct tomoyo_io_buffer".
92 *
93 * Returns true if all data was flushed, false otherwise.
94 */
95static bool tomoyo_flush(struct tomoyo_io_buffer *head)
96{
97	while (head->r.w_pos) {
98		const char *w = head->r.w[0];
99		int len = strlen(w);
100		if (len) {
101			if (len > head->read_user_buf_avail)
102				len = head->read_user_buf_avail;
103			if (!len)
104				return false;
105			if (copy_to_user(head->read_user_buf, w, len))
106				return false;
107			head->read_user_buf_avail -= len;
108			head->read_user_buf += len;
109			w += len;
110		}
111		if (*w) {
112			head->r.w[0] = w;
113			return false;
114		}
115		/* Add '\0' for query. */
116		if (head->poll) {
117			if (!head->read_user_buf_avail ||
118			    copy_to_user(head->read_user_buf, "", 1))
119				return false;
120			head->read_user_buf_avail--;
121			head->read_user_buf++;
122		}
123		head->r.w_pos--;
124		for (len = 0; len < head->r.w_pos; len++)
125			head->r.w[len] = head->r.w[len + 1];
126	}
127	head->r.avail = 0;
128	return true;
129}
130
131/**
132 * tomoyo_set_string - Queue string to "struct tomoyo_io_buffer" structure.
133 *
134 * @head:   Pointer to "struct tomoyo_io_buffer".
135 * @string: String to print.
136 *
137 * Note that @string has to be kept valid until @head is kfree()d.
138 * This means that char[] allocated on stack memory cannot be passed to
139 * this function. Use tomoyo_io_printf() for char[] allocated on stack memory.
140 */
141static void tomoyo_set_string(struct tomoyo_io_buffer *head, const char *string)
142{
143	if (head->r.w_pos < TOMOYO_MAX_IO_READ_QUEUE) {
144		head->r.w[head->r.w_pos++] = string;
145		tomoyo_flush(head);
146	} else
147		WARN_ON(1);
148}
149
150/**
151 * tomoyo_io_printf - printf() to "struct tomoyo_io_buffer" structure.
152 *
153 * @head: Pointer to "struct tomoyo_io_buffer".
154 * @fmt:  The printf()'s format string, followed by parameters.
155 */
156void tomoyo_io_printf(struct tomoyo_io_buffer *head, const char *fmt, ...)
157{
158	va_list args;
159	int len;
160	int pos = head->r.avail;
161	int size = head->readbuf_size - pos;
162	if (size <= 0)
163		return;
164	va_start(args, fmt);
165	len = vsnprintf(head->read_buf + pos, size, fmt, args) + 1;
166	va_end(args);
167	if (pos + len >= head->readbuf_size) {
168		WARN_ON(1);
169		return;
170	}
171	head->r.avail += len;
172	tomoyo_set_string(head, head->read_buf + pos);
173}
174
175static void tomoyo_set_space(struct tomoyo_io_buffer *head)
176{
177	tomoyo_set_string(head, " ");
178}
179
180static bool tomoyo_set_lf(struct tomoyo_io_buffer *head)
181{
182	tomoyo_set_string(head, "\n");
183	return !head->r.w_pos;
184}
185
186/**
187 * tomoyo_print_name_union - Print a tomoyo_name_union.
188 *
189 * @head: Pointer to "struct tomoyo_io_buffer".
190 * @ptr:  Pointer to "struct tomoyo_name_union".
191 */
192static void tomoyo_print_name_union(struct tomoyo_io_buffer *head,
193				    const struct tomoyo_name_union *ptr)
194{
195	tomoyo_set_space(head);
196	if (ptr->is_group) {
197		tomoyo_set_string(head, "@");
198		tomoyo_set_string(head, ptr->group->group_name->name);
199	} else {
200		tomoyo_set_string(head, ptr->filename->name);
201	}
202}
203
204/**
205 * tomoyo_print_number_union - Print a tomoyo_number_union.
206 *
207 * @head:       Pointer to "struct tomoyo_io_buffer".
208 * @ptr:        Pointer to "struct tomoyo_number_union".
209 */
210static void tomoyo_print_number_union(struct tomoyo_io_buffer *head,
211				      const struct tomoyo_number_union *ptr)
212{
213	tomoyo_set_space(head);
214	if (ptr->is_group) {
215		tomoyo_set_string(head, "@");
216		tomoyo_set_string(head, ptr->group->group_name->name);
217	} else {
218		int i;
219		unsigned long min = ptr->values[0];
220		const unsigned long max = ptr->values[1];
221		u8 min_type = ptr->min_type;
222		const u8 max_type = ptr->max_type;
223		char buffer[128];
224		buffer[0] = '\0';
225		for (i = 0; i < 2; i++) {
226			switch (min_type) {
227			case TOMOYO_VALUE_TYPE_HEXADECIMAL:
228				tomoyo_addprintf(buffer, sizeof(buffer),
229						 "0x%lX", min);
230				break;
231			case TOMOYO_VALUE_TYPE_OCTAL:
232				tomoyo_addprintf(buffer, sizeof(buffer),
233						 "0%lo", min);
234				break;
235			default:
236				tomoyo_addprintf(buffer, sizeof(buffer),
237						 "%lu", min);
238				break;
239			}
240			if (min == max && min_type == max_type)
241				break;
242			tomoyo_addprintf(buffer, sizeof(buffer), "-");
243			min_type = max_type;
244			min = max;
245		}
246		tomoyo_io_printf(head, "%s", buffer);
247	}
248}
249
250/**
251 * tomoyo_find_or_assign_new_profile - Create a new profile.
252 *
253 * @profile: Profile number to create.
254 *
255 * Returns pointer to "struct tomoyo_profile" on success, NULL otherwise.
256 */
257static struct tomoyo_profile *tomoyo_find_or_assign_new_profile
258(const unsigned int profile)
259{
260	struct tomoyo_profile *ptr;
261	struct tomoyo_profile *entry;
262	if (profile >= TOMOYO_MAX_PROFILES)
263		return NULL;
264	ptr = tomoyo_profile_ptr[profile];
265	if (ptr)
266		return ptr;
267	entry = kzalloc(sizeof(*entry), GFP_NOFS);
268	if (mutex_lock_interruptible(&tomoyo_policy_lock))
269		goto out;
270	ptr = tomoyo_profile_ptr[profile];
271	if (!ptr && tomoyo_memory_ok(entry)) {
272		ptr = entry;
273		ptr->learning = &tomoyo_default_profile.preference;
274		ptr->permissive = &tomoyo_default_profile.preference;
275		ptr->enforcing = &tomoyo_default_profile.preference;
276		ptr->default_config = TOMOYO_CONFIG_DISABLED;
277		memset(ptr->config, TOMOYO_CONFIG_USE_DEFAULT,
278		       sizeof(ptr->config));
279		mb(); /* Avoid out-of-order execution. */
280		tomoyo_profile_ptr[profile] = ptr;
281		entry = NULL;
282	}
283	mutex_unlock(&tomoyo_policy_lock);
284 out:
285	kfree(entry);
286	return ptr;
287}
288
289/**
290 * tomoyo_profile - Find a profile.
291 *
292 * @profile: Profile number to find.
293 *
294 * Returns pointer to "struct tomoyo_profile".
295 */
296struct tomoyo_profile *tomoyo_profile(const u8 profile)
297{
298	struct tomoyo_profile *ptr = tomoyo_profile_ptr[profile];
299	if (!tomoyo_policy_loaded)
300		return &tomoyo_default_profile;
301	BUG_ON(!ptr);
302	return ptr;
303}
304
305/**
306 * tomoyo_write_profile - Write profile table.
307 *
308 * @head: Pointer to "struct tomoyo_io_buffer".
309 *
310 * Returns 0 on success, negative value otherwise.
311 */
312static int tomoyo_write_profile(struct tomoyo_io_buffer *head)
313{
314	char *data = head->write_buf;
315	unsigned int i;
316	int value;
317	int mode;
318	u8 config;
319	bool use_default = false;
320	char *cp;
321	struct tomoyo_profile *profile;
322	if (sscanf(data, "PROFILE_VERSION=%u", &tomoyo_profile_version) == 1)
323		return 0;
324	i = simple_strtoul(data, &cp, 10);
325	if (data == cp) {
326		profile = &tomoyo_default_profile;
327	} else {
328		if (*cp != '-')
329			return -EINVAL;
330		data = cp + 1;
331		profile = tomoyo_find_or_assign_new_profile(i);
332		if (!profile)
333			return -EINVAL;
334	}
335	cp = strchr(data, '=');
336	if (!cp)
337		return -EINVAL;
338	*cp++ = '\0';
339	if (profile != &tomoyo_default_profile)
340		use_default = strstr(cp, "use_default") != NULL;
341	if (strstr(cp, "verbose=yes"))
342		value = 1;
343	else if (strstr(cp, "verbose=no"))
344		value = 0;
345	else
346		value = -1;
347	if (!strcmp(data, "PREFERENCE::enforcing")) {
348		if (use_default) {
349			profile->enforcing = &tomoyo_default_profile.preference;
350			return 0;
351		}
352		profile->enforcing = &profile->preference;
353		if (value >= 0)
354			profile->preference.enforcing_verbose = value;
355		return 0;
356	}
357	if (!strcmp(data, "PREFERENCE::permissive")) {
358		if (use_default) {
359			profile->permissive = &tomoyo_default_profile.preference;
360			return 0;
361		}
362		profile->permissive = &profile->preference;
363		if (value >= 0)
364			profile->preference.permissive_verbose = value;
365		return 0;
366	}
367	if (!strcmp(data, "PREFERENCE::learning")) {
368		char *cp2;
369		if (use_default) {
370			profile->learning = &tomoyo_default_profile.preference;
371			return 0;
372		}
373		profile->learning = &profile->preference;
374		if (value >= 0)
375			profile->preference.learning_verbose = value;
376		cp2 = strstr(cp, "max_entry=");
377		if (cp2)
378			sscanf(cp2 + 10, "%u",
379			       &profile->preference.learning_max_entry);
380		return 0;
381	}
382	if (profile == &tomoyo_default_profile)
383		return -EINVAL;
384	if (!strcmp(data, "COMMENT")) {
385		const struct tomoyo_path_info *old_comment = profile->comment;
386		profile->comment = tomoyo_get_name(cp);
387		tomoyo_put_name(old_comment);
388		return 0;
389	}
390	if (!strcmp(data, "CONFIG")) {
391		i = TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX;
392		config = profile->default_config;
393	} else if (tomoyo_str_starts(&data, "CONFIG::")) {
394		config = 0;
395		for (i = 0; i < TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX; i++) {
396			if (strcmp(data, tomoyo_mac_keywords[i]))
397				continue;
398			config = profile->config[i];
399			break;
400		}
401		if (i == TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX)
402			return -EINVAL;
403	} else {
404		return -EINVAL;
405	}
406	if (use_default) {
407		config = TOMOYO_CONFIG_USE_DEFAULT;
408	} else {
409		for (mode = 3; mode >= 0; mode--)
410			if (strstr(cp, tomoyo_mode[mode]))
411				/*
412				 * Update lower 3 bits in order to distinguish
413				 * 'config' from 'TOMOYO_CONFIG_USE_DEAFULT'.
414				 */
415				config = (config & ~7) | mode;
416	}
417	if (i < TOMOYO_MAX_MAC_INDEX + TOMOYO_MAX_MAC_CATEGORY_INDEX)
418		profile->config[i] = config;
419	else if (config != TOMOYO_CONFIG_USE_DEFAULT)
420		profile->default_config = config;
421	return 0;
422}
423
424static void tomoyo_print_preference(struct tomoyo_io_buffer *head,
425				    const int idx)
426{
427	struct tomoyo_preference *pref = &tomoyo_default_profile.preference;
428	const struct tomoyo_profile *profile = idx >= 0 ?
429		tomoyo_profile_ptr[idx] : NULL;
430	char buffer[16] = "";
431	if (profile) {
432		buffer[sizeof(buffer) - 1] = '\0';
433		snprintf(buffer, sizeof(buffer) - 1, "%u-", idx);
434	}
435	if (profile) {
436		pref = profile->learning;
437		if (pref == &tomoyo_default_profile.preference)
438			goto skip1;
439	}
440	tomoyo_io_printf(head, "%sPREFERENCE::%s={ "
441			 "verbose=%s max_entry=%u }\n",
442			 buffer, "learning",
443			 tomoyo_yesno(pref->learning_verbose),
444			 pref->learning_max_entry);
445 skip1:
446	if (profile) {
447		pref = profile->permissive;
448		if (pref == &tomoyo_default_profile.preference)
449			goto skip2;
450	}
451	tomoyo_io_printf(head, "%sPREFERENCE::%s={ verbose=%s }\n",
452			 buffer, "permissive",
453			 tomoyo_yesno(pref->permissive_verbose));
454 skip2:
455	if (profile) {
456		pref = profile->enforcing;
457		if (pref == &tomoyo_default_profile.preference)
458			return;
459	}
460	tomoyo_io_printf(head, "%sPREFERENCE::%s={ verbose=%s }\n",
461			 buffer, "enforcing",
462			 tomoyo_yesno(pref->enforcing_verbose));
463}
464
465static void tomoyo_print_config(struct tomoyo_io_buffer *head, const u8 config)
466{
467	tomoyo_io_printf(head, "={ mode=%s }\n", tomoyo_mode[config & 3]);
468}
469
470/**
471 * tomoyo_read_profile - Read profile table.
472 *
473 * @head: Pointer to "struct tomoyo_io_buffer".
474 */
475static void tomoyo_read_profile(struct tomoyo_io_buffer *head)
476{
477	u8 index;
478	const struct tomoyo_profile *profile;
479 next:
480	index = head->r.index;
481	profile = tomoyo_profile_ptr[index];
482	switch (head->r.step) {
483	case 0:
484		tomoyo_io_printf(head, "PROFILE_VERSION=%s\n", "20090903");
485		tomoyo_print_preference(head, -1);
486		head->r.step++;
487		break;
488	case 1:
489		for ( ; head->r.index < TOMOYO_MAX_PROFILES;
490		      head->r.index++)
491			if (tomoyo_profile_ptr[head->r.index])
492				break;
493		if (head->r.index == TOMOYO_MAX_PROFILES)
494			return;
495		head->r.step++;
496		break;
497	case 2:
498		{
499			const struct tomoyo_path_info *comment =
500				profile->comment;
501			tomoyo_io_printf(head, "%u-COMMENT=", index);
502			tomoyo_set_string(head, comment ? comment->name : "");
503			tomoyo_set_lf(head);
504			head->r.step++;
505		}
506		break;
507	case 3:
508		{
509			tomoyo_io_printf(head, "%u-%s", index, "CONFIG");
510			tomoyo_print_config(head, profile->default_config);
511			head->r.bit = 0;
512			head->r.step++;
513		}
514		break;
515	case 4:
516		for ( ; head->r.bit < TOMOYO_MAX_MAC_INDEX
517			      + TOMOYO_MAX_MAC_CATEGORY_INDEX; head->r.bit++) {
518			const u8 i = head->r.bit;
519			const u8 config = profile->config[i];
520			if (config == TOMOYO_CONFIG_USE_DEFAULT)
521				continue;
522			tomoyo_io_printf(head, "%u-%s%s", index, "CONFIG::",
523					 tomoyo_mac_keywords[i]);
524			tomoyo_print_config(head, config);
525			head->r.bit++;
526			break;
527		}
528		if (head->r.bit == TOMOYO_MAX_MAC_INDEX
529		    + TOMOYO_MAX_MAC_CATEGORY_INDEX) {
530			tomoyo_print_preference(head, index);
531			head->r.index++;
532			head->r.step = 1;
533		}
534		break;
535	}
536	if (tomoyo_flush(head))
537		goto next;
538}
539
540static bool tomoyo_same_manager_entry(const struct tomoyo_acl_head *a,
541				      const struct tomoyo_acl_head *b)
542{
543	return container_of(a, struct tomoyo_policy_manager_entry, head)
544		->manager ==
545		container_of(b, struct tomoyo_policy_manager_entry, head)
546		->manager;
547}
548
549/**
550 * tomoyo_update_manager_entry - Add a manager entry.
551 *
552 * @manager:   The path to manager or the domainnamme.
553 * @is_delete: True if it is a delete request.
554 *
555 * Returns 0 on success, negative value otherwise.
556 *
557 * Caller holds tomoyo_read_lock().
558 */
559static int tomoyo_update_manager_entry(const char *manager,
560				       const bool is_delete)
561{
562	struct tomoyo_policy_manager_entry e = { };
563	int error;
564
565	if (tomoyo_domain_def(manager)) {
566		if (!tomoyo_correct_domain(manager))
567			return -EINVAL;
568		e.is_domain = true;
569	} else {
570		if (!tomoyo_correct_path(manager))
571			return -EINVAL;
572	}
573	e.manager = tomoyo_get_name(manager);
574	if (!e.manager)
575		return -ENOMEM;
576	error = tomoyo_update_policy(&e.head, sizeof(e), is_delete,
577				     &tomoyo_policy_list[TOMOYO_ID_MANAGER],
578				     tomoyo_same_manager_entry);
579	tomoyo_put_name(e.manager);
580	return error;
581}
582
583/**
584 * tomoyo_write_manager_policy - Write manager policy.
585 *
586 * @head: Pointer to "struct tomoyo_io_buffer".
587 *
588 * Returns 0 on success, negative value otherwise.
589 *
590 * Caller holds tomoyo_read_lock().
591 */
592static int tomoyo_write_manager_policy(struct tomoyo_io_buffer *head)
593{
594	char *data = head->write_buf;
595	bool is_delete = tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE);
596
597	if (!strcmp(data, "manage_by_non_root")) {
598		tomoyo_manage_by_non_root = !is_delete;
599		return 0;
600	}
601	return tomoyo_update_manager_entry(data, is_delete);
602}
603
604/**
605 * tomoyo_read_manager_policy - Read manager policy.
606 *
607 * @head: Pointer to "struct tomoyo_io_buffer".
608 *
609 * Caller holds tomoyo_read_lock().
610 */
611static void tomoyo_read_manager_policy(struct tomoyo_io_buffer *head)
612{
613	if (head->r.eof)
614		return;
615	list_for_each_cookie(head->r.acl,
616			     &tomoyo_policy_list[TOMOYO_ID_MANAGER]) {
617		struct tomoyo_policy_manager_entry *ptr =
618			list_entry(head->r.acl, typeof(*ptr), head.list);
619		if (ptr->head.is_deleted)
620			continue;
621		if (!tomoyo_flush(head))
622			return;
623		tomoyo_set_string(head, ptr->manager->name);
624		tomoyo_set_lf(head);
625	}
626	head->r.eof = true;
627}
628
629/**
630 * tomoyo_policy_manager - Check whether the current process is a policy manager.
631 *
632 * Returns true if the current process is permitted to modify policy
633 * via /sys/kernel/security/tomoyo/ interface.
634 *
635 * Caller holds tomoyo_read_lock().
636 */
637static bool tomoyo_policy_manager(void)
638{
639	struct tomoyo_policy_manager_entry *ptr;
640	const char *exe;
641	const struct task_struct *task = current;
642	const struct tomoyo_path_info *domainname = tomoyo_domain()->domainname;
643	bool found = false;
644
645	if (!tomoyo_policy_loaded)
646		return true;
647	if (!tomoyo_manage_by_non_root && (task->cred->uid || task->cred->euid))
648		return false;
649	list_for_each_entry_rcu(ptr, &tomoyo_policy_list[TOMOYO_ID_MANAGER],
650				head.list) {
651		if (!ptr->head.is_deleted && ptr->is_domain
652		    && !tomoyo_pathcmp(domainname, ptr->manager)) {
653			found = true;
654			break;
655		}
656	}
657	if (found)
658		return true;
659	exe = tomoyo_get_exe();
660	if (!exe)
661		return false;
662	list_for_each_entry_rcu(ptr, &tomoyo_policy_list[TOMOYO_ID_MANAGER],
663				head.list) {
664		if (!ptr->head.is_deleted && !ptr->is_domain
665		    && !strcmp(exe, ptr->manager->name)) {
666			found = true;
667			break;
668		}
669	}
670	if (!found) { /* Reduce error messages. */
671		static pid_t last_pid;
672		const pid_t pid = current->pid;
673		if (last_pid != pid) {
674			printk(KERN_WARNING "%s ( %s ) is not permitted to "
675			       "update policies.\n", domainname->name, exe);
676			last_pid = pid;
677		}
678	}
679	kfree(exe);
680	return found;
681}
682
683/**
684 * tomoyo_select_one - Parse select command.
685 *
686 * @head: Pointer to "struct tomoyo_io_buffer".
687 * @data: String to parse.
688 *
689 * Returns true on success, false otherwise.
690 *
691 * Caller holds tomoyo_read_lock().
692 */
693static bool tomoyo_select_one(struct tomoyo_io_buffer *head, const char *data)
694{
695	unsigned int pid;
696	struct tomoyo_domain_info *domain = NULL;
697	bool global_pid = false;
698
699	if (!strcmp(data, "allow_execute")) {
700		head->r.print_execute_only = true;
701		return true;
702	}
703	if (sscanf(data, "pid=%u", &pid) == 1 ||
704	    (global_pid = true, sscanf(data, "global-pid=%u", &pid) == 1)) {
705		struct task_struct *p;
706		rcu_read_lock();
707		read_lock(&tasklist_lock);
708		if (global_pid)
709			p = find_task_by_pid_ns(pid, &init_pid_ns);
710		else
711			p = find_task_by_vpid(pid);
712		if (p)
713			domain = tomoyo_real_domain(p);
714		read_unlock(&tasklist_lock);
715		rcu_read_unlock();
716	} else if (!strncmp(data, "domain=", 7)) {
717		if (tomoyo_domain_def(data + 7))
718			domain = tomoyo_find_domain(data + 7);
719	} else
720		return false;
721	head->write_var1 = domain;
722	/* Accessing read_buf is safe because head->io_sem is held. */
723	if (!head->read_buf)
724		return true; /* Do nothing if open(O_WRONLY). */
725	memset(&head->r, 0, sizeof(head->r));
726	head->r.print_this_domain_only = true;
727	head->r.eof = !domain;
728	head->r.domain = &domain->list;
729	tomoyo_io_printf(head, "# select %s\n", data);
730	if (domain && domain->is_deleted)
731		tomoyo_io_printf(head, "# This is a deleted domain.\n");
732	return true;
733}
734
735/**
736 * tomoyo_delete_domain - Delete a domain.
737 *
738 * @domainname: The name of domain.
739 *
740 * Returns 0.
741 *
742 * Caller holds tomoyo_read_lock().
743 */
744static int tomoyo_delete_domain(char *domainname)
745{
746	struct tomoyo_domain_info *domain;
747	struct tomoyo_path_info name;
748
749	name.name = domainname;
750	tomoyo_fill_path_info(&name);
751	if (mutex_lock_interruptible(&tomoyo_policy_lock))
752		return 0;
753	/* Is there an active domain? */
754	list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
755		/* Never delete tomoyo_kernel_domain */
756		if (domain == &tomoyo_kernel_domain)
757			continue;
758		if (domain->is_deleted ||
759		    tomoyo_pathcmp(domain->domainname, &name))
760			continue;
761		domain->is_deleted = true;
762		break;
763	}
764	mutex_unlock(&tomoyo_policy_lock);
765	return 0;
766}
767
768/**
769 * tomoyo_write_domain_policy2 - Write domain policy.
770 *
771 * @head: Pointer to "struct tomoyo_io_buffer".
772 *
773 * Returns 0 on success, negative value otherwise.
774 *
775 * Caller holds tomoyo_read_lock().
776 */
777static int tomoyo_write_domain_policy2(char *data,
778				       struct tomoyo_domain_info *domain,
779				       const bool is_delete)
780{
781	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALLOW_MOUNT))
782                return tomoyo_write_mount_policy(data, domain, is_delete);
783	return tomoyo_write_file_policy(data, domain, is_delete);
784}
785
786/**
787 * tomoyo_write_domain_policy - Write domain policy.
788 *
789 * @head: Pointer to "struct tomoyo_io_buffer".
790 *
791 * Returns 0 on success, negative value otherwise.
792 *
793 * Caller holds tomoyo_read_lock().
794 */
795static int tomoyo_write_domain_policy(struct tomoyo_io_buffer *head)
796{
797	char *data = head->write_buf;
798	struct tomoyo_domain_info *domain = head->write_var1;
799	bool is_delete = false;
800	bool is_select = false;
801	unsigned int profile;
802
803	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE))
804		is_delete = true;
805	else if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_SELECT))
806		is_select = true;
807	if (is_select && tomoyo_select_one(head, data))
808		return 0;
809	/* Don't allow updating policies by non manager programs. */
810	if (!tomoyo_policy_manager())
811		return -EPERM;
812	if (tomoyo_domain_def(data)) {
813		domain = NULL;
814		if (is_delete)
815			tomoyo_delete_domain(data);
816		else if (is_select)
817			domain = tomoyo_find_domain(data);
818		else
819			domain = tomoyo_find_or_assign_new_domain(data, 0);
820		head->write_var1 = domain;
821		return 0;
822	}
823	if (!domain)
824		return -EINVAL;
825
826	if (sscanf(data, TOMOYO_KEYWORD_USE_PROFILE "%u", &profile) == 1
827	    && profile < TOMOYO_MAX_PROFILES) {
828		if (tomoyo_profile_ptr[profile] || !tomoyo_policy_loaded)
829			domain->profile = (u8) profile;
830		return 0;
831	}
832	if (!strcmp(data, TOMOYO_KEYWORD_IGNORE_GLOBAL_ALLOW_READ)) {
833		domain->ignore_global_allow_read = !is_delete;
834		return 0;
835	}
836	if (!strcmp(data, TOMOYO_KEYWORD_QUOTA_EXCEEDED)) {
837		domain->quota_warned = !is_delete;
838		return 0;
839	}
840	if (!strcmp(data, TOMOYO_KEYWORD_TRANSITION_FAILED)) {
841		domain->transition_failed = !is_delete;
842		return 0;
843	}
844	return tomoyo_write_domain_policy2(data, domain, is_delete);
845}
846
847/**
848 * tomoyo_fns - Find next set bit.
849 *
850 * @perm: 8 bits value.
851 * @bit:  First bit to find.
852 *
853 * Returns next on-bit on success, 8 otherwise.
854 */
855static u8 tomoyo_fns(const u8 perm, u8 bit)
856{
857	for ( ; bit < 8; bit++)
858		if (perm & (1 << bit))
859			break;
860	return bit;
861}
862
863/**
864 * tomoyo_print_entry - Print an ACL entry.
865 *
866 * @head: Pointer to "struct tomoyo_io_buffer".
867 * @acl:  Pointer to an ACL entry.
868 *
869 * Returns true on success, false otherwise.
870 */
871static bool tomoyo_print_entry(struct tomoyo_io_buffer *head,
872			       struct tomoyo_acl_info *acl)
873{
874	const u8 acl_type = acl->type;
875	u8 bit;
876
877	if (acl->is_deleted)
878		return true;
879 next:
880	bit = head->r.bit;
881	if (!tomoyo_flush(head))
882		return false;
883	else if (acl_type == TOMOYO_TYPE_PATH_ACL) {
884		struct tomoyo_path_acl *ptr =
885			container_of(acl, typeof(*ptr), head);
886		const u16 perm = ptr->perm;
887		for ( ; bit < TOMOYO_MAX_PATH_OPERATION; bit++) {
888			if (!(perm & (1 << bit)))
889				continue;
890			if (head->r.print_execute_only &&
891			    bit != TOMOYO_TYPE_EXECUTE)
892				continue;
893			/* Print "read/write" instead of "read" and "write". */
894			if ((bit == TOMOYO_TYPE_READ ||
895			     bit == TOMOYO_TYPE_WRITE)
896			    && (perm & (1 << TOMOYO_TYPE_READ_WRITE)))
897				continue;
898			break;
899		}
900		if (bit >= TOMOYO_MAX_PATH_OPERATION)
901			goto done;
902		tomoyo_io_printf(head, "allow_%s", tomoyo_path_keyword[bit]);
903		tomoyo_print_name_union(head, &ptr->name);
904	} else if (head->r.print_execute_only) {
905		return true;
906	} else if (acl_type == TOMOYO_TYPE_PATH2_ACL) {
907		struct tomoyo_path2_acl *ptr =
908			container_of(acl, typeof(*ptr), head);
909		bit = tomoyo_fns(ptr->perm, bit);
910		if (bit >= TOMOYO_MAX_PATH2_OPERATION)
911			goto done;
912		tomoyo_io_printf(head, "allow_%s", tomoyo_path2_keyword[bit]);
913		tomoyo_print_name_union(head, &ptr->name1);
914		tomoyo_print_name_union(head, &ptr->name2);
915	} else if (acl_type == TOMOYO_TYPE_PATH_NUMBER_ACL) {
916		struct tomoyo_path_number_acl *ptr =
917			container_of(acl, typeof(*ptr), head);
918		bit = tomoyo_fns(ptr->perm, bit);
919		if (bit >= TOMOYO_MAX_PATH_NUMBER_OPERATION)
920			goto done;
921		tomoyo_io_printf(head, "allow_%s",
922				 tomoyo_path_number_keyword[bit]);
923		tomoyo_print_name_union(head, &ptr->name);
924		tomoyo_print_number_union(head, &ptr->number);
925	} else if (acl_type == TOMOYO_TYPE_MKDEV_ACL) {
926		struct tomoyo_mkdev_acl *ptr =
927			container_of(acl, typeof(*ptr), head);
928		bit = tomoyo_fns(ptr->perm, bit);
929		if (bit >= TOMOYO_MAX_MKDEV_OPERATION)
930			goto done;
931		tomoyo_io_printf(head, "allow_%s", tomoyo_mkdev_keyword[bit]);
932		tomoyo_print_name_union(head, &ptr->name);
933		tomoyo_print_number_union(head, &ptr->mode);
934		tomoyo_print_number_union(head, &ptr->major);
935		tomoyo_print_number_union(head, &ptr->minor);
936	} else if (acl_type == TOMOYO_TYPE_MOUNT_ACL) {
937		struct tomoyo_mount_acl *ptr =
938			container_of(acl, typeof(*ptr), head);
939		tomoyo_io_printf(head, "allow_mount");
940		tomoyo_print_name_union(head, &ptr->dev_name);
941		tomoyo_print_name_union(head, &ptr->dir_name);
942		tomoyo_print_name_union(head, &ptr->fs_type);
943		tomoyo_print_number_union(head, &ptr->flags);
944	}
945	head->r.bit = bit + 1;
946	tomoyo_io_printf(head, "\n");
947	if (acl_type != TOMOYO_TYPE_MOUNT_ACL)
948		goto next;
949 done:
950	head->r.bit = 0;
951	return true;
952}
953
954/**
955 * tomoyo_read_domain2 - Read domain policy.
956 *
957 * @head:   Pointer to "struct tomoyo_io_buffer".
958 * @domain: Pointer to "struct tomoyo_domain_info".
959 *
960 * Caller holds tomoyo_read_lock().
961 *
962 * Returns true on success, false otherwise.
963 */
964static bool tomoyo_read_domain2(struct tomoyo_io_buffer *head,
965				struct tomoyo_domain_info *domain)
966{
967	list_for_each_cookie(head->r.acl, &domain->acl_info_list) {
968		struct tomoyo_acl_info *ptr =
969			list_entry(head->r.acl, typeof(*ptr), list);
970		if (!tomoyo_print_entry(head, ptr))
971			return false;
972	}
973	head->r.acl = NULL;
974	return true;
975}
976
977/**
978 * tomoyo_read_domain_policy - Read domain policy.
979 *
980 * @head: Pointer to "struct tomoyo_io_buffer".
981 *
982 * Caller holds tomoyo_read_lock().
983 */
984static void tomoyo_read_domain_policy(struct tomoyo_io_buffer *head)
985{
986	if (head->r.eof)
987		return;
988	list_for_each_cookie(head->r.domain, &tomoyo_domain_list) {
989		struct tomoyo_domain_info *domain =
990			list_entry(head->r.domain, typeof(*domain), list);
991		switch (head->r.step) {
992		case 0:
993			if (domain->is_deleted &&
994			    !head->r.print_this_domain_only)
995				continue;
996			/* Print domainname and flags. */
997			tomoyo_set_string(head, domain->domainname->name);
998			tomoyo_set_lf(head);
999			tomoyo_io_printf(head,
1000					 TOMOYO_KEYWORD_USE_PROFILE "%u\n",
1001					 domain->profile);
1002			if (domain->quota_warned)
1003				tomoyo_set_string(head, "quota_exceeded\n");
1004			if (domain->transition_failed)
1005				tomoyo_set_string(head, "transition_failed\n");
1006			if (domain->ignore_global_allow_read)
1007				tomoyo_set_string(head,
1008				       TOMOYO_KEYWORD_IGNORE_GLOBAL_ALLOW_READ
1009						  "\n");
1010			head->r.step++;
1011			tomoyo_set_lf(head);
1012			/* fall through */
1013		case 1:
1014			if (!tomoyo_read_domain2(head, domain))
1015				return;
1016			head->r.step++;
1017			if (!tomoyo_set_lf(head))
1018				return;
1019			/* fall through */
1020		case 2:
1021			head->r.step = 0;
1022			if (head->r.print_this_domain_only)
1023				goto done;
1024		}
1025	}
1026 done:
1027	head->r.eof = true;
1028}
1029
1030/**
1031 * tomoyo_write_domain_profile - Assign profile for specified domain.
1032 *
1033 * @head: Pointer to "struct tomoyo_io_buffer".
1034 *
1035 * Returns 0 on success, -EINVAL otherwise.
1036 *
1037 * This is equivalent to doing
1038 *
1039 *     ( echo "select " $domainname; echo "use_profile " $profile ) |
1040 *     /usr/sbin/tomoyo-loadpolicy -d
1041 *
1042 * Caller holds tomoyo_read_lock().
1043 */
1044static int tomoyo_write_domain_profile(struct tomoyo_io_buffer *head)
1045{
1046	char *data = head->write_buf;
1047	char *cp = strchr(data, ' ');
1048	struct tomoyo_domain_info *domain;
1049	unsigned long profile;
1050
1051	if (!cp)
1052		return -EINVAL;
1053	*cp = '\0';
1054	domain = tomoyo_find_domain(cp + 1);
1055	if (strict_strtoul(data, 10, &profile))
1056		return -EINVAL;
1057	if (domain && profile < TOMOYO_MAX_PROFILES
1058	    && (tomoyo_profile_ptr[profile] || !tomoyo_policy_loaded))
1059		domain->profile = (u8) profile;
1060	return 0;
1061}
1062
1063/**
1064 * tomoyo_read_domain_profile - Read only domainname and profile.
1065 *
1066 * @head: Pointer to "struct tomoyo_io_buffer".
1067 *
1068 * Returns list of profile number and domainname pairs.
1069 *
1070 * This is equivalent to doing
1071 *
1072 *     grep -A 1 '^<kernel>' /sys/kernel/security/tomoyo/domain_policy |
1073 *     awk ' { if ( domainname == "" ) { if ( $1 == "<kernel>" )
1074 *     domainname = $0; } else if ( $1 == "use_profile" ) {
1075 *     print $2 " " domainname; domainname = ""; } } ; '
1076 *
1077 * Caller holds tomoyo_read_lock().
1078 */
1079static void tomoyo_read_domain_profile(struct tomoyo_io_buffer *head)
1080{
1081	if (head->r.eof)
1082		return;
1083	list_for_each_cookie(head->r.domain, &tomoyo_domain_list) {
1084		struct tomoyo_domain_info *domain =
1085			list_entry(head->r.domain, typeof(*domain), list);
1086		if (domain->is_deleted)
1087			continue;
1088		if (!tomoyo_flush(head))
1089			return;
1090		tomoyo_io_printf(head, "%u ", domain->profile);
1091		tomoyo_set_string(head, domain->domainname->name);
1092		tomoyo_set_lf(head);
1093	}
1094	head->r.eof = true;
1095}
1096
1097/**
1098 * tomoyo_write_pid: Specify PID to obtain domainname.
1099 *
1100 * @head: Pointer to "struct tomoyo_io_buffer".
1101 *
1102 * Returns 0.
1103 */
1104static int tomoyo_write_pid(struct tomoyo_io_buffer *head)
1105{
1106	head->r.eof = false;
1107	return 0;
1108}
1109
1110/**
1111 * tomoyo_read_pid - Get domainname of the specified PID.
1112 *
1113 * @head: Pointer to "struct tomoyo_io_buffer".
1114 *
1115 * Returns the domainname which the specified PID is in on success,
1116 * empty string otherwise.
1117 * The PID is specified by tomoyo_write_pid() so that the user can obtain
1118 * using read()/write() interface rather than sysctl() interface.
1119 */
1120static void tomoyo_read_pid(struct tomoyo_io_buffer *head)
1121{
1122	char *buf = head->write_buf;
1123	bool global_pid = false;
1124	unsigned int pid;
1125	struct task_struct *p;
1126	struct tomoyo_domain_info *domain = NULL;
1127
1128	/* Accessing write_buf is safe because head->io_sem is held. */
1129	if (!buf) {
1130		head->r.eof = true;
1131		return; /* Do nothing if open(O_RDONLY). */
1132	}
1133	if (head->r.w_pos || head->r.eof)
1134		return;
1135	head->r.eof = true;
1136	if (tomoyo_str_starts(&buf, "global-pid "))
1137		global_pid = true;
1138	pid = (unsigned int) simple_strtoul(buf, NULL, 10);
1139	rcu_read_lock();
1140	read_lock(&tasklist_lock);
1141	if (global_pid)
1142		p = find_task_by_pid_ns(pid, &init_pid_ns);
1143	else
1144		p = find_task_by_vpid(pid);
1145	if (p)
1146		domain = tomoyo_real_domain(p);
1147	read_unlock(&tasklist_lock);
1148	rcu_read_unlock();
1149	if (!domain)
1150		return;
1151	tomoyo_io_printf(head, "%u %u ", pid, domain->profile);
1152	tomoyo_set_string(head, domain->domainname->name);
1153}
1154
1155static const char *tomoyo_transition_type[TOMOYO_MAX_TRANSITION_TYPE] = {
1156	[TOMOYO_TRANSITION_CONTROL_NO_INITIALIZE]
1157	= TOMOYO_KEYWORD_NO_INITIALIZE_DOMAIN,
1158	[TOMOYO_TRANSITION_CONTROL_INITIALIZE]
1159	= TOMOYO_KEYWORD_INITIALIZE_DOMAIN,
1160	[TOMOYO_TRANSITION_CONTROL_NO_KEEP] = TOMOYO_KEYWORD_NO_KEEP_DOMAIN,
1161	[TOMOYO_TRANSITION_CONTROL_KEEP] = TOMOYO_KEYWORD_KEEP_DOMAIN
1162};
1163
1164/**
1165 * tomoyo_write_exception_policy - Write exception policy.
1166 *
1167 * @head: Pointer to "struct tomoyo_io_buffer".
1168 *
1169 * Returns 0 on success, negative value otherwise.
1170 *
1171 * Caller holds tomoyo_read_lock().
1172 */
1173static int tomoyo_write_exception_policy(struct tomoyo_io_buffer *head)
1174{
1175	char *data = head->write_buf;
1176	bool is_delete = tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE);
1177	u8 i;
1178
1179	for (i = 0; i < TOMOYO_MAX_TRANSITION_TYPE; i++) {
1180		if (tomoyo_str_starts(&data, tomoyo_transition_type[i]))
1181			return tomoyo_write_transition_control(data, is_delete,
1182							       i);
1183	}
1184	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_AGGREGATOR))
1185		return tomoyo_write_aggregator_policy(data, is_delete);
1186	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALLOW_READ))
1187		return tomoyo_write_globally_readable_policy(data, is_delete);
1188	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_FILE_PATTERN))
1189		return tomoyo_write_pattern_policy(data, is_delete);
1190	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_DENY_REWRITE))
1191		return tomoyo_write_no_rewrite_policy(data, is_delete);
1192	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_PATH_GROUP))
1193		return tomoyo_write_group(data, is_delete, TOMOYO_PATH_GROUP);
1194	if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_NUMBER_GROUP))
1195		return tomoyo_write_group(data, is_delete, TOMOYO_NUMBER_GROUP);
1196	return -EINVAL;
1197}
1198
1199static const char *tomoyo_group_name[TOMOYO_MAX_GROUP] = {
1200	[TOMOYO_PATH_GROUP] = TOMOYO_KEYWORD_PATH_GROUP,
1201	[TOMOYO_NUMBER_GROUP] = TOMOYO_KEYWORD_NUMBER_GROUP
1202};
1203
1204/**
1205 * tomoyo_read_group - Read "struct tomoyo_path_group"/"struct tomoyo_number_group" list.
1206 *
1207 * @head: Pointer to "struct tomoyo_io_buffer".
1208 * @idx:  Index number.
1209 *
1210 * Returns true on success, false otherwise.
1211 *
1212 * Caller holds tomoyo_read_lock().
1213 */
1214static bool tomoyo_read_group(struct tomoyo_io_buffer *head, const int idx)
1215{
1216	list_for_each_cookie(head->r.group, &tomoyo_group_list[idx]) {
1217		struct tomoyo_group *group =
1218			list_entry(head->r.group, typeof(*group), list);
1219		list_for_each_cookie(head->r.acl, &group->member_list) {
1220			struct tomoyo_acl_head *ptr =
1221				list_entry(head->r.acl, typeof(*ptr), list);
1222			if (ptr->is_deleted)
1223				continue;
1224			if (!tomoyo_flush(head))
1225				return false;
1226			tomoyo_set_string(head, tomoyo_group_name[idx]);
1227			tomoyo_set_string(head, group->group_name->name);
1228			if (idx == TOMOYO_PATH_GROUP) {
1229				tomoyo_set_space(head);
1230				tomoyo_set_string(head, container_of
1231					       (ptr, struct tomoyo_path_group,
1232						head)->member_name->name);
1233			} else if (idx == TOMOYO_NUMBER_GROUP) {
1234				tomoyo_print_number_union(head, &container_of
1235							  (ptr,
1236						   struct tomoyo_number_group,
1237							   head)->number);
1238			}
1239			tomoyo_set_lf(head);
1240		}
1241		head->r.acl = NULL;
1242	}
1243	head->r.group = NULL;
1244	return true;
1245}
1246
1247/**
1248 * tomoyo_read_policy - Read "struct tomoyo_..._entry" list.
1249 *
1250 * @head: Pointer to "struct tomoyo_io_buffer".
1251 * @idx:  Index number.
1252 *
1253 * Returns true on success, false otherwise.
1254 *
1255 * Caller holds tomoyo_read_lock().
1256 */
1257static bool tomoyo_read_policy(struct tomoyo_io_buffer *head, const int idx)
1258{
1259	list_for_each_cookie(head->r.acl, &tomoyo_policy_list[idx]) {
1260		struct tomoyo_acl_head *acl =
1261			container_of(head->r.acl, typeof(*acl), list);
1262		if (acl->is_deleted)
1263			continue;
1264		if (!tomoyo_flush(head))
1265			return false;
1266		switch (idx) {
1267		case TOMOYO_ID_TRANSITION_CONTROL:
1268			{
1269				struct tomoyo_transition_control *ptr =
1270					container_of(acl, typeof(*ptr), head);
1271				tomoyo_set_string(head,
1272						  tomoyo_transition_type
1273						  [ptr->type]);
1274				if (ptr->program)
1275					tomoyo_set_string(head,
1276							  ptr->program->name);
1277				if (ptr->program && ptr->domainname)
1278					tomoyo_set_string(head, " from ");
1279				if (ptr->domainname)
1280					tomoyo_set_string(head,
1281							  ptr->domainname->
1282							  name);
1283			}
1284			break;
1285		case TOMOYO_ID_GLOBALLY_READABLE:
1286			{
1287				struct tomoyo_globally_readable_file_entry *ptr
1288					= container_of(acl, typeof(*ptr), head);
1289				tomoyo_set_string(head,
1290						  TOMOYO_KEYWORD_ALLOW_READ);
1291				tomoyo_set_string(head, ptr->filename->name);
1292			}
1293			break;
1294		case TOMOYO_ID_AGGREGATOR:
1295			{
1296				struct tomoyo_aggregator_entry *ptr =
1297					container_of(acl, typeof(*ptr), head);
1298				tomoyo_set_string(head,
1299						  TOMOYO_KEYWORD_AGGREGATOR);
1300				tomoyo_set_string(head,
1301						  ptr->original_name->name);
1302				tomoyo_set_space(head);
1303				tomoyo_set_string(head,
1304					       ptr->aggregated_name->name);
1305			}
1306			break;
1307		case TOMOYO_ID_PATTERN:
1308			{
1309				struct tomoyo_pattern_entry *ptr =
1310					container_of(acl, typeof(*ptr), head);
1311				tomoyo_set_string(head,
1312						  TOMOYO_KEYWORD_FILE_PATTERN);
1313				tomoyo_set_string(head, ptr->pattern->name);
1314			}
1315			break;
1316		case TOMOYO_ID_NO_REWRITE:
1317			{
1318				struct tomoyo_no_rewrite_entry *ptr =
1319					container_of(acl, typeof(*ptr), head);
1320				tomoyo_set_string(head,
1321						  TOMOYO_KEYWORD_DENY_REWRITE);
1322				tomoyo_set_string(head, ptr->pattern->name);
1323			}
1324			break;
1325		default:
1326			continue;
1327		}
1328		tomoyo_set_lf(head);
1329	}
1330	head->r.acl = NULL;
1331	return true;
1332}
1333
1334/**
1335 * tomoyo_read_exception_policy - Read exception policy.
1336 *
1337 * @head: Pointer to "struct tomoyo_io_buffer".
1338 *
1339 * Caller holds tomoyo_read_lock().
1340 */
1341static void tomoyo_read_exception_policy(struct tomoyo_io_buffer *head)
1342{
1343	if (head->r.eof)
1344		return;
1345	while (head->r.step < TOMOYO_MAX_POLICY &&
1346	       tomoyo_read_policy(head, head->r.step))
1347		head->r.step++;
1348	if (head->r.step < TOMOYO_MAX_POLICY)
1349		return;
1350	while (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP &&
1351	       tomoyo_read_group(head, head->r.step - TOMOYO_MAX_POLICY))
1352		head->r.step++;
1353	if (head->r.step < TOMOYO_MAX_POLICY + TOMOYO_MAX_GROUP)
1354		return;
1355	head->r.eof = true;
1356}
1357
1358/**
1359 * tomoyo_print_header - Get header line of audit log.
1360 *
1361 * @r: Pointer to "struct tomoyo_request_info".
1362 *
1363 * Returns string representation.
1364 *
1365 * This function uses kmalloc(), so caller must kfree() if this function
1366 * didn't return NULL.
1367 */
1368static char *tomoyo_print_header(struct tomoyo_request_info *r)
1369{
1370	struct timeval tv;
1371	const pid_t gpid = task_pid_nr(current);
1372	static const int tomoyo_buffer_len = 4096;
1373	char *buffer = kmalloc(tomoyo_buffer_len, GFP_NOFS);
1374	if (!buffer)
1375		return NULL;
1376	do_gettimeofday(&tv);
1377	snprintf(buffer, tomoyo_buffer_len - 1,
1378		 "#timestamp=%lu profile=%u mode=%s (global-pid=%u)"
1379		 " task={ pid=%u ppid=%u uid=%u gid=%u euid=%u"
1380		 " egid=%u suid=%u sgid=%u fsuid=%u fsgid=%u }",
1381		 tv.tv_sec, r->profile, tomoyo_mode[r->mode], gpid,
1382		 (pid_t) sys_getpid(), (pid_t) sys_getppid(),
1383		 current_uid(), current_gid(), current_euid(),
1384		 current_egid(), current_suid(), current_sgid(),
1385		 current_fsuid(), current_fsgid());
1386	return buffer;
1387}
1388
1389/**
1390 * tomoyo_init_audit_log - Allocate buffer for audit logs.
1391 *
1392 * @len: Required size.
1393 * @r:   Pointer to "struct tomoyo_request_info".
1394 *
1395 * Returns pointer to allocated memory.
1396 *
1397 * The @len is updated to add the header lines' size on success.
1398 *
1399 * This function uses kzalloc(), so caller must kfree() if this function
1400 * didn't return NULL.
1401 */
1402static char *tomoyo_init_audit_log(int *len, struct tomoyo_request_info *r)
1403{
1404	char *buf = NULL;
1405	const char *header;
1406	const char *domainname;
1407	if (!r->domain)
1408		r->domain = tomoyo_domain();
1409	domainname = r->domain->domainname->name;
1410	header = tomoyo_print_header(r);
1411	if (!header)
1412		return NULL;
1413	*len += strlen(domainname) + strlen(header) + 10;
1414	buf = kzalloc(*len, GFP_NOFS);
1415	if (buf)
1416		snprintf(buf, (*len) - 1, "%s\n%s\n", header, domainname);
1417	kfree(header);
1418	return buf;
1419}
1420
1421/* Wait queue for tomoyo_query_list. */
1422static DECLARE_WAIT_QUEUE_HEAD(tomoyo_query_wait);
1423
1424/* Lock for manipulating tomoyo_query_list. */
1425static DEFINE_SPINLOCK(tomoyo_query_list_lock);
1426
1427/* Structure for query. */
1428struct tomoyo_query_entry {
1429	struct list_head list;
1430	char *query;
1431	int query_len;
1432	unsigned int serial;
1433	int timer;
1434	int answer;
1435};
1436
1437/* The list for "struct tomoyo_query_entry". */
1438static LIST_HEAD(tomoyo_query_list);
1439
1440/*
1441 * Number of "struct file" referring /sys/kernel/security/tomoyo/query
1442 * interface.
1443 */
1444static atomic_t tomoyo_query_observers = ATOMIC_INIT(0);
1445
1446/**
1447 * tomoyo_supervisor - Ask for the supervisor's decision.
1448 *
1449 * @r:       Pointer to "struct tomoyo_request_info".
1450 * @fmt:     The printf()'s format string, followed by parameters.
1451 *
1452 * Returns 0 if the supervisor decided to permit the access request which
1453 * violated the policy in enforcing mode, TOMOYO_RETRY_REQUEST if the
1454 * supervisor decided to retry the access request which violated the policy in
1455 * enforcing mode, 0 if it is not in enforcing mode, -EPERM otherwise.
1456 */
1457int tomoyo_supervisor(struct tomoyo_request_info *r, const char *fmt, ...)
1458{
1459	va_list args;
1460	int error = -EPERM;
1461	int pos;
1462	int len;
1463	static unsigned int tomoyo_serial;
1464	struct tomoyo_query_entry *tomoyo_query_entry = NULL;
1465	bool quota_exceeded = false;
1466	char *header;
1467	switch (r->mode) {
1468		char *buffer;
1469	case TOMOYO_CONFIG_LEARNING:
1470		if (!tomoyo_domain_quota_is_ok(r))
1471			return 0;
1472		va_start(args, fmt);
1473		len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 4;
1474		va_end(args);
1475		buffer = kmalloc(len, GFP_NOFS);
1476		if (!buffer)
1477			return 0;
1478		va_start(args, fmt);
1479		vsnprintf(buffer, len - 1, fmt, args);
1480		va_end(args);
1481		tomoyo_normalize_line(buffer);
1482		tomoyo_write_domain_policy2(buffer, r->domain, false);
1483		kfree(buffer);
1484		/* fall through */
1485	case TOMOYO_CONFIG_PERMISSIVE:
1486		return 0;
1487	}
1488	if (!r->domain)
1489		r->domain = tomoyo_domain();
1490	if (!atomic_read(&tomoyo_query_observers))
1491		return -EPERM;
1492	va_start(args, fmt);
1493	len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 32;
1494	va_end(args);
1495	header = tomoyo_init_audit_log(&len, r);
1496	if (!header)
1497		goto out;
1498	tomoyo_query_entry = kzalloc(sizeof(*tomoyo_query_entry), GFP_NOFS);
1499	if (!tomoyo_query_entry)
1500		goto out;
1501	tomoyo_query_entry->query = kzalloc(len, GFP_NOFS);
1502	if (!tomoyo_query_entry->query)
1503		goto out;
1504	len = ksize(tomoyo_query_entry->query);
1505	INIT_LIST_HEAD(&tomoyo_query_entry->list);
1506	spin_lock(&tomoyo_query_list_lock);
1507	if (tomoyo_quota_for_query && tomoyo_query_memory_size + len +
1508	    sizeof(*tomoyo_query_entry) >= tomoyo_quota_for_query) {
1509		quota_exceeded = true;
1510	} else {
1511		tomoyo_query_memory_size += len + sizeof(*tomoyo_query_entry);
1512		tomoyo_query_entry->serial = tomoyo_serial++;
1513	}
1514	spin_unlock(&tomoyo_query_list_lock);
1515	if (quota_exceeded)
1516		goto out;
1517	pos = snprintf(tomoyo_query_entry->query, len - 1, "Q%u-%hu\n%s",
1518		       tomoyo_query_entry->serial, r->retry, header);
1519	kfree(header);
1520	header = NULL;
1521	va_start(args, fmt);
1522	vsnprintf(tomoyo_query_entry->query + pos, len - 1 - pos, fmt, args);
1523	tomoyo_query_entry->query_len = strlen(tomoyo_query_entry->query) + 1;
1524	va_end(args);
1525	spin_lock(&tomoyo_query_list_lock);
1526	list_add_tail(&tomoyo_query_entry->list, &tomoyo_query_list);
1527	spin_unlock(&tomoyo_query_list_lock);
1528	/* Give 10 seconds for supervisor's opinion. */
1529	for (tomoyo_query_entry->timer = 0;
1530	     atomic_read(&tomoyo_query_observers) && tomoyo_query_entry->timer < 100;
1531	     tomoyo_query_entry->timer++) {
1532		wake_up(&tomoyo_query_wait);
1533		set_current_state(TASK_INTERRUPTIBLE);
1534		schedule_timeout(HZ / 10);
1535		if (tomoyo_query_entry->answer)
1536			break;
1537	}
1538	spin_lock(&tomoyo_query_list_lock);
1539	list_del(&tomoyo_query_entry->list);
1540	tomoyo_query_memory_size -= len + sizeof(*tomoyo_query_entry);
1541	spin_unlock(&tomoyo_query_list_lock);
1542	switch (tomoyo_query_entry->answer) {
1543	case 3: /* Asked to retry by administrator. */
1544		error = TOMOYO_RETRY_REQUEST;
1545		r->retry++;
1546		break;
1547	case 1:
1548		/* Granted by administrator. */
1549		error = 0;
1550		break;
1551	case 0:
1552		/* Timed out. */
1553		break;
1554	default:
1555		/* Rejected by administrator. */
1556		break;
1557	}
1558 out:
1559	if (tomoyo_query_entry)
1560		kfree(tomoyo_query_entry->query);
1561	kfree(tomoyo_query_entry);
1562	kfree(header);
1563	return error;
1564}
1565
1566/**
1567 * tomoyo_poll_query - poll() for /sys/kernel/security/tomoyo/query.
1568 *
1569 * @file: Pointer to "struct file".
1570 * @wait: Pointer to "poll_table".
1571 *
1572 * Returns POLLIN | POLLRDNORM when ready to read, 0 otherwise.
1573 *
1574 * Waits for access requests which violated policy in enforcing mode.
1575 */
1576static int tomoyo_poll_query(struct file *file, poll_table *wait)
1577{
1578	struct list_head *tmp;
1579	bool found = false;
1580	u8 i;
1581	for (i = 0; i < 2; i++) {
1582		spin_lock(&tomoyo_query_list_lock);
1583		list_for_each(tmp, &tomoyo_query_list) {
1584			struct tomoyo_query_entry *ptr
1585				= list_entry(tmp, struct tomoyo_query_entry,
1586					     list);
1587			if (ptr->answer)
1588				continue;
1589			found = true;
1590			break;
1591		}
1592		spin_unlock(&tomoyo_query_list_lock);
1593		if (found)
1594			return POLLIN | POLLRDNORM;
1595		if (i)
1596			break;
1597		poll_wait(file, &tomoyo_query_wait, wait);
1598	}
1599	return 0;
1600}
1601
1602/**
1603 * tomoyo_read_query - Read access requests which violated policy in enforcing mode.
1604 *
1605 * @head: Pointer to "struct tomoyo_io_buffer".
1606 */
1607static void tomoyo_read_query(struct tomoyo_io_buffer *head)
1608{
1609	struct list_head *tmp;
1610	int pos = 0;
1611	int len = 0;
1612	char *buf;
1613	if (head->r.w_pos)
1614		return;
1615	if (head->read_buf) {
1616		kfree(head->read_buf);
1617		head->read_buf = NULL;
1618	}
1619	spin_lock(&tomoyo_query_list_lock);
1620	list_for_each(tmp, &tomoyo_query_list) {
1621		struct tomoyo_query_entry *ptr =
1622			list_entry(tmp, typeof(*ptr), list);
1623		if (ptr->answer)
1624			continue;
1625		if (pos++ != head->r.query_index)
1626			continue;
1627		len = ptr->query_len;
1628		break;
1629	}
1630	spin_unlock(&tomoyo_query_list_lock);
1631	if (!len) {
1632		head->r.query_index = 0;
1633		return;
1634	}
1635	buf = kzalloc(len, GFP_NOFS);
1636	if (!buf)
1637		return;
1638	pos = 0;
1639	spin_lock(&tomoyo_query_list_lock);
1640	list_for_each(tmp, &tomoyo_query_list) {
1641		struct tomoyo_query_entry *ptr =
1642			list_entry(tmp, typeof(*ptr), list);
1643		if (ptr->answer)
1644			continue;
1645		if (pos++ != head->r.query_index)
1646			continue;
1647		/*
1648		 * Some query can be skipped because tomoyo_query_list
1649		 * can change, but I don't care.
1650		 */
1651		if (len == ptr->query_len)
1652			memmove(buf, ptr->query, len);
1653		break;
1654	}
1655	spin_unlock(&tomoyo_query_list_lock);
1656	if (buf[0]) {
1657		head->read_buf = buf;
1658		head->r.w[head->r.w_pos++] = buf;
1659		head->r.query_index++;
1660	} else {
1661		kfree(buf);
1662	}
1663}
1664
1665/**
1666 * tomoyo_write_answer - Write the supervisor's decision.
1667 *
1668 * @head: Pointer to "struct tomoyo_io_buffer".
1669 *
1670 * Returns 0 on success, -EINVAL otherwise.
1671 */
1672static int tomoyo_write_answer(struct tomoyo_io_buffer *head)
1673{
1674	char *data = head->write_buf;
1675	struct list_head *tmp;
1676	unsigned int serial;
1677	unsigned int answer;
1678	spin_lock(&tomoyo_query_list_lock);
1679	list_for_each(tmp, &tomoyo_query_list) {
1680		struct tomoyo_query_entry *ptr
1681			= list_entry(tmp, struct tomoyo_query_entry, list);
1682		ptr->timer = 0;
1683	}
1684	spin_unlock(&tomoyo_query_list_lock);
1685	if (sscanf(data, "A%u=%u", &serial, &answer) != 2)
1686		return -EINVAL;
1687	spin_lock(&tomoyo_query_list_lock);
1688	list_for_each(tmp, &tomoyo_query_list) {
1689		struct tomoyo_query_entry *ptr
1690			= list_entry(tmp, struct tomoyo_query_entry, list);
1691		if (ptr->serial != serial)
1692			continue;
1693		if (!ptr->answer)
1694			ptr->answer = answer;
1695		break;
1696	}
1697	spin_unlock(&tomoyo_query_list_lock);
1698	return 0;
1699}
1700
1701/**
1702 * tomoyo_read_version: Get version.
1703 *
1704 * @head: Pointer to "struct tomoyo_io_buffer".
1705 *
1706 * Returns version information.
1707 */
1708static void tomoyo_read_version(struct tomoyo_io_buffer *head)
1709{
1710	if (!head->r.eof) {
1711		tomoyo_io_printf(head, "2.3.0-pre");
1712		head->r.eof = true;
1713	}
1714}
1715
1716/**
1717 * tomoyo_read_self_domain - Get the current process's domainname.
1718 *
1719 * @head: Pointer to "struct tomoyo_io_buffer".
1720 *
1721 * Returns the current process's domainname.
1722 */
1723static void tomoyo_read_self_domain(struct tomoyo_io_buffer *head)
1724{
1725	if (!head->r.eof) {
1726		/*
1727		 * tomoyo_domain()->domainname != NULL
1728		 * because every process belongs to a domain and
1729		 * the domain's name cannot be NULL.
1730		 */
1731		tomoyo_io_printf(head, "%s", tomoyo_domain()->domainname->name);
1732		head->r.eof = true;
1733	}
1734}
1735
1736/**
1737 * tomoyo_open_control - open() for /sys/kernel/security/tomoyo/ interface.
1738 *
1739 * @type: Type of interface.
1740 * @file: Pointer to "struct file".
1741 *
1742 * Associates policy handler and returns 0 on success, -ENOMEM otherwise.
1743 *
1744 * Caller acquires tomoyo_read_lock().
1745 */
1746int tomoyo_open_control(const u8 type, struct file *file)
1747{
1748	struct tomoyo_io_buffer *head = kzalloc(sizeof(*head), GFP_NOFS);
1749
1750	if (!head)
1751		return -ENOMEM;
1752	mutex_init(&head->io_sem);
1753	head->type = type;
1754	switch (type) {
1755	case TOMOYO_DOMAINPOLICY:
1756		/* /sys/kernel/security/tomoyo/domain_policy */
1757		head->write = tomoyo_write_domain_policy;
1758		head->read = tomoyo_read_domain_policy;
1759		break;
1760	case TOMOYO_EXCEPTIONPOLICY:
1761		/* /sys/kernel/security/tomoyo/exception_policy */
1762		head->write = tomoyo_write_exception_policy;
1763		head->read = tomoyo_read_exception_policy;
1764		break;
1765	case TOMOYO_SELFDOMAIN:
1766		/* /sys/kernel/security/tomoyo/self_domain */
1767		head->read = tomoyo_read_self_domain;
1768		break;
1769	case TOMOYO_DOMAIN_STATUS:
1770		/* /sys/kernel/security/tomoyo/.domain_status */
1771		head->write = tomoyo_write_domain_profile;
1772		head->read = tomoyo_read_domain_profile;
1773		break;
1774	case TOMOYO_PROCESS_STATUS:
1775		/* /sys/kernel/security/tomoyo/.process_status */
1776		head->write = tomoyo_write_pid;
1777		head->read = tomoyo_read_pid;
1778		break;
1779	case TOMOYO_VERSION:
1780		/* /sys/kernel/security/tomoyo/version */
1781		head->read = tomoyo_read_version;
1782		head->readbuf_size = 128;
1783		break;
1784	case TOMOYO_MEMINFO:
1785		/* /sys/kernel/security/tomoyo/meminfo */
1786		head->write = tomoyo_write_memory_quota;
1787		head->read = tomoyo_read_memory_counter;
1788		head->readbuf_size = 512;
1789		break;
1790	case TOMOYO_PROFILE:
1791		/* /sys/kernel/security/tomoyo/profile */
1792		head->write = tomoyo_write_profile;
1793		head->read = tomoyo_read_profile;
1794		break;
1795	case TOMOYO_QUERY: /* /sys/kernel/security/tomoyo/query */
1796		head->poll = tomoyo_poll_query;
1797		head->write = tomoyo_write_answer;
1798		head->read = tomoyo_read_query;
1799		break;
1800	case TOMOYO_MANAGER:
1801		/* /sys/kernel/security/tomoyo/manager */
1802		head->write = tomoyo_write_manager_policy;
1803		head->read = tomoyo_read_manager_policy;
1804		break;
1805	}
1806	if (!(file->f_mode & FMODE_READ)) {
1807		/*
1808		 * No need to allocate read_buf since it is not opened
1809		 * for reading.
1810		 */
1811		head->read = NULL;
1812		head->poll = NULL;
1813	} else if (!head->poll) {
1814		/* Don't allocate read_buf for poll() access. */
1815		if (!head->readbuf_size)
1816			head->readbuf_size = 4096 * 2;
1817		head->read_buf = kzalloc(head->readbuf_size, GFP_NOFS);
1818		if (!head->read_buf) {
1819			kfree(head);
1820			return -ENOMEM;
1821		}
1822	}
1823	if (!(file->f_mode & FMODE_WRITE)) {
1824		/*
1825		 * No need to allocate write_buf since it is not opened
1826		 * for writing.
1827		 */
1828		head->write = NULL;
1829	} else if (head->write) {
1830		head->writebuf_size = 4096 * 2;
1831		head->write_buf = kzalloc(head->writebuf_size, GFP_NOFS);
1832		if (!head->write_buf) {
1833			kfree(head->read_buf);
1834			kfree(head);
1835			return -ENOMEM;
1836		}
1837	}
1838	if (type != TOMOYO_QUERY)
1839		head->reader_idx = tomoyo_read_lock();
1840	file->private_data = head;
1841	/*
1842	 * Call the handler now if the file is
1843	 * /sys/kernel/security/tomoyo/self_domain
1844	 * so that the user can use
1845	 * cat < /sys/kernel/security/tomoyo/self_domain"
1846	 * to know the current process's domainname.
1847	 */
1848	if (type == TOMOYO_SELFDOMAIN)
1849		tomoyo_read_control(file, NULL, 0);
1850	/*
1851	 * If the file is /sys/kernel/security/tomoyo/query , increment the
1852	 * observer counter.
1853	 * The obserber counter is used by tomoyo_supervisor() to see if
1854	 * there is some process monitoring /sys/kernel/security/tomoyo/query.
1855	 */
1856	else if (type == TOMOYO_QUERY)
1857		atomic_inc(&tomoyo_query_observers);
1858	return 0;
1859}
1860
1861/**
1862 * tomoyo_poll_control - poll() for /sys/kernel/security/tomoyo/ interface.
1863 *
1864 * @file: Pointer to "struct file".
1865 * @wait: Pointer to "poll_table".
1866 *
1867 * Waits for read readiness.
1868 * /sys/kernel/security/tomoyo/query is handled by /usr/sbin/tomoyo-queryd .
1869 */
1870int tomoyo_poll_control(struct file *file, poll_table *wait)
1871{
1872	struct tomoyo_io_buffer *head = file->private_data;
1873	if (!head->poll)
1874		return -ENOSYS;
1875	return head->poll(file, wait);
1876}
1877
1878/**
1879 * tomoyo_read_control - read() for /sys/kernel/security/tomoyo/ interface.
1880 *
1881 * @file:       Pointer to "struct file".
1882 * @buffer:     Poiner to buffer to write to.
1883 * @buffer_len: Size of @buffer.
1884 *
1885 * Returns bytes read on success, negative value otherwise.
1886 *
1887 * Caller holds tomoyo_read_lock().
1888 */
1889int tomoyo_read_control(struct file *file, char __user *buffer,
1890			const int buffer_len)
1891{
1892	int len;
1893	struct tomoyo_io_buffer *head = file->private_data;
1894
1895	if (!head->read)
1896		return -ENOSYS;
1897	if (mutex_lock_interruptible(&head->io_sem))
1898		return -EINTR;
1899	head->read_user_buf = buffer;
1900	head->read_user_buf_avail = buffer_len;
1901	if (tomoyo_flush(head))
1902		/* Call the policy handler. */
1903		head->read(head);
1904	tomoyo_flush(head);
1905	len = head->read_user_buf - buffer;
1906	mutex_unlock(&head->io_sem);
1907	return len;
1908}
1909
1910/**
1911 * tomoyo_write_control - write() for /sys/kernel/security/tomoyo/ interface.
1912 *
1913 * @file:       Pointer to "struct file".
1914 * @buffer:     Pointer to buffer to read from.
1915 * @buffer_len: Size of @buffer.
1916 *
1917 * Returns @buffer_len on success, negative value otherwise.
1918 *
1919 * Caller holds tomoyo_read_lock().
1920 */
1921int tomoyo_write_control(struct file *file, const char __user *buffer,
1922			 const int buffer_len)
1923{
1924	struct tomoyo_io_buffer *head = file->private_data;
1925	int error = buffer_len;
1926	int avail_len = buffer_len;
1927	char *cp0 = head->write_buf;
1928
1929	if (!head->write)
1930		return -ENOSYS;
1931	if (!access_ok(VERIFY_READ, buffer, buffer_len))
1932		return -EFAULT;
1933	/* Don't allow updating policies by non manager programs. */
1934	if (head->write != tomoyo_write_pid &&
1935	    head->write != tomoyo_write_domain_policy &&
1936	    !tomoyo_policy_manager())
1937		return -EPERM;
1938	if (mutex_lock_interruptible(&head->io_sem))
1939		return -EINTR;
1940	/* Read a line and dispatch it to the policy handler. */
1941	while (avail_len > 0) {
1942		char c;
1943		if (head->write_avail >= head->writebuf_size - 1) {
1944			error = -ENOMEM;
1945			break;
1946		} else if (get_user(c, buffer)) {
1947			error = -EFAULT;
1948			break;
1949		}
1950		buffer++;
1951		avail_len--;
1952		cp0[head->write_avail++] = c;
1953		if (c != '\n')
1954			continue;
1955		cp0[head->write_avail - 1] = '\0';
1956		head->write_avail = 0;
1957		tomoyo_normalize_line(cp0);
1958		head->write(head);
1959	}
1960	mutex_unlock(&head->io_sem);
1961	return error;
1962}
1963
1964/**
1965 * tomoyo_close_control - close() for /sys/kernel/security/tomoyo/ interface.
1966 *
1967 * @file: Pointer to "struct file".
1968 *
1969 * Releases memory and returns 0.
1970 *
1971 * Caller looses tomoyo_read_lock().
1972 */
1973int tomoyo_close_control(struct file *file)
1974{
1975	struct tomoyo_io_buffer *head = file->private_data;
1976	const bool is_write = !!head->write_buf;
1977
1978	/*
1979	 * If the file is /sys/kernel/security/tomoyo/query , decrement the
1980	 * observer counter.
1981	 */
1982	if (head->type == TOMOYO_QUERY)
1983		atomic_dec(&tomoyo_query_observers);
1984	else
1985		tomoyo_read_unlock(head->reader_idx);
1986	/* Release memory used for policy I/O. */
1987	kfree(head->read_buf);
1988	head->read_buf = NULL;
1989	kfree(head->write_buf);
1990	head->write_buf = NULL;
1991	kfree(head);
1992	head = NULL;
1993	file->private_data = NULL;
1994	if (is_write)
1995		tomoyo_run_gc();
1996	return 0;
1997}
1998
1999/**
2000 * tomoyo_check_profile - Check all profiles currently assigned to domains are defined.
2001 */
2002void tomoyo_check_profile(void)
2003{
2004	struct tomoyo_domain_info *domain;
2005	const int idx = tomoyo_read_lock();
2006	tomoyo_policy_loaded = true;
2007	/* Check all profiles currently assigned to domains are defined. */
2008	list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
2009		const u8 profile = domain->profile;
2010		if (tomoyo_profile_ptr[profile])
2011			continue;
2012		panic("Profile %u (used by '%s') not defined.\n",
2013		      profile, domain->domainname->name);
2014	}
2015	tomoyo_read_unlock(idx);
2016	if (tomoyo_profile_version != 20090903)
2017		panic("Profile version %u is not supported.\n",
2018		      tomoyo_profile_version);
2019	printk(KERN_INFO "TOMOYO: 2.3.0-pre   2010/06/03\n");
2020	printk(KERN_INFO "Mandatory Access Control activated.\n");
2021}
2022