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

Subversion リポジトリの参照

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

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

revision 1012 by kumaneko, Mon Mar 3 05:07:11 2008 UTC revision 1280 by kumaneko, Tue Jun 10 05:22:12 2008 UTC
# Line 5  Line 5 
5   *   *
6   * Copyright (C) 2005-2008  NTT DATA CORPORATION   * Copyright (C) 2005-2008  NTT DATA CORPORATION
7   *   *
8   * Version: 1.6.0-pre   2008/03/03   * Version: 1.6.2-pre   2008/06/10
9   *   *
10   * 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.
11   * See README.ccs for ChangeLog.   * See README.ccs for ChangeLog.
12   *   *
13   */   */
14    
15    #include <linux/version.h>
16    #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0)
17    #define __KERNEL_SYSCALLS__
18    #endif
19  #include <linux/string.h>  #include <linux/string.h>
20  #include <linux/mm.h>  #include <linux/mm.h>
21  #include <linux/utime.h>  #include <linux/utime.h>
# Line 20  Line 24 
24  #include <linux/slab.h>  #include <linux/slab.h>
25  #include <asm/uaccess.h>  #include <asm/uaccess.h>
26  #include <stdarg.h>  #include <stdarg.h>
27  #include <linux/version.h>  #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 0)
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)  
28  #include <linux/namei.h>  #include <linux/namei.h>
29  #include <linux/mount.h>  #include <linux/mount.h>
30  static const int lookup_flags = LOOKUP_FOLLOW;  static const int lookup_flags = LOOKUP_FOLLOW;
# Line 32  static const int lookup_flags = LOOKUP_F Line 35  static const int lookup_flags = LOOKUP_F
35  #include <linux/ccs_common.h>  #include <linux/ccs_common.h>
36  #include <linux/ccs_proc.h>  #include <linux/ccs_proc.h>
37  #include <linux/tomoyo.h>  #include <linux/tomoyo.h>
38  #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)  #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0)
39    #include <linux/unistd.h>
40    #endif
41    
42    /* To support PID namespace. */
43    #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24)
44  #define find_task_by_pid find_task_by_vpid  #define find_task_by_pid find_task_by_vpid
45  #endif  #endif
46    
47  #ifdef CONFIG_TOMOYO_MAX_ACCEPT_ENTRY  /* Set default specified by the kernel config. */
48    #ifdef CONFIG_TOMOYO
49  #define MAX_ACCEPT_ENTRY (CONFIG_TOMOYO_MAX_ACCEPT_ENTRY)  #define MAX_ACCEPT_ENTRY (CONFIG_TOMOYO_MAX_ACCEPT_ENTRY)
50    #define MAX_GRANT_LOG    (CONFIG_TOMOYO_MAX_GRANT_LOG)
51    #define MAX_REJECT_LOG   (CONFIG_TOMOYO_MAX_REJECT_LOG)
52  #else  #else
53  #define MAX_ACCEPT_ENTRY 2048  #define MAX_ACCEPT_ENTRY 0
54  #endif  #define MAX_GRANT_LOG    0
55  #ifdef CONFIG_TOMOYO_MAX_GRANT_LOG  #define MAX_REJECT_LOG   0
 #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  
56  #endif  #endif
57    
58  /*************************  VARIABLES  *************************/  /* Has /sbin/init started? */
   
 /* /sbin/init started? */  
