]> git.karo-electronics.de Git - linux-beck.git/blob - security/tomoyo/util.c
TOMOYO: Add policy namespace support.
[linux-beck.git] / security / tomoyo / util.c
1 /*
2  * security/tomoyo/util.c
3  *
4  * Utility functions for TOMOYO.
5  *
6  * Copyright (C) 2005-2010  NTT DATA CORPORATION
7  */
8
9 #include <linux/slab.h>
10 #include "common.h"
11
12 /* Lock for protecting policy. */
13 DEFINE_MUTEX(tomoyo_policy_lock);
14
15 /* Has /sbin/init started? */
16 bool tomoyo_policy_loaded;
17
18 /**
19  * tomoyo_permstr - Find permission keywords.
20  *
21  * @string: String representation for permissions in foo/bar/buz format.
22  * @keyword: Keyword to find from @string/
23  *
24  * Returns ture if @keyword was found in @string, false otherwise.
25  *
26  * This function assumes that strncmp(w1, w2, strlen(w1)) != 0 if w1 != w2.
27  */
28 bool tomoyo_permstr(const char *string, const char *keyword)
29 {
30         const char *cp = strstr(string, keyword);
31         if (cp)
32                 return cp == string || *(cp - 1) == '/';
33         return false;
34 }
35
36 /**
37  * tomoyo_read_token - Read a word from a line.
38  *
39  * @param: Pointer to "struct tomoyo_acl_param".
40  *
41  * Returns a word on success, "" otherwise.
42  *
43  * To allow the caller to skip NULL check, this function returns "" rather than
44  * NULL if there is no more words to read.
45  */
46 char *tomoyo_read_token(struct tomoyo_acl_param *param)
47 {
48         char *pos = param->data;
49         char *del = strchr(pos, ' ');
50         if (del)
51                 *del++ = '\0';
52         else
53                 del = pos + strlen(pos);
54         param->data = del;
55         return pos;
56 }
57
58 /**
59  * tomoyo_parse_ulong - Parse an "unsigned long" value.
60  *
61  * @result: Pointer to "unsigned long".
62  * @str:    Pointer to string to parse.
63  *
64  * Returns one of values in "enum tomoyo_value_type".
65  *
66  * The @src is updated to point the first character after the value
67  * on success.
68  */
69 static u8 tomoyo_parse_ulong(unsigned long *result, char **str)
70 {
71         const char *cp = *str;
72         char *ep;
73         int base = 10;
74         if (*cp == '0') {
75                 char c = *(cp + 1);
76                 if (c == 'x' || c == 'X') {
77                         base = 16;
78                         cp += 2;
79                 } else if (c >= '0' && c <= '7') {
80                         base = 8;
81                         cp++;
82                 }
83         }
84         *result = simple_strtoul(cp, &ep, base);
85         if (cp == ep)
86                 return TOMOYO_VALUE_TYPE_INVALID;
87         *str = ep;
88         switch (base) {
89         case 16:
90                 return TOMOYO_VALUE_TYPE_HEXADECIMAL;
91         case 8:
92                 return TOMOYO_VALUE_TYPE_OCTAL;
93         default:
94                 return TOMOYO_VALUE_TYPE_DECIMAL;
95         }
96 }
97
98 /**
99  * tomoyo_print_ulong - Print an "unsigned long" value.
100  *
101  * @buffer:     Pointer to buffer.
102  * @buffer_len: Size of @buffer.
103  * @value:      An "unsigned long" value.
104  * @type:       Type of @value.
105  *
106  * Returns nothing.
107  */
108 void tomoyo_print_ulong(char *buffer, const int buffer_len,
109                         const unsigned long value, const u8 type)
110 {
111         if (type == TOMOYO_VALUE_TYPE_DECIMAL)
112                 snprintf(buffer, buffer_len, "%lu", value);
113         else if (type == TOMOYO_VALUE_TYPE_OCTAL)
114                 snprintf(buffer, buffer_len, "0%lo", value);
115         else if (type == TOMOYO_VALUE_TYPE_HEXADECIMAL)
116                 snprintf(buffer, buffer_len, "0x%lX", value);
117         else
118                 snprintf(buffer, buffer_len, "type(%u)", type);
119 }
120
121 /**
122  * tomoyo_parse_name_union - Parse a tomoyo_name_union.
123  *
124  * @param: Pointer to "struct tomoyo_acl_param".
125  * @ptr:   Pointer to "struct tomoyo_name_union".
126  *
127  * Returns true on success, false otherwise.
128  */
129 bool tomoyo_parse_name_union(struct tomoyo_acl_param *param,
130                              struct tomoyo_name_union *ptr)
131 {
132         char *filename;
133         if (param->data[0] == '@') {
134                 param->data++;
135                 ptr->group = tomoyo_get_group(param, TOMOYO_PATH_GROUP);
136                 return ptr->group != NULL;
137         }
138         filename = tomoyo_read_token(param);
139         if (!tomoyo_correct_word(filename))
140                 return false;
141         ptr->filename = tomoyo_get_name(filename);
142         return ptr->filename != NULL;
143 }
144
145 /**
146  * tomoyo_parse_number_union - Parse a tomoyo_number_union.
147  *
148  * @param: Pointer to "struct tomoyo_acl_param".
149  * @ptr:   Pointer to "struct tomoyo_number_union".
150  *
151  * Returns true on success, false otherwise.
152  */
153 bool tomoyo_parse_number_union(struct tomoyo_acl_param *param,
154                                struct tomoyo_number_union *ptr)
155 {
156         char *data;
157         u8 type;
158         unsigned long v;
159         memset(ptr, 0, sizeof(*ptr));
160         if (param->data[0] == '@') {
161                 param->data++;
162                 ptr->group = tomoyo_get_group(param, TOMOYO_NUMBER_GROUP);
163                 return ptr->group != NULL;
164         }
165         data = tomoyo_read_token(param);
166         type = tomoyo_parse_ulong(&v, &data);
167         if (type == TOMOYO_VALUE_TYPE_INVALID)
168                 return false;
169         ptr->values[0] = v;
170         ptr->value_type[0] = type;
171         if (!*data) {
172                 ptr->values[1] = v;
173                 ptr->value_type[1] = type;
174                 return true;
175         }
176         if (*data++ != '-')
177                 return false;
178         type = tomoyo_parse_ulong(&v, &data);
179         if (type == TOMOYO_VALUE_TYPE_INVALID || *data || ptr->values[0] > v)
180                 return false;
181         ptr->values[1] = v;
182         ptr->value_type[1] = type;
183         return true;
184 }
185
186 /**
187  * tomoyo_byte_range - Check whether the string is a \ooo style octal value.
188  *
189  * @str: Pointer to the string.
190  *
191  * Returns true if @str is a \ooo style octal value, false otherwise.
192  *
193  * TOMOYO uses \ooo style representation for 0x01 - 0x20 and 0x7F - 0xFF.
194  * This function verifies that \ooo is in valid range.
195  */
196 static inline bool tomoyo_byte_range(const char *str)
197 {
198         return *str >= '0' && *str++ <= '3' &&
199                 *str >= '0' && *str++ <= '7' &&
200                 *str >= '0' && *str <= '7';
201 }
202
203 /**
204  * tomoyo_alphabet_char - Check whether the character is an alphabet.
205  *
206  * @c: The character to check.
207  *
208  * Returns true if @c is an alphabet character, false otherwise.
209  */
210 static inline bool tomoyo_alphabet_char(const char c)
211 {
212         return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
213 }
214
215 /**
216  * tomoyo_make_byte - Make byte value from three octal characters.
217  *
218  * @c1: The first character.
219  * @c2: The second character.
220  * @c3: The third character.
221  *
222  * Returns byte value.
223  */
224 static inline u8 tomoyo_make_byte(const u8 c1, const u8 c2, const u8 c3)
225 {
226         return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
227 }
228
229 /**
230  * tomoyo_valid - Check whether the character is a valid char.
231  *
232  * @c: The character to check.
233  *
234  * Returns true if @c is a valid character, false otherwise.
235  */
236 static inline bool tomoyo_valid(const unsigned char c)
237 {
238         return c > ' ' && c < 127;
239 }
240
241 /**
242  * tomoyo_invalid - Check whether the character is an invalid char.
243  *
244  * @c: The character to check.
245  *
246  * Returns true if @c is an invalid character, false otherwise.
247  */
248 static inline bool tomoyo_invalid(const unsigned char c)
249 {
250         return c && (c <= ' ' || c >= 127);
251 }
252
253 /**
254  * tomoyo_str_starts - Check whether the given string starts with the given keyword.
255  *
256  * @src:  Pointer to pointer to the string.
257  * @find: Pointer to the keyword.
258  *
259  * Returns true if @src starts with @find, false otherwise.
260  *
261  * The @src is updated to point the first character after the @find
262  * if @src starts with @find.
263  */
264 bool tomoyo_str_starts(char **src, const char *find)
265 {
266         const int len = strlen(find);
267         char *tmp = *src;
268
269         if (strncmp(tmp, find, len))
270                 return false;
271         tmp += len;
272         *src = tmp;
273         return true;
274 }
275
276 /**
277  * tomoyo_normalize_line - Format string.
278  *
279  * @buffer: The line to normalize.
280  *
281  * Leading and trailing whitespaces are removed.
282  * Multiple whitespaces are packed into single space.
283  *
284  * Returns nothing.
285  */
286 void tomoyo_normalize_line(unsigned char *buffer)
287 {
288         unsigned char *sp = buffer;
289         unsigned char *dp = buffer;
290         bool first = true;
291
292         while (tomoyo_invalid(*sp))
293                 sp++;
294         while (*sp) {
295                 if (!first)
296                         *dp++ = ' ';
297                 first = false;
298                 while (tomoyo_valid(*sp))
299                         *dp++ = *sp++;
300                 while (tomoyo_invalid(*sp))
301                         sp++;
302         }
303         *dp = '\0';
304 }
305
306 /**
307  * tomoyo_correct_word2 - Validate a string.
308  *
309  * @string: The string to check. May be non-'\0'-terminated.
310  * @len:    Length of @string.
311  *
312  * Check whether the given string follows the naming rules.
313  * Returns true if @string follows the naming rules, false otherwise.
314  */
315 static bool tomoyo_correct_word2(const char *string, size_t len)
316 {
317         const char *const start = string;
318         bool in_repetition = false;
319         unsigned char c;
320         unsigned char d;
321         unsigned char e;
322         if (!len)
323                 goto out;
324         while (len--) {
325                 c = *string++;
326                 if (c == '\\') {
327                         if (!len--)
328                                 goto out;
329                         c = *string++;
330                         switch (c) {
331                         case '\\':  /* "\\" */
332                                 continue;
333                         case '$':   /* "\$" */
334                         case '+':   /* "\+" */
335                         case '?':   /* "\?" */
336                         case '*':   /* "\*" */
337                         case '@':   /* "\@" */
338                         case 'x':   /* "\x" */
339                         case 'X':   /* "\X" */
340                         case 'a':   /* "\a" */
341                         case 'A':   /* "\A" */
342                         case '-':   /* "\-" */
343                                 continue;
344                         case '{':   /* "/\{" */
345                                 if (string - 3 < start || *(string - 3) != '/')
346                                         break;
347                                 in_repetition = true;
348                                 continue;
349                         case '}':   /* "\}/" */
350                                 if (*string != '/')
351                                         break;
352                                 if (!in_repetition)
353                                         break;
354                                 in_repetition = false;
355                                 continue;
356                         case '0':   /* "\ooo" */
357                         case '1':
358                         case '2':
359                         case '3':
360                                 if (!len-- || !len--)
361                                         break;
362                                 d = *string++;
363                                 e = *string++;
364                                 if (d < '0' || d > '7' || e < '0' || e > '7')
365                                         break;
366                                 c = tomoyo_make_byte(c, d, e);
367                                 if (tomoyo_invalid(c))
368                                         continue; /* pattern is not \000 */
369                         }
370                         goto out;
371                 } else if (in_repetition && c == '/') {
372                         goto out;
373                 } else if (tomoyo_invalid(c)) {
374                         goto out;
375                 }
376         }
377         if (in_repetition)
378                 goto out;
379         return true;
380  out:
381         return false;
382 }
383
384 /**
385  * tomoyo_correct_word - Validate a string.
386  *
387  * @string: The string to check.
388  *
389  * Check whether the given string follows the naming rules.
390  * Returns true if @string follows the naming rules, false otherwise.
391  */
392 bool tomoyo_correct_word(const char *string)
393 {
394         return tomoyo_correct_word2(string, strlen(string));
395 }
396
397 /**
398  * tomoyo_correct_path - Validate a pathname.
399  *
400  * @filename: The pathname to check.
401  *
402  * Check whether the given pathname follows the naming rules.
403  * Returns true if @filename follows the naming rules, false otherwise.
404  */
405 bool tomoyo_correct_path(const char *filename)
406 {
407         return *filename == '/' && tomoyo_correct_word(filename);
408 }
409
410 /**
411  * tomoyo_correct_domain - Check whether the given domainname follows the naming rules.
412  *
413  * @domainname: The domainname to check.
414  *
415  * Returns true if @domainname follows the naming rules, false otherwise.
416  */
417 bool tomoyo_correct_domain(const unsigned char *domainname)
418 {
419         if (!domainname || !tomoyo_domain_def(domainname))
420                 return false;
421         domainname = strchr(domainname, ' ');
422         if (!domainname++)
423                 return true;
424         while (1) {
425                 const unsigned char *cp = strchr(domainname, ' ');
426                 if (!cp)
427                         break;
428                 if (*domainname != '/' ||
429                     !tomoyo_correct_word2(domainname, cp - domainname))
430                         return false;
431                 domainname = cp + 1;
432         }
433         return tomoyo_correct_path(domainname);
434 }
435
436 /**
437  * tomoyo_domain_def - Check whether the given token can be a domainname.
438  *
439  * @buffer: The token to check.
440  *
441  * Returns true if @buffer possibly be a domainname, false otherwise.
442  */
443 bool tomoyo_domain_def(const unsigned char *buffer)
444 {
445         const unsigned char *cp;
446         int len;
447         if (*buffer != '<')
448                 return false;
449         cp = strchr(buffer, ' ');
450         if (!cp)
451                 len = strlen(buffer);
452         else
453                 len = cp - buffer;
454         if (buffer[len - 1] != '>' ||
455             !tomoyo_correct_word2(buffer + 1, len - 2))
456                 return false;
457         return true;
458 }
459
460 /**
461  * tomoyo_find_domain - Find a domain by the given name.
462  *
463  * @domainname: The domainname to find.
464  *
465  * Returns pointer to "struct tomoyo_domain_info" if found, NULL otherwise.
466  *
467  * Caller holds tomoyo_read_lock().
468  */
469 struct tomoyo_domain_info *tomoyo_find_domain(const char *domainname)
470 {
471         struct tomoyo_domain_info *domain;
472         struct tomoyo_path_info name;
473
474         name.name = domainname;
475         tomoyo_fill_path_info(&name);
476         list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
477                 if (!domain->is_deleted &&
478                     !tomoyo_pathcmp(&name, domain->domainname))
479                         return domain;
480         }
481         return NULL;
482 }
483
484 /**
485  * tomoyo_const_part_length - Evaluate the initial length without a pattern in a token.
486  *
487  * @filename: The string to evaluate.
488  *
489  * Returns the initial length without a pattern in @filename.
490  */
491 static int tomoyo_const_part_length(const char *filename)
492 {
493         char c;
494         int len = 0;
495
496         if (!filename)
497                 return 0;
498         while ((c = *filename++) != '\0') {
499                 if (c != '\\') {
500                         len++;
501                         continue;
502                 }
503                 c = *filename++;
504                 switch (c) {
505                 case '\\':  /* "\\" */
506                         len += 2;
507                         continue;
508                 case '0':   /* "\ooo" */
509                 case '1':
510                 case '2':
511                 case '3':
512                         c = *filename++;
513                         if (c < '0' || c > '7')
514                                 break;
515                         c = *filename++;
516                         if (c < '0' || c > '7')
517                                 break;
518                         len += 4;
519                         continue;
520                 }
521                 break;
522         }
523         return len;
524 }
525
526 /**
527  * tomoyo_fill_path_info - Fill in "struct tomoyo_path_info" members.
528  *
529  * @ptr: Pointer to "struct tomoyo_path_info" to fill in.
530  *
531  * The caller sets "struct tomoyo_path_info"->name.
532  */
533 void tomoyo_fill_path_info(struct tomoyo_path_info *ptr)
534 {
535         const char *name = ptr->name;
536         const int len = strlen(name);
537
538         ptr->const_len = tomoyo_const_part_length(name);
539         ptr->is_dir = len && (name[len - 1] == '/');
540         ptr->is_patterned = (ptr->const_len < len);
541         ptr->hash = full_name_hash(name, len);
542 }
543
544 /**
545  * tomoyo_file_matches_pattern2 - Pattern matching without '/' character and "\-" pattern.
546  *
547  * @filename:     The start of string to check.
548  * @filename_end: The end of string to check.
549  * @pattern:      The start of pattern to compare.
550  * @pattern_end:  The end of pattern to compare.
551  *
552  * Returns true if @filename matches @pattern, false otherwise.
553  */
554 static bool tomoyo_file_matches_pattern2(const char *filename,
555                                          const char *filename_end,
556                                          const char *pattern,
557                                          const char *pattern_end)
558 {
559         while (filename < filename_end && pattern < pattern_end) {
560                 char c;
561                 if (*pattern != '\\') {
562                         if (*filename++ != *pattern++)
563                                 return false;
564                         continue;
565                 }
566                 c = *filename;
567                 pattern++;
568                 switch (*pattern) {
569                         int i;
570                         int j;
571                 case '?':
572                         if (c == '/') {
573                                 return false;
574                         } else if (c == '\\') {
575                                 if (filename[1] == '\\')
576                                         filename++;
577                                 else if (tomoyo_byte_range(filename + 1))
578                                         filename += 3;
579                                 else
580                                         return false;
581                         }
582                         break;
583                 case '\\':
584                         if (c != '\\')
585                                 return false;
586                         if (*++filename != '\\')
587                                 return false;
588                         break;
589                 case '+':
590                         if (!isdigit(c))
591                                 return false;
592                         break;
593                 case 'x':
594                         if (!isxdigit(c))
595                                 return false;
596                         break;
597                 case 'a':
598                         if (!tomoyo_alphabet_char(c))
599                                 return false;
600                         break;
601                 case '0':
602                 case '1':
603                 case '2':
604                 case '3':
605                         if (c == '\\' && tomoyo_byte_range(filename + 1)
606                             && strncmp(filename + 1, pattern, 3) == 0) {
607                                 filename += 3;
608                                 pattern += 2;
609                                 break;
610                         }
611                         return false; /* Not matched. */
612                 case '*':
613                 case '@':
614                         for (i = 0; i <= filename_end - filename; i++) {
615                                 if (tomoyo_file_matches_pattern2(
616                                                     filename + i, filename_end,
617                                                     pattern + 1, pattern_end))
618                                         return true;
619                                 c = filename[i];
620                                 if (c == '.' && *pattern == '@')
621                                         break;
622                                 if (c != '\\')
623                                         continue;
624                                 if (filename[i + 1] == '\\')
625                                         i++;
626                                 else if (tomoyo_byte_range(filename + i + 1))
627                                         i += 3;
628                                 else
629                                         break; /* Bad pattern. */
630                         }
631                         return false; /* Not matched. */
632                 default:
633                         j = 0;
634                         c = *pattern;
635                         if (c == '$') {
636                                 while (isdigit(filename[j]))
637                                         j++;
638                         } else if (c == 'X') {
639                                 while (isxdigit(filename[j]))
640                                         j++;
641                         } else if (c == 'A') {
642                                 while (tomoyo_alphabet_char(filename[j]))
643                                         j++;
644                         }
645                         for (i = 1; i <= j; i++) {
646                                 if (tomoyo_file_matches_pattern2(
647                                                     filename + i, filename_end,
648                                                     pattern + 1, pattern_end))
649                                         return true;
650                         }
651                         return false; /* Not matched or bad pattern. */
652                 }
653                 filename++;
654                 pattern++;
655         }
656         while (*pattern == '\\' &&
657                (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
658                 pattern += 2;
659         return filename == filename_end && pattern == pattern_end;
660 }
661
662 /**
663  * tomoyo_file_matches_pattern - Pattern matching without '/' character.
664  *
665  * @filename:     The start of string to check.
666  * @filename_end: The end of string to check.
667  * @pattern:      The start of pattern to compare.
668  * @pattern_end:  The end of pattern to compare.
669  *
670  * Returns true if @filename matches @pattern, false otherwise.
671  */
672 static bool tomoyo_file_matches_pattern(const char *filename,
673                                         const char *filename_end,
674                                         const char *pattern,
675                                         const char *pattern_end)
676 {
677         const char *pattern_start = pattern;
678         bool first = true;
679         bool result;
680
681         while (pattern < pattern_end - 1) {
682                 /* Split at "\-" pattern. */
683                 if (*pattern++ != '\\' || *pattern++ != '-')
684                         continue;
685                 result = tomoyo_file_matches_pattern2(filename,
686                                                       filename_end,
687                                                       pattern_start,
688                                                       pattern - 2);
689                 if (first)
690                         result = !result;
691                 if (result)
692                         return false;
693                 first = false;
694                 pattern_start = pattern;
695         }
696         result = tomoyo_file_matches_pattern2(filename, filename_end,
697                                               pattern_start, pattern_end);
698         return first ? result : !result;
699 }
700
701 /**
702  * tomoyo_path_matches_pattern2 - Do pathname pattern matching.
703  *
704  * @f: The start of string to check.
705  * @p: The start of pattern to compare.
706  *
707  * Returns true if @f matches @p, false otherwise.
708  */
709 static bool tomoyo_path_matches_pattern2(const char *f, const char *p)
710 {
711         const char *f_delimiter;
712         const char *p_delimiter;
713
714         while (*f && *p) {
715                 f_delimiter = strchr(f, '/');
716                 if (!f_delimiter)
717                         f_delimiter = f + strlen(f);
718                 p_delimiter = strchr(p, '/');
719                 if (!p_delimiter)
720                         p_delimiter = p + strlen(p);
721                 if (*p == '\\' && *(p + 1) == '{')
722                         goto recursive;
723                 if (!tomoyo_file_matches_pattern(f, f_delimiter, p,
724                                                  p_delimiter))
725                         return false;
726                 f = f_delimiter;
727                 if (*f)
728                         f++;
729                 p = p_delimiter;
730                 if (*p)
731                         p++;
732         }
733         /* Ignore trailing "\*" and "\@" in @pattern. */
734         while (*p == '\\' &&
735                (*(p + 1) == '*' || *(p + 1) == '@'))
736                 p += 2;
737         return !*f && !*p;
738  recursive:
739         /*
740          * The "\{" pattern is permitted only after '/' character.
741          * This guarantees that below "*(p - 1)" is safe.
742          * Also, the "\}" pattern is permitted only before '/' character
743          * so that "\{" + "\}" pair will not break the "\-" operator.
744          */
745         if (*(p - 1) != '/' || p_delimiter <= p + 3 || *p_delimiter != '/' ||
746             *(p_delimiter - 1) != '}' || *(p_delimiter - 2) != '\\')
747                 return false; /* Bad pattern. */
748         do {
749                 /* Compare current component with pattern. */
750                 if (!tomoyo_file_matches_pattern(f, f_delimiter, p + 2,
751                                                  p_delimiter - 2))
752                         break;
753                 /* Proceed to next component. */
754                 f = f_delimiter;
755                 if (!*f)
756                         break;
757                 f++;
758                 /* Continue comparison. */
759                 if (tomoyo_path_matches_pattern2(f, p_delimiter + 1))
760                         return true;
761                 f_delimiter = strchr(f, '/');
762         } while (f_delimiter);
763         return false; /* Not matched. */
764 }
765
766 /**
767  * tomoyo_path_matches_pattern - Check whether the given filename matches the given pattern.
768  *
769  * @filename: The filename to check.
770  * @pattern:  The pattern to compare.
771  *
772  * Returns true if matches, false otherwise.
773  *
774  * The following patterns are available.
775  *   \\     \ itself.
776  *   \ooo   Octal representation of a byte.
777  *   \*     Zero or more repetitions of characters other than '/'.
778  *   \@     Zero or more repetitions of characters other than '/' or '.'.
779  *   \?     1 byte character other than '/'.
780  *   \$     One or more repetitions of decimal digits.
781  *   \+     1 decimal digit.
782  *   \X     One or more repetitions of hexadecimal digits.
783  *   \x     1 hexadecimal digit.
784  *   \A     One or more repetitions of alphabet characters.
785  *   \a     1 alphabet character.
786  *
787  *   \-     Subtraction operator.
788  *
789  *   /\{dir\}/   '/' + 'One or more repetitions of dir/' (e.g. /dir/ /dir/dir/
790  *               /dir/dir/dir/ ).
791  */
792 bool tomoyo_path_matches_pattern(const struct tomoyo_path_info *filename,
793                                  const struct tomoyo_path_info *pattern)
794 {
795         const char *f = filename->name;
796         const char *p = pattern->name;
797         const int len = pattern->const_len;
798
799         /* If @pattern doesn't contain pattern, I can use strcmp(). */
800         if (!pattern->is_patterned)
801                 return !tomoyo_pathcmp(filename, pattern);
802         /* Don't compare directory and non-directory. */
803         if (filename->is_dir != pattern->is_dir)
804                 return false;
805         /* Compare the initial length without patterns. */
806         if (strncmp(f, p, len))
807                 return false;
808         f += len;
809         p += len;
810         return tomoyo_path_matches_pattern2(f, p);
811 }
812
813 /**
814  * tomoyo_get_exe - Get tomoyo_realpath() of current process.
815  *
816  * Returns the tomoyo_realpath() of current process on success, NULL otherwise.
817  *
818  * This function uses kzalloc(), so the caller must call kfree()
819  * if this function didn't return NULL.
820  */
821 const char *tomoyo_get_exe(void)
822 {
823         struct mm_struct *mm = current->mm;
824         struct vm_area_struct *vma;
825         const char *cp = NULL;
826
827         if (!mm)
828                 return NULL;
829         down_read(&mm->mmap_sem);
830         for (vma = mm->mmap; vma; vma = vma->vm_next) {
831                 if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
832                         cp = tomoyo_realpath_from_path(&vma->vm_file->f_path);
833                         break;
834                 }
835         }
836         up_read(&mm->mmap_sem);
837         return cp;
838 }
839
840 /**
841  * tomoyo_get_mode - Get MAC mode.
842  *
843  * @ns:      Pointer to "struct tomoyo_policy_namespace".
844  * @profile: Profile number.
845  * @index:   Index number of functionality.
846  *
847  * Returns mode.
848  */
849 int tomoyo_get_mode(const struct tomoyo_policy_namespace *ns, const u8 profile,
850                     const u8 index)
851 {
852         u8 mode;
853         const u8 category = TOMOYO_MAC_CATEGORY_FILE;
854         if (!tomoyo_policy_loaded)
855                 return TOMOYO_CONFIG_DISABLED;
856         mode = tomoyo_profile(ns, profile)->config[index];
857         if (mode == TOMOYO_CONFIG_USE_DEFAULT)
858                 mode = tomoyo_profile(ns, profile)->config[category];
859         if (mode == TOMOYO_CONFIG_USE_DEFAULT)
860                 mode = tomoyo_profile(ns, profile)->default_config;
861         return mode & 3;
862 }
863
864 /**
865  * tomoyo_init_request_info - Initialize "struct tomoyo_request_info" members.
866  *
867  * @r:      Pointer to "struct tomoyo_request_info" to initialize.
868  * @domain: Pointer to "struct tomoyo_domain_info". NULL for tomoyo_domain().
869  * @index:  Index number of functionality.
870  *
871  * Returns mode.
872  */
873 int tomoyo_init_request_info(struct tomoyo_request_info *r,
874                              struct tomoyo_domain_info *domain, const u8 index)
875 {
876         u8 profile;
877         memset(r, 0, sizeof(*r));
878         if (!domain)
879                 domain = tomoyo_domain();
880         r->domain = domain;
881         profile = domain->profile;
882         r->profile = profile;
883         r->type = index;
884         r->mode = tomoyo_get_mode(domain->ns, profile, index);
885         return r->mode;
886 }
887
888 /**
889  * tomoyo_domain_quota_is_ok - Check for domain's quota.
890  *
891  * @r: Pointer to "struct tomoyo_request_info".
892  *
893  * Returns true if the domain is not exceeded quota, false otherwise.
894  *
895  * Caller holds tomoyo_read_lock().
896  */
897 bool tomoyo_domain_quota_is_ok(struct tomoyo_request_info *r)
898 {
899         unsigned int count = 0;
900         struct tomoyo_domain_info *domain = r->domain;
901         struct tomoyo_acl_info *ptr;
902
903         if (r->mode != TOMOYO_CONFIG_LEARNING)
904                 return false;
905         if (!domain)
906                 return true;
907         list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
908                 u16 perm;
909                 u8 i;
910                 if (ptr->is_deleted)
911                         continue;
912                 switch (ptr->type) {
913                 case TOMOYO_TYPE_PATH_ACL:
914                         perm = container_of(ptr, struct tomoyo_path_acl, head)
915                                 ->perm;
916                         break;
917                 case TOMOYO_TYPE_PATH2_ACL:
918                         perm = container_of(ptr, struct tomoyo_path2_acl, head)
919                                 ->perm;
920                         break;
921                 case TOMOYO_TYPE_PATH_NUMBER_ACL:
922                         perm = container_of(ptr, struct tomoyo_path_number_acl,
923                                             head)->perm;
924                         break;
925                 case TOMOYO_TYPE_MKDEV_ACL:
926                         perm = container_of(ptr, struct tomoyo_mkdev_acl,
927                                             head)->perm;
928                         break;
929                 default:
930                         perm = 1;
931                 }
932                 for (i = 0; i < 16; i++)
933                         if (perm & (1 << i))
934                                 count++;
935         }
936         if (count < tomoyo_profile(domain->ns, domain->profile)->
937             pref[TOMOYO_PREF_MAX_LEARNING_ENTRY])
938                 return true;
939         if (!domain->quota_warned) {
940                 domain->quota_warned = true;
941                 printk(KERN_WARNING "TOMOYO-WARNING: "
942                        "Domain '%s' has too many ACLs to hold. "
943                        "Stopped learning mode.\n", domain->domainname->name);
944         }
945         return false;
946 }