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