59  bool sbin_init_started = false;  bool sbin_init_started = false;
60    
61    /* Log level for SAKURA's printk(). */
62  const char *ccs_log_level = KERN_DEBUG;  const char *ccs_log_level = KERN_DEBUG;
63    
64    /* String table for functionality that takes 4 modes. */
65    static const char *mode_4[4] = {
66            "disabled", "learning", "permissive", "enforcing"
67    };
68    /* String table for functionality that takes 2 modes. */
69    static const char *mode_2[4] = {
70            "disabled", "enabled", "enabled", "enabled"
71    };
72    
73    /* Table for profile. */
74  static struct {  static struct {
75          const char *keyword;          const char *keyword;
76          unsigned int current_value;          unsigned int current_value;
77          const unsigned int max_value;          const unsigned int max_value;
78  } ccs_control_array[CCS_MAX_CONTROL_INDEX] = {  } ccs_control_array[CCS_MAX_CONTROL_INDEX] = {
         [CCS_PROFILE_COMMENT]            = { "COMMENT",             0, 0 }, /* Reserved for string. */  
79          [CCS_TOMOYO_MAC_FOR_FILE]        = { "MAC_FOR_FILE",        0, 3 },          [CCS_TOMOYO_MAC_FOR_FILE]        = { "MAC_FOR_FILE",        0, 3 },
80          [CCS_TOMOYO_MAC_FOR_ARGV0]       = { "MAC_FOR_ARGV0",       0, 3 },          [CCS_TOMOYO_MAC_FOR_ARGV0]       = { "MAC_FOR_ARGV0",       0, 3 },
81          [CCS_TOMOYO_MAC_FOR_ENV]         = { "MAC_FOR_ENV",         0, 3 },          [CCS_TOMOYO_MAC_FOR_ENV]         = { "MAC_FOR_ENV",         0, 3 },
# Line 76  static struct { Line 87  static struct {
87          [CCS_SAKURA_RESTRICT_UNMOUNT]    = { "RESTRICT_UNMOUNT",    0, 3 },          [CCS_SAKURA_RESTRICT_UNMOUNT]    = { "RESTRICT_UNMOUNT",    0, 3 },
88          [CCS_SAKURA_RESTRICT_PIVOT_ROOT] = { "RESTRICT_PIVOT_ROOT", 0, 3 },          [CCS_SAKURA_RESTRICT_PIVOT_ROOT] = { "RESTRICT_PIVOT_ROOT", 0, 3 },
89          [CCS_SAKURA_RESTRICT_AUTOBIND]   = { "RESTRICT_AUTOBIND",   0, 1 },          [CCS_SAKURA_RESTRICT_AUTOBIND]   = { "RESTRICT_AUTOBIND",   0, 1 },
90          [CCS_TOMOYO_MAX_ACCEPT_ENTRY]    = { "MAX_ACCEPT_ENTRY",    MAX_ACCEPT_ENTRY, INT_MAX },          [CCS_TOMOYO_MAX_ACCEPT_ENTRY]
91          [CCS_TOMOYO_MAX_GRANT_LOG]       = { "MAX_GRANT_LOG",       MAX_GRANT_LOG, INT_MAX },          = { "MAX_ACCEPT_ENTRY",    MAX_ACCEPT_ENTRY, INT_MAX },
92          [CCS_TOMOYO_MAX_REJECT_LOG]      = { "MAX_REJECT_LOG",      MAX_REJECT_LOG, INT_MAX },          [CCS_TOMOYO_MAX_GRANT_LOG]
93            = { "MAX_GRANT_LOG",       MAX_GRANT_LOG, INT_MAX },
94            [CCS_TOMOYO_MAX_REJECT_LOG]
95            = { "MAX_REJECT_LOG",      MAX_REJECT_LOG, INT_MAX },
96          [CCS_TOMOYO_VERBOSE]             = { "TOMOYO_VERBOSE",      1, 1 },          [CCS_TOMOYO_VERBOSE]             = { "TOMOYO_VERBOSE",      1, 1 },
97          [CCS_ALLOW_ENFORCE_GRACE]        = { "ALLOW_ENFORCE_GRACE", 0, 1 },          [CCS_ALLOW_ENFORCE_GRACE]        = { "ALLOW_ENFORCE_GRACE", 0, 1 },
98          [CCS_SLEEP_PERIOD]               = { "SLEEP_PERIOD",        0, 3000 }, /* in 0.1 second */          [CCS_SLEEP_PERIOD]
99          [CCS_TOMOYO_ALT_EXEC]            = { "ALT_EXEC",            0, 0 }, /* Reserved for string. */          = { "SLEEP_PERIOD",        0, 3000 }, /* in 0.1 second */
100    };
101    
102    #ifdef CONFIG_TOMOYO
103    /* Capability name used by domain policy. */
104    static const char *capability_control_keyword[TOMOYO_MAX_CAPABILITY_INDEX] = {
105            [TOMOYO_INET_STREAM_SOCKET_CREATE]  = "inet_tcp_create",
106            [TOMOYO_INET_STREAM_SOCKET_LISTEN]  = "inet_tcp_listen",
107            [TOMOYO_INET_STREAM_SOCKET_CONNECT] = "inet_tcp_connect",
108            [TOMOYO_USE_INET_DGRAM_SOCKET]      = "use_inet_udp",
109            [TOMOYO_USE_INET_RAW_SOCKET]        = "use_inet_ip",
110            [TOMOYO_USE_ROUTE_SOCKET]           = "use_route",
111            [TOMOYO_USE_PACKET_SOCKET]          = "use_packet",
112            [TOMOYO_SYS_MOUNT]                  = "SYS_MOUNT",
113            [TOMOYO_SYS_UMOUNT]                 = "SYS_UMOUNT",
114            [TOMOYO_SYS_REBOOT]                 = "SYS_REBOOT",
115            [TOMOYO_SYS_CHROOT]                 = "SYS_CHROOT",
116            [TOMOYO_SYS_KILL]                   = "SYS_KILL",
117            [TOMOYO_SYS_VHANGUP]                = "SYS_VHANGUP",
118            [TOMOYO_SYS_SETTIME]                = "SYS_TIME",
119            [TOMOYO_SYS_NICE]                   = "SYS_NICE",
120            [TOMOYO_SYS_SETHOSTNAME]            = "SYS_SETHOSTNAME",
121            [TOMOYO_USE_KERNEL_MODULE]          = "use_kernel_module",
122            [TOMOYO_CREATE_FIFO]                = "create_fifo",
123            [TOMOYO_CREATE_BLOCK_DEV]           = "create_block_dev",
124            [TOMOYO_CREATE_CHAR_DEV]            = "create_char_dev",
125            [TOMOYO_CREATE_UNIX_SOCKET]         = "create_unix_socket",
126            [TOMOYO_SYS_LINK]                   = "SYS_LINK",
127            [TOMOYO_SYS_SYMLINK]                = "SYS_SYMLINK",
128            [TOMOYO_SYS_RENAME]                 = "SYS_RENAME",
129            [TOMOYO_SYS_UNLINK]                 = "SYS_UNLINK",
130            [TOMOYO_SYS_CHMOD]                  = "SYS_CHMOD",
131            [TOMOYO_SYS_CHOWN]                  = "SYS_CHOWN",
132            [TOMOYO_SYS_IOCTL]                  = "SYS_IOCTL",
133            [TOMOYO_SYS_KEXEC_LOAD]             = "SYS_KEXEC_LOAD",
134            [TOMOYO_SYS_PIVOT_ROOT]             = "SYS_PIVOT_ROOT",
135            [TOMOYO_SYS_PTRACE]                 = "SYS_PTRACE",
136  };  };
137    #endif
138    
139  struct profile {  /* Profile table. Memory is allocated as needed. */
140    static struct profile {
141          unsigned int value[CCS_MAX_CONTROL_INDEX];          unsigned int value[CCS_MAX_CONTROL_INDEX];
142          const struct path_info *comment;          const struct path_info *comment;
143          const struct path_info *alt_exec;  #ifdef CONFIG_TOMOYO
144  };          unsigned char capability_value[TOMOYO_MAX_CAPABILITY_INDEX];
145    #endif
146    } *profile_ptr[MAX_PROFILES];
147    
148  static struct profile *profile_ptr[MAX_PROFILES];  /* Permit policy management by non-root user? */
149  static bool manage_by_non_root = false;  static bool manage_by_non_root = false;
150    
151  /*************************  UTILITY FUNCTIONS  *************************/  /* Utility functions. */
152    
153  #ifdef CONFIG_TOMOYO  #ifdef CONFIG_TOMOYO
154  static int __init TOMOYO_Quiet_Setup(char *str)  /**
155     * tomoyo_quiet_setup - Set TOMOYO_VERBOSE=0 by default.
156     *
157     * @str: Unused.
158     *
159     * Returns 0.
160     */
161    static int __init tomoyo_quiet_setup(char *str)
162  {  {
163          ccs_control_array[CCS_TOMOYO_VERBOSE].current_value = 0;          ccs_control_array[CCS_TOMOYO_VERBOSE].current_value = 0;
164          return 0;          return 0;
165  }  }
166    
167  __setup("TOMOYO_QUIET", TOMOYO_Quiet_Setup);  __setup("TOMOYO_QUIET", tomoyo_quiet_setup);
168  #endif  #endif
169    
170  /*  /**
171   * Format string.   * is_byte_range - Check whether the string isa \ooo style octal value.
172     *
173     * @str: Pointer to the string.
174     *
175     * Returns true if @str is a \ooo style octal value, false otherwise.
176     */
177    static bool is_byte_range(const char *str)
178    {
179            return *str >= '0' && *str++ <= '3' &&
180                    *str >= '0' && *str++ <= '7' &&
181                    *str >= '0' && *str <= '7';
182    }
183    
184    /**
185     * is_decimal - Check whether the character is a decimal character.
186     *
187     * @c: The character to check.
188     *
189     * Returns true if @c is a decimal character, false otherwise.
190     */
191    static bool is_decimal(const char c)
192    {
193            return (c >= '0' && c <= '9');
194    }
195    
196    /**
197     * is_hexadecimal - Check whether the character is a hexadecimal character.
198     *
199     * @c: The character to check.
200     *
201     * Returns true if @c is a hexadecimal character, false otherwise.
202     */
203    static bool is_hexadecimal(const char c)
204    {
205            return ((c >= '0' && c <= '9') ||
206                    (c >= 'A' && c <= 'F') ||
207                    (c >= 'a' && c <= 'f'));
208    }
209    
210    /**
211     * is_alphabet_char - Check whether the character is an alphabet.
212     *
213     * @c: The character to check.
214     *
215     * Returns true if @c is an alphabet character, false otherwise.
216     */
217    static bool is_alphabet_char(const char c)
218    {
219            return ((c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'));
220    }
221    
222    /**
223     * make_byte - Make byte value from three octal characters.
224     *
225     * @c1: The first character.
226     * @c2: The second character.
227     * @c3: The third character.
228     *
229     * Returns byte value.
230     */
231    static u8 make_byte(const u8 c1, const u8 c2, const u8 c3)
232    {
233            return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
234    }
235    
236    /**
237     * str_starts - Check whether the given string starts with the given keyword.
238     *
239     * @src:  Pointer to pointer to the string.
240     * @find: Pointer to the keyword.
241     *
242     * Returns true if @src starts with @find, false otherwise.
243     *
244     * The @src is updated to point the first character after the @find
245     * if @src starts with @find.
246     */
247    static bool str_starts(char **src, const char *find)
248    {
249            const int len = strlen(find);
250            char *tmp = *src;
251            if (strncmp(tmp, find, len))
252                    return false;
253            tmp += len;
254            *src = tmp;
255            return true;
256    }
257    
258    /**
259     * normalize_line - Format string.
260     *
261     * @buffer: The line to normalize.
262     *
263   * Leading and trailing whitespaces are removed.   * Leading and trailing whitespaces are removed.
264   * Multiple whitespaces are packed into single space.   * Multiple whitespaces are packed into single space.
265     *
266     * Returns nothing.
267   */   */
268  static void NormalizeLine(unsigned char *buffer)  static void normalize_line(unsigned char *buffer)
269  {  {
270          unsigned char *sp = buffer, *dp = buffer;          unsigned char *sp = buffer;
271            unsigned char *dp = buffer;
272          bool first = true;          bool first = true;
273          while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;          while (*sp && (*sp <= ' ' || *sp >= 127))
274                    sp++;
275          while (*sp) {          while (*sp) {
276                  if (!first) *dp++ = ' ';                  if (!first)
277                            *dp++ = ' ';
278                  first = false;                  first = false;
279                  while (*sp > ' ' && *sp < 127) *dp++ = *sp++;                  while (*sp > ' ' && *sp < 127)
280                  while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;                          *dp++ = *sp++;
281                    while (*sp && (*sp <= ' ' || *sp >= 127))
282                            sp++;
283          }          }
284          *dp = '\0';          *dp = '\0';
285  }  }
286    
287  /*  /**
288   *  Check whether the given filename follows the naming rules.   * ccs_is_correct_path - Validate a pathname.
289   *  Returns true if follows, false otherwise.   * @filename:     The pathname to check.
290     * @start_type:   Should the pathname start with '/'?
291     *                1 = must / -1 = must not / 0 = don't care
292     * @pattern_type: Can the pathname contain a wildcard?
293     *                1 = must / -1 = must not / 0 = don't care
294     * @end_type:     Should the pathname end with '/'?
295     *                1 = must / -1 = must not / 0 = don't care
296     * @function:     The name of function calling me.
297     *
298     * Check whether the given filename follows the naming rules.
299     * Returns true if @filename follows the naming rules, false otherwise.
300   */   */
301  bool IsCorrectPath(const char *filename, const s8 start_type, const s8 pattern_type, const s8 end_type, const char *function)  bool ccs_is_correct_path(const char *filename, const s8 start_type,
302                             const s8 pattern_type, const s8 end_type,
303                             const char *function)
304  {  {
305          bool contains_pattern = false;          bool contains_pattern = false;
306          char c, d, e;          unsigned char c;
307            unsigned char d;
308            unsigned char e;
309          const char *original_filename = filename;          const char *original_filename = filename;
310          if (!filename) goto out;          if (!filename)
311                    goto out;
312          c = *filename;          c = *filename;
313          if (start_type == 1) { /* Must start with '/' */          if (start_type == 1) { /* Must start with '/' */
314                  if (c != '/') goto out;                  if (c != '/')
315                            goto out;
316          } else if (start_type == -1) { /* Must not start with '/' */          } else if (start_type == -1) { /* Must not start with '/' */
317                  if (c == '/') goto out;                  if (c == '/')
318                            goto out;
319          }          }
320          if (c) c = * (strchr(filename, '\0') - 1);          if (c)
321                    c = *(strchr(filename, '\0') - 1);
322          if (end_type == 1) { /* Must end with '/' */          if (end_type == 1) { /* Must end with '/' */
323                  if (c != '/') goto out;                  if (c != '/')
324                            goto out;
325          } else if (end_type == -1) { /* Must not end with '/' */          } else if (end_type == -1) { /* Must not end with '/' */
326                  if (c == '/') goto out;                  if (c == '/')
327                            goto out;
328          }          }
329          while ((c = *filename++) != '\0') {          while ((c = *filename++) != '\0') {
330                  if (c == '\\') {                  if (c == '\\') {
# Line 162  bool IsCorrectPath(const char *filename, Line 341  bool IsCorrectPath(const char *filename,
341                          case 'a':   /* "\a" */                          case 'a':   /* "\a" */
342                          case 'A':   /* "\A" */                          case 'A':   /* "\A" */
343                          case '-':   /* "\-" */                          case '-':   /* "\-" */
344                                  if (pattern_type == -1) break; /* Must not contain pattern */                                  if (pattern_type == -1)
345                                            break; /* Must not contain pattern */
346                                  contains_pattern = true;                                  contains_pattern = true;
347                                  continue;                                  continue;
348                          case '0':   /* "\ooo" */                          case '0':   /* "\ooo" */
349                          case '1':                          case '1':
350                          case '2':                          case '2':
351                          case '3':                          case '3':
352                                  if ((d = *filename++) >= '0' && d <= '7' && (e = *filename++) >= '0' && e <= '7') {                                  d = *filename++;
353                                          const unsigned char f =                                  if (d < '0' || d > '7')
354                                                  (((unsigned char) (c - '0')) << 6) +                                          break;
355                                                  (((unsigned char) (d - '0')) << 3) +                                  e = *filename++;
356                                                  (((unsigned char) (e - '0')));                                  if (e < '0' || e > '7')
357                                          if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                          break;
358                                  }                                  c = make_byte(c, d, e);
359                                    if (c && (c <= ' ' || c >= 127))
360                                            continue; /* pattern is not \000 */
361                          }                          }
362                          goto out;                          goto out;
363                  } else if (c <= ' ' || c >= 127) {                  } else if (c <= ' ' || c >= 127) {
# Line 183  bool IsCorrectPath(const char *filename, Line 365  bool IsCorrectPath(const char *filename,
365                  }                  }
366          }          }
367          if (pattern_type == 1) { /* Must contain pattern */          if (pattern_type == 1) { /* Must contain pattern */
368                  if (!contains_pattern) goto out;                  if (!contains_pattern)
369                            goto out;
370          }          }
371          return true;          return true;
372   out:   out:
373          printk(KERN_DEBUG "%s: Invalid pathname '%s'\n", function, original_filename);          printk(KERN_DEBUG "%s: Invalid pathname '%s'\n", function,
374                   original_filename);
375          return false;          return false;
376  }  }
377    
378  /*  /**
379   *  Check whether the given domainname follows the naming rules.   * ccs_is_correct_domain - Check whether the given domainname follows the naming rules.
380   *  Returns true if follows, false otherwise.   * @domainname:   The domainname to check.
381     * @function:     The name of function calling me.
382     *
383     * Returns true if @domainname follows the naming rules, false otherwise.
384   */   */
385  bool IsCorrectDomain(const unsigned char *domainname, const char *function)  bool ccs_is_correct_domain(const unsigned char *domainname,
386                               const char *function)
387  {  {
388          unsigned char c, d, e;          unsigned char c;
389            unsigned char d;
390            unsigned char e;
391          const char *org_domainname = domainname;          const char *org_domainname = domainname;
392          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN)) goto out;          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN))
393                    goto out;
394          domainname += ROOT_NAME_LEN;          domainname += ROOT_NAME_LEN;
395          if (!*domainname) return true;          if (!*domainname)
396                    return true;
397          do {          do {
398                  if (*domainname++ != ' ') goto out;                  if (*domainname++ != ' ')
399                  if (*domainname++ != '/') goto out;                          goto out;
400                    if (*domainname++ != '/')
401                            goto out;
402                  while ((c = *domainname) != '\0' && c != ' ') {                  while ((c = *domainname) != '\0' && c != ' ') {
403                          domainname++;                          domainname++;
404                          if (c == '\\') {                          if (c == '\\') {
405                                  switch ((c = *domainname++)) {                                  c = *domainname++;
406                                    switch ((c)) {
407                                  case '\\':  /* "\\" */                                  case '\\':  /* "\\" */
408                                          continue;                                          continue;
409                                  case '0':   /* "\ooo" */                                  case '0':   /* "\ooo" */
410                                  case '1':                                  case '1':
411                                  case '2':                                  case '2':
412                                  case '3':                                  case '3':
413                                          if ((d = *domainname++) >= '0' && d <= '7' && (e = *domainname++) >= '0' && e <= '7') {                                          d = *domainname++;
414                                                  const unsigned char f =                                          if (d < '0' || d > '7')
415                                                          (((unsigned char) (c - '0')) << 6) +                                                  break;
416                                                          (((unsigned char) (d - '0')) << 3) +                                          e = *domainname++;
417                                                          (((unsigned char) (e - '0')));                                          if (e < '0' || e > '7')
418                                                  if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                                  break;
419                                          }                                          c = make_byte(c, d, e);
420                                            if (c && (c <= ' ' || c >= 127))
421                                                    /* pattern is not \000 */
422                                                    continue;
423                                  }                                  }
424                                  goto out;                                  goto out;
425                          } else if (c < ' ' || c >= 127) {                          } else if (c < ' ' || c >= 127) {
# Line 231  bool IsCorrectDomain(const unsigned char Line 429  bool IsCorrectDomain(const unsigned char
429          } while (*domainname);          } while (*domainname);
430          return true;          return true;
431   out:   out:
432          printk(KERN_DEBUG "%s: Invalid domainname '%s'\n", function, org_domainname);          printk(KERN_DEBUG "%s: Invalid domainname '%s'\n", function,
433                   org_domainname);
434          return false;          return false;
435  }  }
436    
437  bool IsDomainDef(const unsigned char *buffer)  /**
438     * ccs_is_domain_def - Check whether the given token can be a domainname.
439     *
440     * @buffer: The token to check.
441     *
442     * Returns true if @buffer possibly be a domainname, false otherwise.
443     */
444    bool ccs_is_domain_def(const unsigned char *buffer)
445  {  {
446          /* while (*buffer && (*buffer <= ' ' || *buffer >= 127)) buffer++; */          return !strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN);
         return strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN) == 0;  
447  }  }
448    
449  struct domain_info *FindDomain(const char *domainname0)  /**
450     * ccs_find_domain - Find a domain by the given name.
451     *
452     * @domainname: The domainname to find.
453     *
454     * Returns pointer to "struct domain_info" if found, NULL otherwise.
455     */
456    struct domain_info *ccs_find_domain(const char *domainname)
457  {  {
458          struct domain_info *domain;          struct domain_info *domain;
459          struct path_info domainname;          struct path_info name;
460          domainname.name = domainname0;          name.name = domainname;
461          fill_path_info(&domainname);          ccs_fill_path_info(&name);
462          list1_for_each_entry(domain, &domain_list, list) {          list1_for_each_entry(domain, &domain_list, list) {
463                  if (!domain->is_deleted && !pathcmp(&domainname, domain->domainname)) return domain;                  if (!domain->is_deleted &&
464                        !ccs_pathcmp(&name, domain->domainname))
465                            return domain;
466          }          }
467          return NULL;          return NULL;
468  }  }
469    
470  static int PathDepth(const char *pathname)  /**
471     * path_depth - Evaluate the number of '/' in a string.
472     *
473     * @pathname: The string to evaluate.
474     *
475     * Returns path depth of the string.
476     *
477     * I score 2 for each of the '/' in the @pathname
478     * and score 1 if the @pathname ends with '/'.
479     */
480    static int path_depth(const char *pathname)
481  {  {
482          int i = 0;          int i = 0;
483          if (pathname) {          if (pathname) {
484                  char *ep = strchr(pathname, '\0');                  char *ep = strchr(pathname, '\0');
485                  if (pathname < ep--) {                  if (pathname < ep--) {
486                          if (*ep != '/') i++;                          if (*ep != '/')
487                          while (pathname <= ep) if (*ep-- == '/') i += 2;                                  i++;
488                            while (pathname <= ep)
489                                    if (*ep-- == '/')
490                                            i += 2;
491                  }                  }
492          }          }
493          return i;          return i;
494  }  }
495    
496    /**
497     * const_part_length - Evaluate the initial length without a pattern in a token.
498     *
499     * @filename: The string to evaluate.
500     *
501     * Returns the initial length without a pattern in @filename.
502     */
503  static int const_part_length(const char *filename)  static int const_part_length(const char *filename)
504  {  {
505            char c;
506          int len = 0;          int len = 0;
507          if (filename) {          if (!filename)
508                  char c;                  return 0;
509                  while ((c = *filename++) != '\0') {          while ((c = *filename++) != '\0') {
510                          if (c != '\\') { len++; continue; }                  if (c != '\\') {
511                          switch (c = *filename++) {                          len++;
512                          case '\\':  /* "\\" */                          continue;
513                                  len += 2; continue;                  }
514                          case '0':   /* "\ooo" */                  c = *filename++;
515                          case '1':                  switch (c) {
516                          case '2':                  case '\\':  /* "\\" */
517                          case '3':                          len += 2;
518                                  if ((c = *filename++) >= '0' && c <= '7' && (c = *filename++) >= '0' && c <= '7') { len += 4; continue; }                          continue;
519                          }                  case '0':   /* "\ooo" */
520                          break;                  case '1':
521                    case '2':
522                    case '3':
523                            c = *filename++;
524                            if (c < '0' || c > '7')
525                                    break;
526                            c = *filename++;
527                            if (c < '0' || c > '7')
528                                    break;
529                            len += 4;
530                            continue;
531                  }                  }
532                    break;
533          }          }
534          return len;          return len;
535  }  }
536    
537  void fill_path_info(struct path_info *ptr)  /**
538     * ccs_fill_path_info - Fill in "struct path_info" members.
539     *
540     * @ptr: Pointer to "struct path_info" to fill in.
541     *
542     * The caller sets "struct path_info"->name.
543     */
544    void ccs_fill_path_info(struct path_info *ptr)
545  {  {
546          const char *name = ptr->name;          const char *name = ptr->name;
547          const int len = strlen(name);          const int len = strlen(name);
# Line 297  void fill_path_info(struct path_info *pt Line 550  void fill_path_info(struct path_info *pt
550          ptr->is_dir = len && (name[len - 1] == '/');          ptr->is_dir = len && (name[len - 1] == '/');
551          ptr->is_patterned = (ptr->const_len < len);          ptr->is_patterned = (ptr->const_len < len);
552          ptr->hash = full_name_hash(name, len);          ptr->hash = full_name_hash(name, len);
553          ptr->depth = PathDepth(name);          ptr->depth = path_depth(name);
554  }  }
555    
556  static bool FileMatchesToPattern2(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
557     * file_matches_to_pattern2 - Pattern matching without '/' character
558     * and "\-" pattern.
559     *
560     * @filename:     The start of string to check.
561     * @filename_end: The end of string to check.
562     * @pattern:      The start of pattern to compare.
563     * @pattern_end:  The end of pattern to compare.
564     *
565     * Returns true if @filename matches @pattern, false otherwise.
566     */
567    static bool file_matches_to_pattern2(const char *filename,
568                                         const char *filename_end,
569                                         const char *pattern,
570                                         const char *pattern_end)
571  {  {
572          while (filename < filename_end && pattern < pattern_end) {          while (filename < filename_end && pattern < pattern_end) {
573                    char c;
574                  if (*pattern != '\\') {                  if (*pattern != '\\') {
575                          if (*filename++ != *pattern++) return false;                          if (*filename++ != *pattern++)
576                  } else {                                  return false;
577                          char c = *filename;                          continue;
578                          pattern++;                  }
579                          switch (*pattern) {                  c = *filename;
580                          case '?':                  pattern++;
581                                  if (c == '/') {                  switch (*pattern) {
582                            int i;
583                            int j;
584                    case '?':
585                            if (c == '/') {
586                                    return false;
587                            } else if (c == '\\') {
588                                    if (filename[1] == '\\')
589                                            filename++;
590                                    else if (is_byte_range(filename + 1))
591                                            filename += 3;
592                                    else
593                                          return false;                                          return false;
594                                  } else if (c == '\\') {                          }
595                                          if ((c = filename[1]) == '\\') {                          break;
596                                                  filename++; /* safe because filename is \\ */                  case '\\':
597                                          } else if (c >= '0' && c <= '3' && (c = filename[2]) >= '0' && c <= '7' && (c = filename[3]) >= '0' && c <= '7') {                          if (c != '\\')
598                                                  filename += 3; /* safe because filename is \ooo */                                  return false;
599                                          } else {                          if (*++filename != '\\')
600                                                  return false;                                  return false;
601                                          }                          break;
602                                  }                  case '+':
603                                  break;                          if (!is_decimal(c))
604                          case '\\':                                  return false;
605                                  if (c != '\\') return false;                          break;
606                                  if (*++filename != '\\') return false; /* safe because *filename != '\0' */                  case 'x':
607                                  break;                          if (!is_hexadecimal(c))
608                          case '+':                                  return false;
609                                  if (c < '0' || c > '9') return false;                          break;
610                                  break;                  case 'a':
611                          case 'x':                          if (!is_alphabet_char(c))
612                                  if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))) return false;                                  return false;
613                                  break;                          break;
614                          case 'a':                  case '0':
615                                  if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) return false;                  case '1':
616                    case '2':
617                    case '3':
618                            if (c == '\\' && is_byte_range(filename + 1)
619                                && strncmp(filename + 1, pattern, 3) == 0) {
620                                    filename += 3;
621                                    pattern += 2;
622                                  break;                                  break;
623                          case '0':                          }
624                          case '1':                          return false; /* Not matched. */
625                          case '2':                  case '*':
626                          case '3':                  case '@':
627                                  if (c == '\\' && (c = filename[1]) >= '0' && c <= '3' && c == *pattern                          for (i = 0; i <= filename_end - filename; i++) {
628                                          && (c = filename[2]) >= '0' && c <= '7' && c == pattern[1]                                  if (file_matches_to_pattern2(filename + i,
629                                          && (c = filename[3]) >= '0' && c <= '7' && c == pattern[2]) {                                                               filename_end,
630                                          filename += 3; /* safe because filename is \ooo */                                                               pattern + 1,
631                                          pattern += 2; /* safe because pattern is \ooo  */                                                               pattern_end))
632                                            return true;
633                                    c = filename[i];
634                                    if (c == '.' && *pattern == '@')
635                                          break;                                          break;
636                                  }                                  if (c != '\\')
637                                  return false; /* Not matched. */                                          continue;
638                          case '*':                                  if (filename[i + 1] == '\\')
639                          case '@':                                          i++;
640                                  {                                  else if (is_byte_range(filename + i + 1))
641                                          int i;                                          i += 3;
642                                          for (i = 0; i <= filename_end - filename; i++) {                                  else
643                                                  if (FileMatchesToPattern2(filename + i, filename_end, pattern + 1, pattern_end)) return true;                                          break; /* Bad pattern. */
644                                                  if ((c = filename[i]) == '.' && *pattern == '@') break;                          }
645                                                  if (c == '\\') {                          return false; /* Not matched. */
646                                                          if ((c = filename[i + 1]) == '\\') {                  default:
647                                                                  i++; /* safe because filename is \\ */                          j = 0;
648                                                          } else if (c >= '0' && c <= '3' && (c = filename[i + 2]) >= '0' && c <= '7' && (c = filename[i + 3]) >= '0' && c <= '7') {                          c = *pattern;
649                                                                  i += 3; /* safe because filename is \ooo */                          if (c == '$') {
650                                                          } else {                                  while (is_decimal(filename[j]))
651                                                                  break; /* Bad pattern. */                                          j++;
652                                                          }                          } else if (c == 'X') {
653                                                  }                                  while (is_hexadecimal(filename[j]))
654                                          }                                          j++;
655                                          return false; /* Not matched. */                          } else if (c == 'A') {
656                                  }                                  while (is_alphabet_char(filename[j]))
657                          default:                                          j++;
658                                  {                          }
659                                          int i, j = 0;                          for (i = 1; i <= j; i++) {
660                                          if ((c = *pattern) == '$') {                                  if (file_matches_to_pattern2(filename + i,
661                                                  while ((c = filename[j]) >= '0' && c <= '9') j++;                                                               filename_end,
662                                          } else if (c == 'X') {                                                               pattern + 1,
663                                                  while (((c = filename[j]) >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) j++;                                                               pattern_end))
664                                          } else if (c == 'A') {                                          return true;
                                                 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 true;  
                                         }  
                                 }  
                                 return false; /* Not matched or bad pattern. */  
665                          }                          }
666                          filename++; /* safe because *filename != '\0' */                          return false; /* Not matched or bad pattern. */
                         pattern++; /* safe because *pattern != '\0' */  
667                  }                  }
668                    filename++;
669                    pattern++;
670          }          }
671          while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;          while (*pattern == '\\' &&
672                   (*(pattern + 1) == '*' || *(pattern + 1) == '@'))
673                    pattern += 2;
674          return (filename == filename_end && pattern == pattern_end);          return (filename == filename_end && pattern == pattern_end);
675  }  }
676    
677  static bool FileMatchesToPattern(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
678     * file_matches_to_pattern - Pattern matching without without '/' character.
679     *
680     * @filename:     The start of string to check.
681     * @filename_end: The end of string to check.
682     * @pattern:      The start of pattern to compare.
683     * @pattern_end:  The end of pattern to compare.
684     *
685     * Returns true if @filename matches @pattern, false otherwise.
686     */
687    static bool file_matches_to_pattern(const char *filename,
688                                        const char *filename_end,
689                                        const char *pattern,
690                                        const char *pattern_end)
691  {  {
692          const char *pattern_start = pattern;          const char *pattern_start = pattern;
693          bool first = true;          bool first = true;
694          bool result;          bool result;
695          while (pattern < pattern_end - 1) {          while (pattern < pattern_end - 1) {
696                  if (*pattern++ != '\\' || *pattern++ != '-') continue;                  /* Split at "\-" pattern. */
697                  result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern - 2);                  if (*pattern++ != '\\' || *pattern++ != '-')
698                  if (first) result = !result;                          continue;
699                  if (result) return false;                  result = file_matches_to_pattern2(filename, filename_end,
700                                                      pattern_start, pattern - 2);
701                    if (first)
702                            result = !result;
703                    if (result)
704                            return false;
705                  first = false;                  first = false;
706                  pattern_start = pattern;                  pattern_start = pattern;
707          }          }
708          result = FileMatchesToPattern2(filename, filename_end, pattern_start, pattern_end);          result = file_matches_to_pattern2(filename, filename_end,
709                                              pattern_start, pattern_end);
710          return first ? result : !result;          return first ? result : !result;
711  }  }
712    
713  /*  /**
714   *  Check whether the given pathname matches to the given pattern.   * ccs_path_matches_pattern - Check whether the given filename matches the given pattern.
715   *  Returns true if matches, false otherwise.   * @filename: The filename to check.
716   *   * @pattern:  The pattern to compare.
717   *  The following patterns are available.   *
718   *    \\     \ itself.   * Returns true if matches, false otherwise.
719   *    \ooo   Octal representation of a byte.   *
720   *    \*     More than or equals to 0 character other than '/'.   * The following patterns are available.
721   *    \@     More than or equals to 0 character other than '/' or '.'.   *   \\     \ itself.
722   *    \?     1 byte character other than '/'.   *   \ooo   Octal representation of a byte.
723   *    \$     More than or equals to 1 decimal digit.   *   \*     More than or equals to 0 character other than '/'.
724   *    \+     1 decimal digit.   *   \@     More than or equals to 0 character other than '/' or '.'.
725   *    \X     More than or equals to 1 hexadecimal digit.   *   \?     1 byte character other than '/'.
726   *    \x     1 hexadecimal digit.   *   \$     More than or equals to 1 decimal digit.
727   *    \A     More than or equals to 1 alphabet character.   *   \+     1 decimal digit.
728   *    \a     1 alphabet character.   *   \X     More than or equals to 1 hexadecimal digit.
729   *    \-     Subtraction operator.   *   \x     1 hexadecimal digit.
730   */   *   \A     More than or equals to 1 alphabet character.
731     *   \a     1 alphabet character.
732  bool PathMatchesToPattern(const struct path_info *pathname0, const struct path_info *pattern0)   *   \-     Subtraction operator.
733  {   */
734          /* if (!pathname || !pattern) return false; */  bool ccs_path_matches_pattern(const struct path_info *filename,
735          const char *pathname = pathname0->name, *pattern = pattern0->name;                                const struct path_info *pattern)
736          const int len = pattern0->const_len;  {
737          if (!pattern0->is_patterned) return !pathcmp(pathname0, pattern0);          /*
738          if (pathname0->depth != pattern0->depth) return false;            if (!filename || !pattern)
739          if (strncmp(pathname, pattern, len)) return false;            return false;
740          pathname += len; pattern += len;          */
741          while (*pathname && *pattern) {          const char *f = filename->name;
742                  const char *pathname_delimiter = strchr(pathname, '/'), *pattern_delimiter = strchr(pattern, '/');          const char *p = pattern->name;
743                  if (!pathname_delimiter) pathname_delimiter = strchr(pathname, '\0');          const int len = pattern->const_len;
744                  if (!pattern_delimiter) pattern_delimiter = strchr(pattern, '\0');          /* If @pattern doesn't contain pattern, I can use strcmp(). */
745                  if (!FileMatchesToPattern(pathname, pathname_delimiter, pattern, pattern_delimiter)) return false;          if (!pattern->is_patterned)
746                  pathname = *pathname_delimiter ? pathname_delimiter + 1 : pathname_delimiter;                  return !ccs_pathcmp(filename, pattern);
747                  pattern = *pattern_delimiter ? pattern_delimiter + 1 : pattern_delimiter;          /* Dont compare if the number of '/' differs. */
748          }          if (filename->depth != pattern->depth)
749          while (*pattern == '\\' && (*(pattern + 1) == '*' || *(pattern + 1) == '@')) pattern += 2;                  return false;
750          return (!*pathname && !*pattern);          /* Compare the initial length without patterns. */
751  }          if (strncmp(f, p, len))
752                    return false;
753  /*          f += len;
754   *  Transactional printf() to struct io_buffer structure.          p += len;
755   *  snprintf() will truncate, but io_printf() won't.          /* Main loop. Compare each directory component. */
756   *  Returns zero on success, nonzero otherwise.          while (*f && *p) {
757                    const char *f_delimiter = strchr(f, '/');
758                    const char *p_delimiter = strchr(p, '/');
759                    if (!f_delimiter)
760                            f_delimiter = strchr(f, '\0');
761                    if (!p_delimiter)
762                            p_delimiter = strchr(p, '\0');
763                    if (!file_matches_to_pattern(f, f_delimiter, p, p_delimiter))
764                            return false;
765                    f = f_delimiter;
766                    if (*f)
767                            f++;
768                    p = p_delimiter;
769                    if (*p)
770                            p++;
771            }
772            /* Ignore trailing "\*" and "\@" in @pattern. */
773            while (*p == '\\' &&
774                   (*(p + 1) == '*' || *(p + 1) == '@'))
775                    p += 2;
776            return (!*f && !*p);
777    }
778    
779    /**
780     * ccs_io_printf - Transactional printf() to "struct ccs_io_buffer" structure.
781     *
782     * @head: Pointer to "struct ccs_io_buffer".
783     * @fmt:  The printf()'s format string, followed by parameters.
784     *
785     * Returns true on success, false otherwise.
786     *
787     * The snprintf() will truncate, but ccs_io_printf() won't.
788   */   */
789  int io_printf(struct io_buffer *head, const char *fmt, ...)  bool ccs_io_printf(struct ccs_io_buffer *head, const char *fmt, ...)
790  {  {
791          va_list args;          va_list args;
792          int len, pos = head->read_avail, size = head->readbuf_size - pos;          int len;
793          if (size <= 0) return -ENOMEM;          int pos = head->read_avail;
794            int size = head->readbuf_size - pos;
795            if (size <= 0)
796                    return false;
797          va_start(args, fmt);          va_start(args, fmt);
798          len = vsnprintf(head->read_buf + pos, size, fmt, args);          len = vsnprintf(head->read_buf + pos, size, fmt, args);
799          va_end(args);          va_end(args);
800          if (pos + len >= head->readbuf_size) return -ENOMEM;          if (pos + len >= head->readbuf_size)
801                    return false;
802          head->read_avail += len;          head->read_avail += len;
803          return 0;          return true;
804  }  }
805    
806  /*  /**
807   * Get realpath() of current process.   * ccs_get_exe - Get ccs_realpath() of current process.
808   * This function uses ccs_alloc(), so caller must ccs_free() if this function didn't return NULL.   *
809     * Returns the ccs_realpath() of current process on success, NULL otherwise.
810     *
811     * This function uses ccs_alloc(), so the caller must ccs_free()
812     * if this function didn't return NULL.
813   */   */
814  const char *GetEXE(void)  const char *ccs_get_exe(void)
815  {  {
816          struct mm_struct *mm = current->mm;          struct mm_struct *mm = current->mm;
817          struct vm_area_struct *vma;          struct vm_area_struct *vma;
818          const char *cp = NULL;          const char *cp = NULL;
819          if (!mm) return NULL;          if (!mm)
820                    return NULL;
821          down_read(&mm->mmap_sem);          down_read(&mm->mmap_sem);
822          for (vma = mm->mmap; vma; vma = vma->vm_next) {          for (vma = mm->mmap; vma; vma = vma->vm_next) {
823                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {                  if ((vma->vm_flags & VM_EXECUTABLE) && vma->vm_file) {
824                          cp = realpath_from_dentry(vma->vm_file->f_dentry, vma->vm_file->f_vfsmnt);                          cp = ccs_realpath_from_dentry(vma->vm_file->f_dentry,
825                                                          vma->vm_file->f_vfsmnt);
826                          break;                          break;
827                  }                  }
828          }          }
# Line 486  const char *GetEXE(void) Line 830  const char *GetEXE(void)
830          return cp;          return cp;
831  }  }
832    
833  const char *GetMSG(const bool is_enforce)  /**
834     * ccs_get_msg - Get warning message.
835     *
836     * @is_enforce: Is it enforcing mode?
837     *
838     * Returns "ERROR" or "WARNING".
839     */
840    const char *ccs_get_msg(const bool is_enforce)
841  {  {
842          if (is_enforce) return "ERROR"; else return "WARNING";          if (is_enforce)
843                    return "ERROR";
844            else
845                    return "WARNING";
846  }  }
847    
848  const char *GetAltExec(void)  /**
849     * ccs_check_flags_no_sleep_check - Check mode for specified functionality.
850     *
851     * @index: The functionality to check mode.
852     *
853     * Returns the mode of specified functionality.
854     */
855    unsigned int ccs_check_flags_no_sleep_check(const u8 index)
856  {  {
857          const u8 profile = current->domain_info->profile;          const u8 profile = current->domain_info->profile;
858          const struct path_info *alt_exec = profile_ptr[profile] ? profile_ptr[profile]->alt_exec : NULL;          return sbin_init_started && index < CCS_MAX_CONTROL_INDEX
859          return alt_exec ? alt_exec->name : NULL;  #if MAX_PROFILES != 256
860                    && profile < MAX_PROFILES
861    #endif
862                    && profile_ptr[profile] ?
863                    profile_ptr[profile]->value[index] : 0;
864  }  }
865    
866  /*************************  DOMAIN POLICY HANDLER  *************************/  /**
867     * sleep_check - Check whether it is permitted to do operations that may sleep.
868     *
869     * Returns true if it is permitted to do operations that may sleep,
870     * false otherwise.
871     *
872     * TOMOYO Linux supports interactive enforcement that lets processes
873     * wait for the administrator's decision.
874     * All hooks but the one for ccs_may_autobind() are inserted where
875     * it is permitted to do operations that may sleep.
876     * Thus, this warning should not happen.
877     */
878    static bool sleep_check(void)
879    {
880            static u8 count = 20;
881            if (likely(!in_interrupt()))
882                    return true;
883            if (count) {
884                    count--;
885                    printk(KERN_ERR "BUG: sleeping function called "
886                           "from invalid context.\n");
887                    dump_stack();
888            }
889            return false;
890    }
891    
892  /* Check whether the given access control is enabled. */  /**
893  unsigned int CheckCCSFlags_NoSleepCheck(const u8 index)   * ccs_check_flags - Check mode for specified functionality.
894     *
895     * @index: The functionality to check mode.
896     *
897     * Returns the mode of specified functionality.
898     */
899    unsigned int ccs_check_flags(const u8 index)
900    {
901            return sleep_check() ? ccs_check_flags_no_sleep_check(index) : 0;
902    }
903    
904    #ifdef CONFIG_TOMOYO
905    /**
906     * ccs_check_capability_flags - Check mode for specified capability.
907     *
908     * @index: The capability to check mode.
909     *
910     * Returns the mode of specified capability.
911     */
912    u8 ccs_check_capability_flags(const u8 index)
913  {  {
914          const u8 profile = current->domain_info->profile;          const u8 profile = current->domain_info->profile;
915          return sbin_init_started && index < CCS_MAX_CONTROL_INDEX          return sbin_init_started && index < TOMOYO_MAX_CAPABILITY_INDEX
916  #if MAX_PROFILES != 256  #if MAX_PROFILES != 256
917                  && profile < MAX_PROFILES                  && profile < MAX_PROFILES
918  #endif  #endif
919                  && profile_ptr[profile] ? profile_ptr[profile]->value[index] : 0;                  && sleep_check()
920                    && profile_ptr[profile] ?
921                    profile_ptr[profile]->capability_value[index] : 0;
922  }  }
923    
924  unsigned int CheckCCSFlags(const u8 index)  /**
925     * ccs_cap2keyword - Convert capability operation to capability name.
926     *
927     * @operation: The capability index.
928     *
929     * Returns the name of the specified capability's name.
930     */
931    const char *ccs_cap2keyword(const u8 operation)
932  {  {
933  #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)          return operation < TOMOYO_MAX_CAPABILITY_INDEX
934          if (unlikely(in_interrupt()))                  ? capability_control_keyword[operation] : NULL;
 #else  
         if (unlikely(in_atomic()))  
 #endif  
         {  
                 static u8 count = 20;  
                 if (count) {  
                         count--;  
                         printk(KERN_ERR "BUG: sleeping function called from invalid context.\n");  
                         dump_stack();  
                 }  
                 /* Return 0 so that no MAC checks are performed. */  
                 return 0;  
         }  
         return CheckCCSFlags_NoSleepCheck(index);  
935  }  }
936    
937  bool TomoyoVerboseMode(void)  #endif
938    
939    /**
940     * ccs_verbose_mode - Check whether TOMOYO is verbose mode.
941     *
942     * Returns true if domain policy violation warning should be printed to
943     * console.
944     */
945    bool ccs_verbose_mode(void)
946  {  {
947          return CheckCCSFlags(CCS_TOMOYO_VERBOSE) != 0;          return ccs_check_flags(CCS_TOMOYO_VERBOSE) != 0;
948  }  }
949    
950  bool CheckDomainQuota(struct domain_info * const domain)  /**
951     * ccs_check_domain_quota - Check for domain's quota.
952     *
953     * @domain: Pointer to "struct domain_info".
954     *
955     * Returns true if the domain is not exceeded quota, false otherwise.
956     */
957    bool ccs_check_domain_quota(struct domain_info * const domain)
958  {  {
959          unsigned int count = 0;          unsigned int count = 0;
960          struct acl_info *ptr;          struct acl_info *ptr;
961          if (!domain) return true;          if (!domain)
962                    return true;
963          list1_for_each_entry(ptr, &domain->acl_info_list, list) {          list1_for_each_entry(ptr, &domain->acl_info_list, list) {
964                  if (!(ptr->type & ACL_DELETED)) count++;                  if (ptr->type & ACL_DELETED)
965                            continue;
966                    switch (ccs_acl_type2(ptr)) {
967                            struct single_path_acl_record *acl1;
968                            struct double_path_acl_record *acl2;
969                            u16 perm;
970                    case TYPE_SINGLE_PATH_ACL:
971                            acl1 = container_of(ptr, struct single_path_acl_record,
972                                                head);
973                            perm = acl1->perm;
974                            if (perm & (1 << TYPE_EXECUTE_ACL))
975                                    count++;
976                            if (perm &
977                                ((1 << TYPE_READ_ACL) | (1 << TYPE_WRITE_ACL)))
978                                    count++;
979                            if (perm & (1 << TYPE_CREATE_ACL))
980                                    count++;
981                            if (perm & (1 << TYPE_UNLINK_ACL))
982                                    count++;
983                            if (perm & (1 << TYPE_MKDIR_ACL))
984                                    count++;
985                            if (perm & (1 << TYPE_RMDIR_ACL))
986                                    count++;
987                            if (perm & (1 << TYPE_MKFIFO_ACL))
988                                    count++;
989                            if (perm & (1 << TYPE_MKSOCK_ACL))
990                                    count++;
991                            if (perm & (1 << TYPE_MKBLOCK_ACL))
992                                    count++;
993                            if (perm & (1 << TYPE_MKCHAR_ACL))
994                                    count++;
995                            if (perm & (1 << TYPE_TRUNCATE_ACL))
996                                    count++;
997                            if (perm & (1 << TYPE_SYMLINK_ACL))
998                                    count++;
999                            if (perm & (1 << TYPE_REWRITE_ACL))
1000                                    count++;
1001                            break;
1002                    case TYPE_DOUBLE_PATH_ACL:
1003                            acl2 = container_of(ptr, struct double_path_acl_record,
1004                                                head);
1005                            perm = acl2->perm;
1006                            if (perm & (1 << TYPE_LINK_ACL))
1007                                    count++;
1008                            if (perm & (1 << TYPE_RENAME_ACL))
1009                                    count++;
1010                            break;
1011                    case TYPE_EXECUTE_HANDLER:
1012                    case TYPE_DENIED_EXECUTE_HANDLER:
1013                            break;
1014                    default:
1015                            count++;
1016                    }
1017          }          }
1018          if (count < CheckCCSFlags(CCS_TOMOYO_MAX_ACCEPT_ENTRY)) return true;          if (count < ccs_check_flags(CCS_TOMOYO_MAX_ACCEPT_ENTRY))
1019                    return true;
1020          if (!domain->quota_warned) {          if (!domain->quota_warned) {
1021                  domain->quota_warned = true;                  domain->quota_warned = true;
1022                  printk("TOMOYO-WARNING: Domain '%s' has so many ACLs to hold. Stopped learning mode.\n", domain->domainname->name);                  printk(KERN_WARNING "TOMOYO-WARNING: "
1023                           "Domain '%s' has so many ACLs to hold. "
1024                           "Stopped learning mode.\n", domain->domainname->name);
1025          }          }
1026          return false;          return false;
1027  }  }
1028    
1029  static struct profile *FindOrAssignNewProfile(const unsigned int profile)  /**
1030     * ccs_find_or_assign_new_profile - Create a new profile.
1031     *
1032     * @profile: Profile number to create.
1033     *
1034     * Returns pointer to "struct profile" on success, NULL otherwise.
1035     */
1036    static struct profile *ccs_find_or_assign_new_profile(const unsigned int
1037                                                          profile)
1038  {  {
1039          static DEFINE_MUTEX(profile_lock);          static DEFINE_MUTEX(profile_lock);
1040          struct profile *ptr = NULL;          struct profile *ptr = NULL;
1041          mutex_lock(&profile_lock);          mutex_lock(&profile_lock);
1042          if (profile < MAX_PROFILES && (ptr = profile_ptr[profile]) == NULL) {          if (profile < MAX_PROFILES) {
1043                  if ((ptr = alloc_element(sizeof(*ptr))) != NULL) {                  ptr = profile_ptr[profile];
1044                    if (ptr)
1045                            goto ok;
1046                    ptr = ccs_alloc_element(sizeof(*ptr));
1047                    if (ptr) {
1048                          int i;                          int i;
1049                          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) ptr->value[i] = ccs_control_array[i].current_value;                          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++)
1050                                    ptr->value[i]
1051                                            = ccs_control_array[i].current_value;
1052                            /*
1053                             * Needn't to initialize "ptr->capability_value"
1054                             * because they are always 0.
1055                             */
1056                          mb(); /* Avoid out-of-order execution. */                          mb(); /* Avoid out-of-order execution. */
1057                          profile_ptr[profile] = ptr;                          profile_ptr[profile] = ptr;
1058                  }                  }
1059          }          }
1060     ok:
1061          mutex_unlock(&profile_lock);          mutex_unlock(&profile_lock);
1062          return ptr;          return ptr;
1063  }  }
1064    
1065  static int SetProfile(struct io_buffer *head)  /**
1066     * write_profile - Write profile table.
1067     *
1068     * @head: Pointer to "struct ccs_io_buffer"
1069     *
1070     * Returns 0 on success, negative value otherwise.
1071     */
1072    static int write_profile(struct ccs_io_buffer *head)
1073  {  {
1074          char *data = head->write_buf;          char *data = head->write_buf;
1075          unsigned int i, value;          unsigned int i;
1076            unsigned int value;
1077          char *cp;          char *cp;
1078          struct profile *profile;          struct profile *profile;
1079          i = simple_strtoul(data, &cp, 10);          i = simple_strtoul(data, &cp, 10);
1080          if (data != cp) {          if (data != cp) {
1081                  if (*cp != '-') return -EINVAL;                  if (*cp != '-')
1082                  data= cp + 1;                          return -EINVAL;
1083                    data = cp + 1;
1084          }          }
1085          profile = FindOrAssignNewProfile(i);          profile = ccs_find_or_assign_new_profile(i);
1086          if (!profile) return -EINVAL;          if (!profile)
1087                    return -EINVAL;
1088          cp = strchr(data, '=');          cp = strchr(data, '=');
1089          if (!cp) return -EINVAL;          if (!cp)
1090                    return -EINVAL;
1091          *cp = '\0';          *cp = '\0';
1092          UpdateCounter(CCS_UPDATES_COUNTER_PROFILE);          ccs_update_counter(CCS_UPDATES_COUNTER_PROFILE);
1093          if (strcmp(data, ccs_control_array[CCS_PROFILE_COMMENT].keyword) == 0) {          if (!strcmp(data, "COMMENT")) {
1094                  profile->comment = SaveName(cp + 1);                  profile->comment = ccs_save_name(cp + 1);
1095                  return 0;                  return 0;
1096          }          }
1097  #ifdef CONFIG_TOMOYO  #ifdef CONFIG_TOMOYO
1098          if (strcmp(data, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword) == 0) {          if (str_starts(&data, KEYWORD_MAC_FOR_CAPABILITY)) {
1099                  cp++;                  if (sscanf(cp + 1, "%u", &value) != 1) {
1100                  if (*cp && !IsCorrectPath(cp, 1, -1, -1, __FUNCTION__)) cp = "";                          for (i = 0; i < 4; i++) {
1101                  profile->alt_exec = SaveName(cp);                                  if (strcmp(cp + 1, mode_4[i]))
1102                  return 0;                                          continue;
1103          }                                  value = i;
1104  #endif                                  break;
1105          if (sscanf(cp + 1, "%u", &value) != 1) return -EINVAL;                          }
1106  #ifdef CONFIG_TOMOYO                          if (i == 4)
1107          if (strncmp(data, KEYWORD_MAC_FOR_CAPABILITY, KEYWORD_MAC_FOR_CAPABILITY_LEN) == 0) {                                  return -EINVAL;
1108                  return SetCapabilityStatus(data + KEYWORD_MAC_FOR_CAPABILITY_LEN, value, i);                  }
1109                    if (value > 3)
1110                            value = 3;
1111                    for (i = 0; i < TOMOYO_MAX_CAPABILITY_INDEX; i++) {
1112                            if (strcmp(data, capability_control_keyword[i]))
1113                                    continue;
1114                            profile->capability_value[i] = value;
1115                            return 0;
1116                    }
1117                    return -EINVAL;
1118          }          }
1119  #endif  #endif
1120          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) {          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) {
1121                  if (strcmp(data, ccs_control_array[i].keyword)) continue;                  if (strcmp(data, ccs_control_array[i].keyword))
1122                  if (value > ccs_control_array[i].max_value) value = ccs_control_array[i].max_value;                          continue;
1123                    if (sscanf(cp + 1, "%u", &value) != 1) {
1124                            int j;
1125                            const char **modes;
1126                            switch (i) {
1127                            case CCS_SAKURA_RESTRICT_AUTOBIND:
1128                            case CCS_TOMOYO_VERBOSE:
1129                            case CCS_ALLOW_ENFORCE_GRACE:
1130                                    modes = mode_2;
1131                                    break;
1132                            default:
1133                                    modes = mode_4;
1134                                    break;
1135                            }
1136                            for (j = 0; j < 4; j++) {
1137                                    if (strcmp(cp + 1, modes[j]))
1138                                            continue;
1139                                    value = j;
1140                                    break;
1141                            }
1142                            if (j == 4)
1143                                    return -EINVAL;
1144                    } else if (value > ccs_control_array[i].max_value) {
1145                            value = ccs_control_array[i].max_value;
1146                    }
1147                    switch (i) {
1148                    case CCS_SAKURA_DENY_CONCEAL_MOUNT:
1149                    case CCS_SAKURA_RESTRICT_UNMOUNT:
1150                            if (value == 1)
1151                                    value = 2; /* learning mode is not supported. */
1152                    }
1153                  profile->value[i] = value;                  profile->value[i] = value;
1154                  return 0;                  return 0;
1155          }          }
1156          return -EINVAL;          return -EINVAL;
1157  }  }
1158    
1159  static int ReadProfile(struct io_buffer *head)  /**
1160     * read_profile - Read profile table.
1161     *
1162     * @head: Pointer to "struct ccs_io_buffer"
1163     *
1164     * Returns 0.
1165     */
1166    static int read_profile(struct ccs_io_buffer *head)
1167  {  {
1168            static const int total
1169                    = CCS_MAX_CONTROL_INDEX + TOMOYO_MAX_CAPABILITY_INDEX + 1;
1170          int step;          int step;
1171          if (head->read_eof) return 0;          if (head->read_eof)
1172          if (head->read_var2) goto print_capability;                  return 0;
1173          for (step = head->read_step; step < MAX_PROFILES * CCS_MAX_CONTROL_INDEX; step++) {          for (step = head->read_step; step < MAX_PROFILES * total; step++) {
1174                  const int i = step / CCS_MAX_CONTROL_INDEX, j = step % CCS_MAX_CONTROL_INDEX;                  const u8 index = step / total;
1175                  const struct profile *profile = profile_ptr[i];                  u8 type = step % total;
1176                    const struct profile *profile = profile_ptr[index];
1177                  head->read_step = step;                  head->read_step = step;
1178                  if (!profile) continue;                  if (!profile)
1179                  switch (j) {                          continue;
1180                  case -1: /* Dummy */  #if !defined(CONFIG_SAKURA) || !defined(CONFIG_TOMOYO)
1181                    switch (type) {
1182  #ifndef CONFIG_SAKURA  #ifndef CONFIG_SAKURA
1183                  case CCS_SAKURA_DENY_CONCEAL_MOUNT:                  case CCS_SAKURA_DENY_CONCEAL_MOUNT:
1184                  case CCS_SAKURA_RESTRICT_CHROOT:                  case CCS_SAKURA_RESTRICT_CHROOT:
# Line 646  static int ReadProfile(struct io_buffer Line 1200  static int ReadProfile(struct io_buffer
1200  #endif  #endif
1201                          continue;                          continue;
1202                  }                  }
1203                  if (j == CCS_PROFILE_COMMENT) {  #endif
1204                          if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_PROFILE_COMMENT].keyword, profile->comment ? profile->comment->name : "")) break;                  if (!type) { /* Print profile' comment tag. */
1205                  } else if (j == CCS_TOMOYO_ALT_EXEC) {                          if (!ccs_io_printf(head, "%u-COMMENT=%s\n",
1206                          const struct path_info *alt_exec = profile->alt_exec;                                             index, profile->comment ?
1207                          if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword, alt_exec ? alt_exec->name : "")) break;                                             profile->comment->name : ""))
1208                  } else {                                  break;
1209                          if (io_printf(head, "%u-%s=%u\n", i, ccs_control_array[j].keyword, profile->value[j])) break;                          continue;
1210                  }                  }
1211          }                  type--;
1212          if (step == MAX_PROFILES * CCS_MAX_CONTROL_INDEX) {                  if (type >= CCS_MAX_CONTROL_INDEX) {
                 head->read_var2 = (void *) "";  
                 head->read_step = 0;  
         }  
  print_capability:  
         if (head->read_var2) {  
1213  #ifdef CONFIG_TOMOYO  #ifdef CONFIG_TOMOYO
1214                  if (ReadCapabilityStatus(head) == 0)                          const int i = type - CCS_MAX_CONTROL_INDEX;
1215                            const u8 value = profile->capability_value[i];
1216                            if (!ccs_io_printf(head,
1217                                               "%u-" KEYWORD_MAC_FOR_CAPABILITY
1218                                               "%s=%s\n", index,
1219                                               capability_control_keyword[i],
1220                                               mode_4[value]))
1221                                    break;
1222  #endif  #endif
1223                          head->read_eof = true;                  } else {
1224                            const unsigned int value = profile->value[type];
1225                            const char **modes = NULL;
1226                            const char *keyword = ccs_control_array[type].keyword;
1227                            switch (ccs_control_array[type].max_value) {
1228                            case 3:
1229                                    modes = mode_4;
1230                                    break;
1231                            case 1:
1232                                    modes = mode_2;
1233                                    break;
1234                            }
1235                            if (modes) {
1236                                    if (!ccs_io_printf(head, "%u-%s=%s\n", index,
1237                                                       keyword, modes[value]))
1238                                            break;
1239                            } else {
1240                                    if (!ccs_io_printf(head, "%u-%s=%u\n", index,
1241                                                       keyword, value))
1242                                            break;
1243                            }
1244                    }
1245          }          }
1246            if (step == MAX_PROFILES * total)
1247                    head->read_eof = true;
1248          return 0;          return 0;
1249  }  }
1250    
1251  /*************************  POLICY MANAGER HANDLER  *************************/  /* Structure for policy manager. */
   
