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

Subversion リポジトリの参照

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

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

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