]> bbs.cooldavid.org Git - net-next-2.6.git/blob - security/tomoyo/common.c
TOMOYO: Add rest of file operation restrictions.
[net-next-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 *acl;
846                         u32 perm;
847                         u8 i;
848                 case TOMOYO_TYPE_SINGLE_PATH_ACL:
849                         acl = container_of(ptr,
850                                            struct tomoyo_single_path_acl_record,
851                                            head);
852                         perm = acl->perm | (((u32) acl->perm_high) << 16);
853                         for (i = 0; i < TOMOYO_MAX_SINGLE_PATH_OPERATION; i++)
854                                 if (perm & (1 << i))
855                                         count++;
856                         if (perm & (1 << TOMOYO_TYPE_READ_WRITE_ACL))
857                                 count -= 2;
858                         break;
859                 case TOMOYO_TYPE_DOUBLE_PATH_ACL:
860                         perm = container_of(ptr,
861                                     struct tomoyo_double_path_acl_record,
862                                             head)->perm;
863                         for (i = 0; i < TOMOYO_MAX_DOUBLE_PATH_OPERATION; i++)
864                                 if (perm & (1 << i))
865                                         count++;
866                         break;
867                 }
868         }
869         up_read(&tomoyo_domain_acl_info_list_lock);
870         if (count < tomoyo_check_flags(domain, TOMOYO_MAX_ACCEPT_ENTRY))
871                 return true;
872         if (!domain->quota_warned) {
873                 domain->quota_warned = true;
874                 printk(KERN_WARNING "TOMOYO-WARNING: "
875                        "Domain '%s' has so many ACLs to hold. "
876                        "Stopped learning mode.\n", domain->domainname->name);
877         }
878         return false;
879 }
880
881 /**
882  * tomoyo_find_or_assign_new_profile - Create a new profile.
883  *
884  * @profile: Profile number to create.
885  *
886  * Returns pointer to "struct tomoyo_profile" on success, NULL otherwise.
887  */
888 static struct tomoyo_profile *tomoyo_find_or_assign_new_profile(const unsigned
889                                                                 int profile)
890 {
891         static DEFINE_MUTEX(lock);
892         struct tomoyo_profile *ptr = NULL;
893         int i;
894
895         if (profile >= TOMOYO_MAX_PROFILES)
896                 return NULL;
897         mutex_lock(&lock);
898         ptr = tomoyo_profile_ptr[profile];
899         if (ptr)
900                 goto ok;
901         ptr = tomoyo_alloc_element(sizeof(*ptr));
902         if (!ptr)
903                 goto ok;
904         for (i = 0; i < TOMOYO_MAX_CONTROL_INDEX; i++)
905                 ptr->value[i] = tomoyo_control_array[i].current_value;
906         mb(); /* Avoid out-of-order execution. */
907         tomoyo_profile_ptr[profile] = ptr;
908  ok:
909         mutex_unlock(&lock);
910         return ptr;
911 }
912
913 /**
914  * tomoyo_write_profile - Write to profile table.
915  *
916  * @head: Pointer to "struct tomoyo_io_buffer".
917  *
918  * Returns 0 on success, negative value otherwise.
919  */
920 static int tomoyo_write_profile(struct tomoyo_io_buffer *head)
921 {
922         char *data = head->write_buf;
923         unsigned int i;
924         unsigned int value;
925         char *cp;
926         struct tomoyo_profile *profile;
927         unsigned long num;
928
929         cp = strchr(data, '-');
930         if (cp)
931                 *cp = '\0';
932         if (strict_strtoul(data, 10, &num))
933                 return -EINVAL;
934         if (cp)
935                 data = cp + 1;
936         profile = tomoyo_find_or_assign_new_profile(num);
937         if (!profile)
938                 return -EINVAL;
939         cp = strchr(data, '=');
940         if (!cp)
941                 return -EINVAL;
942         *cp = '\0';
943         if (!strcmp(data, "COMMENT")) {
944                 profile->comment = tomoyo_save_name(cp + 1);
945                 return 0;
946         }
947         for (i = 0; i < TOMOYO_MAX_CONTROL_INDEX; i++) {
948                 if (strcmp(data, tomoyo_control_array[i].keyword))
949                         continue;
950                 if (sscanf(cp + 1, "%u", &value) != 1) {
951                         int j;
952                         const char **modes;
953                         switch (i) {
954                         case TOMOYO_VERBOSE:
955                                 modes = tomoyo_mode_2;
956                                 break;
957                         default:
958                                 modes = tomoyo_mode_4;
959                                 break;
960                         }
961                         for (j = 0; j < 4; j++) {
962                                 if (strcmp(cp + 1, modes[j]))
963                                         continue;
964                                 value = j;
965                                 break;
966                         }
967                         if (j == 4)
968                                 return -EINVAL;
969                 } else if (value > tomoyo_control_array[i].max_value) {
970                         value = tomoyo_control_array[i].max_value;
971                 }
972                 profile->value[i] = value;
973                 return 0;
974         }
975         return -EINVAL;
976 }
977
978 /**
979  * tomoyo_read_profile - Read from profile table.
980  *
981  * @head: Pointer to "struct tomoyo_io_buffer".
982  *
983  * Returns 0.
984  */
985 static int tomoyo_read_profile(struct tomoyo_io_buffer *head)
986 {
987         static const int total = TOMOYO_MAX_CONTROL_INDEX + 1;
988         int step;
989
990         if (head->read_eof)
991                 return 0;
992         for (step = head->read_step; step < TOMOYO_MAX_PROFILES * total;
993              step++) {
994                 const u8 index = step / total;
995                 u8 type = step % total;
996                 const struct tomoyo_profile *profile
997                         = tomoyo_profile_ptr[index];
998                 head->read_step = step;
999                 if (!profile)
1000                         continue;
1001                 if (!type) { /* Print profile' comment tag. */
1002                         if (!tomoyo_io_printf(head, "%u-COMMENT=%s\n",
1003                                               index, profile->comment ?
1004                                               profile->comment->name : ""))
1005                                 break;
1006                         continue;
1007                 }
1008                 type--;
1009                 if (type < TOMOYO_MAX_CONTROL_INDEX) {
1010                         const unsigned int value = profile->value[type];
1011                         const char **modes = NULL;
1012                         const char *keyword
1013                                 = tomoyo_control_array[type].keyword;
1014                         switch (tomoyo_control_array[type].max_value) {
1015                         case 3:
1016                                 modes = tomoyo_mode_4;
1017                                 break;
1018                         case 1:
1019                                 modes = tomoyo_mode_2;
1020                                 break;
1021                         }
1022                         if (modes) {
1023                                 if (!tomoyo_io_printf(head, "%u-%s=%s\n", index,
1024                                                       keyword, modes[value]))
1025                                         break;
1026                         } else {
1027                                 if (!tomoyo_io_printf(head, "%u-%s=%u\n", index,
1028                                                       keyword, value))
1029                                         break;
1030                         }
1031                 }
1032         }
1033         if (step == TOMOYO_MAX_PROFILES * total)
1034                 head->read_eof = true;
1035         return 0;
1036 }
1037
1038 /*
1039  * tomoyo_policy_manager_entry is a structure which is used for holding list of
1040  * domainnames or programs which are permitted to modify configuration via
1041  * /sys/kernel/security/tomoyo/ interface.
1042  * It has following fields.
1043  *
1044  *  (1) "list" which is linked to tomoyo_policy_manager_list .
1045  *  (2) "manager" is a domainname or a program's pathname.
1046  *  (3) "is_domain" is a bool which is true if "manager" is a domainname, false
1047  *      otherwise.
1048  *  (4) "is_deleted" is a bool which is true if marked as deleted, false
1049  *      otherwise.
1050  */
1051 struct tomoyo_policy_manager_entry {
1052         struct list_head list;
1053         /* A path to program or a domainname. */
1054         const struct tomoyo_path_info *manager;
1055         bool is_domain;  /* True if manager is a domainname. */
1056         bool is_deleted; /* True if this entry is deleted. */
1057 };
1058
1059 /*
1060  * tomoyo_policy_manager_list is used for holding list of domainnames or
1061  * programs which are permitted to modify configuration via
1062  * /sys/kernel/security/tomoyo/ interface.
1063  *
1064  * An entry is added by
1065  *
1066  * # echo '<kernel> /sbin/mingetty /bin/login /bin/bash' > \
1067  *                                        /sys/kernel/security/tomoyo/manager
1068  *  (if you want to specify by a domainname)
1069  *
1070  *  or
1071  *
1072  * # echo '/usr/lib/ccs/editpolicy' > /sys/kernel/security/tomoyo/manager
1073  *  (if you want to specify by a program's location)
1074  *
1075  * and is deleted by
1076  *
1077  * # echo 'delete <kernel> /sbin/mingetty /bin/login /bin/bash' > \
1078  *                                        /sys/kernel/security/tomoyo/manager
1079  *
1080  *  or
1081  *
1082  * # echo 'delete /usr/lib/ccs/editpolicy' > \
1083  *                                        /sys/kernel/security/tomoyo/manager
1084  *
1085  * and all entries are retrieved by
1086  *
1087  * # cat /sys/kernel/security/tomoyo/manager
1088  */
1089 static LIST_HEAD(tomoyo_policy_manager_list);
1090 static DECLARE_RWSEM(tomoyo_policy_manager_list_lock);
1091
1092 /**
1093  * tomoyo_update_manager_entry - Add a manager entry.
1094  *
1095  * @manager:   The path to manager or the domainnamme.
1096  * @is_delete: True if it is a delete request.
1097  *
1098  * Returns 0 on success, negative value otherwise.
1099  */
1100 static int tomoyo_update_manager_entry(const char *manager,
1101                                        const bool is_delete)
1102 {
1103         struct tomoyo_policy_manager_entry *new_entry;
1104         struct tomoyo_policy_manager_entry *ptr;
1105         const struct tomoyo_path_info *saved_manager;
1106         int error = -ENOMEM;
1107         bool is_domain = false;
1108
1109         if (tomoyo_is_domain_def(manager)) {
1110                 if (!tomoyo_is_correct_domain(manager, __func__))
1111                         return -EINVAL;
1112                 is_domain = true;
1113         } else {
1114                 if (!tomoyo_is_correct_path(manager, 1, -1, -1, __func__))
1115                         return -EINVAL;
1116         }
1117         saved_manager = tomoyo_save_name(manager);
1118         if (!saved_manager)
1119                 return -ENOMEM;
1120         down_write(&tomoyo_policy_manager_list_lock);
1121         list_for_each_entry(ptr, &tomoyo_policy_manager_list, list) {
1122                 if (ptr->manager != saved_manager)
1123                         continue;
1124                 ptr->is_deleted = is_delete;
1125                 error = 0;
1126                 goto out;
1127         }
1128         if (is_delete) {
1129                 error = -ENOENT;
1130                 goto out;
1131         }
1132         new_entry = tomoyo_alloc_element(sizeof(*new_entry));
1133         if (!new_entry)
1134                 goto out;
1135         new_entry->manager = saved_manager;
1136         new_entry->is_domain = is_domain;
1137         list_add_tail(&new_entry->list, &tomoyo_policy_manager_list);
1138         error = 0;
1139  out:
1140         up_write(&tomoyo_policy_manager_list_lock);
1141         return error;
1142 }
1143
1144 /**
1145  * tomoyo_write_manager_policy - Write manager policy.
1146  *
1147  * @head: Pointer to "struct tomoyo_io_buffer".
1148  *
1149  * Returns 0 on success, negative value otherwise.
1150  */
1151 static int tomoyo_write_manager_policy(struct tomoyo_io_buffer *head)
1152 {
1153         char *data = head->write_buf;
1154         bool is_delete = tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE);
1155
1156         if (!strcmp(data, "manage_by_non_root")) {
1157                 tomoyo_manage_by_non_root = !is_delete;
1158                 return 0;
1159         }
1160         return tomoyo_update_manager_entry(data, is_delete);
1161 }
1162
1163 /**
1164  * tomoyo_read_manager_policy - Read manager policy.
1165  *
1166  * @head: Pointer to "struct tomoyo_io_buffer".
1167  *
1168  * Returns 0.
1169  */
1170 static int tomoyo_read_manager_policy(struct tomoyo_io_buffer *head)
1171 {
1172         struct list_head *pos;
1173         bool done = true;
1174
1175         if (head->read_eof)
1176                 return 0;
1177         down_read(&tomoyo_policy_manager_list_lock);
1178         list_for_each_cookie(pos, head->read_var2,
1179                              &tomoyo_policy_manager_list) {
1180                 struct tomoyo_policy_manager_entry *ptr;
1181                 ptr = list_entry(pos, struct tomoyo_policy_manager_entry,
1182                                  list);
1183                 if (ptr->is_deleted)
1184                         continue;
1185                 done = tomoyo_io_printf(head, "%s\n", ptr->manager->name);
1186                 if (!done)
1187                         break;
1188         }
1189         up_read(&tomoyo_policy_manager_list_lock);
1190         head->read_eof = done;
1191         return 0;
1192 }
1193
1194 /**
1195  * tomoyo_is_policy_manager - Check whether the current process is a policy manager.
1196  *
1197  * Returns true if the current process is permitted to modify policy
1198  * via /sys/kernel/security/tomoyo/ interface.
1199  */
1200 static bool tomoyo_is_policy_manager(void)
1201 {
1202         struct tomoyo_policy_manager_entry *ptr;
1203         const char *exe;
1204         const struct task_struct *task = current;
1205         const struct tomoyo_path_info *domainname = tomoyo_domain()->domainname;
1206         bool found = false;
1207
1208         if (!tomoyo_policy_loaded)
1209                 return true;
1210         if (!tomoyo_manage_by_non_root && (task->cred->uid || task->cred->euid))
1211                 return false;
1212         down_read(&tomoyo_policy_manager_list_lock);
1213         list_for_each_entry(ptr, &tomoyo_policy_manager_list, list) {
1214                 if (!ptr->is_deleted && ptr->is_domain
1215                     && !tomoyo_pathcmp(domainname, ptr->manager)) {
1216                         found = true;
1217                         break;
1218                 }
1219         }
1220         up_read(&tomoyo_policy_manager_list_lock);
1221         if (found)
1222                 return true;
1223         exe = tomoyo_get_exe();
1224         if (!exe)
1225                 return false;
1226         down_read(&tomoyo_policy_manager_list_lock);
1227         list_for_each_entry(ptr, &tomoyo_policy_manager_list, list) {
1228                 if (!ptr->is_deleted && !ptr->is_domain
1229                     && !strcmp(exe, ptr->manager->name)) {
1230                         found = true;
1231                         break;
1232                 }
1233         }
1234         up_read(&tomoyo_policy_manager_list_lock);
1235         if (!found) { /* Reduce error messages. */
1236                 static pid_t last_pid;
1237                 const pid_t pid = current->pid;
1238                 if (last_pid != pid) {
1239                         printk(KERN_WARNING "%s ( %s ) is not permitted to "
1240                                "update policies.\n", domainname->name, exe);
1241                         last_pid = pid;
1242                 }
1243         }
1244         tomoyo_free(exe);
1245         return found;
1246 }
1247
1248 /**
1249  * tomoyo_is_select_one - Parse select command.
1250  *
1251  * @head: Pointer to "struct tomoyo_io_buffer".
1252  * @data: String to parse.
1253  *
1254  * Returns true on success, false otherwise.
1255  */
1256 static bool tomoyo_is_select_one(struct tomoyo_io_buffer *head,
1257                                  const char *data)
1258 {
1259         unsigned int pid;
1260         struct tomoyo_domain_info *domain = NULL;
1261
1262         if (sscanf(data, "pid=%u", &pid) == 1) {
1263                 struct task_struct *p;
1264                 read_lock(&tasklist_lock);
1265                 p = find_task_by_vpid(pid);
1266                 if (p)
1267                         domain = tomoyo_real_domain(p);
1268                 read_unlock(&tasklist_lock);
1269         } else if (!strncmp(data, "domain=", 7)) {
1270                 if (tomoyo_is_domain_def(data + 7)) {
1271                         down_read(&tomoyo_domain_list_lock);
1272                         domain = tomoyo_find_domain(data + 7);
1273                         up_read(&tomoyo_domain_list_lock);
1274                 }
1275         } else
1276                 return false;
1277         head->write_var1 = domain;
1278         /* Accessing read_buf is safe because head->io_sem is held. */
1279         if (!head->read_buf)
1280                 return true; /* Do nothing if open(O_WRONLY). */
1281         head->read_avail = 0;
1282         tomoyo_io_printf(head, "# select %s\n", data);
1283         head->read_single_domain = true;
1284         head->read_eof = !domain;
1285         if (domain) {
1286                 struct tomoyo_domain_info *d;
1287                 head->read_var1 = NULL;
1288                 down_read(&tomoyo_domain_list_lock);
1289                 list_for_each_entry(d, &tomoyo_domain_list, list) {
1290                         if (d == domain)
1291                                 break;
1292                         head->read_var1 = &d->list;
1293                 }
1294                 up_read(&tomoyo_domain_list_lock);
1295                 head->read_var2 = NULL;
1296                 head->read_bit = 0;
1297                 head->read_step = 0;
1298                 if (domain->is_deleted)
1299                         tomoyo_io_printf(head, "# This is a deleted domain.\n");
1300         }
1301         return true;
1302 }
1303
1304 /**
1305  * tomoyo_delete_domain - Delete a domain.
1306  *
1307  * @domainname: The name of domain.
1308  *
1309  * Returns 0.
1310  */
1311 static int tomoyo_delete_domain(char *domainname)
1312 {
1313         struct tomoyo_domain_info *domain;
1314         struct tomoyo_path_info name;
1315
1316         name.name = domainname;
1317         tomoyo_fill_path_info(&name);
1318         down_write(&tomoyo_domain_list_lock);
1319         /* Is there an active domain? */
1320         list_for_each_entry(domain, &tomoyo_domain_list, list) {
1321                 /* Never delete tomoyo_kernel_domain */
1322                 if (domain == &tomoyo_kernel_domain)
1323                         continue;
1324                 if (domain->is_deleted ||
1325                     tomoyo_pathcmp(domain->domainname, &name))
1326                         continue;
1327                 domain->is_deleted = true;
1328                 break;
1329         }
1330         up_write(&tomoyo_domain_list_lock);
1331         return 0;
1332 }
1333
1334 /**
1335  * tomoyo_write_domain_policy - Write domain policy.
1336  *
1337  * @head: Pointer to "struct tomoyo_io_buffer".
1338  *
1339  * Returns 0 on success, negative value otherwise.
1340  */
1341 static int tomoyo_write_domain_policy(struct tomoyo_io_buffer *head)
1342 {
1343         char *data = head->write_buf;
1344         struct tomoyo_domain_info *domain = head->write_var1;
1345         bool is_delete = false;
1346         bool is_select = false;
1347         unsigned int profile;
1348
1349         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE))
1350                 is_delete = true;
1351         else if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_SELECT))
1352                 is_select = true;
1353         if (is_select && tomoyo_is_select_one(head, data))
1354                 return 0;
1355         /* Don't allow updating policies by non manager programs. */
1356         if (!tomoyo_is_policy_manager())
1357                 return -EPERM;
1358         if (tomoyo_is_domain_def(data)) {
1359                 domain = NULL;
1360                 if (is_delete)
1361                         tomoyo_delete_domain(data);
1362                 else if (is_select) {
1363                         down_read(&tomoyo_domain_list_lock);
1364                         domain = tomoyo_find_domain(data);
1365                         up_read(&tomoyo_domain_list_lock);
1366                 } else
1367                         domain = tomoyo_find_or_assign_new_domain(data, 0);
1368                 head->write_var1 = domain;
1369                 return 0;
1370         }
1371         if (!domain)
1372                 return -EINVAL;
1373
1374         if (sscanf(data, TOMOYO_KEYWORD_USE_PROFILE "%u", &profile) == 1
1375             && profile < TOMOYO_MAX_PROFILES) {
1376                 if (tomoyo_profile_ptr[profile] || !tomoyo_policy_loaded)
1377                         domain->profile = (u8) profile;
1378                 return 0;
1379         }
1380         if (!strcmp(data, TOMOYO_KEYWORD_IGNORE_GLOBAL_ALLOW_READ)) {
1381                 tomoyo_set_domain_flag(domain, is_delete,
1382                                TOMOYO_DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_READ);
1383                 return 0;
1384         }
1385         return tomoyo_write_file_policy(data, domain, is_delete);
1386 }
1387
1388 /**
1389  * tomoyo_print_single_path_acl - Print a single path ACL entry.
1390  *
1391  * @head: Pointer to "struct tomoyo_io_buffer".
1392  * @ptr:  Pointer to "struct tomoyo_single_path_acl_record".
1393  *
1394  * Returns true on success, false otherwise.
1395  */
1396 static bool tomoyo_print_single_path_acl(struct tomoyo_io_buffer *head,
1397                                          struct tomoyo_single_path_acl_record *
1398                                          ptr)
1399 {
1400         int pos;
1401         u8 bit;
1402         const char *atmark = "";
1403         const char *filename;
1404         const u32 perm = ptr->perm | (((u32) ptr->perm_high) << 16);
1405
1406         filename = ptr->filename->name;
1407         for (bit = head->read_bit; bit < TOMOYO_MAX_SINGLE_PATH_OPERATION;
1408              bit++) {
1409                 const char *msg;
1410                 if (!(perm & (1 << bit)))
1411                         continue;
1412                 /* Print "read/write" instead of "read" and "write". */
1413                 if ((bit == TOMOYO_TYPE_READ_ACL ||
1414                      bit == TOMOYO_TYPE_WRITE_ACL)
1415                     && (perm & (1 << TOMOYO_TYPE_READ_WRITE_ACL)))
1416                         continue;
1417                 msg = tomoyo_sp2keyword(bit);
1418                 pos = head->read_avail;
1419                 if (!tomoyo_io_printf(head, "allow_%s %s%s\n", msg,
1420                                       atmark, filename))
1421                         goto out;
1422         }
1423         head->read_bit = 0;
1424         return true;
1425  out:
1426         head->read_bit = bit;
1427         head->read_avail = pos;
1428         return false;
1429 }
1430
1431 /**
1432  * tomoyo_print_double_path_acl - Print a double path ACL entry.
1433  *
1434  * @head: Pointer to "struct tomoyo_io_buffer".
1435  * @ptr:  Pointer to "struct tomoyo_double_path_acl_record".
1436  *
1437  * Returns true on success, false otherwise.
1438  */
1439 static bool tomoyo_print_double_path_acl(struct tomoyo_io_buffer *head,
1440                                          struct tomoyo_double_path_acl_record *
1441                                          ptr)
1442 {
1443         int pos;
1444         const char *atmark1 = "";
1445         const char *atmark2 = "";
1446         const char *filename1;
1447         const char *filename2;
1448         const u8 perm = ptr->perm;
1449         u8 bit;
1450
1451         filename1 = ptr->filename1->name;
1452         filename2 = ptr->filename2->name;
1453         for (bit = head->read_bit; bit < TOMOYO_MAX_DOUBLE_PATH_OPERATION;
1454              bit++) {
1455                 const char *msg;
1456                 if (!(perm & (1 << bit)))
1457                         continue;
1458                 msg = tomoyo_dp2keyword(bit);
1459                 pos = head->read_avail;
1460                 if (!tomoyo_io_printf(head, "allow_%s %s%s %s%s\n", msg,
1461                                       atmark1, filename1, atmark2, filename2))
1462                         goto out;
1463         }
1464         head->read_bit = 0;
1465         return true;
1466  out:
1467         head->read_bit = bit;
1468         head->read_avail = pos;
1469         return false;
1470 }
1471
1472 /**
1473  * tomoyo_print_entry - Print an ACL entry.
1474  *
1475  * @head: Pointer to "struct tomoyo_io_buffer".
1476  * @ptr:  Pointer to an ACL entry.
1477  *
1478  * Returns true on success, false otherwise.
1479  */
1480 static bool tomoyo_print_entry(struct tomoyo_io_buffer *head,
1481                                struct tomoyo_acl_info *ptr)
1482 {
1483         const u8 acl_type = tomoyo_acl_type2(ptr);
1484
1485         if (acl_type & TOMOYO_ACL_DELETED)
1486                 return true;
1487         if (acl_type == TOMOYO_TYPE_SINGLE_PATH_ACL) {
1488                 struct tomoyo_single_path_acl_record *acl
1489                         = container_of(ptr,
1490                                        struct tomoyo_single_path_acl_record,
1491                                        head);
1492                 return tomoyo_print_single_path_acl(head, acl);
1493         }
1494         if (acl_type == TOMOYO_TYPE_DOUBLE_PATH_ACL) {
1495                 struct tomoyo_double_path_acl_record *acl
1496                         = container_of(ptr,
1497                                        struct tomoyo_double_path_acl_record,
1498                                        head);
1499                 return tomoyo_print_double_path_acl(head, acl);
1500         }
1501         BUG(); /* This must not happen. */
1502         return false;
1503 }
1504
1505 /**
1506  * tomoyo_read_domain_policy - Read domain policy.
1507  *
1508  * @head: Pointer to "struct tomoyo_io_buffer".
1509  *
1510  * Returns 0.
1511  */
1512 static int tomoyo_read_domain_policy(struct tomoyo_io_buffer *head)
1513 {
1514         struct list_head *dpos;
1515         struct list_head *apos;
1516         bool done = true;
1517
1518         if (head->read_eof)
1519                 return 0;
1520         if (head->read_step == 0)
1521                 head->read_step = 1;
1522         down_read(&tomoyo_domain_list_lock);
1523         list_for_each_cookie(dpos, head->read_var1, &tomoyo_domain_list) {
1524                 struct tomoyo_domain_info *domain;
1525                 const char *quota_exceeded = "";
1526                 const char *transition_failed = "";
1527                 const char *ignore_global_allow_read = "";
1528                 domain = list_entry(dpos, struct tomoyo_domain_info, list);
1529                 if (head->read_step != 1)
1530                         goto acl_loop;
1531                 if (domain->is_deleted && !head->read_single_domain)
1532                         continue;
1533                 /* Print domainname and flags. */
1534                 if (domain->quota_warned)
1535                         quota_exceeded = "quota_exceeded\n";
1536                 if (domain->flags & TOMOYO_DOMAIN_FLAGS_TRANSITION_FAILED)
1537                         transition_failed = "transition_failed\n";
1538                 if (domain->flags &
1539                     TOMOYO_DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_READ)
1540                         ignore_global_allow_read
1541                                 = TOMOYO_KEYWORD_IGNORE_GLOBAL_ALLOW_READ "\n";
1542                 done = tomoyo_io_printf(head, "%s\n" TOMOYO_KEYWORD_USE_PROFILE
1543                                         "%u\n%s%s%s\n",
1544                                         domain->domainname->name,
1545                                         domain->profile, quota_exceeded,
1546                                         transition_failed,
1547                                         ignore_global_allow_read);
1548                 if (!done)
1549                         break;
1550                 head->read_step = 2;
1551 acl_loop:
1552                 if (head->read_step == 3)
1553                         goto tail_mark;
1554                 /* Print ACL entries in the domain. */
1555                 down_read(&tomoyo_domain_acl_info_list_lock);
1556                 list_for_each_cookie(apos, head->read_var2,
1557                                      &domain->acl_info_list) {
1558                         struct tomoyo_acl_info *ptr
1559                                 = list_entry(apos, struct tomoyo_acl_info,
1560                                              list);
1561                         done = tomoyo_print_entry(head, ptr);
1562                         if (!done)
1563                                 break;
1564                 }
1565                 up_read(&tomoyo_domain_acl_info_list_lock);
1566                 if (!done)
1567                         break;
1568                 head->read_step = 3;
1569 tail_mark:
1570                 done = tomoyo_io_printf(head, "\n");
1571                 if (!done)
1572                         break;
1573                 head->read_step = 1;
1574                 if (head->read_single_domain)
1575                         break;
1576         }
1577         up_read(&tomoyo_domain_list_lock);
1578         head->read_eof = done;
1579         return 0;
1580 }
1581
1582 /**
1583  * tomoyo_write_domain_profile - Assign profile for specified domain.
1584  *
1585  * @head: Pointer to "struct tomoyo_io_buffer".
1586  *
1587  * Returns 0 on success, -EINVAL otherwise.
1588  *
1589  * This is equivalent to doing
1590  *
1591  *     ( echo "select " $domainname; echo "use_profile " $profile ) |
1592  *     /usr/lib/ccs/loadpolicy -d
1593  */
1594 static int tomoyo_write_domain_profile(struct tomoyo_io_buffer *head)
1595 {
1596         char *data = head->write_buf;
1597         char *cp = strchr(data, ' ');
1598         struct tomoyo_domain_info *domain;
1599         unsigned long profile;
1600
1601         if (!cp)
1602                 return -EINVAL;
1603         *cp = '\0';
1604         down_read(&tomoyo_domain_list_lock);
1605         domain = tomoyo_find_domain(cp + 1);
1606         up_read(&tomoyo_domain_list_lock);
1607         if (strict_strtoul(data, 10, &profile))
1608                 return -EINVAL;
1609         if (domain && profile < TOMOYO_MAX_PROFILES
1610             && (tomoyo_profile_ptr[profile] || !tomoyo_policy_loaded))
1611                 domain->profile = (u8) profile;
1612         return 0;
1613 }
1614
1615 /**
1616  * tomoyo_read_domain_profile - Read only domainname and profile.
1617  *
1618  * @head: Pointer to "struct tomoyo_io_buffer".
1619  *
1620  * Returns list of profile number and domainname pairs.
1621  *
1622  * This is equivalent to doing
1623  *
1624  *     grep -A 1 '^<kernel>' /sys/kernel/security/tomoyo/domain_policy |
1625  *     awk ' { if ( domainname == "" ) { if ( $1 == "<kernel>" )
1626  *     domainname = $0; } else if ( $1 == "use_profile" ) {
1627  *     print $2 " " domainname; domainname = ""; } } ; '
1628  */
1629 static int tomoyo_read_domain_profile(struct tomoyo_io_buffer *head)
1630 {
1631         struct list_head *pos;
1632         bool done = true;
1633
1634         if (head->read_eof)
1635                 return 0;
1636         down_read(&tomoyo_domain_list_lock);
1637         list_for_each_cookie(pos, head->read_var1, &tomoyo_domain_list) {
1638                 struct tomoyo_domain_info *domain;
1639                 domain = list_entry(pos, struct tomoyo_domain_info, list);
1640                 if (domain->is_deleted)
1641                         continue;
1642                 done = tomoyo_io_printf(head, "%u %s\n", domain->profile,
1643                                         domain->domainname->name);
1644                 if (!done)
1645                         break;
1646         }
1647         up_read(&tomoyo_domain_list_lock);
1648         head->read_eof = done;
1649         return 0;
1650 }
1651
1652 /**
1653  * tomoyo_write_pid: Specify PID to obtain domainname.
1654  *
1655  * @head: Pointer to "struct tomoyo_io_buffer".
1656  *
1657  * Returns 0.
1658  */
1659 static int tomoyo_write_pid(struct tomoyo_io_buffer *head)
1660 {
1661         unsigned long pid;
1662         /* No error check. */
1663         strict_strtoul(head->write_buf, 10, &pid);
1664         head->read_step = (int) pid;
1665         head->read_eof = false;
1666         return 0;
1667 }
1668
1669 /**
1670  * tomoyo_read_pid - Get domainname of the specified PID.
1671  *
1672  * @head: Pointer to "struct tomoyo_io_buffer".
1673  *
1674  * Returns the domainname which the specified PID is in on success,
1675  * empty string otherwise.
1676  * The PID is specified by tomoyo_write_pid() so that the user can obtain
1677  * using read()/write() interface rather than sysctl() interface.
1678  */
1679 static int tomoyo_read_pid(struct tomoyo_io_buffer *head)
1680 {
1681         if (head->read_avail == 0 && !head->read_eof) {
1682                 const int pid = head->read_step;
1683                 struct task_struct *p;
1684                 struct tomoyo_domain_info *domain = NULL;
1685                 read_lock(&tasklist_lock);
1686                 p = find_task_by_vpid(pid);
1687                 if (p)
1688                         domain = tomoyo_real_domain(p);
1689                 read_unlock(&tasklist_lock);
1690                 if (domain)
1691                         tomoyo_io_printf(head, "%d %u %s", pid, domain->profile,
1692                                          domain->domainname->name);
1693                 head->read_eof = true;
1694         }
1695         return 0;
1696 }
1697
1698 /**
1699  * tomoyo_write_exception_policy - Write exception policy.
1700  *
1701  * @head: Pointer to "struct tomoyo_io_buffer".
1702  *
1703  * Returns 0 on success, negative value otherwise.
1704  */
1705 static int tomoyo_write_exception_policy(struct tomoyo_io_buffer *head)
1706 {
1707         char *data = head->write_buf;
1708         bool is_delete = tomoyo_str_starts(&data, TOMOYO_KEYWORD_DELETE);
1709
1710         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_KEEP_DOMAIN))
1711                 return tomoyo_write_domain_keeper_policy(data, false,
1712                                                          is_delete);
1713         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_NO_KEEP_DOMAIN))
1714                 return tomoyo_write_domain_keeper_policy(data, true, is_delete);
1715         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_INITIALIZE_DOMAIN))
1716                 return tomoyo_write_domain_initializer_policy(data, false,
1717                                                               is_delete);
1718         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_NO_INITIALIZE_DOMAIN))
1719                 return tomoyo_write_domain_initializer_policy(data, true,
1720                                                               is_delete);
1721         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALIAS))
1722                 return tomoyo_write_alias_policy(data, is_delete);
1723         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_ALLOW_READ))
1724                 return tomoyo_write_globally_readable_policy(data, is_delete);
1725         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_FILE_PATTERN))
1726                 return tomoyo_write_pattern_policy(data, is_delete);
1727         if (tomoyo_str_starts(&data, TOMOYO_KEYWORD_DENY_REWRITE))
1728                 return tomoyo_write_no_rewrite_policy(data, is_delete);
1729         return -EINVAL;
1730 }
1731
1732 /**
1733  * tomoyo_read_exception_policy - Read exception policy.
1734  *
1735  * @head: Pointer to "struct tomoyo_io_buffer".
1736  *
1737  * Returns 0 on success, -EINVAL otherwise.
1738  */
1739 static int tomoyo_read_exception_policy(struct tomoyo_io_buffer *head)
1740 {
1741         if (!head->read_eof) {
1742                 switch (head->read_step) {
1743                 case 0:
1744                         head->read_var2 = NULL;
1745                         head->read_step = 1;
1746                 case 1:
1747                         if (!tomoyo_read_domain_keeper_policy(head))
1748                                 break;
1749                         head->read_var2 = NULL;
1750                         head->read_step = 2;
1751                 case 2:
1752                         if (!tomoyo_read_globally_readable_policy(head))
1753                                 break;
1754                         head->read_var2 = NULL;
1755                         head->read_step = 3;
1756                 case 3:
1757                         head->read_var2 = NULL;
1758                         head->read_step = 4;
1759                 case 4:
1760                         if (!tomoyo_read_domain_initializer_policy(head))
1761                                 break;
1762                         head->read_var2 = NULL;
1763                         head->read_step = 5;
1764                 case 5:
1765                         if (!tomoyo_read_alias_policy(head))
1766                                 break;
1767                         head->read_var2 = NULL;
1768                         head->read_step = 6;
1769                 case 6:
1770                         head->read_var2 = NULL;
1771                         head->read_step = 7;
1772                 case 7:
1773                         if (!tomoyo_read_file_pattern(head))
1774                                 break;
1775                         head->read_var2 = NULL;
1776                         head->read_step = 8;
1777                 case 8:
1778                         if (!tomoyo_read_no_rewrite_policy(head))
1779                                 break;
1780                         head->read_var2 = NULL;
1781                         head->read_step = 9;
1782                 case 9:
1783                         head->read_eof = true;
1784                         break;
1785                 default:
1786                         return -EINVAL;
1787                 }
1788         }
1789         return 0;
1790 }
1791
1792 /* path to policy loader */
1793 static const char *tomoyo_loader = "/sbin/tomoyo-init";
1794
1795 /**
1796  * tomoyo_policy_loader_exists - Check whether /sbin/tomoyo-init exists.
1797  *
1798  * Returns true if /sbin/tomoyo-init exists, false otherwise.
1799  */
1800 static bool tomoyo_policy_loader_exists(void)
1801 {
1802         /*
1803          * Don't activate MAC if the policy loader doesn't exist.
1804          * If the initrd includes /sbin/init but real-root-dev has not
1805          * mounted on / yet, activating MAC will block the system since
1806          * policies are not loaded yet.
1807          * Thus, let do_execve() call this function everytime.
1808          */
1809         struct path path;
1810
1811         if (kern_path(tomoyo_loader, LOOKUP_FOLLOW, &path)) {
1812                 printk(KERN_INFO "Not activating Mandatory Access Control now "
1813                        "since %s doesn't exist.\n", tomoyo_loader);
1814                 return false;
1815         }
1816         path_put(&path);
1817         return true;
1818 }
1819
1820 /**
1821  * tomoyo_load_policy - Run external policy loader to load policy.
1822  *
1823  * @filename: The program about to start.
1824  *
1825  * This function checks whether @filename is /sbin/init , and if so
1826  * invoke /sbin/tomoyo-init and wait for the termination of /sbin/tomoyo-init
1827  * and then continues invocation of /sbin/init.
1828  * /sbin/tomoyo-init reads policy files in /etc/tomoyo/ directory and
1829  * writes to /sys/kernel/security/tomoyo/ interfaces.
1830  *
1831  * Returns nothing.
1832  */
1833 void tomoyo_load_policy(const char *filename)
1834 {
1835         char *argv[2];
1836         char *envp[3];
1837
1838         if (tomoyo_policy_loaded)
1839                 return;
1840         /*
1841          * Check filename is /sbin/init or /sbin/tomoyo-start.
1842          * /sbin/tomoyo-start is a dummy filename in case where /sbin/init can't
1843          * be passed.
1844          * You can create /sbin/tomoyo-start by
1845          * "ln -s /bin/true /sbin/tomoyo-start".
1846          */
1847         if (strcmp(filename, "/sbin/init") &&
1848             strcmp(filename, "/sbin/tomoyo-start"))
1849                 return;
1850         if (!tomoyo_policy_loader_exists())
1851                 return;
1852
1853         printk(KERN_INFO "Calling %s to load policy. Please wait.\n",
1854                tomoyo_loader);
1855         argv[0] = (char *) tomoyo_loader;
1856         argv[1] = NULL;
1857         envp[0] = "HOME=/";
1858         envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
1859         envp[2] = NULL;
1860         call_usermodehelper(argv[0], argv, envp, 1);
1861
1862         printk(KERN_INFO "TOMOYO: 2.2.0   2009/04/01\n");
1863         printk(KERN_INFO "Mandatory Access Control activated.\n");
1864         tomoyo_policy_loaded = true;
1865         { /* Check all profiles currently assigned to domains are defined. */
1866                 struct tomoyo_domain_info *domain;
1867                 down_read(&tomoyo_domain_list_lock);
1868                 list_for_each_entry(domain, &tomoyo_domain_list, list) {
1869                         const u8 profile = domain->profile;
1870                         if (tomoyo_profile_ptr[profile])
1871                                 continue;
1872                         panic("Profile %u (used by '%s') not defined.\n",
1873                               profile, domain->domainname->name);
1874                 }
1875                 up_read(&tomoyo_domain_list_lock);
1876         }
1877 }
1878
1879 /**
1880  * tomoyo_read_version: Get version.
1881  *
1882  * @head: Pointer to "struct tomoyo_io_buffer".
1883  *
1884  * Returns version information.
1885  */
1886 static int tomoyo_read_version(struct tomoyo_io_buffer *head)
1887 {
1888         if (!head->read_eof) {
1889                 tomoyo_io_printf(head, "2.2.0");
1890                 head->read_eof = true;
1891         }
1892         return 0;
1893 }
1894
1895 /**
1896  * tomoyo_read_self_domain - Get the current process's domainname.
1897  *
1898  * @head: Pointer to "struct tomoyo_io_buffer".
1899  *
1900  * Returns the current process's domainname.
1901  */
1902 static int tomoyo_read_self_domain(struct tomoyo_io_buffer *head)
1903 {
1904         if (!head->read_eof) {
1905                 /*
1906                  * tomoyo_domain()->domainname != NULL
1907                  * because every process belongs to a domain and
1908                  * the domain's name cannot be NULL.
1909                  */
1910                 tomoyo_io_printf(head, "%s", tomoyo_domain()->domainname->name);
1911                 head->read_eof = true;
1912         }
1913         return 0;
1914 }
1915
1916 /**
1917  * tomoyo_open_control - open() for /sys/kernel/security/tomoyo/ interface.
1918  *
1919  * @type: Type of interface.
1920  * @file: Pointer to "struct file".
1921  *
1922  * Associates policy handler and returns 0 on success, -ENOMEM otherwise.
1923  */
1924 static int tomoyo_open_control(const u8 type, struct file *file)
1925 {
1926         struct tomoyo_io_buffer *head = tomoyo_alloc(sizeof(*head));
1927
1928         if (!head)
1929                 return -ENOMEM;
1930         mutex_init(&head->io_sem);
1931         switch (type) {
1932         case TOMOYO_DOMAINPOLICY:
1933                 /* /sys/kernel/security/tomoyo/domain_policy */
1934                 head->write = tomoyo_write_domain_policy;
1935                 head->read = tomoyo_read_domain_policy;
1936                 break;
1937         case TOMOYO_EXCEPTIONPOLICY:
1938                 /* /sys/kernel/security/tomoyo/exception_policy */
1939                 head->write = tomoyo_write_exception_policy;
1940                 head->read = tomoyo_read_exception_policy;
1941                 break;
1942         case TOMOYO_SELFDOMAIN:
1943                 /* /sys/kernel/security/tomoyo/self_domain */
1944                 head->read = tomoyo_read_self_domain;
1945                 break;
1946         case TOMOYO_DOMAIN_STATUS:
1947                 /* /sys/kernel/security/tomoyo/.domain_status */
1948                 head->write = tomoyo_write_domain_profile;
1949                 head->read = tomoyo_read_domain_profile;
1950                 break;
1951         case TOMOYO_PROCESS_STATUS:
1952                 /* /sys/kernel/security/tomoyo/.process_status */
1953                 head->write = tomoyo_write_pid;
1954                 head->read = tomoyo_read_pid;
1955                 break;
1956         case TOMOYO_VERSION:
1957                 /* /sys/kernel/security/tomoyo/version */
1958                 head->read = tomoyo_read_version;
1959                 head->readbuf_size = 128;
1960                 break;
1961         case TOMOYO_MEMINFO:
1962                 /* /sys/kernel/security/tomoyo/meminfo */
1963                 head->write = tomoyo_write_memory_quota;
1964                 head->read = tomoyo_read_memory_counter;
1965                 head->readbuf_size = 512;
1966                 break;
1967         case TOMOYO_PROFILE:
1968                 /* /sys/kernel/security/tomoyo/profile */
1969                 head->write = tomoyo_write_profile;
1970                 head->read = tomoyo_read_profile;
1971                 break;
1972         case TOMOYO_MANAGER:
1973                 /* /sys/kernel/security/tomoyo/manager */
1974                 head->write = tomoyo_write_manager_policy;
1975                 head->read = tomoyo_read_manager_policy;
1976                 break;
1977         }
1978         if (!(file->f_mode & FMODE_READ)) {
1979                 /*
1980                  * No need to allocate read_buf since it is not opened
1981                  * for reading.
1982                  */
1983                 head->read = NULL;
1984         } else {
1985                 if (!head->readbuf_size)
1986                         head->readbuf_size = 4096 * 2;
1987                 head->read_buf = tomoyo_alloc(head->readbuf_size);
1988                 if (!head->read_buf) {
1989                         tomoyo_free(head);
1990                         return -ENOMEM;
1991                 }
1992         }
1993         if (!(file->f_mode & FMODE_WRITE)) {
1994                 /*
1995                  * No need to allocate write_buf since it is not opened
1996                  * for writing.
1997                  */
1998                 head->write = NULL;
1999         } else if (head->write) {
2000                 head->writebuf_size = 4096 * 2;
2001                 head->write_buf = tomoyo_alloc(head->writebuf_size);
2002                 if (!head->write_buf) {
2003                         tomoyo_free(head->read_buf);
2004                         tomoyo_free(head);
2005                         return -ENOMEM;
2006                 }
2007         }
2008         file->private_data = head;
2009         /*
2010          * Call the handler now if the file is
2011          * /sys/kernel/security/tomoyo/self_domain
2012          * so that the user can use
2013          * cat < /sys/kernel/security/tomoyo/self_domain"
2014          * to know the current process's domainname.
2015          */
2016         if (type == TOMOYO_SELFDOMAIN)
2017                 tomoyo_read_control(file, NULL, 0);
2018         return 0;
2019 }
2020
2021 /**
2022  * tomoyo_read_control - read() for /sys/kernel/security/tomoyo/ interface.
2023  *
2024  * @file:       Pointer to "struct file".
2025  * @buffer:     Poiner to buffer to write to.
2026  * @buffer_len: Size of @buffer.
2027  *
2028  * Returns bytes read on success, negative value otherwise.
2029  */
2030 static int tomoyo_read_control(struct file *file, char __user *buffer,
2031                                const int buffer_len)
2032 {
2033         int len = 0;
2034         struct tomoyo_io_buffer *head = file->private_data;
2035         char *cp;
2036
2037         if (!head->read)
2038                 return -ENOSYS;
2039         if (mutex_lock_interruptible(&head->io_sem))
2040                 return -EINTR;
2041         /* Call the policy handler. */
2042         len = head->read(head);
2043         if (len < 0)
2044                 goto out;
2045         /* Write to buffer. */
2046         len = head->read_avail;
2047         if (len > buffer_len)
2048                 len = buffer_len;
2049         if (!len)
2050                 goto out;
2051         /* head->read_buf changes by some functions. */
2052         cp = head->read_buf;
2053         if (copy_to_user(buffer, cp, len)) {
2054                 len = -EFAULT;
2055                 goto out;
2056         }
2057         head->read_avail -= len;
2058         memmove(cp, cp + len, head->read_avail);
2059  out:
2060         mutex_unlock(&head->io_sem);
2061         return len;
2062 }
2063
2064 /**
2065  * tomoyo_write_control - write() for /sys/kernel/security/tomoyo/ interface.
2066  *
2067  * @file:       Pointer to "struct file".
2068  * @buffer:     Pointer to buffer to read from.
2069  * @buffer_len: Size of @buffer.
2070  *
2071  * Returns @buffer_len on success, negative value otherwise.
2072  */
2073 static int tomoyo_write_control(struct file *file, const char __user *buffer,
2074                                 const int buffer_len)
2075 {
2076         struct tomoyo_io_buffer *head = file->private_data;
2077         int error = buffer_len;
2078         int avail_len = buffer_len;
2079         char *cp0 = head->write_buf;
2080
2081         if (!head->write)
2082                 return -ENOSYS;
2083         if (!access_ok(VERIFY_READ, buffer, buffer_len))
2084                 return -EFAULT;
2085         /* Don't allow updating policies by non manager programs. */
2086         if (head->write != tomoyo_write_pid &&
2087             head->write != tomoyo_write_domain_policy &&
2088             !tomoyo_is_policy_manager())
2089                 return -EPERM;
2090         if (mutex_lock_interruptible(&head->io_sem))
2091                 return -EINTR;
2092         /* Read a line and dispatch it to the policy handler. */
2093         while (avail_len > 0) {
2094                 char c;
2095                 if (head->write_avail >= head->writebuf_size - 1) {
2096                         error = -ENOMEM;
2097                         break;
2098                 } else if (get_user(c, buffer)) {
2099                         error = -EFAULT;
2100                         break;
2101                 }
2102                 buffer++;
2103                 avail_len--;
2104                 cp0[head->write_avail++] = c;
2105                 if (c != '\n')
2106                         continue;
2107                 cp0[head->write_avail - 1] = '\0';
2108                 head->write_avail = 0;
2109                 tomoyo_normalize_line(cp0);
2110                 head->write(head);
2111         }
2112         mutex_unlock(&head->io_sem);
2113         return error;
2114 }
2115
2116 /**
2117  * tomoyo_close_control - close() for /sys/kernel/security/tomoyo/ interface.
2118  *
2119  * @file: Pointer to "struct file".
2120  *
2121  * Releases memory and returns 0.
2122  */
2123 static int tomoyo_close_control(struct file *file)
2124 {
2125         struct tomoyo_io_buffer *head = file->private_data;
2126
2127         /* Release memory used for policy I/O. */
2128         tomoyo_free(head->read_buf);
2129         head->read_buf = NULL;
2130         tomoyo_free(head->write_buf);
2131         head->write_buf = NULL;
2132         tomoyo_free(head);
2133         head = NULL;
2134         file->private_data = NULL;
2135         return 0;
2136 }
2137
2138 /**
2139  * tomoyo_alloc_acl_element - Allocate permanent memory for ACL entry.
2140  *
2141  * @acl_type:  Type of ACL entry.
2142  *
2143  * Returns pointer to the ACL entry on success, NULL otherwise.
2144  */
2145 void *tomoyo_alloc_acl_element(const u8 acl_type)
2146 {
2147         int len;
2148         struct tomoyo_acl_info *ptr;
2149
2150         switch (acl_type) {
2151         case TOMOYO_TYPE_SINGLE_PATH_ACL:
2152                 len = sizeof(struct tomoyo_single_path_acl_record);
2153                 break;
2154         case TOMOYO_TYPE_DOUBLE_PATH_ACL:
2155                 len = sizeof(struct tomoyo_double_path_acl_record);
2156                 break;
2157         default:
2158                 return NULL;
2159         }
2160         ptr = tomoyo_alloc_element(len);
2161         if (!ptr)
2162                 return NULL;
2163         ptr->type = acl_type;
2164         return ptr;
2165 }
2166
2167 /**
2168  * tomoyo_open - open() for /sys/kernel/security/tomoyo/ interface.
2169  *
2170  * @inode: Pointer to "struct inode".
2171  * @file:  Pointer to "struct file".
2172  *
2173  * Returns 0 on success, negative value otherwise.
2174  */
2175 static int tomoyo_open(struct inode *inode, struct file *file)
2176 {
2177         const int key = ((u8 *) file->f_path.dentry->d_inode->i_private)
2178                 - ((u8 *) NULL);
2179         return tomoyo_open_control(key, file);
2180 }
2181
2182 /**
2183  * tomoyo_release - close() for /sys/kernel/security/tomoyo/ interface.
2184  *
2185  * @inode: Pointer to "struct inode".
2186  * @file:  Pointer to "struct file".
2187  *
2188  * Returns 0 on success, negative value otherwise.
2189  */
2190 static int tomoyo_release(struct inode *inode, struct file *file)
2191 {
2192         return tomoyo_close_control(file);
2193 }
2194
2195 /**
2196  * tomoyo_read - read() for /sys/kernel/security/tomoyo/ interface.
2197  *
2198  * @file:  Pointer to "struct file".
2199  * @buf:   Pointer to buffer.
2200  * @count: Size of @buf.
2201  * @ppos:  Unused.
2202  *
2203  * Returns bytes read on success, negative value otherwise.
2204  */
2205 static ssize_t tomoyo_read(struct file *file, char __user *buf, size_t count,
2206                            loff_t *ppos)
2207 {
2208         return tomoyo_read_control(file, buf, count);
2209 }
2210
2211 /**
2212  * tomoyo_write - write() for /sys/kernel/security/tomoyo/ interface.
2213  *
2214  * @file:  Pointer to "struct file".
2215  * @buf:   Pointer to buffer.
2216  * @count: Size of @buf.
2217  * @ppos:  Unused.
2218  *
2219  * Returns @count on success, negative value otherwise.
2220  */
2221 static ssize_t tomoyo_write(struct file *file, const char __user *buf,
2222                             size_t count, loff_t *ppos)
2223 {
2224         return tomoyo_write_control(file, buf, count);
2225 }
2226
2227 /*
2228  * tomoyo_operations is a "struct file_operations" which is used for handling
2229  * /sys/kernel/security/tomoyo/ interface.
2230  *
2231  * Some files under /sys/kernel/security/tomoyo/ directory accept open(O_RDWR).
2232  * See tomoyo_io_buffer for internals.
2233  */
2234 static const struct file_operations tomoyo_operations = {
2235         .open    = tomoyo_open,
2236         .release = tomoyo_release,
2237         .read    = tomoyo_read,
2238         .write   = tomoyo_write,
2239 };
2240
2241 /**
2242  * tomoyo_create_entry - Create interface files under /sys/kernel/security/tomoyo/ directory.
2243  *
2244  * @name:   The name of the interface file.
2245  * @mode:   The permission of the interface file.
2246  * @parent: The parent directory.
2247  * @key:    Type of interface.
2248  *
2249  * Returns nothing.
2250  */
2251 static void __init tomoyo_create_entry(const char *name, const mode_t mode,
2252                                        struct dentry *parent, const u8 key)
2253 {
2254         securityfs_create_file(name, mode, parent, ((u8 *) NULL) + key,
2255                                &tomoyo_operations);
2256 }
2257
2258 /**
2259  * tomoyo_initerface_init - Initialize /sys/kernel/security/tomoyo/ interface.
2260  *
2261  * Returns 0.
2262  */
2263 static int __init tomoyo_initerface_init(void)
2264 {
2265         struct dentry *tomoyo_dir;
2266
2267         /* Don't create securityfs entries unless registered. */
2268         if (current_cred()->security != &tomoyo_kernel_domain)
2269                 return 0;
2270
2271         tomoyo_dir = securityfs_create_dir("tomoyo", NULL);
2272         tomoyo_create_entry("domain_policy",    0600, tomoyo_dir,
2273                             TOMOYO_DOMAINPOLICY);
2274         tomoyo_create_entry("exception_policy", 0600, tomoyo_dir,
2275                             TOMOYO_EXCEPTIONPOLICY);
2276         tomoyo_create_entry("self_domain",      0400, tomoyo_dir,
2277                             TOMOYO_SELFDOMAIN);
2278         tomoyo_create_entry(".domain_status",   0600, tomoyo_dir,
2279                             TOMOYO_DOMAIN_STATUS);
2280         tomoyo_create_entry(".process_status",  0600, tomoyo_dir,
2281                             TOMOYO_PROCESS_STATUS);
2282         tomoyo_create_entry("meminfo",          0600, tomoyo_dir,
2283                             TOMOYO_MEMINFO);
2284         tomoyo_create_entry("profile",          0600, tomoyo_dir,
2285                             TOMOYO_PROFILE);
2286         tomoyo_create_entry("manager",          0600, tomoyo_dir,
2287                             TOMOYO_MANAGER);
2288         tomoyo_create_entry("version",          0400, tomoyo_dir,
2289                             TOMOYO_VERSION);
2290         return 0;
2291 }
2292
2293 fs_initcall(tomoyo_initerface_init);