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

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

Legend:
Removed from v.741  
changed lines
  Added in v.2946

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