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