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

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 813 by kumaneko, Tue Dec 18 05:35:28 2007 UTC branches/ccs-patch/security/ccsecurity/util.c revision 2911 by kumaneko, Sat Aug 15 12:21:38 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-2007  NTT DATA CORPORATION   * Version: 1.7.0-pre   2009/08/08
  *  
  * Version: 1.5.3-pre   2007/12/18  
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  DEFINE_MUTEX(ccs_policy_lock);
 #define MAX_ACCEPT_ENTRY (CONFIG_TOMOYO_MAX_ACCEPT_ENTRY)  
 #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  
16    
17  /*************************  VARIABLES  *************************/  /* Has /sbin/init started? */
18    bool ccs_policy_loaded;
19    
20  /* /sbin/init started? */  /* Capability name used by domain policy. */
21  int sbin_init_started = 0;  const char *ccs_capability_list[CCS_MAX_CAPABILITY_INDEX] = {
22            [CCS_INET_STREAM_SOCKET_CREATE]  = "inet_tcp_create",
23            [CCS_INET_STREAM_SOCKET_LISTEN]  = "inet_tcp_listen",
24            [CCS_INET_STREAM_SOCKET_CONNECT] = "inet_tcp_connect",
25            [CCS_USE_INET_DGRAM_SOCKET]      = "use_inet_udp",
26            [CCS_USE_INET_RAW_SOCKET]        = "use_inet_ip",
27            [CCS_USE_ROUTE_SOCKET]           = "use_route",
28            [CCS_USE_PACKET_SOCKET]          = "use_packet",
29            [CCS_SYS_MOUNT]                  = "SYS_MOUNT",
30            [CCS_SYS_UMOUNT]                 = "SYS_UMOUNT",
31            [CCS_SYS_REBOOT]                 = "SYS_REBOOT",
32            [CCS_SYS_CHROOT]                 = "SYS_CHROOT",
33            [CCS_SYS_KILL]                   = "SYS_KILL",
34            [CCS_SYS_VHANGUP]                = "SYS_VHANGUP",
35            [CCS_SYS_SETTIME]                = "SYS_TIME",
36            [CCS_SYS_NICE]                   = "SYS_NICE",
37            [CCS_SYS_SETHOSTNAME]            = "SYS_SETHOSTNAME",
38            [CCS_USE_KERNEL_MODULE]          = "use_kernel_module",
39            [CCS_CREATE_FIFO]                = "create_fifo",
40            [CCS_CREATE_BLOCK_DEV]           = "create_block_dev",
41            [CCS_CREATE_CHAR_DEV]            = "create_char_dev",
42            [CCS_CREATE_UNIX_SOCKET]         = "create_unix_socket",
43            [CCS_SYS_LINK]                   = "SYS_LINK",
44            [CCS_SYS_SYMLINK]                = "SYS_SYMLINK",
45            [CCS_SYS_RENAME]                 = "SYS_RENAME",
46            [CCS_SYS_UNLINK]                 = "SYS_UNLINK",
47            [CCS_SYS_CHMOD]                  = "SYS_CHMOD",
48            [CCS_SYS_CHOWN]                  = "SYS_CHOWN",
49            [CCS_SYS_IOCTL]                  = "SYS_IOCTL",
50            [CCS_SYS_KEXEC_LOAD]             = "SYS_KEXEC_LOAD",
51            [CCS_SYS_PIVOT_ROOT]             = "SYS_PIVOT_ROOT",
52            [CCS_SYS_PTRACE]                 = "SYS_PTRACE",
53            [CCS_CONCEAL_MOUNT]              = "conceal_mount",
54    };
55    
56  const char *ccs_log_level = KERN_DEBUG;  /* Profile table. Memory is allocated as needed. */
57    struct ccs_profile *ccs_profile_ptr[CCS_MAX_PROFILES];
58    
59  static struct {  /* Utility functions. */
         const char *keyword;  
         unsigned int current_value;  
         const unsigned int max_value;  
 } ccs_control_array[CCS_MAX_CONTROL_INDEX] = {  
         [CCS_PROFILE_COMMENT]            = { "COMMENT",             0, 0 }, /* Reserved for string. */  
         [CCS_TOMOYO_MAC_FOR_FILE]        = { "MAC_FOR_FILE",        0, 3 },  
         [CCS_TOMOYO_MAC_FOR_ARGV0]       = { "MAC_FOR_ARGV0",       0, 3 },  
         [CCS_TOMOYO_MAC_FOR_ENV]         = { "MAC_FOR_ENV",         0, 3 },  
         [CCS_TOMOYO_MAC_FOR_NETWORK]     = { "MAC_FOR_NETWORK",     0, 3 },  
         [CCS_TOMOYO_MAC_FOR_SIGNAL]      = { "MAC_FOR_SIGNAL",      0, 3 },  
         [CCS_SAKURA_DENY_CONCEAL_MOUNT]  = { "DENY_CONCEAL_MOUNT",  0, 3 },  
         [CCS_SAKURA_RESTRICT_CHROOT]     = { "RESTRICT_CHROOT",     0, 3 },  
         [CCS_SAKURA_RESTRICT_MOUNT]      = { "RESTRICT_MOUNT",      0, 3 },  
         [CCS_SAKURA_RESTRICT_UNMOUNT]    = { "RESTRICT_UNMOUNT",    0, 3 },  
         [CCS_SAKURA_RESTRICT_PIVOT_ROOT] = { "RESTRICT_PIVOT_ROOT", 0, 3 },  
         [CCS_SAKURA_RESTRICT_AUTOBIND]   = { "RESTRICT_AUTOBIND",   0, 1 },  
         [CCS_TOMOYO_MAX_ACCEPT_ENTRY]    = { "MAX_ACCEPT_ENTRY",    MAX_ACCEPT_ENTRY, INT_MAX },  
         [CCS_TOMOYO_MAX_GRANT_LOG]       = { "MAX_GRANT_LOG",       MAX_GRANT_LOG, INT_MAX },  
         [CCS_TOMOYO_MAX_REJECT_LOG]      = { "MAX_REJECT_LOG",      MAX_REJECT_LOG, INT_MAX },  
         [CCS_TOMOYO_VERBOSE]             = { "TOMOYO_VERBOSE",      1, 1 },  
         [CCS_ALLOW_ENFORCE_GRACE]        = { "ALLOW_ENFORCE_GRACE", 0, 1 },  
         [CCS_SLEEP_PERIOD]               = { "SLEEP_PERIOD",        0, 3000 }, /* in 0.1 second */  
         [CCS_TOMOYO_ALT_EXEC]            = { "ALT_EXEC",            0, 0 }, /* Reserved for string. */  
 };  
