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