オープンソース・ソフトウェアの開発とダウンロード

Subversion リポジトリの参照

Diff of /trunk/1.7.x/ccs-patch/security/ccsecurity/util.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/1.5.x/ccs-patch/fs/ccs_common.c revision 853 by kumaneko, Wed Jan 2 07:32:11 2008 UTC trunk/1.7.x/ccs-patch/security/ccsecurity/util.c revision 2951 by kumaneko, Tue Aug 25 04:26:20 2009 UTC
# Line 1  Line 1 
1  /*  /*
2   * fs/ccs_common.c   * security/ccsecurity/util.c
3   *   *
4   * Common functions for SAKURA and TOMOYO.   * Copyright (C) 2005-2009  NTT DATA CORPORATION
5   *   *
6   * Copyright (C) 2005-2008  NTT DATA CORPORATION   * Version: 1.7.0-pre   2009/08/24
  *  
  * Version: 1.5.3-pre   2008/01/02  
7   *   *
8   * This file is applicable to both 2.4.30 and 2.6.11 and later.   * This file is applicable to both 2.4.30 and 2.6.11 and later.
9   * See README.ccs for ChangeLog.   * See README.ccs for ChangeLog.
10   *   *
11   */   */
12    
13  #include <linux/string.h>  #include "internal.h"
 #include <linux/mm.h>  
 #include <linux/utime.h>  
 #include <linux/file.h>  
 #include <linux/module.h>  
 #include <linux/slab.h>  
 #include <asm/uaccess.h>  
 #include <stdarg.h>  
 #include <linux/version.h>  
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)  
 #include <linux/namei.h>  
 #include <linux/mount.h>  
 static const int lookup_flags = LOOKUP_FOLLOW;  
 #else  
 static const int lookup_flags = LOOKUP_FOLLOW | LOOKUP_POSITIVE;  
 #endif  
 #include <linux/realpath.h>  
 #include <linux/ccs_common.h>  
 #include <linux/ccs_proc.h>  
 #include <linux/tomoyo.h>  
14    
15  #ifdef CONFIG_TOMOYO_MAX_ACCEPT_ENTRY  /* Lock for protecting policy. */
16  #define MAX_ACCEPT_ENTRY (CONFIG_TOMOYO_MAX_ACCEPT_ENTRY)  DEFINE_MUTEX(ccs_policy_lock);
 #else  
 #define MAX_ACCEPT_ENTRY 2048  
 #endif  
 #ifdef CONFIG_TOMOYO_MAX_GRANT_LOG  
 #define MAX_GRANT_LOG (CONFIG_TOMOYO_MAX_GRANT_LOG)  
 #else  
 #define MAX_GRANT_LOG 1024  
 #endif  
 #ifdef CONFIG_TOMOYO_MAX_REJECT_LOG  
 #define MAX_REJECT_LOG (CONFIG_TOMOYO_MAX_REJECT_LOG)  
 #else  
 #define MAX_REJECT_LOG 1024  
 #endif  