60    
61  struct profile {  /**
62          unsigned int value[CCS_MAX_CONTROL_INDEX];   * ccs_parse_ulong - Parse an "unsigned long" value.
63          const struct path_info *comment;   *
64          const struct path_info *alt_exec;   * @result: Pointer to "unsigned long".
65  };   * @str:    Pointer to string to parse.
66     *
67     * Returns value type on success, 0 otherwise.
68     *
69     * The @src is updated to point the first character after the value
70     * on success.
71     */
72    u8 ccs_parse_ulong(unsigned long *result, char **str)
73    {
74            const char *cp = *str;
75            char *ep;
76            int base = 10;
77            if (*cp == '0') {
78                    char c = *(cp + 1);
79                    if (c == 'x' || c == 'X') {
80                            base = 16;
81                            cp += 2;
82                    } else if (c >= '0' && c <= '7') {
83                            base = 8;
84                            cp++;
85                    }
86            }
87            *result = simple_strtoul(cp, &ep, base);
88            if (cp == ep)
89                    return 0;
90            *str = ep;
91            switch (base) {
92            case 16:
93                    return CCS_VALUE_TYPE_HEXADECIMAL;
94            case 8:
95                    return CCS_VALUE_TYPE_OCTAL;
96            default:
97                    return CCS_VALUE_TYPE_DECIMAL;
98            }
99    }
100    
101  static struct profile *profile_ptr[MAX_PROFILES];  /**
102     * ccs_print_ulong - Print an "unsigned long" value.
103     *
104     * @buffer:     Pointer to buffer.
105     * @buffer_len: Size of @buffer.
106     * @value:      An "unsigned long" value.
107     * @type:       Type of @value.
108     *
109     * Returns nothing.
110     */
111    void ccs_print_ulong(char *buffer, const int buffer_len,
112                         const unsigned long value, const u8 type)
113    {
114            if (type == CCS_VALUE_TYPE_DECIMAL)
115                    snprintf(buffer, buffer_len, "%lu", value);
116            else if (type == CCS_VALUE_TYPE_OCTAL)
117                    snprintf(buffer, buffer_len, "0%lo", value);
118            else if (type == CCS_VALUE_TYPE_HEXADECIMAL)
119                    snprintf(buffer, buffer_len, "0x%lX", value);
120            else
121                    snprintf(buffer, buffer_len, "type(%u)", type);
122    }
123    
124    bool ccs_parse_name_union(const char *filename, struct ccs_name_union *ptr)
125    {
126            if (!ccs_is_correct_path(filename, 0, 0, 0))
127                    return false;
128            if (filename[0] == '@') {
129                    ptr->group = ccs_get_path_group(filename + 1);
130                    ptr->is_group = true;
131                    return ptr->group != NULL;
132            }
133            ptr->filename = ccs_get_name(filename);
134            ptr->is_group = false;
135            return ptr->filename != NULL;
136    }
137    
138    bool ccs_parse_number_union(char *data, struct ccs_number_union *num)
139    {
140            u8 type;
141            unsigned long v;
142            memset(num, 0, sizeof(*num));
143            if (data[0] == '@') {
144                    if (!ccs_is_correct_path(data, 0, 0, 0))
145                            return false;
146                    num->group = ccs_get_number_group(data + 1);
147                    num->is_group = true;
148                    return num->group != NULL;
149            }
150            type = ccs_parse_ulong(&v, &data);
151            if (!type)
152                    return false;
153            num->values[0] = v;
154            num->min_type = type;
155            if (!*data) {
156                    num->values[1] = v;
157                    num->max_type = type;
158                    return true;
159            }
160            if (*data++ != '-')
161                    return false;
162            type = ccs_parse_ulong(&v, &data);
163            if (!type || *data)
164                    return false;
165            num->values[1] = v;
166            num->max_type = type;
167            return true;
168    }
169    
170  /*************************  UTILITY FUNCTIONS  *************************/  /**
171     * ccs_is_byte_range - Check whether the string isa \ooo style octal value.
172     *
173     * @str: Pointer to the string.
174     *
175     * Returns true if @str is a \ooo style octal value, false otherwise.
176     */
177    static inline bool ccs_is_byte_range(const char *str)
178    {
179            return *str >= '0' && *str++ <= '3' &&
180                    *str >= '0' && *str++ <= '7' &&
181                    *str >= '0' && *str <= '7';
182    }
183    
184  #ifdef CONFIG_TOMOYO  /**
185  static int __init TOMOYO_Quiet_Setup(char *str)   * ccs_is_decimal - Check whether the character is a decimal character.
186     *
187     * @c: The character to check.
188     *
189     * Returns true if @c is a decimal character, false otherwise.
190     */
191    static inline bool ccs_is_decimal(const char c)
192  {  {
193          ccs_control_array[CCS_TOMOYO_VERBOSE].current_value = 0;          return c >= '0' && c <= '9';
         return 0;  
194  }  }
195    
196  __setup("TOMOYO_QUIET", TOMOYO_Quiet_Setup);  /**
197  #endif   * ccs_is_hexadecimal - Check whether the character is a hexadecimal character.
198     *
199     * @c: The character to check.
200     *
201     * Returns true if @c is a hexadecimal character, false otherwise.
202     */
203    static inline bool ccs_is_hexadecimal(const char c)
204    {
205            return (c >= '0' && c <= '9') ||
206                    (c >= 'A' && c <= 'F') ||
207                    (c >= 'a' && c <= 'f');
208    }
209    
210  /* Am I root? */  /**
211  static int isRoot(void)   * ccs_is_alphabet_char - Check whether the character is an alphabet.
212     *
213     * @c: The character to check.
214     *
215     * Returns true if @c is an alphabet character, false otherwise.
216     */
217    static inline bool ccs_is_alphabet_char(const char c)
218  {  {
219          return !current->uid && !current->euid;          return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
220  }  }
221    
222  /*  /**
223   * Format string.   * ccs_make_byte - Make byte value from three octal characters.
224     *
225     * @c1: The first character.
226     * @c2: The second character.
227     * @c3: The third character.
228     *
229     * Returns byte value.
230     */
231    static inline u8 ccs_make_byte(const u8 c1, const u8 c2, const u8 c3)
232    {
233            return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
234    }
235    
236    /**
237     * ccs_str_starts - Check whether the given string starts with the given keyword.
238     *
239     * @src:  Pointer to pointer to the string.
240     * @find: Pointer to the keyword.
241     *
242     * Returns true if @src starts with @find, false otherwise.
243     *
244     * The @src is updated to point the first character after the @find
245     * if @src starts with @find.
246     */
247    bool ccs_str_starts(char **src, const char *find)
248    {
249            const int len = strlen(find);
250            char *tmp = *src;
251            if (strncmp(tmp, find, len))
252                    return false;
253            tmp += len;
254            *src = tmp;
255            return true;
256    }
257    
258    /**
259     * ccs_normalize_line - Format string.
260     *
261     * @buffer: The line to normalize.
262     *
263   * Leading and trailing whitespaces are removed.   * Leading and trailing whitespaces are removed.
264   * Multiple whitespaces are packed into single space.   * Multiple whitespaces are packed into single space.
265     *
266     * Returns nothing.
267   */   */
268  static void NormalizeLine(unsigned char *buffer)  void ccs_normalize_line(unsigned char *buffer)
269  {  {
270          unsigned char *sp = buffer, *dp = buffer;          unsigned char *sp = buffer;
271          int first = 1;          unsigned char *dp = buffer;
272          while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;          bool first = true;
273            while (*sp && (*sp <= ' ' || *sp >= 127))
274                    sp++;
275          while (*sp) {          while (*sp) {
276                  if (!first) *dp++ = ' ';                  if (!first)
277                  first = 0;                          *dp++ = ' ';
278                  while (*sp > ' ' && *sp < 127) *dp++ = *sp++;                  first = false;
279                  while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;                  while (*sp > ' ' && *sp < 127)
280                            *dp++ = *sp++;
281                    while (*sp && (*sp <= ' ' || *sp >= 127))
282                            sp++;
283          }          }
284          *dp = '\0';          *dp = '\0';
285  }  }
286    
287  /*  /**
288   *  Check whether the given filename follows the naming rules.   * ccs_tokenize - Tokenize string.
289   *  Returns nonzero if follows, zero otherwise.   *
290     * @buffer: The line to tokenize.
291     * @w:      Pointer to "char *".
292     * @size:   Sizeof @w .
293     *
294     * Returns true on success, false otherwise.
295     */
296    bool ccs_tokenize(char *buffer, char *w[], size_t size)
297    {
298            int count = size / sizeof(char *);
299            int i;
300            for (i = 0; i < count; i++)
301                    w[i] = "";
302            for (i = 0; i < count; i++) {
303                    char *cp = strchr(buffer, ' ');
304                    if (cp)
305                            *cp = '\0';
306                    w[i] = buffer;
307                    if (!cp)
308                            break;
309                    buffer = cp + 1;
310            }
311            return i < count || !*buffer;
312    }
313    
314    /**
315     * ccs_is_correct_path - Validate a pathname.
316     * @filename:     The pathname to check.
317     * @start_type:   Should the pathname start with '/'?
318     *                1 = must / -1 = must not / 0 = don't care
319     * @pattern_type: Can the pathname contain a wildcard?
320     *                1 = must / -1 = must not / 0 = don't care
321     * @end_type:     Should the pathname end with '/'?
322     *                1 = must / -1 = must not / 0 = don't care
323     *
324     * Check whether the given filename follows the naming rules.
325     * Returns true if @filename follows the naming rules, false otherwise.
326   */   */
327  bool IsCorrectPath(const char *filename, const int start_type, const int pattern_type, const int end_type, const char *function)  bool ccs_is_correct_path(const char *filename, const s8 start_type,
328                             const s8 pattern_type, const s8 end_type)
329  {  {
330          int contains_pattern = 0;          bool contains_pattern = false;
331          char c, d, e;          unsigned char c;
332            unsigned char d;
333            unsigned char e;
334          const char *original_filename = filename;          const char *original_filename = filename;
335          if (!filename) goto out;          if (!filename)
336                    goto out;
337          c = *filename;          c = *filename;
338          if (start_type == 1) { /* Must start with '/' */          if (start_type == 1) { /* Must start with '/' */
339                  if (c != '/') goto out;                  if (c != '/')
340                            goto out;
341          } else if (start_type == -1) { /* Must not start with '/' */          } else if (start_type == -1) { /* Must not start with '/' */
342                  if (c == '/') goto out;                  if (c == '/')
343                            goto out;
344          }          }
345          if (c) c = * (strchr(filename, '\0') - 1);          if (c)
346                    c = *(filename + strlen(filename) - 1);
347          if (end_type == 1) { /* Must end with '/' */          if (end_type == 1) { /* Must end with '/' */
348                  if (c != '/') goto out;                  if (c != '/')
349                            goto out;
350          } else if (end_type == -1) { /* Must not end with '/' */          } else if (end_type == -1) { /* Must not end with '/' */
351                  if (c == '/') goto out;                  if (c == '/')
352                            goto out;
353          }          }
354          while ((c = *filename++) != '\0') {          while (1) {
355                    c = *filename++;
356                    if (!c)
357                            break;
358                  if (c == '\\') {                  if (c == '\\') {
359                          switch ((c = *filename++)) {                          c = *filename++;
360                            switch (c) {
361                          case '\\':  /* "\\" */                          case '\\':  /* "\\" */
362                                  continue;                                  continue;
363                          case '$':   /* "\$" */                          case '$':   /* "\$" */
# Line 164  bool IsCorrectPath(const char *filename, Line 370  bool IsCorrectPath(const char *filename,
370                          case 'a':   /* "\a" */                          case 'a':   /* "\a" */
371                          case 'A':   /* "\A" */                          case 'A':   /* "\A" */
372                          case '-':   /* "\-" */                          case '-':   /* "\-" */
373                                  if (pattern_type == -1) break; /* Must not contain pattern */                                  if (pattern_type == -1)
374                                  contains_pattern = 1;                                          break; /* Must not contain pattern */
375                                    contains_pattern = true;
376                                  continue;                                  continue;
377                          case '0':   /* "\ooo" */                          case '0':   /* "\ooo" */
378                          case '1':                          case '1':
379                          case '2':                          case '2':
380                          case '3':                          case '3':
381                                  if ((d = *filename++) >= '0' && d <= '7' && (e = *filename++) >= '0' && e <= '7') {                                  d = *filename++;
382                                          const unsigned char f =                                  if (d < '0' || d > '7')
383                                                  (((unsigned char) (c - '0')) << 6) +                                          break;
384                                                  (((unsigned char) (d - '0')) << 3) +                                  e = *filename++;
385                                                  (((unsigned char) (e - '0')));                                  if (e < '0' || e > '7')
386                                          if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                          break;
387                                  }                                  c = ccs_make_byte(c, d, e);
388                                    if (c && (c <= ' ' || c >= 127))
389                                            continue; /* pattern is not \000 */
390                          }                          }
391                          goto out;                          goto out;
392                  } else if (c <= ' ' || c >= 127) {                  } else if (c <= ' ' || c >= 127) {
# Line 185  bool IsCorrectPath(const char *filename, Line 394  bool IsCorrectPath(const char *filename,
394                  }                  }
395          }          }
396          if (pattern_type == 1) { /* Must contain pattern */          if (pattern_type == 1) { /* Must contain pattern */
397                  if (!contains_pattern) goto out;                  if (!contains_pattern)
398                            goto out;
399          }          }
400          return 1;          return true;
401   out:   out:
402          printk(KERN_DEBUG "%s: Invalid pathname '%s'\n", function, original_filename);          printk(KERN_DEBUG "Invalid pathname '%s'\n", original_filename);
403          return 0;          return false;
404  }  }
405    
406  /*  /**
407   *  Check whether the given domainname follows the naming rules.   * ccs_is_correct_domain - Check whether the given domainname follows the naming rules.
408   *  Returns nonzero if follows, zero otherwise.   * @domainname:   The domainname to check.
409     *
410     * Returns true if @domainname follows the naming rules, false otherwise.
411   */   */
412  bool IsCorrectDomain(const unsigned char *domainname, const char *function)  bool ccs_is_correct_domain(const unsigned char *domainname)
413  {  {
414          unsigned char c, d, e;          unsigned char c;
415            unsigned char d;
416            unsigned char e;
417          const char *org_domainname = domainname;          const char *org_domainname = domainname;
418          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN)) goto out;          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN))
419                    goto out;
420          domainname += ROOT_NAME_LEN;          domainname += ROOT_NAME_LEN;
421          if (!*domainname) return 1;          if (!*domainname)
422                    return true;
423          do {          do {
424                  if (*domainname++ != ' ') goto out;                  if (*domainname++ != ' ')
425                  if (*domainname++ != '/') goto out;                          goto out;
426                  while ((c = *domainname) != '\0' && c != ' ') {                  if (*domainname++ != '/')
427                            goto out;
428                    while (1) {
429                            c = *domainname;
430                            if (!c || c == ' ')
431                                    break;
432                          domainname++;                          domainname++;
433                          if (c == '\\') {                          if (c == '\\') {
434                                  switch ((c = *domainname++)) {                                  c = *domainname++;
435                                    switch ((c)) {
436                                  case '\\':  /* "\\" */                                  case '\\':  /* "\\" */
437                                          continue;                                          continue;
438                                  case '0':   /* "\ooo" */                                  case '0':   /* "\ooo" */
439                                  case '1':                                  case '1':
440                                  case '2':                                  case '2':
441                                  case '3':                                  case '3':
442                                          if ((d = *domainname++) >= '0' && d <= '7' && (e = *domainname++) >= '0' && e <= '7') {                                          d = *domainname++;
443                                                  const unsigned char f =                                          if (d < '0' || d > '7')
444                                                          (((unsigned char) (c - '0')) << 6) +                                                  break;
445                                                          (((unsigned char) (d - '0')) << 3) +                                          e = *domainname++;
446                                                          (((unsigned char) (e - '0')));                                          if (e < '0' || e > '7')
447                                                  if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                                  break;
448                                          }                                          c = ccs_make_byte(c, d, e);
449                                            if (c && (c <= ' ' || c >= 127))
450                                                    /* pattern is not \000 */
451                                                    continue;
452                                  }                                  }
453                                  goto out;                                  goto out;
454                          } else if (c < ' ' || c >= 127) {                          } else if (c < ' ' || c >= 127) {
# Line 231  bool IsCorrectDomain(const unsigned char Line 456  bool IsCorrectDomain(const unsigned char
456                          }                          }
457                  }                  }
458          } while (*domainname);          } while (*domainname);
459          return 1;          return true;
460   out:   out:
461          printk(KERN_DEBUG "%s: Invalid domainname '%s'\n", function, org_domainname);          printk(KERN_DEBUG "Invalid domainname '%s'\n", org_domainname);
462          return 0;          return false;
463  }  }
464    
465  bool IsDomainDef(const unsigned char *buffer)  /**
466     * ccs_is_domain_def - Check whether the given token can be a domainname.
467     *
468     * @buffer: The token to check.
469     *
470     * Returns true if @buffer possibly be a domainname, false otherwise.
471     */
472    bool ccs_is_domain_def(const unsigned char *buffer)
473  {  {
474          /* while (*buffer && (*buffer <= ' ' || *buffer >= 127)) buffer++; */          return !strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN);
         return strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN) == 0;  
