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