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 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_is_correct_path(filename, 0, 0, 0))
94 if (filename[0] == '@') {
95 ptr->group = tomoyo_get_path_group(filename + 1);
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_is_correct_path(data, 0, 0, 0))
120 num->group = tomoyo_get_number_group(data + 1);
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_is_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_is_byte_range(const char *str)
156 return *str >= '0' && *str++ <= '3' &&
157 *str >= '0' && *str++ <= '7' &&
158 *str >= '0' && *str <= '7';
162 * tomoyo_is_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_is_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_is_invalid(*sp))
232 while (tomoyo_is_valid(*sp))
234 while (tomoyo_is_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_is_correct_path - Validate a pathname.
270 * @filename: The pathname to check.
271 * @start_type: Should the pathname start with '/'?
272 * 1 = must / -1 = must not / 0 = don't care
273 * @pattern_type: Can the pathname contain a wildcard?
274 * 1 = must / -1 = must not / 0 = don't care
275 * @end_type: Should the pathname end with '/'?
276 * 1 = must / -1 = must not / 0 = don't care
278 * Check whether the given filename follows the naming rules.
279 * Returns true if @filename follows the naming rules, false otherwise.
281 bool tomoyo_is_correct_path(const char *filename, const s8 start_type,
282 const s8 pattern_type, const s8 end_type)
284 const char *const start = filename;
285 bool in_repetition = false;
286 bool contains_pattern = false;
294 if (start_type == 1) { /* Must start with '/' */
297 } else if (start_type == -1) { /* Must not start with '/' */
302 c = *(filename + strlen(filename) - 1);
303 if (end_type == 1) { /* Must end with '/' */
306 } else if (end_type == -1) { /* Must not end with '/' */
317 case '\\': /* "\\" */
329 if (pattern_type == -1)
330 break; /* Must not contain pattern */
331 contains_pattern = true;
333 case '{': /* "/\{" */
334 if (filename - 3 < start ||
335 *(filename - 3) != '/')
337 if (pattern_type == -1)
338 break; /* Must not contain pattern */
339 contains_pattern = true;
340 in_repetition = true;
342 case '}': /* "\}/" */
343 if (*filename != '/')
347 in_repetition = false;
349 case '0': /* "\ooo" */
354 if (d < '0' || d > '7')
357 if (e < '0' || e > '7')
359 c = tomoyo_make_byte(c, d, e);
360 if (tomoyo_is_invalid(c))
361 continue; /* pattern is not \000 */
364 } else if (in_repetition && c == '/') {
366 } else if (tomoyo_is_invalid(c)) {
370 if (pattern_type == 1) { /* Must contain pattern */
371 if (!contains_pattern)
382 * tomoyo_is_correct_domain - Check whether the given domainname follows the naming rules.
384 * @domainname: The domainname to check.
386 * Returns true if @domainname follows the naming rules, false otherwise.
388 bool tomoyo_is_correct_domain(const unsigned char *domainname)
394 if (!domainname || strncmp(domainname, TOMOYO_ROOT_NAME,
395 TOMOYO_ROOT_NAME_LEN))
397 domainname += TOMOYO_ROOT_NAME_LEN;
401 if (*domainname++ != ' ')
403 if (*domainname++ != '/')
405 while ((c = *domainname) != '\0' && c != ' ') {
410 case '\\': /* "\\" */
412 case '0': /* "\ooo" */
417 if (d < '0' || d > '7')
420 if (e < '0' || e > '7')
422 c = tomoyo_make_byte(c, d, e);
423 if (tomoyo_is_invalid(c))
424 /* pattern is not \000 */
428 } else if (tomoyo_is_invalid(c)) {
432 } while (*domainname);
439 * tomoyo_is_domain_def - Check whether the given token can be a domainname.
441 * @buffer: The token to check.
443 * Returns true if @buffer possibly be a domainname, false otherwise.
445 bool tomoyo_is_domain_def(const unsigned char *buffer)
447 return !strncmp(buffer, TOMOYO_ROOT_NAME, TOMOYO_ROOT_NAME_LEN);
451 * tomoyo_find_domain - Find a domain by the given name.
453 * @domainname: The domainname to find.
455 * Returns pointer to "struct tomoyo_domain_info" if found, NULL otherwise.
457 * Caller holds tomoyo_read_lock().
459 struct tomoyo_domain_info *tomoyo_find_domain(const char *domainname)
461 struct tomoyo_domain_info *domain;
462 struct tomoyo_path_info name;
464 name.name = domainname;
465 tomoyo_fill_path_info(&name);
466 list_for_each_entry_rcu(domain, &tomoyo_domain_list, list) {
467 if (!domain->is_deleted &&
468 !tomoyo_pathcmp(&name, domain->domainname))
475 * tomoyo_const_part_length - Evaluate the initial length without a pattern in a token.
477 * @filename: The string to evaluate.
479 * Returns the initial length without a pattern in @filename.
481 static int tomoyo_const_part_length(const char *filename)
488 while ((c = *filename++) != '\0') {
495 case '\\': /* "\\" */
498 case '0': /* "\ooo" */
503 if (c < '0' || c > '7')
506 if (c < '0' || c > '7')
517 * tomoyo_fill_path_info - Fill in "struct tomoyo_path_info" members.
519 * @ptr: Pointer to "struct tomoyo_path_info" to fill in.
521 * The caller sets "struct tomoyo_path_info"->name.
523 void tomoyo_fill_path_info(struct tomoyo_path_info *ptr)
525 const char *name = ptr->name;
526 const int len = strlen(name);
528 ptr->const_len = tomoyo_const_part_length(name);
529 ptr->is_dir = len && (name[len - 1] == '/');
530 ptr->is_patterned = (ptr->const_len < len);
531 ptr->hash = full_name_hash(name, len);
535 * tomoyo_file_matches_pattern2 - Pattern matching without '/' character and "\-" pattern.
537 * @filename: The start of string to check.
538 * @filename_end: The end of string to check.
539 * @pattern: The start of pattern to compare.
540 * @pattern_end: The end of pattern to compare.
542 * Returns true if @filename matches @pattern, false otherwise.
544 static bool tomoyo_file_matches_pattern2(const char *filename,
545 const char *filename_end,
547 const char *pattern_end)
549 while (filename < filename_end && pattern < pattern_end) {
551 if (*pattern != '\\') {
552 if (*filename++ != *pattern++)
564 } else if (c == '\\') {
565 if (filename[1] == '\\')
567 else if (tomoyo_is_byte_range(filename + 1))
576 if (*++filename != '\\')
588 if (!tomoyo_is_alphabet_char(c))
595 if (c == '\\' && tomoyo_is_byte_range(filename + 1)
596 && strncmp(filename + 1, pattern, 3) == 0) {
601 return false; /* Not matched. */
604 for (i = 0; i <= filename_end - filename; i++) {
605 if (tomoyo_file_matches_pattern2(
606 filename + i, filename_end,
607 pattern + 1, pattern_end))
610 if (c == '.' && *pattern == '@')
614 if (filename[i + 1] == '\\')
616 else if (tomoyo_is_byte_range(filename + i + 1))
619 break; /* Bad pattern. */
621 return false; /* Not matched. */
626 while (isdigit(filename[j]))
628 } else if (c == 'X') {
629 while (isxdigit(filename[j]))
631 } else if (c == 'A') {
632 while (tomoyo_is_alphabet_char(filename[j]))
635 for (i = 1; i <= j; i++) {
636 if (tomoyo_file_matches_pattern2(
637 filename + i, filename_end,
638 pattern + 1, pattern_end))
641 return false; /* Not matched or bad pattern. */
646 while (*pattern == '\\' &&
647 (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
649 return filename == filename_end && pattern == pattern_end;
653 * tomoyo_file_matches_pattern - Pattern matching without '/' character.
655 * @filename: The start of string to check.
656 * @filename_end: The end of string to check.
657 * @pattern: The start of pattern to compare.
658 * @pattern_end: The end of pattern to compare.
660 * Returns true if @filename matches @pattern, false otherwise.
662 static bool tomoyo_file_matches_pattern(const char *filename,
663 const char *filename_end,
665 const char *pattern_end)
667 const char *pattern_start = pattern;
671 while (pattern < pattern_end - 1) {
672 /* Split at "\-" pattern. */
673 if (*pattern++ != '\\' || *pattern++ != '-')
675 result = tomoyo_file_matches_pattern2(filename,
684 pattern_start = pattern;
686 result = tomoyo_file_matches_pattern2(filename, filename_end,
687 pattern_start, pattern_end);
688 return first ? result : !result;
692 * tomoyo_path_matches_pattern2 - Do pathname pattern matching.
694 * @f: The start of string to check.
695 * @p: The start of pattern to compare.
697 * Returns true if @f matches @p, false otherwise.
699 static bool tomoyo_path_matches_pattern2(const char *f, const char *p)
701 const char *f_delimiter;
702 const char *p_delimiter;
705 f_delimiter = strchr(f, '/');
707 f_delimiter = f + strlen(f);
708 p_delimiter = strchr(p, '/');
710 p_delimiter = p + strlen(p);
711 if (*p == '\\' && *(p + 1) == '{')
713 if (!tomoyo_file_matches_pattern(f, f_delimiter, p,
723 /* Ignore trailing "\*" and "\@" in @pattern. */
725 (*(p + 1) == '*' || *(p + 1) == '@'))
730 * The "\{" pattern is permitted only after '/' character.
731 * This guarantees that below "*(p - 1)" is safe.
732 * Also, the "\}" pattern is permitted only before '/' character
733 * so that "\{" + "\}" pair will not break the "\-" operator.
735 if (*(p - 1) != '/' || p_delimiter <= p + 3 || *p_delimiter != '/' ||
736 *(p_delimiter - 1) != '}' || *(p_delimiter - 2) != '\\')
737 return false; /* Bad pattern. */
739 /* Compare current component with pattern. */
740 if (!tomoyo_file_matches_pattern(f, f_delimiter, p + 2,
743 /* Proceed to next component. */
748 /* Continue comparison. */
749 if (tomoyo_path_matches_pattern2(f, p_delimiter + 1))
751 f_delimiter = strchr(f, '/');
752 } while (f_delimiter);
753 return false; /* Not matched. */
757 * tomoyo_path_matches_pattern - Check whether the given filename matches the given pattern.
759 * @filename: The filename to check.
760 * @pattern: The pattern to compare.
762 * Returns true if matches, false otherwise.
764 * The following patterns are available.
766 * \ooo Octal representation of a byte.
767 * \* Zero or more repetitions of characters other than '/'.
768 * \@ Zero or more repetitions of characters other than '/' or '.'.
769 * \? 1 byte character other than '/'.
770 * \$ One or more repetitions of decimal digits.
771 * \+ 1 decimal digit.
772 * \X One or more repetitions of hexadecimal digits.
773 * \x 1 hexadecimal digit.
774 * \A One or more repetitions of alphabet characters.
775 * \a 1 alphabet character.
777 * \- Subtraction operator.
779 * /\{dir\}/ '/' + 'One or more repetitions of dir/' (e.g. /dir/ /dir/dir/
782 bool tomoyo_path_matches_pattern(const struct tomoyo_path_info *filename,
783 const struct tomoyo_path_info *pattern)
785 const char *f = filename->name;
786 const char *p = pattern->name;
787 const int len = pattern->const_len;
789 /* If @pattern doesn't contain pattern, I can use strcmp(). */
790 if (!pattern->is_patterned)
791 return !tomoyo_pathcmp(filename, pattern);
792 /* Don't compare directory and non-directory. */
793 if (filename->is_dir != pattern->is_dir)
795 /* Compare the initial length without patterns. */
796 if (strncmp(f, p, len))
800 return tomoyo_path_matches_pattern2(f, p);
804 * tomoyo_get_exe - Get tomoyo_realpath() of current process.
806 * Returns the tomoyo_realpath() of current process on success, NULL otherwise.
808 * This function uses kzalloc(), so the caller must call kfree()
809 * if this function didn't return NULL.
811 const char *tomoyo_get_exe(void)
813 struct mm_struct *mm = current->mm;
814 struct vm_area_struct *vma;
815 const char *cp = NULL;
819 down_read(&mm->mmap_sem);
820 for (vma = mm->mmap; vma; vma = vma->vm_next) {
821 if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
822 cp = tomoyo_realpath_from_path(&vma->vm_file->f_path);
826 up_read(&mm->mmap_sem);
831 * tomoyo_init_request_info - Initialize "struct tomoyo_request_info" members.
833 * @r: Pointer to "struct tomoyo_request_info" to initialize.
834 * @domain: Pointer to "struct tomoyo_domain_info". NULL for tomoyo_domain().
838 int tomoyo_init_request_info(struct tomoyo_request_info *r,
839 struct tomoyo_domain_info *domain)
841 memset(r, 0, sizeof(*r));
843 domain = tomoyo_domain();
845 r->mode = tomoyo_check_flags(domain, TOMOYO_MAC_FOR_FILE);
850 * tomoyo_warn_log - Print warning or error message on console.
852 * @r: Pointer to "struct tomoyo_request_info".
853 * @fmt: The printf()'s format string, followed by parameters.
855 void tomoyo_warn_log(struct tomoyo_request_info *r, const char *fmt, ...)
860 if (!tomoyo_verbose_mode(r->domain))
864 buffer = kmalloc(len, GFP_NOFS);
868 len2 = vsnprintf(buffer, len - 1, fmt, args);
870 if (len2 <= len - 1) {
877 printk(KERN_WARNING "TOMOYO-%s: Access %s denied for %s\n",
878 r->mode == TOMOYO_CONFIG_ENFORCING ? "ERROR" : "WARNING",
879 buffer, tomoyo_get_last_name(r->domain));
884 * tomoyo_domain_quota_is_ok - Check for domain's quota.
886 * @r: Pointer to "struct tomoyo_request_info".
888 * Returns true if the domain is not exceeded quota, false otherwise.
890 * Caller holds tomoyo_read_lock().
892 bool tomoyo_domain_quota_is_ok(struct tomoyo_request_info *r)
894 unsigned int count = 0;
895 struct tomoyo_domain_info *domain = r->domain;
896 struct tomoyo_acl_info *ptr;
898 if (r->mode != TOMOYO_CONFIG_LEARNING)
902 list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
906 case TOMOYO_TYPE_PATH_ACL:
907 perm = container_of(ptr, struct tomoyo_path_acl, head)
909 for (i = 0; i < TOMOYO_MAX_PATH_OPERATION; i++)
912 if (perm & (1 << TOMOYO_TYPE_READ_WRITE))
915 case TOMOYO_TYPE_PATH2_ACL:
916 perm = container_of(ptr, struct tomoyo_path2_acl, head)
918 for (i = 0; i < TOMOYO_MAX_PATH2_OPERATION; i++)
922 case TOMOYO_TYPE_PATH_NUMBER_ACL:
923 perm = container_of(ptr, struct tomoyo_path_number_acl,
925 for (i = 0; i < TOMOYO_MAX_PATH_NUMBER_OPERATION; i++)
929 case TOMOYO_TYPE_PATH_NUMBER3_ACL:
930 perm = container_of(ptr, struct tomoyo_path_number3_acl,
932 for (i = 0; i < TOMOYO_MAX_PATH_NUMBER3_OPERATION; i++)
936 case TOMOYO_TYPE_MOUNT_ACL:
937 if (!container_of(ptr, struct tomoyo_mount_acl, head)->
942 if (count < tomoyo_check_flags(domain, TOMOYO_MAX_ACCEPT_ENTRY))
944 if (!domain->quota_warned) {
945 domain->quota_warned = true;
946 printk(KERN_WARNING "TOMOYO-WARNING: "
947 "Domain '%s' has so many ACLs to hold. "
948 "Stopped learning mode.\n", domain->domainname->name);