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