17    
18  /*************************  VARIABLES  *************************/  /* Has /sbin/init started? */
19    bool ccs_policy_loaded;
20    
21  /* /sbin/init started? */  /* Profile table. Memory is allocated as needed. */
22  bool sbin_init_started = 0;  struct ccs_profile *ccs_profile_ptr[CCS_MAX_PROFILES];
23    
24    /* Index table for searching parent category. */
25    static const u8 ccs_index2category[CCS_MAX_MAC_INDEX +
26                                       CCS_MAX_CAPABILITY_INDEX] = {
27            [CCS_MAC_FILE_EXECUTE]    = CCS_MAC_CATEGORY_FILE,
28            [CCS_MAC_FILE_OPEN]       = CCS_MAC_CATEGORY_FILE,
29            [CCS_MAC_FILE_CREATE]     = CCS_MAC_CATEGORY_FILE,
30            [CCS_MAC_FILE_UNLINK]     = CCS_MAC_CATEGORY_FILE,
31            [CCS_MAC_FILE_MKDIR]      = CCS_MAC_CATEGORY_FILE,
32            [CCS_MAC_FILE_RMDIR]      = CCS_MAC_CATEGORY_FILE,
33            [CCS_MAC_FILE_MKFIFO]     = CCS_MAC_CATEGORY_FILE,
34            [CCS_MAC_FILE_MKSOCK]     = CCS_MAC_CATEGORY_FILE,
35            [CCS_MAC_FILE_TRUNCATE]   = CCS_MAC_CATEGORY_FILE,
36            [CCS_MAC_FILE_SYMLINK]    = CCS_MAC_CATEGORY_FILE,
37            [CCS_MAC_FILE_REWRITE]    = CCS_MAC_CATEGORY_FILE,
38            [CCS_MAC_FILE_MKBLOCK]    = CCS_MAC_CATEGORY_FILE,
39            [CCS_MAC_FILE_MKCHAR]     = CCS_MAC_CATEGORY_FILE,
40            [CCS_MAC_FILE_LINK]       = CCS_MAC_CATEGORY_FILE,
41            [CCS_MAC_FILE_RENAME]     = CCS_MAC_CATEGORY_FILE,
42            [CCS_MAC_FILE_CHMOD]      = CCS_MAC_CATEGORY_FILE,
43            [CCS_MAC_FILE_CHOWN]      = CCS_MAC_CATEGORY_FILE,
44            [CCS_MAC_FILE_CHGRP]      = CCS_MAC_CATEGORY_FILE,
45            [CCS_MAC_FILE_IOCTL]      = CCS_MAC_CATEGORY_FILE,
46            [CCS_MAC_FILE_CHROOT]     = CCS_MAC_CATEGORY_FILE,
47            [CCS_MAC_FILE_MOUNT]      = CCS_MAC_CATEGORY_FILE,
48            [CCS_MAC_FILE_UMOUNT]     = CCS_MAC_CATEGORY_FILE,
49            [CCS_MAC_FILE_PIVOT_ROOT] = CCS_MAC_CATEGORY_FILE,
50            [CCS_MAC_ENVIRON]         = CCS_MAC_CATEGORY_MISC,
51            [CCS_MAC_NETWORK_UDP_BIND]    = CCS_MAC_CATEGORY_NETWORK,
52            [CCS_MAC_NETWORK_UDP_CONNECT] = CCS_MAC_CATEGORY_NETWORK,
53            [CCS_MAC_NETWORK_TCP_BIND]    = CCS_MAC_CATEGORY_NETWORK,
54            [CCS_MAC_NETWORK_TCP_LISTEN]  = CCS_MAC_CATEGORY_NETWORK,
55            [CCS_MAC_NETWORK_TCP_CONNECT] = CCS_MAC_CATEGORY_NETWORK,
56            [CCS_MAC_NETWORK_TCP_ACCEPT]  = CCS_MAC_CATEGORY_NETWORK,
57            [CCS_MAC_NETWORK_RAW_BIND]    = CCS_MAC_CATEGORY_NETWORK,
58            [CCS_MAC_NETWORK_RAW_CONNECT] = CCS_MAC_CATEGORY_NETWORK,
59            [CCS_MAC_SIGNAL]          = CCS_MAC_CATEGORY_IPC,
60            [CCS_MAX_MAC_INDEX + CCS_INET_STREAM_SOCKET_CREATE]
61            = CCS_MAC_CATEGORY_CAPABILITY,
62            [CCS_MAX_MAC_INDEX + CCS_INET_STREAM_SOCKET_LISTEN]
63            = CCS_MAC_CATEGORY_CAPABILITY,
64            [CCS_MAX_MAC_INDEX + CCS_INET_STREAM_SOCKET_CONNECT]
65            = CCS_MAC_CATEGORY_CAPABILITY,
66            [CCS_MAX_MAC_INDEX + CCS_USE_INET_DGRAM_SOCKET]
67            = CCS_MAC_CATEGORY_CAPABILITY,
68            [CCS_MAX_MAC_INDEX + CCS_USE_INET_RAW_SOCKET]
69            = CCS_MAC_CATEGORY_CAPABILITY,
70            [CCS_MAX_MAC_INDEX + CCS_USE_ROUTE_SOCKET]
71            = CCS_MAC_CATEGORY_CAPABILITY,
72            [CCS_MAX_MAC_INDEX + CCS_USE_PACKET_SOCKET]
73            = CCS_MAC_CATEGORY_CAPABILITY,
74            [CCS_MAX_MAC_INDEX + CCS_SYS_MOUNT]
75            = CCS_MAC_CATEGORY_CAPABILITY,
76            [CCS_MAX_MAC_INDEX + CCS_SYS_UMOUNT]
77            = CCS_MAC_CATEGORY_CAPABILITY,
78            [CCS_MAX_MAC_INDEX + CCS_SYS_REBOOT]
79            = CCS_MAC_CATEGORY_CAPABILITY,
80            [CCS_MAX_MAC_INDEX + CCS_SYS_CHROOT]
81            = CCS_MAC_CATEGORY_CAPABILITY,
82            [CCS_MAX_MAC_INDEX + CCS_SYS_KILL]
83            = CCS_MAC_CATEGORY_CAPABILITY,
84            [CCS_MAX_MAC_INDEX + CCS_SYS_VHANGUP]
85            = CCS_MAC_CATEGORY_CAPABILITY,
86            [CCS_MAX_MAC_INDEX + CCS_SYS_SETTIME]
87            = CCS_MAC_CATEGORY_CAPABILITY,
88            [CCS_MAX_MAC_INDEX + CCS_SYS_NICE]
89            = CCS_MAC_CATEGORY_CAPABILITY,
90            [CCS_MAX_MAC_INDEX + CCS_SYS_SETHOSTNAME]
91            = CCS_MAC_CATEGORY_CAPABILITY,
92            [CCS_MAX_MAC_INDEX + CCS_USE_KERNEL_MODULE]
93            = CCS_MAC_CATEGORY_CAPABILITY,
94            [CCS_MAX_MAC_INDEX + CCS_CREATE_FIFO]
95            = CCS_MAC_CATEGORY_CAPABILITY,
96            [CCS_MAX_MAC_INDEX + CCS_CREATE_BLOCK_DEV]
97            = CCS_MAC_CATEGORY_CAPABILITY,
98            [CCS_MAX_MAC_INDEX + CCS_CREATE_CHAR_DEV]
99            = CCS_MAC_CATEGORY_CAPABILITY,
100            [CCS_MAX_MAC_INDEX + CCS_CREATE_UNIX_SOCKET]
101            = CCS_MAC_CATEGORY_CAPABILITY,
102            [CCS_MAX_MAC_INDEX + CCS_SYS_LINK]
103            = CCS_MAC_CATEGORY_CAPABILITY,
104            [CCS_MAX_MAC_INDEX + CCS_SYS_SYMLINK]
105            = CCS_MAC_CATEGORY_CAPABILITY,
106            [CCS_MAX_MAC_INDEX + CCS_SYS_RENAME]
107            = CCS_MAC_CATEGORY_CAPABILITY,
108            [CCS_MAX_MAC_INDEX + CCS_SYS_UNLINK]
109            = CCS_MAC_CATEGORY_CAPABILITY,
110            [CCS_MAX_MAC_INDEX + CCS_SYS_CHMOD]
111            = CCS_MAC_CATEGORY_CAPABILITY,
112            [CCS_MAX_MAC_INDEX + CCS_SYS_CHOWN]
113            = CCS_MAC_CATEGORY_CAPABILITY,
114            [CCS_MAX_MAC_INDEX + CCS_SYS_IOCTL]
115            = CCS_MAC_CATEGORY_CAPABILITY,
116            [CCS_MAX_MAC_INDEX + CCS_SYS_KEXEC_LOAD]
117            = CCS_MAC_CATEGORY_CAPABILITY,
118            [CCS_MAX_MAC_INDEX + CCS_SYS_PIVOT_ROOT]
119            = CCS_MAC_CATEGORY_CAPABILITY,
120            [CCS_MAX_MAC_INDEX + CCS_SYS_PTRACE]
121            = CCS_MAC_CATEGORY_CAPABILITY,
122            [CCS_MAX_MAC_INDEX + CCS_CONCEAL_MOUNT]
123            = CCS_MAC_CATEGORY_CAPABILITY,
124    };
125    
126  const char *ccs_log_level = KERN_DEBUG;  /* Utility functions. */
127    
128  static struct {  /**
129          const char *keyword;   * ccs_parse_ulong - Parse an "unsigned long" value.
130          unsigned int current_value;   *
131          const unsigned int max_value;   * @result: Pointer to "unsigned long".
132  } ccs_control_array[CCS_MAX_CONTROL_INDEX] = {   * @str:    Pointer to string to parse.
133          [CCS_PROFILE_COMMENT]            = { "COMMENT",             0, 0 }, /* Reserved for string. */   *
134          [CCS_TOMOYO_MAC_FOR_FILE]        = { "MAC_FOR_FILE",        0, 3 },   * Returns value type on success, 0 otherwise.
135          [CCS_TOMOYO_MAC_FOR_ARGV0]       = { "MAC_FOR_ARGV0",       0, 3 },   *
136          [CCS_TOMOYO_MAC_FOR_ENV]         = { "MAC_FOR_ENV",         0, 3 },   * The @src is updated to point the first character after the value
137          [CCS_TOMOYO_MAC_FOR_NETWORK]     = { "MAC_FOR_NETWORK",     0, 3 },   * on success.
138          [CCS_TOMOYO_MAC_FOR_SIGNAL]      = { "MAC_FOR_SIGNAL",      0, 3 },   */
139          [CCS_SAKURA_DENY_CONCEAL_MOUNT]  = { "DENY_CONCEAL_MOUNT",  0, 3 },  u8 ccs_parse_ulong(unsigned long *result, char **str)
140          [CCS_SAKURA_RESTRICT_CHROOT]     = { "RESTRICT_CHROOT",     0, 3 },  {
141          [CCS_SAKURA_RESTRICT_MOUNT]      = { "RESTRICT_MOUNT",      0, 3 },          const char *cp = *str;
142          [CCS_SAKURA_RESTRICT_UNMOUNT]    = { "RESTRICT_UNMOUNT",    0, 3 },          char *ep;
143          [CCS_SAKURA_RESTRICT_PIVOT_ROOT] = { "RESTRICT_PIVOT_ROOT", 0, 3 },          int base = 10;
144          [CCS_SAKURA_RESTRICT_AUTOBIND]   = { "RESTRICT_AUTOBIND",   0, 1 },          if (*cp == '0') {
145          [CCS_TOMOYO_MAX_ACCEPT_ENTRY]    = { "MAX_ACCEPT_ENTRY",    MAX_ACCEPT_ENTRY, INT_MAX },                  char c = *(cp + 1);
146          [CCS_TOMOYO_MAX_GRANT_LOG]       = { "MAX_GRANT_LOG",       MAX_GRANT_LOG, INT_MAX },                  if (c == 'x' || c == 'X') {
147          [CCS_TOMOYO_MAX_REJECT_LOG]      = { "MAX_REJECT_LOG",      MAX_REJECT_LOG, INT_MAX },                          base = 16;
148          [CCS_TOMOYO_VERBOSE]             = { "TOMOYO_VERBOSE",      1, 1 },                          cp += 2;
149          [CCS_ALLOW_ENFORCE_GRACE]        = { "ALLOW_ENFORCE_GRACE", 0, 1 },                  } else if (c >= '0' && c <= '7') {
150          [CCS_SLEEP_PERIOD]               = { "SLEEP_PERIOD",        0, 3000 }, /* in 0.1 second */                          base = 8;
151          [CCS_TOMOYO_ALT_EXEC]            = { "ALT_EXEC",            0, 0 }, /* Reserved for string. */                          cp++;
152  };                  }
153            }
154            *result = simple_strtoul(cp, &ep, base);
155            if (cp == ep)
156                    return 0;
157            *str = ep;
158            switch (base) {
159            case 16:
160                    return CCS_VALUE_TYPE_HEXADECIMAL;
161            case 8:
162                    return CCS_VALUE_TYPE_OCTAL;
163            default:
164                    return CCS_VALUE_TYPE_DECIMAL;
165            }
166    }
167    
168  struct profile {  /**
169          unsigned int value[CCS_MAX_CONTROL_INDEX];   * ccs_print_ulong - Print an "unsigned long" value.
170          const struct path_info *comment;   *
171          const struct path_info *alt_exec;   * @buffer:     Pointer to buffer.
172  };   * @buffer_len: Size of @buffer.
173     * @value:      An "unsigned long" value.
174     * @type:       Type of @value.
175     *
176     * Returns nothing.
177     */
178    void ccs_print_ulong(char *buffer, const int buffer_len,
179                         const unsigned long value, const u8 type)
180    {
181            if (type == CCS_VALUE_TYPE_DECIMAL)
182                    snprintf(buffer, buffer_len, "%lu", value);
183            else if (type == CCS_VALUE_TYPE_OCTAL)
184                    snprintf(buffer, buffer_len, "0%lo", value);
185            else if (type == CCS_VALUE_TYPE_HEXADECIMAL)
186                    snprintf(buffer, buffer_len, "0x%lX", value);
187            else
188                    snprintf(buffer, buffer_len, "type(%u)", type);
189    }
190    
191  static struct profile *profile_ptr[MAX_PROFILES];  /**
192     * ccs_parse_name_union - Parse a ccs_name_union.
193     *
194     * @filename: Name or name group.
195     * @ptr:      Pointer to "struct ccs_name_union".
196     *
197     * Returns true on success, false otherwise.
198     */
199    bool ccs_parse_name_union(const char *filename, struct ccs_name_union *ptr)
200    {
201            if (!ccs_is_correct_path(filename, 0, 0, 0))
202                    return false;
203            if (filename[0] == '@') {
204                    ptr->group = ccs_get_path_group(filename + 1);
205                    ptr->is_group = true;
206                    return ptr->group != NULL;
207            }
208            ptr->filename = ccs_get_name(filename);
209            ptr->is_group = false;
210            return ptr->filename != NULL;
211    }
212    
213  /*************************  UTILITY FUNCTIONS  *************************/  /**
214     * ccs_parse_number_union - Parse a ccs_number_union.
215     *
216     * @data: Number or number range or number group.
217     * @ptr:  Pointer to "struct ccs_number_union".
218     *
219     * Returns true on success, false otherwise.
220     */
221    bool ccs_parse_number_union(char *data, struct ccs_number_union *num)
222    {
223            u8 type;
224            unsigned long v;
225            memset(num, 0, sizeof(*num));
226            if (data[0] == '@') {
227                    if (!ccs_is_correct_path(data, 0, 0, 0))
228                            return false;
229                    num->group = ccs_get_number_group(data + 1);
230                    num->is_group = true;
231                    return num->group != NULL;
232            }
233            type = ccs_parse_ulong(&v, &data);
234            if (!type)
235                    return false;
236            num->values[0] = v;
237            num->min_type = type;
238            if (!*data) {
239                    num->values[1] = v;
240                    num->max_type = type;
241                    return true;
242            }
243            if (*data++ != '-')
244                    return false;
245            type = ccs_parse_ulong(&v, &data);
246            if (!type || *data)
247                    return false;
248            num->values[1] = v;
249            num->max_type = type;
250            return true;
251    }
252    
253  #ifdef CONFIG_TOMOYO  /**
254  static int __init TOMOYO_Quiet_Setup(char *str)   * ccs_is_byte_range - Check whether the string isa \ooo style octal value.
255     *
256     * @str: Pointer to the string.
257     *
258     * Returns true if @str is a \ooo style octal value, false otherwise.
259     */
260    static inline bool ccs_is_byte_range(const char *str)
261  {  {
262          ccs_control_array[CCS_TOMOYO_VERBOSE].current_value = 0;          return *str >= '0' && *str++ <= '3' &&
263          return 0;                  *str >= '0' && *str++ <= '7' &&
264                    *str >= '0' && *str <= '7';
265  }  }
266    
267  __setup("TOMOYO_QUIET", TOMOYO_Quiet_Setup);  /**
268  #endif   * ccs_is_decimal - Check whether the character is a decimal character.
269     *
270     * @c: The character to check.
271     *
272     * Returns true if @c is a decimal character, false otherwise.
273     */
274    static inline bool ccs_is_decimal(const char c)
275    {
276            return c >= '0' && c <= '9';
277    }
278    
279  /* Am I root? */  /**
280  static int isRoot(void)   * ccs_is_hexadecimal - Check whether the character is a hexadecimal character.
281     *
282     * @c: The character to check.
283     *
284     * Returns true if @c is a hexadecimal character, false otherwise.
285     */
286    static inline bool ccs_is_hexadecimal(const char c)
287  {  {
288          return !current->uid && !current->euid;          return (c >= '0' && c <= '9') ||
289                    (c >= 'A' && c <= 'F') ||
290                    (c >= 'a' && c <= 'f');
291  }  }
292    
293  /*  /**
294   * Format string.   * ccs_is_alphabet_char - Check whether the character is an alphabet.
295     *
296     * @c: The character to check.
297     *
298     * Returns true if @c is an alphabet character, false otherwise.
299     */
300    static inline bool ccs_is_alphabet_char(const char c)
301    {
302            return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
303    }
304    
305    /**
306     * ccs_make_byte - Make byte value from three octal characters.
307     *
308     * @c1: The first character.
309     * @c2: The second character.
310     * @c3: The third character.
311     *
312     * Returns byte value.
313     */
314    static inline u8 ccs_make_byte(const u8 c1, const u8 c2, const u8 c3)
315    {
316            return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
317    }
318    
319    /**
320     * ccs_str_starts - Check whether the given string starts with the given keyword.
321     *
322     * @src:  Pointer to pointer to the string.
323     * @find: Pointer to the keyword.
324     *
325     * Returns true if @src starts with @find, false otherwise.
326     *
327     * The @src is updated to point the first character after the @find
328     * if @src starts with @find.
329     */
330    bool ccs_str_starts(char **src, const char *find)
331    {
332            const int len = strlen(find);
333            char *tmp = *src;
334            if (strncmp(tmp, find, len))
335                    return false;
336            tmp += len;
337            *src = tmp;
338            return true;
339    }
340    
341    /**
342     * ccs_normalize_line - Format string.
343     *
344     * @buffer: The line to normalize.
345     *
346   * Leading and trailing whitespaces are removed.   * Leading and trailing whitespaces are removed.
347   * Multiple whitespaces are packed into single space.   * Multiple whitespaces are packed into single space.
348     *
349     * Returns nothing.
350   */   */
351  static void NormalizeLine(unsigned char *buffer)  void ccs_normalize_line(unsigned char *buffer)
352  {  {
353          unsigned char *sp = buffer, *dp = buffer;          unsigned char *sp = buffer;
354          int first = 1;          unsigned char *dp = buffer;
355          while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;          bool first = true;
356            while (*sp && (*sp <= ' ' || *sp >= 127))
357                    sp++;
358          while (*sp) {          while (*sp) {
359                  if (!first) *dp++ = ' ';                  if (!first)
360                  first = 0;                          *dp++ = ' ';
361                  while (*sp > ' ' && *sp < 127) *dp++ = *sp++;                  first = false;
362                  while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;                  while (*sp > ' ' && *sp < 127)
363                            *dp++ = *sp++;
364                    while (*sp && (*sp <= ' ' || *sp >= 127))
365                            sp++;
366          }          }
367          *dp = '\0';          *dp = '\0';
368  }  }
369    
370  /*  /**
371   *  Check whether the given filename follows the naming rules.   * ccs_tokenize - Tokenize string.
372   *  Returns nonzero if follows, zero otherwise.   *
373     * @buffer: The line to tokenize.
374     * @w:      Pointer to "char *".
375     * @size:   Sizeof @w .
376     *
377     * Returns true on success, false otherwise.
378     */
379    bool ccs_tokenize(char *buffer, char *w[], size_t size)
380    {
381            int count = size / sizeof(char *);
382            int i;
383            for (i = 0; i < count; i++)
384                    w[i] = "";
385            for (i = 0; i < count; i++) {
386                    char *cp = strchr(buffer, ' ');
387                    if (cp)
388                            *cp = '\0';
389                    w[i] = buffer;
390                    if (!cp)
391                            break;
392                    buffer = cp + 1;
393            }
394            return i < count || !*buffer;
395    }
396    
397    /**
398     * ccs_is_correct_path - Validate a pathname.
399     * @filename:     The pathname to check.
400     * @start_type:   Should the pathname start with '/'?
401     *                1 = must / -1 = must not / 0 = don't care
402     * @pattern_type: Can the pathname contain a wildcard?
403     *                1 = must / -1 = must not / 0 = don't care
404     * @end_type:     Should the pathname end with '/'?
405     *                1 = must / -1 = must not / 0 = don't care
406     *
407     * Check whether the given filename follows the naming rules.
408     * Returns true if @filename follows the naming rules, false otherwise.
409   */   */
410  bool IsCorrectPath(const char *filename, const s8 start_type, const s8 pattern_type, const s8 end_type, const char *function)  bool ccs_is_correct_path(const char *filename, const s8 start_type,
411                             const s8 pattern_type, const s8 end_type)
412  {  {
413          int contains_pattern = 0;          bool contains_pattern = false;
414          char c, d, e;          unsigned char c;
415          const char *original_filename = filename;          unsigned char d;
416          if (!filename) goto out;          unsigned char e;
417            if (!filename)
418                    goto out;
419          c = *filename;          c = *filename;
420          if (start_type == 1) { /* Must start with '/' */          if (start_type == 1) { /* Must start with '/' */
421                  if (c != '/') goto out;                  if (c != '/')
422                            goto out;
423          } else if (start_type == -1) { /* Must not start with '/' */          } else if (start_type == -1) { /* Must not start with '/' */
424                  if (c == '/') goto out;                  if (c == '/')
425                            goto out;
426          }          }
427          if (c) c = * (strchr(filename, '\0') - 1);          if (c)
428                    c = *(filename + strlen(filename) - 1);
429          if (end_type == 1) { /* Must end with '/' */          if (end_type == 1) { /* Must end with '/' */
430                  if (c != '/') goto out;                  if (c != '/')
431                            goto out;
432          } else if (end_type == -1) { /* Must not end with '/' */          } else if (end_type == -1) { /* Must not end with '/' */
433                  if (c == '/') goto out;                  if (c == '/')
434                            goto out;
435          }          }
436          while ((c = *filename++) != '\0') {          while (1) {
437                    c = *filename++;
438                    if (!c)
439                            break;
440                  if (c == '\\') {                  if (c == '\\') {
441                          switch ((c = *filename++)) {                          c = *filename++;
442                            switch (c) {
443                          case '\\':  /* "\\" */                          case '\\':  /* "\\" */
444                                  continue;                                  continue;
445                          case '$':   /* "\$" */                          case '$':   /* "\$" */
# Line 164  bool IsCorrectPath(const char *filename, Line 452  bool IsCorrectPath(const char *filename,
452                          case 'a':   /* "\a" */                          case 'a':   /* "\a" */
453                          case 'A':   /* "\A" */                          case 'A':   /* "\A" */
454                          case '-':   /* "\-" */                          case '-':   /* "\-" */
455                                  if (pattern_type == -1) break; /* Must not contain pattern */                                  if (pattern_type == -1)
456                                  contains_pattern = 1;                                          break; /* Must not contain pattern */
457                                    contains_pattern = true;
458                                  continue;                                  continue;
459                          case '0':   /* "\ooo" */                          case '0':   /* "\ooo" */
460                          case '1':                          case '1':
461                          case '2':                          case '2':
462                          case '3':                          case '3':
463                                  if ((d = *filename++) >= '0' && d <= '7' && (e = *filename++) >= '0' && e <= '7') {                                  d = *filename++;
464                                          const unsigned char f =                                  if (d < '0' || d > '7')
465                                                  (((unsigned char) (c - '0')) << 6) +                                          break;
466                                                  (((unsigned char) (d - '0')) << 3) +                                  e = *filename++;
467                                                  (((unsigned char) (e - '0')));                                  if (e < '0' || e > '7')
468                                          if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                          break;
469                                  }                                  c = ccs_make_byte(c, d, e);
470                                    if (c && (c <= ' ' || c >= 127))
471                                            continue; /* pattern is not \000 */
472                          }                          }
473                          goto out;                          goto out;
474                  } else if (c <= ' ' || c >= 127) {                  } else if (c <= ' ' || c >= 127) {
# Line 185  bool IsCorrectPath(const char *filename, Line 476  bool IsCorrectPath(const char *filename,
476                  }                  }
477          }          }
478          if (pattern_type == 1) { /* Must contain pattern */          if (pattern_type == 1) { /* Must contain pattern */
479                  if (!contains_pattern) goto out;                  if (!contains_pattern)
480                            goto out;
481          }          }
482          return 1;          return true;
483   out:   out:
484          printk(KERN_DEBUG "%s: Invalid pathname '%s'\n", function, original_filename);          return false;
         return 0;  
485  }  }
486    
487  /*  /**
488   *  Check whether the given domainname follows the naming rules.   * ccs_is_correct_domain - Check whether the given domainname follows the naming rules.
489   *  Returns nonzero if follows, zero otherwise.   * @domainname:   The domainname to check.
490     *
491     * Returns true if @domainname follows the naming rules, false otherwise.
492   */   */
493  bool IsCorrectDomain(const unsigned char *domainname, const char *function)  bool ccs_is_correct_domain(const unsigned char *domainname)
494  {  {
495          unsigned char c, d, e;          unsigned char c;
496          const char *org_domainname = domainname;          unsigned char d;
497          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN)) goto out;          unsigned char e;
498            if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN))
499                    goto out;
500          domainname += ROOT_NAME_LEN;          domainname += ROOT_NAME_LEN;
501          if (!*domainname) return 1;          if (!*domainname)
502                    return true;
503          do {          do {
504                  if (*domainname++ != ' ') goto out;                  if (*domainname++ != ' ')
505                  if (*domainname++ != '/') goto out;                          goto out;
506                  while ((c = *domainname) != '\0' && c != ' ') {                  if (*domainname++ != '/')
507                            goto out;
508                    while (1) {
509                            c = *domainname;
510                            if (!c || c == ' ')
511                                    break;
512                          domainname++;                          domainname++;
513                          if (c == '\\') {                          if (c == '\\') {
514                                  switch ((c = *domainname++)) {                                  c = *domainname++;
515                                    switch ((c)) {
516                                  case '\\':  /* "\\" */                                  case '\\':  /* "\\" */
517                                          continue;                                          continue;
518                                  case '0':   /* "\ooo" */                                  case '0':   /* "\ooo" */
519                                  case '1':                                  case '1':
520                                  case '2':                                  case '2':
521                                  case '3':                                  case '3':
522                                          if ((d = *domainname++) >= '0' && d <= '7' && (e = *domainname++) >= '0' && e <= '7') {                                          d = *domainname++;
523                                                  const unsigned char f =                                          if (d < '0' || d > '7')
524                                                          (((unsigned char) (c - '0')) << 6) +                                                  break;
525                                                          (((unsigned char) (d - '0')) << 3) +                                          e = *domainname++;
526                                                          (((unsigned char) (e - '0')));                                          if (e < '0' || e > '7')
527                                                  if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                                  break;
528                                          }                                          c = ccs_make_byte(c, d, e);
529                                            if (c && (c <= ' ' || c >= 127))
530                                                    /* pattern is not \000 */
531                                                    continue;
532                                  }                                  }
533                                  goto out;                                  goto out;
534                          } else if (c < ' ' || c >= 127) {                          } else if (c < ' ' || c >= 127) {
# Line 231  bool IsCorrectDomain(const unsigned char Line 536  bool IsCorrectDomain(const unsigned char
536                          }                          }
537                  }                  }
538          } while (*domainname);          } while (*domainname);
539          return 1;          return true;
540   out:   out:
541          printk(KERN_DEBUG "%s: Invalid domainname '%s'\n", function, org_domainname);          return false;
         return 0;  
