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