475  }  }
476    
477  struct domain_info *FindDomain(const char *domainname0)  /**
478     * ccs_find_domain - Find a domain by the given name.
479     *
480     * @domainname: The domainname to find.
481     *
482     * Returns pointer to "struct ccs_domain_info" if found, NULL otherwise.
483     *
484     * Caller holds ccs_read_lock().
485     */
486    struct ccs_domain_info *ccs_find_domain(const char *domainname)
487  {  {
488          struct domain_info *domain;          struct ccs_domain_info *domain;
489          struct path_info domainname;          struct ccs_path_info name;
490          domainname.name = domainname0;          ccs_check_read_lock();
491          fill_path_info(&domainname);          name.name = domainname;
492          list1_for_each_entry(domain, &domain_list, list) {          ccs_fill_path_info(&name);
493                  if (!domain->is_deleted && !pathcmp(&domainname, domain->domainname)) return domain;          list_for_each_entry_rcu(domain, &ccs_domain_list, list) {
494                    if (!domain->is_deleted &&
495                        !ccs_pathcmp(&name, domain->domainname))
496                            return domain;
497          }          }
498          return NULL;          return NULL;
499  }  }
500    
501  static int PathDepth(const char *pathname)  /**
502     * ccs_path_depth - Evaluate the number of '/' in a string.
503     *
504     * @pathname: The string to evaluate.
505     *
506     * Returns path depth of the string.
507     *
508     * I score 2 for each of the '/' in the @pathname
509     * and score 1 if the @pathname ends with '/'.
510     */
511    static int ccs_path_depth(const char *pathname)
512  {  {
513          int i = 0;          int i = 0;
514          if (pathname) {          if (pathname) {
515                  char *ep = strchr(pathname, '\0');                  const char *ep = pathname + strlen(pathname);
516                  if (pathname < ep--) {                  if (pathname < ep--) {
517                          if (*ep != '/') i++;                          if (*ep != '/')
518                          while (pathname <= ep) if (*ep-- == '/') i += 2;                                  i++;
519                            while (pathname <= ep)
520                                    if (*ep-- == '/')
521                                            i += 2;
522                  }                  }
523          }          }
524          return i;          return i;
525  }  }
526    
527  static int const_part_length(const char *filename)  /**
528     * ccs_const_part_length - Evaluate the initial length without a pattern in a token.
529     *
530     * @filename: The string to evaluate.
531     *
532     * Returns the initial length without a pattern in @filename.
533     */
534    static int ccs_const_part_length(const char *filename)
535  {  {
536            char c;
537          int len = 0;          int len = 0;
538          if (filename) {          if (!filename)
539                  char c;                  return 0;
540                  while ((c = *filename++) != '\0') {          while (1) {
541                          if (c != '\\') { len++; continue; }                  c = *filename++;
542                          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; }  
                         }  
543                          break;                          break;
544                    if (c != '\\') {
545                            len++;
546                            continue;
547                    }
548                    c = *filename++;
549                    switch (c) {
550                    case '\\':  /* "\\" */
551                            len += 2;
552                            continue;
553                    case '0':   /* "\ooo" */
554                    case '1':
555                    case '2':
556                    case '3':
557                            c = *filename++;
558                            if (c < '0' || c > '7')
559                                    break;
560                            c = *filename++;
561                            if (c < '0' || c > '7')
562                                    break;
563                            len += 4;
564                            continue;
565                  }                  }
566                    break;
567          }          }
568          return len;          return len;
569  }  }
570    
571  void fill_path_info(struct path_info *ptr)  /**
572     * ccs_fill_path_info - Fill in "struct ccs_path_info" members.
573     *
574     * @ptr: Pointer to "struct ccs_path_info" to fill in.
575     *
576     * The caller sets "struct ccs_path_info"->name.
577     */
578    void ccs_fill_path_info(struct ccs_path_info *ptr)
579  {  {
580          const char *name = ptr->name;          const char *name = ptr->name;
581          const int len = strlen(name);          const int len = strlen(name);
582          ptr->total_len = len;          ptr->total_len = len;
583          ptr->const_len = const_part_length(name);          ptr->const_len = ccs_const_part_length(name);
584          ptr->is_dir = len && (name[len - 1] == '/');          ptr->is_dir = len && (name[len - 1] == '/');
585          ptr->is_patterned = (ptr->const_len < len);          ptr->is_patterned = (ptr->const_len < len);
586          ptr->hash = full_name_hash(name, len);          ptr->hash = full_name_hash(name, len);
587          ptr->depth = PathDepth(name);          ptr->depth = ccs_path_depth(name);
588  }  }
589    
590  static int FileMatchesToPattern2(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
591     * ccs_file_matches_pattern2 - Pattern matching without '/' character
592     * and "\-" pattern.
593     *
594     * @filename:     The start of string to check.
595     * @filename_end: The end of string to check.
596     * @pattern:      The start of pattern to compare.
597     * @pattern_end:  The end of pattern to compare.
598     *
599     * Returns true if @filename matches @pattern, false otherwise.
600     */
601    static bool ccs_file_matches_pattern2(const char *filename,
602                                          const char *filename_end,
603                                          const char *pattern,
604                                          const char *pattern_end)
605  {  {
606          while (filename < filename_end && pattern < pattern_end) {          while (filename < filename_end && pattern < pattern_end) {
607                    char c;
608                  if (*pattern != '\\') {                  if (*pattern != '\\') {
609                          if (*filename++ != *pattern++) return 0;                          if (*filename++ != *pattern++)
610                  } else {                                  return false;
611                          char c = *filename;                          continue;
612                          pattern++;                  }
613                          switch (*pattern) {                  c = *filename;
614                          case '?':                  pattern++;
615                                  if (c == '/') {                  switch (*pattern) {
616                                          return 0;                          int i;
617                                  } else if (c == '\\') {                          int j;
618                                          if ((c = filename[1]) == '\\') {                  case '?':
619                                                  filename++; /* safe because filename is \\ */                          if (c == '/') {
620                                          } else if (c >= '0' && c <= '3' && (c = filename[2]) >= '0' && c <= '7' && (c = filename[3]) >= '0' && c <= '7') {                                  return false;
621                                                  filename += 3; /* safe because filename is \ooo */                          } else if (c == '\\') {
622                                          } else {                                  if (filename[1] == '\\')
623                                                  return 0;                                          filename++;
624                                          }                                  else if (ccs_is_byte_range(filename + 1))
625                                  }                                          filename += 3;
626                                  break;                                  else
627                          case '\\':                                          return false;
628                                  if (c != '\\') return 0;                          }
629                                  if (*++filename != '\\') return 0; /* safe because *filename != '\0' */                          break;
630                                  break;                  case '\\':
631                          case '+':                          if (c != '\\')
632                                  if (c < '0' || c > '9') return 0;                                  return false;
633                                  break;                          if (*++filename != '\\')
634                          case 'x':                                  return false;
635                                  if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))) return 0;                          break;
636                                  break;                  case '+':
637                          case 'a':                          if (!ccs_is_decimal(c))
638                                  if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) return 0;                                  return false;
639                            break;
640                    case 'x':
641                            if (!ccs_is_hexadecimal(c))
642                                    return false;
643                            break;
644                    case 'a':
645                            if (!ccs_is_alphabet_char(c))
646                                    return false;
647                            break;
648                    case '0':
649                    case '1':
650                    case '2':
651                    case '3':
652                            if (c == '\\' && ccs_is_byte_range(filename + 1)
653                                && strncmp(filename + 1, pattern, 3) == 0) {
654                                    filename += 3;
655                                    pattern += 2;
656                                  break;                                  break;
657                          case '0':                          }
658                          case '1':                          return false; /* Not matched. */
659                          case '2':                  case '*':
660                          case '3':                  case '@':
661                                  if (c == '\\' && (c = filename[1]) >= '0' && c <= '3' && c == *pattern                          for (i = 0; i <= filename_end - filename; i++) {
662                                          && (c = filename[2]) >= '0' && c <= '7' && c == pattern[1]                                  if (ccs_file_matches_pattern2(filename + i,
663                                          && (c = filename[3]) >= '0' && c <= '7' && c == pattern[2]) {                                                                filename_end,
664                                          filename += 3; /* safe because filename is \ooo */                                                                pattern + 1,
665                                          pattern += 2; /* safe because pattern is \ooo  */                                                                pattern_end))
666                                            return true;
667                                    c = filename[i];
668                                    if (c == '.' && *pattern == '@')
669                                          break;                                          break;
670                                  }                                  if (c != '\\')
671                                  return 0; /* Not matched. */                                          continue;
672                          case '*':                                  if (filename[i + 1] == '\\')
673                          case '@':                                          i++;
674                                  {                                  else if (ccs_is_byte_range(filename + i + 1))
675                                          int i;                                          i += 3;
676                                          for (i = 0; i <= filename_end - filename; i++) {                                  else
677                                                  if (FileMatchesToPattern2(filename + i, filename_end, pattern + 1, pattern_end)) return 1;                                          break; /* Bad pattern. */
678                                                  if ((c = filename[i]) == '.' && *pattern == '@') break;                          }
679                                                  if (c == '\\') {                          return false; /* Not matched. */
680                                                          if ((c = filename[i + 1]) == '\\') {                  default:
681                                                                  i++; /* safe because filename is \\ */                          j = 0;
682                                                          } else if (c >= '0' && c <= '3' && (c = filename[i + 2]) >= '0' && c <= '7' && (c = filename[i + 3]) >= '0' && c <= '7') {                          c = *pattern;
683                                                                  i += 3; /* safe because filename is \ooo */                          if (c == '$') {
684                                                          } else {                                  while (ccs_is_decimal(filename[j]))
685                                                                  break; /* Bad pattern. */                                          j++;
686                                                          }                          } else if (c == 'X') {
687                                                  }                                  while (ccs_is_hexadecimal(filename[j]))
688                                          }                                          j++;
689                                          return 0; /* Not matched. */                          } else if (c == 'A') {
690                                  }                                  while (ccs_is_alphabet_char(filename[j]))
691                          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. */  
692                          }                          }
693                          filename++; /* safe because *filename != '\0' */                          for (i = 1; i <= j; i++) {
694                          pattern++; /* safe because *pattern != '\0' */                                  if (ccs_file_matches_pattern2(filename + i,
695                                                                  filename_end,
696                                                                  pattern + 1,
697                                                                  pattern_end))
698                                            return true;
699                            }
700                            return false; /* Not matched or bad pattern. */
701                  }                  }
702                    filename++;
703                    pattern++;
704          }          }
705          while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;          while (*pattern == '\\' &&
706          return (filename == filename_end && pattern == pattern_end);                 (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
707                    pattern += 2;
708            return filename == filename_end && pattern == pattern_end;
709  }  }
710    
711  static int FileMatchesToPattern(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
712     * ccs_file_matches_pattern - Pattern matching without without '/' character.
713     *
714     * @filename:     The start of string to check.
715     * @filename_end: The end of string to check.
716     * @pattern:      The start of pattern to compare.
717     * @pattern_end:  The end of pattern to compare.
718     *
719     * Returns true if @filename matches @pattern, false otherwise.
720     */
721    static bool ccs_file_matches_pattern(const char *filename,
722                                         const char *filename_end,
723                                         const char *pattern,
724                                         const char *pattern_end)
725  {  {
726          const char *pattern_start = pattern;          const char *pattern_start = pattern;
727          int first = 1;          bool first = true;
728          int result;          bool result;
729          while (pattern < pattern_end - 1) {          while (pattern < pattern_end - 1) {
730                  if (*pattern++ != '\\' || *pattern++ != '-') continue;                  /* Split at "\-" pattern. */
731                  result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern - 2);                  if (*pattern++ != '\\' || *pattern++ != '-')
732                  if (first) result = !result;                          continue;
733                  if (result) return 0;                  result = ccs_file_matches_pattern2(filename, filename_end,
734                  first = 0;                                                     pattern_start, pattern - 2);
735                    if (first)
736                            result = !result;
737                    if (result)
738                            return false;
739                    first = false;
740                  pattern_start = pattern;                  pattern_start = pattern;
741          }          }
742          result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern_end);          result = ccs_file_matches_pattern2(filename, filename_end,
743                                               pattern_start, pattern_end);
744          return first ? result : !result;          return first ? result : !result;
745  }  }
746    
747  /*  /**
748   *  Check whether the given pathname matches to the given pattern.   * ccs_path_matches_pattern - Check whether the given filename matches the given pattern.
749   *  Returns nonzero if matches, zero otherwise.   * @filename: The filename to check.
750     * @pattern:  The pattern to compare.
751   *   *
752   *  The following patterns are available.   * Returns true if matches, false otherwise.
753   *    \\     \ itself.   *
754   *    \ooo   Octal representation of a byte.   * The following patterns are available.
755   *    \*     More than or equals to 0 character other than '/'.   *   \\     \ itself.
756   *    \@     More than or equals to 0 character other than '/' or '.'.   *   \ooo   Octal representation of a byte.
757   *    \?     1 byte character other than '/'.   *   \*     More than or equals to 0 character other than '/'.
758   *    \$     More than or equals to 1 decimal digit.   *   \@     More than or equals to 0 character other than '/' or '.'.
759   *    \+     1 decimal digit.   *   \?     1 byte character other than '/'.
760   *    \X     More than or equals to 1 hexadecimal digit.   *   \$     More than or equals to 1 decimal digit.
761   *    \x     1 hexadecimal digit.   *   \+     1 decimal digit.
762   *    \A     More than or equals to 1 alphabet character.   *   \X     More than or equals to 1 hexadecimal digit.
763   *    \a     1 alphabet character.   *   \x     1 hexadecimal digit.
764   *    \-     Subtraction operator.   *   \A     More than or equals to 1 alphabet character.
765   */   *   \a     1 alphabet character.
766     *   \-     Subtraction operator.
767  int PathMatchesToPattern(const struct path_info *pathname0, const struct path_info *pattern0)   */
768  {  bool ccs_path_matches_pattern(const struct ccs_path_info *filename,
769          /* if (!pathname || !pattern) return 0; */                                const struct ccs_path_info *pattern)
770          const char *pathname = pathname0->name, *pattern = pattern0->name;  {
771          const int len = pattern0->const_len;          /*
772          if (!pattern0->is_patterned) return !pathcmp(pathname0, pattern0);            if (!filename || !pattern)
773          if (pathname0->depth != pattern0->depth) return 0;            return false;
774          if (strncmp(pathname, pattern, len)) return 0;          */
775          pathname += len; pattern += len;          const char *f = filename->name;
776          while (*pathname && *pattern) {          const char *p = pattern->name;
777                  const char *pathname_delimiter = strchr(pathname, '/'), *pattern_delimiter = strchr(pattern, '/');          const int len = pattern->const_len;
778                  if (!pathname_delimiter) pathname_delimiter = strchr(pathname, '\0');          /* If @pattern doesn't contain pattern, I can use strcmp(). */
779                  if (!pattern_delimiter) pattern_delimiter = strchr(pattern, '\0');          if (!pattern->is_patterned)
780                  if (!FileMatchesToPattern(pathname, pathname_delimiter, pattern, pattern_delimiter)) return 0;                  return !ccs_pathcmp(filename, pattern);
781                  pathname = *pathname_delimiter ? pathname_delimiter + 1 : pathname_delimiter;          /* Don't compare if the number of '/' differs. */
782                  pattern = *pattern_delimiter ? pattern_delimiter + 1 : pattern_delimiter;          if (filename->depth != pattern->depth)
783          }                  return false;
784          while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;          /* Compare the initial length without patterns. */
785          return (!*pathname && !*pattern);          if (strncmp(f, p, len))
786  }                  return false;
787            f += len;
788  /*          p += len;
789   *  Transactional printf() to struct io_buffer structure.          /* Main loop. Compare each directory component. */
790   *  snprintf() will truncate, but io_printf() won't.          while (*f && *p) {
791   *  Returns zero on success, nonzero otherwise.                  const char *f_delimiter = strchr(f, '/');
792   */                  const char *p_delimiter = strchr(p, '/');
793  int io_printf(struct io_buffer *head, const char *fmt, ...)                  if (!f_delimiter)
794  {                          f_delimiter = f + strlen(f);
795          va_list args;                  if (!p_delimiter)
796          int len, pos = head->read_avail, size = head->readbuf_size - pos;                          p_delimiter = p + strlen(p);
797          if (size <= 0) return -ENOMEM;                  if (!ccs_file_matches_pattern(f, f_delimiter, p, p_delimiter))
798          va_start(args, fmt);                          return false;
799          len = vsnprintf(head->read_buf + pos, size, fmt, args);                  f = f_delimiter;
800          va_end(args);                  if (*f)
801          if (pos + len >= head->readbuf_size) return -ENOMEM;                          f++;
802          head->read_avail += len;                  p = p_delimiter;
803          return 0;                  if (*p)
804                            p++;
805            }
806            /* Ignore trailing "\*" and "\@" in @pattern. */
807            while (*p == '\\' &&
808                   (*(p + 1) == '*' || *(p + 1) == '@'))
809                    p += 2;
810            return !*f && !*p;
811  }  }
812    
813  /*  /**
814   * Get realpath() of current process.   * ccs_get_exe - Get ccs_realpath() of current process.
815   * This function uses ccs_alloc(), so caller must ccs_free() if this function didn't return NULL.   *
816     * Returns the ccs_realpath() of current process on success, NULL otherwise.
817     *
818     * This function uses kzalloc(), so the caller must kfree()
819     * if this function didn't return NULL.
820   */   */
821  const char *GetEXE(void)  const char *ccs_get_exe(void)
822  {  {
823          struct mm_struct *mm = current->mm;          struct mm_struct *mm = current->mm;
824          struct vm_area_struct *vma;          struct vm_area_struct *vma;
825          const char *cp = NULL;          const char *cp = NULL;
826          if (!mm) return NULL;          if (!mm)
827                    return NULL;
828          down_read(&mm->mmap_sem);          down_read(&mm->mmap_sem);
829          for (vma = mm->mmap; vma; vma = vma->vm_next) {          for (vma = mm->mmap; vma; vma = vma->vm_next) {
830                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
831                          cp = realpath_from_dentry(vma->vm_file->f_dentry, vma->vm_file->f_vfsmnt);  #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 20)
832                            struct path path = { vma->vm_file->f_vfsmnt,
833                                                 vma->vm_file->f_dentry };
834                            cp = ccs_realpath_from_path(&path);
835    #else
836                            cp = ccs_realpath_from_path(&vma->vm_file->f_path);
837    #endif
838                          break;                          break;
839                  }                  }
840          }          }
# Line 488  const char *GetEXE(void) Line 842  const char *GetEXE(void)
842          return cp;          return cp;
843  }  }
844    
845  const char *GetMSG(const bool is_enforce)  /**
846  {   * ccs_get_msg - Get warning message.
847          if (is_enforce) return "ERROR"; else return "WARNING";   *
848  }   * @is_enforce: Is it enforcing mode?
849     *
850  const char *GetAltExec(void)   * Returns "ERROR" or "WARNING".
851  {   */
852          const u8 profile = current->domain_info->profile;  const char *ccs_get_msg(const bool is_enforce)
         const struct path_info *alt_exec = profile_ptr[profile] ? profile_ptr[profile]->alt_exec : NULL;  
         return alt_exec ? alt_exec->name : NULL;  
 }  
   
 /*************************  DOMAIN POLICY HANDLER  *************************/  
   
 /* Check whether the given access control is enabled. */  
 unsigned int CheckCCSFlags(const unsigned int index)  
 {  
         const u8 profile = current->domain_info->profile;  
         return sbin_init_started && index < CCS_MAX_CONTROL_INDEX  
 #if MAX_PROFILES != 256  
                 && profile < MAX_PROFILES  
 #endif  
                 && profile_ptr[profile] ? profile_ptr[profile]->value[index] : 0;  
 }  
   
 bool TomoyoVerboseMode(void)  
 {  
         return CheckCCSFlags(CCS_TOMOYO_VERBOSE) != 0;  
 }  
   
 /* Check whether the given access control is enforce mode. */  
 bool CheckCCSEnforce(const unsigned int index)  
 {  
         return CheckCCSFlags(index) == 3;  
 }  
   
 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;  
 }  
   
 /* Check whether the given access control is learning mode. */  
 bool CheckCCSAccept(const unsigned int index, struct domain_info * const domain)  
