TOMOYO: Add numeric values grouping support.
[linux-2.6.git] / security / tomoyo / common.c
1 /*
2  * security/tomoyo/common.c
3  *
4  * Common functions for TOMOYO.
5  *
6  * Copyright (C) 2005-2009  NTT DATA CORPORATION
7  *
8  * Version: 2.2.0   2009/04/01
9  *
10  */
11
12 #include <linux/uaccess.h>
13 #include <linux/slab.h>
14 #include <linux/security.h>
15 #include <linux/hardirq.h>
16 #include "common.h"
17
18 /* Lock for protecting policy. */
19 DEFINE_MUTEX(tomoyo_policy_lock);
20
21 /* Has loading policy done? */
22 bool tomoyo_policy_loaded;
23
24 /* String table for functionality that takes 4 modes. */
25 static const char *tomoyo_mode_4[4] = {
26         "disabled", "learning", "permissive", "enforcing"
27 };
28 /* String table for functionality that takes 2 modes. */
29 static const char *tomoyo_mode_2[4] = {
30         "disabled", "enabled", "enabled", "enabled"
31 };
32
33 /*
34  * tomoyo_control_array is a static data which contains
35  *
36  *  (1) functionality name used by /sys/kernel/security/tomoyo/profile .
37  *  (2) initial values for "struct tomoyo_profile".
38  *  (3) max values for "struct tomoyo_profile".
39  */
40 static struct {
41         const char *keyword;
42         unsigned int current_value;
43         const unsigned int max_value;
44 } tomoyo_control_array[TOMOYO_MAX_CONTROL_INDEX] = {
45         [TOMOYO_MAC_FOR_FILE]     = { "MAC_FOR_FILE",        0,       3 },
46         [TOMOYO_MAX_ACCEPT_ENTRY] = { "MAX_ACCEPT_ENTRY", 2048, INT_MAX },
47         [TOMOYO_VERBOSE]          = { "TOMOYO_VERBOSE",      1,       1 },
48 };
49
50 /*
51  * tomoyo_profile is a structure which is used for holding the mode of access
52  * controls. TOMOYO has 4 modes: disabled, learning, permissive, enforcing.
53  * An administrator can define up to 256 profiles.
54  * The ->profile of "struct tomoyo_domain_info" is used for remembering
55  * the profile's number (0 - 255) assigned to that domain.
56  */
57 static struct tomoyo_profile {
58         unsigned int value[TOMOYO_MAX_CONTROL_INDEX];
59         const struct tomoyo_path_info *comment;
60 } *tomoyo_profile_ptr[TOMOYO_MAX_PROFILES];
61
62 /* Permit policy management by non-root user? */
63 static bool tomoyo_manage_by_non_root;
64
65 /* Utility functions. */
66
67 /* Open operation for /sys/kernel/security/tomoyo/ interface. */
68 static int tomoyo_open_control(const u8 type, struct file *file);
69 /* Close /sys/kernel/security/tomoyo/ interface. */
70 static int tomoyo_close_control(struct file *file);
71 /* Read operation for /sys/kernel/security/tomoyo/ interface. */
72 static int tomoyo_read_control(struct file *file, char __user *buffer,
73                                const int buffer_len);
74 /* Write operation for /sys/kernel/security/tomoyo/ interface. */
75 static int tomoyo_write_control(struct file *file, const char __user *buffer,
76                                 const int buffer_len);
77
78 /**
79  * tomoyo_parse_name_union - Parse a tomoyo_name_union.
80  *
81  * @filename: Name or name group.
82  * @ptr:      Pointer to "struct tomoyo_name_union".
83  *
84  * Returns true on success, false otherwise.
85  */
86 bool tomoyo_parse_name_union(const char *filename,
87                              struct tomoyo_name_union *ptr)
88 {
89         if (!tomoyo_is_correct_path(filename, 0, 0, 0))
90                 return false;
91         if (filename[0] == '@') {
92                 ptr->group = tomoyo_get_path_group(filename + 1);
93                 ptr->is_group = true;
94                 return ptr->group != NULL;
95         }
96         ptr->filename = tomoyo_get_name(filename);
97         ptr->is_group = false;
98         return ptr->filename != NULL;
99 }
100
101 /**
102  * tomoyo_print_name_union - Print a tomoyo_name_union.
103  *
104  * @head: Pointer to "struct tomoyo_io_buffer".
105  * @ptr:  Pointer to "struct tomoyo_name_union".
106  *
107  * Returns true on success, false otherwise.
108  */
109 static bool tomoyo_print_name_union(struct tomoyo_io_buffer *head,
110                                  const struct tomoyo_name_union *ptr)
111 {
112         int pos = head->read_avail;
113         if (pos && head->read_buf[pos - 1] == ' ')
114                 head->read_avail--;
115         if (ptr->is_group)
116                 return tomoyo_io_printf(head, " @%s",
117                                         ptr->group->group_name->name);
118         return tomoyo_io_printf(head, " %s", ptr->filename->name);
119 }
120
121 /**
122  * tomoyo_parse_ulong - Parse an "unsigned long" value.
123  *
124  * @result: Pointer to "unsigned long".
125  * @str:    Pointer to string to parse.
126  *
127  * Returns value type on success, 0 otherwise.
128  *
129  * The @src is updated to point the first character after the value
130  * on success.
131  */
132 u8 tomoyo_parse_ulong(unsigned long *result, char **str)
133 {
134         const char *cp = *str;
135         char *ep;
136         int base = 10;
137         if (*cp == '0') {
138                 char c = *(cp + 1);
139                 if (c == 'x' || c == 'X') {
140                         base = 16;
141                         cp += 2;
142                 } else if (c >= '0' && c <= '7') {
143                         base = 8;
144                         cp++;
145                 }
146         }
147         *result = simple_strtoul(cp, &ep, base);
148         if (cp == ep)
149                 return 0;
150         *str = ep;
151         switch (base) {
152         case 16:
153                 return TOMOYO_VALUE_TYPE_HEXADECIMAL;
154         case 8:
155                 return TOMOYO_VALUE_TYPE_OCTAL;
156         default:
157                 return TOMOYO_VALUE_TYPE_DECIMAL;
158         }
159 }
160
161 /**
162  * tomoyo_print_ulong - Print an "unsigned long" value.
163  *
164  * @buffer:     Pointer to buffer.
165  * @buffer_len: Size of @buffer.
166  * @value:      An "unsigned long" value.
167  * @type:       Type of @value.
168  *
169  * Returns nothing.
170  */
171 void tomoyo_print_ulong(char *buffer, const int buffer_len,
172                         const unsigned long value, const u8 type)
173 {
174         if (type == TOMOYO_VALUE_TYPE_DECIMAL)
175                 snprintf(buffer, buffer_len, "%lu", value);
176         else if (type == TOMOYO_VALUE_TYPE_OCTAL)
177                 snprintf(buffer, buffer_len, "0%lo", value);
178         else if (type == TOMOYO_VALUE_TYPE_HEXADECIMAL)
179                 snprintf(buffer, buffer_len, "0x%lX", value);
180         else
181                 snprintf(buffer, buffer_len, "type(%u)", type);
182 }
183
184 /**
185  * tomoyo_print_number_union - Print a tomoyo_number_union.
186  *
187  * @head:       Pointer to "struct tomoyo_io_buffer".
188  * @ptr:        Pointer to "struct tomoyo_number_union".
189  *
190  * Returns true on success, false otherwise.
191  */
192 bool tomoyo_print_number_union(struct tomoyo_io_buffer *head,
193                                const struct tomoyo_number_union *ptr)
194 {
195         unsigned long min;
196         unsigned long max;
197         u8 min_type;
198         u8 max_type;
199         if (!tomoyo_io_printf(head, " "))
200                 return false;
201         if (ptr->is_group)
202                 return tomoyo_io_printf(head, "@%s",
203                                         ptr->group->group_name->name);
204         min_type = ptr->min_type;
205         max_type = ptr->max_type;
206         min = ptr->values[0];
207         max = ptr->values[1];
208         switch (min_type) {
209         case TOMOYO_VALUE_TYPE_HEXADECIMAL:
210                 if (!tomoyo_io_printf(head, "0x%lX", min))
211                         return false;
212                 break;
213         case TOMOYO_VALUE_TYPE_OCTAL:
214                 if (!tomoyo_io_printf(head, "0%lo", min))
215                         return false;
216                 break;
217         default:
218                 if (!tomoyo_io_printf(head, "%lu", min))
219                         return false;
220                 break;
221         }
222         if (min == max && min_type == max_type)
223                 return true;
224         switch (max_type) {
225         case TOMOYO_VALUE_TYPE_HEXADECIMAL:
226                 return tomoyo_io_printf(head, "-0x%lX", max);
227         case TOMOYO_VALUE_TYPE_OCTAL:
228                 return tomoyo_io_printf(head, "-0%lo", max);
229         default:
230                 return tomoyo_io_printf(head, "-%lu", max);
231         }
232 }
233
234 /**
235  * tomoyo_parse_number_union - Parse a tomoyo_number_union.
236  *
237  * @data: Number or number range or number group.
238  * @ptr:  Pointer to "struct tomoyo_number_union".
239  *
240  * Returns true on success, false otherwise.
241  */
242 bool tomoyo_parse_number_union(char *data, struct tomoyo_number_union *num)
243 {
244         u8 type;
245         unsigned long v;
246         memset(num, 0, sizeof(*num));
247         if (data[0] == '@') {
248                 if (!tomoyo_is_correct_path(data, 0, 0, 0))
249                         return false;
250                 num->group = tomoyo_get_number_group(data + 1);
251                 num->is_group = true;
252                 return num->group != NULL;
253         }
254         type = tomoyo_parse_ulong(&v, &data);
255         if (!type)
256                 return false;
257         num->values[0] = v;
258         num->min_type = type;
259         if (!*data) {
260                 num->values[1] = v;
261                 num->max_type = type;
262                 return true;
263         }
264         if (*data++ != '-')
265                 return false;
266         type = tomoyo_parse_ulong(&v, &data);
267         if (!type || *data)
268                 return false;
269         num->values[1] = v;
270         num->max_type = type;
271         return true;
272 }
273
274 /**
275  * tomoyo_is_byte_range - Check whether the string isa \ooo style octal value.
276  *
277  * @str: Pointer to the string.
278  *
279  * Returns true if @str is a \ooo style octal value, false otherwise.
280  *
281  * TOMOYO uses \ooo style representation for 0x01 - 0x20 and 0x7F - 0xFF.
282  * This function verifies that \ooo is in valid range.
283  */
284 static inline bool tomoyo_is_byte_range(const char *str)
285 {
286         return *str >= '0' && *str++ <= '3' &&
287                 *str >= '0' && *str++ <= '7' &&
288                 *str >= '0' && *str <= '7';
289 }
290
291 /**
292  * tomoyo_is_alphabet_char - Check whether the character is an alphabet.
293  *
294  * @c: The character to check.
295  *
296  * Returns true if @c is an alphabet character, false otherwise.
297  */
298 static inline bool tomoyo_is_alphabet_char(const char c)
299 {
300         return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
301 }
302
303 /**
304  * tomoyo_make_byte - Make byte value from three octal characters.
305  *
306  * @c1: The first character.
307  * @c2: The second character.
308  * @c3: The third character.
309  *
310  * Returns byte value.
311  */
312 static inline u8 tomoyo_make_byte(const u8 c1, const u8 c2, const u8 c3)
313 {
314         return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
315 }
316
317 /**
318  * tomoyo_str_starts - Check whether the given string starts with the given keyword.
319  *
320  * @src:  Pointer to pointer to the string.
321  * @find: Pointer to the keyword.
322  *
323  * Returns true if @src starts with @find, false otherwise.
324  *
325  * The @src is updated to point the first character after the @find
326  * if @src starts with @find.
327  */
328 static bool tomoyo_str_starts(char **src, const char *find)
329 {
330         const int len = strlen(find);
331         char *tmp = *src;
332
333         if (strncmp(tmp, find, len))
334                 return false;
335         tmp += len;
336         *src = tmp;
337         return true;
338 }
339
340 /**
341  * tomoyo_normalize_line - Format string.
342  *
343  * @buffer: The line to normalize.
344  *
345  * Leading and trailing whitespaces are removed.
346  * Multiple whitespaces are packed into single space.
347  *
348  * Returns nothing.
349  */
350 static void tomoyo_normalize_line(unsigned char *buffer)
351 {
352         unsigned char *sp = buffer;
353         unsigned char *dp = buffer;
354         bool first = true;
355
356         while (tomoyo_is_invalid(*sp))
357                 sp++;
358         while (*sp) {
359                 if (!first)
360                         *dp++ = ' ';
361                 first = false;
362                 while (tomoyo_is_valid(*sp))
363                         *dp++ = *sp++;
364                 while (tomoyo_is_invalid(*sp))
365                         sp++;
366         }
367         *dp = '\0';
368 }
369
370 /**
371  * tomoyo_tokenize - Tokenize string.
372  *
373  * @buffer: The line to tokenize.
374  * @w:      Pointer to "char *".
375  * @size:   Sizeof @w .
376  *
377  * Returns true on success, false otherwise.
378  */
379 bool tomoyo_tokenize(char *buffer, char *w[], size_t size)
380 {
381         int count = size / sizeof(char *);
382         int i;
383         for (i = 0; i < count; i++)
384                 w[i] = "";
385         for (i = 0; i < count; i++) {
386                 char *cp = strchr(buffer, ' ');
387                 if (cp)
388                         *cp = '\0';
389                 w[i] = buffer;
390                 if (!cp)
391                         break;
392                 buffer = cp + 1;
393         }
394         return i < count || !*buffer;
395 }
396
397 /**
398  * tomoyo_is_correct_path - Validate a pathname.
399  * @filename:     The pathname to check.
400  * @start_type:   Should the pathname start with '/'?
401  *                1 = must / -1 = must not / 0 = don't care
402  * @pattern_type: Can the pathname contain a wildcard?
403  *                1 = must / -1 = must not / 0 = don't care
404  * @end_type:     Should the pathname end with '/'?
405  *                1 = must / -1 = must not / 0 = don't care
406  *
407  * Check whether the given filename follows the naming rules.
408  * Returns true if @filename follows the naming rules, false otherwise.
409  */
410 bool tomoyo_is_correct_path(const char *filename, const s8 start_type,
411                             const s8 pattern_type, const s8 end_type)
412 {
413         const char *const start = filename;
414         bool in_repetition = false;
415         bool contains_pattern = false;
416         unsigned char c;
417         unsigned char d;
418         unsigned char e;
419
420         if (!filename)
421                 goto out;
422         c = *filename;
423         if (start_type == 1) { /* Must start with '/' */
424                 if (c != '/')
425                         goto out;
426         } else if (start_type == -1) { /* Must not start with '/' */
427                 if (c == '/')
428                         goto out;
429         }
430         if (c)
431                 c = *(filename + strlen(filename) - 1);
432         if (end_type == 1) { /* Must end with '/' */
433                 if (c != '/')
434                         goto out;
435         } else if (end_type == -1) { /* Must not end with '/' */
436                 if (c == '/')
437                         goto out;
438         }
439         while (1) {
440                 c = *filename++;
441                 if (!c)
442                         break;
443                 if (c == '\\') {
444                         c = *filename++;
445                         switch (c) {
446                         case '\\':  /* "\\" */
447                                 continue;
448                         case '$':   /* "\$" */
449                         case '+':   /* "\+" */
450                         case '?':   /* "\?" */
451                         case '*':   /* "\*" */
452                         case '@':   /* "\@" */
453                         case 'x':   /* "\x" */
454                         case 'X':   /* "\X" */
455                         case 'a':   /* "\a" */
456                         case 'A':   /* "\A" */
457                         case '-':   /* "\-" */
458                                 if (pattern_type == -1)
459                                         break; /* Must not contain pattern */
460                                 contains_pattern = true;
461                                 continue;
462                         case '{':   /* "/\{" */
463                                 if (filename - 3 < start ||
464                                     *(filename - 3) != '/')
465                                         break;
466                                 if (pattern_type == -1)
467                                         break; /* Must not contain pattern */
468                                 contains_pattern = true;
469                                 in_repetition = true;
470                                 continue;
471                         case '}':   /* "\}/" */
472                                 if (*filename != '/')
473                                         break;
474                                 if (!in_repetition)
475                                         break;
476                                 in_repetition = false;
477                                 continue;
478                         case '0':   /* "\ooo" */
479                         case '1':
480                         case '2':
481                         case '3':
482                                 d = *filename++;
483                                 if (d < '0' || d > '7')
484                                         break;
485                                 e = *filename++;
486                                 if (e < '0' || e > '7')
487                                         break;
488                                 c = tomoyo_make_byte(c, d, e);
489                                 if (tomoyo_is_invalid(c))
490                                         continue; /* pattern is not \000 */
491                         }
492                         goto out;
493                 } else if (in_repetition && c == '/') {
494                         goto out;
495                 } else if (tomoyo_is_invalid(c)) {
496                         goto out;
497                 }
498         }
499         if (pattern_type == 1) { /* Must contain pattern */
500                 if (!contains_pattern)
501                         goto out;
502         }
503         if (in_repetition)
504                 goto out;
505         return true;
506  out:
507         return false;
508 }
509
510 /**
511  * tomoyo_is_correct_domain - Check whether the given domainname follows the naming rules.
512  * @domainname:   The domainname to check.
513  *
514  * Returns true if @domainname follows the naming rules, false otherwise.
515  */
516 bool tomoyo_is_correct_domain(const unsigned char *domainname)
517 {
518         unsigned char c;
519         unsigned char d;
520         unsigned char e;
521
522         if (!domainname || strncmp(domainname, TOMOYO_ROOT_NAME,
523                                    TOMOYO_ROOT_NAME_LEN))
524                 goto out;
525         domainname += TOMOYO_ROOT_NAME_LEN;
526         if (!*domainname)
527                 return true;
528         do {
529                 if (*domainname++ != ' ')
530                         goto out;
531                 if (*domainname++ != '/')
532                         goto out;
533                 while ((c = *domainname) != '\0' && c != ' ') {
534                         domainname++;
535                         if (c == '\\') {
536                                 c = *domainname++;
537                                 switch ((c)) {
538                                 case '\\':  /* "\\" */
539                                         continue;
540                                 case '0':   /* "\ooo" */
541                                 case '1':
542                                 case '2':
543                                 case '3':
544                                         d = *domainname++;
545                                         if (d < '0' || d > '7')
546                                                 break;
547                                         e = *domainname++;
548                                         if (e < '0' || e > '7')
549                                                 break;
550                                         c = tomoyo_make_byte(c, d, e);
551                                         if (tomoyo_is_invalid(c))
552                                                 /* pattern is not \000 */
553                                                 continue;
554                                 }
555                                 goto out;
556                         } else if (tomoyo_is_invalid(c)) {
557                                 goto out;
558                         }
559                 }
560         } while (*domainname);
561         return true;
562  out:
563         return false;
564 }
565
566 /**
567  * tomoyo_is_domain_def - Check whether the given token can be a domainname.
568  *
569  * @buffer: The token to check.
570  *
571  * Returns true if @buffer possibly be a domainname, false otherwise.
572  */
573 bool tomoyo_is_domain_def(const unsigned char *buffer)
574 {
575         return !strncmp(buffer, TOMOYO_ROOT_NAME, TOMOYO_ROOT_NAME_LEN);
576 }
577
578 /**
579  * tomoyo_find_domain - Find a domain by the given name.
580  *
581  * @domainname: The domainname to find.
582  *
583  * Returns pointer to "struct tomoyo_domain_info" if found, NULL otherwise.
584  *
585  * Caller holds tomoyo_read_lock().
586  */
587 struct tomoyo_domain_info *tomoyo_find_domain(const char *domainname)
588 {
589         struct tomoyo_domain_info *domain;
590         struct tomoyo_path_info name;
591
592         name.name = domainname;
593         tomoyo_fill_path_info(&name);
594         list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
595                 if (!domain->is_deleted &&
596                     !tomoyo_pathcmp(&name, domain->domainname))
597                         return domain;
598         }
599         return NULL;
600 }
601
602 /**
603  * tomoyo_const_part_length - Evaluate the initial length without a pattern in a token.
604  *
605  * @filename: The string to evaluate.
606  *
607  * Returns the initial length without a pattern in @filename.
608  */
609 static int tomoyo_const_part_length(const char *filename)
610 {
611         char c;
612         int len = 0;
613
614         if (!filename)
615                 return 0;
616         while ((c = *filename++) != '\0') {
617                 if (c != '\\') {
618                         len++;
619                         continue;
620                 }
621                 c = *filename++;
622                 switch (c) {
623                 case '\\':  /* "\\" */
624                         len += 2;
625                         continue;
626                 case '0':   /* "\ooo" */
627                 case '1':
628                 case '2':
629                 case '3':
630                         c = *filename++;
631                         if (c < '0' || c > '7')
632                                 break;
633                         c = *filename++;
634                         if (c < '0' || c > '7')
635                                 break;
636                         len += 4;
637                         continue;
638                 }
639                 break;
640         }
641         return len;
642 }
643
644 /**
645  * tomoyo_fill_path_info - Fill in "struct tomoyo_path_info" members.
646  *
647  * @ptr: Pointer to "struct tomoyo_path_info" to fill in.
648  *
649  * The caller sets "struct tomoyo_path_info"->name.
650  */
651 void tomoyo_fill_path_info(struct tomoyo_path_info *ptr)
652 {
653         const char *name = ptr->name;
654         const int len = strlen(name);
655
656         ptr->const_len = tomoyo_const_part_length(name);
657         ptr->is_dir = len && (name[len - 1] == '/');
658         ptr->is_patterned = (ptr->const_len < len);
659         ptr->hash = full_name_hash(name, len);
660 }
661
662 /**
663  * tomoyo_file_matches_pattern2 - Pattern matching without '/' character
664  * and "\-" pattern.
665  *
666  * @filename:     The start of string to check.
667  * @filename_end: The end of string to check.
668  * @pattern:      The start of pattern to compare.
669  * @pattern_end:  The end of pattern to compare.
670  *
671  * Returns true if @filename matches @pattern, false otherwise.
672  */
673 static bool tomoyo_file_matches_pattern2(const char *filename,
674                                          const char *filename_end,
675                                          const char *pattern,
676                                          const char *pattern_end)
677 {
678         while (filename < filename_end && pattern < pattern_end) {
679                 char c;
680                 if (*pattern != '\\') {
681                         if (*filename++ != *pattern++)
682                                 return false;
683                         continue;
684                 }
685                 c = *filename;
686                 pattern++;
687                 switch (*pattern) {
688                         int i;
689                         int j;
690                 case '?':
691                         if (c == '/') {
692                                 return false;
693                         } else if (c == '\\') {
694                                 if (filename[1] == '\\')
695                                         filename++;
696                                 else if (tomoyo_is_byte_range(filename + 1))
697                                         filename += 3;
698                                 else
699                                         return false;
700                         }
701                         break;
702                 case '\\':
703                         if (c != '\\')
704                                 return false;
705                         if (*++filename != '\\')
706                                 return false;
707                         break;
708                 case '+':
709                         if (!isdigit(c))
710                                 return false;
711                         break;
712                 case 'x':
713                         if (!isxdigit(c))
714                                 return false;
715                         break;
716                 case 'a':
717                         if (!tomoyo_is_alphabet_char(c))
718                                 return false;
719                         break;
720                 case '0':
721                 case '1':
722                 case '2':
723                 case '3':
724                         if (c == '\\' && tomoyo_is_byte_range(filename + 1)
725                             && strncmp(filename + 1, pattern, 3) == 0) {
726                                 filename += 3;
727                                 pattern += 2;
728                                 break;
729                         }
730                         return false; /* Not matched. */
731                 case '*':
732                 case '@':
733                         for (i = 0; i <= filename_end - filename; i++) {
734                                 if (tomoyo_file_matches_pattern2(
735                                                     filename + i, filename_end,
736                                                     pattern + 1, pattern_end))
737                                         return true;
738                                 c = filename[i];
739                                 if (c == '.' && *pattern == '@')
740                                         break;
741                                 if (c != '\\')
742                                         continue;
743                                 if (filename[i + 1] == '\\')
744                                         i++;
745                                 else if (tomoyo_is_byte_range(filename + i + 1))
746                                         i += 3;
747                                 else
748                                         break; /* Bad pattern. */
749                         }
750                         return false; /* Not matched. */
751                 default:
752                         j = 0;
753                         c = *pattern;
754                         if (c == '$') {
755                                 while (isdigit(filename[j]))
756                                         j++;
757                         } else if (c == 'X') {
758                                 while (isxdigit(filename[j]))
759                                         j++;
760                         } else if (c == 'A') {
761                                 while (tomoyo_is_alphabet_char(filename[j]))
762                                         j++;
763                         }
764                         for (i = 1; i <= j; i++) {
765                                 if (tomoyo_file_matches_pattern2(
766                                                     filename + i, filename_end,
767                                                     pattern + 1, pattern_end))
768                                         return true;
769                         }
770                         return false; /* Not matched or bad pattern. */
771                 }
772                 filename++;
773                 pattern++;
774         }
775         while (*pattern == '\\' &&
776                (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
777                 pattern += 2;
778         return filename == filename_end && pattern == pattern_end;
779 }
780
781 /**
782  * tomoyo_file_matches_pattern - Pattern matching without without '/' character.
783  *
784  * @filename:     The start of string to check.
785  * @filename_end: The end of string to check.
786  * @pattern:      The start of pattern to compare.
787  * @pattern_end:  The end of pattern to compare.
788  *
789  * Returns true if @filename matches @pattern, false otherwise.
790  */
791 static bool tomoyo_file_matches_pattern(const char *filename,
792                                            const char *filename_end,
793                                            const char *pattern,
794                                            const char *pattern_end)
795 {
796         const char *pattern_start = pattern;
797         bool first = true;
798         bool result;
799
800         while (pattern < pattern_end - 1) {
801                 /* Split at "\-" pattern. */
802                 if (*pattern++ != '\\' || *pattern++ != '-')
803                         continue;
804                 result = tomoyo_file_matches_pattern2(filename,
805                                                       filename_end,
806                                                       pattern_start,
807                                                       pattern - 2);
808                 if (first)
809                         result = !result;
810                 if (result)
811                         return false;
812                 first = false;
813                 pattern_start = pattern;
814         }
815         result = tomoyo_file_matches_pattern2(filename, filename_end,
816                                               pattern_start, pattern_end);
817         return first ? result : !result;
818 }
819
820 /**
821  * tomoyo_path_matches_pattern2 - Do pathname pattern matching.
822  *
823  * @f: The start of string to check.
824  * @p: The start of pattern to compare.
825  *
826  * Returns true if @f matches @p, false otherwise.
827  */
828 static bool tomoyo_path_matches_pattern2(const char *f, const char *p)
829 {
830         const char *f_delimiter;
831         const char *p_delimiter;
832
833         while (*f && *p) {
834                 f_delimiter = strchr(f, '/');
835                 if (!f_delimiter)
836                         f_delimiter = f + strlen(f);
837                 p_delimiter = strchr(p, '/');
838                 if (!p_delimiter)
839                         p_delimiter = p + strlen(p);
840                 if (*p == '\\' && *(p + 1) == '{')
841                         goto recursive;
842                 if (!tomoyo_file_matches_pattern(f, f_delimiter, p,
843                                                  p_delimiter))
844                         return false;
845                 f = f_delimiter;
846                 if (*f)
847                         f++;
848                 p = p_delimiter;
849                 if (*p)
850                         p++;
851         }
852         /* Ignore trailing "\*" and "\@" in @pattern. */
853         while (*p == '\\' &&
854                (*(p + 1) == '*' || *(p + 1) == '@'))
855                 p += 2;
856         return !*f && !*p;
857  recursive:
858         /*
859          * The "\{" pattern is permitted only after '/' character.
860          * This guarantees that below "*(p - 1)" is safe.
861          * Also, the "\}" pattern is permitted only before '/' character
862          * so that "\{" + "\}" pair will not break the "\-" operator.
863          */
864         if (*(p - 1) != '/' || p_delimiter <= p + 3 || *p_delimiter != '/' ||
865             *(p_delimiter - 1) != '}' || *(p_delimiter - 2) != '\\')
866                 return false; /* Bad pattern. */
867         do {
868                 /* Compare current component with pattern. */
869                 if (!tomoyo_file_matches_pattern(f, f_delimiter, p + 2,
870                                                  p_delimiter - 2))
871                         break;
872                 /* Proceed to next component. */
873                 f = f_delimiter;
874                 if (!*f)
875                         break;
876                 f++;
877                 /* Continue comparison. */
878                 if (tomoyo_path_matches_pattern2(f, p_delimiter + 1))
879                         return true;
880                 f_delimiter = strchr(f, '/');
881         } while (f_delimiter);
882         return false; /* Not matched. */
883 }
884
885 /**
886  * tomoyo_path_matches_pattern - Check whether the given filename matches the given pattern.
887  *
888  * @filename: The filename to check.
889  * @pattern:  The pattern to compare.
890  *
891  * Returns true if matches, false otherwise.
892  *
893  * The following patterns are available.
894  *   \\     \ itself.
895  *   \ooo   Octal representation of a byte.
896  *   \*     Zero or more repetitions of characters other than '/'.
897  *   \@     Zero or more repetitions of characters other than '/' or '.'.
898  *   \?     1 byte character other than '/'.
899  *   \$     One or more repetitions of decimal digits.
900  *   \+     1 decimal digit.
901  *   \X     One or more repetitions of hexadecimal digits.
902  *   \x     1 hexadecimal digit.
903  *   \A     One or more repetitions of alphabet characters.
904  *   \a     1 alphabet character.
905  *
906  *   \-     Subtraction operator.
907  *
908  *   /\{dir\}/   '/' + 'One or more repetitions of dir/' (e.g. /dir/ /dir/dir/
909  *               /dir/dir/dir/ ).
910  */
911 bool tomoyo_path_matches_pattern(const struct tomoyo_path_info *filename,
912                                  const struct tomoyo_path_info *pattern)
913 {
914         const char *f = filename->name;
915         const char *p = pattern->name;
916         const int len = pattern->const_len;
917
918         /* If @pattern doesn't contain pattern, I can use strcmp(). */
919         if (!pattern->is_patterned)
920                 return !tomoyo_pathcmp(filename, pattern);
921         /* Don't compare directory and non-directory. */
922         if (filename->is_dir != pattern->is_dir)
923                 return false;
924         /* Compare the initial length without patterns. */
925         if (strncmp(f, p, len))
926                 return false;
927         f += len;
928         p += len;
929         return tomoyo_path_matches_pattern2(f, p);
930 }
931
932 /**
933  * tomoyo_io_printf - Transactional printf() to "struct tomoyo_io_buffer" structure.
934  *
935  * @head: Pointer to "struct tomoyo_io_buffer".
936  * @fmt:  The printf()'s format string, followed by parameters.
937  *
938  * Returns true if output was written, false otherwise.
939  *
940  * The snprintf() will truncate, but tomoyo_io_printf() won't.
941  */
942 bool tomoyo_io_printf(struct tomoyo_io_buffer *head, const char *fmt, ...)
943 {
944         va_list args;
945         int len;
946         int pos = head->read_avail;
947         int size = head->readbuf_size - pos;
948
949         if (size <= 0)
950                 return false;
951         va_start(args, fmt);
952         len = vsnprintf(head->read_buf + pos, size, fmt, args);
953         va_end(args);
954         if (pos + len >= head->readbuf_size)
955                 return false;
956         head->read_avail += len;
957         return true;
958 }
959
960 /**
961  * tomoyo_get_exe - Get tomoyo_realpath() of current process.
962  *
963  * Returns the tomoyo_realpath() of current process on success, NULL otherwise.
964  *
965  * This function uses kzalloc(), so the caller must call kfree()
966  * if this function didn't return NULL.
967  */
968 static const char *tomoyo_get_exe(void)
969 {
970         struct mm_struct *mm = current->mm;
971         struct vm_area_struct *vma;
972         const char *cp = NULL;
973
974         if (!mm)
975                 return NULL;
976         down_read(&mm->mmap_sem);
977         for (vma = mm->mmap; vma; vma = vma->vm_next) {
978                 if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
979                         cp = tomoyo_realpath_from_path(&vma->vm_file->f_path);
980                         break;
981                 }
982         }
983         up_read(&mm->mmap_sem);
984         return cp;
985 }
986
987 /**
988  * tomoyo_get_msg - Get warning message.
989  *
990  * @is_enforce: Is it enforcing mode?
991  *
992  * Returns "ERROR" or "WARNING".
993  */
994 const char *tomoyo_get_msg(const bool is_enforce)
995 {
996         if (is_enforce)
997                 return "ERROR";
998         else
999                 return "WARNING";
1000 }
1001
1002 /**
1003  * tomoyo_check_flags - Check mode for specified functionality.
1004  *
1005  * @domain: Pointer to "struct tomoyo_domain_info".
1006  * @index:  The functionality to check mode.
1007  *
1008  * TOMOYO checks only process context.
1009  * This code disables TOMOYO's enforcement in case the function is called from
1010  * interrupt context.
1011  */
1012 unsigned int tomoyo_check_flags(const struct tomoyo_domain_info *domain,
1013                                 const u8 index)
1014 {
1015         const u8 profile = domain->profile;
1016
1017         if (WARN_ON(in_interrupt()))
1018                 return 0;
1019         return tomoyo_policy_loaded && index < TOMOYO_MAX_CONTROL_INDEX
1020 #if TOMOYO_MAX_PROFILES != 256
1021                 && profile < TOMOYO_MAX_PROFILES
1022 #endif
1023                 && tomoyo_profile_ptr[profile] ?
1024                 tomoyo_profile_ptr[profile]->value[index] : 0;
1025 }
1026
1027 /**
1028  * tomoyo_verbose_mode - Check whether TOMOYO is verbose mode.
1029  *
1030  * @domain: Pointer to "struct tomoyo_domain_info".
1031  *
1032  * Returns true if domain policy violation warning should be printed to
1033  * console.
1034  */
1035 bool tomoyo_verbose_mode(const struct tomoyo_domain_info *domain)
1036 {
1037         return tomoyo_check_flags(domain, TOMOYO_VERBOSE) != 0;
1038 }
1039
1040 /**
1041  * tomoyo_domain_quota_is_ok - Check for domain's quota.
1042  *
1043  * @domain: Pointer to "struct tomoyo_domain_info".
1044  *
1045  * Returns true if the domain is not exceeded quota, false otherwise.
1046  *
1047  * Caller holds tomoyo_read_lock().
1048  */
1049 bool tomoyo_domain_quota_is_ok(struct tomoyo_domain_info * const domain)
1050 {
1051         unsigned int count = 0;
1052         struct tomoyo_acl_info *ptr;
1053
1054         if (!domain)
1055                 return true;
1056         list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
1057                 switch (ptr->type) {
1058                         struct tomoyo_path_acl *acl;
1059                         u32 perm;
1060                         u8 i;
1061                 case TOMOYO_TYPE_PATH_ACL:
1062                         acl = container_of(ptr, struct tomoyo_path_acl, head);
1063                         perm = acl->perm | (((u32) acl->perm_high) << 16);
1064                         for (i = 0; i < TOMOYO_MAX_PATH_OPERATION; i++)
1065                                 if (perm & (1 << i))
1066                                         count++;
1067                         if (perm & (1 << TOMOYO_TYPE_READ_WRITE))
1068                                 count -= 2;
1069                         break;
1070                 case TOMOYO_TYPE_PATH2_ACL:
1071                         perm = container_of(ptr, struct tomoyo_path2_acl, head)
1072                                 ->perm;
1073                         for (i = 0; i < TOMOYO_MAX_PATH2_OPERATION; i++)
1074                                 if (perm & (1 << i))
1075                                         count++;
1076                         break;
1077                 }
1078         }
1079         if (count < tomoyo_check_flags(domain, TOMOYO_MAX_ACCEPT_ENTRY))
1080                 return true;
1081         if (!domain->quota_warned) {
1082                 domain->quota_warned = true;
1083                 printk(KERN_WARNING "TOMOYO-WARNING: "
1084                        "Domain '%s' has so many ACLs to hold. "
1085                        "Stopped learning mode.\n", domain->domainname->name);
1086         }
1087         return false;
1088 }
1089
1090 /**
1091  * tomoyo_find_or_assign_new_profile - Create a new profile.
1092  *
1093  * @profile: Profile number to create.
1094  *
1095  * Returns pointer to "struct tomoyo_profile" on success, NULL otherwise.
1096  */
1097 static struct tomoyo_profile *tomoyo_find_or_assign_new_profile(const unsigned
1098                                                                 int profile)
1099 {
1100         struct tomoyo_profile *ptr = NULL;
1101         int i;
1102
1103         if (profile >= TOMOYO_MAX_PROFILES)
1104                 return NULL;
1105         if (mutex_lock_interruptible(&tomoyo_policy_lock))
1106                 return NULL;
1107         ptr = tomoyo_profile_ptr[profile];
1108         if (ptr)
1109                 goto ok;
1110         ptr = kmalloc(sizeof(*ptr), GFP_NOFS);
1111         if (!tomoyo_memory_ok(ptr)) {
1112                 kfree(ptr);
1113                 ptr = NULL;
1114                 goto ok;
1115         }
1116         for (i = 0; i < TOMOYO_MAX_CONTROL_INDEX; i++)
1117                 ptr->value[i] = tomoyo_control_array[i].current_value;
1118         mb(); /* Avoid out-of-order execution. */
1119         tomoyo_profile_ptr[profile] = ptr;
1120  ok:
1121         mutex_unlock(&tomoyo_policy_lock);
1122         return ptr;
1123 }
1124
1125 /**
1126  * tomoyo_write_profile - Write to profile table.
1127  *
1128  * @head: Pointer to "struct tomoyo_io_buffer".
1129  *
1130  * Returns 0 on success, negative value otherwise.
1131  */
1132 static int tomoyo_write_profile(struct tomoyo_io_buffer *head)
1133 {
1134         char *data = head->write_buf;
1135         unsigned int i;
1136         unsigned int value;
1137         char *cp;
1138         struct tomoyo_profile *profile;
1139         unsigned long num;
1140
1141         cp = strchr(data, '-');
1142         if (cp)
1143                 *cp = '\0';
1144         if (strict_strtoul(data, 10, &num))
1145                 return -EINVAL;
1146         if (cp)
1147                 data = cp + 1;
1148         profile = tomoyo_find_or_assign_new_profile(num);
1149         if (!profile)
1150                 return -EINVAL;
1151         cp = strchr(data, '=');
1152         if (!cp)
1153                 return -EINVAL;
1154         *cp = '\0';
1155         if (!strcmp(data, "COMMENT")) {
1156                 const struct tomoyo_path_info *old_comment = profile->comment;
1157                 profile->comment = tomoyo_get_name(cp + 1);
1158                 tomoyo_put_name(old_comment);
1159                 return 0;
1160         }
1161         for (i = 0; i < TOMOYO_MAX_CONTROL_INDEX; i++) {
1162                 if (strcmp(data, tomoyo_control_array[i].keyword))
1163                         continue;
1164                 if (sscanf(cp + 1, "%u", &value) != 1) {
1165                         int j;
1166                         const char **modes;
1167                         switch (i) {
1168                         case TOMOYO_VERBOSE:
1169                                 modes = tomoyo_mode_2;
1170                                 break;
1171                         default:
1172                                 modes = tomoyo_mode_4;
1173                                 break;
1174                         }
1175                         for (j = 0; j < 4; j++) {
1176                                 if (strcmp(cp + 1, modes[j]))
1177                                         continue;
1178                                 value = j;
1179                                 break;
1180                         }
1181                         if (j == 4)
1182                                 return -EINVAL;
1183                 } else if (value > tomoyo_control_array[i].max_value) {
1184                         value = tomoyo_control_array[i].max_value;
1185                 }
1186                 profile->value[i] = value;
1187                 return 0;
1188         }
1189         return -EINVAL;
1190 }
1191
1192 /**
1193  * tomoyo_read_profile - Read from profile table.
1194  *
1195  * @head: Pointer to "struct tomoyo_io_buffer".
1196  *
1197  * Returns 0.
1198  */
1199 static int tomoyo_read_profile(struct tomoyo_io_buffer *head)
1200 {
1201         static const int total = TOMOYO_MAX_CONTROL_INDEX + 1;
1202         int step;
1203
1204         if (head->read_eof)
1205                 return 0;
1206         for (step = head->read_step; step < TOMOYO_MAX_PROFILES * total;
1207              step++) {
1208                 const u8 index = step / total;
1209                 u8 type = step % total;
1210                 const struct tomoyo_profile *profile
1211                         = tomoyo_profile_ptr[index];
1212                 head->read_step = step;
1213                 if (!profile)
1214                         continue;
1215                 if (!type) { /* Print profile' comment tag. */
1216                         if (!tomoyo_io_printf(head, "%u-COMMENT=%s\n",
1217                                               index, profile->comment ?
1218                                               profile->comment->name : ""))
1219                                 break;
1220                         continue;
1221                 }
1222                 type--;
1223                 if (type < TOMOYO_MAX_CONTROL_INDEX) {
1224                         const unsigned int value = profile->value[type];
1225                         const char **modes = NULL;
1226                         const char *keyword
1227                                 = tomoyo_control_array[type].keyword;
1228                         switch (tomoyo_control_array[type].max_value) {
1229                         case 3:
1230                                 modes = tomoyo_mode_4;
1231                                 break;
1232                         case 1:
1233                                 modes = tomoyo_mode_2;
1234                                 break;
1235                         }
1236                         if (modes) {
1237                                 if (!tomoyo_io_printf(head, "%u-%s=%s\n", index,
1238                                                       keyword, modes[value]))
1239                                         break;
1240                         } else {
1241                                 if (!tomoyo_io_printf(head, "%u-%s=%u\n", index,
1242                                                       keyword, value))
1243                                         break;
1244                         }
1245                 }
1246         }
1247         if (step == TOMOYO_MAX_PROFILES * total)
1248                 head->read_eof = true;
1249         return 0;
1250 }
1251
1252 /*
1253  * tomoyo_policy_manager_list is used for holding list of domainnames or
1254  * programs which are permitted to modify configuration via
1255  * /sys/kernel/security/tomoyo/ interface.
1256  *
1257  * An entry is added by
1258  *
1259  * # echo '<kernel> /sbin/mingetty /bin/login /bin/bash' > \
1260  *                                        /sys/kernel/security/tomoyo/manager
1261  *  (if you want to specify by a domainname)
1262  *
1263  *  or
1264  *
1265  * # echo '/usr/lib/ccs/editpolicy' > /sys/kernel/security/tomoyo/manager
1266  *  (if you want to specify by a program's location)
1267  *
1268  * and is deleted by
1269  *
1270  * # echo 'delete <kernel> /sbin/mingetty /bin/login /bin/bash' > \
1271  *                                        /sys/kernel/security/tomoyo/manager
1272  *
1273  *  or
1274  *
1275  * # echo 'delete /usr/lib/ccs/editpolicy' > \
1276  *                                        /sys/kernel/security/tomoyo/manager
1277  *
1278  * and all entries are retrieved by
1279  *
1280  * # cat /sys/kernel/security/tomoyo/manager
1281  */
1282 LIST_HEAD(tomoyo_policy_manager_list);
1283
1284 /**
1285  * tomoyo_update_manager_entry - Add a manager entry.
1286  *
1287  * @manager:   The path to manager or the domainnamme.
1288  * @is_delete: True if it is a delete request.
1289  *
1290  * Returns 0 on success, negative value otherwise.
1291  *
1292  * Caller holds tomoyo_read_lock().
1293  */
1294 static int tomoyo_update_manager_entry(const char *manager,
1295                                        const bool is_delete)
1296 {
1297         struct tomoyo_policy_manager_entry *ptr;
1298         struct tomoyo_policy_manager_entry e = { };
1299         int error = is_delete ? -ENOENT : -ENOMEM;
1300
1301         if (tomoyo_is_domain_def(manager)) {
1302                 if (!tomoyo_is_correct_domain(manager))
1303                         return -EINVAL;
1304                 e.is_domain = true;
1305         } else {
1306                 if (!tomoyo_is_correct_path(manager, 1, -1, -1))
1307                         return -EINVAL;
1308         }
1309         e.manager = tomoyo_get_name(manager);
1310         if (!e.manager)
1311                 return -ENOMEM;
1312         if (mutex_lock_interruptible(&tomoyo_policy_lock))
1313                 goto out;
1314         list_for_each_entry_rcu(ptr, &tomoyo_policy_manager_list, list) {
1315                 if (ptr->manager != e.manager)
1316                         continue;
1317                 ptr->is_deleted = is_delete;
1318                 error = 0;
1319                 break;
1320         }
1321         if (!is_delete && error) {
1322                 struct tomoyo_policy_manager_entry *entry =
1323                         tomoyo_commit_ok(&e, sizeof(e));
1324                 if (entry) {
1325                         list_add_tail_rcu(&entry->list,
1326                                           &tomoyo_policy_manager_list);
1327                         error = 0;
1328                 }
1329         }
1330         mutex_unlock(&tomoyo_policy_lock);
1331  out:
1332         tomoyo_put_name(e.manager);
1333         return error;
1334 }
1335
1336 /**
1337  * tomoyo_write_manager_policy - Write manager policy.
1338  *
1339  * @head: Pointer to "struct tomoyo_io_buffer".
1340  *
1341  * Returns 0 on success, negative value otherwise.
1342  *
1343  * Caller holds tomoyo_read_lock().
1344  */
1345 static int tomoyo_write_manager_policy(struct tomoyo_io_buffer *head)
1346 {
1347         char *data = head->write_buf;
1348         bool is_delete = tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE);
1349
1350         if (!strcmp(data, "manage_by_non_root")) {
1351                 tomoyo_manage_by_non_root = !is_delete;
1352                 return 0;
1353         }
1354         return tomoyo_update_manager_entry(data, is_delete);
1355 }
1356
1357 /**
1358  * tomoyo_read_manager_policy - Read manager policy.
1359  *
1360  * @head: Pointer to "struct tomoyo_io_buffer".
1361  *
1362  * Returns 0.
1363  *
1364  * Caller holds tomoyo_read_lock().
1365  */
1366 static int tomoyo_read_manager_policy(struct tomoyo_io_buffer *head)
1367 {
1368         struct list_head *pos;
1369         bool done = true;
1370
1371         if (head->read_eof)
1372                 return 0;
1373         list_for_each_cookie(pos, head->read_var2,
1374                              &tomoyo_policy_manager_list) {
1375                 struct tomoyo_policy_manager_entry *ptr;
1376                 ptr = list_entry(pos, struct tomoyo_policy_manager_entry,
1377                                  list);
1378                 if (ptr->is_deleted)
1379                         continue;
1380                 done = tomoyo_io_printf(head, "%s\n", ptr->manager->name);
1381                 if (!done)
1382                         break;
1383         }
1384         head->read_eof = done;
1385         return 0;
1386 }
1387
1388 /**
1389  * tomoyo_is_policy_manager - Check whether the current process is a policy manager.
1390  *
1391  * Returns true if the current process is permitted to modify policy
1392  * via /sys/kernel/security/tomoyo/ interface.
1393  *
1394  * Caller holds tomoyo_read_lock().
1395  */
1396 static bool tomoyo_is_policy_manager(void)
1397 {
1398         struct tomoyo_policy_manager_entry *ptr;
1399         const char *exe;
1400         const struct task_struct *task = current;
1401         const struct tomoyo_path_info *domainname = tomoyo_domain()->domainname;
1402         bool found = false;
1403
1404         if (!tomoyo_policy_loaded)
1405                 return true;
1406         if (!tomoyo_manage_by_non_root && (task->cred->uid || task->cred->euid))
1407                 return false;
1408         list_for_each_entry_rcu(ptr, &tomoyo_policy_manager_list, list) {
1409                 if (!ptr->is_deleted && ptr->is_domain
1410                     && !tomoyo_pathcmp(domainname, ptr->manager)) {
1411                         found = true;
1412                         break;
1413                 }
1414         }
1415         if (found)
1416                 return true;
1417         exe = tomoyo_get_exe();
1418         if (!exe)
1419                 return false;
1420         list_for_each_entry_rcu(ptr, &tomoyo_policy_manager_list, list) {
1421                 if (!ptr->is_deleted && !ptr->is_domain
1422                     && !strcmp(exe, ptr->manager->name)) {
1423                         found = true;
1424                         break;
1425                 }
1426         }
1427         if (!found) { /* Reduce error messages. */
1428                 static pid_t last_pid;
1429                 const pid_t pid = current->pid;
1430                 if (last_pid != pid) {
1431                         printk(KERN_WARNING "%s ( %s ) is not permitted to "
1432                                "update policies.\n", domainname->name, exe);
1433                         last_pid = pid;
1434                 }
1435         }
1436         kfree(exe);
1437         return found;
1438 }
1439
1440 /**
1441  * tomoyo_is_select_one - Parse select command.
1442  *
1443  * @head: Pointer to "struct tomoyo_io_buffer".
1444  * @data: String to parse.
1445  *
1446  * Returns true on success, false otherwise.
1447  *
1448  * Caller holds tomoyo_read_lock().
1449  */
1450 static bool tomoyo_is_select_one(struct tomoyo_io_buffer *head,
1451                                  const char *data)
1452 {
1453         unsigned int pid;
1454         struct tomoyo_domain_info *domain = NULL;
1455
1456         if (sscanf(data, "pid=%u", &pid) == 1) {
1457                 struct task_struct *p;
1458                 rcu_read_lock();
1459                 read_lock(&tasklist_lock);
1460                 p = find_task_by_vpid(pid);
1461                 if (p)
1462                         domain = tomoyo_real_domain(p);
1463                 read_unlock(&tasklist_lock);
1464                 rcu_read_unlock();
1465         } else if (!strncmp(data, "domain=", 7)) {
1466                 if (tomoyo_is_domain_def(data + 7))
1467                         domain = tomoyo_find_domain(data + 7);
1468         } else
1469                 return false;
1470         head->write_var1 = domain;
1471         /* Accessing read_buf is safe because head->io_sem is held. */
1472         if (!head->read_buf)
1473                 return true; /* Do nothing if open(O_WRONLY). */
1474         head->read_avail = 0;
1475         tomoyo_io_printf(head, "# select %s\n", data);
1476         head->read_single_domain = true;
1477         head->read_eof = !domain;
1478         if (domain) {
1479                 struct tomoyo_domain_info *d;
1480                 head->read_var1 = NULL;
1481                 list_for_each_entry_rcu(d, &tomoyo_domain_list, list) {
1482                         if (d == domain)
1483                                 break;
1484                         head->read_var1 = &d->list;
1485                 }
1486                 head->read_var2 = NULL;
1487                 head->read_bit = 0;
1488                 head->read_step = 0;
1489                 if (domain->is_deleted)
1490                         tomoyo_io_printf(head, "# This is a deleted domain.\n");
1491         }
1492         return true;
1493 }
1494
1495 /**
1496  * tomoyo_delete_domain - Delete a domain.
1497  *
1498  * @domainname: The name of domain.
1499  *
1500  * Returns 0.
1501  *
1502  * Caller holds tomoyo_read_lock().
1503  */
1504 static int tomoyo_delete_domain(char *domainname)
1505 {
1506         struct tomoyo_domain_info *domain;
1507         struct tomoyo_path_info name;
1508
1509         name.name = domainname;
1510         tomoyo_fill_path_info(&name);
1511         if (mutex_lock_interruptible(&tomoyo_policy_lock))
1512                 return 0;
1513         /* Is there an active domain? */
1514         list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
1515                 /* Never delete tomoyo_kernel_domain */
1516                 if (domain == &tomoyo_kernel_domain)
1517                         continue;
1518                 if (domain->is_deleted ||
1519                     tomoyo_pathcmp(domain->domainname, &name))
1520                         continue;
1521                 domain->is_deleted = true;
1522                 break;
1523         }
1524         mutex_unlock(&tomoyo_policy_lock);
1525         return 0;
1526 }
1527
1528 /**
1529  * tomoyo_write_domain_policy - Write domain policy.
1530  *
1531  * @head: Pointer to "struct tomoyo_io_buffer".
1532  *
1533  * Returns 0 on success, negative value otherwise.
1534  *
1535  * Caller holds tomoyo_read_lock().
1536  */
1537 static int tomoyo_write_domain_policy(struct tomoyo_io_buffer *head)
1538 {
1539         char *data = head->write_buf;
1540         struct tomoyo_domain_info *domain = head->write_var1;
1541         bool is_delete = false;
1542         bool is_select = false;
1543         unsigned int profile;
1544
1545         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE))
1546                 is_delete = true;
1547         else if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_SELECT))
1548                 is_select = true;
1549         if (is_select && tomoyo_is_select_one(head, data))
1550                 return 0;
1551         /* Don't allow updating policies by non manager programs. */
1552         if (!tomoyo_is_policy_manager())
1553                 return -EPERM;
1554         if (tomoyo_is_domain_def(data)) {
1555                 domain = NULL;
1556                 if (is_delete)
1557                         tomoyo_delete_domain(data);
1558                 else if (is_select)
1559                         domain = tomoyo_find_domain(data);
1560                 else
1561                         domain = tomoyo_find_or_assign_new_domain(data, 0);
1562                 head->write_var1 = domain;
1563                 return 0;
1564         }
1565         if (!domain)
1566                 return -EINVAL;
1567
1568         if (sscanf(data, TOMOYO_KEYWORD_USE_PROFILE "%u", &profile) == 1
1569             && profile < TOMOYO_MAX_PROFILES) {
1570                 if (tomoyo_profile_ptr[profile] || !tomoyo_policy_loaded)
1571                         domain->profile = (u8) profile;
1572                 return 0;
1573         }
1574         if (!strcmp(data, TOMOYO_KEYWORD_IGNORE_GLOBAL_ALLOW_READ)) {
1575                 domain->ignore_global_allow_read = !is_delete;
1576                 return 0;
1577         }
1578         return tomoyo_write_file_policy(data, domain, is_delete);
1579 }
1580
1581 /**
1582  * tomoyo_print_path_acl - Print a single path ACL entry.
1583  *
1584  * @head: Pointer to "struct tomoyo_io_buffer".
1585  * @ptr:  Pointer to "struct tomoyo_path_acl".
1586  *
1587  * Returns true on success, false otherwise.
1588  */
1589 static bool tomoyo_print_path_acl(struct tomoyo_io_buffer *head,
1590                                   struct tomoyo_path_acl *ptr)
1591 {
1592         int pos;
1593         u8 bit;
1594         const u32 perm = ptr->perm | (((u32) ptr->perm_high) << 16);
1595
1596         for (bit = head->read_bit; bit < TOMOYO_MAX_PATH_OPERATION; bit++) {
1597                 if (!(perm & (1 << bit)))
1598                         continue;
1599                 /* Print "read/write" instead of "read" and "write". */
1600                 if ((bit == TOMOYO_TYPE_READ || bit == TOMOYO_TYPE_WRITE)
1601                     && (perm & (1 << TOMOYO_TYPE_READ_WRITE)))
1602                         continue;
1603                 pos = head->read_avail;
1604                 if (!tomoyo_io_printf(head, "allow_%s ",
1605                                       tomoyo_path2keyword(bit)) ||
1606                     !tomoyo_print_name_union(head, &ptr->name) ||
1607                     !tomoyo_io_printf(head, "\n"))
1608                         goto out;
1609         }
1610         head->read_bit = 0;
1611         return true;
1612  out:
1613         head->read_bit = bit;
1614         head->read_avail = pos;
1615         return false;
1616 }
1617
1618 /**
1619  * tomoyo_print_path2_acl - Print a double path ACL entry.
1620  *
1621  * @head: Pointer to "struct tomoyo_io_buffer".
1622  * @ptr:  Pointer to "struct tomoyo_path2_acl".
1623  *
1624  * Returns true on success, false otherwise.
1625  */
1626 static bool tomoyo_print_path2_acl(struct tomoyo_io_buffer *head,
1627                                    struct tomoyo_path2_acl *ptr)
1628 {
1629         int pos;
1630         const u8 perm = ptr->perm;
1631         u8 bit;
1632
1633         for (bit = head->read_bit; bit < TOMOYO_MAX_PATH2_OPERATION; bit++) {
1634                 if (!(perm & (1 << bit)))
1635                         continue;
1636                 pos = head->read_avail;
1637                 if (!tomoyo_io_printf(head, "allow_%s ",
1638                                       tomoyo_path22keyword(bit)) ||
1639                     !tomoyo_print_name_union(head, &ptr->name1) ||
1640                     !tomoyo_print_name_union(head, &ptr->name2) ||
1641                     !tomoyo_io_printf(head, "\n"))
1642                         goto out;
1643         }
1644         head->read_bit = 0;
1645         return true;
1646  out:
1647         head->read_bit = bit;
1648         head->read_avail = pos;
1649         return false;
1650 }
1651
1652 /**
1653  * tomoyo_print_entry - Print an ACL entry.
1654  *
1655  * @head: Pointer to "struct tomoyo_io_buffer".
1656  * @ptr:  Pointer to an ACL entry.
1657  *
1658  * Returns true on success, false otherwise.
1659  */
1660 static bool tomoyo_print_entry(struct tomoyo_io_buffer *head,
1661                                struct tomoyo_acl_info *ptr)
1662 {
1663         const u8 acl_type = ptr->type;
1664
1665         if (acl_type == TOMOYO_TYPE_PATH_ACL) {
1666                 struct tomoyo_path_acl *acl
1667                         = container_of(ptr, struct tomoyo_path_acl, head);
1668                 return tomoyo_print_path_acl(head, acl);
1669         }
1670         if (acl_type == TOMOYO_TYPE_PATH2_ACL) {
1671                 struct tomoyo_path2_acl *acl
1672                         = container_of(ptr, struct tomoyo_path2_acl, head);
1673                 return tomoyo_print_path2_acl(head, acl);
1674         }
1675         BUG(); /* This must not happen. */
1676         return false;
1677 }
1678
1679 /**
1680  * tomoyo_read_domain_policy - Read domain policy.
1681  *
1682  * @head: Pointer to "struct tomoyo_io_buffer".
1683  *
1684  * Returns 0.
1685  *
1686  * Caller holds tomoyo_read_lock().
1687  */
1688 static int tomoyo_read_domain_policy(struct tomoyo_io_buffer *head)
1689 {
1690         struct list_head *dpos;
1691         struct list_head *apos;
1692         bool done = true;
1693
1694         if (head->read_eof)
1695                 return 0;
1696         if (head->read_step == 0)
1697                 head->read_step = 1;
1698         list_for_each_cookie(dpos, head->read_var1, &tomoyo_domain_list) {
1699                 struct tomoyo_domain_info *domain;
1700                 const char *quota_exceeded = "";
1701                 const char *transition_failed = "";
1702                 const char *ignore_global_allow_read = "";
1703                 domain = list_entry(dpos, struct tomoyo_domain_info, list);
1704                 if (head->read_step != 1)
1705                         goto acl_loop;
1706                 if (domain->is_deleted && !head->read_single_domain)
1707                         continue;
1708                 /* Print domainname and flags. */
1709                 if (domain->quota_warned)
1710                         quota_exceeded = "quota_exceeded\n";
1711                 if (domain->transition_failed)
1712                         transition_failed = "transition_failed\n";
1713                 if (domain->ignore_global_allow_read)
1714                         ignore_global_allow_read
1715                                 = TOMOYO_KEYWORD_IGNORE_GLOBAL_ALLOW_READ "\n";
1716                 done = tomoyo_io_printf(head, "%s\n" TOMOYO_KEYWORD_USE_PROFILE
1717                                         "%u\n%s%s%s\n",
1718                                         domain->domainname->name,
1719                                         domain->profile, quota_exceeded,
1720                                         transition_failed,
1721                                         ignore_global_allow_read);
1722                 if (!done)
1723                         break;
1724                 head->read_step = 2;
1725 acl_loop:
1726                 if (head->read_step == 3)
1727                         goto tail_mark;
1728                 /* Print ACL entries in the domain. */
1729                 list_for_each_cookie(apos, head->read_var2,
1730                                      &domain->acl_info_list) {
1731                         struct tomoyo_acl_info *ptr
1732                                 = list_entry(apos, struct tomoyo_acl_info,
1733                                              list);
1734                         done = tomoyo_print_entry(head, ptr);
1735                         if (!done)
1736                                 break;
1737                 }
1738                 if (!done)
1739                         break;
1740                 head->read_step = 3;
1741 tail_mark:
1742                 done = tomoyo_io_printf(head, "\n");
1743                 if (!done)
1744                         break;
1745                 head->read_step = 1;
1746                 if (head->read_single_domain)
1747                         break;
1748         }
1749         head->read_eof = done;
1750         return 0;
1751 }
1752
1753 /**
1754  * tomoyo_write_domain_profile - Assign profile for specified domain.
1755  *
1756  * @head: Pointer to "struct tomoyo_io_buffer".
1757  *
1758  * Returns 0 on success, -EINVAL otherwise.
1759  *
1760  * This is equivalent to doing
1761  *
1762  *     ( echo "select " $domainname; echo "use_profile " $profile ) |
1763  *     /usr/lib/ccs/loadpolicy -d
1764  *
1765  * Caller holds tomoyo_read_lock().
1766  */
1767 static int tomoyo_write_domain_profile(struct tomoyo_io_buffer *head)
1768 {
1769         char *data = head->write_buf;
1770         char *cp = strchr(data, ' ');
1771         struct tomoyo_domain_info *domain;
1772         unsigned long profile;
1773
1774         if (!cp)
1775                 return -EINVAL;
1776         *cp = '\0';
1777         domain = tomoyo_find_domain(cp + 1);
1778         if (strict_strtoul(data, 10, &profile))
1779                 return -EINVAL;
1780         if (domain && profile < TOMOYO_MAX_PROFILES
1781             && (tomoyo_profile_ptr[profile] || !tomoyo_policy_loaded))
1782                 domain->profile = (u8) profile;
1783         return 0;
1784 }
1785
1786 /**
1787  * tomoyo_read_domain_profile - Read only domainname and profile.
1788  *
1789  * @head: Pointer to "struct tomoyo_io_buffer".
1790  *
1791  * Returns list of profile number and domainname pairs.
1792  *
1793  * This is equivalent to doing
1794  *
1795  *     grep -A 1 '^<kernel>' /sys/kernel/security/tomoyo/domain_policy |
1796  *     awk ' { if ( domainname == "" ) { if ( $1 == "<kernel>" )
1797  *     domainname = $0; } else if ( $1 == "use_profile" ) {
1798  *     print $2 " " domainname; domainname = ""; } } ; '
1799  *
1800  * Caller holds tomoyo_read_lock().
1801  */
1802 static int tomoyo_read_domain_profile(struct tomoyo_io_buffer *head)
1803 {
1804         struct list_head *pos;
1805         bool done = true;
1806
1807         if (head->read_eof)
1808                 return 0;
1809         list_for_each_cookie(pos, head->read_var1, &tomoyo_domain_list) {
1810                 struct tomoyo_domain_info *domain;
1811                 domain = list_entry(pos, struct tomoyo_domain_info, list);
1812                 if (domain->is_deleted)
1813                         continue;
1814                 done = tomoyo_io_printf(head, "%u %s\n", domain->profile,
1815                                         domain->domainname->name);
1816                 if (!done)
1817                         break;
1818         }
1819         head->read_eof = done;
1820         return 0;
1821 }
1822
1823 /**
1824  * tomoyo_write_pid: Specify PID to obtain domainname.
1825  *
1826  * @head: Pointer to "struct tomoyo_io_buffer".
1827  *
1828  * Returns 0.
1829  */
1830 static int tomoyo_write_pid(struct tomoyo_io_buffer *head)
1831 {
1832         unsigned long pid;
1833         /* No error check. */
1834         strict_strtoul(head->write_buf, 10, &pid);
1835         head->read_step = (int) pid;
1836         head->read_eof = false;
1837         return 0;
1838 }
1839
1840 /**
1841  * tomoyo_read_pid - Get domainname of the specified PID.
1842  *
1843  * @head: Pointer to "struct tomoyo_io_buffer".
1844  *
1845  * Returns the domainname which the specified PID is in on success,
1846  * empty string otherwise.
1847  * The PID is specified by tomoyo_write_pid() so that the user can obtain
1848  * using read()/write() interface rather than sysctl() interface.
1849  */
1850 static int tomoyo_read_pid(struct tomoyo_io_buffer *head)
1851 {
1852         if (head->read_avail == 0 && !head->read_eof) {
1853                 const int pid = head->read_step;
1854                 struct task_struct *p;
1855                 struct tomoyo_domain_info *domain = NULL;
1856                 rcu_read_lock();
1857                 read_lock(&tasklist_lock);
1858                 p = find_task_by_vpid(pid);
1859                 if (p)
1860                         domain = tomoyo_real_domain(p);
1861                 read_unlock(&tasklist_lock);
1862                 rcu_read_unlock();
1863                 if (domain)
1864                         tomoyo_io_printf(head, "%d %u %s", pid, domain->profile,
1865                                          domain->domainname->name);
1866                 head->read_eof = true;
1867         }
1868         return 0;
1869 }
1870
1871 /**
1872  * tomoyo_write_exception_policy - Write exception policy.
1873  *
1874  * @head: Pointer to "struct tomoyo_io_buffer".
1875  *
1876  * Returns 0 on success, negative value otherwise.
1877  *
1878  * Caller holds tomoyo_read_lock().
1879  */
1880 static int tomoyo_write_exception_policy(struct tomoyo_io_buffer *head)
1881 {
1882         char *data = head->write_buf;
1883         bool is_delete = tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE);
1884
1885         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_KEEP_DOMAIN))
1886                 return tomoyo_write_domain_keeper_policy(data, false,
1887                                                          is_delete);
1888         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_NO_KEEP_DOMAIN))
1889                 return tomoyo_write_domain_keeper_policy(data, true, is_delete);
1890         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_INITIALIZE_DOMAIN))
1891                 return tomoyo_write_domain_initializer_policy(data, false,
1892                                                               is_delete);
1893         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_NO_INITIALIZE_DOMAIN))
1894                 return tomoyo_write_domain_initializer_policy(data, true,
1895                                                               is_delete);
1896         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALIAS))
1897                 return tomoyo_write_alias_policy(data, is_delete);
1898         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALLOW_READ))
1899                 return tomoyo_write_globally_readable_policy(data, is_delete);
1900         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_FILE_PATTERN))
1901                 return tomoyo_write_pattern_policy(data, is_delete);
1902         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_DENY_REWRITE))
1903                 return tomoyo_write_no_rewrite_policy(data, is_delete);
1904         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_PATH_GROUP))
1905                 return tomoyo_write_path_group_policy(data, is_delete);
1906         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_NUMBER_GROUP))
1907                 return tomoyo_write_number_group_policy(data, is_delete);
1908         return -EINVAL;
1909 }
1910
1911 /**
1912  * tomoyo_read_exception_policy - Read exception policy.
1913  *
1914  * @head: Pointer to "struct tomoyo_io_buffer".
1915  *
1916  * Returns 0 on success, -EINVAL otherwise.
1917  *
1918  * Caller holds tomoyo_read_lock().
1919  */
1920 static int tomoyo_read_exception_policy(struct tomoyo_io_buffer *head)
1921 {
1922         if (!head->read_eof) {
1923                 switch (head->read_step) {
1924                 case 0:
1925                         head->read_var2 = NULL;
1926                         head->read_step = 1;
1927                 case 1:
1928                         if (!tomoyo_read_domain_keeper_policy(head))
1929                                 break;
1930                         head->read_var2 = NULL;
1931                         head->read_step = 2;
1932                 case 2:
1933                         if (!tomoyo_read_globally_readable_policy(head))
1934                                 break;
1935                         head->read_var2 = NULL;
1936                         head->read_step = 3;
1937                 case 3:
1938                         head->read_var2 = NULL;
1939                         head->read_step = 4;
1940                 case 4:
1941                         if (!tomoyo_read_domain_initializer_policy(head))
1942                                 break;
1943                         head->read_var2 = NULL;
1944                         head->read_step = 5;
1945                 case 5:
1946                         if (!tomoyo_read_alias_policy(head))
1947                                 break;
1948                         head->read_var2 = NULL;
1949                         head->read_step = 6;
1950                 case 6:
1951                         head->read_var2 = NULL;
1952                         head->read_step = 7;
1953                 case 7:
1954                         if (!tomoyo_read_file_pattern(head))
1955                                 break;
1956                         head->read_var2 = NULL;
1957                         head->read_step = 8;
1958                 case 8:
1959                         if (!tomoyo_read_no_rewrite_policy(head))
1960                                 break;
1961                         head->read_var2 = NULL;
1962                         head->read_step = 9;
1963                 case 9:
1964                         if (!tomoyo_read_path_group_policy(head))
1965                                 break;
1966                         head->read_var1 = NULL;
1967                         head->read_var2 = NULL;
1968                         head->read_step = 10;
1969                 case 10:
1970                         if (!tomoyo_read_number_group_policy(head))
1971                                 break;
1972                         head->read_var1 = NULL;
1973                         head->read_var2 = NULL;
1974                         head->read_step = 11;
1975                 case 11:
1976                         head->read_eof = true;
1977                         break;
1978                 default:
1979                         return -EINVAL;
1980                 }
1981         }
1982         return 0;
1983 }
1984
1985 /* path to policy loader */
1986 static const char *tomoyo_loader = "/sbin/tomoyo-init";
1987
1988 /**
1989  * tomoyo_policy_loader_exists - Check whether /sbin/tomoyo-init exists.
1990  *
1991  * Returns true if /sbin/tomoyo-init exists, false otherwise.
1992  */
1993 static bool tomoyo_policy_loader_exists(void)
1994 {
1995         /*
1996          * Don't activate MAC if the policy loader doesn't exist.
1997          * If the initrd includes /sbin/init but real-root-dev has not
1998          * mounted on / yet, activating MAC will block the system since
1999          * policies are not loaded yet.
2000          * Thus, let do_execve() call this function everytime.
2001          */
2002         struct path path;
2003
2004         if (kern_path(tomoyo_loader, LOOKUP_FOLLOW, &path)) {
2005                 printk(KERN_INFO "Not activating Mandatory Access Control now "
2006                        "since %s doesn't exist.\n", tomoyo_loader);
2007                 return false;
2008         }
2009         path_put(&path);
2010         return true;
2011 }
2012
2013 /**
2014  * tomoyo_load_policy - Run external policy loader to load policy.
2015  *
2016  * @filename: The program about to start.
2017  *
2018  * This function checks whether @filename is /sbin/init , and if so
2019  * invoke /sbin/tomoyo-init and wait for the termination of /sbin/tomoyo-init
2020  * and then continues invocation of /sbin/init.
2021  * /sbin/tomoyo-init reads policy files in /etc/tomoyo/ directory and
2022  * writes to /sys/kernel/security/tomoyo/ interfaces.
2023  *
2024  * Returns nothing.
2025  */
2026 void tomoyo_load_policy(const char *filename)
2027 {
2028         char *argv[2];
2029         char *envp[3];
2030
2031         if (tomoyo_policy_loaded)
2032                 return;
2033         /*
2034          * Check filename is /sbin/init or /sbin/tomoyo-start.
2035          * /sbin/tomoyo-start is a dummy filename in case where /sbin/init can't
2036          * be passed.
2037          * You can create /sbin/tomoyo-start by
2038          * "ln -s /bin/true /sbin/tomoyo-start".
2039          */
2040         if (strcmp(filename, "/sbin/init") &&
2041             strcmp(filename, "/sbin/tomoyo-start"))
2042                 return;
2043         if (!tomoyo_policy_loader_exists())
2044                 return;
2045
2046         printk(KERN_INFO "Calling %s to load policy. Please wait.\n",
2047                tomoyo_loader);
2048         argv[0] = (char *) tomoyo_loader;
2049         argv[1] = NULL;
2050         envp[0] = "HOME=/";
2051         envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
2052         envp[2] = NULL;
2053         call_usermodehelper(argv[0], argv, envp, 1);
2054
2055         printk(KERN_INFO "TOMOYO: 2.2.0   2009/04/01\n");
2056         printk(KERN_INFO "Mandatory Access Control activated.\n");
2057         tomoyo_policy_loaded = true;
2058         { /* Check all profiles currently assigned to domains are defined. */
2059                 struct tomoyo_domain_info *domain;
2060                 list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
2061                         const u8 profile = domain->profile;
2062                         if (tomoyo_profile_ptr[profile])
2063                                 continue;
2064                         panic("Profile %u (used by '%s') not defined.\n",
2065                               profile, domain->domainname->name);
2066                 }
2067         }
2068 }
2069
2070 /**
2071  * tomoyo_read_version: Get version.
2072  *
2073  * @head: Pointer to "struct tomoyo_io_buffer".
2074  *
2075  * Returns version information.
2076  */
2077 static int tomoyo_read_version(struct tomoyo_io_buffer *head)
2078 {
2079         if (!head->read_eof) {
2080                 tomoyo_io_printf(head, "2.2.0");
2081                 head->read_eof = true;
2082         }
2083         return 0;
2084 }
2085
2086 /**
2087  * tomoyo_read_self_domain - Get the current process's domainname.
2088  *
2089  * @head: Pointer to "struct tomoyo_io_buffer".
2090  *
2091  * Returns the current process's domainname.
2092  */
2093 static int tomoyo_read_self_domain(struct tomoyo_io_buffer *head)
2094 {
2095         if (!head->read_eof) {
2096                 /*
2097                  * tomoyo_domain()->domainname != NULL
2098                  * because every process belongs to a domain and
2099                  * the domain's name cannot be NULL.
2100                  */
2101                 tomoyo_io_printf(head, "%s", tomoyo_domain()->domainname->name);
2102                 head->read_eof = true;
2103         }
2104         return 0;
2105 }
2106
2107 /**
2108  * tomoyo_open_control - open() for /sys/kernel/security/tomoyo/ interface.
2109  *
2110  * @type: Type of interface.
2111  * @file: Pointer to "struct file".
2112  *
2113  * Associates policy handler and returns 0 on success, -ENOMEM otherwise.
2114  *
2115  * Caller acquires tomoyo_read_lock().
2116  */
2117 static int tomoyo_open_control(const u8 type, struct file *file)
2118 {
2119         struct tomoyo_io_buffer *head = kzalloc(sizeof(*head), GFP_NOFS);
2120
2121         if (!head)
2122                 return -ENOMEM;
2123         mutex_init(&head->io_sem);
2124         switch (type) {
2125         case TOMOYO_DOMAINPOLICY:
2126                 /* /sys/kernel/security/tomoyo/domain_policy */
2127                 head->write = tomoyo_write_domain_policy;
2128                 head->read = tomoyo_read_domain_policy;
2129                 break;
2130         case TOMOYO_EXCEPTIONPOLICY:
2131                 /* /sys/kernel/security/tomoyo/exception_policy */
2132                 head->write = tomoyo_write_exception_policy;
2133                 head->read = tomoyo_read_exception_policy;
2134                 break;
2135         case TOMOYO_SELFDOMAIN:
2136                 /* /sys/kernel/security/tomoyo/self_domain */
2137                 head->read = tomoyo_read_self_domain;
2138                 break;
2139         case TOMOYO_DOMAIN_STATUS:
2140                 /* /sys/kernel/security/tomoyo/.domain_status */
2141                 head->write = tomoyo_write_domain_profile;
2142                 head->read = tomoyo_read_domain_profile;
2143                 break;
2144         case TOMOYO_PROCESS_STATUS:
2145                 /* /sys/kernel/security/tomoyo/.process_status */
2146                 head->write = tomoyo_write_pid;
2147                 head->read = tomoyo_read_pid;
2148                 break;
2149         case TOMOYO_VERSION:
2150                 /* /sys/kernel/security/tomoyo/version */
2151                 head->read = tomoyo_read_version;
2152                 head->readbuf_size = 128;
2153                 break;
2154         case TOMOYO_MEMINFO:
2155                 /* /sys/kernel/security/tomoyo/meminfo */
2156                 head->write = tomoyo_write_memory_quota;
2157                 head->read = tomoyo_read_memory_counter;
2158                 head->readbuf_size = 512;
2159                 break;
2160         case TOMOYO_PROFILE:
2161                 /* /sys/kernel/security/tomoyo/profile */
2162                 head->write = tomoyo_write_profile;
2163                 head->read = tomoyo_read_profile;
2164                 break;
2165         case TOMOYO_MANAGER:
2166                 /* /sys/kernel/security/tomoyo/manager */
2167                 head->write = tomoyo_write_manager_policy;
2168                 head->read = tomoyo_read_manager_policy;
2169                 break;
2170         }
2171         if (!(file->f_mode & FMODE_READ)) {
2172                 /*
2173                  * No need to allocate read_buf since it is not opened
2174                  * for reading.
2175                  */
2176                 head->read = NULL;
2177         } else {
2178                 if (!head->readbuf_size)
2179                         head->readbuf_size = 4096 * 2;
2180                 head->read_buf = kzalloc(head->readbuf_size, GFP_NOFS);
2181                 if (!head->read_buf) {
2182                         kfree(head);
2183                         return -ENOMEM;
2184                 }
2185         }
2186         if (!(file->f_mode & FMODE_WRITE)) {
2187                 /*
2188                  * No need to allocate write_buf since it is not opened
2189                  * for writing.
2190                  */
2191                 head->write = NULL;
2192         } else if (head->write) {
2193                 head->writebuf_size = 4096 * 2;
2194                 head->write_buf = kzalloc(head->writebuf_size, GFP_NOFS);
2195                 if (!head->write_buf) {
2196                         kfree(head->read_buf);
2197                         kfree(head);
2198                         return -ENOMEM;
2199                 }
2200         }
2201         head->reader_idx = tomoyo_read_lock();
2202         file->private_data = head;
2203         /*
2204          * Call the handler now if the file is
2205          * /sys/kernel/security/tomoyo/self_domain
2206          * so that the user can use
2207          * cat < /sys/kernel/security/tomoyo/self_domain"
2208          * to know the current process's domainname.
2209          */
2210         if (type == TOMOYO_SELFDOMAIN)
2211                 tomoyo_read_control(file, NULL, 0);
2212         return 0;
2213 }
2214
2215 /**
2216  * tomoyo_read_control - read() for /sys/kernel/security/tomoyo/ interface.
2217  *
2218  * @file:       Pointer to "struct file".
2219  * @buffer:     Poiner to buffer to write to.
2220  * @buffer_len: Size of @buffer.
2221  *
2222  * Returns bytes read on success, negative value otherwise.
2223  *
2224  * Caller holds tomoyo_read_lock().
2225  */
2226 static int tomoyo_read_control(struct file *file, char __user *buffer,
2227                                const int buffer_len)
2228 {
2229         int len = 0;
2230         struct tomoyo_io_buffer *head = file->private_data;
2231         char *cp;
2232
2233         if (!head->read)
2234                 return -ENOSYS;
2235         if (mutex_lock_interruptible(&head->io_sem))
2236                 return -EINTR;
2237         /* Call the policy handler. */
2238         len = head->read(head);
2239         if (len < 0)
2240                 goto out;
2241         /* Write to buffer. */
2242         len = head->read_avail;
2243         if (len > buffer_len)
2244                 len = buffer_len;
2245         if (!len)
2246                 goto out;
2247         /* head->read_buf changes by some functions. */
2248         cp = head->read_buf;
2249         if (copy_to_user(buffer, cp, len)) {
2250                 len = -EFAULT;
2251                 goto out;
2252         }
2253         head->read_avail -= len;
2254         memmove(cp, cp + len, head->read_avail);
2255  out:
2256         mutex_unlock(&head->io_sem);
2257         return len;
2258 }
2259
2260 /**
2261  * tomoyo_write_control - write() for /sys/kernel/security/tomoyo/ interface.
2262  *
2263  * @file:       Pointer to "struct file".
2264  * @buffer:     Pointer to buffer to read from.
2265  * @buffer_len: Size of @buffer.
2266  *
2267  * Returns @buffer_len on success, negative value otherwise.
2268  *
2269  * Caller holds tomoyo_read_lock().
2270  */
2271 static int tomoyo_write_control(struct file *file, const char __user *buffer,
2272                                 const int buffer_len)
2273 {
2274         struct tomoyo_io_buffer *head = file->private_data;
2275         int error = buffer_len;
2276         int avail_len = buffer_len;
2277         char *cp0 = head->write_buf;
2278
2279         if (!head->write)
2280                 return -ENOSYS;
2281         if (!access_ok(VERIFY_READ, buffer, buffer_len))
2282                 return -EFAULT;
2283         /* Don't allow updating policies by non manager programs. */
2284         if (head->write != tomoyo_write_pid &&
2285             head->write != tomoyo_write_domain_policy &&
2286             !tomoyo_is_policy_manager())
2287                 return -EPERM;
2288         if (mutex_lock_interruptible(&head->io_sem))
2289                 return -EINTR;
2290         /* Read a line and dispatch it to the policy handler. */
2291         while (avail_len > 0) {
2292                 char c;
2293                 if (head->write_avail >= head->writebuf_size - 1) {
2294                         error = -ENOMEM;
2295                         break;
2296                 } else if (get_user(c, buffer)) {
2297                         error = -EFAULT;
2298                         break;
2299                 }
2300                 buffer++;
2301                 avail_len--;
2302                 cp0[head->write_avail++] = c;
2303                 if (c != '\n')
2304                         continue;
2305                 cp0[head->write_avail - 1] = '\0';
2306                 head->write_avail = 0;
2307                 tomoyo_normalize_line(cp0);
2308                 head->write(head);
2309         }
2310         mutex_unlock(&head->io_sem);
2311         return error;
2312 }
2313
2314 /**
2315  * tomoyo_close_control - close() for /sys/kernel/security/tomoyo/ interface.
2316  *
2317  * @file: Pointer to "struct file".
2318  *
2319  * Releases memory and returns 0.
2320  *
2321  * Caller looses tomoyo_read_lock().
2322  */
2323 static int tomoyo_close_control(struct file *file)
2324 {
2325         struct tomoyo_io_buffer *head = file->private_data;
2326         const bool is_write = !!head->write_buf;
2327
2328         tomoyo_read_unlock(head->reader_idx);
2329         /* Release memory used for policy I/O. */
2330         kfree(head->read_buf);
2331         head->read_buf = NULL;
2332         kfree(head->write_buf);
2333         head->write_buf = NULL;
2334         kfree(head);
2335         head = NULL;
2336         file->private_data = NULL;
2337         if (is_write)
2338                 tomoyo_run_gc();
2339         return 0;
2340 }
2341
2342 /**
2343  * tomoyo_open - open() for /sys/kernel/security/tomoyo/ interface.
2344  *
2345  * @inode: Pointer to "struct inode".
2346  * @file:  Pointer to "struct file".
2347  *
2348  * Returns 0 on success, negative value otherwise.
2349  */
2350 static int tomoyo_open(struct inode *inode, struct file *file)
2351 {
2352         const int key = ((u8 *) file->f_path.dentry->d_inode->i_private)
2353                 - ((u8 *) NULL);
2354         return tomoyo_open_control(key, file);
2355 }
2356
2357 /**
2358  * tomoyo_release - close() for /sys/kernel/security/tomoyo/ interface.
2359  *
2360  * @inode: Pointer to "struct inode".
2361  * @file:  Pointer to "struct file".
2362  *
2363  * Returns 0 on success, negative value otherwise.
2364  */
2365 static int tomoyo_release(struct inode *inode, struct file *file)
2366 {
2367         return tomoyo_close_control(file);
2368 }
2369
2370 /**
2371  * tomoyo_read - read() for /sys/kernel/security/tomoyo/ interface.
2372  *
2373  * @file:  Pointer to "struct file".
2374  * @buf:   Pointer to buffer.
2375  * @count: Size of @buf.
2376  * @ppos:  Unused.
2377  *
2378  * Returns bytes read on success, negative value otherwise.
2379  */
2380 static ssize_t tomoyo_read(struct file *file, char __user *buf, size_t count,
2381                            loff_t *ppos)
2382 {
2383         return tomoyo_read_control(file, buf, count);
2384 }
2385
2386 /**
2387  * tomoyo_write - write() for /sys/kernel/security/tomoyo/ interface.
2388  *
2389  * @file:  Pointer to "struct file".
2390  * @buf:   Pointer to buffer.
2391  * @count: Size of @buf.
2392  * @ppos:  Unused.
2393  *
2394  * Returns @count on success, negative value otherwise.
2395  */
2396 static ssize_t tomoyo_write(struct file *file, const char __user *buf,
2397                             size_t count, loff_t *ppos)
2398 {
2399         return tomoyo_write_control(file, buf, count);
2400 }
2401
2402 /*
2403  * tomoyo_operations is a "struct file_operations" which is used for handling
2404  * /sys/kernel/security/tomoyo/ interface.
2405  *
2406  * Some files under /sys/kernel/security/tomoyo/ directory accept open(O_RDWR).
2407  * See tomoyo_io_buffer for internals.
2408  */
2409 static const struct file_operations tomoyo_operations = {
2410         .open    = tomoyo_open,
2411         .release = tomoyo_release,
2412         .read    = tomoyo_read,
2413         .write   = tomoyo_write,
2414 };
2415
2416 /**
2417  * tomoyo_create_entry - Create interface files under /sys/kernel/security/tomoyo/ directory.
2418  *
2419  * @name:   The name of the interface file.
2420  * @mode:   The permission of the interface file.
2421  * @parent: The parent directory.
2422  * @key:    Type of interface.
2423  *
2424  * Returns nothing.
2425  */
2426 static void __init tomoyo_create_entry(const char *name, const mode_t mode,
2427                                        struct dentry *parent, const u8 key)
2428 {
2429         securityfs_create_file(name, mode, parent, ((u8 *) NULL) + key,
2430                                &tomoyo_operations);
2431 }
2432
2433 /**
2434  * tomoyo_initerface_init - Initialize /sys/kernel/security/tomoyo/ interface.
2435  *
2436  * Returns 0.
2437  */
2438 static int __init tomoyo_initerface_init(void)
2439 {
2440         struct dentry *tomoyo_dir;
2441
2442         /* Don't create securityfs entries unless registered. */
2443         if (current_cred()->security != &tomoyo_kernel_domain)
2444                 return 0;
2445
2446         tomoyo_dir = securityfs_create_dir("tomoyo", NULL);
2447         tomoyo_create_entry("domain_policy",    0600, tomoyo_dir,
2448                             TOMOYO_DOMAINPOLICY);
2449         tomoyo_create_entry("exception_policy", 0600, tomoyo_dir,
2450                             TOMOYO_EXCEPTIONPOLICY);
2451         tomoyo_create_entry("self_domain",      0400, tomoyo_dir,
2452                             TOMOYO_SELFDOMAIN);
2453         tomoyo_create_entry(".domain_status",   0600, tomoyo_dir,
2454                             TOMOYO_DOMAIN_STATUS);
2455         tomoyo_create_entry(".process_status",  0600, tomoyo_dir,
2456                             TOMOYO_PROCESS_STATUS);
2457         tomoyo_create_entry("meminfo",          0600, tomoyo_dir,
2458                             TOMOYO_MEMINFO);
2459         tomoyo_create_entry("profile",          0600, tomoyo_dir,
2460                             TOMOYO_PROFILE);
2461         tomoyo_create_entry("manager",          0600, tomoyo_dir,
2462                             TOMOYO_MANAGER);
2463         tomoyo_create_entry("version",          0400, tomoyo_dir,
2464                             TOMOYO_VERSION);
2465         return 0;
2466 }
2467
2468 fs_initcall(tomoyo_initerface_init);