2 * security/tomoyo/util.c
4 * Utility functions for TOMOYO.
6 * Copyright (C) 2005-2010 NTT DATA CORPORATION
9 #include <linux/slab.h>
12 /* Lock for protecting policy. */
13 DEFINE_MUTEX(tomoyo_policy_lock);
15 /* Has /sbin/init started? */
16 bool tomoyo_policy_loaded;
19 * tomoyo_parse_ulong - Parse an "unsigned long" value.
21 * @result: Pointer to "unsigned long".
22 * @str: Pointer to string to parse.
24 * Returns one of values in "enum tomoyo_value_type".
26 * The @src is updated to point the first character after the value
29 static u8 tomoyo_parse_ulong(unsigned long *result, char **str)
31 const char *cp = *str;
36 if (c == 'x' || c == 'X') {
39 } else if (c >= '0' && c <= '7') {
44 *result = simple_strtoul(cp, &ep, base);
46 return TOMOYO_VALUE_TYPE_INVALID;
50 return TOMOYO_VALUE_TYPE_HEXADECIMAL;
52 return TOMOYO_VALUE_TYPE_OCTAL;
54 return TOMOYO_VALUE_TYPE_DECIMAL;
59 * tomoyo_print_ulong - Print an "unsigned long" value.
61 * @buffer: Pointer to buffer.
62 * @buffer_len: Size of @buffer.
63 * @value: An "unsigned long" value.
64 * @type: Type of @value.
68 void tomoyo_print_ulong(char *buffer, const int buffer_len,
69 const unsigned long value, const u8 type)
71 if (type == TOMOYO_VALUE_TYPE_DECIMAL)
72 snprintf(buffer, buffer_len, "%lu", value);
73 else if (type == TOMOYO_VALUE_TYPE_OCTAL)
74 snprintf(buffer, buffer_len, "0%lo", value);
75 else if (type == TOMOYO_VALUE_TYPE_HEXADECIMAL)
76 snprintf(buffer, buffer_len, "0x%lX", value);
78 snprintf(buffer, buffer_len, "type(%u)", type);
82 * tomoyo_parse_name_union - Parse a tomoyo_name_union.
84 * @filename: Name or name group.
85 * @ptr: Pointer to "struct tomoyo_name_union".
87 * Returns true on success, false otherwise.
89 bool tomoyo_parse_name_union(const char *filename,
90 struct tomoyo_name_union *ptr)
92 if (!tomoyo_correct_word(filename))
94 if (filename[0] == '@') {
95 ptr->group = tomoyo_get_group(filename + 1, TOMOYO_PATH_GROUP);
96 return ptr->group != NULL;
98 ptr->filename = tomoyo_get_name(filename);
99 return ptr->filename != NULL;
103 * tomoyo_parse_number_union - Parse a tomoyo_number_union.
105 * @data: Number or number range or number group.
106 * @ptr: Pointer to "struct tomoyo_number_union".
108 * Returns true on success, false otherwise.
110 bool tomoyo_parse_number_union(char *data, struct tomoyo_number_union *num)
114 memset(num, 0, sizeof(*num));
115 if (data[0] == '@') {
116 if (!tomoyo_correct_word(data))
118 num->group = tomoyo_get_group(data + 1, TOMOYO_NUMBER_GROUP);
119 return num->group != NULL;
121 type = tomoyo_parse_ulong(&v, &data);
125 num->value_type[0] = type;
128 num->value_type[1] = type;
133 type = tomoyo_parse_ulong(&v, &data);
137 num->value_type[1] = type;
142 * tomoyo_byte_range - Check whether the string is a \ooo style octal value.
144 * @str: Pointer to the string.
146 * Returns true if @str is a \ooo style octal value, false otherwise.
148 * TOMOYO uses \ooo style representation for 0x01 - 0x20 and 0x7F - 0xFF.
149 * This function verifies that \ooo is in valid range.
151 static inline bool tomoyo_byte_range(const char *str)
153 return *str >= '0' && *str++ <= '3' &&
154 *str >= '0' && *str++ <= '7' &&
155 *str >= '0' && *str <= '7';
159 * tomoyo_alphabet_char - Check whether the character is an alphabet.
161 * @c: The character to check.
163 * Returns true if @c is an alphabet character, false otherwise.
165 static inline bool tomoyo_alphabet_char(const char c)
167 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
171 * tomoyo_make_byte - Make byte value from three octal characters.
173 * @c1: The first character.
174 * @c2: The second character.
175 * @c3: The third character.
177 * Returns byte value.
179 static inline u8 tomoyo_make_byte(const u8 c1, const u8 c2, const u8 c3)
181 return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
185 * tomoyo_valid - Check whether the character is a valid char.
187 * @c: The character to check.
189 * Returns true if @c is a valid character, false otherwise.
191 static inline bool tomoyo_valid(const unsigned char c)
193 return c > ' ' && c < 127;
197 * tomoyo_invalid - Check whether the character is an invalid char.
199 * @c: The character to check.
201 * Returns true if @c is an invalid character, false otherwise.
203 static inline bool tomoyo_invalid(const unsigned char c)
205 return c && (c <= ' ' || c >= 127);
209 * tomoyo_str_starts - Check whether the given string starts with the given keyword.
211 * @src: Pointer to pointer to the string.
212 * @find: Pointer to the keyword.
214 * Returns true if @src starts with @find, false otherwise.
216 * The @src is updated to point the first character after the @find
217 * if @src starts with @find.
219 bool tomoyo_str_starts(char **src, const char *find)
221 const int len = strlen(find);
224 if (strncmp(tmp, find, len))
232 * tomoyo_normalize_line - Format string.
234 * @buffer: The line to normalize.
236 * Leading and trailing whitespaces are removed.
237 * Multiple whitespaces are packed into single space.
241 void tomoyo_normalize_line(unsigned char *buffer)
243 unsigned char *sp = buffer;
244 unsigned char *dp = buffer;
247 while (tomoyo_invalid(*sp))
253 while (tomoyo_valid(*sp))
255 while (tomoyo_invalid(*sp))
262 * tomoyo_tokenize - Tokenize string.
264 * @buffer: The line to tokenize.
265 * @w: Pointer to "char *".
268 * Returns true on success, false otherwise.
270 bool tomoyo_tokenize(char *buffer, char *w[], size_t size)
272 int count = size / sizeof(char *);
274 for (i = 0; i < count; i++)
276 for (i = 0; i < count; i++) {
277 char *cp = strchr(buffer, ' ');
285 return i < count || !*buffer;
289 * tomoyo_correct_word2 - Validate a string.
291 * @string: The string to check. May be non-'\0'-terminated.
292 * @len: Length of @string.
294 * Check whether the given string follows the naming rules.
295 * Returns true if @string follows the naming rules, false otherwise.
297 static bool tomoyo_correct_word2(const char *string, size_t len)
299 const char *const start = string;
300 bool in_repetition = false;
313 case '\\': /* "\\" */
326 case '{': /* "/\{" */
327 if (string - 3 < start || *(string - 3) != '/')
329 in_repetition = true;
331 case '}': /* "\}/" */
336 in_repetition = false;
338 case '0': /* "\ooo" */
342 if (!len-- || !len--)
346 if (d < '0' || d > '7' || e < '0' || e > '7')
348 c = tomoyo_make_byte(c, d, e);
349 if (tomoyo_invalid(c))
350 continue; /* pattern is not \000 */
353 } else if (in_repetition && c == '/') {
355 } else if (tomoyo_invalid(c)) {
367 * tomoyo_correct_word - Validate a string.
369 * @string: The string to check.
371 * Check whether the given string follows the naming rules.
372 * Returns true if @string follows the naming rules, false otherwise.
374 bool tomoyo_correct_word(const char *string)
376 return tomoyo_correct_word2(string, strlen(string));
380 * tomoyo_correct_path - Validate a pathname.
382 * @filename: The pathname to check.
384 * Check whether the given pathname follows the naming rules.
385 * Returns true if @filename follows the naming rules, false otherwise.
387 bool tomoyo_correct_path(const char *filename)
389 return *filename == '/' && tomoyo_correct_word(filename);
393 * tomoyo_correct_domain - Check whether the given domainname follows the naming rules.
395 * @domainname: The domainname to check.
397 * Returns true if @domainname follows the naming rules, false otherwise.
399 bool tomoyo_correct_domain(const unsigned char *domainname)
401 if (!domainname || strncmp(domainname, TOMOYO_ROOT_NAME,
402 TOMOYO_ROOT_NAME_LEN))
404 domainname += TOMOYO_ROOT_NAME_LEN;
407 if (*domainname++ != ' ')
410 const unsigned char *cp = strchr(domainname, ' ');
413 if (*domainname != '/' ||
414 !tomoyo_correct_word2(domainname, cp - domainname))
418 return tomoyo_correct_path(domainname);
424 * tomoyo_domain_def - Check whether the given token can be a domainname.
426 * @buffer: The token to check.
428 * Returns true if @buffer possibly be a domainname, false otherwise.
430 bool tomoyo_domain_def(const unsigned char *buffer)
432 return !strncmp(buffer, TOMOYO_ROOT_NAME, TOMOYO_ROOT_NAME_LEN);
436 * tomoyo_find_domain - Find a domain by the given name.
438 * @domainname: The domainname to find.
440 * Returns pointer to "struct tomoyo_domain_info" if found, NULL otherwise.
442 * Caller holds tomoyo_read_lock().
444 struct tomoyo_domain_info *tomoyo_find_domain(const char *domainname)
446 struct tomoyo_domain_info *domain;
447 struct tomoyo_path_info name;
449 name.name = domainname;
450 tomoyo_fill_path_info(&name);
451 list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
452 if (!domain->is_deleted &&
453 !tomoyo_pathcmp(&name, domain->domainname))
460 * tomoyo_const_part_length - Evaluate the initial length without a pattern in a token.
462 * @filename: The string to evaluate.
464 * Returns the initial length without a pattern in @filename.
466 static int tomoyo_const_part_length(const char *filename)
473 while ((c = *filename++) != '\0') {
480 case '\\': /* "\\" */
483 case '0': /* "\ooo" */
488 if (c < '0' || c > '7')
491 if (c < '0' || c > '7')
502 * tomoyo_fill_path_info - Fill in "struct tomoyo_path_info" members.
504 * @ptr: Pointer to "struct tomoyo_path_info" to fill in.
506 * The caller sets "struct tomoyo_path_info"->name.
508 void tomoyo_fill_path_info(struct tomoyo_path_info *ptr)
510 const char *name = ptr->name;
511 const int len = strlen(name);
513 ptr->const_len = tomoyo_const_part_length(name);
514 ptr->is_dir = len && (name[len - 1] == '/');
515 ptr->is_patterned = (ptr->const_len < len);
516 ptr->hash = full_name_hash(name, len);
520 * tomoyo_file_matches_pattern2 - Pattern matching without '/' character and "\-" pattern.
522 * @filename: The start of string to check.
523 * @filename_end: The end of string to check.
524 * @pattern: The start of pattern to compare.
525 * @pattern_end: The end of pattern to compare.
527 * Returns true if @filename matches @pattern, false otherwise.
529 static bool tomoyo_file_matches_pattern2(const char *filename,
530 const char *filename_end,
532 const char *pattern_end)
534 while (filename < filename_end && pattern < pattern_end) {
536 if (*pattern != '\\') {
537 if (*filename++ != *pattern++)
549 } else if (c == '\\') {
550 if (filename[1] == '\\')
552 else if (tomoyo_byte_range(filename + 1))
561 if (*++filename != '\\')
573 if (!tomoyo_alphabet_char(c))
580 if (c == '\\' && tomoyo_byte_range(filename + 1)
581 && strncmp(filename + 1, pattern, 3) == 0) {
586 return false; /* Not matched. */
589 for (i = 0; i <= filename_end - filename; i++) {
590 if (tomoyo_file_matches_pattern2(
591 filename + i, filename_end,
592 pattern + 1, pattern_end))
595 if (c == '.' && *pattern == '@')
599 if (filename[i + 1] == '\\')
601 else if (tomoyo_byte_range(filename + i + 1))
604 break; /* Bad pattern. */
606 return false; /* Not matched. */
611 while (isdigit(filename[j]))
613 } else if (c == 'X') {
614 while (isxdigit(filename[j]))
616 } else if (c == 'A') {
617 while (tomoyo_alphabet_char(filename[j]))
620 for (i = 1; i <= j; i++) {
621 if (tomoyo_file_matches_pattern2(
622 filename + i, filename_end,
623 pattern + 1, pattern_end))
626 return false; /* Not matched or bad pattern. */
631 while (*pattern == '\\' &&
632 (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
634 return filename == filename_end && pattern == pattern_end;
638 * tomoyo_file_matches_pattern - Pattern matching without '/' character.
640 * @filename: The start of string to check.
641 * @filename_end: The end of string to check.
642 * @pattern: The start of pattern to compare.
643 * @pattern_end: The end of pattern to compare.
645 * Returns true if @filename matches @pattern, false otherwise.
647 static bool tomoyo_file_matches_pattern(const char *filename,
648 const char *filename_end,
650 const char *pattern_end)
652 const char *pattern_start = pattern;
656 while (pattern < pattern_end - 1) {
657 /* Split at "\-" pattern. */
658 if (*pattern++ != '\\' || *pattern++ != '-')
660 result = tomoyo_file_matches_pattern2(filename,
669 pattern_start = pattern;
671 result = tomoyo_file_matches_pattern2(filename, filename_end,
672 pattern_start, pattern_end);
673 return first ? result : !result;
677 * tomoyo_path_matches_pattern2 - Do pathname pattern matching.
679 * @f: The start of string to check.
680 * @p: The start of pattern to compare.
682 * Returns true if @f matches @p, false otherwise.
684 static bool tomoyo_path_matches_pattern2(const char *f, const char *p)
686 const char *f_delimiter;
687 const char *p_delimiter;
690 f_delimiter = strchr(f, '/');
692 f_delimiter = f + strlen(f);
693 p_delimiter = strchr(p, '/');
695 p_delimiter = p + strlen(p);
696 if (*p == '\\' && *(p + 1) == '{')
698 if (!tomoyo_file_matches_pattern(f, f_delimiter, p,
708 /* Ignore trailing "\*" and "\@" in @pattern. */
710 (*(p + 1) == '*' || *(p + 1) == '@'))
715 * The "\{" pattern is permitted only after '/' character.
716 * This guarantees that below "*(p - 1)" is safe.
717 * Also, the "\}" pattern is permitted only before '/' character
718 * so that "\{" + "\}" pair will not break the "\-" operator.
720 if (*(p - 1) != '/' || p_delimiter <= p + 3 || *p_delimiter != '/' ||
721 *(p_delimiter - 1) != '}' || *(p_delimiter - 2) != '\\')
722 return false; /* Bad pattern. */
724 /* Compare current component with pattern. */
725 if (!tomoyo_file_matches_pattern(f, f_delimiter, p + 2,
728 /* Proceed to next component. */
733 /* Continue comparison. */
734 if (tomoyo_path_matches_pattern2(f, p_delimiter + 1))
736 f_delimiter = strchr(f, '/');
737 } while (f_delimiter);
738 return false; /* Not matched. */
742 * tomoyo_path_matches_pattern - Check whether the given filename matches the given pattern.
744 * @filename: The filename to check.
745 * @pattern: The pattern to compare.
747 * Returns true if matches, false otherwise.
749 * The following patterns are available.
751 * \ooo Octal representation of a byte.
752 * \* Zero or more repetitions of characters other than '/'.
753 * \@ Zero or more repetitions of characters other than '/' or '.'.
754 * \? 1 byte character other than '/'.
755 * \$ One or more repetitions of decimal digits.
756 * \+ 1 decimal digit.
757 * \X One or more repetitions of hexadecimal digits.
758 * \x 1 hexadecimal digit.
759 * \A One or more repetitions of alphabet characters.
760 * \a 1 alphabet character.
762 * \- Subtraction operator.
764 * /\{dir\}/ '/' + 'One or more repetitions of dir/' (e.g. /dir/ /dir/dir/
767 bool tomoyo_path_matches_pattern(const struct tomoyo_path_info *filename,
768 const struct tomoyo_path_info *pattern)
770 const char *f = filename->name;
771 const char *p = pattern->name;
772 const int len = pattern->const_len;
774 /* If @pattern doesn't contain pattern, I can use strcmp(). */
775 if (!pattern->is_patterned)
776 return !tomoyo_pathcmp(filename, pattern);
777 /* Don't compare directory and non-directory. */
778 if (filename->is_dir != pattern->is_dir)
780 /* Compare the initial length without patterns. */
781 if (strncmp(f, p, len))
785 return tomoyo_path_matches_pattern2(f, p);
789 * tomoyo_get_exe - Get tomoyo_realpath() of current process.
791 * Returns the tomoyo_realpath() of current process on success, NULL otherwise.
793 * This function uses kzalloc(), so the caller must call kfree()
794 * if this function didn't return NULL.
796 const char *tomoyo_get_exe(void)
798 struct mm_struct *mm = current->mm;
799 struct vm_area_struct *vma;
800 const char *cp = NULL;
804 down_read(&mm->mmap_sem);
805 for (vma = mm->mmap; vma; vma = vma->vm_next) {
806 if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
807 cp = tomoyo_realpath_from_path(&vma->vm_file->f_path);
811 up_read(&mm->mmap_sem);
816 * tomoyo_get_mode - Get MAC mode.
818 * @profile: Profile number.
819 * @index: Index number of functionality.
823 int tomoyo_get_mode(const u8 profile, const u8 index)
826 const u8 category = TOMOYO_MAC_CATEGORY_FILE;
827 if (!tomoyo_policy_loaded)
828 return TOMOYO_CONFIG_DISABLED;
829 mode = tomoyo_profile(profile)->config[index];
830 if (mode == TOMOYO_CONFIG_USE_DEFAULT)
831 mode = tomoyo_profile(profile)->config[category];
832 if (mode == TOMOYO_CONFIG_USE_DEFAULT)
833 mode = tomoyo_profile(profile)->default_config;
838 * tomoyo_init_request_info - Initialize "struct tomoyo_request_info" members.
840 * @r: Pointer to "struct tomoyo_request_info" to initialize.
841 * @domain: Pointer to "struct tomoyo_domain_info". NULL for tomoyo_domain().
842 * @index: Index number of functionality.
846 int tomoyo_init_request_info(struct tomoyo_request_info *r,
847 struct tomoyo_domain_info *domain, const u8 index)
850 memset(r, 0, sizeof(*r));
852 domain = tomoyo_domain();
854 profile = domain->profile;
855 r->profile = profile;
857 r->mode = tomoyo_get_mode(profile, index);
862 * tomoyo_last_word - Get last component of a line.
866 * Returns the last word of a line.
868 const char *tomoyo_last_word(const char *name)
870 const char *cp = strrchr(name, ' ');
877 * tomoyo_warn_log - Print warning or error message on console.
879 * @r: Pointer to "struct tomoyo_request_info".
880 * @fmt: The printf()'s format string, followed by parameters.
882 void tomoyo_warn_log(struct tomoyo_request_info *r, const char *fmt, ...)
886 const struct tomoyo_domain_info * const domain = r->domain;
887 const struct tomoyo_profile *profile = tomoyo_profile(domain->profile);
889 case TOMOYO_CONFIG_ENFORCING:
890 if (!profile->enforcing->enforcing_verbose)
893 case TOMOYO_CONFIG_PERMISSIVE:
894 if (!profile->permissive->permissive_verbose)
897 case TOMOYO_CONFIG_LEARNING:
898 if (!profile->learning->learning_verbose)
902 buffer = kmalloc(4096, GFP_NOFS);
906 vsnprintf(buffer, 4095, fmt, args);
909 printk(KERN_WARNING "%s: Access %s denied for %s\n",
910 r->mode == TOMOYO_CONFIG_ENFORCING ? "ERROR" : "WARNING", buffer,
911 tomoyo_last_word(domain->domainname->name));
916 * tomoyo_domain_quota_is_ok - Check for domain's quota.
918 * @r: Pointer to "struct tomoyo_request_info".
920 * Returns true if the domain is not exceeded quota, false otherwise.
922 * Caller holds tomoyo_read_lock().
924 bool tomoyo_domain_quota_is_ok(struct tomoyo_request_info *r)
926 unsigned int count = 0;
927 struct tomoyo_domain_info *domain = r->domain;
928 struct tomoyo_acl_info *ptr;
930 if (r->mode != TOMOYO_CONFIG_LEARNING)
934 list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
940 case TOMOYO_TYPE_PATH_ACL:
941 perm = container_of(ptr, struct tomoyo_path_acl, head)
944 case TOMOYO_TYPE_PATH2_ACL:
945 perm = container_of(ptr, struct tomoyo_path2_acl, head)
948 case TOMOYO_TYPE_PATH_NUMBER_ACL:
949 perm = container_of(ptr, struct tomoyo_path_number_acl,
952 case TOMOYO_TYPE_MKDEV_ACL:
953 perm = container_of(ptr, struct tomoyo_mkdev_acl,
959 for (i = 0; i < 16; i++)
963 if (count < tomoyo_profile(domain->profile)->learning->
966 if (!domain->quota_warned) {
967 domain->quota_warned = true;
968 printk(KERN_WARNING "TOMOYO-WARNING: "
969 "Domain '%s' has so many ACLs to hold. "
970 "Stopped learning mode.\n", domain->domainname->name);