1252  struct policy_manager_entry {  struct policy_manager_entry {
1253          struct list1_head list;          struct list1_head list;
1254            /* A path to program or a domainname. */
1255          const struct path_info *manager;          const struct path_info *manager;
1256          bool is_domain;          bool is_domain;  /* True if manager is a domainname. */
1257          bool is_deleted;          bool is_deleted; /* True if this entry is deleted. */
1258  };  };
1259    
1260    /* The list for "struct policy_manager_entry". */
1261  static LIST1_HEAD(policy_manager_list);  static LIST1_HEAD(policy_manager_list);
1262    
1263  static int AddManagerEntry(const char *manager, const bool is_delete)  /**
1264     * update_manager_entry - Add a manager entry.
1265     *
1266     * @manager:   The path to manager or the domainnamme.
1267     * @is_delete: True if it is a delete request.
1268     *
1269     * Returns 0 on success, negative value otherwise.
1270     */
1271    static int update_manager_entry(const char *manager, const bool is_delete)
1272  {  {
1273          struct policy_manager_entry *new_entry, *ptr;          struct policy_manager_entry *new_entry;
1274            struct policy_manager_entry *ptr;
1275          static DEFINE_MUTEX(lock);          static DEFINE_MUTEX(lock);
1276          const struct path_info *saved_manager;          const struct path_info *saved_manager;
1277          int error = -ENOMEM;          int error = -ENOMEM;
1278          bool is_domain = false;          bool is_domain = false;
1279          if (IsDomainDef(manager)) {          if (ccs_is_domain_def(manager)) {
1280                  if (!IsCorrectDomain(manager, __FUNCTION__)) return -EINVAL;                  if (!ccs_is_correct_domain(manager, __func__))
1281                            return -EINVAL;
1282                  is_domain = true;                  is_domain = true;
1283          } else {          } else {
1284                  if (!IsCorrectPath(manager, 1, -1, -1, __FUNCTION__)) return -EINVAL;                  if (!ccs_is_correct_path(manager, 1, -1, -1, __func__))
1285                            return -EINVAL;
1286          }          }
1287          if ((saved_manager = SaveName(manager)) == NULL) return -ENOMEM;          saved_manager = ccs_save_name(manager);
1288            if (!saved_manager)
1289                    return -ENOMEM;
1290          mutex_lock(&lock);          mutex_lock(&lock);
1291          list1_for_each_entry(ptr, &policy_manager_list, list) {          list1_for_each_entry(ptr, &policy_manager_list, list) {
1292                  if (ptr->manager == saved_manager) {                  if (ptr->manager != saved_manager)
1293                          ptr->is_deleted = is_delete;                          continue;
1294                          error = 0;                  ptr->is_deleted = is_delete;
1295                          goto out;                  error = 0;
1296                  }                  goto out;
1297          }          }
1298          if (is_delete) {          if (is_delete) {
1299                  error = -ENOENT;                  error = -ENOENT;
1300                  goto out;                  goto out;
1301          }          }
1302          if ((new_entry = alloc_element(sizeof(*new_entry))) == NULL) goto out;          new_entry = ccs_alloc_element(sizeof(*new_entry));
1303            if (!new_entry)
1304                    goto out;
1305          new_entry->manager = saved_manager;          new_entry->manager = saved_manager;
1306          new_entry->is_domain = is_domain;          new_entry->is_domain = is_domain;
1307          list1_add_tail_mb(&new_entry->list, &policy_manager_list);          list1_add_tail_mb(&new_entry->list, &policy_manager_list);
1308          error = 0;          error = 0;
1309   out:   out:
1310          mutex_unlock(&lock);          mutex_unlock(&lock);
1311          if (!error) UpdateCounter(CCS_UPDATES_COUNTER_MANAGER);          if (!error)
1312                    ccs_update_counter(CCS_UPDATES_COUNTER_MANAGER);
1313          return error;          return error;
1314  }  }
1315    
1316  static int AddManagerPolicy(struct io_buffer *head)  /**
1317     * write_manager_policy - Write manager policy.
1318     *
1319     * @head: Pointer to "struct ccs_io_buffer"
1320     *
1321     * Returns 0 on success, negative value otherwise.
1322     */
1323    static int write_manager_policy(struct ccs_io_buffer *head)
1324  {  {
1325          const char *data = head->write_buf;          char *data = head->write_buf;
1326          bool is_delete = false;          bool is_delete = str_starts(&data, KEYWORD_DELETE);
1327          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {          if (!strcmp(data, "manage_by_non_root")) {
1328                  data += KEYWORD_DELETE_LEN;                  manage_by_non_root = !is_delete;
                 is_delete = true;  
         }  
         if (strcmp(data, "manage_by_non_root") == 0) {  
                 manage_by_non_root = is_delete;  
1329                  return 0;                  return 0;
1330          }          }
1331          return AddManagerEntry(data, is_delete);          return update_manager_entry(data, is_delete);
1332  }  }
1333    
1334  static int ReadManagerPolicy(struct io_buffer *head)  /**
1335     * read_manager_policy - Read manager policy.
1336     *
1337     * @head: Pointer to "struct ccs_io_buffer"
1338     *
1339     * Returns 0.
1340     */
1341    static int read_manager_policy(struct ccs_io_buffer *head)
1342  {  {
1343          struct list1_head *pos;          struct list1_head *pos;
1344          if (head->read_eof) return 0;          if (head->read_eof)
1345                    return 0;
1346          list1_for_each_cookie(pos, head->read_var2, &policy_manager_list) {          list1_for_each_cookie(pos, head->read_var2, &policy_manager_list) {
1347                  struct policy_manager_entry *ptr;                  struct policy_manager_entry *ptr;
1348                  ptr = list1_entry(pos, struct policy_manager_entry, list);                  ptr = list1_entry(pos, struct policy_manager_entry, list);
1349                  if (ptr->is_deleted) continue;                  if (ptr->is_deleted)
1350                  if (io_printf(head, "%s\n", ptr->manager->name)) return 0;                          continue;
1351                    if (!ccs_io_printf(head, "%s\n", ptr->manager->name))
1352                            return 0;
1353          }          }
1354          head->read_eof = true;          head->read_eof = true;
1355          return 0;          return 0;
1356  }  }
1357    
1358  /* Check whether the current process is a policy manager. */  /**
1359  static bool IsPolicyManager(void)   * is_policy_manager - Check whether the current process is a policy manager.
1360     *
1361     * Returns true if the current process is permitted to modify policy
1362     * via /proc/ccs/ interface.
1363     */
1364    static bool is_policy_manager(void)
1365  {  {
1366          struct policy_manager_entry *ptr;          struct policy_manager_entry *ptr;
1367          const char *exe;          const char *exe;
1368          const struct task_struct *task = current;          const struct task_struct *task = current;
1369          const struct path_info *domainname = task->domain_info->domainname;          const struct path_info *domainname = task->domain_info->domainname;
1370          bool found = false;          bool found = false;
1371          if (!sbin_init_started) return true;          if (!sbin_init_started)
1372          if (!manage_by_non_root && (task->uid || task->euid)) return false;                  return true;
1373            if (!manage_by_non_root && (task->uid || task->euid))
1374                    return false;
1375          list1_for_each_entry(ptr, &policy_manager_list, list) {          list1_for_each_entry(ptr, &policy_manager_list, list) {
1376                  if (!ptr->is_deleted && ptr->is_domain && !pathcmp(domainname, ptr->manager)) return true;                  if (!ptr->is_deleted && ptr->is_domain
1377          }                      && !ccs_pathcmp(domainname, ptr->manager))
1378          if ((exe = GetEXE()) == NULL) return false;                          return true;
1379            }
1380            exe = ccs_get_exe();
1381            if (!exe)
1382                    return false;
1383          list1_for_each_entry(ptr, &policy_manager_list, list) {          list1_for_each_entry(ptr, &policy_manager_list, list) {
1384                  if (!ptr->is_deleted && !ptr->is_domain && !strcmp(exe, ptr->manager->name)) {                  if (!ptr->is_deleted && !ptr->is_domain
1385                        && !strcmp(exe, ptr->manager->name)) {
1386                          found = true;                          found = true;
1387                          break;                          break;
1388                  }                  }
1389          }          }
1390          if (!found) { /* Reduce error messages. */          if (!found) { /* Reduce error messages. */
1391                  static pid_t last_pid = 0;                  static pid_t last_pid;
1392                  const pid_t pid = current->pid;                  const pid_t pid = current->pid;
1393                  if (last_pid != pid) {                  if (last_pid != pid) {
1394                          printk("%s ( %s ) is not permitted to update policies.\n", domainname->name, exe);                          printk(KERN_WARNING "%s ( %s ) is not permitted to "
1395                                   "update policies.\n", domainname->name, exe);
1396                          last_pid = pid;                          last_pid = pid;
1397                  }                  }
1398          }          }
# Line 780  static bool IsPolicyManager(void) Line 1402  static bool IsPolicyManager(void)
1402    
1403  #ifdef CONFIG_TOMOYO  #ifdef CONFIG_TOMOYO
1404    
1405  /*************************  DOMAIN POLICY HANDLER  *************************/  /**
1406     * ccs_find_condition_part - Find condition part from the statement.
1407  static char *FindConditionPart(char *data)   *
1408     * @data: String to parse.
1409     *
1410     * Returns pointer to the condition part if it was found in the statement,
1411     * NULL otherwise.
1412     */
1413    static char *ccs_find_condition_part(char *data)
1414  {  {
1415          char *cp = strstr(data, " if "), *cp2;          char *cp = strstr(data, " if ");
1416          if (cp) {          if (cp) {
1417                  while ((cp2 = strstr(cp + 3, " if ")) != NULL) cp = cp2;                  char *cp2;
1418                  *cp++ = '\0';                  while ((cp2 = strstr(cp + 3, " if ")) != NULL)
1419          } else if ((cp = strstr(data, " ; set ")) != NULL) {                          cp = cp2;
1420                  *cp++ = '\0';                  *cp++ = '\0';
1421            } else {
1422                    cp = strstr(data, " ; set ");
1423                    if (cp)
1424                            *cp++ = '\0';
1425          }          }
1426          return cp;          return cp;
1427  }  }
1428    
1429  static int AddDomainPolicy(struct io_buffer *head)  /**
1430     * write_domain_policy - Write domain policy.
1431     *
1432     * @head: Pointer to "struct ccs_io_buffer".
1433     *
1434     * Returns 0 on success, negative value otherwise.
1435     */
1436    static int write_domain_policy(struct ccs_io_buffer *head)
1437  {  {
1438          char *data = head->write_buf;          char *data = head->write_buf;
1439          struct domain_info *domain = head->write_var1;          struct domain_info *domain = head->write_var1;
1440          bool is_delete = false, is_select = false, is_undelete = false;          bool is_delete = false;
1441            bool is_select = false;
1442            bool is_undelete = false;
1443          unsigned int profile;          unsigned int profile;
1444          const struct condition_list *cond = NULL;          const struct condition_list *cond = NULL;
1445          char *cp;          char *cp;
1446          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {          if (str_starts(&data, KEYWORD_DELETE))
                 data += KEYWORD_DELETE_LEN;  
1447                  is_delete = true;                  is_delete = true;
1448          } else if (strncmp(data, KEYWORD_SELECT, KEYWORD_SELECT_LEN) == 0) {          else if (str_starts(&data, KEYWORD_SELECT))
                 data += KEYWORD_SELECT_LEN;  
1449                  is_select = true;                  is_select = true;
1450          } else if (strncmp(data, KEYWORD_UNDELETE, KEYWORD_UNDELETE_LEN) == 0) {          else if (str_starts(&data, KEYWORD_UNDELETE))
                 data += KEYWORD_UNDELETE_LEN;  
1451                  is_undelete = true;                  is_undelete = true;
1452          }          if (ccs_is_domain_def(data)) {
1453          if (IsDomainDef(data)) {                  domain = NULL;
1454                  if (is_delete) {                  if (is_delete)
1455                          DeleteDomain(data);                          ccs_delete_domain(data);
1456                          domain = NULL;                  else if (is_select)
1457                  } else if (is_select) {                          domain = ccs_find_domain(data);
1458                          domain = FindDomain(data);                  else if (is_undelete)
1459                  } else if (is_undelete) {                          domain = ccs_undelete_domain(data);
1460                          domain = UndeleteDomain(data);                  else
1461                  } else {                          domain = ccs_find_or_assign_new_domain(data, 0);
                         domain = FindOrAssignNewDomain(data, 0);  
                 }  
1462                  head->write_var1 = domain;                  head->write_var1 = domain;
1463                  UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);                  ccs_update_counter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);
1464                  return 0;                  return 0;
1465          }          }
1466          if (!domain) return -EINVAL;          if (!domain)
1467                    return -EINVAL;
1468    
1469          if (sscanf(data, KEYWORD_USE_PROFILE "%u", &profile) == 1 && profile < MAX_PROFILES) {          if (sscanf(data, KEYWORD_USE_PROFILE "%u", &profile) == 1
1470                  if (profile_ptr[profile] || !sbin_init_started) domain->profile = (u8) profile;              && profile < MAX_PROFILES) {
1471                  return 0;                  if (profile_ptr[profile] || !sbin_init_started)
1472          }                          domain->profile = (u8) profile;
         if (strcmp(data, KEYWORD_IGNORE_GLOBAL_ALLOW_READ) == 0) {  
                 if (!is_delete) domain->flags |= DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_READ;  
                 else domain->flags &= ~DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_READ;  
1473                  return 0;                  return 0;
1474          }          }
1475          if (strcmp(data, KEYWORD_IGNORE_GLOBAL_ALLOW_ENV) == 0) {          if (!strcmp(data, KEYWORD_IGNORE_GLOBAL_ALLOW_READ)) {
1476                  if (!is_delete) domain->flags |= DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_ENV;                  ccs_set_domain_flag(domain, is_delete,
1477                  else domain->flags &= ~DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_ENV;                                      DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_READ);
1478                  return 0;                  return 0;
1479          }          }
1480          if (strcmp(data, KEYWORD_FORCE_ALT_EXEC) == 0) {          if (!strcmp(data, KEYWORD_IGNORE_GLOBAL_ALLOW_ENV)) {
1481                  if (!is_delete) domain->flags |= DOMAIN_FLAGS_FORCE_ALT_EXEC;                  ccs_set_domain_flag(domain, is_delete,
1482                  else domain->flags &= ~DOMAIN_FLAGS_FORCE_ALT_EXEC;                                      DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_ENV);
1483                  return 0;                  return 0;
1484          }          }
1485          cp = FindConditionPart(data);          cp = ccs_find_condition_part(data);
1486          if (cp && (cond = FindOrAssignNewCondition(cp)) == NULL) return -EINVAL;          if (cp) {
1487          if (strncmp(data, KEYWORD_ALLOW_CAPABILITY, KEYWORD_ALLOW_CAPABILITY_LEN) == 0) {                  cond = ccs_find_or_assign_new_condition(cp);
1488                  return AddCapabilityPolicy(data + KEYWORD_ALLOW_CAPABILITY_LEN, domain, cond, is_delete);                  if (!cond)
1489          } else if (strncmp(data, KEYWORD_ALLOW_NETWORK, KEYWORD_ALLOW_NETWORK_LEN) == 0) {                          return -EINVAL;
                 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);  
1490          }          }
1491          return -EINVAL;          if (str_starts(&data, KEYWORD_ALLOW_CAPABILITY))
1492                    return ccs_write_capability_policy(data, domain, cond,
1493                                                       is_delete);
1494            else if (str_starts(&data, KEYWORD_ALLOW_NETWORK))
1495                    return ccs_write_network_policy(data, domain, cond, is_delete);
1496            else if (str_starts(&data, KEYWORD_ALLOW_SIGNAL))
1497                    return ccs_write_signal_policy(data, domain, cond, is_delete);
1498            else if (str_starts(&data, KEYWORD_ALLOW_ARGV0))
1499                    return ccs_write_argv0_policy(data, domain, cond, is_delete);
1500            else if (str_starts(&data, KEYWORD_ALLOW_ENV))
1501                    return ccs_write_env_policy(data, domain, cond, is_delete);
1502            else
1503                    return ccs_write_file_policy(data, domain, cond, is_delete);
1504  }  }
1505    
1506  static bool print_single_path_acl(struct io_buffer *head, struct single_path_acl_record *ptr, const struct condition_list *cond)  /**
1507     * print_single_path_acl - Print a single path ACL entry.
1508     *
1509     * @head: Pointer to "struct ccs_io_buffer".
1510     * @ptr:  Pointer to "struct single_path_acl_record".
1511     * @cond: Pointer to "struct condition_list". May be NULL.
1512     *
1513     * Returns true on success, false otherwise.
1514     */
1515    static bool print_single_path_acl(struct ccs_io_buffer *head,
1516                                      struct single_path_acl_record *ptr,
1517                                      const struct condition_list *cond)
1518  {  {
1519          int pos;          int pos;
1520          u8 bit;          u8 bit;
1521          const bool b = ptr->u_is_group;          const char *atmark = "";
1522            const char *filename;
1523          const u16 perm = ptr->perm;          const u16 perm = ptr->perm;
1524            if (ptr->u_is_group) {
1525                    atmark = "@";
1526                    filename = ptr->u.group->group_name->name;
1527            } else {
1528                    filename = ptr->u.filename->name;
1529            }
1530          for (bit = head->read_bit; bit < MAX_SINGLE_PATH_OPERATION; bit++) {          for (bit = head->read_bit; bit < MAX_SINGLE_PATH_OPERATION; bit++) {
1531                  const char *msg;                  const char *msg;
1532                  if (!(perm & (1 << bit))) continue;                  if (!(perm & (1 << bit)))
1533                            continue;
1534                  /* Print "read/write" instead of "read" and "write". */                  /* Print "read/write" instead of "read" and "write". */
1535                  if ((bit == TYPE_READ_ACL || bit == TYPE_WRITE_ACL) && (perm & (1 << TYPE_READ_WRITE_ACL))) continue;                  if ((bit == TYPE_READ_ACL || bit == TYPE_WRITE_ACL)
1536                  msg = sp_operation2keyword(bit);                      && (perm & (1 << TYPE_READ_WRITE_ACL)))
1537                            continue;
1538                    msg = ccs_sp2keyword(bit);
1539                  pos = head->read_avail;                  pos = head->read_avail;
1540                  if (b && io_printf(head, "allow_%s @%s ", msg, ptr->u.group->group_name->name)) goto out;                  if (!ccs_io_printf(head, "allow_%s %s%s", msg,
1541                  if (!b && io_printf(head, "allow_%s %s ", msg, ptr->u.filename->name)) goto out;                                     atmark, filename) ||
1542                  if (DumpCondition(head, cond)) goto out;                      !ccs_print_condition(head, cond))
1543                            goto out;
1544          }          }
1545          head->read_bit = 0;          head->read_bit = 0;
1546          return true;          return true;
# Line 891  static bool print_single_path_acl(struct Line 1550  static bool print_single_path_acl(struct
1550          return false;          return false;
1551  }  }
1552    
1553  static bool print_double_path_acl(struct io_buffer *head, struct double_path_acl_record *ptr, const struct condition_list *cond)  /**
1554     * print_double_path_acl - Print a double path ACL entry.
1555     *
1556     * @head: Pointer to "struct ccs_io_buffer".
1557     * @ptr:  Pointer to "struct double_path_acl_record".
1558     * @cond: Pointer to "struct condition_list". May be NULL.
1559     *
1560     * Returns true on success, false otherwise.
1561     */
1562    static bool print_double_path_acl(struct ccs_io_buffer *head,
1563                                      struct double_path_acl_record *ptr,
1564                                      const struct condition_list *cond)
1565  {  {
1566          int pos;          int pos;
1567          const bool b0 = ptr->u1_is_group, b1 = ptr->u2_is_group;          const char *atmark1 = "";
1568            const char *atmark2 = "";
1569            const char *filename1;
1570            const char *filename2;
1571          const u8 perm = ptr->perm;          const u8 perm = ptr->perm;
1572          u8 bit;          u8 bit;
1573            if (ptr->u1_is_group) {
1574                    atmark1 = "@";
1575                    filename1 = ptr->u1.group1->group_name->name;
1576            } else {
1577                    filename1 = ptr->u1.filename1->name;
1578            }
1579            if (ptr->u2_is_group) {
1580                    atmark2 = "@";
1581                    filename2 = ptr->u2.group2->group_name->name;
1582            } else {
1583                    filename2 = ptr->u2.filename2->name;
1584            }
1585          for (bit = head->read_bit; bit < MAX_DOUBLE_PATH_OPERATION; bit++) {          for (bit = head->read_bit; bit < MAX_DOUBLE_PATH_OPERATION; bit++) {
1586                  const char *msg;                  const char *msg;
1587                  if (!(perm & (1 << bit))) continue;                  if (!(perm & (1 << bit)))
1588                  msg = dp_operation2keyword(bit);                          continue;
1589                    msg = ccs_dp2keyword(bit);
1590                  pos = head->read_avail;                  pos = head->read_avail;
1591                  if (io_printf(head, "allow_%s ", msg)) goto out;                  if (!ccs_io_printf(head, "allow_%s %s%s %s%s", msg,
1592                  if (b0 && io_printf(head, "@%s ", ptr->u1.group1->group_name->name)) goto out;                                     atmark1, filename1, atmark2, filename2) ||
1593                  if (!b0 && io_printf(head, "%s ", ptr->u1.filename1->name)) goto out;                      !ccs_print_condition(head, cond))
1594                  if (b1 && io_printf(head, "@%s", ptr->u2.group2->group_name->name)) goto out;                          goto out;
                 if (!b1 && io_printf(head, "%s", ptr->u2.filename2->name)) goto out;  
                 if (DumpCondition(head, cond)) goto out;  
1595          }          }
1596          head->read_bit = 0;          head->read_bit = 0;
1597          return true;          return true;
1598   out:   out:
1599          head->read_bit = bit;          head->read_bit = bit;
# Line 917  static bool print_double_path_acl(struct Line 1601  static bool print_double_path_acl(struct
1601          return false;          return false;
1602  }  }
1603    
1604  static bool print_argv0_acl(struct io_buffer *head, struct argv0_acl_record *ptr, const struct condition_list *cond)  /**
1605     * print_argv0_acl - Print an argv[0] ACL entry.
1606     *
1607     * @head: Pointer to "struct ccs_io_buffer".
1608     * @ptr:  Pointer to "struct argv0_acl_record".
1609     * @cond: Pointer to "struct condition_list". May be NULL.
1610     *
1611     * Returns true on success, false otherwise.
1612     */
1613    static bool print_argv0_acl(struct ccs_io_buffer *head,
1614                                struct argv0_acl_record *ptr,
1615                                const struct condition_list *cond)
1616  {  {
1617          int pos = head->read_avail;          int pos = head->read_avail;
1618          if (io_printf(head, KEYWORD_ALLOW_ARGV0 "%s %s",          if (!ccs_io_printf(head, KEYWORD_ALLOW_ARGV0 "%s %s",
1619                        ptr->filename->name, ptr->argv0->name)) goto out;                             ptr->filename->name, ptr->argv0->name))
1620          if (DumpCondition(head, cond)) goto out;                  goto out;
1621            if (!ccs_print_condition(head, cond))
1622                    goto out;
1623          return true;          return true;
1624   out:   out:
1625          head->read_avail = pos;          head->read_avail = pos;
1626          return false;          return false;
1627  }  }
1628    
1629  static bool print_env_acl(struct io_buffer *head, struct env_acl_record *ptr, const struct condition_list *cond)  /**
1630     * print_env_acl - Print an evironment variable name's ACL entry.
1631     *
1632     * @head: Pointer to "struct ccs_io_buffer".
1633     * @ptr:  Pointer to "struct env_acl_record".
1634     * @cond: Pointer to "struct condition_list". May be NULL.
1635     *
1636     * Returns true on success, false otherwise.
1637     */
1638    static bool print_env_acl(struct ccs_io_buffer *head,
1639                              struct env_acl_record *ptr,
1640                              const struct condition_list *cond)
1641  {  {
1642          int pos = head->read_avail;          int pos = head->read_avail;
1643          if (io_printf(head, KEYWORD_ALLOW_ENV "%s", ptr->env->name)) goto out;          if (!ccs_io_printf(head, KEYWORD_ALLOW_ENV "%s", ptr->env->name))
1644          if (DumpCondition(head, cond)) goto out;                  goto out;
1645            if (!ccs_print_condition(head, cond))
1646                    goto out;
1647          return true;          return true;
1648   out:   out:
1649          head->read_avail = pos;          head->read_avail = pos;
1650          return false;          return false;
1651  }  }
1652    
1653  static bool print_capability_acl(struct io_buffer *head, struct capability_acl_record *ptr, const struct condition_list *cond)  /**
1654     * print_capability_acl - Print a capability ACL entry.
1655     *
1656     * @head: Pointer to "struct ccs_io_buffer".
1657     * @ptr:  Pointer to "struct capability_acl_record".
1658     * @cond: Pointer to "struct condition_list". May be NULL.
1659     *
1660     * Returns true on success, false otherwise.
1661     */
1662    static bool print_capability_acl(struct ccs_io_buffer *head,
1663                                     struct capability_acl_record *ptr,
1664                                     const struct condition_list *cond)
1665  {  {
1666          int pos = head->read_avail;          int pos = head->read_avail;
1667          if (io_printf(head, KEYWORD_ALLOW_CAPABILITY "%s", cap_operation2keyword(ptr->operation))) goto out;          if (!ccs_io_printf(head, KEYWORD_ALLOW_CAPABILITY "%s",
1668          if (DumpCondition(head, cond)) goto out;                             ccs_cap2keyword(ptr->operation)))
1669                    goto out;
1670            if (!ccs_print_condition(head, cond))
1671                    goto out;
1672          return true;          return true;
1673   out:   out:
1674          head->read_avail = pos;          head->read_avail = pos;
1675          return false;          return false;
1676  }  }
1677    
1678  static bool print_network_acl(struct io_buffer *head, struct ip_network_acl_record *ptr, const struct condition_list *cond)  /**
1679     * print_ipv4_entry - Print IPv4 address of a network ACL entry.
1680     *
1681     * @head: Pointer to "struct ccs_io_buffer".
1682     * @ptr:  Pointer to "struct ip_network_acl_record".
1683     *
1684     * Returns true on success, false otherwise.
1685     */
1686    static bool print_ipv4_entry(struct ccs_io_buffer *head,
1687                                 struct ip_network_acl_record *ptr)
1688    {
1689            const u32 min_address = ptr->u.ipv4.min;
1690            const u32 max_address = ptr->u.ipv4.max;
1691            if (!ccs_io_printf(head, "%u.%u.%u.%u", HIPQUAD(min_address)))
1692                    return false;
1693            if (min_address != max_address
1694                && !ccs_io_printf(head, "-%u.%u.%u.%u", HIPQUAD(max_address)))
1695                    return false;
1696            return true;
1697    }
1698    
1699    /**
1700     * print_ipv6_entry - Print IPv6 address of a network ACL entry.
1701     *
1702     * @head: Pointer to "struct ccs_io_buffer".
1703     * @ptr:  Pointer to "struct ip_network_acl_record".
1704     *
1705     * Returns true on success, false otherwise.
1706     */
1707    static bool print_ipv6_entry(struct ccs_io_buffer *head,
1708                                 struct ip_network_acl_record *ptr)
1709    {
1710            char buf[64];
1711            const struct in6_addr *min_address = ptr->u.ipv6.min;
1712            const struct in6_addr *max_address = ptr->u.ipv6.max;
1713            ccs_print_ipv6(buf, sizeof(buf), min_address);
1714            if (!ccs_io_printf(head, "%s", buf))
1715                    return false;
1716            if (min_address != max_address) {
1717                    ccs_print_ipv6(buf, sizeof(buf), max_address);
1718                    if (!ccs_io_printf(head, "-%s", buf))
1719                            return false;
1720            }
1721            return true;
1722    }
1723    
1724    /**
1725     * print_port_entry - Print port number of a network ACL entry.
1726     *
1727     * @head: Pointer to "struct ccs_io_buffer".
1728     * @ptr:  Pointer to "struct ip_network_acl_record".
1729     *
1730     * Returns true on success, false otherwise.
1731     */
1732    static bool print_port_entry(struct ccs_io_buffer *head,
1733                                 struct ip_network_acl_record *ptr)
1734    {
1735            const u16 min_port = ptr->min_port, max_port = ptr->max_port;
1736            if (!ccs_io_printf(head, " %u", min_port))
1737                    return false;
1738            if (min_port != max_port && !ccs_io_printf(head, "-%u", max_port))
1739                    return false;
1740            return true;
1741    }
1742    
1743    /**
1744     * print_network_acl - Print a network ACL entry.
1745     *
1746     * @head: Pointer to "struct ccs_io_buffer".
1747     * @ptr:  Pointer to "struct ip_network_acl_record".
1748     * @cond: Pointer to "struct condition_list". May be NULL.
1749     *
1750     * Returns true on success, false otherwise.
1751     */
1752    static bool print_network_acl(struct ccs_io_buffer *head,
1753                                  struct ip_network_acl_record *ptr,
1754                                  const struct condition_list *cond)
1755  {  {
1756          int pos = head->read_avail;          int pos = head->read_avail;
1757          if (io_printf(head, KEYWORD_ALLOW_NETWORK "%s ", net_operation2keyword(ptr->operation_type))) goto out;          if (!ccs_io_printf(head, KEYWORD_ALLOW_NETWORK "%s ",
1758                               ccs_net2keyword(ptr->operation_type)))
1759                    goto out;
1760          switch (ptr->record_type) {          switch (ptr->record_type) {
1761          case IP_RECORD_TYPE_ADDRESS_GROUP:          case IP_RECORD_TYPE_ADDRESS_GROUP:
1762                  if (io_printf(head, "@%s", ptr->u.group->group_name->name)) goto out;                  if (!ccs_io_printf(head, "@%s", ptr->u.group->group_name->name))
1763                            goto out;
1764                  break;                  break;
1765          case IP_RECORD_TYPE_IPv4:          case IP_RECORD_TYPE_IPv4:
1766                  {                  if (!print_ipv4_entry(head, ptr))
1767                          const u32 min_address = ptr->u.ipv4.min, max_address = ptr->u.ipv4.max;                          goto out;
                         if (io_printf(head, "%u.%u.%u.%u", HIPQUAD(min_address))) goto out;  
                         if (min_address != max_address && io_printf(head, "-%u.%u.%u.%u", HIPQUAD(max_address))) goto out;  
                 }  
1768                  break;                  break;
1769          case IP_RECORD_TYPE_IPv6:          case IP_RECORD_TYPE_IPv6:
1770                  {                  if (!print_ipv6_entry(head, ptr))
1771                          char buf[64];                          goto out;
                         const struct in6_addr *min_address = ptr->u.ipv6.min, *max_address = ptr->u.ipv6.max;  
                         print_ipv6(buf, sizeof(buf), min_address);  
                         if (io_printf(head, "%s", buf)) goto out;  
                         if (min_address != max_address) {  
                                 print_ipv6(buf, sizeof(buf), max_address);  
                                 if (io_printf(head, "-%s", buf)) goto out;  
                         }  
                 }  
1772                  break;                  break;
1773          }          }
1774          {          if (!print_port_entry(head, ptr))
1775                  const u16 min_port = ptr->min_port, max_port = ptr->max_port;                  goto out;
1776                  if (io_printf(head, " %u", min_port)) goto out;          if (!ccs_print_condition(head, cond))
1777                  if (min_port != max_port && io_printf(head, "-%u", max_port)) goto out;                  goto out;
         }  
         if (DumpCondition(head, cond)) goto out;  
1778          return true;          return true;
1779   out:   out:
1780          head->read_avail = pos;          head->read_avail = pos;
1781          return false;          return false;
1782  }  }
1783    
1784  static bool print_signal_acl(struct io_buffer *head, struct signal_acl_record *ptr, const struct condition_list *cond)  /**
1785     * print_signal_acl - Print a signal ACL entry.
1786     *
1787     * @head: Pointer to "struct ccs_io_buffer".
1788     * @ptr:  Pointer to "struct signale_acl_record".
1789     * @cond: Pointer to "struct condition_list". May be NULL.
1790     *
1791     * Returns true on success, false otherwise.
1792     */
1793    static bool print_signal_acl(struct ccs_io_buffer *head,
1794                                 struct signal_acl_record *ptr,
1795                                 const struct condition_list *cond)
1796  {  {
1797          int pos = head->read_avail;          int pos = head->read_avail;
1798          if (io_printf(head, KEYWORD_ALLOW_SIGNAL "%u %s", ptr->sig, ptr->domainname->name)) goto out;          if (!ccs_io_printf(head, KEYWORD_ALLOW_SIGNAL "%u %s",
1799          if (DumpCondition(head, cond)) goto out;                             ptr->sig, ptr->domainname->name))
1800                    goto out;
1801            if (!ccs_print_condition(head, cond))
1802                    goto out;
1803          return true;          return true;
1804   out:   out:
1805          head->read_avail = pos;          head->read_avail = pos;
1806          return false;          return false;
1807  }  }
1808    
1809  static int ReadDomainPolicy(struct io_buffer *head)  /**
1810     * print_execute_handler_record - Print an execute handler ACL entry.
1811     *
1812     * @head:    Pointer to "struct ccs_io_buffer".
1813     * @keyword: Name of the keyword.
1814     * @ptr:     Pointer to "struct execute_handler_record".
1815     *
1816     * Returns true on success, false otherwise.
1817     */
1818    static bool print_execute_handler_record(struct ccs_io_buffer *head,
1819                                             const char *keyword,
1820                                             struct execute_handler_record *ptr)
1821    {
1822            return ccs_io_printf(head, "%s %s\n", keyword, ptr->handler->name);
1823    }
1824    
1825    /**
1826     * print_entry - Print an ACL entry.
1827     *
1828     * @head: Pointer to "struct ccs_io_buffer".
1829     * @ptr:  Pointer to an ACL entry.
1830     *
1831     * Returns true on success, false otherwise.
1832     */
1833    static bool print_entry(struct ccs_io_buffer *head, struct acl_info *ptr)
1834    {
1835            const struct condition_list *cond = ccs_get_condition_part(ptr);
1836            const u8 acl_type = ccs_acl_type2(ptr);
1837            if (acl_type & ACL_DELETED)
1838                    return true;
1839            if (acl_type == TYPE_SINGLE_PATH_ACL) {
1840                    struct single_path_acl_record *acl
1841                            = container_of(ptr, struct single_path_acl_record,
1842                                           head);
1843                    return print_single_path_acl(head, acl, cond);
1844            }
1845            if (acl_type == TYPE_DOUBLE_PATH_ACL) {
1846                    struct double_path_acl_record *acl
1847                            = container_of(ptr, struct double_path_acl_record,
1848                                           head);
1849                    return print_double_path_acl(head, acl, cond);
1850            }
1851            if (acl_type == TYPE_ARGV0_ACL) {
1852                    struct argv0_acl_record *acl
1853                            = container_of(ptr, struct argv0_acl_record, head);
1854                    return print_argv0_acl(head, acl, cond);
1855            }
1856            if (acl_type == TYPE_ENV_ACL) {
1857                    struct env_acl_record *acl
1858                            = container_of(ptr, struct env_acl_record, head);
1859                    return print_env_acl(head, acl, cond);
1860            }
1861            if (acl_type == TYPE_CAPABILITY_ACL) {
1862                    struct capability_acl_record *acl
1863                            = container_of(ptr, struct capability_acl_record, head);
1864                    return print_capability_acl(head, acl, cond);
1865            }
1866            if (acl_type == TYPE_IP_NETWORK_ACL) {
1867                    struct ip_network_acl_record *acl
1868                            = container_of(ptr, struct ip_network_acl_record, head);
1869                    return print_network_acl(head, acl, cond);
1870            }
1871            if (acl_type == TYPE_SIGNAL_ACL) {
1872                    struct signal_acl_record *acl
1873                            = container_of(ptr, struct signal_acl_record, head);
1874                    return print_signal_acl(head, acl, cond);
1875            }
1876            if (acl_type == TYPE_EXECUTE_HANDLER) {
1877                    struct execute_handler_record *acl
1878                            = container_of(ptr, struct execute_handler_record,
1879                                           head);
1880                    const char *keyword = KEYWORD_EXECUTE_HANDLER;
1881                    return print_execute_handler_record(head, keyword, acl);
1882            }
1883            if (acl_type == TYPE_DENIED_EXECUTE_HANDLER) {
1884                    struct execute_handler_record *acl
1885                            = container_of(ptr, struct execute_handler_record,
1886                                           head);
1887                    const char *keyword = KEYWORD_DENIED_EXECUTE_HANDLER;
1888                    return print_execute_handler_record(head, keyword, acl);
1889            }
1890            /* Workaround for gcc 3.2.2's inline bug. */
1891            if (acl_type & ACL_DELETED)
1892                    return true;
1893            BUG(); /* This must not happen. */
1894            return false;
1895    }
1896    
1897    /**
1898     * read_domain_policy - Read domain policy.
1899     *
1900     * @head: Pointer to "struct ccs_io_buffer".
1901     *
1902     * Returns 0.
1903     */
1904    static int read_domain_policy(struct ccs_io_buffer *head)
1905  {  {
1906          struct list1_head *dpos;          struct list1_head *dpos;
1907          struct list1_head *apos;          struct list1_head *apos;
1908          if (head->read_eof) return 0;          if (head->read_eof)
1909          if (head->read_step == 0) head->read_step = 1;                  return 0;
1910            if (head->read_step == 0)
1911                    head->read_step = 1;
1912          list1_for_each_cookie(dpos, head->read_var1, &domain_list) {          list1_for_each_cookie(dpos, head->read_var1, &domain_list) {
1913                  struct domain_info *domain;                  struct domain_info *domain;
1914                    const char *quota_exceeded = "";
1915                    const char *transition_failed = "";
1916                    const char *ignore_global_allow_read = "";
1917                    const char *ignore_global_allow_env = "";
1918                  domain = list1_entry(dpos, struct domain_info, list);                  domain = list1_entry(dpos, struct domain_info, list);
1919                  if (head->read_step != 1) goto acl_loop;                  if (head->read_step != 1)
1920                  if (domain->is_deleted) continue;                          goto acl_loop;
1921                  if (io_printf(head, "%s\n" KEYWORD_USE_PROFILE "%u\n%s\n%s%s%s", domain->domainname->name, domain->profile, domain->quota_warned ? "quota_exceeded\n" : "", domain->flags & DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_READ ? KEYWORD_IGNORE_GLOBAL_ALLOW_READ "\n" : "", domain->flags & DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_ENV ? KEYWORD_IGNORE_GLOBAL_ALLOW_ENV "\n" : "", domain->flags & DOMAIN_FLAGS_FORCE_ALT_EXEC ? KEYWORD_FORCE_ALT_EXEC "\n" : "")) return 0;                  if (domain->is_deleted)
1922                            continue;
1923                    /* Print domainname and flags. */
1924                    if (domain->quota_warned)
1925                            quota_exceeded = "quota_exceeded\n";
1926                    if (domain->flags & DOMAIN_FLAGS_TRANSITION_FAILED)
1927                            transition_failed = "transition_failed\n";
1928                    if (domain->flags & DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_READ)
1929                            ignore_global_allow_read
1930                                    = KEYWORD_IGNORE_GLOBAL_ALLOW_READ "\n";
1931                    if (domain->flags & DOMAIN_FLAGS_IGNORE_GLOBAL_ALLOW_ENV)
1932                            ignore_global_allow_env
1933                                    = KEYWORD_IGNORE_GLOBAL_ALLOW_ENV "\n";
1934                    if (!ccs_io_printf(head, "%s\n" KEYWORD_USE_PROFILE "%u\n"
1935                                       "%s%s%s%s\n", domain->domainname->name,
1936                                       domain->profile, quota_exceeded,
1937                                       transition_failed,
1938                                       ignore_global_allow_read,
1939                                       ignore_global_allow_env))
1940                            return 0;
1941                  head->read_step = 2;                  head->read_step = 2;
1942          acl_loop: ;   acl_loop:
1943                  if (head->read_step == 3) goto tail_mark;                  if (head->read_step == 3)
1944                  list1_for_each_cookie(apos, head->read_var2, &domain->acl_info_list) {                          goto tail_mark;
1945                          struct acl_info *ptr;                  /* Print ACL entries in the domain. */
1946                          u8 acl_type;                  list1_for_each_cookie(apos, head->read_var2,
1947                          const struct condition_list *cond;                                        &domain->acl_info_list) {
1948                          ptr = list1_entry(apos, struct acl_info, list);                          struct acl_info *ptr
1949                          cond = GetConditionPart(ptr);                                  = list1_entry(apos, struct acl_info, list);
1950                          acl_type = ptr->type & ~ACL_WITH_CONDITION;                          if (!print_entry(head, ptr))
1951                          if (acl_type & ACL_DELETED) {                                  return 0;
                                 /* Deleted entry. */  
                         } else if (acl_type == TYPE_SINGLE_PATH_ACL) {  
                                 if (!print_single_path_acl(head, container_of(ptr, struct single_path_acl_record, head), cond)) return 0;  
                         } else if (acl_type == TYPE_DOUBLE_PATH_ACL) {  
                                 if (!print_double_path_acl(head, container_of(ptr, struct double_path_acl_record, head), cond)) return 0;  
                         } else if (acl_type == TYPE_ARGV0_ACL) {  
                                 if (!print_argv0_acl(head, container_of(ptr, struct argv0_acl_record, head), cond)) return 0;  
                         } else if (acl_type == TYPE_ENV_ACL) {  
                                 if (!print_env_acl(head, container_of(ptr, struct env_acl_record, head), cond)) return 0;  
                         } else if (acl_type == TYPE_CAPABILITY_ACL) {  
                                 if (!print_capability_acl(head, container_of(ptr, struct capability_acl_record, head), cond)) return 0;  
                         } else if (acl_type == TYPE_IP_NETWORK_ACL) {  
                                 if (!print_network_acl(head, container_of(ptr, struct ip_network_acl_record, head), cond)) return 0;  
                         } else if (acl_type == TYPE_SIGNAL_ACL) {  
                                 if (!print_signal_acl(head, container_of(ptr, struct signal_acl_record, head), cond)) return 0;  
                         } else {  
                                 BUG();  
                         }  
1952                  }                  }
1953                  head->read_step = 3;                  head->read_step = 3;
1954          tail_mark: ;   tail_mark:
1955                  if (io_printf(head, "\n")) return 0;                  if (!ccs_io_printf(head, "\n"))
1956                            return 0;
1957                  head->read_step = 1;                  head->read_step = 1;
1958          }          }
1959          head->read_eof = true;          head->read_eof = true;
# Line 1055  static int ReadDomainPolicy(struct io_bu Line 1962  static int ReadDomainPolicy(struct io_bu
1962    
1963  #endif  #endif
1964    
1965  static int UpdateDomainProfile(struct io_buffer *head)  /**
1966     * write_domain_profile - Assign profile for specified domain.
1967     *
1968     * @head: Pointer to "struct ccs_io_buffer".
1969     *
1970     * Returns 0 on success, -EINVAL otherwise.
1971     *
1972     * This is equivalent to doing
1973     *
1974     *     ( echo "select " $domainname; echo "use_profile " $profile ) |
1975     *     /usr/lib/ccs/loadpolicy -d
1976     */
1977    static int write_domain_profile(struct ccs_io_buffer *head)
1978  {  {
1979          char *data = head->write_buf;          char *data = head->write_buf;
1980          char *cp = strchr(data, ' ');          char *cp = strchr(data, ' ');
1981          struct domain_info *domain;          struct domain_info *domain;
1982          unsigned int profile;          unsigned int profile;
1983          if (!cp) return -EINVAL;          if (!cp)
1984                    return -EINVAL;
1985          *cp = '\0';          *cp = '\0';
1986          domain = FindDomain(cp + 1);          domain = ccs_find_domain(cp + 1);
1987          profile = simple_strtoul(data, NULL, 10);          profile = simple_strtoul(data, NULL, 10);
1988          if (domain && profile < MAX_PROFILES && (profile_ptr[profile] || !sbin_init_started)) domain->profile = (u8) profile;          if (domain && profile < MAX_PROFILES
1989          UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);              && (profile_ptr[profile] || !sbin_init_started))
1990                    domain->profile = (u8) profile;
1991            ccs_update_counter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);
1992          return 0;          return 0;
1993  }  }
1994    
1995  static int ReadDomainProfile(struct io_buffer *head)  /**
1996     * read_domain_profile - Read only domainname and profile.
1997     *
1998     * @head: Pointer to "struct ccs_io_buffer".
1999     *
2000     * Returns list of profile number and domainname pairs.
2001     *
2002     * This is equivalent to doing
2003     *
2004     *     grep -A 1 '^<kernel>' /proc/ccs/domain_policy |
2005     *     awk ' { if ( domainname == "" ) { if ( $1 == "<kernel>" )
2006     *     domainname = $0; } else if ( $1 == "use_profile" ) {
2007     *     print $2 " " domainname; domainname = ""; } } ; '
2008     */
2009    static int read_domain_profile(struct ccs_io_buffer *head)
2010  {  {
2011          struct list1_head *pos;          struct list1_head *pos;
2012          if (head->read_eof) return 0;          if (head->read_eof)
2013                    return 0;
2014          list1_for_each_cookie(pos, head->read_var1, &domain_list) {          list1_for_each_cookie(pos, head->read_var1, &domain_list) {
2015                  struct domain_info *domain;                  struct domain_info *domain;
2016                  domain = list1_entry(pos, struct domain_info, list);                  domain = list1_entry(pos, struct domain_info, list);
2017                  if (domain->is_deleted) continue;                  if (domain->is_deleted)
2018                  if (io_printf(head, "%u %s\n", domain->profile, domain->domainname->name)) return 0;                          continue;
2019                    if (!ccs_io_printf(head, "%u %s\n", domain->profile,
2020                                       domain->domainname->name))
2021                            return 0;
2022          }          }
2023          head->read_eof = true;          head->read_eof = true;
2024          return 0;          return 0;
2025  }  }
2026    
2027  static int WritePID(struct io_buffer *head)  /**
2028     * write_pid: Specify PID to obtain domainname.
2029     *
2030     * @head: Pointer to "struct ccs_io_buffer".
2031     *
2032     * Returns 0.
2033     */
2034    static int write_pid(struct ccs_io_buffer *head)
2035  {  {
2036          head->read_step = (int) simple_strtoul(head->write_buf, NULL, 10);          head->read_step = (int) simple_strtoul(head->write_buf, NULL, 10);
2037          head->read_eof = false;          head->read_eof = false;
2038          return 0;          return 0;
2039  }  }
2040    
2041  static int ReadPID(struct io_buffer *head)  /**
2042     * read_pid - Get domainname of the specified PID.
2043     *
2044     * @head: Pointer to "struct ccs_io_buffer".
2045     *
2046     * Returns the domainname which the specified PID is in on success,
2047     * empty string otherwise.
2048     * The PID is specified by write_pid() so that the user can obtain
2049     * using read()/write() interface rather than sysctl() interface.
2050     */
2051    static int read_pid(struct ccs_io_buffer *head)
2052  {  {
2053          if (head->read_avail == 0 && !head->read_eof) {          if (head->read_avail == 0 && !head->read_eof) {
2054                  const int pid = head->read_step;                  const int pid = head->read_step;
# Line 1100  static int ReadPID(struct io_buffer *hea Line 2057  static int ReadPID(struct io_buffer *hea
2057                  /***** CRITICAL SECTION START *****/                  /***** CRITICAL SECTION START *****/
2058                  read_lock(&tasklist_lock);                  read_lock(&tasklist_lock);
2059                  p = find_task_by_pid(pid);                  p = find_task_by_pid(pid);
2060                  if (p) domain = p->domain_info;                  if (p)
2061                            domain = p->domain_info;
2062                  read_unlock(&tasklist_lock);                  read_unlock(&tasklist_lock);
2063                  /***** CRITICAL SECTION END *****/                  /***** CRITICAL SECTION END *****/
2064                  if (domain) io_printf(head, "%d %u %s", pid, domain->profile, domain->domainname->name);                  if (domain)
2065                            ccs_io_printf(head, "%d %u %s", pid, domain->profile,
2066                                          domain->domainname->name);
2067                  head->read_eof = true;                  head->read_eof = true;
2068          }          }
2069          return 0;          return 0;
2070  }  }
2071    
 /*************************  EXCEPTION POLICY HANDLER  *************************/  
   
