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