TOMOYO: Add pathname aggregation support.
[pandora-kernel.git] / security / tomoyo / common.c
1 /*
2  * security/tomoyo/common.c
3  *
4  * Common functions for TOMOYO.
5  *
6  * Copyright (C) 2005-2010  NTT DATA CORPORATION
7  */
8
9 #include <linux/uaccess.h>
10 #include <linux/slab.h>
11 #include <linux/security.h>
12 #include <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_AGGREGATOR))
1145                 return tomoyo_write_aggregator_policy(data, is_delete);
1146         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALIAS))
1147                 return tomoyo_write_alias_policy(data, is_delete);
1148         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALLOW_READ))
1149                 return tomoyo_write_globally_readable_policy(data, is_delete);
1150         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_FILE_PATTERN))
1151                 return tomoyo_write_pattern_policy(data, is_delete);
1152         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_DENY_REWRITE))
1153                 return tomoyo_write_no_rewrite_policy(data, is_delete);
1154         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_PATH_GROUP))
1155                 return tomoyo_write_path_group_policy(data, is_delete);
1156         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_NUMBER_GROUP))
1157                 return tomoyo_write_number_group_policy(data, is_delete);
1158         return -EINVAL;
1159 }
1160
1161 /**
1162  * tomoyo_read_exception_policy - Read exception policy.
1163  *
1164  * @head: Pointer to "struct tomoyo_io_buffer".
1165  *
1166  * Returns 0 on success, -EINVAL otherwise.
1167  *
1168  * Caller holds tomoyo_read_lock().
1169  */
1170 static int tomoyo_read_exception_policy(struct tomoyo_io_buffer *head)
1171 {
1172         if (!head->read_eof) {
1173                 switch (head->read_step) {
1174                 case 0:
1175                         head->read_var2 = NULL;
1176                         head->read_step = 1;
1177                 case 1:
1178                         if (!tomoyo_read_domain_keeper_policy(head))
1179                                 break;
1180                         head->read_var2 = NULL;
1181                         head->read_step = 2;
1182                 case 2:
1183                         if (!tomoyo_read_globally_readable_policy(head))
1184                                 break;
1185                         head->read_var2 = NULL;
1186                         head->read_step = 3;
1187                 case 3:
1188                         head->read_var2 = NULL;
1189                         head->read_step = 4;
1190                 case 4:
1191                         if (!tomoyo_read_domain_initializer_policy(head))
1192                                 break;
1193                         head->read_var2 = NULL;
1194                         head->read_step = 5;
1195                 case 5:
1196                         if (!tomoyo_read_alias_policy(head))
1197                                 break;
1198                         head->read_var2 = NULL;
1199                         head->read_step = 6;
1200                 case 6:
1201                         if (!tomoyo_read_aggregator_policy(head))
1202                                 break;
1203                         head->read_var2 = NULL;
1204                         head->read_step = 7;
1205                 case 7:
1206                         if (!tomoyo_read_file_pattern(head))
1207                                 break;
1208                         head->read_var2 = NULL;
1209                         head->read_step = 8;
1210                 case 8:
1211                         if (!tomoyo_read_no_rewrite_policy(head))
1212                                 break;
1213                         head->read_var2 = NULL;
1214                         head->read_step = 9;
1215                 case 9:
1216                         if (!tomoyo_read_path_group_policy(head))
1217                                 break;
1218                         head->read_var1 = NULL;
1219                         head->read_var2 = NULL;
1220                         head->read_step = 10;
1221                 case 10:
1222                         if (!tomoyo_read_number_group_policy(head))
1223                                 break;
1224                         head->read_var1 = NULL;
1225                         head->read_var2 = NULL;
1226                         head->read_step = 11;
1227                 case 11:
1228                         head->read_eof = true;
1229                         break;
1230                 default:
1231                         return -EINVAL;
1232                 }
1233         }
1234         return 0;
1235 }
1236
1237 /**
1238  * tomoyo_print_header - Get header line of audit log.
1239  *
1240  * @r: Pointer to "struct tomoyo_request_info".
1241  *
1242  * Returns string representation.
1243  *
1244  * This function uses kmalloc(), so caller must kfree() if this function
1245  * didn't return NULL.
1246  */
1247 static char *tomoyo_print_header(struct tomoyo_request_info *r)
1248 {
1249         static const char *tomoyo_mode_4[4] = {
1250                 "disabled", "learning", "permissive", "enforcing"
1251         };
1252         struct timeval tv;
1253         const pid_t gpid = task_pid_nr(current);
1254         static const int tomoyo_buffer_len = 4096;
1255         char *buffer = kmalloc(tomoyo_buffer_len, GFP_NOFS);
1256         if (!buffer)
1257                 return NULL;
1258         do_gettimeofday(&tv);
1259         snprintf(buffer, tomoyo_buffer_len - 1,
1260                  "#timestamp=%lu profile=%u mode=%s (global-pid=%u)"
1261                  " task={ pid=%u ppid=%u uid=%u gid=%u euid=%u"
1262                  " egid=%u suid=%u sgid=%u fsuid=%u fsgid=%u }",
1263                  tv.tv_sec, r->profile, tomoyo_mode_4[r->mode], gpid,
1264                  (pid_t) sys_getpid(), (pid_t) sys_getppid(),
1265                  current_uid(), current_gid(), current_euid(),
1266                  current_egid(), current_suid(), current_sgid(),
1267                  current_fsuid(), current_fsgid());
1268         return buffer;
1269 }
1270
1271 /**
1272  * tomoyo_init_audit_log - Allocate buffer for audit logs.
1273  *
1274  * @len: Required size.
1275  * @r:   Pointer to "struct tomoyo_request_info".
1276  *
1277  * Returns pointer to allocated memory.
1278  *
1279  * The @len is updated to add the header lines' size on success.
1280  *
1281  * This function uses kzalloc(), so caller must kfree() if this function
1282  * didn't return NULL.
1283  */
1284 static char *tomoyo_init_audit_log(int *len, struct tomoyo_request_info *r)
1285 {
1286         char *buf = NULL;
1287         const char *header;
1288         const char *domainname;
1289         if (!r->domain)
1290                 r->domain = tomoyo_domain();
1291         domainname = r->domain->domainname->name;
1292         header = tomoyo_print_header(r);
1293         if (!header)
1294                 return NULL;
1295         *len += strlen(domainname) + strlen(header) + 10;
1296         buf = kzalloc(*len, GFP_NOFS);
1297         if (buf)
1298                 snprintf(buf, (*len) - 1, "%s\n%s\n", header, domainname);
1299         kfree(header);
1300         return buf;
1301 }
1302
1303 /* Wait queue for tomoyo_query_list. */
1304 static DECLARE_WAIT_QUEUE_HEAD(tomoyo_query_wait);
1305
1306 /* Lock for manipulating tomoyo_query_list. */
1307 static DEFINE_SPINLOCK(tomoyo_query_list_lock);
1308
1309 /* Structure for query. */
1310 struct tomoyo_query_entry {
1311         struct list_head list;
1312         char *query;
1313         int query_len;
1314         unsigned int serial;
1315         int timer;
1316         int answer;
1317 };
1318
1319 /* The list for "struct tomoyo_query_entry". */
1320 static LIST_HEAD(tomoyo_query_list);
1321
1322 /*
1323  * Number of "struct file" referring /sys/kernel/security/tomoyo/query
1324  * interface.
1325  */
1326 static atomic_t tomoyo_query_observers = ATOMIC_INIT(0);
1327
1328 /**
1329  * tomoyo_supervisor - Ask for the supervisor's decision.
1330  *
1331  * @r:       Pointer to "struct tomoyo_request_info".
1332  * @fmt:     The printf()'s format string, followed by parameters.
1333  *
1334  * Returns 0 if the supervisor decided to permit the access request which
1335  * violated the policy in enforcing mode, TOMOYO_RETRY_REQUEST if the
1336  * supervisor decided to retry the access request which violated the policy in
1337  * enforcing mode, 0 if it is not in enforcing mode, -EPERM otherwise.
1338  */
1339 int tomoyo_supervisor(struct tomoyo_request_info *r, const char *fmt, ...)
1340 {
1341         va_list args;
1342         int error = -EPERM;
1343         int pos;
1344         int len;
1345         static unsigned int tomoyo_serial;
1346         struct tomoyo_query_entry *tomoyo_query_entry = NULL;
1347         bool quota_exceeded = false;
1348         char *header;
1349         switch (r->mode) {
1350                 char *buffer;
1351         case TOMOYO_CONFIG_LEARNING:
1352                 if (!tomoyo_domain_quota_is_ok(r))
1353                         return 0;
1354                 va_start(args, fmt);
1355                 len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 4;
1356                 va_end(args);
1357                 buffer = kmalloc(len, GFP_NOFS);
1358                 if (!buffer)
1359                         return 0;
1360                 va_start(args, fmt);
1361                 vsnprintf(buffer, len - 1, fmt, args);
1362                 va_end(args);
1363                 tomoyo_normalize_line(buffer);
1364                 tomoyo_write_domain_policy2(buffer, r->domain, false);
1365                 kfree(buffer);
1366                 /* fall through */
1367         case TOMOYO_CONFIG_PERMISSIVE:
1368                 return 0;
1369         }
1370         if (!r->domain)
1371                 r->domain = tomoyo_domain();
1372         if (!atomic_read(&tomoyo_query_observers))
1373                 return -EPERM;
1374         va_start(args, fmt);
1375         len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 32;
1376         va_end(args);
1377         header = tomoyo_init_audit_log(&len, r);
1378         if (!header)
1379                 goto out;
1380         tomoyo_query_entry = kzalloc(sizeof(*tomoyo_query_entry), GFP_NOFS);
1381         if (!tomoyo_query_entry)
1382                 goto out;
1383         tomoyo_query_entry->query = kzalloc(len, GFP_NOFS);
1384         if (!tomoyo_query_entry->query)
1385                 goto out;
1386         len = ksize(tomoyo_query_entry->query);
1387         INIT_LIST_HEAD(&tomoyo_query_entry->list);
1388         spin_lock(&tomoyo_query_list_lock);
1389         if (tomoyo_quota_for_query && tomoyo_query_memory_size + len +
1390             sizeof(*tomoyo_query_entry) >= tomoyo_quota_for_query) {
1391                 quota_exceeded = true;
1392         } else {
1393                 tomoyo_query_memory_size += len + sizeof(*tomoyo_query_entry);
1394                 tomoyo_query_entry->serial = tomoyo_serial++;
1395         }
1396         spin_unlock(&tomoyo_query_list_lock);
1397         if (quota_exceeded)
1398                 goto out;
1399         pos = snprintf(tomoyo_query_entry->query, len - 1, "Q%u-%hu\n%s",
1400                        tomoyo_query_entry->serial, r->retry, header);
1401         kfree(header);
1402         header = NULL;
1403         va_start(args, fmt);
1404         vsnprintf(tomoyo_query_entry->query + pos, len - 1 - pos, fmt, args);
1405         tomoyo_query_entry->query_len = strlen(tomoyo_query_entry->query) + 1;
1406         va_end(args);
1407         spin_lock(&tomoyo_query_list_lock);
1408         list_add_tail(&tomoyo_query_entry->list, &tomoyo_query_list);
1409         spin_unlock(&tomoyo_query_list_lock);
1410         /* Give 10 seconds for supervisor's opinion. */
1411         for (tomoyo_query_entry->timer = 0;
1412              atomic_read(&tomoyo_query_observers) && tomoyo_query_entry->timer < 100;
1413              tomoyo_query_entry->timer++) {
1414                 wake_up(&tomoyo_query_wait);
1415                 set_current_state(TASK_INTERRUPTIBLE);
1416                 schedule_timeout(HZ / 10);
1417                 if (tomoyo_query_entry->answer)
1418                         break;
1419         }
1420         spin_lock(&tomoyo_query_list_lock);
1421         list_del(&tomoyo_query_entry->list);
1422         tomoyo_query_memory_size -= len + sizeof(*tomoyo_query_entry);
1423         spin_unlock(&tomoyo_query_list_lock);
1424         switch (tomoyo_query_entry->answer) {
1425         case 3: /* Asked to retry by administrator. */
1426                 error = TOMOYO_RETRY_REQUEST;
1427                 r->retry++;
1428                 break;
1429         case 1:
1430                 /* Granted by administrator. */
1431                 error = 0;
1432                 break;
1433         case 0:
1434                 /* Timed out. */
1435                 break;
1436         default:
1437                 /* Rejected by administrator. */
1438                 break;
1439         }
1440  out:
1441         if (tomoyo_query_entry)
1442                 kfree(tomoyo_query_entry->query);
1443         kfree(tomoyo_query_entry);
1444         kfree(header);
1445         return error;
1446 }
1447
1448 /**
1449  * tomoyo_poll_query - poll() for /sys/kernel/security/tomoyo/query.
1450  *
1451  * @file: Pointer to "struct file".
1452  * @wait: Pointer to "poll_table".
1453  *
1454  * Returns POLLIN | POLLRDNORM when ready to read, 0 otherwise.
1455  *
1456  * Waits for access requests which violated policy in enforcing mode.
1457  */
1458 static int tomoyo_poll_query(struct file *file, poll_table *wait)
1459 {
1460         struct list_head *tmp;
1461         bool found = false;
1462         u8 i;
1463         for (i = 0; i < 2; i++) {
1464                 spin_lock(&tomoyo_query_list_lock);
1465                 list_for_each(tmp, &tomoyo_query_list) {
1466                         struct tomoyo_query_entry *ptr
1467                                 = list_entry(tmp, struct tomoyo_query_entry,
1468                                              list);
1469                         if (ptr->answer)
1470                                 continue;
1471                         found = true;
1472                         break;
1473                 }
1474                 spin_unlock(&tomoyo_query_list_lock);
1475                 if (found)
1476                         return POLLIN | POLLRDNORM;
1477                 if (i)
1478                         break;
1479                 poll_wait(file, &tomoyo_query_wait, wait);
1480         }
1481         return 0;
1482 }
1483
1484 /**
1485  * tomoyo_read_query - Read access requests which violated policy in enforcing mode.
1486  *
1487  * @head: Pointer to "struct tomoyo_io_buffer".
1488  *
1489  * Returns 0.
1490  */
1491 static int tomoyo_read_query(struct tomoyo_io_buffer *head)
1492 {
1493         struct list_head *tmp;
1494         int pos = 0;
1495         int len = 0;
1496         char *buf;
1497         if (head->read_avail)
1498                 return 0;
1499         if (head->read_buf) {
1500                 kfree(head->read_buf);
1501                 head->read_buf = NULL;
1502                 head->readbuf_size = 0;
1503         }
1504         spin_lock(&tomoyo_query_list_lock);
1505         list_for_each(tmp, &tomoyo_query_list) {
1506                 struct tomoyo_query_entry *ptr
1507                         = list_entry(tmp, struct tomoyo_query_entry, list);
1508                 if (ptr->answer)
1509                         continue;
1510                 if (pos++ != head->read_step)
1511                         continue;
1512                 len = ptr->query_len;
1513                 break;
1514         }
1515         spin_unlock(&tomoyo_query_list_lock);
1516         if (!len) {
1517                 head->read_step = 0;
1518                 return 0;
1519         }
1520         buf = kzalloc(len, GFP_NOFS);
1521         if (!buf)
1522                 return 0;
1523         pos = 0;
1524         spin_lock(&tomoyo_query_list_lock);
1525         list_for_each(tmp, &tomoyo_query_list) {
1526                 struct tomoyo_query_entry *ptr
1527                         = list_entry(tmp, struct tomoyo_query_entry, list);
1528                 if (ptr->answer)
1529                         continue;
1530                 if (pos++ != head->read_step)
1531                         continue;
1532                 /*
1533                  * Some query can be skipped because tomoyo_query_list
1534                  * can change, but I don't care.
1535                  */
1536                 if (len == ptr->query_len)
1537                         memmove(buf, ptr->query, len);
1538                 break;
1539         }
1540         spin_unlock(&tomoyo_query_list_lock);
1541         if (buf[0]) {
1542                 head->read_avail = len;
1543                 head->readbuf_size = head->read_avail;
1544                 head->read_buf = buf;
1545                 head->read_step++;
1546         } else {
1547                 kfree(buf);
1548         }
1549         return 0;
1550 }
1551
1552 /**
1553  * tomoyo_write_answer - Write the supervisor's decision.
1554  *
1555  * @head: Pointer to "struct tomoyo_io_buffer".
1556  *
1557  * Returns 0 on success, -EINVAL otherwise.
1558  */
1559 static int tomoyo_write_answer(struct tomoyo_io_buffer *head)
1560 {
1561         char *data = head->write_buf;
1562         struct list_head *tmp;
1563         unsigned int serial;
1564         unsigned int answer;
1565         spin_lock(&tomoyo_query_list_lock);
1566         list_for_each(tmp, &tomoyo_query_list) {
1567                 struct tomoyo_query_entry *ptr
1568                         = list_entry(tmp, struct tomoyo_query_entry, list);
1569                 ptr->timer = 0;
1570         }
1571         spin_unlock(&tomoyo_query_list_lock);
1572         if (sscanf(data, "A%u=%u", &serial, &answer) != 2)
1573                 return -EINVAL;
1574         spin_lock(&tomoyo_query_list_lock);
1575         list_for_each(tmp, &tomoyo_query_list) {
1576                 struct tomoyo_query_entry *ptr
1577                         = list_entry(tmp, struct tomoyo_query_entry, list);
1578                 if (ptr->serial != serial)
1579                         continue;
1580                 if (!ptr->answer)
1581                         ptr->answer = answer;
1582                 break;
1583         }
1584         spin_unlock(&tomoyo_query_list_lock);
1585         return 0;
1586 }
1587
1588 /**
1589  * tomoyo_read_version: Get version.
1590  *
1591  * @head: Pointer to "struct tomoyo_io_buffer".
1592  *
1593  * Returns version information.
1594  */
1595 static int tomoyo_read_version(struct tomoyo_io_buffer *head)
1596 {
1597         if (!head->read_eof) {
1598                 tomoyo_io_printf(head, "2.2.0");
1599                 head->read_eof = true;
1600         }
1601         return 0;
1602 }
1603
1604 /**
1605  * tomoyo_read_self_domain - Get the current process's domainname.
1606  *
1607  * @head: Pointer to "struct tomoyo_io_buffer".
1608  *
1609  * Returns the current process's domainname.
1610  */
1611 static int tomoyo_read_self_domain(struct tomoyo_io_buffer *head)
1612 {
1613         if (!head->read_eof) {
1614                 /*
1615                  * tomoyo_domain()->domainname != NULL
1616                  * because every process belongs to a domain and
1617                  * the domain's name cannot be NULL.
1618                  */
1619                 tomoyo_io_printf(head, "%s", tomoyo_domain()->domainname->name);
1620                 head->read_eof = true;
1621         }
1622         return 0;
1623 }
1624
1625 /**
1626  * tomoyo_open_control - open() for /sys/kernel/security/tomoyo/ interface.
1627  *
1628  * @type: Type of interface.
1629  * @file: Pointer to "struct file".
1630  *
1631  * Associates policy handler and returns 0 on success, -ENOMEM otherwise.
1632  *
1633  * Caller acquires tomoyo_read_lock().
1634  */
1635 int tomoyo_open_control(const u8 type, struct file *file)
1636 {
1637         struct tomoyo_io_buffer *head = kzalloc(sizeof(*head), GFP_NOFS);
1638
1639         if (!head)
1640                 return -ENOMEM;
1641         mutex_init(&head->io_sem);
1642         head->type = type;
1643         switch (type) {
1644         case TOMOYO_DOMAINPOLICY:
1645                 /* /sys/kernel/security/tomoyo/domain_policy */
1646                 head->write = tomoyo_write_domain_policy;
1647                 head->read = tomoyo_read_domain_policy;
1648                 break;
1649         case TOMOYO_EXCEPTIONPOLICY:
1650                 /* /sys/kernel/security/tomoyo/exception_policy */
1651                 head->write = tomoyo_write_exception_policy;
1652                 head->read = tomoyo_read_exception_policy;
1653                 break;
1654         case TOMOYO_SELFDOMAIN:
1655                 /* /sys/kernel/security/tomoyo/self_domain */
1656                 head->read = tomoyo_read_self_domain;
1657                 break;
1658         case TOMOYO_DOMAIN_STATUS:
1659                 /* /sys/kernel/security/tomoyo/.domain_status */
1660                 head->write = tomoyo_write_domain_profile;
1661                 head->read = tomoyo_read_domain_profile;
1662                 break;
1663         case TOMOYO_PROCESS_STATUS:
1664                 /* /sys/kernel/security/tomoyo/.process_status */
1665                 head->write = tomoyo_write_pid;
1666                 head->read = tomoyo_read_pid;
1667                 break;
1668         case TOMOYO_VERSION:
1669                 /* /sys/kernel/security/tomoyo/version */
1670                 head->read = tomoyo_read_version;
1671                 head->readbuf_size = 128;
1672                 break;
1673         case TOMOYO_MEMINFO:
1674                 /* /sys/kernel/security/tomoyo/meminfo */
1675                 head->write = tomoyo_write_memory_quota;
1676                 head->read = tomoyo_read_memory_counter;
1677                 head->readbuf_size = 512;
1678                 break;
1679         case TOMOYO_PROFILE:
1680                 /* /sys/kernel/security/tomoyo/profile */
1681                 head->write = tomoyo_write_profile;
1682                 head->read = tomoyo_read_profile;
1683                 break;
1684         case TOMOYO_QUERY: /* /sys/kernel/security/tomoyo/query */
1685                 head->poll = tomoyo_poll_query;
1686                 head->write = tomoyo_write_answer;
1687                 head->read = tomoyo_read_query;
1688                 break;
1689         case TOMOYO_MANAGER:
1690                 /* /sys/kernel/security/tomoyo/manager */
1691                 head->write = tomoyo_write_manager_policy;
1692                 head->read = tomoyo_read_manager_policy;
1693                 break;
1694         }
1695         if (!(file->f_mode & FMODE_READ)) {
1696                 /*
1697                  * No need to allocate read_buf since it is not opened
1698                  * for reading.
1699                  */
1700                 head->read = NULL;
1701                 head->poll = NULL;
1702         } else if (!head->poll) {
1703                 /* Don't allocate read_buf for poll() access. */
1704                 if (!head->readbuf_size)
1705                         head->readbuf_size = 4096 * 2;
1706                 head->read_buf = kzalloc(head->readbuf_size, GFP_NOFS);
1707                 if (!head->read_buf) {
1708                         kfree(head);
1709                         return -ENOMEM;
1710                 }
1711         }
1712         if (!(file->f_mode & FMODE_WRITE)) {
1713                 /*
1714                  * No need to allocate write_buf since it is not opened
1715                  * for writing.
1716                  */
1717                 head->write = NULL;
1718         } else if (head->write) {
1719                 head->writebuf_size = 4096 * 2;
1720                 head->write_buf = kzalloc(head->writebuf_size, GFP_NOFS);
1721                 if (!head->write_buf) {
1722                         kfree(head->read_buf);
1723                         kfree(head);
1724                         return -ENOMEM;
1725                 }
1726         }
1727         if (type != TOMOYO_QUERY)
1728                 head->reader_idx = tomoyo_read_lock();
1729         file->private_data = head;
1730         /*
1731          * Call the handler now if the file is
1732          * /sys/kernel/security/tomoyo/self_domain
1733          * so that the user can use
1734          * cat < /sys/kernel/security/tomoyo/self_domain"
1735          * to know the current process's domainname.
1736          */
1737         if (type == TOMOYO_SELFDOMAIN)
1738                 tomoyo_read_control(file, NULL, 0);
1739         /*
1740          * If the file is /sys/kernel/security/tomoyo/query , increment the
1741          * observer counter.
1742          * The obserber counter is used by tomoyo_supervisor() to see if
1743          * there is some process monitoring /sys/kernel/security/tomoyo/query.
1744          */
1745         else if (type == TOMOYO_QUERY)
1746                 atomic_inc(&tomoyo_query_observers);
1747         return 0;
1748 }
1749
1750 /**
1751  * tomoyo_poll_control - poll() for /sys/kernel/security/tomoyo/ interface.
1752  *
1753  * @file: Pointer to "struct file".
1754  * @wait: Pointer to "poll_table".
1755  *
1756  * Waits for read readiness.
1757  * /sys/kernel/security/tomoyo/query is handled by /usr/sbin/tomoyo-queryd .
1758  */
1759 int tomoyo_poll_control(struct file *file, poll_table *wait)
1760 {
1761         struct tomoyo_io_buffer *head = file->private_data;
1762         if (!head->poll)
1763                 return -ENOSYS;
1764         return head->poll(file, wait);
1765 }
1766
1767 /**
1768  * tomoyo_read_control - read() for /sys/kernel/security/tomoyo/ interface.
1769  *
1770  * @file:       Pointer to "struct file".
1771  * @buffer:     Poiner to buffer to write to.
1772  * @buffer_len: Size of @buffer.
1773  *
1774  * Returns bytes read on success, negative value otherwise.
1775  *
1776  * Caller holds tomoyo_read_lock().
1777  */
1778 int tomoyo_read_control(struct file *file, char __user *buffer,
1779                         const int buffer_len)
1780 {
1781         int len = 0;
1782         struct tomoyo_io_buffer *head = file->private_data;
1783         char *cp;
1784
1785         if (!head->read)
1786                 return -ENOSYS;
1787         if (mutex_lock_interruptible(&head->io_sem))
1788                 return -EINTR;
1789         /* Call the policy handler. */
1790         len = head->read(head);
1791         if (len < 0)
1792                 goto out;
1793         /* Write to buffer. */
1794         len = head->read_avail;
1795         if (len > buffer_len)
1796                 len = buffer_len;
1797         if (!len)
1798                 goto out;
1799         /* head->read_buf changes by some functions. */
1800         cp = head->read_buf;
1801         if (copy_to_user(buffer, cp, len)) {
1802                 len = -EFAULT;
1803                 goto out;
1804         }
1805         head->read_avail -= len;
1806         memmove(cp, cp + len, head->read_avail);
1807  out:
1808         mutex_unlock(&head->io_sem);
1809         return len;
1810 }
1811
1812 /**
1813  * tomoyo_write_control - write() for /sys/kernel/security/tomoyo/ interface.
1814  *
1815  * @file:       Pointer to "struct file".
1816  * @buffer:     Pointer to buffer to read from.
1817  * @buffer_len: Size of @buffer.
1818  *
1819  * Returns @buffer_len on success, negative value otherwise.
1820  *
1821  * Caller holds tomoyo_read_lock().
1822  */
1823 int tomoyo_write_control(struct file *file, const char __user *buffer,
1824                          const int buffer_len)
1825 {
1826         struct tomoyo_io_buffer *head = file->private_data;
1827         int error = buffer_len;
1828         int avail_len = buffer_len;
1829         char *cp0 = head->write_buf;
1830
1831         if (!head->write)
1832                 return -ENOSYS;
1833         if (!access_ok(VERIFY_READ, buffer, buffer_len))
1834                 return -EFAULT;
1835         /* Don't allow updating policies by non manager programs. */
1836         if (head->write != tomoyo_write_pid &&
1837             head->write != tomoyo_write_domain_policy &&
1838             !tomoyo_is_policy_manager())
1839                 return -EPERM;
1840         if (mutex_lock_interruptible(&head->io_sem))
1841                 return -EINTR;
1842         /* Read a line and dispatch it to the policy handler. */
1843         while (avail_len > 0) {
1844                 char c;
1845                 if (head->write_avail >= head->writebuf_size - 1) {
1846                         error = -ENOMEM;
1847                         break;
1848                 } else if (get_user(c, buffer)) {
1849                         error = -EFAULT;
1850                         break;
1851                 }
1852                 buffer++;
1853                 avail_len--;
1854                 cp0[head->write_avail++] = c;
1855                 if (c != '\n')
1856                         continue;
1857                 cp0[head->write_avail - 1] = '\0';
1858                 head->write_avail = 0;
1859                 tomoyo_normalize_line(cp0);
1860                 head->write(head);
1861         }
1862         mutex_unlock(&head->io_sem);
1863         return error;
1864 }
1865
1866 /**
1867  * tomoyo_close_control - close() for /sys/kernel/security/tomoyo/ interface.
1868  *
1869  * @file: Pointer to "struct file".
1870  *
1871  * Releases memory and returns 0.
1872  *
1873  * Caller looses tomoyo_read_lock().
1874  */
1875 int tomoyo_close_control(struct file *file)
1876 {
1877         struct tomoyo_io_buffer *head = file->private_data;
1878         const bool is_write = !!head->write_buf;
1879
1880         /*
1881          * If the file is /sys/kernel/security/tomoyo/query , decrement the
1882          * observer counter.
1883          */
1884         if (head->type == TOMOYO_QUERY)
1885                 atomic_dec(&tomoyo_query_observers);
1886         else
1887                 tomoyo_read_unlock(head->reader_idx);
1888         /* Release memory used for policy I/O. */
1889         kfree(head->read_buf);
1890         head->read_buf = NULL;
1891         kfree(head->write_buf);
1892         head->write_buf = NULL;
1893         kfree(head);
1894         head = NULL;
1895         file->private_data = NULL;
1896         if (is_write)
1897                 tomoyo_run_gc();
1898         return 0;
1899 }
1900
1901 /**
1902  * tomoyo_check_profile - Check all profiles currently assigned to domains are defined.
1903  */
1904 void tomoyo_check_profile(void)
1905 {
1906         struct tomoyo_domain_info *domain;
1907         const int idx = tomoyo_read_lock();
1908         tomoyo_policy_loaded = true;
1909         /* Check all profiles currently assigned to domains are defined. */
1910         list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
1911                 const u8 profile = domain->profile;
1912                 if (tomoyo_profile_ptr[profile])
1913                         continue;
1914                 panic("Profile %u (used by '%s') not defined.\n",
1915                       profile, domain->domainname->name);
1916         }
1917         tomoyo_read_unlock(idx);
1918         printk(KERN_INFO "TOMOYO: 2.2.0   2009/04/01\n");
1919         printk(KERN_INFO "Mandatory Access Control activated.\n");
1920 }