2072  #ifdef CONFIG_TOMOYO  #ifdef CONFIG_TOMOYO
2073    
2074  static int AddExceptionPolicy(struct io_buffer *head)  /**
2075     * write_exception_policy - Write exception policy.
2076     *
2077     * @head: Pointer to "struct ccs_io_buffer".
2078     *
2079     * Returns 0 on success, negative value otherwise.
2080     */
2081    static int write_exception_policy(struct ccs_io_buffer *head)
2082  {  {
2083          char *data = head->write_buf;          char *data = head->write_buf;
2084          bool is_delete = false;          bool is_delete = str_starts(&data, KEYWORD_DELETE);
2085          UpdateCounter(CCS_UPDATES_COUNTER_EXCEPTION_POLICY);          if (str_starts(&data, KEYWORD_KEEP_DOMAIN))
2086          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {                  return ccs_write_domain_keeper_policy(data, false, is_delete);
2087                  data += KEYWORD_DELETE_LEN;          if (str_starts(&data, KEYWORD_NO_KEEP_DOMAIN))
2088                  is_delete = true;                  return ccs_write_domain_keeper_policy(data, true, is_delete);
2089          }          if (str_starts(&data, KEYWORD_INITIALIZE_DOMAIN))
2090          if (strncmp(data, KEYWORD_KEEP_DOMAIN, KEYWORD_KEEP_DOMAIN_LEN) == 0) {                  return ccs_write_domain_initializer_policy(data, false,
2091                  return AddDomainKeeperPolicy(data + KEYWORD_KEEP_DOMAIN_LEN, 0, is_delete);                                                             is_delete);
2092          } else if (strncmp(data, KEYWORD_NO_KEEP_DOMAIN, KEYWORD_NO_KEEP_DOMAIN_LEN) == 0) {          if (str_starts(&data, KEYWORD_NO_INITIALIZE_DOMAIN))
2093                  return AddDomainKeeperPolicy(data + KEYWORD_NO_KEEP_DOMAIN_LEN, 1, is_delete);                  return ccs_write_domain_initializer_policy(data, true,
2094          } else if (strncmp(data, KEYWORD_INITIALIZE_DOMAIN, KEYWORD_INITIALIZE_DOMAIN_LEN) == 0) {                                                             is_delete);
2095                  return AddDomainInitializerPolicy(data + KEYWORD_INITIALIZE_DOMAIN_LEN, 0, is_delete);          if (str_starts(&data, KEYWORD_ALIAS))
2096          } else if (strncmp(data, KEYWORD_NO_INITIALIZE_DOMAIN, KEYWORD_NO_INITIALIZE_DOMAIN_LEN) == 0) {                  return ccs_write_alias_policy(data, is_delete);
2097                  return AddDomainInitializerPolicy(data + KEYWORD_NO_INITIALIZE_DOMAIN_LEN, 1, is_delete);          if (str_starts(&data, KEYWORD_AGGREGATOR))
2098          } else if (strncmp(data, KEYWORD_ALIAS, KEYWORD_ALIAS_LEN) == 0) {                  return ccs_write_aggregator_policy(data, is_delete);
2099                  return AddAliasPolicy(data + KEYWORD_ALIAS_LEN, is_delete);          if (str_starts(&data, KEYWORD_ALLOW_READ))
2100          } else if (strncmp(data, KEYWORD_AGGREGATOR, KEYWORD_AGGREGATOR_LEN) == 0) {                  return ccs_write_globally_readable_policy(data, is_delete);
2101                  return AddAggregatorPolicy(data + KEYWORD_AGGREGATOR_LEN, is_delete);          if (str_starts(&data, KEYWORD_ALLOW_ENV))
2102          } else if (strncmp(data, KEYWORD_ALLOW_READ, KEYWORD_ALLOW_READ_LEN) == 0) {                  return ccs_write_globally_usable_env_policy(data, is_delete);
2103                  return AddGloballyReadablePolicy(data + KEYWORD_ALLOW_READ_LEN, is_delete);          if (str_starts(&data, KEYWORD_FILE_PATTERN))
2104          } else if (strncmp(data, KEYWORD_ALLOW_ENV, KEYWORD_ALLOW_ENV_LEN) == 0) {                  return ccs_write_pattern_policy(data, is_delete);
2105                  return AddGloballyUsableEnvPolicy(data + KEYWORD_ALLOW_ENV_LEN, is_delete);          if (str_starts(&data, KEYWORD_PATH_GROUP))
2106          } else if (strncmp(data, KEYWORD_FILE_PATTERN, KEYWORD_FILE_PATTERN_LEN) == 0) {                  return ccs_write_path_group_policy(data, is_delete);
2107                  return AddFilePatternPolicy(data + KEYWORD_FILE_PATTERN_LEN, is_delete);          if (str_starts(&data, KEYWORD_DENY_REWRITE))
2108          } else if (strncmp(data, KEYWORD_PATH_GROUP, KEYWORD_PATH_GROUP_LEN) == 0) {                  return ccs_write_no_rewrite_policy(data, is_delete);
2109                  return AddPathGroupPolicy(data + KEYWORD_PATH_GROUP_LEN, is_delete);          if (str_starts(&data, KEYWORD_ADDRESS_GROUP))
2110          } else if (strncmp(data, KEYWORD_DENY_REWRITE, KEYWORD_DENY_REWRITE_LEN) == 0) {                  return ccs_write_address_group_policy(data, is_delete);
                 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);  
         }  
2111          return -EINVAL;          return -EINVAL;
2112  }  }
2113    
2114  static int ReadExceptionPolicy(struct io_buffer *head)  /**
2115     * read_exception_policy - Read exception policy.
2116     *
2117     * @head: Pointer to "struct ccs_io_buffer".
2118     *
2119     * Returns 0 on success, -EINVAL otherwise.
2120     */
2121    static int read_exception_policy(struct ccs_io_buffer *head)
2122  {  {
2123          if (!head->read_eof) {          if (!head->read_eof) {
2124                  switch (head->read_step) {                  switch (head->read_step) {
2125                  case 0:                  case 0:
2126                          head->read_var2 = NULL; head->read_step = 1;                          head->read_var2 = NULL;
2127                            head->read_step = 1;
2128                  case 1:                  case 1:
2129                          if (ReadDomainKeeperPolicy(head)) break;                          if (!ccs_read_domain_keeper_policy(head))
2130                          head->read_var2 = NULL; head->read_step = 2;                                  break;
2131                            head->read_var2 = NULL;
2132                            head->read_step = 2;
2133                  case 2:                  case 2:
2134                          if (ReadGloballyReadablePolicy(head)) break;                          if (!ccs_read_globally_readable_policy(head))
2135                          head->read_var2 = NULL; head->read_step = 3;                                  break;
2136                            head->read_var2 = NULL;
2137                            head->read_step = 3;
2138                  case 3:                  case 3:
2139                          if (ReadGloballyUsableEnvPolicy(head)) break;                          if (!ccs_read_globally_usable_env_policy(head))
2140                          head->read_var2 = NULL; head->read_step = 4;                                  break;
2141                            head->read_var2 = NULL;
2142                            head->read_step = 4;
2143                  case 4:                  case 4:
2144                          if (ReadDomainInitializerPolicy(head)) break;                          if (!ccs_read_domain_initializer_policy(head))
2145                          head->read_var2 = NULL; head->read_step = 5;                                  break;
2146                            head->read_var2 = NULL;
2147                            head->read_step = 5;
2148                  case 5:                  case 5:
2149                          if (ReadAliasPolicy(head)) break;                          if (!ccs_read_alias_policy(head))
2150                          head->read_var2 = NULL; head->read_step = 6;                                  break;
2151                            head->read_var2 = NULL;
2152                            head->read_step = 6;
2153                  case 6:                  case 6:
2154                          if (ReadAggregatorPolicy(head)) break;                          if (!ccs_read_aggregator_policy(head))
2155                          head->read_var2 = NULL; head->read_step = 7;                                  break;
2156                            head->read_var2 = NULL;
2157                            head->read_step = 7;
2158                  case 7:                  case 7:
2159                          if (ReadFilePatternPolicy(head)) break;                          if (!ccs_read_file_pattern(head))
2160                          head->read_var2 = NULL; head->read_step = 8;                                  break;
2161                            head->read_var2 = NULL;
2162                            head->read_step = 8;
2163                  case 8:                  case 8:
2164                          if (ReadNoRewritePolicy(head)) break;                          if (!ccs_read_no_rewrite_policy(head))
2165                          head->read_var2 = NULL; head->read_step = 9;                                  break;
2166                            head->read_var2 = NULL;
2167                            head->read_step = 9;
2168                  case 9:                  case 9:
2169                          if (ReadPathGroupPolicy(head)) break;                          if (!ccs_read_path_group_policy(head))
2170                          head->read_var1 = head->read_var2 = NULL; head->read_step = 10;                                  break;
2171                            head->read_var1 = NULL;
2172                            head->read_var2 = NULL;
2173                            head->read_step = 10;
2174                  case 10:                  case 10:
2175                          if (ReadAddressGroupPolicy(head)) break;                          if (!ccs_read_address_group_policy(head))
2176                                    break;
2177                          head->read_eof = true;                          head->read_eof = true;
2178                          break;                          break;
2179                  default:                  default:
# Line 1196  static int ReadExceptionPolicy(struct io Line 2185  static int ReadExceptionPolicy(struct io
2185    
2186  #endif  #endif
2187    
 /*************************  SYSTEM POLICY HANDLER  *************************/  
   
2188  #ifdef CONFIG_SAKURA  #ifdef CONFIG_SAKURA
2189    
2190  static int AddSystemPolicy(struct io_buffer *head)  /**
2191     * write_system_policy - Write system policy.
2192     *
2193     * @head: Pointer to "struct ccs_io_buffer".
2194     *
2195     * Returns 0 on success, negative value otherwise.
2196     */
2197    static int write_system_policy(struct ccs_io_buffer *head)
2198  {  {
2199          char *data = head->write_buf;          char *data = head->write_buf;
2200          bool is_delete = false;          bool is_delete = false;
2201          UpdateCounter(CCS_UPDATES_COUNTER_SYSTEM_POLICY);          if (str_starts(&data, KEYWORD_DELETE))
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
2202                  is_delete = true;                  is_delete = true;
2203          }          if (str_starts(&data, KEYWORD_ALLOW_MOUNT))
2204          if (strncmp(data, KEYWORD_ALLOW_MOUNT, KEYWORD_ALLOW_MOUNT_LEN) == 0)                  return ccs_write_mount_policy(data, is_delete);
2205                  return AddMountPolicy(data + KEYWORD_ALLOW_MOUNT_LEN, is_delete);          if (str_starts(&data, KEYWORD_DENY_UNMOUNT))
2206          if (strncmp(data, KEYWORD_DENY_UNMOUNT, KEYWORD_DENY_UNMOUNT_LEN) == 0)                  return ccs_write_no_umount_policy(data, is_delete);
2207                  return AddNoUmountPolicy(data + KEYWORD_DENY_UNMOUNT_LEN, is_delete);          if (str_starts(&data, KEYWORD_ALLOW_CHROOT))
2208          if (strncmp(data, KEYWORD_ALLOW_CHROOT, KEYWORD_ALLOW_CHROOT_LEN) == 0)                  return ccs_write_chroot_policy(data, is_delete);
2209                  return AddChrootPolicy(data + KEYWORD_ALLOW_CHROOT_LEN, is_delete);          if (str_starts(&data, KEYWORD_ALLOW_PIVOT_ROOT))
2210          if (strncmp(data, KEYWORD_ALLOW_PIVOT_ROOT, KEYWORD_ALLOW_PIVOT_ROOT_LEN) == 0)                  return ccs_write_pivot_root_policy(data, is_delete);
2211                  return AddPivotRootPolicy(data + KEYWORD_ALLOW_PIVOT_ROOT_LEN, is_delete);          if (str_starts(&data, KEYWORD_DENY_AUTOBIND))
2212          if (strncmp(data, KEYWORD_DENY_AUTOBIND, KEYWORD_DENY_AUTOBIND_LEN) == 0)                  return ccs_write_reserved_port_policy(data, is_delete);
                 return AddReservedPortPolicy(data + KEYWORD_DENY_AUTOBIND_LEN, is_delete);  
2213          return -EINVAL;          return -EINVAL;
2214  }  }
2215    
2216  static int ReadSystemPolicy(struct io_buffer *head)  /**
2217     * read_system_policy - Read system policy.
2218     *
2219     * @head: Pointer to "struct ccs_io_buffer".
2220     *
2221     * Returns 0 on success, -EINVAL otherwise.
2222     */
2223    static int read_system_policy(struct ccs_io_buffer *head)
2224  {  {
2225          if (!head->read_eof) {          if (!head->read_eof) {
2226                  switch (head->read_step) {                  switch (head->read_step) {
2227                  case 0:                  case 0:
2228                          head->read_var2 = NULL; head->read_step = 1;                          head->read_var2 = NULL;
2229                            head->read_step = 1;
2230                  case 1:                  case 1:
2231                          if (ReadMountPolicy(head)) break;                          if (!ccs_read_mount_policy(head))
2232                          head->read_var2 = NULL; head->read_step = 2;                                  break;
2233                            head->read_var2 = NULL;
2234                            head->read_step = 2;
2235                  case 2:                  case 2:
2236                          if (ReadNoUmountPolicy(head)) break;                          if (!ccs_read_no_umount_policy(head))
2237                          head->read_var2 = NULL; head->read_step = 3;                                  break;
2238                            head->read_var2 = NULL;
2239                            head->read_step = 3;
2240                  case 3:                  case 3:
2241                          if (ReadChrootPolicy(head)) break;                          if (!ccs_read_chroot_policy(head))
2242                          head->read_var2 = NULL; head->read_step = 4;                                  break;
2243                            head->read_var2 = NULL;
2244                            head->read_step = 4;
2245                  case 4:                  case 4:
2246                          if (ReadPivotRootPolicy(head)) break;                          if (!ccs_read_pivot_root_policy(head))
2247                          head->read_var2 = NULL; head->read_step = 5;                                  break;
2248                            head->read_var2 = NULL;
2249                            head->read_step = 5;
2250                  case 5:                  case 5:
2251                          if (ReadReservedPortPolicy(head)) break;                          if (!ccs_read_reserved_port_policy(head))
2252                                    break;
2253                          head->read_eof = true;                          head->read_eof = true;
2254                          break;                          break;
2255                  default:                  default:
# Line 1253  static int ReadSystemPolicy(struct io_bu Line 2261  static int ReadSystemPolicy(struct io_bu
2261    
2262  #endif  #endif
2263    
2264  /*************************  POLICY LOADER  *************************/  /* Path to the policy loader. The default is /sbin/ccs-init. */
2265    static const char *ccs_loader;
2266    
2267  static bool profile_loaded = false;  /**
2268     * loader_setup - Specify the policy loader to use.
2269  static const char *ccs_loader = NULL;   *
2270     * @str: Path to the policy loader.
2271  static int __init CCS_loader_Setup(char *str)   *
2272     * Returns 0.
2273     */
2274    static int __init loader_setup(char *str)
2275  {  {
2276          ccs_loader = str;          ccs_loader = str;
2277          return 0;          return 0;
2278  }  }
2279    
2280  __setup("CCS_loader=", CCS_loader_Setup);  __setup("CCS_loader=", loader_setup);
2281    
2282  void CCS_LoadPolicy(const char *filename)  /**
2283     * policy_loader_exists - Check whether /sbin/ccs-init exists.
2284     *
2285     * Returns true if /sbin/ccs-init exists, false otherwise.
2286     */
2287    static bool policy_loader_exists(void)
2288  {  {
         if (sbin_init_started) return;  
2289          /*          /*
2290           * Check filename is /sbin/init or /sbin/ccs-start .           * Don't activate MAC if the path given by 'CCS_loader=' option doesn't
2291           * /sbin/ccs-start is a dummy filename in case where /sbin/init can't be passed.           * exist. If the initrd includes /sbin/init but real-root-dev has not
2292           * You can create /sbin/ccs-start by "ln -s /bin/true /sbin/ccs-start", for           * mounted on / yet, activating MAC will block the system since
2293           * only the pathname is needed to activate Mandatory Access Control.           * policies are not loaded yet.
2294             * Thus, let do_execve() call this function everytime.
2295           */           */
2296          if (strcmp(filename, "/sbin/init") != 0 && strcmp(filename, "/sbin/ccs-start") != 0) return;          struct nameidata nd;
2297            if (!ccs_loader)
2298                    ccs_loader = "/sbin/ccs-init";
2299            if (path_lookup(ccs_loader, lookup_flags, &nd)) {
2300                    printk(KERN_INFO "Not activating Mandatory Access Control now "
2301                           "since %s doesn't exist.\n", ccs_loader);
2302                    return false;
2303            }
2304    #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)
2305            path_put(&nd.path);
2306    #else
2307            path_release(&nd);
2308    #endif
2309            return true;
2310    }
2311    
2312    #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0)
2313    /**
2314     * run_ccs_loader - Start /sbin/ccs-init .
2315     *
2316     * @unused: Not used.
2317     *
2318     * Returns PID of /sbin/ccs-init on success, negative value otherwise.
2319     */
2320    static int run_ccs_loader(void *unused)
2321    {
2322            char *argv[2];
2323            char *envp[3];
2324            printk(KERN_INFO "Calling %s to load policy. Please wait.\n",
2325                   ccs_loader);
2326            argv[0] = (char *) ccs_loader;
2327            argv[1] = NULL;
2328            envp[0] = "HOME=/";
2329            envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
2330            envp[2] = NULL;
2331            return exec_usermodehelper(argv[0], argv, envp);
2332    }
2333    #endif
2334    
2335    /**
2336     * ccs_load_policy - Run external policy loader to load policy.
2337     *
2338     * @filename: The program about to start.
2339     *
2340     * This function checks whether @filename is /sbin/init , and if so
2341     * invoke /sbin/ccs-init and wait for the termination of /sbin/ccs-init
2342     * and then continues invocation of /sbin/init.
2343     * /sbin/ccs-init reads policy files in /etc/ccs/ directory and
2344     * writes to /proc/ccs/ interfaces.
2345     *
2346     * Returns nothing.
2347     */
2348    void ccs_load_policy(const char *filename)
2349    {
2350            if (sbin_init_started)
2351                    return;
2352          /*          /*
2353           * Don't activate MAC if the path given by 'CCS_loader=' option doesn't exist.           * Check filename is /sbin/init or /sbin/ccs-start.
2354           * If initrd.img includes /sbin/init but real-root-dev has not mounted on / yet,           * /sbin/ccs-start is a dummy filename in case where /sbin/init can't
2355           * activating MAC will block the system since policies are not loaded yet.           * be passed.
2356           * So let do_execve() call this function everytime.           * You can create /sbin/ccs-start by "ln -s /bin/true /sbin/ccs-start".
2357           */           */
2358            if (strcmp(filename, "/sbin/init") &&
2359                strcmp(filename, "/sbin/ccs-start"))
2360                    return;
2361            if (!policy_loader_exists())
2362                    return;
2363    #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 0)
2364          {          {
2365                  struct nameidata nd;                  char *argv[2];
2366                  if (!ccs_loader) ccs_loader = "/sbin/ccs-init";                  char *envp[3];
2367                  if (path_lookup(ccs_loader, lookup_flags, &nd)) {                  printk(KERN_INFO "Calling %s to load policy. Please wait.\n",
2368                          printk("Not activating Mandatory Access Control now since %s doesn't exist.\n", ccs_loader);                         ccs_loader);
                         return;  
                 }  
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,25)  
                 path_put(&nd.path);  
 #else  
                 path_release(&nd);  
 #endif  
         }  
         if (!profile_loaded) {  
                 char *argv[2], *envp[3];  
                 printk("Calling %s to load policy. Please wait.\n", ccs_loader);  
2369                  argv[0] = (char *) ccs_loader;                  argv[0] = (char *) ccs_loader;
2370                  argv[1] = NULL;                  argv[1] = NULL;
2371                  envp[0] = "HOME=/";                  envp[0] = "HOME=/";
2372                  envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";                  envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
2373                  envp[2] = NULL;                  envp[2] = NULL;
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)  
2374                  call_usermodehelper(argv[0], argv, envp, 1);                  call_usermodehelper(argv[0], argv, envp, 1);
2375            }
2376  #else  #else
2377                  call_usermodehelper(argv[0], argv, envp);          {
2378  #endif                  /* Copied from kernel/kmod.c */
2379                  while (!profile_loaded) {                  struct task_struct *task = current;
2380                          set_current_state(TASK_INTERRUPTIBLE);                  pid_t pid = kernel_thread(run_ccs_loader, NULL, 0);
2381                          schedule_timeout(HZ / 10);                  sigset_t tmpsig;
2382                  }                  spin_lock_irq(&task->sigmask_lock);
2383                    tmpsig = task->blocked;
2384                    siginitsetinv(&task->blocked,
2385                                  sigmask(SIGKILL) | sigmask(SIGSTOP));
2386                    recalc_sigpending(task);
2387                    spin_unlock_irq(&task->sigmask_lock);
2388                    if (pid >= 0)
2389                            waitpid(pid, NULL, __WCLONE);
2390                    spin_lock_irq(&task->sigmask_lock);
2391                    task->blocked = tmpsig;
2392                    recalc_sigpending(task);
2393                    spin_unlock_irq(&task->sigmask_lock);
2394          }          }
2395    #endif
2396  #ifdef CONFIG_SAKURA  #ifdef CONFIG_SAKURA
2397          printk("SAKURA: 1.6.0-pre   2008/03/03\n");          printk(KERN_INFO "SAKURA: 1.6.2-pre   2008/06/10\n");
2398  #endif  #endif
2399  #ifdef CONFIG_TOMOYO  #ifdef CONFIG_TOMOYO
2400          printk("TOMOYO: 1.6.0-pre   2008/03/03\n");          printk(KERN_INFO "TOMOYO: 1.6.2-pre   2008/06/10\n");
2401  #endif  #endif
2402          printk("Mandatory Access Control activated.\n");          printk(KERN_INFO "Mandatory Access Control activated.\n");
2403          sbin_init_started = true;          sbin_init_started = true;
2404          ccs_log_level = KERN_WARNING;          ccs_log_level = KERN_WARNING;
2405          { /* Check all profiles currently assigned to domains are defined. */          { /* Check all profiles currently assigned to domains are defined. */
2406                  struct domain_info *domain;                  struct domain_info *domain;
2407                  list1_for_each_entry(domain, &domain_list, list) {                  list1_for_each_entry(domain, &domain_list, list) {
2408                          const u8 profile = domain->profile;                          const u8 profile = domain->profile;
2409                          if (!profile_ptr[profile]) panic("Profile %u (used by '%s') not defined.\n", profile, domain->domainname->name);                          if (profile_ptr[profile])
2410                                    continue;
2411                            panic("Profile %u (used by '%s') not defined.\n",
2412                                  profile, domain->domainname->name);
2413                  }                  }
2414          }          }
2415  }  }
2416    
2417  #ifndef CONFIG_TOMOYO  /* Wait queue for query_list. */
   
 int search_binary_handler_with_transition(struct linux_binprm *bprm, struct pt_regs *regs)  
 {  
 #ifdef CONFIG_SAKURA  
         CCS_LoadPolicy(bprm->filename);  
 #endif  
         return search_binary_handler(bprm, regs);  
 }  
   
 #endif  
   
 /*************************  MAC Decision Delayer  *************************/  
   
2418  static DECLARE_WAIT_QUEUE_HEAD(query_wait);  static DECLARE_WAIT_QUEUE_HEAD(query_wait);
2419    
2420  static spinlock_t query_lock = SPIN_LOCK_UNLOCKED;  /* Lock for manipurating query_list. */
2421    static DEFINE_SPINLOCK(query_lock);
2422    
2423    /* Structure for query. */
2424  struct query_entry {  struct query_entry {
2425          struct list_head list;          struct list_head list;
2426          char *query;          char *query;
# Line 1359  struct query_entry { Line 2430  struct query_entry {
2430          int answer;          int answer;
2431  };  };
2432    
2433    /* The list for "struct query_entry". */
2434  static LIST_HEAD(query_list);  static LIST_HEAD(query_list);
2435    
2436    /* Number of "struct file" referring /proc/ccs/query interface. */
2437  static atomic_t queryd_watcher = ATOMIC_INIT(0);  static atomic_t queryd_watcher = ATOMIC_INIT(0);
2438    
2439  int CheckSupervisor(const char *fmt, ...)  /**
2440     * ccs_check_supervisor - Ask for the supervisor's decision.
2441     *
2442     * @bprm: Pointer to "struct linux_binprm". May be NULL.
2443     * @fmt:  The printf()'s format string, followed by parameters.
2444     *
2445     * Returns 0 if the supervisor decided to permit the access request which
2446     * violated the policy in enforcing mode, -EPERM otherwise.
2447     */
2448    int ccs_check_supervisor(struct linux_binprm *bprm, const char *fmt, ...)
2449  {  {
2450          va_list args;          va_list args;
2451          int error = -EPERM;          int error = -EPERM;
2452          int pos, len;          int pos;
2453          static unsigned int serial = 0;          int len;
2454          struct query_entry *query_entry;          static unsigned int serial;
2455          if (!CheckCCSFlags(CCS_ALLOW_ENFORCE_GRACE) || !atomic_read(&queryd_watcher)) {          struct query_entry *query_entry = NULL;
2456                  if ((current->tomoyo_flags & CCS_DONT_SLEEP_ON_ENFORCE_ERROR) == 0) {          char *header;
2457                          int i;          if (!atomic_read(&queryd_watcher)) {
2458                          for (i = 0; i < CheckCCSFlags(CCS_SLEEP_PERIOD); i++) {                  int i;
2459                                  set_current_state(TASK_INTERRUPTIBLE);                  if (current->tomoyo_flags & CCS_DONT_SLEEP_ON_ENFORCE_ERROR)
2460                                  schedule_timeout(HZ / 10);                          return -EPERM;
2461                          }                  for (i = 0; i < ccs_check_flags(CCS_SLEEP_PERIOD); i++) {
2462                            set_current_state(TASK_INTERRUPTIBLE);
2463                            schedule_timeout(HZ / 10);
2464                  }                  }
2465                  return -EPERM;                  return -EPERM;
2466          }          }
2467          va_start(args, fmt);          va_start(args, fmt);
2468          len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 32;          len = vsnprintf((char *) &pos, sizeof(pos) - 1, fmt, args) + 32;
2469          va_end(args);          va_end(args);
2470          if ((query_entry = ccs_alloc(sizeof(*query_entry))) == NULL ||  #ifdef CONFIG_TOMOYO
2471                  (query_entry->query = ccs_alloc(len)) == NULL) goto out;          header = ccs_init_audit_log(&len, current->domain_info->profile,
2472                                        3, bprm);
2473    #else
2474            header = ccs_alloc(1);
2475    #endif
2476            if (!header)
2477                    goto out;
2478            query_entry = ccs_alloc(sizeof(*query_entry));
2479            if (!query_entry)
2480                    goto out;
2481            query_entry->query = ccs_alloc(len);
2482            if (!query_entry->query)
2483                    goto out;
2484          INIT_LIST_HEAD(&query_entry->list);          INIT_LIST_HEAD(&query_entry->list);
2485          /***** CRITICAL SECTION START *****/          /***** CRITICAL SECTION START *****/
2486          spin_lock(&query_lock);          spin_lock(&query_lock);
2487          query_entry->serial = serial++;          query_entry->serial = serial++;
2488          spin_unlock(&query_lock);          spin_unlock(&query_lock);
2489          /***** CRITICAL SECTION END *****/          /***** CRITICAL SECTION END *****/
2490          pos = snprintf(query_entry->query, len - 1, "Q%u\n", query_entry->serial);          pos = snprintf(query_entry->query, len - 1, "Q%u\n%s",
2491                           query_entry->serial, header);
2492            ccs_free(header);
2493            header = NULL;
2494          va_start(args, fmt);          va_start(args, fmt);
2495          vsnprintf(query_entry->query + pos, len - 1 - pos, fmt, args);          vsnprintf(query_entry->query + pos, len - 1 - pos, fmt, args);
2496          query_entry->query_len = strlen(query_entry->query) + 1;          query_entry->query_len = strlen(query_entry->query) + 1;
# Line 1400  int CheckSupervisor(const char *fmt, ... Line 2500  int CheckSupervisor(const char *fmt, ...
2500          list_add_tail(&query_entry->list, &query_list);          list_add_tail(&query_entry->list, &query_list);
2501          spin_unlock(&query_lock);          spin_unlock(&query_lock);
2502          /***** CRITICAL SECTION END *****/          /***** CRITICAL SECTION END *****/
2503          UpdateCounter(CCS_UPDATES_COUNTER_QUERY);          ccs_update_counter(CCS_UPDATES_COUNTER_QUERY);
2504          /* Give 10 seconds for supervisor's opinion. */          /* Give 10 seconds for supervisor's opinion. */
2505          for (query_entry->timer = 0; atomic_read(&queryd_watcher) && CheckCCSFlags(CCS_ALLOW_ENFORCE_GRACE) && query_entry->timer < 100; query_entry->timer++) {          for (query_entry->timer = 0; atomic_read(&queryd_watcher)
2506                         && query_entry->timer < 100; query_entry->timer++) {
2507                  wake_up(&query_wait);                  wake_up(&query_wait);
2508                  set_current_state(TASK_INTERRUPTIBLE);                  set_current_state(TASK_INTERRUPTIBLE);
2509                  schedule_timeout(HZ / 10);                  schedule_timeout(HZ / 10);
2510                  if (query_entry->answer) break;                  if (query_entry->answer)
2511                            break;
2512          }          }
2513          UpdateCounter(CCS_UPDATES_COUNTER_QUERY);          ccs_update_counter(CCS_UPDATES_COUNTER_QUERY);
2514          /***** CRITICAL SECTION START *****/          /***** CRITICAL SECTION START *****/
2515          spin_lock(&query_lock);          spin_lock(&query_lock);
2516          list_del(&query_entry->list);          list_del(&query_entry->list);
# Line 1426  int CheckSupervisor(const char *fmt, ... Line 2528  int CheckSupervisor(const char *fmt, ...
2528                  /* Rejected by administrator. */                  /* Rejected by administrator. */
2529                  break;                  break;
2530          }          }
2531   out: ;   out:
2532          if (query_entry) ccs_free(query_entry->query);          if (query_entry)
2533                    ccs_free(query_entry->query);
2534          ccs_free(query_entry);          ccs_free(query_entry);
2535            ccs_free(header);
2536          return error;          return error;
2537  }  }
2538    
2539  static int PollQuery(struct file *file, poll_table *wait)  /**
2540     * poll_query - poll() for /proc/ccs/query.
2541     *
2542     * @file: Pointer to "struct file".
2543     * @wait: Pointer to "poll_table".
2544     *
2545     * Returns POLLIN | POLLRDNORM when ready to read, 0 otherwise.
2546     *
2547     * Waits for access requests which violated policy in enforcing mode.
2548     */
2549    static int poll_query(struct file *file, poll_table *wait)
2550  {  {
2551          int found;          bool found;
2552          /***** CRITICAL SECTION START *****/          /***** CRITICAL SECTION START *****/
2553          spin_lock(&query_lock);          spin_lock(&query_lock);
2554          found = !list_empty(&query_list);          found = !list_empty(&query_list);
2555          spin_unlock(&query_lock);          spin_unlock(&query_lock);
2556          /***** CRITICAL SECTION END *****/          /***** CRITICAL SECTION END *****/
2557          if (found) return POLLIN | POLLRDNORM;          if (found)
2558                    return POLLIN | POLLRDNORM;
2559          poll_wait(file, &query_wait, wait);          poll_wait(file, &query_wait, wait);
2560          /***** CRITICAL SECTION START *****/          /***** CRITICAL SECTION START *****/
2561          spin_lock(&query_lock);          spin_lock(&query_lock);
2562          found = !list_empty(&query_list);          found = !list_empty(&query_list);
2563          spin_unlock(&query_lock);          spin_unlock(&query_lock);
2564          /***** CRITICAL SECTION END *****/          /***** CRITICAL SECTION END *****/
2565          if (found) return POLLIN | POLLRDNORM;          if (found)
2566                    return POLLIN | POLLRDNORM;
2567          return 0;          return 0;
2568  }  }
2569    
2570  static int ReadQuery(struct io_buffer *head)  /**
2571     * read_query - Read access requests which violated policy in enforcing mode.
2572     *
2573     * @head: Pointer to "struct ccs_io_buffer".
2574     *
2575     * Returns 0.
2576     */
2577    static int read_query(struct ccs_io_buffer *head)
2578  {  {
2579          struct list_head *tmp;          struct list_head *tmp;
2580          int pos = 0, len = 0;          int pos = 0;
2581            int len = 0;
2582          char *buf;          char *buf;
2583          if (head->read_avail) return 0;          if (head->read_avail)
2584                    return 0;
2585          if (head->read_buf) {          if (head->read_buf) {
2586                  ccs_free(head->read_buf); head->read_buf = NULL;                  ccs_free(head->read_buf);
2587                    head->read_buf = NULL;
2588                  head->readbuf_size = 0;                  head->readbuf_size = 0;
2589          }          }
2590          /***** CRITICAL SECTION START *****/          /***** CRITICAL SECTION START *****/
2591          spin_lock(&query_lock);          spin_lock(&query_lock);
2592          list_for_each(tmp, &query_list) {          list_for_each(tmp, &query_list) {
2593                  struct query_entry *ptr = list_entry(tmp, struct query_entry, list);                  struct query_entry *ptr
2594                  if (pos++ == head->read_step) {                          = list_entry(tmp, struct query_entry, list);
2595                          len = ptr->query_len;                  if (pos++ != head->read_step)
2596                          break;                          continue;
2597                  }                  len = ptr->query_len;
2598                    break;
2599          }          }
2600          spin_unlock(&query_lock);          spin_unlock(&query_lock);
2601          /***** CRITICAL SECTION END *****/          /***** CRITICAL SECTION END *****/
# Line 1476  static int ReadQuery(struct io_buffer *h Line 2603  static int ReadQuery(struct io_buffer *h
2603                  head->read_step = 0;                  head->read_step = 0;
2604                  return 0;                  return 0;
2605          }          }
2606          if ((buf = ccs_alloc(len)) != NULL) {          buf = ccs_alloc(len);
2607            if (buf) {
2608                  pos = 0;                  pos = 0;
2609                  /***** CRITICAL SECTION START *****/                  /***** CRITICAL SECTION START *****/
2610                  spin_lock(&query_lock);                  spin_lock(&query_lock);
2611                  list_for_each(tmp, &query_list) {                  list_for_each(tmp, &query_list) {
2612                          struct query_entry *ptr = list_entry(tmp, struct query_entry, list);                          struct query_entry *ptr
2613                          if (pos++ == head->read_step) {                                  = list_entry(tmp, struct query_entry, list);
2614                                  /* Some query can be skiipped since query_list can change, but I don't care. */                          if (pos++ != head->read_step)
2615                                  if (len == ptr->query_len) memmove(buf, ptr->query, len);                                  continue;
2616                                  break;                          /*
2617                          }                           * Some query can be skipped because query_list
2618                             * can change, but I don't care.
2619                             */
2620                            if (len == ptr->query_len)
2621                                    memmove(buf, ptr->query, len);
2622                            break;
2623                  }                  }
2624                  spin_unlock(&query_lock);                  spin_unlock(&query_lock);
2625                  /***** CRITICAL SECTION END *****/                  /***** CRITICAL SECTION END *****/
2626                  if (buf[0]) {                  if (buf[0]) {
2627                          head->readbuf_size = head->read_avail = len;                          head->read_avail = len;
2628                            head->readbuf_size = head->read_avail;
2629                          head->read_buf = buf;                          head->read_buf = buf;
2630                          head->read_step++;                          head->read_step++;
2631                  } else {                  } else {
# Line 1501  static int ReadQuery(struct io_buffer *h Line 2635  static int ReadQuery(struct io_buffer *h
2635          return 0;          return 0;
2636  }  }
2637    
2638  static int WriteAnswer(struct io_buffer *head)  /**
2639     * write_answer - Write the supervisor's decision.
2640     *
2641     * @head: Pointer to "struct ccs_io_buffer".
2642     *
2643     * Returns 0 on success, -EINVAL otherwise.
2644     */
2645    static int write_answer(struct ccs_io_buffer *head)
2646  {  {
2647          char *data = head->write_buf;          char *data = head->write_buf;
2648          struct list_head *tmp;          struct list_head *tmp;
2649          unsigned int serial, answer;          unsigned int serial;
2650            unsigned int answer;
2651            if (!ccs_check_flags(CCS_ALLOW_ENFORCE_GRACE))
2652                    return -EPERM;
2653          /***** CRITICAL SECTION START *****/          /***** CRITICAL SECTION START *****/
2654          spin_lock(&query_lock);          spin_lock(&query_lock);
2655          list_for_each(tmp, &query_list) {          list_for_each(tmp, &query_list) {
2656                  struct query_entry *ptr = list_entry(tmp, struct query_entry, list);                  struct query_entry *ptr
2657                            = list_entry(tmp, struct query_entry, list);
2658                  ptr->timer = 0;                  ptr->timer = 0;
2659          }          }
2660          spin_unlock(&query_lock);          spin_unlock(&query_lock);
2661          /***** CRITICAL SECTION END *****/          /***** CRITICAL SECTION END *****/
2662          if (sscanf(data, "A%u=%u", &serial, &answer) != 2) return -EINVAL;          if (sscanf(data, "A%u=%u", &serial, &answer) != 2)
2663                    return -EINVAL;
2664          /***** CRITICAL SECTION START *****/          /***** CRITICAL SECTION START *****/
2665          spin_lock(&query_lock);          spin_lock(&query_lock);
2666          list_for_each(tmp, &query_list) {          list_for_each(tmp, &query_list) {
2667                  struct query_entry *ptr = list_entry(tmp, struct query_entry, list);                  struct query_entry *ptr
2668                  if (ptr->serial != serial) continue;                          = list_entry(tmp, struct query_entry, list);
2669                  if (!ptr->answer) ptr->answer = answer;                  if (ptr->serial != serial)
2670                            continue;
2671                    if (!ptr->answer)
2672                            ptr->answer = answer;
2673                  break;                  break;
2674          }          }
2675          spin_unlock(&query_lock);          spin_unlock(&query_lock);
# Line 1528  static int WriteAnswer(struct io_buffer Line 2677  static int WriteAnswer(struct io_buffer
2677          return 0;          return 0;
2678  }  }
2679    
 /*************************  /proc INTERFACE HANDLER  *************************/  
   
2680  /* Policy updates counter. */  /* Policy updates counter. */
2681  static unsigned int updates_counter[MAX_CCS_UPDATES_COUNTER];  static unsigned int updates_counter[MAX_CCS_UPDATES_COUNTER];
 static spinlock_t updates_counter_lock = SPIN_LOCK_UNLOCKED;  
2682    
2683  void UpdateCounter(const unsigned char index)  /* Policy updates counter lock. */
2684    static DEFINE_SPINLOCK(updates_counter_lock);
2685