853  {  {
854          if (CheckCCSFlags(index) != 1) return 0;          if (is_enforce)
855          return CheckDomainQuota(domain);                  return "ERROR";
856            else
857                    return "WARNING";
858  }  }
859    
860  static struct profile *FindOrAssignNewProfile(const unsigned int profile)  /**
861     * ccs_can_sleep - Check whether it is permitted to do operations that may sleep.
862     *
863     * Returns true if it is permitted to do operations that may sleep,
864     * false otherwise.
865     *
866     * TOMOYO Linux supports interactive enforcement that lets processes
867     * wait for the administrator's decision.
868     * All hooks but the one for ccs_may_autobind() are inserted where
869     * it is permitted to do operations that may sleep.
870     * Thus, this warning should not happen.
871     */
872    bool ccs_can_sleep(void)
873  {  {
874          static DEFINE_MUTEX(profile_lock);          static u8 count = 20;
875          struct profile *ptr = NULL;          if (likely(!in_interrupt()))
876          mutex_lock(&profile_lock);                  return true;
877          if (profile < MAX_PROFILES && (ptr = profile_ptr[profile]) == NULL) {          if (count) {
878                  if ((ptr = alloc_element(sizeof(*ptr))) != NULL) {                  count--;
879                          int i;                  printk(KERN_ERR "BUG: sleeping function called "
880                          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) ptr->value[i] = ccs_control_array[i].current_value;                         "from invalid context.\n");
881                          mb(); /* Avoid out-of-order execution. */                  dump_stack();
                         profile_ptr[profile] = ptr;  
                 }  
882          }          }
883          mutex_unlock(&profile_lock);          return false;
         return ptr;  
884  }  }
885    
886  /* #define ALT_EXEC */  /**
887     * ccs_check_flags - Check mode for specified functionality.
888  static int SetProfile(struct io_buffer *head)   *
889     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
890     * @index:  The functionality to check mode.
891     *
892     * Returns the mode of specified functionality.
893     */
894    unsigned int ccs_check_flags(const struct ccs_domain_info *domain,
895                                 const u8 index)
896  {  {
897          char *data = head->write_buf;          u8 profile;
898          unsigned int i, value;          if (!domain)
899          char *cp;                  domain = ccs_current_domain();
900          struct profile *profile;          profile = domain->profile;
901          if (!isRoot()) return -EPERM;          return ccs_policy_loaded && index < CCS_MAX_CONTROL_INDEX
902          i = simple_strtoul(data, &cp, 10);  #if CCS_MAX_PROFILES != 256
903          if (data != cp) {                  && profile < CCS_MAX_PROFILES
                 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  
904  #endif  #endif
905          if (sscanf(cp + 1, "%u", &value) != 1) return -EINVAL;                  && ccs_profile_ptr[profile] ?
906  #ifdef CONFIG_TOMOYO                  ccs_profile_ptr[profile]->value[index] : 0;
         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;  
907  }  }
908    
909  static int ReadProfile(struct io_buffer *head)  /**
910  {   * ccs_cap2keyword - Convert capability operation to capability name.
911          if (!head->read_eof) {   *
912                  if (!isRoot()) return -EPERM;   * @operation: The capability index.
913                  if (!head->read_var2) {   *
914                          int step;   * Returns the name of the specified capability's name.
915                          for (step = head->read_step; step < MAX_PROFILES * CCS_MAX_CONTROL_INDEX; step++) {   */
916                                  const int i = step / CCS_MAX_CONTROL_INDEX, j = step % CCS_MAX_CONTROL_INDEX;  const char *ccs_cap2keyword(const u8 operation)
                                 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)  