542  }  }
543    
544  bool IsDomainDef(const unsigned char *buffer)  /**
545     * ccs_is_domain_def - Check whether the given token can be a domainname.
546     *
547     * @buffer: The token to check.
548     *
549     * Returns true if @buffer possibly be a domainname, false otherwise.
550     */
551    bool ccs_is_domain_def(const unsigned char *buffer)
552  {  {
553          /* while (*buffer && (*buffer <= ' ' || *buffer >= 127)) buffer++; */          return !strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN);
         return strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN) == 0;  
554  }  }
555    
556  struct domain_info *FindDomain(const char *domainname0)  /**
557     * ccs_find_domain - Find a domain by the given name.
558     *
559     * @domainname: The domainname to find.
560     *
561     * Returns pointer to "struct ccs_domain_info" if found, NULL otherwise.
562     *
563     * Caller holds ccs_read_lock().
564     */
565    struct ccs_domain_info *ccs_find_domain(const char *domainname)
566  {  {
567          struct domain_info *domain;          struct ccs_domain_info *domain;
568          struct path_info domainname;          struct ccs_path_info name;
569          domainname.name = domainname0;          name.name = domainname;
570          fill_path_info(&domainname);          ccs_fill_path_info(&name);
571          list1_for_each_entry(domain, &domain_list, list) {          list_for_each_entry_rcu(domain, &ccs_domain_list, list) {
572                  if (!domain->is_deleted && !pathcmp(&domainname, domain->domainname)) return domain;                  if (!domain->is_deleted &&
573                        !ccs_pathcmp(&name, domain->domainname))
574                            return domain;
575          }          }
576          return NULL;          return NULL;
577  }  }
578    
579  static int PathDepth(const char *pathname)  /**
580     * ccs_path_depth - Evaluate the number of '/' in a string.
581     *
582     * @pathname: The string to evaluate.
583     *
584     * Returns path depth of the string.
585     *
586     * I score 2 for each of the '/' in the @pathname
587     * and score 1 if the @pathname ends with '/'.
588     */
589    static int ccs_path_depth(const char *pathname)
590  {  {
591          int i = 0;          int i = 0;
592          if (pathname) {          if (pathname) {
593                  char *ep = strchr(pathname, '\0');                  const char *ep = pathname + strlen(pathname);
594                  if (pathname < ep--) {                  if (pathname < ep--) {
595                          if (*ep != '/') i++;                          if (*ep != '/')
596                          while (pathname <= ep) if (*ep-- == '/') i += 2;                                  i++;
597                            while (pathname <= ep)
598                                    if (*ep-- == '/')
599                                            i += 2;
600                  }                  }
601          }          }
602          return i;          return i;
603  }  }
604    
605  static int const_part_length(const char *filename)  /**
606     * ccs_const_part_length - Evaluate the initial length without a pattern in a token.
607     *
608     * @filename: The string to evaluate.
609     *
610     * Returns the initial length without a pattern in @filename.
611     */
612    static int ccs_const_part_length(const char *filename)
613  {  {
614            char c;
615          int len = 0;          int len = 0;
616          if (filename) {          if (!filename)
617                  char c;                  return 0;
618                  while ((c = *filename++) != '\0') {          while (1) {
619                          if (c != '\\') { len++; continue; }                  c = *filename++;
620                          switch (c = *filename++) {                  if (!c)
                         case '\\':  /* "\\" */  
                                 len += 2; continue;  
                         case '0':   /* "\ooo" */  
                         case '1':  
                         case '2':  
                         case '3':  
                                 if ((c = *filename++) >= '0' && c <= '7' && (c = *filename++) >= '0' && c <= '7') { len += 4; continue; }  
                         }  
621                          break;                          break;
622                    if (c != '\\') {
623                            len++;
624                            continue;
625                    }
626                    c = *filename++;
627                    switch (c) {
628                    case '\\':  /* "\\" */
629                            len += 2;
630                            continue;
631                    case '0':   /* "\ooo" */
632                    case '1':
633                    case '2':
634                    case '3':
635                            c = *filename++;
636                            if (c < '0' || c > '7')
637                                    break;
638                            c = *filename++;
639                            if (c < '0' || c > '7')
640                                    break;
641                            len += 4;
642                            continue;
643                  }                  }
644                    break;
645          }          }
646          return len;          return len;
647  }  }
648    
649  void fill_path_info(struct path_info *ptr)  /**
650     * ccs_fill_path_info - Fill in "struct ccs_path_info" members.
651     *
652     * @ptr: Pointer to "struct ccs_path_info" to fill in.
653     *
654     * The caller sets "struct ccs_path_info"->name.
655     */
656    void ccs_fill_path_info(struct ccs_path_info *ptr)
657  {  {
658          const char *name = ptr->name;          const char *name = ptr->name;
659          const int len = strlen(name);          const int len = strlen(name);
660          ptr->total_len = len;          ptr->total_len = len;
661          ptr->const_len = const_part_length(name);          ptr->const_len = ccs_const_part_length(name);
662          ptr->is_dir = len && (name[len - 1] == '/');          ptr->is_dir = len && (name[len - 1] == '/');
663          ptr->is_patterned = (ptr->const_len < len);          ptr->is_patterned = (ptr->const_len < len);
664          ptr->hash = full_name_hash(name, len);          ptr->hash = full_name_hash(name, len);
665          ptr->depth = PathDepth(name);          ptr->depth = ccs_path_depth(name);
666  }  }
667    
668  static int FileMatchesToPattern2(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
669     * ccs_file_matches_pattern2 - Pattern matching without '/' character
670     * and "\-" pattern.
671     *
672     * @filename:     The start of string to check.
673     * @filename_end: The end of string to check.
674     * @pattern:      The start of pattern to compare.
675     * @pattern_end:  The end of pattern to compare.
676     *
677     * Returns true if @filename matches @pattern, false otherwise.
678     */
679    static bool ccs_file_matches_pattern2(const char *filename,
680                                          const char *filename_end,
681                                          const char *pattern,
682                                          const char *pattern_end)
683  {  {
684          while (filename < filename_end && pattern < pattern_end) {          while (filename < filename_end && pattern < pattern_end) {
685                    char c;
686                  if (*pattern != '\\') {                  if (*pattern != '\\') {
687                          if (*filename++ != *pattern++) return 0;                          if (*filename++ != *pattern++)
688                  } else {                                  return false;
689                          char c = *filename;                          continue;
690                          pattern++;                  }
691                          switch (*pattern) {                  c = *filename;
692                          case '?':                  pattern++;
693                                  if (c == '/') {                  switch (*pattern) {
694                                          return 0;                          int i;
695                                  } else if (c == '\\') {                          int j;
696                                          if ((c = filename[1]) == '\\') {                  case '?':
697                                                  filename++; /* safe because filename is \\ */                          if (c == '/') {
698                                          } else if (c >= '0' && c <= '3' && (c = filename[2]) >= '0' && c <= '7' && (c = filename[3]) >= '0' && c <= '7') {                                  return false;
699                                                  filename += 3; /* safe because filename is \ooo */                          } else if (c == '\\') {
700                                          } else {                                  if (filename[1] == '\\')
701                                                  return 0;                                          filename++;
702                                          }                                  else if (ccs_is_byte_range(filename + 1))
703                                  }                                          filename += 3;
704                                  break;                                  else
705                          case '\\':                                          return false;
706                                  if (c != '\\') return 0;                          }
707                                  if (*++filename != '\\') return 0; /* safe because *filename != '\0' */                          break;
708                                  break;                  case '\\':
709                          case '+':                          if (c != '\\')
710                                  if (c < '0' || c > '9') return 0;                                  return false;
711                                  break;                          if (*++filename != '\\')
712                          case 'x':                                  return false;
713                                  if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))) return 0;                          break;
714                                  break;                  case '+':
715                          case 'a':                          if (!ccs_is_decimal(c))
716                                  if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) return 0;                                  return false;
717                            break;
718                    case 'x':
719                            if (!ccs_is_hexadecimal(c))
720                                    return false;
721                            break;
722                    case 'a':
723                            if (!ccs_is_alphabet_char(c))
724                                    return false;
725                            break;
726                    case '0':
727                    case '1':
728                    case '2':
729                    case '3':
730                            if (c == '\\' && ccs_is_byte_range(filename + 1)
731                                && strncmp(filename + 1, pattern, 3) == 0) {
732                                    filename += 3;
733                                    pattern += 2;
734                                  break;                                  break;
735                          case '0':                          }
736                          case '1':                          return false; /* Not matched. */
737                          case '2':                  case '*':
738                          case '3':                  case '@':
739                                  if (c == '\\' && (c = filename[1]) >= '0' && c <= '3' && c == *pattern                          for (i = 0; i <= filename_end - filename; i++) {
740                                          && (c = filename[2]) >= '0' && c <= '7' && c == pattern[1]                                  if (ccs_file_matches_pattern2(filename + i,
741                                          && (c = filename[3]) >= '0' && c <= '7' && c == pattern[2]) {                                                                filename_end,
742                                          filename += 3; /* safe because filename is \ooo */                                                                pattern + 1,
743                                          pattern += 2; /* safe because pattern is \ooo  */                                                                pattern_end))
744                                            return true;
745                                    c = filename[i];
746                                    if (c == '.' && *pattern == '@')
747                                          break;                                          break;
748                                  }                                  if (c != '\\')
749                                  return 0; /* Not matched. */                                          continue;
750                          case '*':                                  if (filename[i + 1] == '\\')
751                          case '@':                                          i++;
752                                  {                                  else if (ccs_is_byte_range(filename + i + 1))
753                                          int i;                                          i += 3;
754                                          for (i = 0; i <= filename_end - filename; i++) {                                  else
755                                                  if (FileMatchesToPattern2(filename + i, filename_end, pattern + 1, pattern_end)) return 1;                                          break; /* Bad pattern. */
756                                                  if ((c = filename[i]) == '.' && *pattern == '@') break;                          }
757                                                  if (c == '\\') {                          return false; /* Not matched. */
758                                                          if ((c = filename[i + 1]) == '\\') {                  default:
759                                                                  i++; /* safe because filename is \\ */                          j = 0;
760                                                          } else if (c >= '0' && c <= '3' && (c = filename[i + 2]) >= '0' && c <= '7' && (c = filename[i + 3]) >= '0' && c <= '7') {                          c = *pattern;
761                                                                  i += 3; /* safe because filename is \ooo */                          if (c == '$') {
762                                                          } else {                                  while (ccs_is_decimal(filename[j]))
763                                                                  break; /* Bad pattern. */                                          j++;
764                                                          }                          } else if (c == 'X') {
765                                                  }                                  while (ccs_is_hexadecimal(filename[j]))
766                                          }                                          j++;
767                                          return 0; /* Not matched. */                          } else if (c == 'A') {
768                                  }                                  while (ccs_is_alphabet_char(filename[j]))
769                          default:                                          j++;
                                 {  
                                         int i, j = 0;  
                                         if ((c = *pattern) == '$') {  
                                                 while ((c = filename[j]) >= '0' && c <= '9') j++;  
                                         } else if (c == 'X') {  
                                                 while (((c = filename[j]) >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) j++;  
                                         } else if (c == 'A') {  
                                                 while (((c = filename[j]) >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) j++;  
                                         }  
                                         for (i = 1; i <= j; i++) {  
                                                 if (FileMatchesToPattern2(filename + i, filename_end, pattern + 1, pattern_end)) return 1;  
                                         }  
                                 }  
                                 return 0; /* Not matched or bad pattern. */  
770                          }                          }
771                          filename++; /* safe because *filename != '\0' */                          for (i = 1; i <= j; i++) {
772                          pattern++; /* safe because *pattern != '\0' */                                  if (ccs_file_matches_pattern2(filename + i,
773                                                                  filename_end,
774                                                                  pattern + 1,
775                                                                  pattern_end))
776                                            return true;
777                            }
778                            return false; /* Not matched or bad pattern. */
779                  }                  }
780                    filename++;
781                    pattern++;
782          }          }
783          while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;          while (*pattern == '\\' &&
784          return (filename == filename_end && pattern == pattern_end);                 (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
785                    pattern += 2;
786            return filename == filename_end && pattern == pattern_end;
787  }  }
788    
789  static int FileMatchesToPattern(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
790     * ccs_file_matches_pattern - Pattern matching without without '/' character.
791     *
792     * @filename:     The start of string to check.
793     * @filename_end: The end of string to check.
794     * @pattern:      The start of pattern to compare.
795     * @pattern_end:  The end of pattern to compare.
796     *
797     * Returns true if @filename matches @pattern, false otherwise.
798     */
799    static bool ccs_file_matches_pattern(const char *filename,
800                                         const char *filename_end,
801                                         const char *pattern,
802                                         const char *pattern_end)
803  {  {
804          const char *pattern_start = pattern;          const char *pattern_start = pattern;
805          int first = 1;          bool first = true;
806          int result;          bool result;
807          while (pattern < pattern_end - 1) {          while (pattern < pattern_end - 1) {
808                  if (*pattern++ != '\\' || *pattern++ != '-') continue;                  /* Split at "\-" pattern. */
809                  result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern - 2);                  if (*pattern++ != '\\' || *pattern++ != '-')
810                  if (first) result = !result;                          continue;
811                  if (result) return 0;                  result = ccs_file_matches_pattern2(filename, filename_end,
812                  first = 0;                                                     pattern_start, pattern - 2);
813                    if (first)
814                            result = !result;
815                    if (result)
816                            return false;
817                    first = false;
818                  pattern_start = pattern;                  pattern_start = pattern;
819          }          }
820          result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern_end);          result = ccs_file_matches_pattern2(filename, filename_end,
821                                               pattern_start, pattern_end);
822          return first ? result : !result;          return first ? result : !result;
823  }  }
824    
825  /*  /**
826   *  Check whether the given pathname matches to the given pattern.   * ccs_path_matches_pattern - Check whether the given filename matches the given pattern.
827   *  Returns nonzero if matches, zero otherwise.   * @filename: The filename to check.
828     * @pattern:  The pattern to compare.
829   *   *
830   *  The following patterns are available.   * Returns true if matches, false otherwise.
831   *    \\     \ itself.   *
832   *    \ooo   Octal representation of a byte.   * The following patterns are available.
833   *    \*     More than or equals to 0 character other than '/'.   *   \\     \ itself.
834   *    \@     More than or equals to 0 character other than '/' or '.'.   *   \ooo   Octal representation of a byte.
835   *    \?     1 byte character other than '/'.   *   \*     More than or equals to 0 character other than '/'.
836   *    \$     More than or equals to 1 decimal digit.   *   \@     More than or equals to 0 character other than '/' or '.'.
837   *    \+     1 decimal digit.   *   \?     1 byte character other than '/'.
838   *    \X     More than or equals to 1 hexadecimal digit.   *   \$     More than or equals to 1 decimal digit.
839   *    \x     1 hexadecimal digit.   *   \+     1 decimal digit.
840   *    \A     More than or equals to 1 alphabet character.   *   \X     More than or equals to 1 hexadecimal digit.
841   *    \a     1 alphabet character.   *   \x     1 hexadecimal digit.
842   *    \-     Subtraction operator.   *   \A     More than or equals to 1 alphabet character.
843   */   *   \a     1 alphabet character.
844     *   \-     Subtraction operator.
 int PathMatchesToPattern(const struct path_info *pathname0, const struct path_info *pattern0)  
 {  
         /* if (!pathname || !pattern) return 0; */  
         const char *pathname = pathname0->name, *pattern = pattern0->name;  
         const int len = pattern0->const_len;  
         if (!pattern0->is_patterned) return !pathcmp(pathname0, pattern0);  
         if (pathname0->depth != pattern0->depth) return 0;  
         if (strncmp(pathname, pattern, len)) return 0;  
         pathname += len; pattern += len;  
         while (*pathname && *pattern) {  
                 const char *pathname_delimiter = strchr(pathname, '/'), *pattern_delimiter = strchr(pattern, '/');  
                 if (!pathname_delimiter) pathname_delimiter = strchr(pathname, '\0');  
                 if (!pattern_delimiter) pattern_delimiter = strchr(pattern, '\0');  
                 if (!FileMatchesToPattern(pathname, pathname_delimiter, pattern, pattern_delimiter)) return 0;  
                 pathname = *pathname_delimiter ? pathname_delimiter + 1 : pathname_delimiter;  
                 pattern = *pattern_delimiter ? pattern_delimiter + 1 : pattern_delimiter;  
         }  
         while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;  
         return (!*pathname && !*pattern);  
 }  
   
 /*  
  *  Transactional printf() to struct io_buffer structure.  
  *  snprintf() will truncate, but io_printf() won't.  
  *  Returns zero on success, nonzero otherwise.  
845   */   */
846  int io_printf(struct io_buffer *head, const char *fmt, ...)  bool ccs_path_matches_pattern(const struct ccs_path_info *filename,
847                                  const struct ccs_path_info *pattern)
848  {  {
849          va_list args;          /*
850          int len, pos = head->read_avail, size = head->readbuf_size - pos;            if (!filename || !pattern)
851          if (size <= 0) return -ENOMEM;            return false;
852          va_start(args, fmt);          */
853          len = vsnprintf(head->read_buf + pos, size, fmt, args);          const char *f = filename->name;
854          va_end(args);          const char *p = pattern->name;
855          if (pos + len >= head->readbuf_size) return -ENOMEM;          const int len = pattern->const_len;
856          head->read_avail += len;          /* If @pattern doesn't contain pattern, I can use strcmp(). */
857          return 0;          if (!pattern->is_patterned)
858                    return !ccs_pathcmp(filename, pattern);
859            /* Don't compare if the number of '/' differs. */
860            if (filename->depth != pattern->depth)
861                    return false;
862            /* Compare the initial length without patterns. */
863            if (strncmp(f, p, len))
864                    return false;
865            f += len;
866            p += len;
867            /* Main loop. Compare each directory component. */
868            while (*f && *p) {
869                    const char *f_delimiter = strchr(f, '/');
870                    const char *p_delimiter = strchr(p, '/');
871                    if (!f_delimiter)
872                            f_delimiter = f + strlen(f);
873                    if (!p_delimiter)
874                            p_delimiter = p + strlen(p);
875                    if (!ccs_file_matches_pattern(f, f_delimiter, p, p_delimiter))
876                            return false;
877                    f = f_delimiter;
878                    if (*f)
879                            f++;
880                    p = p_delimiter;
881                    if (*p)
882                            p++;
883            }
884            /* Ignore trailing "\*" and "\@" in @pattern. */
885            while (*p == '\\' &&
886                   (*(p + 1) == '*' || *(p + 1) == '@'))
887                    p += 2;
888            return !*f && !*p;
889  }  }
890    
891  /*  /**
892   * Get realpath() of current process.   * ccs_get_exe - Get ccs_realpath() of current process.
893   * This function uses ccs_alloc(), so caller must ccs_free() if this function didn't return NULL.   *
894     * Returns the ccs_realpath() of current process on success, NULL otherwise.
895     *
896     * This function uses kzalloc(), so the caller must kfree()
897     * if this function didn't return NULL.
898   */   */
899  const char *GetEXE(void)  const char *ccs_get_exe(void)
900  {  {
901          struct mm_struct *mm = current->mm;          struct mm_struct *mm = current->mm;
902          struct vm_area_struct *vma;          struct vm_area_struct *vma;
903          const char *cp = NULL;          const char *cp = NULL;
904          if (!mm) return NULL;          if (!mm)
905                    return NULL;
906          down_read(&mm->mmap_sem);          down_read(&mm->mmap_sem);
907          for (vma = mm->mmap; vma; vma = vma->vm_next) {          for (vma = mm->mmap; vma; vma = vma->vm_next) {
908                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
909                          cp = realpath_from_dentry(vma->vm_file->f_dentry, vma->vm_file->f_vfsmnt);  #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
910                            struct path path = { vma->vm_file->f_vfsmnt,
911                                                 vma->vm_file->f_dentry };
912                            cp = ccs_realpath_from_path(&path);
913    #else
914                            cp = ccs_realpath_from_path(&vma->vm_file->f_path);
915    #endif
916                          break;                          break;
917                  }                  }
918          }          }
# Line 488  const char *GetEXE(void) Line 920  const char *GetEXE(void)
920          return cp;          return cp;
921  }  }
922    
923  const char *GetMSG(const bool is_enforce)  /**
924  {   * ccs_flags - Check mode for specified functionality.
925          if (is_enforce) return "ERROR"; else return "WARNING";   *
926  }   * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
927     * @index:  The functionality to check mode.
928  const char *GetAltExec(void)   *
929  {   * Returns the mode of specified functionality.
930          const u8 profile = current->domain_info->profile;   */
931          const struct path_info *alt_exec = profile_ptr[profile] ? profile_ptr[profile]->alt_exec : NULL;  unsigned int ccs_flags(const struct ccs_domain_info *domain,
932          return alt_exec ? alt_exec->name : NULL;                         const u8 index)
 }  
   
 /*************************  DOMAIN POLICY HANDLER  *************************/  
   
 /* Check whether the given access control is enabled. */  
 unsigned int CheckCCSFlags(const u8 index)  
