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