917  {  {
918          struct policy_manager_entry *new_entry, *ptr;          return operation < CCS_MAX_CAPABILITY_INDEX
919          static DEFINE_MUTEX(lock);                  ? ccs_capability_list[operation] : NULL;
         const struct path_info *saved_manager;  
         int error = -ENOMEM;  
         bool is_domain = 0;  
         if (!isRoot()) return -EPERM;  
         if (IsDomainDef(manager)) {  
                 if (!IsCorrectDomain(manager, __FUNCTION__)) return -EINVAL;  
                 is_domain = 1;  
         } else {  
                 if (!IsCorrectPath(manager, 1, -1, -1, __FUNCTION__)) return -EINVAL;  
         }  
         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;  
920  }  }
921    
922  static int AddManagerPolicy(struct io_buffer *head)  /**
923     * ccs_init_request_info - Initialize "struct ccs_request_info" members.
924     *
925     * @r:      Pointer to "struct ccs_request_info" to initialize.
926     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
927     * @index:  Index number of functionality.
928     *
929     * Returns mode.
930     */
931    int ccs_init_request_info(struct ccs_request_info *r,
932                              struct ccs_domain_info *domain, const u8 index)
933  {  {
934          const char *data = head->write_buf;          memset(r, 0, sizeof(*r));
935          bool is_delete = 0;          if (!domain)
936          if (!isRoot()) return -EPERM;                  domain = ccs_current_domain();
937          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {          r->domain = domain;
938                  data += KEYWORD_DELETE_LEN;          r->profile = domain->profile;
939                  is_delete = 1;          if (index < CCS_MAX_CONTROL_INDEX)
940          }                  r->mode = ccs_check_flags(domain, index);
941          return AddManagerEntry(data, is_delete);          return r->mode;
942  }  }
943    
944  static int ReadManagerPolicy(struct io_buffer *head)  /**
945     * ccs_verbose_mode - Check whether TOMOYO is verbose mode.
946     *
947     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
948     *
949     * Returns true if domain policy violation warning should be printed to
950     * console.
951     */
952    bool ccs_verbose_mode(const struct ccs_domain_info *domain)
953  {  {
954          struct list1_head *pos;          return ccs_check_flags(domain, CCS_VERBOSE) != 0;
         if (head->read_eof) return 0;  
         if (!isRoot()) return -EPERM;  
         list1_for_each_cookie(pos, head->read_var2, &policy_manager_list) {  
                 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;  
955  }  }
956    
957  /* Check whether the current process is a policy manager. */  /**
958  static int IsPolicyManager(void)   * ccs_domain_quota_ok - Check for domain's quota.
959     *
960     * @r: Pointer to "struct ccs_request_info".
961     *
962     * Returns true if the domain is not exceeded quota, false otherwise.
963     *
964     * Caller holds ccs_read_lock().
965     */
966    bool ccs_domain_quota_ok(struct ccs_request_info *r)
967  {  {
968          struct policy_manager_entry *ptr;          unsigned int count = 0;
969          const char *exe;          struct ccs_domain_info *domain = r->domain;
970          const struct path_info *domainname = current->domain_info->domainname;          struct ccs_acl_info *ptr;
971          bool found = 0;          ccs_check_read_lock();
972          if (!sbin_init_started) return 1;          if (r->mode != 1)
973          list1_for_each_entry(ptr, &policy_manager_list, list) {                  return false;
974                  if (!ptr->is_deleted && ptr->is_domain && !pathcmp(domainname, ptr->manager)) return 1;          if (!domain)
975          }                  return true;
976          if ((exe = GetEXE()) == NULL) return 0;          list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
977          list1_for_each_entry(ptr, &policy_manager_list, list) {                  if (ptr->is_deleted)
978                  if (!ptr->is_deleted && !ptr->is_domain && !strcmp(exe, ptr->manager->name)) {                          continue;
979                          found = 1;                  switch (ptr->type) {
980                            struct ccs_single_path_acl_record *acl1;
981                            struct ccs_double_path_acl_record *acl2;
982                            u16 perm;
983                    case CCS_TYPE_SINGLE_PATH_ACL:
984                            acl1 = container_of(ptr,
985                                                struct ccs_single_path_acl_record,
986                                                head);
987                            perm = acl1->perm;
988                            if (perm & (1 << CCS_TYPE_EXECUTE_ACL))
989                                    count++;
990                            if (perm & ((1 << CCS_TYPE_READ_ACL) |
991                                        (1 << CCS_TYPE_WRITE_ACL)))
992                                    count++;
993                            if (perm & (1 << CCS_TYPE_CREATE_ACL))
994                                    count++;
995                            if (perm & (1 << CCS_TYPE_UNLINK_ACL))
996                                    count++;
997                            if (perm & (1 << CCS_TYPE_MKDIR_ACL))
998                                    count++;
999                            if (perm & (1 << CCS_TYPE_RMDIR_ACL))
1000                                    count++;
1001                            if (perm & (1 << CCS_TYPE_MKFIFO_ACL))
1002                                    count++;
1003                            if (perm & (1 << CCS_TYPE_MKSOCK_ACL))
1004                                    count++;
1005                            if (perm & (1 << CCS_TYPE_MKBLOCK_ACL))
1006                                    count++;
1007                            if (perm & (1 << CCS_TYPE_MKCHAR_ACL))
1008                                    count++;
1009                            if (perm & (1 << CCS_TYPE_TRUNCATE_ACL))
1010                                    count++;
1011                            if (perm & (1 << CCS_TYPE_SYMLINK_ACL))
1012                                    count++;
1013                            if (perm & (1 << CCS_TYPE_REWRITE_ACL))
1014                                    count++;
1015                          break;                          break;
1016                  }                  case CCS_TYPE_DOUBLE_PATH_ACL:
1017          }                          acl2 = container_of(ptr,
1018          if (!found) { /* Reduce error messages. */                                              struct ccs_double_path_acl_record,
1019                  static pid_t last_pid = 0;                                              head);
1020                  const pid_t pid = current->pid;                          perm = acl2->perm;
1021                  if (last_pid != pid) {                          if (perm & (1 << CCS_TYPE_LINK_ACL))
1022                          printk("%s ( %s ) is not permitted to update policies.\n", domainname->name, exe);                                  count++;
1023                          last_pid = pid;                          if (perm & (1 << CCS_TYPE_RENAME_ACL))
1024                  }                                  count++;
         }  
         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_FILE_ACL) {  
                                 struct file_acl_record *ptr2 = container_of(ptr, struct file_acl_record, head);  
                                 const unsigned char b = ptr2->u_is_group;  
                                 if (io_printf(head, "%d %s%s", ptr2->perm,  
                                               b ? "@" : "",  
                                               b ? ptr2->u.group->group_name->name : ptr2->u.filename->name)) goto print_acl_rollback;  
                         } 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);  
                                 if (io_printf(head, KEYWORD_ALLOW_CAPABILITY "%s", capability2keyword(ptr2->capability))) goto print_acl_rollback;  
                         } 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 ", network2keyword(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 {  
                                 const char *keyword = acltype2keyword(acl_type);  
                                 if (!keyword) continue;  
                                 if (acltype2paths(acl_type) == 2) {  
                                         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;  
                                         if (io_printf(head, "allow_%s %s%s %s%s", keyword,  
                                                       b0 ? "@" : "", b0 ? ptr2->u1.group1->group_name->name : ptr2->u1.filename1->name,  
                                                       b1 ? "@" : "", b1 ? ptr2->u2.group2->group_name->name : ptr2->u2.filename2->name)) goto print_acl_rollback;  
                                 } else {  
                                         struct single_acl_record *ptr2 = container_of(ptr, struct single_acl_record, head);  
                                         const bool b = ptr2->u_is_group;  
                                         if (io_printf(head, "allow_%s %s%s", keyword,  
                                                       b ? "@" : "", b ? ptr2->u.group->group_name->name : ptr2->u.filename->name)) goto print_acl_rollback;  
                                 }  
                         }  
                         if (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;  
 }  
   
 #endif  
   
 static int UpdateDomainProfile(struct io_buffer *head)  
 {  
         char *data = head->write_buf;  
         char *cp = strchr(data, ' ');  
         struct domain_info *domain;  
         unsigned int profile;  
         if (!isRoot()) return -EPERM;  
         if (!cp) return -EINVAL;  
         *cp = '\0';  
         domain = FindDomain(cp + 1);  
         profile = simple_strtoul(data, NULL, 10);  
         if (domain && profile < MAX_PROFILES && (profile_ptr[profile] || !sbin_init_started)) domain->profile = (u8) profile;  
         UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);  
         return 0;  
 }  
   
 static int ReadDomainProfile(struct io_buffer *head)  
 {  
         struct list1_head *pos;  
         if (head->read_eof) return 0;  
         if (!isRoot()) return -EPERM;  
         list1_for_each_cookie(pos, head->read_var1, &domain_list) {  
                 struct domain_info *domain;  
                 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 AddPatternPolicy(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 (ReadPatternPolicy(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;  
1025                          break;                          break;
1026                  default:                  case CCS_TYPE_EXECUTE_HANDLER:
1027                          return -EINVAL;                  case CCS_TYPE_DENIED_EXECUTE_HANDLER:
                 }  
         }  
         return 0;  
 }  
   
 #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;  
1028                          break;                          break;
1029                  default:                  default:
1030                          return -EINVAL;                          count++;
                 }  
         }  
         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;  