933  {  {
934          const u8 profile = current->domain_info->profile;          u8 profile;
935          return sbin_init_started && index < CCS_MAX_CONTROL_INDEX          if (!domain)
936  #if MAX_PROFILES != 256                  domain = ccs_current_domain();
937                  && profile < MAX_PROFILES          profile = domain->profile;
938            return ccs_policy_loaded && index < CCS_MAX_CONTROL_INDEX
939    #if CCS_MAX_PROFILES != 256
940                    && profile < CCS_MAX_PROFILES
941  #endif  #endif
942                  && profile_ptr[profile] ? profile_ptr[profile]->value[index] : 0;                  && ccs_profile_ptr[profile] ?
943  }                  ccs_profile_ptr[profile]->value[index] : 0;
   
 bool TomoyoVerboseMode(void)  
 {  
         return CheckCCSFlags(CCS_TOMOYO_VERBOSE) != 0;  
 }  
   
 bool CheckDomainQuota(struct domain_info * const domain)  
 {  
         unsigned int count = 0;  
         struct acl_info *ptr;  
         if (!domain) return 1;  
         list1_for_each_entry(ptr, &domain->acl_info_list, list) {  
                 if (!ptr->is_deleted) count++;  
         }  
         if (count < CheckCCSFlags(CCS_TOMOYO_MAX_ACCEPT_ENTRY)) return 1;  
         if (!domain->quota_warned) {  
                 domain->quota_warned = 1;  
                 printk("TOMOYO-WARNING: Domain '%s' has so many ACLs to hold. Stopped learning mode.\n", domain->domainname->name);  
         }  
         return 0;  
944  }  }
945    
946  static struct profile *FindOrAssignNewProfile(const unsigned int profile)  /**
947     * ccs_get_audit - Get audit mode.
948     *
949     * @profile:    Profile number.
950     * @index:      Index number of functionality.
951     * @is_granted: True if granted log, false otehrwise.
952     *
953     * Returns mode.
954     */
955    bool ccs_get_audit(const u8 profile, const u8 index, const bool is_granted)
956  {  {
957          static DEFINE_MUTEX(profile_lock);          u8 mode;
958          struct profile *ptr = NULL;          const u8 category = ccs_index2category[index] + CCS_MAX_MAC_INDEX
959          mutex_lock(&profile_lock);                  + CCS_MAX_CAPABILITY_INDEX;
960          if (profile < MAX_PROFILES && (ptr = profile_ptr[profile]) == NULL) {          if (!ccs_policy_loaded || !ccs_profile_ptr[profile])
961                  if ((ptr = alloc_element(sizeof(*ptr))) != NULL) {                  return false;
962                          int i;          mode = ccs_profile_ptr[profile]->config[index];
963                          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) ptr->value[i] = ccs_control_array[i].current_value;          if (mode == CCS_MAC_MODE_USE_DEFAULT)
964                          mb(); /* Avoid out-of-order execution. */                  mode = ccs_profile_ptr[profile]->config[category];
965                          profile_ptr[profile] = ptr;          if (mode == CCS_MAC_MODE_USE_DEFAULT)
966                  }                  mode = ccs_profile_ptr[profile]->default_config;
967          }          if (is_granted)
968          mutex_unlock(&profile_lock);                  return !(mode & CCS_MAC_MODE_NO_GRANT_LOG);
969          return ptr;          return !(mode & CCS_MAC_MODE_NO_REJECT_LOG);
970  }  }
971    
972  /* #define ALT_EXEC */  /**
973     * ccs_get_mode - Get MAC mode.
974  static int SetProfile(struct io_buffer *head)   *
975  {   * @profile: Profile number.
976          char *data = head->write_buf;   * @index:   Index number of functionality.
977          unsigned int i, value;   *
978          char *cp;   * Returns mode.
979          struct profile *profile;   */
980          if (!isRoot()) return -EPERM;  int ccs_get_mode(const u8 profile, const u8 index)
         i = simple_strtoul(data, &cp, 10);  
         if (data != cp) {  
                 if (*cp != '-') return -EINVAL;  
                 data= cp + 1;  
         }  
         profile = FindOrAssignNewProfile(i);  
         if (!profile) return -EINVAL;  
         cp = strchr(data, '=');  
         if (!cp) return -EINVAL;  
         *cp = '\0';  
         UpdateCounter(CCS_UPDATES_COUNTER_PROFILE);  
         if (strcmp(data, ccs_control_array[CCS_PROFILE_COMMENT].keyword) == 0) {  
                 profile->comment = SaveName(cp + 1);  
                 return 0;  
         }  
 #ifdef ALT_EXEC  
 #ifdef CONFIG_TOMOYO  
         if (strcmp(data, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword) == 0) {  
                 cp++;  
                 if (*cp && !IsCorrectPath(cp, 1, -1, -1, __FUNCTION__)) cp = "";  
                 profile->alt_exec = SaveName(cp);  
                 return 0;  
         }  
 #endif  
 #endif  
         if (sscanf(cp + 1, "%u", &value) != 1) return -EINVAL;  
 #ifdef CONFIG_TOMOYO  
         if (strncmp(data, KEYWORD_MAC_FOR_CAPABILITY, KEYWORD_MAC_FOR_CAPABILITY_LEN) == 0) {  
                 return SetCapabilityStatus(data + KEYWORD_MAC_FOR_CAPABILITY_LEN, value, i);  
         }  
 #endif  
         for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) {  
                 if (strcmp(data, ccs_control_array[i].keyword)) continue;  
                 if (value > ccs_control_array[i].max_value) value = ccs_control_array[i].max_value;  
                 profile->value[i] = value;  
                 return 0;  
         }  
         return -EINVAL;  
 }  
   
 static int ReadProfile(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 if (!isRoot()) return -EPERM;  
                 if (!head->read_var2) {  
                         int step;  
                         for (step = head->read_step; step < MAX_PROFILES * CCS_MAX_CONTROL_INDEX; step++) {  
                                 const int i = step / CCS_MAX_CONTROL_INDEX, j = step % CCS_MAX_CONTROL_INDEX;  
                                 const struct profile *profile = profile_ptr[i];  
                                 head->read_step = step;  
                                 if (!profile) continue;  
                                 switch (j) {  
                                 case -1: /* Dummy */  
 #ifndef CONFIG_SAKURA  
                                 case CCS_SAKURA_DENY_CONCEAL_MOUNT:  
                                 case CCS_SAKURA_RESTRICT_CHROOT:  
                                 case CCS_SAKURA_RESTRICT_MOUNT:  
                                 case CCS_SAKURA_RESTRICT_UNMOUNT:  
                                 case CCS_SAKURA_RESTRICT_PIVOT_ROOT:  
                                 case CCS_SAKURA_RESTRICT_AUTOBIND:  
 #endif  
 #ifndef CONFIG_TOMOYO  
                                 case CCS_TOMOYO_MAC_FOR_FILE:  
                                 case CCS_TOMOYO_MAC_FOR_ARGV0:  
                                 case CCS_TOMOYO_MAC_FOR_ENV:  
                                 case CCS_TOMOYO_MAC_FOR_NETWORK:  
                                 case CCS_TOMOYO_MAC_FOR_SIGNAL:  
                                 case CCS_TOMOYO_MAX_ACCEPT_ENTRY:  
                                 case CCS_TOMOYO_MAX_GRANT_LOG:  
                                 case CCS_TOMOYO_MAX_REJECT_LOG:  
                                 case CCS_TOMOYO_VERBOSE:  
 #endif  
 #ifndef ALT_EXEC  
                                 case CCS_TOMOYO_ALT_EXEC:  
                                 case CCS_SLEEP_PERIOD:  
 #endif  
                                         continue;  
                                 }  
                                 if (j == CCS_PROFILE_COMMENT) {  
                                         if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_PROFILE_COMMENT].keyword, profile->comment ? profile->comment->name : "")) break;  
                                 } else if (j == CCS_TOMOYO_ALT_EXEC) {  
                                         const struct path_info *alt_exec = profile->alt_exec;  
                                         if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword, alt_exec ? alt_exec->name : "")) break;  
                                 } else {  
                                         if (io_printf(head, "%u-%s=%u\n", i, ccs_control_array[j].keyword, profile->value[j])) break;  
                                 }  
                         }  
                         if (step == MAX_PROFILES * CCS_MAX_CONTROL_INDEX) {  
                                 head->read_var2 = (void *) "";  
                                 head->read_step = 0;  
                         }  
                 }  
                 if (head->read_var2) {  
 #ifdef CONFIG_TOMOYO  
                         if (ReadCapabilityStatus(head) == 0)  
 #endif  
                                 head->read_eof = 1;  
                 }  
         }  
         return 0;  
 }  
   
 /*************************  POLICY MANAGER HANDLER  *************************/  
   
 struct policy_manager_entry {  
         struct list1_head list;  
         const struct path_info *manager;  
         bool is_domain;  
         bool is_deleted;  
 };  
   
 static LIST1_HEAD(policy_manager_list);  
   
 static int AddManagerEntry(const char *manager, const bool is_delete)  
