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 value type on success, 0 otherwise.
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);
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);
97 return ptr->group != NULL;
99 ptr->filename = tomoyo_get_name(filename);
100 ptr->is_group = false;
101 return ptr->filename != NULL;
105 * tomoyo_parse_number_union - Parse a tomoyo_number_union.
107 * @data: Number or number range or number group.
108 * @ptr: Pointer to "struct tomoyo_number_union".
110 * Returns true on success, false otherwise.
112 bool tomoyo_parse_number_union(char *data, struct tomoyo_number_union *num)
116 memset(num, 0, sizeof(*num));
117 if (data[0] == '@') {
118 if (!tomoyo_correct_word(data))
120 num->group = tomoyo_get_group(data + 1, TOMOYO_NUMBER_GROUP);
121 num->is_group = true;
122 return num->group != NULL;
124 type = tomoyo_parse_ulong(&v, &data);
128 num->min_type = type;
131 num->max_type = type;
136 type = tomoyo_parse_ulong(&v, &data);
140 num->max_type = type;
145 * tomoyo_byte_range - Check whether the string is a \ooo style octal value.
147 * @str: Pointer to the string.
149 * Returns true if @str is a \ooo style octal value, false otherwise.
151 * TOMOYO uses \ooo style representation for 0x01 - 0x20 and 0x7F - 0xFF.
152 * This function verifies that \ooo is in valid range.
154 static inline bool tomoyo_byte_range(const char *str)
156 return *str >= '0' && *str++ <= '3' &&
157 *str >= '0' && *str++ <= '7' &&
158 *str >= '0' && *str <= '7';
162 * tomoyo_alphabet_char - Check whether the character is an alphabet.
164 * @c: The character to check.
166 * Returns true if @c is an alphabet character, false otherwise.
168 static inline bool tomoyo_alphabet_char(const char c)
170 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
174 * tomoyo_make_byte - Make byte value from three octal characters.
176 * @c1: The first character.
177 * @c2: The second character.
178 * @c3: The third character.
180 * Returns byte value.
182 static inline u8 tomoyo_make_byte(const u8 c1, const u8 c2, const u8 c3)
184 return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
188 * tomoyo_str_starts - Check whether the given string starts with the given keyword.
190 * @src: Pointer to pointer to the string.
191 * @find: Pointer to the keyword.
193 * Returns true if @src starts with @find, false otherwise.
195 * The @src is updated to point the first character after the @find
196 * if @src starts with @find.
198 bool tomoyo_str_starts(char **src, const char *find)
200 const int len = strlen(find);
203 if (strncmp(tmp, find, len))
211 * tomoyo_normalize_line - Format string.
213 * @buffer: The line to normalize.
215 * Leading and trailing whitespaces are removed.
216 * Multiple whitespaces are packed into single space.
220 void tomoyo_normalize_line(unsigned char *buffer)
222 unsigned char *sp = buffer;
223 unsigned char *dp = buffer;
226 while (tomoyo_invalid(*sp))
232 while (tomoyo_valid(*sp))
234 while (tomoyo_invalid(*sp))
241 * tomoyo_tokenize - Tokenize string.
243 * @buffer: The line to tokenize.
244 * @w: Pointer to "char *".
247 * Returns true on success, false otherwise.
249 bool tomoyo_tokenize(char *buffer, char *w[], size_t size)
251 int count = size / sizeof(char *);
253 for (i = 0; i < count; i++)
255 for (i = 0; i < count; i++) {
256 char *cp = strchr(buffer, ' ');
264 return i < count || !*buffer;
268 * tomoyo_correct_word2 - Validate a string.
270 * @string: The string to check. May be non-'\0'-terminated.
271 * @len: Length of @string.
273 * Check whether the given string follows the naming rules.
274 * Returns true if @string follows the naming rules, false otherwise.
276 static bool tomoyo_correct_word2(const char *string, size_t len)
278 const char *const start = string;
279 bool in_repetition = false;
292 case '\\': /* "\\" */
305 case '{': /* "/\{" */
306 if (string - 3 < start || *(string - 3) != '/')
308 in_repetition = true;
310 case '}': /* "\}/" */
315 in_repetition = false;
317 case '0': /* "\ooo" */
321 if (!len-- || !len--)
325 if (d < '0' || d > '7' || e < '0' || e > '7')
327 c = tomoyo_make_byte(c, d, e);
328 if (tomoyo_invalid(c))
329 continue; /* pattern is not \000 */
332 } else if (in_repetition && c == '/') {
334 } else if (tomoyo_invalid(c)) {
346 * tomoyo_correct_word - Validate a string.
348 * @string: The string to check.
350 * Check whether the given string follows the naming rules.
351 * Returns true if @string follows the naming rules, false otherwise.
353 bool tomoyo_correct_word(const char *string)
355 return tomoyo_correct_word2(string, strlen(string));
359 * tomoyo_correct_path - Validate a pathname.
361 * @filename: The pathname to check.
363 * Check whether the given pathname follows the naming rules.
364 * Returns true if @filename follows the naming rules, false otherwise.
366 bool tomoyo_correct_path(const char *filename)
368 return *filename == '/' && tomoyo_correct_word(filename);
372 * tomoyo_correct_domain - Check whether the given domainname follows the naming rules.
374 * @domainname: The domainname to check.
376 * Returns true if @domainname follows the naming rules, false otherwise.
378 bool tomoyo_correct_domain(const unsigned char *domainname)
380 if (!domainname || strncmp(domainname, TOMOYO_ROOT_NAME,
381 TOMOYO_ROOT_NAME_LEN))
383 domainname += TOMOYO_ROOT_NAME_LEN;
386 if (*domainname++ != ' ')
389 const unsigned char *cp = strchr(domainname, ' ');
392 if (*domainname != '/' ||
393 !tomoyo_correct_word2(domainname, cp - domainname - 1))
397 return tomoyo_correct_path(domainname);
403 * tomoyo_domain_def - Check whether the given token can be a domainname.
405 * @buffer: The token to check.
407 * Returns true if @buffer possibly be a domainname, false otherwise.
409 bool tomoyo_domain_def(const unsigned char *buffer)
411 return !strncmp(buffer, TOMOYO_ROOT_NAME, TOMOYO_ROOT_NAME_LEN);
415 * tomoyo_find_domain - Find a domain by the given name.
417 * @domainname: The domainname to find.
419 * Returns pointer to "struct tomoyo_domain_info" if found, NULL otherwise.
421 * Caller holds tomoyo_read_lock().
423 struct tomoyo_domain_info *tomoyo_find_domain(const char *domainname)
425 struct tomoyo_domain_info *domain;
426 struct tomoyo_path_info name;
428 name.name = domainname;
429 tomoyo_fill_path_info(&name);
430 list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
431 if (!domain->is_deleted &&
432 !tomoyo_pathcmp(&name, domain->domainname))
439 * tomoyo_const_part_length - Evaluate the initial length without a pattern in a token.
441 * @filename: The string to evaluate.
443 * Returns the initial length without a pattern in @filename.
445 static int tomoyo_const_part_length(const char *filename)
452 while ((c = *filename++) != '\0') {
459 case '\\': /* "\\" */
462 case '0': /* "\ooo" */
467 if (c < '0' || c > '7')
470 if (c < '0' || c > '7')
481 * tomoyo_fill_path_info - Fill in "struct tomoyo_path_info" members.
483 * @ptr: Pointer to "struct tomoyo_path_info" to fill in.
485 * The caller sets "struct tomoyo_path_info"->name.
487 void tomoyo_fill_path_info(struct tomoyo_path_info *ptr)
489 const char *name = ptr->name;
490 const int len = strlen(name);
492 ptr->const_len = tomoyo_const_part_length(name);
493 ptr->is_dir = len && (name[len - 1] == '/');
494 ptr->is_patterned = (ptr->const_len < len);
495 ptr->hash = full_name_hash(name, len);
499 * tomoyo_file_matches_pattern2 - Pattern matching without '/' character and "\-" pattern.
501 * @filename: The start of string to check.
502 * @filename_end: The end of string to check.
503 * @pattern: The start of pattern to compare.
504 * @pattern_end: The end of pattern to compare.
506 * Returns true if @filename matches @pattern, false otherwise.
508 static bool tomoyo_file_matches_pattern2(const char *filename,
509 const char *filename_end,
511 const char *pattern_end)
513 while (filename < filename_end && pattern < pattern_end) {
515 if (*pattern != '\\') {
516 if (*filename++ != *pattern++)
528 } else if (c == '\\') {
529 if (filename[1] == '\\')
531 else if (tomoyo_byte_range(filename + 1))
540 if (*++filename != '\\')
552 if (!tomoyo_alphabet_char(c))
559 if (c == '\\' && tomoyo_byte_range(filename + 1)
560 && strncmp(filename + 1, pattern, 3) == 0) {
565 return false; /* Not matched. */
568 for (i = 0; i <= filename_end - filename; i++) {
569 if (tomoyo_file_matches_pattern2(
570 filename + i, filename_end,
571 pattern + 1, pattern_end))
574 if (c == '.' && *pattern == '@')
578 if (filename[i + 1] == '\\')
580 else if (tomoyo_byte_range(filename + i + 1))
583 break; /* Bad pattern. */
585 return false; /* Not matched. */
590 while (isdigit(filename[j]))
592 } else if (c == 'X') {
593 while (isxdigit(filename[j]))
595 } else if (c == 'A') {
596 while (tomoyo_alphabet_char(filename[j]))
599 for (i = 1; i <= j; i++) {
600 if (tomoyo_file_matches_pattern2(
601 filename + i, filename_end,
602 pattern + 1, pattern_end))
605 return false; /* Not matched or bad pattern. */
610 while (*pattern == '\\' &&
611 (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
613 return filename == filename_end && pattern == pattern_end;
617 * tomoyo_file_matches_pattern - Pattern matching without '/' character.
619 * @filename: The start of string to check.
620 * @filename_end: The end of string to check.
621 * @pattern: The start of pattern to compare.
622 * @pattern_end: The end of pattern to compare.
624 * Returns true if @filename matches @pattern, false otherwise.
626 static bool tomoyo_file_matches_pattern(const char *filename,
627 const char *filename_end,
629 const char *pattern_end)
631 const char *pattern_start = pattern;
635 while (pattern < pattern_end - 1) {
636 /* Split at "\-" pattern. */
637 if (*pattern++ != '\\' || *pattern++ != '-')
639 result = tomoyo_file_matches_pattern2(filename,
648 pattern_start = pattern;
650 result = tomoyo_file_matches_pattern2(filename, filename_end,
651 pattern_start, pattern_end);
652 return first ? result : !result;
656 * tomoyo_path_matches_pattern2 - Do pathname pattern matching.
658 * @f: The start of string to check.
659 * @p: The start of pattern to compare.
661 * Returns true if @f matches @p, false otherwise.
663 static bool tomoyo_path_matches_pattern2(const char *f, const char *p)
665 const char *f_delimiter;
666 const char *p_delimiter;
669 f_delimiter = strchr(f, '/');
671 f_delimiter = f + strlen(f);
672 p_delimiter = strchr(p, '/');
674 p_delimiter = p + strlen(p);
675 if (*p == '\\' && *(p + 1) == '{')
677 if (!tomoyo_file_matches_pattern(f, f_delimiter, p,
687 /* Ignore trailing "\*" and "\@" in @pattern. */
689 (*(p + 1) == '*' || *(p + 1) == '@'))
694 * The "\{" pattern is permitted only after '/' character.
695 * This guarantees that below "*(p - 1)" is safe.
696 * Also, the "\}" pattern is permitted only before '/' character
697 * so that "\{" + "\}" pair will not break the "\-" operator.
699 if (*(p - 1) != '/' || p_delimiter <= p + 3 || *p_delimiter != '/' ||
700 *(p_delimiter - 1) != '}' || *(p_delimiter - 2) != '\\')
701 return false; /* Bad pattern. */
703 /* Compare current component with pattern. */
704 if (!tomoyo_file_matches_pattern(f, f_delimiter, p + 2,
707 /* Proceed to next component. */
712 /* Continue comparison. */
713 if (tomoyo_path_matches_pattern2(f, p_delimiter + 1))
715 f_delimiter = strchr(f, '/');
716 } while (f_delimiter);
717 return false; /* Not matched. */
721 * tomoyo_path_matches_pattern - Check whether the given filename matches the given pattern.
723 * @filename: The filename to check.
724 * @pattern: The pattern to compare.
726 * Returns true if matches, false otherwise.
728 * The following patterns are available.
730 * \ooo Octal representation of a byte.
731 * \* Zero or more repetitions of characters other than '/'.
732 * \@ Zero or more repetitions of characters other than '/' or '.'.
733 * \? 1 byte character other than '/'.
734 * \$ One or more repetitions of decimal digits.
735 * \+ 1 decimal digit.
736 * \X One or more repetitions of hexadecimal digits.
737 * \x 1 hexadecimal digit.
738 * \A One or more repetitions of alphabet characters.
739 * \a 1 alphabet character.
741 * \- Subtraction operator.
743 * /\{dir\}/ '/' + 'One or more repetitions of dir/' (e.g. /dir/ /dir/dir/
746 bool tomoyo_path_matches_pattern(const struct tomoyo_path_info *filename,
747 const struct tomoyo_path_info *pattern)
749 const char *f = filename->name;
750 const char *p = pattern->name;
751 const int len = pattern->const_len;
753 /* If @pattern doesn't contain pattern, I can use strcmp(). */
754 if (!pattern->is_patterned)
755 return !tomoyo_pathcmp(filename, pattern);
756 /* Don't compare directory and non-directory. */
757 if (filename->is_dir != pattern->is_dir)
759 /* Compare the initial length without patterns. */
760 if (strncmp(f, p, len))
764 return tomoyo_path_matches_pattern2(f, p);
768 * tomoyo_get_exe - Get tomoyo_realpath() of current process.
770 * Returns the tomoyo_realpath() of current process on success, NULL otherwise.
772 * This function uses kzalloc(), so the caller must call kfree()
773 * if this function didn't return NULL.
775 const char *tomoyo_get_exe(void)
777 struct mm_struct *mm = current->mm;
778 struct vm_area_struct *vma;
779 const char *cp = NULL;
783 down_read(&mm->mmap_sem);
784 for (vma = mm->mmap; vma; vma = vma->vm_next) {
785 if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
786 cp = tomoyo_realpath_from_path(&vma->vm_file->f_path);
790 up_read(&mm->mmap_sem);
795 * tomoyo_get_mode - Get MAC mode.
797 * @profile: Profile number.
798 * @index: Index number of functionality.
802 int tomoyo_get_mode(const u8 profile, const u8 index)
805 const u8 category = TOMOYO_MAC_CATEGORY_FILE;
806 if (!tomoyo_policy_loaded)
807 return TOMOYO_CONFIG_DISABLED;
808 mode = tomoyo_profile(profile)->config[index];
809 if (mode == TOMOYO_CONFIG_USE_DEFAULT)
810 mode = tomoyo_profile(profile)->config[category];
811 if (mode == TOMOYO_CONFIG_USE_DEFAULT)
812 mode = tomoyo_profile(profile)->default_config;
817 * tomoyo_init_request_info - Initialize "struct tomoyo_request_info" members.
819 * @r: Pointer to "struct tomoyo_request_info" to initialize.
820 * @domain: Pointer to "struct tomoyo_domain_info". NULL for tomoyo_domain().
821 * @index: Index number of functionality.
825 int tomoyo_init_request_info(struct tomoyo_request_info *r,
826 struct tomoyo_domain_info *domain, const u8 index)
829 memset(r, 0, sizeof(*r));
831 domain = tomoyo_domain();
833 profile = domain->profile;
834 r->profile = profile;
836 r->mode = tomoyo_get_mode(profile, index);
841 * tomoyo_last_word - Get last component of a line.
845 * Returns the last word of a line.
847 const char *tomoyo_last_word(const char *name)
849 const char *cp = strrchr(name, ' ');
856 * tomoyo_warn_log - Print warning or error message on console.
858 * @r: Pointer to "struct tomoyo_request_info".
859 * @fmt: The printf()'s format string, followed by parameters.
861 void tomoyo_warn_log(struct tomoyo_request_info *r, const char *fmt, ...)
865 const struct tomoyo_domain_info * const domain = r->domain;
866 const struct tomoyo_profile *profile = tomoyo_profile(domain->profile);
868 case TOMOYO_CONFIG_ENFORCING:
869 if (!profile->enforcing->enforcing_verbose)
872 case TOMOYO_CONFIG_PERMISSIVE:
873 if (!profile->permissive->permissive_verbose)
876 case TOMOYO_CONFIG_LEARNING:
877 if (!profile->learning->learning_verbose)
881 buffer = kmalloc(4096, GFP_NOFS);
885 vsnprintf(buffer, 4095, fmt, args);
888 printk(KERN_WARNING "%s: Access %s denied for %s\n",
889 r->mode == TOMOYO_CONFIG_ENFORCING ? "ERROR" : "WARNING", buffer,
890 tomoyo_last_word(domain->domainname->name));
895 * tomoyo_domain_quota_is_ok - Check for domain's quota.
897 * @r: Pointer to "struct tomoyo_request_info".
899 * Returns true if the domain is not exceeded quota, false otherwise.
901 * Caller holds tomoyo_read_lock().
903 bool tomoyo_domain_quota_is_ok(struct tomoyo_request_info *r)
905 unsigned int count = 0;
906 struct tomoyo_domain_info *domain = r->domain;
907 struct tomoyo_acl_info *ptr;
909 if (r->mode != TOMOYO_CONFIG_LEARNING)
913 list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
919 case TOMOYO_TYPE_PATH_ACL:
920 perm = container_of(ptr, struct tomoyo_path_acl, head)
922 for (i = 0; i < TOMOYO_MAX_PATH_OPERATION; i++)
925 if (perm & (1 << TOMOYO_TYPE_READ_WRITE))
928 case TOMOYO_TYPE_PATH2_ACL:
929 perm = container_of(ptr, struct tomoyo_path2_acl, head)
931 for (i = 0; i < TOMOYO_MAX_PATH2_OPERATION; i++)
935 case TOMOYO_TYPE_PATH_NUMBER_ACL:
936 perm = container_of(ptr, struct tomoyo_path_number_acl,
938 for (i = 0; i < TOMOYO_MAX_PATH_NUMBER_OPERATION; i++)
942 case TOMOYO_TYPE_MKDEV_ACL:
943 perm = container_of(ptr, struct tomoyo_mkdev_acl,
945 for (i = 0; i < TOMOYO_MAX_MKDEV_OPERATION; i++)
953 if (count < tomoyo_profile(domain->profile)->learning->
956 if (!domain->quota_warned) {
957 domain->quota_warned = true;
958 printk(KERN_WARNING "TOMOYO-WARNING: "
959 "Domain '%s' has so many ACLs to hold. "
960 "Stopped learning mode.\n", domain->domainname->name);