1031                  }                  }
                 path_release(&nd);  
1032          }          }
1033          if (!profile_loaded) {          if (count < ccs_check_flags(domain, CCS_MAX_ACCEPT_ENTRY))
1034                  char *argv[2], *envp[3];                  return true;
1035                  printk("Calling %s to load policy. Please wait.\n", ccs_loader);          if (!domain->quota_warned) {
1036                  argv[0] = (char *) ccs_loader;                  domain->quota_warned = true;
1037                  argv[1] = NULL;                  printk(KERN_WARNING "TOMOYO-WARNING: "
1038                  envp[0] = "HOME=/";                         "Domain '%s' has so many ACLs to hold. "
1039                  envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";                         "Stopped learning mode.\n", domain->domainname->name);
                 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   2007/12/18\n");  
 #endif  
 #ifdef CONFIG_TOMOYO  
         printk("TOMOYO: 1.5.3-pre   2007/12/17\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;  
                         break;  
                 }  
         }  
         spin_unlock(&query_lock);  
         /***** CRITICAL SECTION END *****/  
         if (!len) {  
                 head->read_step = 0;  
                 return 0;  
         }  
         if ((buf = ccs_alloc(len)) != NULL) {  
                 pos = 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) {  
                                 /* 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 int 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. */  
1040          }          }
1041          if (mutex_lock_interruptible(&head->write_sem)) return -EINTR;          return false;
         while (avail_len > 0) {  
                 char c;  
                 if (head->write_avail >= head->writebuf_size - 1) {  
                         error = -ENOMEM;  
                         break;  
                 } else if (get_user(c, buffer)) {  
                         error = -EFAULT;  
                         break;  
                 }  
                 buffer++; avail_len--;  
                 cp0[head->write_avail++] = c;  
                 if (c != '\n') continue;  
                 cp0[head->write_avail - 1] = '\0';  
                 head->write_avail = 0;  
                 NormalizeLine(cp0);  
                 head->write(head);  
         }  
         mutex_unlock(&head->write_sem);  
         return error;  
 }  
   
   
 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;  
1042  }  }

Legend:
Removed from v.813  
changed lines
  Added in v.2911

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