981  {  {
982          struct policy_manager_entry *new_entry, *ptr;          u8 mode;
983          static DEFINE_MUTEX(lock);          const u8 category = ccs_index2category[index] + CCS_MAX_MAC_INDEX
984          const struct path_info *saved_manager;                  + CCS_MAX_CAPABILITY_INDEX;
985          int error = -ENOMEM;          if (!ccs_policy_loaded || !ccs_profile_ptr[profile])
986          bool is_domain = 0;                  return CCS_MAC_MODE_DISABLED;
987          if (!isRoot()) return -EPERM;          mode = ccs_profile_ptr[profile]->config[index];
988          if (IsDomainDef(manager)) {          if (mode == CCS_MAC_MODE_USE_DEFAULT)
989                  if (!IsCorrectDomain(manager, __FUNCTION__)) return -EINVAL;                  mode = ccs_profile_ptr[profile]->config[category];
990                  is_domain = 1;          if (mode == CCS_MAC_MODE_USE_DEFAULT)
991          } else {                  mode = ccs_profile_ptr[profile]->default_config;
992                  if (!IsCorrectPath(manager, 1, -1, -1, __FUNCTION__)) return -EINVAL;          return mode & 3;
         }  
         if ((saved_manager = SaveName(manager)) == NULL) return -ENOMEM;  
         mutex_lock(&lock);  
         list1_for_each_entry(ptr, &policy_manager_list, list) {  
                 if (ptr->manager == saved_manager) {  
                         ptr->is_deleted = is_delete;  
                         error = 0;  
                         goto out;  
                 }  
         }  
         if (is_delete) {  
                 error = -ENOENT;  
                 goto out;  
         }  
         if ((new_entry = alloc_element(sizeof(*new_entry))) == NULL) goto out;  
         new_entry->manager = saved_manager;  
         new_entry->is_domain = is_domain;  
         list1_add_tail_mb(&new_entry->list, &policy_manager_list);  
         error = 0;  
  out:  
         mutex_unlock(&lock);  
         if (!error) UpdateCounter(CCS_UPDATES_COUNTER_MANAGER);  
         return error;  
993  }  }
994    
995  static int AddManagerPolicy(struct io_buffer *head)  /**
996     * ccs_init_request_info - Initialize "struct ccs_request_info" members.
997     *
998     * @r:      Pointer to "struct ccs_request_info" to initialize.
999     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
1000     * @index:  Index number of functionality.
1001     *
1002     * Returns mode.
1003     */
1004    int ccs_init_request_info(struct ccs_request_info *r,
1005                              struct ccs_domain_info *domain, const u8 index)
1006  {  {
1007          const char *data = head->write_buf;          u8 profile;
1008          bool is_delete = 0;          memset(r, 0, sizeof(*r));
1009          if (!isRoot()) return -EPERM;          if (!domain)
1010          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {                  domain = ccs_current_domain();
1011                  data += KEYWORD_DELETE_LEN;          r->domain = domain;
1012                  is_delete = 1;          profile = domain->profile;
1013          }          r->profile = profile;
1014          return AddManagerEntry(data, is_delete);          r->type = index;
1015            r->mode = ccs_get_mode(profile, index);
1016            return r->mode;
1017  }  }
1018    
1019  static int ReadManagerPolicy(struct io_buffer *head)  /**
1020     * ccs_last_word - Get last component of a line.
1021     *
1022     * @line: A line.
1023     *
1024     * Returns the last word of a line.
1025     */
1026    const char *ccs_last_word(const char *name)
1027  {  {
1028          struct list1_head *pos;          const char *cp = strrchr(name, ' ');
1029          if (head->read_eof) return 0;          if (cp)
1030          if (!isRoot()) return -EPERM;                  return cp + 1;
1031          list1_for_each_cookie(pos, head->read_var2, &policy_manager_list) {          return name;
                 struct policy_manager_entry *ptr;  
                 ptr = list1_entry(pos, struct policy_manager_entry, list);  
                 if (ptr->is_deleted) continue;  
                 if (io_printf(head, "%s\n", ptr->manager->name)) return 0;  
         }  
         head->read_eof = 1;  
         return 0;  
1032  }  }
1033    
1034  /* Check whether the current process is a policy manager. */  /**
1035  static int IsPolicyManager(void)   * ccs_warn_log - Print warning or error message on console.
1036     *
1037     * @r:   Pointer to "struct ccs_request_info".
1038     * @fmt: The printf()'s format string, followed by parameters.
1039     */
1040    void ccs_warn_log(struct ccs_request_info *r, const char *fmt, ...)
1041  {  {
1042          struct policy_manager_entry *ptr;          int len = PAGE_SIZE;
1043          const char *exe;          va_list args;
1044          const struct path_info *domainname = current->domain_info->domainname;          char *buffer;
1045          bool found = 0;          if (!ccs_flags(r->domain, CCS_VERBOSE))
1046          if (!sbin_init_started) return 1;                  return;
1047          list1_for_each_entry(ptr, &policy_manager_list, list) {          while (1) {
1048                  if (!ptr->is_deleted && ptr->is_domain && !pathcmp(domainname, ptr->manager)) return 1;                  int len2;
1049          }                  buffer = kmalloc(len, GFP_KERNEL);
1050          if ((exe = GetEXE()) == NULL) return 0;                  if (!buffer)
1051          list1_for_each_entry(ptr, &policy_manager_list, list) {                          return;
1052                  if (!ptr->is_deleted && !ptr->is_domain && !strcmp(exe, ptr->manager->name)) {                  va_start(args, fmt);
1053                          found = 1;                  len2 = vsnprintf(buffer, len - 1, fmt, args);
1054                    va_end(args);
1055                    if (len2 < len - 1) {
1056                            buffer[len2] = '\0';
1057                          break;                          break;
1058                  }                  }
1059                    len = len2 + 1;
1060                    kfree(buffer);
1061          }          }
1062          if (!found) { /* Reduce error messages. */          printk(KERN_WARNING "%s: Access %s denied for %s\n",
1063                  static pid_t last_pid = 0;                 r->mode == CCS_MAC_MODE_ENFORCING ? "ERROR" : "WARNING", buffer,
1064                  const pid_t pid = current->pid;                 ccs_last_word(r->domain->domainname->name));
1065                  if (last_pid != pid) {          kfree(buffer);
                         printk("%s ( %s ) is not permitted to update policies.\n", domainname->name, exe);  
                         last_pid = pid;  
                 }  
         }  
         ccs_free(exe);  
         return found;  
 }  
   
 #ifdef CONFIG_TOMOYO  
   
 /*************************  DOMAIN POLICY HANDLER  *************************/  
   
 static char *FindConditionPart(char *data)  
 {  
         char *cp = strstr(data, " if "), *cp2;  
         if (cp) {  
                 while ((cp2 = strstr(cp + 3, " if ")) != NULL) cp = cp2;  
                 *cp++ = '\0';  
         }  
         return cp;  
 }  
   
 static int AddDomainPolicy(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         struct domain_info *domain = head->write_var1;  
         bool is_delete = 0, is_select = 0, is_undelete = 0;  
         unsigned int profile;  
         const struct condition_list *cond = NULL;  
         char *cp;        
         if (!isRoot()) return -EPERM;  
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
                 is_delete = 1;  
         } else if (strncmp(data, KEYWORD_SELECT, KEYWORD_SELECT_LEN) == 0) {  
                 data += KEYWORD_SELECT_LEN;  
                 is_select = 1;  
         } else if (strncmp(data, KEYWORD_UNDELETE, KEYWORD_UNDELETE_LEN) == 0) {  
                 data += KEYWORD_UNDELETE_LEN;  
                 is_undelete = 1;  
         }  
         UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);  
         if (IsDomainDef(data)) {  
                 if (is_delete) {  
                         DeleteDomain(data);  
                         domain = NULL;  
                 } else if (is_select) {  
                         domain = FindDomain(data);  
                 } else if (is_undelete) {  
                         domain = UndeleteDomain(data);  
                 } else {  
                         domain = FindOrAssignNewDomain(data, 0);  
                 }  
                 head->write_var1 = domain;  
                 return 0;  
         }  
         if (!domain) return -EINVAL;  
   
         if (sscanf(data, KEYWORD_USE_PROFILE "%u", &profile) == 1 && profile < MAX_PROFILES) {  
                 if (profile_ptr[profile] || !sbin_init_started) domain->profile = (u8) profile;  
                 return 0;  
         }  
         cp = FindConditionPart(data);  
         if (cp && (cond = FindOrAssignNewCondition(cp)) == NULL) return -EINVAL;  
         if (strncmp(data, KEYWORD_ALLOW_CAPABILITY, KEYWORD_ALLOW_CAPABILITY_LEN) == 0) {  
                 return AddCapabilityPolicy(data + KEYWORD_ALLOW_CAPABILITY_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_NETWORK, KEYWORD_ALLOW_NETWORK_LEN) == 0) {  
                 return AddNetworkPolicy(data + KEYWORD_ALLOW_NETWORK_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_SIGNAL, KEYWORD_ALLOW_SIGNAL_LEN) == 0) {  
                 return AddSignalPolicy(data + KEYWORD_ALLOW_SIGNAL_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_ARGV0, KEYWORD_ALLOW_ARGV0_LEN) == 0) {  
                 return AddArgv0Policy(data + KEYWORD_ALLOW_ARGV0_LEN, domain, cond, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_ENV, KEYWORD_ALLOW_ENV_LEN) == 0) {  
                 return AddEnvPolicy(data + KEYWORD_ALLOW_ENV_LEN, domain, cond, is_delete);  
         } else {  
                 return AddFilePolicy(data, domain, cond, is_delete);  
         }  
         return -EINVAL;  
 }  
   
 static int ReadDomainPolicy(struct io_buffer *head)  
 {  
         struct list1_head *dpos;  
         struct list1_head *apos;  
         if (head->read_eof) return 0;  
         if (head->read_step == 0) {  
                 if (!isRoot()) return -EPERM;  
                 head->read_step = 1;  
         }  
         list1_for_each_cookie(dpos, head->read_var1, &domain_list) {  
                 struct domain_info *domain;  
                 domain = list1_entry(dpos, struct domain_info, list);  
                 if (head->read_step != 1) goto acl_loop;  
                 if (domain->is_deleted) continue;  
                 if (io_printf(head, "%s\n" KEYWORD_USE_PROFILE "%u\n%s\n", domain->domainname->name, domain->profile, domain->quota_warned ? "quota_exceeded\n" : "")) return 0;  
                 head->read_step = 2;  
         acl_loop: ;  
                 if (head->read_step == 3) goto tail_mark;  
                 list1_for_each_cookie(apos, head->read_var2, &domain->acl_info_list) {  
                         struct acl_info *ptr;  
                         int pos;  
                         u8 acl_type;  
                         ptr = list1_entry(apos, struct acl_info, list);  
                         if (ptr->is_deleted) continue;  
                         pos = head->read_avail;  
                         acl_type = ptr->type;  
                         if (acl_type == TYPE_SINGLE_PATH_ACL) {  
                                 struct single_acl_record *ptr2 = container_of(ptr, struct single_acl_record, head);  
                                 const bool b = ptr2->u_is_group;  
                                 const u16 perm = ptr2->perm;  
                                 u8 bit = head->read_bit;  
                                 while (bit < MAX_SINGLE_PATH_OPERATION) {  
                                         if (perm & (1 << bit)) {  
                                                 pos = head->read_avail;  
                                                 if (io_printf(head, "allow_%s %s%s ", sp_operation2keyword(bit),  
                                                               b ? "@" : "", b ? ptr2->u.group->group_name->name : ptr2->u.filename->name)  
                                                     || DumpCondition(head, ptr->cond)) {  
                                                         head->read_bit = bit;  
                                                         head->read_avail = pos;  
                                                         return 0;  
                                                 }  
                                         }  
                                         bit++;  
                                 }  
                                 head->read_bit = 0;  
                         } else if (acl_type == TYPE_DOUBLE_PATH_ACL) {  
                                 struct double_acl_record *ptr2 = container_of(ptr, struct double_acl_record, head);  
                                 const bool b0 = ptr2->u1_is_group, b1 = ptr2->u2_is_group;  
                                 const u8 perm = ptr2->perm;  
                                 u8 bit = head->read_bit;  
                                 while (bit < MAX_DOUBLE_PATH_OPERATION) {  
                                         if (perm & (1 << bit)) {  
                                                 pos = head->read_avail;  
                                                 if (io_printf(head, "allow_%s %s%s %s%s", dp_operation2keyword(bit),  
                                                               b0 ? "@" : "", b0 ? ptr2->u1.group1->group_name->name : ptr2->u1.filename1->name,  
                                                               b1 ? "@" : "", b1 ? ptr2->u2.group2->group_name->name : ptr2->u2.filename2->name)  
                                                     || DumpCondition(head, ptr->cond)) {  
                                                         head->read_bit = bit;  
                                                         head->read_avail = pos;  
                                                         return 0;  
                                                 }  
                                         }  
                                         bit++;  
                                 }  
                                 head->read_bit = 0;  
                         } else if (acl_type == TYPE_ARGV0_ACL) {  
                                 struct argv0_acl_record *ptr2 = container_of(ptr, struct argv0_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_ARGV0 "%s %s",  
                                               ptr2->filename->name, ptr2->argv0->name)) goto print_acl_rollback;  
                         } else if (acl_type == TYPE_ENV_ACL) {  
                                 struct env_acl_record *ptr2 = container_of(ptr, struct env_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_ENV "%s", ptr2->env->name)) goto print_acl_rollback;  
                         } else if (acl_type == TYPE_CAPABILITY_ACL) {  
                                 struct capability_acl_record *ptr2 = container_of(ptr, struct capability_acl_record, head);  
                                 const u32 capability = ptr2->capability;  
                                 u8 bit = head->read_bit;  
                                 while (bit < TOMOYO_MAX_CAPABILITY_INDEX) {  
                                         if (capability & (1 << bit)) {  
                                                 pos = head->read_avail;  
                                                 if (io_printf(head, KEYWORD_ALLOW_CAPABILITY "%s", cap_operation2keyword(bit)) ||  
                                                     DumpCondition(head, ptr->cond)) {  
                                                         head->read_bit = bit;  
                                                         head->read_avail = pos;  
                                                         return 0;  
                                                 }  
                                         }  
                                         bit++;  
                                 }  
                                 head->read_bit = 0;  
                         } else if (acl_type == TYPE_IP_NETWORK_ACL) {  
                                 struct ip_network_acl_record *ptr2 = container_of(ptr, struct ip_network_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_NETWORK "%s ", net_operation2keyword(ptr2->operation_type))) goto print_acl_rollback;  
                                 switch (ptr2->record_type) {  
                                 case IP_RECORD_TYPE_ADDRESS_GROUP:  
                                         if (io_printf(head, "@%s", ptr2->u.group->group_name->name)) goto print_acl_rollback;  
                                         break;  
                                 case IP_RECORD_TYPE_IPv4:  
                                         {  
                                                 const u32 min_address = ptr2->u.ipv4.min, max_address = ptr2->u.ipv4.max;  
                                                 if (io_printf(head, "%u.%u.%u.%u", HIPQUAD(min_address))) goto print_acl_rollback;  
                                                 if (min_address != max_address && io_printf(head, "-%u.%u.%u.%u", HIPQUAD(max_address))) goto print_acl_rollback;  
                                         }  
                                         break;  
                                 case IP_RECORD_TYPE_IPv6:  
                                         {  
                                                 char buf[64];  
                                                 const struct in6_addr *min_address = ptr2->u.ipv6.min, *max_address = ptr2->u.ipv6.max;  
                                                 print_ipv6(buf, sizeof(buf), min_address);  
                                                 if (io_printf(head, "%s", buf)) goto print_acl_rollback;  
                                                 if (min_address != max_address) {  
                                                         print_ipv6(buf, sizeof(buf), max_address);  
                                                         if (io_printf(head, "-%s", buf)) goto print_acl_rollback;  
                                                 }  
                                         }  
                                         break;  
                                 }  
                                 {  
                                         const u16 min_port = ptr2->min_port, max_port = ptr2->max_port;  
                                         if (io_printf(head, " %u", min_port)) goto print_acl_rollback;  
                                         if (min_port != max_port && io_printf(head, "-%u", max_port)) goto print_acl_rollback;  
                                 }  
                         } else if (acl_type == TYPE_SIGNAL_ACL) {  
                                 struct signal_acl_record *ptr2 = container_of(ptr, struct signal_acl_record, head);  
                                 if (io_printf(head, KEYWORD_ALLOW_SIGNAL "%u %s", ptr2->sig, ptr2->domainname->name)) goto print_acl_rollback;  
                         } else {  
                                 BUG();  
                         }  
                         if (acl_type != TYPE_SINGLE_PATH_ACL && acl_type != TYPE_DOUBLE_PATH_ACL && acl_type != TYPE_CAPABILITY_ACL && DumpCondition(head, ptr->cond)) {  
                         print_acl_rollback: ;  
                         head->read_avail = pos;  
                         return 0;  
                         }  
                 }  
                 head->read_step = 3;  
         tail_mark: ;  
                 if (io_printf(head, "\n")) return 0;  
                 head->read_step = 1;  
         }  
         head->read_eof = 1;  
         return 0;  
1066  }  }
1067    
1068  #endif  /**
1069     * ccs_domain_quota_ok - Check for domain's quota.
1070  static int UpdateDomainProfile(struct io_buffer *head)   *
1071     * @r: Pointer to "struct ccs_request_info".
1072     *
1073     * Returns true if the domain is not exceeded quota, false otherwise.
1074     *
1075     * Caller holds ccs_read_lock().
1076     */
1077    bool ccs_domain_quota_ok(struct ccs_request_info *r)
1078  {  {
1079          char *data = head->write_buf;          unsigned int count = 0;
1080          char *cp = strchr(data, ' ');          struct ccs_domain_info *domain = r->domain;
1081          struct domain_info *domain;          struct ccs_acl_info *ptr;
1082          unsigned int profile;          if (r->mode != 1)
1083          if (!isRoot()) return -EPERM;                  return false;
1084          if (!cp) return -EINVAL;          if (!domain)
1085          *cp = '\0';                  return true;
1086          domain = FindDomain(cp + 1);          list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
1087          profile = simple_strtoul(data, NULL, 10);                  if (ptr->is_deleted)
1088          if (domain && profile < MAX_PROFILES && (profile_ptr[profile] || !sbin_init_started)) domain->profile = (u8) profile;                          continue;
1089          UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);                  switch (ptr->type) {
1090          return 0;                          u16 perm;
1091  }                          u8 i;
1092                    case CCS_TYPE_PATH_ACL:
1093  static int ReadDomainProfile(struct io_buffer *head)                          perm = container_of(ptr, struct ccs_path_acl, head)->
1094  {                                  perm;
1095          struct list1_head *pos;                          for (i = 0; i < CCS_MAX_PATH_OPERATION; i++)
1096          if (head->read_eof) return 0;                                  if (perm & (1 << i))
1097          if (!isRoot()) return -EPERM;                                          count++;
1098          list1_for_each_cookie(pos, head->read_var1, &domain_list) {                          if (perm & (1 << CCS_TYPE_READ_WRITE))
1099                  struct domain_info *domain;                                  count -= 2;
                 domain = list1_entry(pos, struct domain_info, list);  
                 if (domain->is_deleted) continue;  
                 if (io_printf(head, "%u %s\n", domain->profile, domain->domainname->name)) return 0;  
         }  
         head->read_eof = 1;  
         return 0;  
 }  
   
 static int WritePID(struct io_buffer *head)  
 {  
         head->read_step = (int) simple_strtoul(head->write_buf, NULL, 10);  
         head->read_eof = 0;  
         return 0;  
 }  
   
 static int ReadPID(struct io_buffer *head)  
 {  
         if (head->read_avail == 0 && !head->read_eof) {  
                 const int pid = head->read_step;  
                 struct task_struct *p;  
                 struct domain_info *domain = NULL;  
                 /***** CRITICAL SECTION START *****/  
                 read_lock(&tasklist_lock);  
                 p = find_task_by_pid(pid);  
                 if (p) domain = p->domain_info;  
                 read_unlock(&tasklist_lock);  
                 /***** CRITICAL SECTION END *****/  
                 if (domain) io_printf(head, "%d %u %s", pid, domain->profile, domain->domainname->name);  
                 head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 /*************************  EXCEPTION POLICY HANDLER  *************************/  
   
 #ifdef CONFIG_TOMOYO  
   
 static int AddExceptionPolicy(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         bool is_delete = 0;  
         if (!isRoot()) return -EPERM;  
         UpdateCounter(CCS_UPDATES_COUNTER_EXCEPTION_POLICY);  
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
                 is_delete = 1;  
         }  
         if (strncmp(data, KEYWORD_KEEP_DOMAIN, KEYWORD_KEEP_DOMAIN_LEN) == 0) {  
                 return AddDomainKeeperPolicy(data + KEYWORD_KEEP_DOMAIN_LEN, 0, is_delete);  
         } else if (strncmp(data, KEYWORD_NO_KEEP_DOMAIN, KEYWORD_NO_KEEP_DOMAIN_LEN) == 0) {  
                 return AddDomainKeeperPolicy(data + KEYWORD_NO_KEEP_DOMAIN_LEN, 1, is_delete);  
         } else if (strncmp(data, KEYWORD_INITIALIZE_DOMAIN, KEYWORD_INITIALIZE_DOMAIN_LEN) == 0) {  
                 return AddDomainInitializerPolicy(data + KEYWORD_INITIALIZE_DOMAIN_LEN, 0, is_delete);  
         } else if (strncmp(data, KEYWORD_NO_INITIALIZE_DOMAIN, KEYWORD_NO_INITIALIZE_DOMAIN_LEN) == 0) {  
                 return AddDomainInitializerPolicy(data + KEYWORD_NO_INITIALIZE_DOMAIN_LEN, 1, is_delete);  
         } else if (strncmp(data, KEYWORD_ALIAS, KEYWORD_ALIAS_LEN) == 0) {  
                 return AddAliasPolicy(data + KEYWORD_ALIAS_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_AGGREGATOR, KEYWORD_AGGREGATOR_LEN) == 0) {  
                 return AddAggregatorPolicy(data + KEYWORD_AGGREGATOR_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_READ, KEYWORD_ALLOW_READ_LEN) == 0) {  
                 return AddGloballyReadablePolicy(data + KEYWORD_ALLOW_READ_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_ALLOW_ENV, KEYWORD_ALLOW_ENV_LEN) == 0) {  
                 return AddGloballyUsableEnvPolicy(data + KEYWORD_ALLOW_ENV_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_FILE_PATTERN, KEYWORD_FILE_PATTERN_LEN) == 0) {  
                 return AddFilePatternPolicy(data + KEYWORD_FILE_PATTERN_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_PATH_GROUP, KEYWORD_PATH_GROUP_LEN) == 0) {  
                 return AddPathGroupPolicy(data + KEYWORD_PATH_GROUP_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_DENY_REWRITE, KEYWORD_DENY_REWRITE_LEN) == 0) {  
                 return AddNoRewritePolicy(data + KEYWORD_DENY_REWRITE_LEN, is_delete);  
         } else if (strncmp(data, KEYWORD_ADDRESS_GROUP, KEYWORD_ADDRESS_GROUP_LEN) == 0) {  
                 return AddAddressGroupPolicy(data + KEYWORD_ADDRESS_GROUP_LEN, is_delete);  
         }  
         return -EINVAL;  
 }  
   
 static int ReadExceptionPolicy(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 switch (head->read_step) {  
                 case 0:  
                         if (!isRoot()) return -EPERM;  
                         head->read_var2 = NULL; head->read_step = 1;  
                 case 1:  
                         if (ReadDomainKeeperPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 2;  
                 case 2:  
                         if (ReadGloballyReadablePolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 3;  
                 case 3:  
                         if (ReadGloballyUsableEnvPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 4;  
                 case 4:  
                         if (ReadDomainInitializerPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 5;  
                 case 5:  
                         if (ReadAliasPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 6;  
                 case 6:  
                         if (ReadAggregatorPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 7;  
                 case 7:  
                         if (ReadFilePatternPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 8;  
                 case 8:  
                         if (ReadNoRewritePolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 9;  
                 case 9:  
                         if (ReadPathGroupPolicy(head)) break;  
                         head->read_var1 = head->read_var2 = NULL; head->read_step = 10;  
                 case 10:  
                         if (ReadAddressGroupPolicy(head)) break;  
                         head->read_eof = 1;  
1100                          break;                          break;
1101                  default:                  case CCS_TYPE_PATH2_ACL:
1102                          return -EINVAL;                          perm = container_of(ptr, struct ccs_path2_acl,
1103                  }                                              head)->perm;
1104          }                          for (i = 0; i < CCS_MAX_PATH2_OPERATION; i++)
1105          return 0;                                  if (perm & (1 << i))
1106  }                                          count++;
   
 #endif  
   
 /*************************  SYSTEM POLICY HANDLER  *************************/  
   
 #ifdef CONFIG_SAKURA  
   
 static int AddSystemPolicy(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         bool is_delete = 0;  
         if (!isRoot()) return -EPERM;  
         UpdateCounter(CCS_UPDATES_COUNTER_SYSTEM_POLICY);  
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
                 is_delete = 1;  
         }  
         if (strncmp(data, KEYWORD_ALLOW_MOUNT, KEYWORD_ALLOW_MOUNT_LEN) == 0)  
                 return AddMountPolicy(data + KEYWORD_ALLOW_MOUNT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_DENY_UNMOUNT, KEYWORD_DENY_UNMOUNT_LEN) == 0)  
                 return AddNoUmountPolicy(data + KEYWORD_DENY_UNMOUNT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_ALLOW_CHROOT, KEYWORD_ALLOW_CHROOT_LEN) == 0)  
                 return AddChrootPolicy(data + KEYWORD_ALLOW_CHROOT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_ALLOW_PIVOT_ROOT, KEYWORD_ALLOW_PIVOT_ROOT_LEN) == 0)  
                 return AddPivotRootPolicy(data + KEYWORD_ALLOW_PIVOT_ROOT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_DENY_AUTOBIND, KEYWORD_DENY_AUTOBIND_LEN) == 0)  
                 return AddReservedPortPolicy(data + KEYWORD_DENY_AUTOBIND_LEN, is_delete);  
         return -EINVAL;  
 }  
   
 static int ReadSystemPolicy(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 switch (head->read_step) {  
                 case 0:  
                         if (!isRoot()) return -EPERM;  
                         head->read_var2 = NULL; head->read_step = 1;  
                 case 1:  
                         if (ReadMountPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 2;  
                 case 2:  
                         if (ReadNoUmountPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 3;  
                 case 3:  
                         if (ReadChrootPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 4;  
                 case 4:  
                         if (ReadPivotRootPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 5;  
                 case 5:  
                         if (ReadReservedPortPolicy(head)) break;  
                         head->read_eof = 1;  
1107                          break;                          break;
1108                  default:                  case CCS_TYPE_EXECUTE_HANDLER:
1109                          return -EINVAL;                  case CCS_TYPE_DENIED_EXECUTE_HANDLER:
                 }  
         }  
         return 0;  
 }  
   
 #endif  
   
 /*************************  POLICY LOADER  *************************/  
   
 static int profile_loaded = 0;  
   
 static const char *ccs_loader = NULL;  
   
 static int __init CCS_loader_Setup(char *str)  
 {  
         ccs_loader = str;  
         return 0;  
 }  
   
 __setup("CCS_loader=", CCS_loader_Setup);  
   
 void CCS_LoadPolicy(const char *filename)  
 {  
         if (sbin_init_started) return;  
         /*  
          * Check filename is /sbin/init or /sbin/ccs-start .  
          * /sbin/ccs-start is a dummy filename in case where /sbin/init can't be passed.  
          * You can create /sbin/ccs-start by "ln -s /bin/true /sbin/ccs-start", for  
          * only the pathname is needed to activate Mandatory Access Control.  
          */  
         if (strcmp(filename, "/sbin/init") != 0 && strcmp(filename, "/sbin/ccs-start") != 0) return;  
         /*  
          * Don't activate MAC if the path given by 'CCS_loader=' option doesn't exist.  
          * If initrd.img includes /sbin/init but real-root-dev has not mounted on / yet,  
          * activating MAC will block the system since policies are not loaded yet.  
          * So let do_execve() call this function everytime.  
          */  
         {  
                 struct nameidata nd;  
                 if (!ccs_loader) ccs_loader = "/sbin/ccs-init";  
                 if (path_lookup(ccs_loader, lookup_flags, &nd)) {  
                         printk("Not activating Mandatory Access Control now since %s doesn't exist.\n", ccs_loader);  
                         return;  
                 }  
                 path_release(&nd);  
         }  
         if (!profile_loaded) {  
                 char *argv[2], *envp[3];  
                 printk("Calling %s to load policy. Please wait.\n", ccs_loader);  
                 argv[0] = (char *) ccs_loader;  
                 argv[1] = NULL;  
                 envp[0] = "HOME=/";  
                 envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";  
                 envp[2] = NULL;  
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)  
                 call_usermodehelper(argv[0], argv, envp, 1);  
 #else  
                 call_usermodehelper(argv[0], argv, envp);  
 #endif  
                 while (!profile_loaded) {  
                         set_current_state(TASK_INTERRUPTIBLE);  
                         schedule_timeout(HZ / 10);  
                 }  
         }  
 #ifdef CONFIG_SAKURA  
         printk("SAKURA: 1.5.3-pre   2008/01/02\n");  
 #endif  
 #ifdef CONFIG_TOMOYO  
         printk("TOMOYO: 1.5.3-pre   2008/01/02\n");  
 #endif  
         //if (!profile_loaded) panic("No profiles loaded. Run policy loader using 'init=' option.\n");  
         printk("Mandatory Access Control activated.\n");  
         sbin_init_started = 1;  
         ccs_log_level = KERN_WARNING;  
         { /* Check all profiles currently assigned to domains are defined. */  
                 struct domain_info *domain;  
                 list1_for_each_entry(domain, &domain_list, list) {  
                         const u8 profile = domain->profile;  
                         if (!profile_ptr[profile]) panic("Profile %u (used by '%s') not defined.\n", profile, domain->domainname->name);  
                 }  
         }  
 }  
   
   
 /*************************  MAC Decision Delayer  *************************/  
   
 static DECLARE_WAIT_QUEUE_HEAD(query_wait);  
   
 static spinlock_t query_lock = SPIN_LOCK_UNLOCKED;  
   
 struct query_entry {  
         struct list_head list;  
         char *query;  
         int query_len;  
         unsigned int serial;  
         int timer;  
         int answer;  
 };  
   
 static LIST_HEAD(query_list);  
 static atomic_t queryd_watcher = ATOMIC_INIT(0);  
   
 int CheckSupervisor(const char *fmt, ...)  
 {  
         va_list args;  
         int error = -EPERM;  
         int pos, len;  
         static unsigned int serial = 0;  
         struct query_entry *query_entry;  
         if (!CheckCCSFlags(CCS_ALLOW_ENFORCE_GRACE) || !atomic_read(&queryd_watcher)) {  
 #ifdef ALT_EXEC  
                 if ((current->tomoyo_flags & CCS_DONT_SLEEP_ON_ENFORCE_ERROR) == 0) {  
                         int i;  
                         for (i = 0; i < CheckCCSFlags(CCS_SLEEP_PERIOD); i++) {  
                                 set_current_state(TASK_INTERRUPTIBLE);  
                                 schedule_timeout(HZ / 10);  
                         }  
                 }  
 #endif  
                 return -EPERM;  
         }  
         va_start(args, fmt);  
         len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 32;  
         va_end(args);  
         if ((query_entry = ccs_alloc(sizeof(*query_entry))) == NULL ||  
                 (query_entry->query = ccs_alloc(len)) == NULL) goto out;  
         INIT_LIST_HEAD(&query_entry->list);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         query_entry->serial = serial++;  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         pos = snprintf(query_entry->query, len - 1, "Q%u\n", query_entry->serial);  
         va_start(args, fmt);  
         vsnprintf(query_entry->query + pos, len - 1 - pos, fmt, args);  
         query_entry->query_len = strlen(query_entry->query) + 1;  
         va_end(args);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_add_tail(&query_entry->list, &query_list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         UpdateCounter(CCS_UPDATES_COUNTER_QUERY);  
         /* Give 10 seconds for supervisor's opinion. */  
         for (query_entry->timer = 0; atomic_read(&queryd_watcher) && CheckCCSFlags(CCS_ALLOW_ENFORCE_GRACE) && query_entry->timer < 100; query_entry->timer++) {  
                 wake_up(&query_wait);  
                 set_current_state(TASK_INTERRUPTIBLE);  
                 schedule_timeout(HZ / 10);  
                 if (query_entry->answer) break;  
         }  
         UpdateCounter(CCS_UPDATES_COUNTER_QUERY);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_del(&query_entry->list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         switch (query_entry->answer) {  
         case 1:  
                 /* Granted by administrator. */  
                 error = 0;  
                 break;  
         case 0:  
                 /* Timed out. */  
                 break;  
         default:  
                 /* Rejected by administrator. */  
                 break;  
         }  
  out: ;  
         if (query_entry) ccs_free(query_entry->query);  
         ccs_free(query_entry);  
         return error;  
 }  
   
 static int PollQuery(struct file *file, poll_table *wait)  
 {  
         int found;  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         found = !list_empty(&query_list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         if (found) return POLLIN | POLLRDNORM;  
         poll_wait(file, &query_wait, wait);  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         found = !list_empty(&query_list);  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         if (found) return POLLIN | POLLRDNORM;  
         return 0;  
 }  
   
 static int ReadQuery(struct io_buffer *head)  
 {  
         struct list_head *tmp;  
         int pos = 0, len = 0;  
         char *buf;  
         if (head->read_avail) return 0;  
         if (head->read_buf) {  
                 ccs_free(head->read_buf); head->read_buf = NULL;  
                 head->readbuf_size = 0;  
         }  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_for_each(tmp, &query_list) {  
                 struct query_entry *ptr = list_entry(tmp, struct query_entry, list);  
                 if (pos++ == head->read_step) {  
                         len = ptr->query_len;  
1110                          break;                          break;
1111                  }                  case CCS_TYPE_PATH_NUMBER_ACL:
1112          }                          perm = container_of(ptr, struct ccs_path_number_acl,
1113          spin_unlock(&query_lock);                                              head)->perm;
1114          /***** CRITICAL SECTION END *****/                          for (i = 0; i < CCS_MAX_PATH_NUMBER_OPERATION; i++)
1115          if (!len) {                                  if (perm & (1 << i))
1116                  head->read_step = 0;                                          count++;
1117                  return 0;                          break;
1118          }                  case CCS_TYPE_PATH_NUMBER3_ACL:
1119          if ((buf = ccs_alloc(len)) != NULL) {                          perm = container_of(ptr,
1120                  pos = 0;                                              struct ccs_path_number3_acl,
1121                  /***** CRITICAL SECTION START *****/                                              head)->perm;
1122                  spin_lock(&query_lock);                          for (i = 0; i < CCS_MAX_PATH_NUMBER3_OPERATION;
1123                  list_for_each(tmp, &query_list) {                               i++)
1124                          struct query_entry *ptr = list_entry(tmp, struct query_entry, list);                                  if (perm & (1 << i))
1125                          if (pos++ == head->read_step) {                                          count++;
                                 /* Some query can be skiipped since query_list can change, but I don't care. */  
                                 if (len == ptr->query_len) memmove(buf, ptr->query, len);  
                                 break;  
                         }  
                 }  
                 spin_unlock(&query_lock);  
                 /***** CRITICAL SECTION END *****/  
                 if (buf[0]) {  
                         head->readbuf_size = head->read_avail = len;  
                         head->read_buf = buf;  
                         head->read_step++;  
                 } else {  
                         ccs_free(buf);  
                 }  
         }  
         return 0;  
 }  
   
 static int WriteAnswer(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         struct list_head *tmp;  
         unsigned int serial, answer;  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_for_each(tmp, &query_list) {  
                 struct query_entry *ptr = list_entry(tmp, struct query_entry, list);  
                 ptr->timer = 0;  
         }  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         if (sscanf(data, "A%u=%u", &serial, &answer) != 2) return -EINVAL;  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&query_lock);  
         list_for_each(tmp, &query_list) {  
                 struct query_entry *ptr = list_entry(tmp, struct query_entry, list);  
                 if (ptr->serial != serial) continue;  
                 if (!ptr->answer) ptr->answer = answer;  
                 break;  
         }  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         return 0;  
 }  
   
 /*************************  /proc INTERFACE HANDLER  *************************/  
   
 /* Policy updates counter. */  
 static unsigned int updates_counter[MAX_CCS_UPDATES_COUNTER];  
 static spinlock_t updates_counter_lock = SPIN_LOCK_UNLOCKED;  
   
 void UpdateCounter(const unsigned char index)  
 {  
         /***** CRITICAL SECTION START *****/  
         spin_lock(&updates_counter_lock);  
         if (index < MAX_CCS_UPDATES_COUNTER) updates_counter[index]++;  
         spin_unlock(&updates_counter_lock);  
         /***** CRITICAL SECTION END *****/  
 }  
   
 static int ReadUpdatesCounter(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 unsigned int counter[MAX_CCS_UPDATES_COUNTER];  
                 /***** CRITICAL SECTION START *****/  
                 spin_lock(&updates_counter_lock);  
                 memmove(counter, updates_counter, sizeof(updates_counter));  
                 memset(updates_counter, 0, sizeof(updates_counter));  
                 spin_unlock(&updates_counter_lock);  
                 /***** CRITICAL SECTION END *****/  
                 io_printf(head,  
                                   "/proc/ccs/system_policy:    %10u\n"  
                                   "/proc/ccs/domain_policy:    %10u\n"  
                                   "/proc/ccs/exception_policy: %10u\n"  
                                   "/proc/ccs/profile:          %10u\n"  
                                   "/proc/ccs/query:            %10u\n"  
                                   "/proc/ccs/manager:          %10u\n"  
                                   "/proc/ccs/grant_log:        %10u\n"  
                                   "/proc/ccs/reject_log:       %10u\n",  
                                   counter[CCS_UPDATES_COUNTER_SYSTEM_POLICY],  
                                   counter[CCS_UPDATES_COUNTER_DOMAIN_POLICY],  
                                   counter[CCS_UPDATES_COUNTER_EXCEPTION_POLICY],  
                                   counter[CCS_UPDATES_COUNTER_PROFILE],  
                                   counter[CCS_UPDATES_COUNTER_QUERY],  
                                   counter[CCS_UPDATES_COUNTER_MANAGER],  
                                   counter[CCS_UPDATES_COUNTER_GRANT_LOG],  
                                   counter[CCS_UPDATES_COUNTER_REJECT_LOG]);  
                 head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 static int ReadVersion(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 if (io_printf(head, "1.5.3-pre") == 0) head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 static int ReadMemoryCounter(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 const int shared = GetMemoryUsedForSaveName(), private = GetMemoryUsedForElements(), dynamic = GetMemoryUsedForDynamic();  
                 if (io_printf(head, "Shared:  %10u\nPrivate: %10u\nDynamic: %10u\nTotal:   %10u\n", shared, private, dynamic, shared + private + dynamic) == 0) head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 static int ReadSelfDomain(struct io_buffer *head)  
 {  
         if (!head->read_eof) {  
                 io_printf(head, "%s", current->domain_info->domainname->name);  
                 head->read_eof = 1;  
         }  
         return 0;  
 }  
   
 int CCS_OpenControl(const u8 type, struct file *file)  
 {  
         struct io_buffer *head = ccs_alloc(sizeof(*head));  
         if (!head) return -ENOMEM;  
         mutex_init(&head->read_sem);  
         mutex_init(&head->write_sem);  
         switch (type) {  
 #ifdef CONFIG_SAKURA  
         case CCS_SYSTEMPOLICY:  
                 head->write = AddSystemPolicy;  
                 head->read = ReadSystemPolicy;  
                 break;  
 #endif  
 #ifdef CONFIG_TOMOYO  
         case CCS_DOMAINPOLICY:  
                 head->write = AddDomainPolicy;  
                 head->read = ReadDomainPolicy;  
                 break;  
         case CCS_EXCEPTIONPOLICY:  
                 head->write = AddExceptionPolicy;  
                 head->read = ReadExceptionPolicy;  
                 break;  
         case CCS_GRANTLOG:  
                 head->poll = PollGrantLog;  
                 head->read = ReadGrantLog;  
                 break;  
         case CCS_REJECTLOG:  
                 head->poll = PollRejectLog;  
                 head->read = ReadRejectLog;  
                 break;  
 #endif  
         case CCS_SELFDOMAIN:  
                 head->read = ReadSelfDomain;  
                 break;  
         case CCS_DOMAIN_STATUS:  
                 head->write = UpdateDomainProfile;  
                 head->read = ReadDomainProfile;  
                 break;  
         case CCS_PROCESS_STATUS:  
                 head->write = WritePID;  
                 head->read = ReadPID;  
                 break;  
         case CCS_VERSION:  
                 head->read = ReadVersion;  
                 head->readbuf_size = 128;  
                 break;  
         case CCS_MEMINFO:  
                 head->read = ReadMemoryCounter;  
                 head->readbuf_size = 128;  
                 break;  
         case CCS_PROFILE:  
                 head->write = SetProfile;  
                 head->read = ReadProfile;  
                 break;  
         case CCS_QUERY:  
                 head->poll = PollQuery;  
                 head->write = WriteAnswer;  
                 head->read = ReadQuery;  
                 break;  
         case CCS_MANAGER:  
                 head->write = AddManagerPolicy;  
                 head->read = ReadManagerPolicy;  
                 break;  
         case CCS_UPDATESCOUNTER:  
                 head->read = ReadUpdatesCounter;  
                 break;  
         }  
         if (type != CCS_GRANTLOG && type != CCS_REJECTLOG && type != CCS_QUERY) {  
                 if (!head->readbuf_size) head->readbuf_size = PAGE_SIZE * 2;  
                 if ((head->read_buf = ccs_alloc(head->readbuf_size)) == NULL) {  
                         ccs_free(head);  
                         return -ENOMEM;  
                 }  
         }  
         if (head->write) {  
                 head->writebuf_size = PAGE_SIZE * 2;  
                 if ((head->write_buf = ccs_alloc(head->writebuf_size)) == NULL) {  
                         ccs_free(head->read_buf);  
                         ccs_free(head);  
                         return -ENOMEM;  
                 }  
         }  
         file->private_data = head;  
         if (type == CCS_SELFDOMAIN) CCS_ReadControl(file, NULL, 0);  
         else if (head->write == WriteAnswer) atomic_inc(&queryd_watcher);  
         return 0;  
 }  
   
 static int CopyToUser(struct io_buffer *head, char __user * buffer, int buffer_len)  
 {  
         int len = head->read_avail;  
         char *cp = head->read_buf;  
         if (len > buffer_len) len = buffer_len;  
         if (len) {  
                 if (copy_to_user(buffer, cp, len)) return -EFAULT;  
                 head->read_avail -= len;  
                 memmove(cp, cp + len, head->read_avail);  
         }  
         return len;  
 }  
   
 int CCS_PollControl(struct file *file, poll_table *wait)  
 {  
         struct io_buffer *head = file->private_data;  
         if (!head->poll) return -ENOSYS;  
         return head->poll(file, wait);  
 }  
   
 int CCS_ReadControl(struct file *file, char __user *buffer, const int buffer_len)  
 {  
         int len = 0;  
         struct io_buffer *head = file->private_data;  
         if (!head->read) return -ENOSYS;  
         if (!access_ok(VERIFY_WRITE, buffer, buffer_len)) return -EFAULT;  
         if (mutex_lock_interruptible(&head->read_sem)) return -EINTR;  
         len = head->read(head);  
         if (len >= 0) len = CopyToUser(head, buffer, buffer_len);  
         mutex_unlock(&head->read_sem);  
         return len;  
 }  
   
 int CCS_WriteControl(struct file *file, const char __user *buffer, const int buffer_len)  
 {  
         struct io_buffer *head = file->private_data;  
         int error = buffer_len;  
         int avail_len = buffer_len;  
         char *cp0 = head->write_buf;  
         if (!head->write) return -ENOSYS;  
         if (!access_ok(VERIFY_READ, buffer, buffer_len)) return -EFAULT;  
         if (!isRoot()) return -EPERM;  
         if (head->write != WritePID && !IsPolicyManager()) {  
                 return -EPERM; /* Forbid updating policies for non manager programs. */  
         }  
         if (mutex_lock_interruptible(&head->write_sem)) return -EINTR;  
         while (avail_len > 0) {  
                 char c;  
                 if (head->write_avail >= head->writebuf_size - 1) {  
                         error = -ENOMEM;  
1126                          break;                          break;
1127                  } else if (get_user(c, buffer)) {                  case CCS_TYPE_IP_NETWORK_ACL:
1128                          error = -EFAULT;                          perm = container_of(ptr, struct ccs_ip_network_acl,
1129                                                head)->perm;
1130                            for (i = 0; i < CCS_MAX_NETWORK_OPERATION; i++)
1131                                    if (perm & (1 << i))
1132                                            count++;
1133                          break;                          break;
1134                    default:
1135                            count++;
1136                  }                  }
1137                  buffer++; avail_len--;          }
1138                  cp0[head->write_avail++] = c;          if (count < ccs_flags(domain, CCS_MAX_ACCEPT_ENTRY))
1139                  if (c != '\n') continue;                  return true;
1140                  cp0[head->write_avail - 1] = '\0';          if (!domain->quota_warned) {
1141                  head->write_avail = 0;                  domain->quota_warned = true;
1142                  NormalizeLine(cp0);                  printk(KERN_WARNING "WARNING: "
1143                  head->write(head);                         "Domain '%s' has so many ACLs to hold. "
1144          }                         "Stopped learning mode.\n", domain->domainname->name);
1145          mutex_unlock(&head->write_sem);          }
1146          return error;          return false;
 }  
   
   
 int CCS_CloseControl(struct file *file)  
 {  
         struct io_buffer *head = file->private_data;  
         if (head->write == WriteAnswer) atomic_dec(&queryd_watcher);  
         else if (head->read == ReadMemoryCounter) profile_loaded = 1;  
         ccs_free(head->read_buf); head->read_buf = NULL;  
         ccs_free(head->write_buf); head->write_buf = NULL;  
         ccs_free(head); head = NULL;  
         file->private_data = NULL;  
         return 0;  
1147  }  }

Legend:
Removed from v.853  
changed lines
  Added in v.2951

Back to OSDN">Back to OSDN
ViewVC Help
Powered by ViewVC 1.1.26