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

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 branches/ccs-patch/fs/ccs_common.c revision 2708 by kumaneko, Tue Jun 30 06:38:14 2009 UTC
# Line 3  Line 3 
3   *   *
4   * Common functions for SAKURA and TOMOYO.   * Common functions for SAKURA and TOMOYO.
5   *   *
6   * Copyright (C) 2005-2008  NTT DATA CORPORATION   * Copyright (C) 2005-2009  NTT DATA CORPORATION
7   *   *
8   * Version: 1.5.3-pre   2008/01/02   * Version: 1.7.0-pre   2009/05/28
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 ccs_lookup_flags = LOOKUP_FOLLOW;
31  #else  #else
32  static const int lookup_flags = LOOKUP_FOLLOW | LOOKUP_POSITIVE;  static const int ccs_lookup_flags = LOOKUP_FOLLOW | LOOKUP_POSITIVE;
33  #endif  #endif
 #include <linux/realpath.h>  
34  #include <linux/ccs_common.h>  #include <linux/ccs_common.h>
35    #include <linux/realpath.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  
 #endif  
 #ifdef CONFIG_TOMOYO_MAX_GRANT_LOG  
 #define MAX_GRANT_LOG (CONFIG_TOMOYO_MAX_GRANT_LOG)  
 #else  
 #define MAX_GRANT_LOG 1024  
40  #endif  #endif
41  #ifdef CONFIG_TOMOYO_MAX_REJECT_LOG  
42  #define MAX_REJECT_LOG (CONFIG_TOMOYO_MAX_REJECT_LOG)  /* To support PID namespace. */
43  #else  #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24)
44  #define MAX_REJECT_LOG 1024  #define find_task_by_pid find_task_by_vpid
45  #endif  #endif
46    
47  /*************************  VARIABLES  *************************/  /* Set default specified by the kernel config. */
48    #define MAX_ACCEPT_ENTRY (CONFIG_CCSECURITY_MAX_ACCEPT_ENTRY)
49    #define MAX_GRANT_LOG    (CONFIG_CCSECURITY_MAX_GRANT_LOG)
50    #define MAX_REJECT_LOG   (CONFIG_CCSECURITY_MAX_REJECT_LOG)
51    
52    DEFINE_MUTEX(ccs_policy_lock);
53    
54  /* /sbin/init started? */  /* Has /sbin/init started? */
55  bool sbin_init_started = 0;  bool ccs_policy_loaded;
56    
57    /* Log level for SAKURA's printk(). */
58  const char *ccs_log_level = KERN_DEBUG;  const char *ccs_log_level = KERN_DEBUG;
59    
60    /* String table for functionality that takes 4 modes. */
61    static const char *ccs_mode_4[4] = {
62            "disabled", "learning", "permissive", "enforcing"
63    };
64    /* String table for functionality that takes 2 modes. */
65    static const char *ccs_mode_2[4] = {
66            "disabled", "enabled", "enabled", "enabled"
67    };
68    
69    /* Table for profile. */
70  static struct {  static struct {
71          const char *keyword;          const char *keyword;
72          unsigned int current_value;          unsigned int current_value;
73          const unsigned int max_value;          const unsigned int max_value;
74  } ccs_control_array[CCS_MAX_CONTROL_INDEX] = {  } ccs_control_array[CCS_MAX_CONTROL_INDEX] = {
75          [CCS_PROFILE_COMMENT]            = { "COMMENT",             0, 0 }, /* Reserved for string. */          [CCS_MAC_FOR_FILE]        = { "MAC_FOR_FILE",        0, 3 },
76          [CCS_TOMOYO_MAC_FOR_FILE]        = { "MAC_FOR_FILE",        0, 3 },          [CCS_MAC_FOR_IOCTL]       = { "MAC_FOR_IOCTL",       0, 3 },
77          [CCS_TOMOYO_MAC_FOR_ARGV0]       = { "MAC_FOR_ARGV0",       0, 3 },          [CCS_MAC_FOR_ARGV0]       = { "MAC_FOR_ARGV0",       0, 3 },
78          [CCS_TOMOYO_MAC_FOR_ENV]         = { "MAC_FOR_ENV",         0, 3 },          [CCS_MAC_FOR_ENV]         = { "MAC_FOR_ENV",         0, 3 },
79          [CCS_TOMOYO_MAC_FOR_NETWORK]     = { "MAC_FOR_NETWORK",     0, 3 },          [CCS_MAC_FOR_NETWORK]     = { "MAC_FOR_NETWORK",     0, 3 },
80          [CCS_TOMOYO_MAC_FOR_SIGNAL]      = { "MAC_FOR_SIGNAL",      0, 3 },          [CCS_MAC_FOR_SIGNAL]      = { "MAC_FOR_SIGNAL",      0, 3 },
81          [CCS_SAKURA_DENY_CONCEAL_MOUNT]  = { "DENY_CONCEAL_MOUNT",  0, 3 },          [CCS_MAC_FOR_NAMESPACE]   = { "MAC_FOR_NAMESPACE",   0, 3 },
82          [CCS_SAKURA_RESTRICT_CHROOT]     = { "RESTRICT_CHROOT",     0, 3 },          [CCS_RESTRICT_AUTOBIND]   = { "RESTRICT_AUTOBIND",   0, 1 },
83          [CCS_SAKURA_RESTRICT_MOUNT]      = { "RESTRICT_MOUNT",      0, 3 },          [CCS_MAX_ACCEPT_ENTRY]
84          [CCS_SAKURA_RESTRICT_UNMOUNT]    = { "RESTRICT_UNMOUNT",    0, 3 },          = { "MAX_ACCEPT_ENTRY",    MAX_ACCEPT_ENTRY, INT_MAX },
85          [CCS_SAKURA_RESTRICT_PIVOT_ROOT] = { "RESTRICT_PIVOT_ROOT", 0, 3 },  #ifdef CONFIG_CCSECURITY_AUDIT
86          [CCS_SAKURA_RESTRICT_AUTOBIND]   = { "RESTRICT_AUTOBIND",   0, 1 },          [CCS_MAX_GRANT_LOG]
87          [CCS_TOMOYO_MAX_ACCEPT_ENTRY]    = { "MAX_ACCEPT_ENTRY",    MAX_ACCEPT_ENTRY, INT_MAX },          = { "MAX_GRANT_LOG",       MAX_GRANT_LOG, INT_MAX },
88          [CCS_TOMOYO_MAX_GRANT_LOG]       = { "MAX_GRANT_LOG",       MAX_GRANT_LOG, INT_MAX },          [CCS_MAX_REJECT_LOG]
89          [CCS_TOMOYO_MAX_REJECT_LOG]      = { "MAX_REJECT_LOG",      MAX_REJECT_LOG, INT_MAX },          = { "MAX_REJECT_LOG",      MAX_REJECT_LOG, INT_MAX },
90          [CCS_TOMOYO_VERBOSE]             = { "TOMOYO_VERBOSE",      1, 1 },  #endif
91          [CCS_ALLOW_ENFORCE_GRACE]        = { "ALLOW_ENFORCE_GRACE", 0, 1 },          [CCS_VERBOSE]             = { "TOMOYO_VERBOSE",      1, 1 },
92          [CCS_SLEEP_PERIOD]               = { "SLEEP_PERIOD",        0, 3000 }, /* in 0.1 second */          [CCS_SLEEP_PERIOD]
93          [CCS_TOMOYO_ALT_EXEC]            = { "ALT_EXEC",            0, 0 }, /* Reserved for string. */          = { "SLEEP_PERIOD",        0, 3000 }, /* in 0.1 second */
94  };  };
95    
96  struct profile {  /* Capability name used by domain policy. */
97          unsigned int value[CCS_MAX_CONTROL_INDEX];  static const char *ccs_capability_control_keyword[CCS_MAX_CAPABILITY_INDEX]
98          const struct path_info *comment;  = {
99          const struct path_info *alt_exec;          [CCS_INET_STREAM_SOCKET_CREATE]  = "inet_tcp_create",
100            [CCS_INET_STREAM_SOCKET_LISTEN]  = "inet_tcp_listen",
101            [CCS_INET_STREAM_SOCKET_CONNECT] = "inet_tcp_connect",
102            [CCS_USE_INET_DGRAM_SOCKET]      = "use_inet_udp",
103            [CCS_USE_INET_RAW_SOCKET]        = "use_inet_ip",
104            [CCS_USE_ROUTE_SOCKET]           = "use_route",
105            [CCS_USE_PACKET_SOCKET]          = "use_packet",
106            [CCS_SYS_MOUNT]                  = "SYS_MOUNT",
107            [CCS_SYS_UMOUNT]                 = "SYS_UMOUNT",
108            [CCS_SYS_REBOOT]                 = "SYS_REBOOT",
109            [CCS_SYS_CHROOT]                 = "SYS_CHROOT",
110            [CCS_SYS_KILL]                   = "SYS_KILL",
111            [CCS_SYS_VHANGUP]                = "SYS_VHANGUP",
112            [CCS_SYS_SETTIME]                = "SYS_TIME",
113            [CCS_SYS_NICE]                   = "SYS_NICE",
114            [CCS_SYS_SETHOSTNAME]            = "SYS_SETHOSTNAME",
115            [CCS_USE_KERNEL_MODULE]          = "use_kernel_module",
116            [CCS_CREATE_FIFO]                = "create_fifo",
117            [CCS_CREATE_BLOCK_DEV]           = "create_block_dev",
118            [CCS_CREATE_CHAR_DEV]            = "create_char_dev",
119            [CCS_CREATE_UNIX_SOCKET]         = "create_unix_socket",
120            [CCS_SYS_LINK]                   = "SYS_LINK",
121            [CCS_SYS_SYMLINK]                = "SYS_SYMLINK",
122            [CCS_SYS_RENAME]                 = "SYS_RENAME",
123            [CCS_SYS_UNLINK]                 = "SYS_UNLINK",
124            [CCS_SYS_CHMOD]                  = "SYS_CHMOD",
125            [CCS_SYS_CHOWN]                  = "SYS_CHOWN",
126            [CCS_SYS_IOCTL]                  = "SYS_IOCTL",
127            [CCS_SYS_KEXEC_LOAD]             = "SYS_KEXEC_LOAD",
128            [CCS_SYS_PIVOT_ROOT]             = "SYS_PIVOT_ROOT",
129            [CCS_SYS_PTRACE]                 = "SYS_PTRACE",
130            [CCS_CONCEAL_MOUNT]              = "conceal_mount",
131  };  };
132    
133  static struct profile *profile_ptr[MAX_PROFILES];  static bool ccs_profile_entry_used[CCS_MAX_CONTROL_INDEX +
134                                       CCS_MAX_CAPABILITY_INDEX + 1];
135    
136    /* Profile table. Memory is allocated as needed. */
137    static struct ccs_profile {
138            unsigned int value[CCS_MAX_CONTROL_INDEX];
139            const struct ccs_path_info *comment;
140            unsigned char capability_value[CCS_MAX_CAPABILITY_INDEX];
141    } *ccs_profile_ptr[MAX_PROFILES];
142    
143  /*************************  UTILITY FUNCTIONS  *************************/  /* Permit policy management by non-root user? */
144    static bool ccs_manage_by_non_root;
145    
146  #ifdef CONFIG_TOMOYO  /* Utility functions. */
147  static int __init TOMOYO_Quiet_Setup(char *str)  
148    /**
149     * ccs_quiet_setup - Set CCS_VERBOSE=0 by default.
150     *
151     * @str: Unused.
152     *
153     * Returns 0.
154     */
155    static int __init ccs_quiet_setup(char *str)
156  {  {
157          ccs_control_array[CCS_TOMOYO_VERBOSE].current_value = 0;          ccs_control_array[CCS_VERBOSE].current_value = 0;
158          return 0;          return 0;
159  }  }
160    
161  __setup("TOMOYO_QUIET", TOMOYO_Quiet_Setup);  __setup("CCS_QUIET", ccs_quiet_setup);
162  #endif  
163    /**
164     * ccs_is_byte_range - Check whether the string isa \ooo style octal value.
165     *
166     * @str: Pointer to the string.
167     *
168     * Returns true if @str is a \ooo style octal value, false otherwise.
169     */
170    static inline bool ccs_is_byte_range(const char *str)
171    {
172            return *str >= '0' && *str++ <= '3' &&
173                    *str >= '0' && *str++ <= '7' &&
174                    *str >= '0' && *str <= '7';
175    }
176    
177    /**
178     * ccs_is_decimal - Check whether the character is a decimal character.
179     *
180     * @c: The character to check.
181     *
182     * Returns true if @c is a decimal character, false otherwise.
183     */
184    static inline bool ccs_is_decimal(const char c)
185    {
186            return c >= '0' && c <= '9';
187    }
188    
189    /**
190     * ccs_is_hexadecimal - Check whether the character is a hexadecimal character.
191     *
192     * @c: The character to check.
193     *
194     * Returns true if @c is a hexadecimal character, false otherwise.
195     */
196    static inline bool ccs_is_hexadecimal(const char c)
197    {
198            return (c >= '0' && c <= '9') ||
199                    (c >= 'A' && c <= 'F') ||
200                    (c >= 'a' && c <= 'f');
201    }
202    
203    /**
204     * ccs_is_alphabet_char - Check whether the character is an alphabet.
205     *
206     * @c: The character to check.
207     *
208     * Returns true if @c is an alphabet character, false otherwise.
209     */
210    static inline bool ccs_is_alphabet_char(const char c)
211    {
212            return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
213    }
214    
215    /**
216     * ccs_make_byte - Make byte value from three octal characters.
217     *
218     * @c1: The first character.
219     * @c2: The second character.
220     * @c3: The third character.
221     *
222     * Returns byte value.
223     */
224    static inline u8 ccs_make_byte(const u8 c1, const u8 c2, const u8 c3)
225    {
226            return ((c1 - '0') << 6) + ((c2 - '0') << 3) + (c3 - '0');
227    }
228    
229  /* Am I root? */  /**
230  static int isRoot(void)   * ccs_str_starts - Check whether the given string starts with the given keyword.
231     *
232     * @src:  Pointer to pointer to the string.
233     * @find: Pointer to the keyword.
234     *
235     * Returns true if @src starts with @find, false otherwise.
236     *
237     * The @src is updated to point the first character after the @find
238     * if @src starts with @find.
239     */
240    static bool ccs_str_starts(char **src, const char *find)
241  {  {
242          return !current->uid && !current->euid;          const int len = strlen(find);
243            char *tmp = *src;
244            if (strncmp(tmp, find, len))
245                    return false;
246            tmp += len;
247            *src = tmp;
248            return true;
249  }  }
250    
251  /*  /**
252   * Format string.   * ccs_normalize_line - Format string.
253     *
254     * @buffer: The line to normalize.
255     *
256   * Leading and trailing whitespaces are removed.   * Leading and trailing whitespaces are removed.
257   * Multiple whitespaces are packed into single space.   * Multiple whitespaces are packed into single space.
258     *
259     * Returns nothing.
260   */   */
261  static void NormalizeLine(unsigned char *buffer)  void ccs_normalize_line(unsigned char *buffer)
262  {  {
263          unsigned char *sp = buffer, *dp = buffer;          unsigned char *sp = buffer;
264          int first = 1;          unsigned char *dp = buffer;
265          while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;          bool first = true;
266            while (*sp && (*sp <= ' ' || *sp >= 127))
267                    sp++;
268          while (*sp) {          while (*sp) {
269                  if (!first) *dp++ = ' ';                  if (!first)
270                  first = 0;                          *dp++ = ' ';
271                  while (*sp > ' ' && *sp < 127) *dp++ = *sp++;                  first = false;
272                  while (*sp && (*sp <= ' ' || *sp >= 127)) sp++;                  while (*sp > ' ' && *sp < 127)
273                            *dp++ = *sp++;
274                    while (*sp && (*sp <= ' ' || *sp >= 127))
275                            sp++;
276          }          }
277          *dp = '\0';          *dp = '\0';
278  }  }
279    
280  /*  /**
281   *  Check whether the given filename follows the naming rules.   * ccs_is_correct_path - Validate a pathname.
282   *  Returns nonzero if follows, zero otherwise.   * @filename:     The pathname to check.
283     * @start_type:   Should the pathname start with '/'?
284     *                1 = must / -1 = must not / 0 = don't care
285     * @pattern_type: Can the pathname contain a wildcard?
286     *                1 = must / -1 = must not / 0 = don't care
287     * @end_type:     Should the pathname end with '/'?
288     *                1 = must / -1 = must not / 0 = don't care
289     *
290     * Check whether the given filename follows the naming rules.
291     * Returns true if @filename follows the naming rules, false otherwise.
292   */   */
293  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,
294                             const s8 pattern_type, const s8 end_type)
295  {  {
296          int contains_pattern = 0;          bool contains_pattern = false;
297          char c, d, e;          unsigned char c;
298            unsigned char d;
299            unsigned char e;
300          const char *original_filename = filename;          const char *original_filename = filename;
301          if (!filename) goto out;          if (!filename)
302                    goto out;
303          c = *filename;          c = *filename;
304          if (start_type == 1) { /* Must start with '/' */          if (start_type == 1) { /* Must start with '/' */
305                  if (c != '/') goto out;                  if (c != '/')
306                            goto out;
307          } else if (start_type == -1) { /* Must not start with '/' */          } else if (start_type == -1) { /* Must not start with '/' */
308                  if (c == '/') goto out;                  if (c == '/')
309                            goto out;
310          }          }
311          if (c) c = * (strchr(filename, '\0') - 1);          if (c)
312                    c = *(filename + strlen(filename) - 1);
313          if (end_type == 1) { /* Must end with '/' */          if (end_type == 1) { /* Must end with '/' */
314                  if (c != '/') goto out;                  if (c != '/')
315                            goto out;
316          } else if (end_type == -1) { /* Must not end with '/' */          } else if (end_type == -1) { /* Must not end with '/' */
317                  if (c == '/') goto out;                  if (c == '/')
318                            goto out;
319          }          }
320          while ((c = *filename++) != '\0') {          while (1) {
321                    c = *filename++;
322                    if (!c)
323                            break;
324                  if (c == '\\') {                  if (c == '\\') {
325                          switch ((c = *filename++)) {                          c = *filename++;
326                            switch (c) {
327                          case '\\':  /* "\\" */                          case '\\':  /* "\\" */
328                                  continue;                                  continue;
329                          case '$':   /* "\$" */                          case '$':   /* "\$" */
# Line 164  bool IsCorrectPath(const char *filename, Line 336  bool IsCorrectPath(const char *filename,
336                          case 'a':   /* "\a" */                          case 'a':   /* "\a" */
337                          case 'A':   /* "\A" */                          case 'A':   /* "\A" */
338                          case '-':   /* "\-" */                          case '-':   /* "\-" */
339                                  if (pattern_type == -1) break; /* Must not contain pattern */                                  if (pattern_type == -1)
340                                  contains_pattern = 1;                                          break; /* Must not contain pattern */
341                                    contains_pattern = true;
342                                  continue;                                  continue;
343                          case '0':   /* "\ooo" */                          case '0':   /* "\ooo" */
344                          case '1':                          case '1':
345                          case '2':                          case '2':
346                          case '3':                          case '3':
347                                  if ((d = *filename++) >= '0' && d <= '7' && (e = *filename++) >= '0' && e <= '7') {                                  d = *filename++;
348                                          const unsigned char f =                                  if (d < '0' || d > '7')
349                                                  (((unsigned char) (c - '0')) << 6) +                                          break;
350                                                  (((unsigned char) (d - '0')) << 3) +                                  e = *filename++;
351                                                  (((unsigned char) (e - '0')));                                  if (e < '0' || e > '7')
352                                          if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                          break;
353                                  }                                  c = ccs_make_byte(c, d, e);
354                                    if (c && (c <= ' ' || c >= 127))
355                                            continue; /* pattern is not \000 */
356                          }                          }
357                          goto out;                          goto out;
358                  } else if (c <= ' ' || c >= 127) {                  } else if (c <= ' ' || c >= 127) {
# Line 185  bool IsCorrectPath(const char *filename, Line 360  bool IsCorrectPath(const char *filename,
360                  }                  }
361          }          }
362          if (pattern_type == 1) { /* Must contain pattern */          if (pattern_type == 1) { /* Must contain pattern */
363                  if (!contains_pattern) goto out;                  if (!contains_pattern)
364                            goto out;
365          }          }
366          return 1;          return true;
367   out:   out:
368          printk(KERN_DEBUG "%s: Invalid pathname '%s'\n", function, original_filename);          printk(KERN_DEBUG "Invalid pathname '%s'\n", original_filename);
369          return 0;          return false;
370  }  }
371    
372  /*  /**
373   *  Check whether the given domainname follows the naming rules.   * ccs_is_correct_domain - Check whether the given domainname follows the naming rules.
374   *  Returns nonzero if follows, zero otherwise.   * @domainname:   The domainname to check.
375     *
376     * Returns true if @domainname follows the naming rules, false otherwise.
377   */   */
378  bool IsCorrectDomain(const unsigned char *domainname, const char *function)  bool ccs_is_correct_domain(const unsigned char *domainname)
379  {  {
380          unsigned char c, d, e;          unsigned char c;
381            unsigned char d;
382            unsigned char e;
383          const char *org_domainname = domainname;          const char *org_domainname = domainname;
384          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN)) goto out;          if (!domainname || strncmp(domainname, ROOT_NAME, ROOT_NAME_LEN))
385                    goto out;
386          domainname += ROOT_NAME_LEN;          domainname += ROOT_NAME_LEN;
387          if (!*domainname) return 1;          if (!*domainname)
388                    return true;
389          do {          do {
390                  if (*domainname++ != ' ') goto out;                  if (*domainname++ != ' ')
391                  if (*domainname++ != '/') goto out;                          goto out;
392                  while ((c = *domainname) != '\0' && c != ' ') {                  if (*domainname++ != '/')
393                            goto out;
394                    while (1) {
395                            c = *domainname;
396                            if (!c || c == ' ')
397                                    break;
398                          domainname++;                          domainname++;
399                          if (c == '\\') {                          if (c == '\\') {
400                                  switch ((c = *domainname++)) {                                  c = *domainname++;
401                                    switch ((c)) {
402                                  case '\\':  /* "\\" */                                  case '\\':  /* "\\" */
403                                          continue;                                          continue;
404                                  case '0':   /* "\ooo" */                                  case '0':   /* "\ooo" */
405                                  case '1':                                  case '1':
406                                  case '2':                                  case '2':
407                                  case '3':                                  case '3':
408                                          if ((d = *domainname++) >= '0' && d <= '7' && (e = *domainname++) >= '0' && e <= '7') {                                          d = *domainname++;
409                                                  const unsigned char f =                                          if (d < '0' || d > '7')
410                                                          (((unsigned char) (c - '0')) << 6) +                                                  break;
411                                                          (((unsigned char) (d - '0')) << 3) +                                          e = *domainname++;
412                                                          (((unsigned char) (e - '0')));                                          if (e < '0' || e > '7')
413                                                  if (f && (f <= ' ' || f >= 127)) continue; /* pattern is not \000 */                                                  break;
414                                          }                                          c = ccs_make_byte(c, d, e);
415                                            if (c && (c <= ' ' || c >= 127))
416                                                    /* pattern is not \000 */
417                                                    continue;
418                                  }                                  }
419                                  goto out;                                  goto out;
420                          } else if (c < ' ' || c >= 127) {                          } else if (c < ' ' || c >= 127) {
# Line 231  bool IsCorrectDomain(const unsigned char Line 422  bool IsCorrectDomain(const unsigned char
422                          }                          }
423                  }                  }
424          } while (*domainname);          } while (*domainname);
425          return 1;          return true;
426   out:   out:
427          printk(KERN_DEBUG "%s: Invalid domainname '%s'\n", function, org_domainname);          printk(KERN_DEBUG "Invalid domainname '%s'\n", org_domainname);
428          return 0;          return false;
429  }  }
430    
431  bool IsDomainDef(const unsigned char *buffer)  /**
432     * ccs_is_domain_def - Check whether the given token can be a domainname.
433     *
434     * @buffer: The token to check.
435     *
436     * Returns true if @buffer possibly be a domainname, false otherwise.
437     */
438    bool ccs_is_domain_def(const unsigned char *buffer)
439  {  {
440          /* while (*buffer && (*buffer <= ' ' || *buffer >= 127)) buffer++; */          return !strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN);
         return strncmp(buffer, ROOT_NAME, ROOT_NAME_LEN) == 0;  
441  }  }
442    
443  struct domain_info *FindDomain(const char *domainname0)  /**
444     * ccs_find_domain - Find a domain by the given name.
445     *
446     * @domainname: The domainname to find.
447     *
448     * Returns pointer to "struct ccs_domain_info" if found, NULL otherwise.
449     *
450     * Caller holds srcu_read_lock(&ccs_ss).
451     */
452    struct ccs_domain_info *ccs_find_domain(const char *domainname)
453  {  {
454          struct domain_info *domain;          struct ccs_domain_info *domain;
455          struct path_info domainname;          struct ccs_path_info name;
456          domainname.name = domainname0;          name.name = domainname;
457          fill_path_info(&domainname);          ccs_fill_path_info(&name);
458          list1_for_each_entry(domain, &domain_list, list) {          list_for_each_entry_rcu(domain, &ccs_domain_list, list) {
459                  if (!domain->is_deleted && !pathcmp(&domainname, domain->domainname)) return domain;                  if (!domain->is_deleted &&
460                        !ccs_pathcmp(&name, domain->domainname))
461                            return domain;
462          }          }
463          return NULL;          return NULL;
464  }  }
465    
466  static int PathDepth(const char *pathname)  /**
467     * ccs_path_depth - Evaluate the number of '/' in a string.
468     *
469     * @pathname: The string to evaluate.
470     *
471     * Returns path depth of the string.
472     *
473     * I score 2 for each of the '/' in the @pathname
474     * and score 1 if the @pathname ends with '/'.
475     */
476    static int ccs_path_depth(const char *pathname)
477  {  {
478          int i = 0;          int i = 0;
479          if (pathname) {          if (pathname) {
480                  char *ep = strchr(pathname, '\0');                  const char *ep = pathname + strlen(pathname);
481                  if (pathname < ep--) {                  if (pathname < ep--) {
482                          if (*ep != '/') i++;                          if (*ep != '/')
483                          while (pathname <= ep) if (*ep-- == '/') i += 2;                                  i++;
484                            while (pathname <= ep)
485                                    if (*ep-- == '/')
486                                            i += 2;
487                  }                  }
488          }          }
489          return i;          return i;
490  }  }
491    
492  static int const_part_length(const char *filename)  /**
493     * ccs_const_part_length - Evaluate the initial length without a pattern in a token.
494     *
495     * @filename: The string to evaluate.
496     *
497     * Returns the initial length without a pattern in @filename.
498     */
499    static int ccs_const_part_length(const char *filename)
500  {  {
501            char c;
502          int len = 0;          int len = 0;
503          if (filename) {          if (!filename)
504                  char c;                  return 0;
505                  while ((c = *filename++) != '\0') {          while (1) {
506                          if (c != '\\') { len++; continue; }                  c = *filename++;
507                          switch (c = *filename++) {                  if (!c)
                         case '\\':  /* "\\" */  
                                 len += 2; continue;  
                         case '0':   /* "\ooo" */  
                         case '1':  
                         case '2':  
                         case '3':  
                                 if ((c = *filename++) >= '0' && c <= '7' && (c = *filename++) >= '0' && c <= '7') { len += 4; continue; }  
                         }  
508                          break;                          break;
509                    if (c != '\\') {
510                            len++;
511                            continue;
512                    }
513                    c = *filename++;
514                    switch (c) {
515                    case '\\':  /* "\\" */
516                            len += 2;
517                            continue;
518                    case '0':   /* "\ooo" */
519                    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 ccs_path_info" members.
538     *
539     * @ptr: Pointer to "struct ccs_path_info" to fill in.
540     *
541     * The caller sets "struct ccs_path_info"->name.
542     */
543    void ccs_fill_path_info(struct ccs_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);
547          ptr->total_len = len;          ptr->total_len = len;
548          ptr->const_len = const_part_length(name);          ptr->const_len = ccs_const_part_length(name);
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 = ccs_path_depth(name);
553  }  }
554    
555  static int FileMatchesToPattern2(const char *filename, const char *filename_end, const char *pattern, const char *pattern_end)  /**
556     * ccs_file_matches_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 ccs_file_matches_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 (ccs_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 (!ccs_is_decimal(c))
603                                  if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) return 0;                                  return false;
604                            break;
605                    case 'x':
606                            if (!ccs_is_hexadecimal(c))
607                                    return false;
608                            break;
609                    case 'a':
610                            if (!ccs_is_alphabet_char(c))
611                                    return false;
612                            break;
613                    case '0':
614                    case '1':
615                    case '2':
616                    case '3':
617                            if (c == '\\' && ccs_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 (ccs_file_matches_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 (ccs_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 (ccs_is_decimal(filename[j]))
650                                            j++;
651                            } else if (c == 'X') {
652                                    while (ccs_is_hexadecimal(filename[j]))
653                                            j++;
654                            } else if (c == 'A') {
655                                    while (ccs_is_alphabet_char(filename[j]))
656                                            j++;
657                            }
658                            for (i = 1; i <= j; i++) {
659                                    if (ccs_file_matches_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     * ccs_file_matches_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 ccs_file_matches_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 = ccs_file_matches_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 = ccs_file_matches_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 ccs_path_info *filename,
734          const char *pathname = pathname0->name, *pattern = pattern0->name;                                const struct ccs_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 = f + strlen(f);
760                    if (!p_delimiter)
761                            p_delimiter = p + strlen(p);
762                    if (!ccs_file_matches_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     *
876     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
877     * @index:  The functionality to check mode.
878     *
879     * Returns the mode of specified functionality.
880     */
881    unsigned int ccs_check_flags(const struct ccs_domain_info *domain,
882                                 const u8 index)
883    {
884            u8 profile;
885            if (!domain)
886                    domain = ccs_current_domain();
887            profile = domain->profile;
888            return ccs_policy_loaded && index < CCS_MAX_CONTROL_INDEX
889    #if MAX_PROFILES != 256
890                    && profile < MAX_PROFILES
891    #endif
892                    && ccs_profile_ptr[profile] ?
893                    ccs_profile_ptr[profile]->value[index] : 0;
894    }
895    
896  /* Check whether the given access control is enabled. */  /**
897  unsigned int CheckCCSFlags(const u8 index)   * ccs_check_capability_flags - Check mode for specified capability.
898     *
899     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
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 ccs_domain_info *domain,
905                                         const u8 index)
906  {  {
907          const u8 profile = current->domain_info->profile;          const u8 profile = domain ? domain->profile :
908          return sbin_init_started && index < CCS_MAX_CONTROL_INDEX                  ccs_current_domain()->profile;
909            return ccs_policy_loaded && index < CCS_MAX_CAPABILITY_INDEX
910  #if MAX_PROFILES != 256  #if MAX_PROFILES != 256
911                  && profile < MAX_PROFILES                  && profile < MAX_PROFILES
912  #endif  #endif
913                  && profile_ptr[profile] ? profile_ptr[profile]->value[index] : 0;                  && ccs_profile_ptr[profile] ?
914                    ccs_profile_ptr[profile]->capability_value[index] : 0;
915    }
916    
917    /**
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 < CCS_MAX_CAPABILITY_INDEX
927                    ? ccs_capability_control_keyword[operation] : NULL;
928  }  }
929    
930  bool TomoyoVerboseMode(void)  /**
931     * ccs_init_request_info - Initialize "struct ccs_request_info" members.
932     *
933     * @r:      Pointer to "struct ccs_request_info" to initialize.
934     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
935     * @index:  Index number of functionality.
936     */
937    void ccs_init_request_info(struct ccs_request_info *r,
938                               struct ccs_domain_info *domain, const u8 index)
939  {  {
940          return CheckCCSFlags(CCS_TOMOYO_VERBOSE) != 0;          memset(r, 0, sizeof(*r));
941            if (!domain)
942                    domain = ccs_current_domain();
943            r->domain = domain;
944            r->profile = domain->profile;
945            if (index < CCS_MAX_CONTROL_INDEX)
946                    r->mode = ccs_check_flags(domain, index);
947            else
948                    r->mode = ccs_check_capability_flags(domain, index
949                                                         - CCS_MAX_CONTROL_INDEX);
950  }  }
951    
952  bool CheckDomainQuota(struct domain_info * const domain)  /**
953     * ccs_verbose_mode - Check whether TOMOYO is verbose mode.
954     *
955     * @domain: Pointer to "struct ccs_domain_info". NULL for ccs_current_domain().
956     *
957     * Returns true if domain policy violation warning should be printed to
958     * console.
959     */
960    bool ccs_verbose_mode(const struct ccs_domain_info *domain)
961    {
962            return ccs_check_flags(domain, CCS_VERBOSE) != 0;
963    }
964    
965    /**
966     * ccs_domain_quota_ok - Check for domain's quota.
967     *
968     * @domain: Pointer to "struct ccs_domain_info".
969     *
970     * Returns true if the domain is not exceeded quota, false otherwise.
971     *
972     * Caller holds srcu_read_lock(&ccs_ss).
973     */
974    bool ccs_domain_quota_ok(struct ccs_domain_info * const domain)
975  {  {
976          unsigned int count = 0;          unsigned int count = 0;
977          struct acl_info *ptr;          struct ccs_acl_info *ptr;
978          if (!domain) return 1;          if (!domain)
979          list1_for_each_entry(ptr, &domain->acl_info_list, list) {                  return true;
980                  if (!ptr->is_deleted) count++;          list_for_each_entry_rcu(ptr, &domain->acl_info_list, list) {
981                    if (ptr->type & ACL_DELETED)
982                            continue;
983                    switch (ccs_acl_type2(ptr)) {
984                            struct ccs_single_path_acl_record *acl1;
985                            struct ccs_double_path_acl_record *acl2;
986                            u16 perm;
987                    case TYPE_SINGLE_PATH_ACL:
988                            acl1 = container_of(ptr,
989                                                struct ccs_single_path_acl_record,
990                                                head);
991                            perm = acl1->perm;
992                            if (perm & (1 << TYPE_EXECUTE_ACL))
993                                    count++;
994                            if (perm &
995                                ((1 << TYPE_READ_ACL) | (1 << TYPE_WRITE_ACL)))
996                                    count++;
997                            if (perm & (1 << TYPE_CREATE_ACL))
998                                    count++;
999                            if (perm & (1 << TYPE_UNLINK_ACL))
1000                                    count++;
1001                            if (perm & (1 << TYPE_MKDIR_ACL))
1002                                    count++;
1003                            if (perm & (1 << TYPE_RMDIR_ACL))
1004                                    count++;
1005                            if (perm & (1 << TYPE_MKFIFO_ACL))
1006                                    count++;
1007                            if (perm & (1 << TYPE_MKSOCK_ACL))
1008                                    count++;
1009                            if (perm & (1 << TYPE_MKBLOCK_ACL))
1010                                    count++;
1011                            if (perm & (1 << TYPE_MKCHAR_ACL))
1012                                    count++;
1013                            if (perm & (1 << TYPE_TRUNCATE_ACL))
1014                                    count++;
1015                            if (perm & (1 << TYPE_SYMLINK_ACL))
1016                                    count++;
1017                            if (perm & (1 << TYPE_REWRITE_ACL))
1018                                    count++;
1019                            break;
1020                    case TYPE_DOUBLE_PATH_ACL:
1021                            acl2 = container_of(ptr,
1022                                                struct ccs_double_path_acl_record,
1023                                                head);
1024                            perm = acl2->perm;
1025                            if (perm & (1 << TYPE_LINK_ACL))
1026                                    count++;
1027                            if (perm & (1 << TYPE_RENAME_ACL))
1028                                    count++;
1029                            break;
1030                    case TYPE_EXECUTE_HANDLER:
1031                    case TYPE_DENIED_EXECUTE_HANDLER:
1032                            break;
1033                    default:
1034                            count++;
1035                    }
1036          }          }
1037          if (count < CheckCCSFlags(CCS_TOMOYO_MAX_ACCEPT_ENTRY)) return 1;          if (count < ccs_check_flags(domain, CCS_MAX_ACCEPT_ENTRY))
1038                    return true;
1039          if (!domain->quota_warned) {          if (!domain->quota_warned) {
1040                  domain->quota_warned = 1;                  domain->quota_warned = true;
1041                  printk("TOMOYO-WARNING: Domain '%s' has so many ACLs to hold. Stopped learning mode.\n", domain->domainname->name);                  printk(KERN_WARNING "TOMOYO-WARNING: "
1042                           "Domain '%s' has so many ACLs to hold. "
1043                           "Stopped learning mode.\n", domain->domainname->name);
1044          }          }
1045          return 0;          return false;
1046  }  }
1047    
1048  static struct profile *FindOrAssignNewProfile(const unsigned int profile)  /**
1049     * ccs_find_or_assign_new_profile - Create a new profile.
1050     *
1051     * @profile: Profile number to create.
1052     *
1053     * Returns pointer to "struct ccs_profile" on success, NULL otherwise.
1054     */
1055    static struct ccs_profile *ccs_find_or_assign_new_profile(const unsigned int
1056                                                              profile)
1057  {  {
1058          static DEFINE_MUTEX(profile_lock);          struct ccs_profile *ptr;
1059          struct profile *ptr = NULL;          struct ccs_profile *entry;
1060          mutex_lock(&profile_lock);          int i;
1061          if (profile < MAX_PROFILES && (ptr = profile_ptr[profile]) == NULL) {          if (profile >= MAX_PROFILES)
1062                  if ((ptr = alloc_element(sizeof(*ptr))) != NULL) {                  return NULL;
1063                          int i;          ptr = ccs_profile_ptr[profile];
1064                          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) ptr->value[i] = ccs_control_array[i].current_value;          if (ptr)
1065                          mb(); /* Avoid out-of-order execution. */                  return ptr;
1066                          profile_ptr[profile] = ptr;          entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1067                  }          mutex_lock(&ccs_policy_lock);
1068            ptr = ccs_profile_ptr[profile];
1069            if (!ptr && ccs_memory_ok(entry)) {
1070                    ptr = entry;
1071                    for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++)
1072                            ptr->value[i] = ccs_control_array[i].current_value;
1073                    /*
1074                     * Needn't to initialize "ptr->capability_value"
1075                     * because they are always 0.
1076                     */
1077                    mb(); /* Avoid out-of-order execution. */
1078                    ccs_profile_ptr[profile] = ptr;
1079                    entry = NULL;
1080          }          }
1081          mutex_unlock(&profile_lock);          mutex_unlock(&ccs_policy_lock);
1082            kfree(entry);
1083          return ptr;          return ptr;
1084  }  }
1085    
1086  /* #define ALT_EXEC */  /**
1087     * ccs_write_profile - Write profile table.
1088  static int SetProfile(struct io_buffer *head)   *
1089     * @head: Pointer to "struct ccs_io_buffer".
1090     *
1091     * Returns 0 on success, negative value otherwise.
1092     */
1093    static int ccs_write_profile(struct ccs_io_buffer *head)
1094  {  {
1095          char *data = head->write_buf;          char *data = head->write_buf;
1096          unsigned int i, value;          unsigned int i;
1097            unsigned int value;
1098          char *cp;          char *cp;
1099          struct profile *profile;          struct ccs_profile *ccs_profile;
         if (!isRoot()) return -EPERM;  
1100          i = simple_strtoul(data, &cp, 10);          i = simple_strtoul(data, &cp, 10);
1101          if (data != cp) {          if (data != cp) {
1102                  if (*cp != '-') return -EINVAL;                  if (*cp != '-')
1103                  data= cp + 1;                          return -EINVAL;
1104                    data = cp + 1;
1105          }          }
1106          profile = FindOrAssignNewProfile(i);          ccs_profile = ccs_find_or_assign_new_profile(i);
1107          if (!profile) return -EINVAL;          if (!ccs_profile)
1108                    return -EINVAL;
1109          cp = strchr(data, '=');          cp = strchr(data, '=');
1110          if (!cp) return -EINVAL;          if (!cp)
1111                    return -EINVAL;
1112          *cp = '\0';          *cp = '\0';
1113          UpdateCounter(CCS_UPDATES_COUNTER_PROFILE);          if (!strcmp(data, "COMMENT")) {
1114          if (strcmp(data, ccs_control_array[CCS_PROFILE_COMMENT].keyword) == 0) {                  ccs_profile->comment = ccs_get_name(cp + 1);
1115                  profile->comment = SaveName(cp + 1);                  ccs_profile_entry_used[0] = true;
1116                  return 0;                  return 0;
1117          }          }
1118  #ifdef ALT_EXEC          if (ccs_str_starts(&data, KEYWORD_MAC_FOR_CAPABILITY)) {
1119  #ifdef CONFIG_TOMOYO                  if (sscanf(cp + 1, "%u", &value) != 1) {
1120          if (strcmp(data, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword) == 0) {                          for (i = 0; i < 4; i++) {
1121                  cp++;                                  if (strcmp(cp + 1, ccs_mode_4[i]))
1122                  if (*cp && !IsCorrectPath(cp, 1, -1, -1, __FUNCTION__)) cp = "";                                          continue;
1123                  profile->alt_exec = SaveName(cp);                                  value = i;
1124                  return 0;                                  break;
1125          }                          }
1126  #endif                          if (i == 4)
1127  #endif                                  return -EINVAL;
1128          if (sscanf(cp + 1, "%u", &value) != 1) return -EINVAL;                  }
1129  #ifdef CONFIG_TOMOYO                  if (value > 3)
1130          if (strncmp(data, KEYWORD_MAC_FOR_CAPABILITY, KEYWORD_MAC_FOR_CAPABILITY_LEN) == 0) {                          value = 3;
1131                  return SetCapabilityStatus(data + KEYWORD_MAC_FOR_CAPABILITY_LEN, value, i);                  for (i = 0; i < CCS_MAX_CAPABILITY_INDEX; i++) {
1132                            if (strcmp(data, ccs_capability_control_keyword[i]))
1133                                    continue;
1134                            ccs_profile->capability_value[i] = value;
1135                            ccs_profile_entry_used[i + 1 + CCS_MAX_CONTROL_INDEX]
1136                                    = true;
1137                            return 0;
1138                    }
1139                    return -EINVAL;
1140          }          }
 #endif  
1141          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) {          for (i = 0; i < CCS_MAX_CONTROL_INDEX; i++) {
1142                  if (strcmp(data, ccs_control_array[i].keyword)) continue;                  if (strcmp(data, ccs_control_array[i].keyword))
1143                  if (value > ccs_control_array[i].max_value) value = ccs_control_array[i].max_value;                          continue;
1144                  profile->value[i] = value;                  if (sscanf(cp + 1, "%u", &value) != 1) {
1145                            int j;
1146                            const char **modes;
1147                            switch (i) {
1148                            case CCS_RESTRICT_AUTOBIND:
1149                            case CCS_VERBOSE:
1150                                    modes = ccs_mode_2;
1151                                    break;
1152                            default:
1153                                    modes = ccs_mode_4;
1154                                    break;
1155                            }
1156                            for (j = 0; j < 4; j++) {
1157                                    if (strcmp(cp + 1, modes[j]))
1158                                            continue;
1159                                    value = j;
1160                                    break;
1161                            }
1162                            if (j == 4)
1163                                    return -EINVAL;
1164                    } else if (value > ccs_control_array[i].max_value) {
1165                            value = ccs_control_array[i].max_value;
1166                    }
1167                    ccs_profile->value[i] = value;
1168                    ccs_profile_entry_used[i + 1] = true;
1169                  return 0;                  return 0;
1170          }          }
1171          return -EINVAL;          return -EINVAL;
1172  }  }
1173    
1174  static int ReadProfile(struct io_buffer *head)  /**
1175     * ccs_read_profile - Read profile table.
1176     *
1177     * @head: Pointer to "struct ccs_io_buffer".
1178     *
1179     * Returns 0.
1180     */
1181    static int ccs_read_profile(struct ccs_io_buffer *head)
1182  {  {
1183          if (!head->read_eof) {          static const int ccs_total
1184                  if (!isRoot()) return -EPERM;                  = CCS_MAX_CONTROL_INDEX + CCS_MAX_CAPABILITY_INDEX + 1;
1185                  if (!head->read_var2) {          int step;
1186                          int step;          if (head->read_eof)
1187                          for (step = head->read_step; step < MAX_PROFILES * CCS_MAX_CONTROL_INDEX; step++) {                  return 0;
1188                                  const int i = step / CCS_MAX_CONTROL_INDEX, j = step % CCS_MAX_CONTROL_INDEX;          for (step = head->read_step; step < MAX_PROFILES * ccs_total; step++) {
1189                                  const struct profile *profile = profile_ptr[i];                  const u8 index = step / ccs_total;
1190                                  head->read_step = step;                  u8 type = step % ccs_total;
1191                                  if (!profile) continue;                  const struct ccs_profile *ccs_profile = ccs_profile_ptr[index];
1192                                  switch (j) {                  head->read_step = step;
1193                                  case -1: /* Dummy */                  if (!ccs_profile)
1194  #ifndef CONFIG_SAKURA                          continue;
1195                                  case CCS_SAKURA_DENY_CONCEAL_MOUNT:                  if (!ccs_profile_entry_used[type])
1196                                  case CCS_SAKURA_RESTRICT_CHROOT:                          continue;
1197                                  case CCS_SAKURA_RESTRICT_MOUNT:                  if (!type) { /* Print profile' comment tag. */
1198                                  case CCS_SAKURA_RESTRICT_UNMOUNT:                          if (!ccs_io_printf(head, "%u-COMMENT=%s\n",
1199                                  case CCS_SAKURA_RESTRICT_PIVOT_ROOT:                                             index, ccs_profile->comment ?
1200                                  case CCS_SAKURA_RESTRICT_AUTOBIND:                                             ccs_profile->comment->name : ""))
1201  #endif                                  break;
1202  #ifndef CONFIG_TOMOYO                          continue;
1203                                  case CCS_TOMOYO_MAC_FOR_FILE:                  }
1204                                  case CCS_TOMOYO_MAC_FOR_ARGV0:                  type--;
1205                                  case CCS_TOMOYO_MAC_FOR_ENV:                  if (type >= CCS_MAX_CONTROL_INDEX) {
1206                                  case CCS_TOMOYO_MAC_FOR_NETWORK:                          const int i = type - CCS_MAX_CONTROL_INDEX;
1207                                  case CCS_TOMOYO_MAC_FOR_SIGNAL:                          const u8 value = ccs_profile->capability_value[i];
1208                                  case CCS_TOMOYO_MAX_ACCEPT_ENTRY:                          if (!ccs_io_printf(head,
1209                                  case CCS_TOMOYO_MAX_GRANT_LOG:                                             "%u-" KEYWORD_MAC_FOR_CAPABILITY
1210                                  case CCS_TOMOYO_MAX_REJECT_LOG:                                             "%s=%s\n", index,
1211                                  case CCS_TOMOYO_VERBOSE:                                             ccs_capability_control_keyword[i],
1212  #endif                                             ccs_mode_4[value]))
1213  #ifndef ALT_EXEC                                  break;
1214                                  case CCS_TOMOYO_ALT_EXEC:                  } else {
1215                                  case CCS_SLEEP_PERIOD:                          const unsigned int value = ccs_profile->value[type];
1216  #endif                          const char **modes = NULL;
1217                                          continue;                          const char *keyword = ccs_control_array[type].keyword;
1218                                  }                          switch (ccs_control_array[type].max_value) {
1219                                  if (j == CCS_PROFILE_COMMENT) {                          case 3:
1220                                          if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_PROFILE_COMMENT].keyword, profile->comment ? profile->comment->name : "")) break;                                  modes = ccs_mode_4;
1221                                  } else if (j == CCS_TOMOYO_ALT_EXEC) {                                  break;
1222                                          const struct path_info *alt_exec = profile->alt_exec;                          case 1:
1223                                          if (io_printf(head, "%u-%s=%s\n", i, ccs_control_array[CCS_TOMOYO_ALT_EXEC].keyword, alt_exec ? alt_exec->name : "")) break;                                  modes = ccs_mode_2;
1224                                  } else {                                  break;
                                         if (io_printf(head, "%u-%s=%u\n", i, ccs_control_array[j].keyword, profile->value[j])) break;  
                                 }  
1225                          }                          }
1226                          if (step == MAX_PROFILES * CCS_MAX_CONTROL_INDEX) {                          if (modes) {
1227                                  head->read_var2 = (void *) "";                                  if (!ccs_io_printf(head, "%u-%s=%s\n", index,
1228                                  head->read_step = 0;                                                     keyword, modes[value]))
1229                                            break;
1230                            } else {
1231                                    if (!ccs_io_printf(head, "%u-%s=%u\n", index,
1232                                                       keyword, value))
1233                                            break;
1234                          }                          }
1235                  }                  }
                 if (head->read_var2) {  
 #ifdef CONFIG_TOMOYO  
                         if (ReadCapabilityStatus(head) == 0)  
 #endif  
                                 head->read_eof = 1;  
                 }  
1236          }          }
1237            if (step == MAX_PROFILES * ccs_total)
1238                    head->read_eof = true;
1239          return 0;          return 0;
1240  }  }
1241    
1242  /*************************  POLICY MANAGER HANDLER  *************************/  /* The list for "struct ccs_policy_manager_entry". */
1243    LIST_HEAD(ccs_policy_manager_list);
 struct policy_manager_entry {  
         struct list1_head list;  
         const struct path_info *manager;  
         bool is_domain;  
         bool is_deleted;  
 };  
1244    
1245  static LIST1_HEAD(policy_manager_list);  /**
1246     * ccs_update_manager_entry - Add a manager entry.
1247  static int AddManagerEntry(const char *manager, const bool is_delete)   *
1248     * @manager:   The path to manager or the domainnamme.
1249     * @is_delete: True if it is a delete request.
1250     *
1251     * Returns 0 on success, negative value otherwise.
1252     */
1253    static int ccs_update_manager_entry(const char *manager, const bool is_delete)
1254  {  {
1255          struct policy_manager_entry *new_entry, *ptr;          struct ccs_policy_manager_entry *entry = NULL;
1256          static DEFINE_MUTEX(lock);          struct ccs_policy_manager_entry *ptr;
1257          const struct path_info *saved_manager;          const struct ccs_path_info *saved_manager;
1258          int error = -ENOMEM;          int error = is_delete ? -ENOENT : -ENOMEM;
1259          bool is_domain = 0;          bool is_domain = false;
1260          if (!isRoot()) return -EPERM;          if (ccs_is_domain_def(manager)) {
1261          if (IsDomainDef(manager)) {                  if (!ccs_is_correct_domain(manager))
1262                  if (!IsCorrectDomain(manager, __FUNCTION__)) return -EINVAL;                          return -EINVAL;
1263                  is_domain = 1;                  is_domain = true;
1264          } else {          } else {
1265                  if (!IsCorrectPath(manager, 1, -1, -1, __FUNCTION__)) return -EINVAL;                  if (!ccs_is_correct_path(manager, 1, -1, -1))
1266                            return -EINVAL;
1267          }          }
1268          if ((saved_manager = SaveName(manager)) == NULL) return -ENOMEM;          saved_manager = ccs_get_name(manager);
1269          mutex_lock(&lock);          if (!saved_manager)
1270          list1_for_each_entry(ptr, &policy_manager_list, list) {                  return -ENOMEM;
1271                  if (ptr->manager == saved_manager) {          if (!is_delete)
1272                          ptr->is_deleted = is_delete;                  entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1273                          error = 0;          mutex_lock(&ccs_policy_lock);
1274                          goto out;          list_for_each_entry_rcu(ptr, &ccs_policy_manager_list, list) {
1275                  }                  if (ptr->manager != saved_manager)
1276                            continue;
1277                    ptr->is_deleted = is_delete;
1278                    error = 0;
1279                    break;
1280          }          }
1281          if (is_delete) {          if (!is_delete && error && ccs_memory_ok(entry)) {
1282                  error = -ENOENT;                  entry->manager = saved_manager;
1283                  goto out;                  saved_manager = NULL;
1284                    entry->is_domain = is_domain;
1285                    list_add_tail_rcu(&entry->list, &ccs_policy_manager_list);
1286                    entry = NULL;
1287                    error = 0;
1288          }          }
1289          if ((new_entry = alloc_element(sizeof(*new_entry))) == NULL) goto out;          mutex_unlock(&ccs_policy_lock);
1290          new_entry->manager = saved_manager;          ccs_put_name(saved_manager);
1291          new_entry->is_domain = is_domain;          kfree(entry);
         list1_add_tail_mb(&new_entry->list, &policy_manager_list);  
         error = 0;  
  out:  
         mutex_unlock(&lock);  
         if (!error) UpdateCounter(CCS_UPDATES_COUNTER_MANAGER);  
1292          return error;          return error;
1293  }  }
1294    
1295  static int AddManagerPolicy(struct io_buffer *head)  /**
1296     * ccs_write_manager_policy - Write manager policy.
1297     *
1298     * @head: Pointer to "struct ccs_io_buffer".
1299     *
1300     * Returns 0 on success, negative value otherwise.
1301     */
1302    static int ccs_write_manager_policy(struct ccs_io_buffer *head)
1303    {
1304            char *data = head->write_buf;
1305            bool is_delete = ccs_str_starts(&data, KEYWORD_DELETE);
1306            if (!strcmp(data, "manage_by_non_root")) {
1307                    ccs_manage_by_non_root = !is_delete;
1308                    return 0;
1309            }
1310            return ccs_update_manager_entry(data, is_delete);
1311    }
1312    
1313    /**
1314     * ccs_read_manager_policy - Read manager policy.
1315     *
1316     * @head: Pointer to "struct ccs_io_buffer".
1317     *
1318     * Returns 0.
1319     *
1320     * Caller holds srcu_read_lock(&ccs_ss).
1321     */
1322    static int ccs_read_manager_policy(struct ccs_io_buffer *head)
1323  {  {
1324          const char *data = head->write_buf;          struct list_head *pos;
1325          bool is_delete = 0;          if (head->read_eof)
1326          if (!isRoot()) return -EPERM;                  return 0;
1327          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {          list_for_each_cookie(pos, head->read_var2, &ccs_policy_manager_list) {
1328                  data += KEYWORD_DELETE_LEN;                  struct ccs_policy_manager_entry *ptr;
1329                  is_delete = 1;                  ptr = list_entry(pos, struct ccs_policy_manager_entry, list);
1330          }                  if (ptr->is_deleted)
1331          return AddManagerEntry(data, is_delete);                          continue;
1332  }                  if (!ccs_io_printf(head, "%s\n", ptr->manager->name))
1333                            return 0;
 static int ReadManagerPolicy(struct io_buffer *head)  
 {  
         struct list1_head *pos;  
         if (head->read_eof) return 0;  
         if (!isRoot()) return -EPERM;  
         list1_for_each_cookie(pos, head->read_var2, &policy_manager_list) {  
                 struct policy_manager_entry *ptr;  
                 ptr = list1_entry(pos, struct policy_manager_entry, list);  
                 if (ptr->is_deleted) continue;  
                 if (io_printf(head, "%s\n", ptr->manager->name)) return 0;  
1334          }          }
1335          head->read_eof = 1;          head->read_eof = true;
1336          return 0;          return 0;
1337  }  }
1338    
1339  /* Check whether the current process is a policy manager. */  /**
1340  static int IsPolicyManager(void)   * ccs_is_policy_manager - Check whether the current process is a policy manager.
1341     *
1342     * Returns true if the current process is permitted to modify policy
1343     * via /proc/ccs/ interface.
1344     *
1345     * Caller holds srcu_read_lock(&ccs_ss).
1346     */
1347    static bool ccs_is_policy_manager(void)
1348  {  {
1349          struct policy_manager_entry *ptr;          struct ccs_policy_manager_entry *ptr;
1350          const char *exe;          const char *exe;
1351          const struct path_info *domainname = current->domain_info->domainname;          struct task_struct *task = current;
1352          bool found = 0;          const struct ccs_path_info *domainname
1353          if (!sbin_init_started) return 1;                  = ccs_current_domain()->domainname;
1354          list1_for_each_entry(ptr, &policy_manager_list, list) {          bool found = false;
1355                  if (!ptr->is_deleted && ptr->is_domain && !pathcmp(domainname, ptr->manager)) return 1;          if (!ccs_policy_loaded)
1356          }                  return true;
1357          if ((exe = GetEXE()) == NULL) return 0;          if (task->ccs_flags & CCS_TASK_IS_POLICY_MANAGER)
1358          list1_for_each_entry(ptr, &policy_manager_list, list) {                  return true;
1359                  if (!ptr->is_deleted && !ptr->is_domain && !strcmp(exe, ptr->manager->name)) {          if (!ccs_manage_by_non_root && (current_uid() || current_euid()))
1360                          found = 1;                  return false;
1361            list_for_each_entry_rcu(ptr, &ccs_policy_manager_list, list) {
1362                    if (!ptr->is_deleted && ptr->is_domain
1363                        && !ccs_pathcmp(domainname, ptr->manager)) {
1364                            /* Set manager flag. */
1365                            task->ccs_flags |= CCS_TASK_IS_POLICY_MANAGER;
1366                            return true;
1367                    }
1368            }
1369            exe = ccs_get_exe();
1370            if (!exe)
1371                    return false;
1372            list_for_each_entry_rcu(ptr, &ccs_policy_manager_list, list) {
1373                    if (!ptr->is_deleted && !ptr->is_domain
1374                        && !strcmp(exe, ptr->manager->name)) {
1375                            found = true;
1376                            /* Set manager flag. */
1377                            task->ccs_flags |= CCS_TASK_IS_POLICY_MANAGER;
1378                          break;                          break;
1379                  }                  }
1380          }          }
1381          if (!found) { /* Reduce error messages. */          if (!found) { /* Reduce error messages. */
1382                  static pid_t last_pid = 0;                  static pid_t ccs_last_pid;
1383                  const pid_t pid = current->pid;                  const pid_t pid = current->pid;
1384                  if (last_pid != pid) {                  if (ccs_last_pid != pid) {
1385                          printk("%s ( %s ) is not permitted to update policies.\n", domainname->name, exe);                          printk(KERN_WARNING "%s ( %s ) is not permitted to "
1386                          last_pid = pid;                                 "update policies.\n", domainname->name, exe);
1387                            ccs_last_pid = pid;
1388                  }                  }
1389          }          }
1390          ccs_free(exe);          ccs_free(exe);
1391          return found;          return found;
1392  }  }
1393    
1394  #ifdef CONFIG_TOMOYO  /**
1395     * ccs_find_condition_part - Find condition part from the statement.
1396  /*************************  DOMAIN POLICY HANDLER  *************************/   *
1397     * @data: String to parse.
1398  static char *FindConditionPart(char *data)   *
1399     * Returns pointer to the condition part if it was found in the statement,
1400     * NULL otherwise.
1401     */
1402    static char *ccs_find_condition_part(char *data)
1403  {  {
1404          char *cp = strstr(data, " if "), *cp2;          char *cp = strstr(data, " if ");
1405          if (cp) {          if (cp) {
1406                  while ((cp2 = strstr(cp + 3, " if ")) != NULL) cp = cp2;                  while (1) {
1407                            char *cp2 = strstr(cp + 3, " if ");
1408                            if (!cp2)
1409                                    break;
1410                            cp = cp2;
1411                    }
1412                  *cp++ = '\0';                  *cp++ = '\0';
1413            } else {
1414                    cp = strstr(data, " ; set ");
1415                    if (cp)
1416                            *cp++ = '\0';
1417          }          }
1418          return cp;          return cp;
1419  }  }
1420    
1421  static int AddDomainPolicy(struct io_buffer *head)  /**
1422     * ccs_is_select_one - Parse select command.
1423     *
1424     * @head: Pointer to "struct ccs_io_buffer".
1425     * @data: String to parse.
1426     *
1427     * Returns true on success, false otherwise.
1428     *
1429     * Caller holds srcu_read_lock(&ccs_ss).
1430     */
1431    static bool ccs_is_select_one(struct ccs_io_buffer *head, const char *data)
1432    {
1433            unsigned int pid;
1434            struct ccs_domain_info *domain = NULL;
1435            if (!strcmp(data, "allow_execute")) {
1436                    head->read_execute_only = true;
1437                    return true;
1438            }
1439            if (sscanf(data, "pid=%u", &pid) == 1) {
1440                    struct task_struct *p;
1441                    /***** CRITICAL SECTION START *****/
1442                    read_lock(&tasklist_lock);
1443                    p = find_task_by_pid(pid);
1444                    if (p)
1445                            domain = ccs_task_domain(p);
1446                    read_unlock(&tasklist_lock);
1447                    /***** CRITICAL SECTION END *****/
1448            } else if (!strncmp(data, "domain=", 7)) {
1449                    if (ccs_is_domain_def(data + 7))
1450                            domain = ccs_find_domain(data + 7);
1451            } else
1452                    return false;
1453            head->write_var1 = domain;
1454            /* Accessing read_buf is safe because head->io_sem is held. */
1455            if (!head->read_buf)
1456                    return true; /* Do nothing if open(O_WRONLY). */
1457            head->read_avail = 0;
1458            ccs_io_printf(head, "# select %s\n", data);
1459            head->read_single_domain = true;
1460            head->read_eof = !domain;
1461            if (domain) {
1462                    struct ccs_domain_info *d;
1463                    head->read_var1 = NULL;
1464                    list_for_each_entry_rcu(d, &ccs_domain_list, list) {
1465                            if (d == domain)
1466                                    break;
1467                            head->read_var1 = &d->list;
1468                    }
1469                    head->read_var2 = NULL;
1470                    head->read_bit = 0;
1471                    head->read_step = 0;
1472                    if (domain->is_deleted)
1473                            ccs_io_printf(head, "# This is a deleted domain.\n");
1474            }
1475            return true;
1476    }
1477    
1478    /**
1479     * ccs_write_domain_policy - Write domain policy.
1480     *
1481     * @head: Pointer to "struct ccs_io_buffer".
1482     *
1483     * Returns 0 on success, negative value otherwise.
1484     */
1485    static int ccs_write_domain_policy(struct ccs_io_buffer *head)
1486  {  {
1487          char *data = head->write_buf;          char *data = head->write_buf;
1488          struct domain_info *domain = head->write_var1;          struct ccs_domain_info *domain = head->write_var1;
1489          bool is_delete = 0, is_select = 0, is_undelete = 0;          bool is_delete = false;
1490            bool is_select = false;
1491          unsigned int profile;          unsigned int profile;
1492          const struct condition_list *cond = NULL;          struct ccs_condition *cond = NULL;
1493          char *cp;                char *cp;
1494          if (!isRoot()) return -EPERM;          int error;
1495          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_DELETE))
1496                  data += KEYWORD_DELETE_LEN;                  is_delete = true;
1497                  is_delete = 1;          else if (ccs_str_starts(&data, KEYWORD_SELECT))
1498          } else if (strncmp(data, KEYWORD_SELECT, KEYWORD_SELECT_LEN) == 0) {                  is_select = true;
1499                  data += KEYWORD_SELECT_LEN;          if (is_select && ccs_is_select_one(head, data))
1500                  is_select = 1;                  return 0;
1501          } else if (strncmp(data, KEYWORD_UNDELETE, KEYWORD_UNDELETE_LEN) == 0) {          /* Don't allow updating policies by non manager programs. */
1502                  data += KEYWORD_UNDELETE_LEN;          if (!ccs_is_policy_manager())
1503                  is_undelete = 1;                  return -EPERM;
1504          }          if (ccs_is_domain_def(data)) {
1505          UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);                  domain = NULL;
1506          if (IsDomainDef(data)) {                  if (is_delete)
1507                  if (is_delete) {                          ccs_delete_domain(data);
1508                          DeleteDomain(data);                  else if (is_select)
1509                          domain = NULL;                          domain = ccs_find_domain(data);
1510                  } else if (is_select) {                  else
1511                          domain = FindDomain(data);                          domain = ccs_find_or_assign_new_domain(data, 0);
                 } else if (is_undelete) {  
                         domain = UndeleteDomain(data);  
                 } else {  
                         domain = FindOrAssignNewDomain(data, 0);  
                 }  
1512                  head->write_var1 = domain;                  head->write_var1 = domain;
1513                  return 0;                  return 0;
1514          }          }
1515          if (!domain) return -EINVAL;          if (!domain)
1516                    return -EINVAL;
1517    
1518          if (sscanf(data, KEYWORD_USE_PROFILE "%u", &profile) == 1 && profile < MAX_PROFILES) {          if (sscanf(data, KEYWORD_USE_PROFILE "%u", &profile) == 1
1519                  if (profile_ptr[profile] || !sbin_init_started) domain->profile = (u8) profile;              && profile < MAX_PROFILES) {
1520                    if (ccs_profile_ptr[profile] || !ccs_policy_loaded)
1521                            domain->profile = (u8) profile;
1522                  return 0;                  return 0;
1523          }          }
1524          cp = FindConditionPart(data);          if (!strcmp(data, KEYWORD_IGNORE_GLOBAL_ALLOW_READ)) {
1525          if (cp && (cond = FindOrAssignNewCondition(cp)) == NULL) return -EINVAL;                  domain->ignore_global_allow_read = !is_delete;
1526          if (strncmp(data, KEYWORD_ALLOW_CAPABILITY, KEYWORD_ALLOW_CAPABILITY_LEN) == 0) {                  return 0;
1527                  return AddCapabilityPolicy(data + KEYWORD_ALLOW_CAPABILITY_LEN, domain, cond, is_delete);          }
1528          } else if (strncmp(data, KEYWORD_ALLOW_NETWORK, KEYWORD_ALLOW_NETWORK_LEN) == 0) {          if (!strcmp(data, KEYWORD_IGNORE_GLOBAL_ALLOW_ENV)) {
1529                  return AddNetworkPolicy(data + KEYWORD_ALLOW_NETWORK_LEN, domain, cond, is_delete);                  domain->ignore_global_allow_env = !is_delete;
1530          } else if (strncmp(data, KEYWORD_ALLOW_SIGNAL, KEYWORD_ALLOW_SIGNAL_LEN) == 0) {                  return 0;
1531                  return AddSignalPolicy(data + KEYWORD_ALLOW_SIGNAL_LEN, domain, cond, is_delete);          }
1532          } else if (strncmp(data, KEYWORD_ALLOW_ARGV0, KEYWORD_ALLOW_ARGV0_LEN) == 0) {          cp = ccs_find_condition_part(data);
1533                  return AddArgv0Policy(data + KEYWORD_ALLOW_ARGV0_LEN, domain, cond, is_delete);          if (cp) {
1534          } else if (strncmp(data, KEYWORD_ALLOW_ENV, KEYWORD_ALLOW_ENV_LEN) == 0) {                  cond = ccs_get_condition(cp);
1535                  return AddEnvPolicy(data + KEYWORD_ALLOW_ENV_LEN, domain, cond, is_delete);                  if (!cond)
1536                            return -EINVAL;
1537            }
1538            if (ccs_str_starts(&data, KEYWORD_ALLOW_CAPABILITY))
1539                    error = ccs_write_capability_policy(data, domain, cond,
1540                                                        is_delete);
1541            else if (ccs_str_starts(&data, KEYWORD_ALLOW_NETWORK))
1542                    error = ccs_write_network_policy(data, domain, cond, is_delete);
1543            else if (ccs_str_starts(&data, KEYWORD_ALLOW_SIGNAL))
1544                    error = ccs_write_signal_policy(data, domain, cond, is_delete);
1545            else if (ccs_str_starts(&data, KEYWORD_ALLOW_ARGV0))
1546                    error = ccs_write_argv0_policy(data, domain, cond, is_delete);
1547            else if (ccs_str_starts(&data, KEYWORD_ALLOW_ENV))
1548                    error = ccs_write_env_policy(data, domain, cond, is_delete);
1549            else if (ccs_str_starts(&data, KEYWORD_ALLOW_IOCTL))
1550                    error = ccs_write_ioctl_policy(data, domain, cond, is_delete);
1551            else if (ccs_str_starts(&data, KEYWORD_ALLOW_MOUNT))
1552                    error = ccs_write_mount_policy(data, domain, cond, is_delete);
1553            else if (ccs_str_starts(&data, KEYWORD_ALLOW_UNMOUNT))
1554                    error = ccs_write_umount_policy(data, domain, cond, is_delete);
1555            else if (ccs_str_starts(&data, KEYWORD_ALLOW_CHROOT))
1556                    error = ccs_write_chroot_policy(data, domain, cond, is_delete);
1557            else if (ccs_str_starts(&data, KEYWORD_ALLOW_PIVOT_ROOT))
1558                    error = ccs_write_pivot_root_policy(data, domain, cond,
1559                                                        is_delete);
1560            else
1561                    error = ccs_write_file_policy(data, domain, cond, is_delete);
1562            if (cond)
1563                    ccs_put_condition(cond);
1564            return error;
1565    }
1566    
1567    /**
1568     * ccs_print_single_path_acl - Print a single path ACL entry.
1569     *
1570     * @head: Pointer to "struct ccs_io_buffer".
1571     * @ptr:  Pointer to "struct ccs_single_path_acl_record".
1572     * @cond: Pointer to "struct ccs_condition". May be NULL.
1573     *
1574     * Returns true on success, false otherwise.
1575     */
1576    static bool ccs_print_single_path_acl(struct ccs_io_buffer *head,
1577                                          struct ccs_single_path_acl_record *ptr,
1578                                          const struct ccs_condition *cond)
1579    {
1580            int pos;
1581            u8 bit;
1582            const char *atmark = "";
1583            const char *filename;
1584            const u16 perm = ptr->perm;
1585            if (ptr->u_is_group) {
1586                    atmark = "@";
1587                    filename = ptr->u.group->group_name->name;
1588          } else {          } else {
1589                  return AddFilePolicy(data, domain, cond, is_delete);                  filename = ptr->u.filename->name;
1590          }          }
1591          return -EINVAL;          for (bit = head->read_bit; bit < MAX_SINGLE_PATH_OPERATION; bit++) {
1592                    const char *msg;
1593                    if (!(perm & (1 << bit)))
1594                            continue;
1595                    if (head->read_execute_only && bit != TYPE_EXECUTE_ACL)
1596                            continue;
1597                    /* Print "read/write" instead of "read" and "write". */
1598                    if ((bit == TYPE_READ_ACL || bit == TYPE_WRITE_ACL)
1599                        && (perm & (1 << TYPE_READ_WRITE_ACL)))
1600                            continue;
1601                    msg = ccs_sp2keyword(bit);
1602                    pos = head->read_avail;
1603                    if (!ccs_io_printf(head, "allow_%s %s%s", msg,
1604                                       atmark, filename) ||
1605                        !ccs_print_condition(head, cond))
1606                            goto out;
1607            }
1608            head->read_bit = 0;
1609            return true;
1610     out:
1611            head->read_bit = bit;
1612            head->read_avail = pos;
1613            return false;
1614  }  }
1615    
1616  static int ReadDomainPolicy(struct io_buffer *head)  /**
1617     * ccs_print_double_path_acl - Print a double path ACL entry.
1618     *
1619     * @head: Pointer to "struct ccs_io_buffer".
1620     * @ptr:  Pointer to "struct ccs_double_path_acl_record".
1621     * @cond: Pointer to "struct ccs_condition". May be NULL.
1622     *
1623     * Returns true on success, false otherwise.
1624     */
1625    static bool ccs_print_double_path_acl(struct ccs_io_buffer *head,
1626                                          struct ccs_double_path_acl_record *ptr,
1627                                          const struct ccs_condition *cond)
1628    {
1629            int pos;
1630            const char *atmark1 = "";
1631            const char *atmark2 = "";
1632            const char *filename1;
1633            const char *filename2;
1634            const u8 perm = ptr->perm;
1635            u8 bit;
1636            if (ptr->u1_is_group) {
1637                    atmark1 = "@";
1638                    filename1 = ptr->u1.group1->group_name->name;
1639            } else {
1640                    filename1 = ptr->u1.filename1->name;
1641            }
1642            if (ptr->u2_is_group) {
1643                    atmark2 = "@";
1644                    filename2 = ptr->u2.group2->group_name->name;
1645            } else {
1646                    filename2 = ptr->u2.filename2->name;
1647            }
1648            for (bit = head->read_bit; bit < MAX_DOUBLE_PATH_OPERATION; bit++) {
1649                    const char *msg;
1650                    if (!(perm & (1 << bit)))
1651                            continue;
1652                    msg = ccs_dp2keyword(bit);
1653                    pos = head->read_avail;
1654                    if (!ccs_io_printf(head, "allow_%s %s%s %s%s", msg,
1655                                       atmark1, filename1, atmark2, filename2) ||
1656                        !ccs_print_condition(head, cond))
1657                            goto out;
1658            }
1659            head->read_bit = 0;
1660            return true;
1661     out:
1662            head->read_bit = bit;
1663            head->read_avail = pos;
1664            return false;
1665    }
1666    
1667    /**
1668     * ccs_print_ioctl_acl - Print an ioctl ACL entry.
1669     *
1670     * @head: Pointer to "struct ccs_io_buffer".
1671     * @ptr:  Pointer to "struct ccs_ioctl_acl_record".
1672     * @cond: Pointer to "struct ccs_condition". May be NULL.
1673     *
1674     * Returns true on success, false otherwise.
1675     */
1676    static bool ccs_print_ioctl_acl(struct ccs_io_buffer *head,
1677                                    struct ccs_ioctl_acl_record *ptr,
1678                                    const struct ccs_condition *cond)
1679    {
1680            int pos = head->read_avail;
1681            const char *atmark = "";
1682            const char *filename;
1683            const unsigned int cmd_min = ptr->cmd_min;
1684            const unsigned int cmd_max = ptr->cmd_max;
1685            if (ptr->u_is_group) {
1686                    atmark = "@";
1687                    filename = ptr->u.group->group_name->name;
1688            } else {
1689                    filename = ptr->u.filename->name;
1690            }
1691            if (!ccs_io_printf(head, KEYWORD_ALLOW_IOCTL "%s%s ", atmark, filename))
1692                    goto out;
1693            if (!ccs_io_printf(head, "%u", cmd_min))
1694                    goto out;
1695            if (cmd_min != cmd_max && !ccs_io_printf(head, "-%u", cmd_max))
1696                    goto out;
1697            if (!ccs_print_condition(head, cond))
1698                    goto out;
1699            return true;
1700     out:
1701            head->read_avail = pos;
1702            return false;
1703    }
1704    
1705    /**
1706     * ccs_print_argv0_acl - Print an argv[0] ACL entry.
1707     *
1708     * @head: Pointer to "struct ccs_io_buffer".
1709     * @ptr:  Pointer to "struct ccs_argv0_acl_record".
1710     * @cond: Pointer to "struct ccs_condition". May be NULL.
1711     *
1712     * Returns true on success, false otherwise.
1713     */
1714    static bool ccs_print_argv0_acl(struct ccs_io_buffer *head,
1715                                    struct ccs_argv0_acl_record *ptr,
1716                                    const struct ccs_condition *cond)
1717    {
1718            int pos = head->read_avail;
1719            if (!ccs_io_printf(head, KEYWORD_ALLOW_ARGV0 "%s %s",
1720                               ptr->filename->name, ptr->argv0->name))
1721                    goto out;
1722            if (!ccs_print_condition(head, cond))
1723                    goto out;
1724            return true;
1725     out:
1726            head->read_avail = pos;
1727            return false;
1728    }
1729    
1730    /**
1731     * ccs_print_env_acl - Print an evironment variable name's ACL entry.
1732     *
1733     * @head: Pointer to "struct ccs_io_buffer".
1734     * @ptr:  Pointer to "struct ccs_env_acl_record".
1735     * @cond: Pointer to "struct ccs_condition". May be NULL.
1736     *
1737     * Returns true on success, false otherwise.
1738     */
1739    static bool ccs_print_env_acl(struct ccs_io_buffer *head,
1740                                  struct ccs_env_acl_record *ptr,
1741                                  const struct ccs_condition *cond)
1742  {  {
1743          struct list1_head *dpos;          int pos = head->read_avail;
1744          struct list1_head *apos;          if (!ccs_io_printf(head, KEYWORD_ALLOW_ENV "%s", ptr->env->name))
1745          if (head->read_eof) return 0;                  goto out;
1746          if (head->read_step == 0) {          if (!ccs_print_condition(head, cond))
1747                  if (!isRoot()) return -EPERM;                  goto out;
1748                  head->read_step = 1;          return true;
1749     out:
1750            head->read_avail = pos;
1751            return false;
1752    }
1753    
1754    /**
1755     * ccs_print_capability_acl - Print a capability ACL entry.
1756     *
1757     * @head: Pointer to "struct ccs_io_buffer".
1758     * @ptr:  Pointer to "struct ccs_capability_acl_record".
1759     * @cond: Pointer to "struct ccs_condition". May be NULL.
1760     *
1761     * Returns true on success, false otherwise.
1762     */
1763    static bool ccs_print_capability_acl(struct ccs_io_buffer *head,
1764                                         struct ccs_capability_acl_record *ptr,
1765                                         const struct ccs_condition *cond)
1766    {
1767            int pos = head->read_avail;
1768            if (!ccs_io_printf(head, KEYWORD_ALLOW_CAPABILITY "%s",
1769                               ccs_cap2keyword(ptr->operation)))
1770                    goto out;
1771            if (!ccs_print_condition(head, cond))
1772                    goto out;
1773            return true;
1774     out:
1775            head->read_avail = pos;
1776            return false;
1777    }
1778    
1779    /**
1780     * ccs_print_ipv4_entry - Print IPv4 address of a network ACL entry.
1781     *
1782     * @head: Pointer to "struct ccs_io_buffer".
1783     * @ptr:  Pointer to "struct ccs_ip_network_acl_record".
1784     *
1785     * Returns true on success, false otherwise.
1786     */
1787    static bool ccs_print_ipv4_entry(struct ccs_io_buffer *head,
1788                                     struct ccs_ip_network_acl_record *ptr)
1789    {
1790            const u32 min_address = ptr->u.ipv4.min;
1791            const u32 max_address = ptr->u.ipv4.max;
1792            if (!ccs_io_printf(head, "%u.%u.%u.%u", HIPQUAD(min_address)))
1793                    return false;
1794            if (min_address != max_address
1795                && !ccs_io_printf(head, "-%u.%u.%u.%u", HIPQUAD(max_address)))
1796                    return false;
1797            return true;
1798    }
1799    
1800    /**
1801     * ccs_print_ipv6_entry - Print IPv6 address of a network ACL entry.
1802     *
1803     * @head: Pointer to "struct ccs_io_buffer".
1804     * @ptr:  Pointer to "struct ccs_ip_network_acl_record".
1805     *
1806     * Returns true on success, false otherwise.
1807     */
1808    static bool ccs_print_ipv6_entry(struct ccs_io_buffer *head,
1809                                     struct ccs_ip_network_acl_record *ptr)
1810    {
1811            char buf[64];
1812            const struct in6_addr *min_address = ptr->u.ipv6.min;
1813            const struct in6_addr *max_address = ptr->u.ipv6.max;
1814            ccs_print_ipv6(buf, sizeof(buf), min_address);
1815            if (!ccs_io_printf(head, "%s", buf))
1816                    return false;
1817            if (min_address != max_address) {
1818                    ccs_print_ipv6(buf, sizeof(buf), max_address);
1819                    if (!ccs_io_printf(head, "-%s", buf))
1820                            return false;
1821          }          }
1822          list1_for_each_cookie(dpos, head->read_var1, &domain_list) {          return true;
1823                  struct domain_info *domain;  }
1824                  domain = list1_entry(dpos, struct domain_info, list);  
1825                  if (head->read_step != 1) goto acl_loop;  /**
1826                  if (domain->is_deleted) continue;   * ccs_print_port_entry - Print port number of a network ACL entry.
1827                  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;   *
1828                  head->read_step = 2;   * @head: Pointer to "struct ccs_io_buffer".
1829          acl_loop: ;   * @ptr:  Pointer to "struct ccs_ip_network_acl_record".
1830                  if (head->read_step == 3) goto tail_mark;   *
1831                  list1_for_each_cookie(apos, head->read_var2, &domain->acl_info_list) {   * Returns true on success, false otherwise.
1832                          struct acl_info *ptr;   */
1833                          int pos;  static bool ccs_print_port_entry(struct ccs_io_buffer *head,
1834                          u8 acl_type;                                   struct ccs_ip_network_acl_record *ptr)
1835                          ptr = list1_entry(apos, struct acl_info, list);  {
1836                          if (ptr->is_deleted) continue;          const u16 min_port = ptr->min_port;
1837                          pos = head->read_avail;          const u16 max_port = ptr->max_port;
1838                          acl_type = ptr->type;          if (!ccs_io_printf(head, " %u", min_port))
1839                          if (acl_type == TYPE_SINGLE_PATH_ACL) {                  return false;
1840                                  struct single_acl_record *ptr2 = container_of(ptr, struct single_acl_record, head);          if (min_port != max_port && !ccs_io_printf(head, "-%u", max_port))
1841                                  const bool b = ptr2->u_is_group;                  return false;
1842                                  const u16 perm = ptr2->perm;          return true;
1843                                  u8 bit = head->read_bit;  }
1844                                  while (bit < MAX_SINGLE_PATH_OPERATION) {  
1845                                          if (perm & (1 << bit)) {  /**
1846                                                  pos = head->read_avail;   * ccs_print_network_acl - Print a network ACL entry.
1847                                                  if (io_printf(head, "allow_%s %s%s ", sp_operation2keyword(bit),   *
1848                                                                b ? "@" : "", b ? ptr2->u.group->group_name->name : ptr2->u.filename->name)   * @head: Pointer to "struct ccs_io_buffer".
1849                                                      || DumpCondition(head, ptr->cond)) {   * @ptr:  Pointer to "struct ccs_ip_network_acl_record".
1850                                                          head->read_bit = bit;   * @cond: Pointer to "struct ccs_condition". May be NULL.
1851                                                          head->read_avail = pos;   *
1852                                                          return 0;   * Returns true on success, false otherwise.
1853                                                  }   */
1854                                          }  static bool ccs_print_network_acl(struct ccs_io_buffer *head,
1855                                          bit++;                                    struct ccs_ip_network_acl_record *ptr,
1856                                  }                                    const struct ccs_condition *cond)
1857                                  head->read_bit = 0;  {
1858                          } else if (acl_type == TYPE_DOUBLE_PATH_ACL) {          int pos = head->read_avail;
1859                                  struct double_acl_record *ptr2 = container_of(ptr, struct double_acl_record, head);          if (!ccs_io_printf(head, KEYWORD_ALLOW_NETWORK "%s ",
1860                                  const bool b0 = ptr2->u1_is_group, b1 = ptr2->u2_is_group;                             ccs_net2keyword(ptr->operation_type)))
1861                                  const u8 perm = ptr2->perm;                  goto out;
1862                                  u8 bit = head->read_bit;          switch (ptr->record_type) {
1863                                  while (bit < MAX_DOUBLE_PATH_OPERATION) {          case IP_RECORD_TYPE_ADDRESS_GROUP:
1864                                          if (perm & (1 << bit)) {                  if (!ccs_io_printf(head, "@%s", ptr->u.group->group_name->name))
1865                                                  pos = head->read_avail;                          goto out;
1866                                                  if (io_printf(head, "allow_%s %s%s %s%s", dp_operation2keyword(bit),                  break;
1867                                                                b0 ? "@" : "", b0 ? ptr2->u1.group1->group_name->name : ptr2->u1.filename1->name,          case IP_RECORD_TYPE_IPv4:
1868                                                                b1 ? "@" : "", b1 ? ptr2->u2.group2->group_name->name : ptr2->u2.filename2->name)                  if (!ccs_print_ipv4_entry(head, ptr))
1869                                                      || DumpCondition(head, ptr->cond)) {                          goto out;
1870                                                          head->read_bit = bit;                  break;
1871                                                          head->read_avail = pos;          case IP_RECORD_TYPE_IPv6:
1872                                                          return 0;                  if (!ccs_print_ipv6_entry(head, ptr))
1873                                                  }                          goto out;
1874                                          }                  break;
1875                                          bit++;          }
1876                                  }          if (!ccs_print_port_entry(head, ptr))
1877                                  head->read_bit = 0;                  goto out;
1878                          } else if (acl_type == TYPE_ARGV0_ACL) {          if (!ccs_print_condition(head, cond))
1879                                  struct argv0_acl_record *ptr2 = container_of(ptr, struct argv0_acl_record, head);                  goto out;
1880                                  if (io_printf(head, KEYWORD_ALLOW_ARGV0 "%s %s",          return true;
1881                                                ptr2->filename->name, ptr2->argv0->name)) goto print_acl_rollback;   out:
1882                          } else if (acl_type == TYPE_ENV_ACL) {          head->read_avail = pos;
1883                                  struct env_acl_record *ptr2 = container_of(ptr, struct env_acl_record, head);          return false;
1884                                  if (io_printf(head, KEYWORD_ALLOW_ENV "%s", ptr2->env->name)) goto print_acl_rollback;  }
1885                          } else if (acl_type == TYPE_CAPABILITY_ACL) {  
1886                                  struct capability_acl_record *ptr2 = container_of(ptr, struct capability_acl_record, head);  /**
1887                                  const u32 capability = ptr2->capability;   * ccs_print_signal_acl - Print a signal ACL entry.
1888                                  u8 bit = head->read_bit;   *
1889                                  while (bit < TOMOYO_MAX_CAPABILITY_INDEX) {   * @head: Pointer to "struct ccs_io_buffer".
1890                                          if (capability & (1 << bit)) {   * @ptr:  Pointer to "struct signale_acl_record".
1891                                                  pos = head->read_avail;   * @cond: Pointer to "struct ccs_condition". May be NULL.
1892                                                  if (io_printf(head, KEYWORD_ALLOW_CAPABILITY "%s", cap_operation2keyword(bit)) ||   *
1893                                                      DumpCondition(head, ptr->cond)) {   * Returns true on success, false otherwise.
1894                                                          head->read_bit = bit;   */
1895                                                          head->read_avail = pos;  static bool ccs_print_signal_acl(struct ccs_io_buffer *head,
1896                                                          return 0;                                   struct ccs_signal_acl_record *ptr,
1897                                                  }                                   const struct ccs_condition *cond)
1898                                          }  {
1899                                          bit++;          int pos = head->read_avail;
1900                                  }          if (!ccs_io_printf(head, KEYWORD_ALLOW_SIGNAL "%u %s",
1901                                  head->read_bit = 0;                             ptr->sig, ptr->domainname->name))
1902                          } else if (acl_type == TYPE_IP_NETWORK_ACL) {                  goto out;
1903                                  struct ip_network_acl_record *ptr2 = container_of(ptr, struct ip_network_acl_record, head);          if (!ccs_print_condition(head, cond))
1904                                  if (io_printf(head, KEYWORD_ALLOW_NETWORK "%s ", net_operation2keyword(ptr2->operation_type))) goto print_acl_rollback;                  goto out;
1905                                  switch (ptr2->record_type) {          return true;
1906                                  case IP_RECORD_TYPE_ADDRESS_GROUP:   out:
1907                                          if (io_printf(head, "@%s", ptr2->u.group->group_name->name)) goto print_acl_rollback;          head->read_avail = pos;
1908                                          break;          return false;
1909                                  case IP_RECORD_TYPE_IPv4:  }
1910                                          {  
1911                                                  const u32 min_address = ptr2->u.ipv4.min, max_address = ptr2->u.ipv4.max;  /**
1912                                                  if (io_printf(head, "%u.%u.%u.%u", HIPQUAD(min_address))) goto print_acl_rollback;   * ccs_print_execute_handler_record - Print an execute handler ACL entry.
1913                                                  if (min_address != max_address && io_printf(head, "-%u.%u.%u.%u", HIPQUAD(max_address))) goto print_acl_rollback;   *
1914                                          }   * @head:    Pointer to "struct ccs_io_buffer".
1915                                          break;   * @keyword: Name of the keyword.
1916                                  case IP_RECORD_TYPE_IPv6:   * @ptr:     Pointer to "struct ccs_execute_handler_record".
1917                                          {   *
1918                                                  char buf[64];   * Returns true on success, false otherwise.
1919                                                  const struct in6_addr *min_address = ptr2->u.ipv6.min, *max_address = ptr2->u.ipv6.max;   */
1920                                                  print_ipv6(buf, sizeof(buf), min_address);  static bool ccs_print_execute_handler_record(struct ccs_io_buffer *head,
1921                                                  if (io_printf(head, "%s", buf)) goto print_acl_rollback;                                               const char *keyword,
1922                                                  if (min_address != max_address) {                                               struct ccs_execute_handler_record *
1923                                                          print_ipv6(buf, sizeof(buf), max_address);                                               ptr)
1924                                                          if (io_printf(head, "-%s", buf)) goto print_acl_rollback;  {
1925                                                  }          return ccs_io_printf(head, "%s %s\n", keyword, ptr->handler->name);
1926                                          }  }
1927                                          break;  
1928                                  }  /**
1929                                  {   * ccs_print_mount_acl - Print a mount ACL entry.
1930                                          const u16 min_port = ptr2->min_port, max_port = ptr2->max_port;   *
1931                                          if (io_printf(head, " %u", min_port)) goto print_acl_rollback;   * @head: Pointer to "struct ccs_io_buffer".
1932                                          if (min_port != max_port && io_printf(head, "-%u", max_port)) goto print_acl_rollback;   * @ptr:  Pointer to "struct ccs_mount_acl_record".
1933                                  }   * @cond: Pointer to "struct ccs_condition". May be NULL.
1934                          } else if (acl_type == TYPE_SIGNAL_ACL) {   *
1935                                  struct signal_acl_record *ptr2 = container_of(ptr, struct signal_acl_record, head);   * Returns true on success, false otherwise.
1936                                  if (io_printf(head, KEYWORD_ALLOW_SIGNAL "%u %s", ptr2->sig, ptr2->domainname->name)) goto print_acl_rollback;   */
1937                          } else {  static bool ccs_print_mount_acl(struct ccs_io_buffer *head,
1938                                  BUG();                                  struct ccs_mount_acl_record *ptr,
1939                          }                                  const struct ccs_condition *cond)
1940                          if (acl_type != TYPE_SINGLE_PATH_ACL && acl_type != TYPE_DOUBLE_PATH_ACL && acl_type != TYPE_CAPABILITY_ACL && DumpCondition(head, ptr->cond)) {  {
1941                          print_acl_rollback: ;          int pos = head->read_avail;
1942                          head->read_avail = pos;          if (!ccs_io_printf(head, KEYWORD_ALLOW_MOUNT "%s %s %s 0x%lX\n",
1943                               ptr->dev_name->name, ptr->dir_name->name,
1944                               ptr->fs_type->name, ptr->flags))
1945                    goto out;
1946            if (!ccs_print_condition(head, cond))
1947                    goto out;
1948            return true;
1949     out:
1950            head->read_avail = pos;
1951            return false;
1952    }
1953    
1954    /**
1955     * ccs_print_umount_acl - Print a mount ACL entry.
1956     *
1957     * @head: Pointer to "struct ccs_io_buffer".
1958     * @ptr:  Pointer to "struct ccs_umount_acl_record".
1959     * @cond: Pointer to "struct ccs_condition". May be NULL.
1960     *
1961     * Returns true on success, false otherwise.
1962     */
1963    static bool ccs_print_umount_acl(struct ccs_io_buffer *head,
1964                                     struct ccs_umount_acl_record *ptr,
1965                                     const struct ccs_condition *cond)
1966    {
1967            int pos = head->read_avail;
1968            if (!ccs_io_printf(head, KEYWORD_ALLOW_UNMOUNT "%s\n",
1969                               ptr->dir->name))
1970                    goto out;
1971            if (!ccs_print_condition(head, cond))
1972                    goto out;
1973            return true;
1974     out:
1975            head->read_avail = pos;
1976            return false;
1977    }
1978    
1979    /**
1980     * ccs_print_chroot_acl - Print a chroot ACL entry.
1981     *
1982     * @head: Pointer to "struct ccs_io_buffer".
1983     * @ptr:  Pointer to "struct ccs_chroot_acl_record".
1984     * @cond: Pointer to "struct ccs_condition". May be NULL.
1985     *
1986     * Returns true on success, false otherwise.
1987     */
1988    static bool ccs_print_chroot_acl(struct ccs_io_buffer *head,
1989                                     struct ccs_chroot_acl_record *ptr,
1990                                     const struct ccs_condition *cond)
1991    {
1992            int pos = head->read_avail;
1993            if (!ccs_io_printf(head, KEYWORD_ALLOW_CHROOT "%s\n",
1994                               ptr->dir->name))
1995                    goto out;
1996            if (!ccs_print_condition(head, cond))
1997                    goto out;
1998            return true;
1999     out:
2000            head->read_avail = pos;
2001            return false;
2002    }
2003    
2004    /**
2005     * ccs_print_pivot_root_acl - Print a pivot_root ACL entry.
2006     *
2007     * @head: Pointer to "struct ccs_io_buffer".
2008     * @ptr:  Pointer to "struct ccs_pivot_root_acl_record".
2009     * @cond: Pointer to "struct ccs_condition". May be NULL.
2010     *
2011     * Returns true on success, false otherwise.
2012     */
2013    static bool ccs_print_pivot_root_acl(struct ccs_io_buffer *head,
2014                                         struct ccs_pivot_root_acl_record *ptr,
2015                                         const struct ccs_condition *cond)
2016    {
2017            int pos = head->read_avail;
2018            if (!ccs_io_printf(head, KEYWORD_ALLOW_PIVOT_ROOT "%s %s\n",
2019                               ptr->new_root->name, ptr->old_root->name))
2020                    goto out;
2021            if (!ccs_print_condition(head, cond))
2022                    goto out;
2023            return true;
2024     out:
2025            head->read_avail = pos;
2026            return false;
2027    }
2028    
2029    /**
2030     * ccs_print_entry - Print an ACL entry.
2031     *
2032     * @head: Pointer to "struct ccs_io_buffer".
2033     * @ptr:  Pointer to an ACL entry.
2034     *
2035     * Returns true on success, false otherwise.
2036     */
2037    static bool ccs_print_entry(struct ccs_io_buffer *head,
2038                                struct ccs_acl_info *ptr)
2039    {
2040            const struct ccs_condition *cond = ptr->cond;
2041            const u8 acl_type = ccs_acl_type2(ptr);
2042            if (acl_type & ACL_DELETED)
2043                    return true;
2044            if (acl_type == TYPE_SINGLE_PATH_ACL) {
2045                    struct ccs_single_path_acl_record *acl
2046                            = container_of(ptr, struct ccs_single_path_acl_record,
2047                                           head);
2048                    return ccs_print_single_path_acl(head, acl, cond);
2049            }
2050            if (acl_type == TYPE_EXECUTE_HANDLER) {
2051                    struct ccs_execute_handler_record *acl
2052                            = container_of(ptr, struct ccs_execute_handler_record,
2053                                           head);
2054                    const char *keyword = KEYWORD_EXECUTE_HANDLER;
2055                    return ccs_print_execute_handler_record(head, keyword, acl);
2056            }
2057            if (acl_type == TYPE_DENIED_EXECUTE_HANDLER) {
2058                    struct ccs_execute_handler_record *acl
2059                            = container_of(ptr, struct ccs_execute_handler_record,
2060                                           head);
2061                    const char *keyword = KEYWORD_DENIED_EXECUTE_HANDLER;
2062                    return ccs_print_execute_handler_record(head, keyword, acl);
2063            }
2064            if (head->read_execute_only)
2065                    return true;
2066            if (acl_type == TYPE_DOUBLE_PATH_ACL) {
2067                    struct ccs_double_path_acl_record *acl
2068                            = container_of(ptr, struct ccs_double_path_acl_record,
2069                                           head);
2070                    return ccs_print_double_path_acl(head, acl, cond);
2071            }
2072            if (acl_type == TYPE_IOCTL_ACL) {
2073                    struct ccs_ioctl_acl_record *acl
2074                            = container_of(ptr, struct ccs_ioctl_acl_record, head);
2075                    return ccs_print_ioctl_acl(head, acl, cond);
2076            }
2077            if (acl_type == TYPE_ARGV0_ACL) {
2078                    struct ccs_argv0_acl_record *acl
2079                            = container_of(ptr, struct ccs_argv0_acl_record, head);
2080                    return ccs_print_argv0_acl(head, acl, cond);
2081            }
2082            if (acl_type == TYPE_ENV_ACL) {
2083                    struct ccs_env_acl_record *acl
2084                            = container_of(ptr, struct ccs_env_acl_record, head);
2085                    return ccs_print_env_acl(head, acl, cond);
2086            }
2087            if (acl_type == TYPE_CAPABILITY_ACL) {
2088                    struct ccs_capability_acl_record *acl
2089                            = container_of(ptr, struct ccs_capability_acl_record,
2090                                           head);
2091                    return ccs_print_capability_acl(head, acl, cond);
2092            }
2093            if (acl_type == TYPE_IP_NETWORK_ACL) {
2094                    struct ccs_ip_network_acl_record *acl
2095                            = container_of(ptr, struct ccs_ip_network_acl_record,
2096                                           head);
2097                    return ccs_print_network_acl(head, acl, cond);
2098            }
2099            if (acl_type == TYPE_SIGNAL_ACL) {
2100                    struct ccs_signal_acl_record *acl
2101                            = container_of(ptr, struct ccs_signal_acl_record, head);
2102                    return ccs_print_signal_acl(head, acl, cond);
2103            }
2104            if (acl_type == TYPE_MOUNT_ACL) {
2105                    struct ccs_mount_acl_record *acl
2106                            = container_of(ptr, struct ccs_mount_acl_record, head);
2107                    return ccs_print_mount_acl(head, acl, cond);
2108            }
2109            if (acl_type == TYPE_UMOUNT_ACL) {
2110                    struct ccs_umount_acl_record *acl
2111                            = container_of(ptr, struct ccs_umount_acl_record, head);
2112                    return ccs_print_umount_acl(head, acl, cond);
2113            }
2114            if (acl_type == TYPE_CHROOT_ACL) {
2115                    struct ccs_chroot_acl_record *acl
2116                            = container_of(ptr, struct ccs_chroot_acl_record, head);
2117                    return ccs_print_chroot_acl(head, acl, cond);
2118            }
2119            if (acl_type == TYPE_PIVOT_ROOT_ACL) {
2120                    struct ccs_pivot_root_acl_record *acl
2121                            = container_of(ptr, struct ccs_pivot_root_acl_record,
2122                                           head);
2123                    return ccs_print_pivot_root_acl(head, acl, cond);
2124            }
2125            /* Workaround for gcc 3.2.2's inline bug. */
2126            if (acl_type & ACL_DELETED)
2127                    return true;
2128            BUG(); /* This must not happen. */
2129            return false;
2130    }
2131    
2132    /**
2133     * ccs_read_domain_policy - Read domain policy.
2134     *
2135     * @head: Pointer to "struct ccs_io_buffer".
2136     *
2137     * Returns 0.
2138     *
2139     * Caller holds srcu_read_lock(&ccs_ss).
2140     */
2141    static int ccs_read_domain_policy(struct ccs_io_buffer *head)
2142    {
2143            struct list_head *dpos;
2144            struct list_head *apos;
2145            if (head->read_eof)
2146                    return 0;
2147            if (head->read_step == 0)
2148                    head->read_step = 1;
2149            list_for_each_cookie(dpos, head->read_var1, &ccs_domain_list) {
2150                    struct ccs_domain_info *domain;
2151                    const char *quota_exceeded = "";
2152                    const char *transition_failed = "";
2153                    const char *ignore_global_allow_read = "";
2154                    const char *ignore_global_allow_env = "";
2155                    domain = list_entry(dpos, struct ccs_domain_info, list);
2156                    if (head->read_step != 1)
2157                            goto acl_loop;
2158                    if (domain->is_deleted && !head->read_single_domain)
2159                            continue;
2160                    /* Print domainname and flags. */
2161                    if (domain->quota_warned)
2162                            quota_exceeded = "quota_exceeded\n";
2163                    if (domain->domain_transition_failed)
2164                            transition_failed = "transition_failed\n";
2165                    if (domain->ignore_global_allow_read)
2166                            ignore_global_allow_read
2167                                    = KEYWORD_IGNORE_GLOBAL_ALLOW_READ "\n";
2168                    if (domain->ignore_global_allow_env)
2169                            ignore_global_allow_env
2170                                    = KEYWORD_IGNORE_GLOBAL_ALLOW_ENV "\n";
2171                    if (!ccs_io_printf(head, "%s\n" KEYWORD_USE_PROFILE "%u\n"
2172                                       "%s%s%s%s\n", domain->domainname->name,
2173                                       domain->profile, quota_exceeded,
2174                                       transition_failed,
2175                                       ignore_global_allow_read,
2176                                       ignore_global_allow_env))
2177                          return 0;                          return 0;
2178                          }                  head->read_step = 2;
2179     acl_loop:
2180                    if (head->read_step == 3)
2181                            goto tail_mark;
2182                    /* Print ACL entries in the domain. */
2183                    list_for_each_cookie(apos, head->read_var2,
2184                                         &domain->acl_info_list) {
2185                            struct ccs_acl_info *ptr
2186                                    = list_entry(apos, struct ccs_acl_info, list);
2187                            if (!ccs_print_entry(head, ptr))
2188                                    return 0;
2189                  }                  }
2190                  head->read_step = 3;                  head->read_step = 3;
2191          tail_mark: ;   tail_mark:
2192                  if (io_printf(head, "\n")) return 0;                  if (!ccs_io_printf(head, "\n"))
2193                            return 0;
2194                  head->read_step = 1;                  head->read_step = 1;
2195                    if (head->read_single_domain)
2196                            break;
2197          }          }
2198          head->read_eof = 1;          head->read_eof = true;
2199          return 0;          return 0;
2200  }  }
2201    
2202  #endif  /**
2203     * ccs_write_domain_profile - Assign profile for specified domain.
2204  static int UpdateDomainProfile(struct io_buffer *head)   *
2205     * @head: Pointer to "struct ccs_io_buffer".
2206     *
2207     * Returns 0 on success, -EINVAL otherwise.
2208     *
2209     * This is equivalent to doing
2210     *
2211     *     ( echo "select " $domainname; echo "use_profile " $profile ) |
2212     *     /usr/lib/ccs/loadpolicy -d
2213     *
2214     * Caller holds srcu_read_lock(&ccs_ss).
2215     */
2216    static int ccs_write_domain_profile(struct ccs_io_buffer *head)
2217  {  {
2218          char *data = head->write_buf;          char *data = head->write_buf;
2219          char *cp = strchr(data, ' ');          char *cp = strchr(data, ' ');
2220          struct domain_info *domain;          struct ccs_domain_info *domain;
2221          unsigned int profile;          unsigned int profile;
2222          if (!isRoot()) return -EPERM;          if (!cp)
2223          if (!cp) return -EINVAL;                  return -EINVAL;
2224          *cp = '\0';          *cp = '\0';
         domain = FindDomain(cp + 1);  
2225          profile = simple_strtoul(data, NULL, 10);          profile = simple_strtoul(data, NULL, 10);
2226          if (domain && profile < MAX_PROFILES && (profile_ptr[profile] || !sbin_init_started)) domain->profile = (u8) profile;          if (profile >= MAX_PROFILES)
2227          UpdateCounter(CCS_UPDATES_COUNTER_DOMAIN_POLICY);                  return -EINVAL;
2228            domain = ccs_find_domain(cp + 1);
2229            if (domain && (ccs_profile_ptr[profile] || !ccs_policy_loaded))
2230                    domain->profile = (u8) profile;
2231          return 0;          return 0;
2232  }  }
2233    
2234  static int ReadDomainProfile(struct io_buffer *head)  /**
2235     * ccs_read_domain_profile - Read only domainname and profile.
2236     *
2237     * @head: Pointer to "struct ccs_io_buffer".
2238     *
2239     * Returns list of profile number and domainname pairs.
2240     *
2241     * This is equivalent to doing
2242     *
2243     *     grep -A 1 '^<kernel>' /proc/ccs/domain_policy |
2244     *     awk ' { if ( domainname == "" ) { if ( $1 == "<kernel>" )
2245     *     domainname = $0; } else if ( $1 == "use_profile" ) {
2246     *     print $2 " " domainname; domainname = ""; } } ; '
2247     *
2248     * Caller holds srcu_read_lock(&ccs_ss).
2249     */
2250    static int ccs_read_domain_profile(struct ccs_io_buffer *head)
2251  {  {
2252          struct list1_head *pos;          struct list_head *pos;
2253          if (head->read_eof) return 0;          if (head->read_eof)
2254          if (!isRoot()) return -EPERM;                  return 0;
2255          list1_for_each_cookie(pos, head->read_var1, &domain_list) {          list_for_each_cookie(pos, head->read_var1, &ccs_domain_list) {
2256                  struct domain_info *domain;                  struct ccs_domain_info *domain;
2257                  domain = list1_entry(pos, struct domain_info, list);                  domain = list_entry(pos, struct ccs_domain_info, list);
2258                  if (domain->is_deleted) continue;                  if (domain->is_deleted)
2259                  if (io_printf(head, "%u %s\n", domain->profile, domain->domainname->name)) return 0;                          continue;
2260                    if (!ccs_io_printf(head, "%u %s\n", domain->profile,
2261                                       domain->domainname->name))
2262                            return 0;
2263          }          }
2264          head->read_eof = 1;          head->read_eof = true;
2265          return 0;          return 0;
2266  }  }
2267    
2268  static int WritePID(struct io_buffer *head)  /**
2269     * ccs_write_pid: Specify PID to obtain domainname.
2270     *
2271     * @head: Pointer to "struct ccs_io_buffer".
2272     *
2273     * Returns 0.
2274     */
2275    static int ccs_write_pid(struct ccs_io_buffer *head)
2276  {  {
2277          head->read_step = (int) simple_strtoul(head->write_buf, NULL, 10);          head->read_eof = false;
         head->read_eof = 0;  
2278          return 0;          return 0;
2279  }  }
2280    
2281  static int ReadPID(struct io_buffer *head)  /**
2282     * ccs_read_pid - Read information of a process.
2283     *
2284     * @head: Pointer to "struct ccs_io_buffer".
2285     *
2286     * Returns the domainname which the specified PID is in or
2287     * process information of the specified PID on success,
2288     * empty string otherwise.
2289     *
2290     * Caller holds srcu_read_lock(&ccs_ss).
2291     */
2292    static int ccs_read_pid(struct ccs_io_buffer *head)
2293  {  {
2294          if (head->read_avail == 0 && !head->read_eof) {          char *buf = head->write_buf;
2295                  const int pid = head->read_step;          bool task_info = false;
2296                  struct task_struct *p;          unsigned int pid;
2297                  struct domain_info *domain = NULL;          struct task_struct *p;
2298                  /***** CRITICAL SECTION START *****/          struct ccs_domain_info *domain = NULL;
2299                  read_lock(&tasklist_lock);          u32 ccs_flags = 0;
2300                  p = find_task_by_pid(pid);          /* Accessing write_buf is safe because head->io_sem is held. */
2301                  if (p) domain = p->domain_info;          if (!buf)
2302                  read_unlock(&tasklist_lock);                  goto done; /* Do nothing if open(O_RDONLY). */
2303                  /***** CRITICAL SECTION END *****/          if (head->read_avail || head->read_eof)
2304                  if (domain) io_printf(head, "%d %u %s", pid, domain->profile, domain->domainname->name);                  goto done;
2305                  head->read_eof = 1;          head->read_eof = true;
2306            if (ccs_str_starts(&buf, "info "))
2307                    task_info = true;
2308            pid = (unsigned int) simple_strtoul(buf, NULL, 10);
2309            /***** CRITICAL SECTION START *****/
2310            read_lock(&tasklist_lock);
2311            p = find_task_by_pid(pid);
2312            if (p) {
2313                    domain = ccs_task_domain(p);
2314                    ccs_flags = p->ccs_flags;
2315          }          }
2316            read_unlock(&tasklist_lock);
2317            /***** CRITICAL SECTION END *****/
2318            if (!domain)
2319                    goto done;
2320            if (!task_info)
2321                    ccs_io_printf(head, "%u %u %s", pid, domain->profile,
2322                                  domain->domainname->name);
2323            else
2324                    ccs_io_printf(head, "%u manager=%s execute_handler=%s "
2325                                  "state[0]=%u state[1]=%u state[2]=%u", pid,
2326                                  ccs_flags & CCS_TASK_IS_POLICY_MANAGER ?
2327                                  "yes" : "no",
2328                                  ccs_flags & CCS_TASK_IS_EXECUTE_HANDLER ?
2329                                  "yes" : "no",
2330                                  (u8) (ccs_flags >> 24),
2331                                  (u8) (ccs_flags >> 16),
2332                                  (u8) (ccs_flags >> 8));
2333     done:
2334          return 0;          return 0;
2335  }  }
2336    
2337  /*************************  EXCEPTION POLICY HANDLER  *************************/  /**
2338     * ccs_write_exception_policy - Write exception policy.
2339  #ifdef CONFIG_TOMOYO   *
2340     * @head: Pointer to "struct ccs_io_buffer".
2341  static int AddExceptionPolicy(struct io_buffer *head)   *
2342     * Returns 0 on success, negative value otherwise.
2343     */
2344    static int ccs_write_exception_policy(struct ccs_io_buffer *head)
2345  {  {
2346          char *data = head->write_buf;          char *data = head->write_buf;
2347          bool is_delete = 0;          bool is_delete = ccs_str_starts(&data, KEYWORD_DELETE);
2348          if (!isRoot()) return -EPERM;          if (ccs_str_starts(&data, KEYWORD_KEEP_DOMAIN))
2349          UpdateCounter(CCS_UPDATES_COUNTER_EXCEPTION_POLICY);                  return ccs_write_domain_keeper_policy(data, false, is_delete);
2350          if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_NO_KEEP_DOMAIN))
2351                  data += KEYWORD_DELETE_LEN;                  return ccs_write_domain_keeper_policy(data, true, is_delete);
2352                  is_delete = 1;          if (ccs_str_starts(&data, KEYWORD_INITIALIZE_DOMAIN))
2353          }                  return ccs_write_domain_initializer_policy(data, false,
2354          if (strncmp(data, KEYWORD_KEEP_DOMAIN, KEYWORD_KEEP_DOMAIN_LEN) == 0) {                                                             is_delete);
2355                  return AddDomainKeeperPolicy(data + KEYWORD_KEEP_DOMAIN_LEN, 0, is_delete);          if (ccs_str_starts(&data, KEYWORD_NO_INITIALIZE_DOMAIN))
2356          } else if (strncmp(data, KEYWORD_NO_KEEP_DOMAIN, KEYWORD_NO_KEEP_DOMAIN_LEN) == 0) {                  return ccs_write_domain_initializer_policy(data, true,
2357                  return AddDomainKeeperPolicy(data + KEYWORD_NO_KEEP_DOMAIN_LEN, 1, is_delete);                                                             is_delete);
2358          } else if (strncmp(data, KEYWORD_INITIALIZE_DOMAIN, KEYWORD_INITIALIZE_DOMAIN_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_ALIAS))
2359                  return AddDomainInitializerPolicy(data + KEYWORD_INITIALIZE_DOMAIN_LEN, 0, is_delete);                  return ccs_write_alias_policy(data, is_delete);
2360          } else if (strncmp(data, KEYWORD_NO_INITIALIZE_DOMAIN, KEYWORD_NO_INITIALIZE_DOMAIN_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_AGGREGATOR))
2361                  return AddDomainInitializerPolicy(data + KEYWORD_NO_INITIALIZE_DOMAIN_LEN, 1, is_delete);                  return ccs_write_aggregator_policy(data, is_delete);
2362          } else if (strncmp(data, KEYWORD_ALIAS, KEYWORD_ALIAS_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_ALLOW_READ))
2363                  return AddAliasPolicy(data + KEYWORD_ALIAS_LEN, is_delete);                  return ccs_write_globally_readable_policy(data, is_delete);
2364          } else if (strncmp(data, KEYWORD_AGGREGATOR, KEYWORD_AGGREGATOR_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_ALLOW_ENV))
2365                  return AddAggregatorPolicy(data + KEYWORD_AGGREGATOR_LEN, is_delete);                  return ccs_write_globally_usable_env_policy(data, is_delete);
2366          } else if (strncmp(data, KEYWORD_ALLOW_READ, KEYWORD_ALLOW_READ_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_FILE_PATTERN))
2367                  return AddGloballyReadablePolicy(data + KEYWORD_ALLOW_READ_LEN, is_delete);                  return ccs_write_pattern_policy(data, is_delete);
2368          } else if (strncmp(data, KEYWORD_ALLOW_ENV, KEYWORD_ALLOW_ENV_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_PATH_GROUP))
2369                  return AddGloballyUsableEnvPolicy(data + KEYWORD_ALLOW_ENV_LEN, is_delete);                  return ccs_write_path_group_policy(data, is_delete);
2370          } else if (strncmp(data, KEYWORD_FILE_PATTERN, KEYWORD_FILE_PATTERN_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_DENY_REWRITE))
2371                  return AddFilePatternPolicy(data + KEYWORD_FILE_PATTERN_LEN, is_delete);                  return ccs_write_no_rewrite_policy(data, is_delete);
2372          } else if (strncmp(data, KEYWORD_PATH_GROUP, KEYWORD_PATH_GROUP_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_ADDRESS_GROUP))
2373                  return AddPathGroupPolicy(data + KEYWORD_PATH_GROUP_LEN, is_delete);                  return ccs_write_address_group_policy(data, is_delete);
2374          } else if (strncmp(data, KEYWORD_DENY_REWRITE, KEYWORD_DENY_REWRITE_LEN) == 0) {          if (ccs_str_starts(&data, KEYWORD_DENY_AUTOBIND))
2375                  return AddNoRewritePolicy(data + KEYWORD_DENY_REWRITE_LEN, is_delete);                  return ccs_write_reserved_port_policy(data, is_delete);
         } else if (strncmp(data, KEYWORD_ADDRESS_GROUP, KEYWORD_ADDRESS_GROUP_LEN) == 0) {  
                 return AddAddressGroupPolicy(data + KEYWORD_ADDRESS_GROUP_LEN, is_delete);  
         }  
2376          return -EINVAL;          return -EINVAL;
2377  }  }
2378    
2379  static int ReadExceptionPolicy(struct io_buffer *head)  /**
2380     * ccs_read_exception_policy - Read exception policy.
2381     *
2382     * @head: Pointer to "struct ccs_io_buffer".
2383     *
2384     * Returns 0 on success, -EINVAL otherwise.
2385     *
2386     * Caller holds srcu_read_lock(&ccs_ss).
2387     */
2388    static int ccs_read_exception_policy(struct ccs_io_buffer *head)
2389  {  {
2390          if (!head->read_eof) {          if (!head->read_eof) {
2391                  switch (head->read_step) {                  switch (head->read_step) {
2392                  case 0:                  case 0:
2393                          if (!isRoot()) return -EPERM;                          head->read_var2 = NULL;
2394                          head->read_var2 = NULL; head->read_step = 1;                          head->read_step = 1;
2395                  case 1:                  case 1:
2396                          if (ReadDomainKeeperPolicy(head)) break;                          if (!ccs_read_domain_keeper_policy(head))
2397                          head->read_var2 = NULL; head->read_step = 2;                                  break;
2398                            head->read_var2 = NULL;
2399                            head->read_step = 2;
2400                  case 2:                  case 2:
2401                          if (ReadGloballyReadablePolicy(head)) break;                          if (!ccs_read_globally_readable_policy(head))
2402                          head->read_var2 = NULL; head->read_step = 3;                                  break;
2403                            head->read_var2 = NULL;
2404                            head->read_step = 3;
2405                  case 3:                  case 3:
2406                          if (ReadGloballyUsableEnvPolicy(head)) break;                          if (!ccs_read_globally_usable_env_policy(head))
2407                          head->read_var2 = NULL; head->read_step = 4;                                  break;
2408                            head->read_var2 = NULL;
2409                            head->read_step = 4;
2410                  case 4:                  case 4:
2411                          if (ReadDomainInitializerPolicy(head)) break;                          if (!ccs_read_domain_initializer_policy(head))
2412                          head->read_var2 = NULL; head->read_step = 5;                                  break;
2413                            head->read_var2 = NULL;
2414                            head->read_step = 5;
2415                  case 5:                  case 5:
2416                          if (ReadAliasPolicy(head)) break;                          if (!ccs_read_alias_policy(head))
2417                          head->read_var2 = NULL; head->read_step = 6;                                  break;
2418                            head->read_var2 = NULL;
2419                            head->read_step = 6;
2420                  case 6:                  case 6:
2421                          if (ReadAggregatorPolicy(head)) break;                          if (!ccs_read_aggregator_policy(head))
2422                          head->read_var2 = NULL; head->read_step = 7;                                  break;
2423                            head->read_var2 = NULL;
2424                            head->read_step = 7;
2425                  case 7:                  case 7:
2426                          if (ReadFilePatternPolicy(head)) break;                          if (!ccs_read_file_pattern(head))
2427                          head->read_var2 = NULL; head->read_step = 8;                                  break;
2428                            head->read_var2 = NULL;
2429                            head->read_step = 8;
2430                  case 8:                  case 8:
2431                          if (ReadNoRewritePolicy(head)) break;                          if (!ccs_read_no_rewrite_policy(head))
2432                          head->read_var2 = NULL; head->read_step = 9;                                  break;
2433                            head->read_var2 = NULL;
2434                            head->read_step = 9;
2435                  case 9:                  case 9:
2436                          if (ReadPathGroupPolicy(head)) break;                          if (!ccs_read_path_group_policy(head))
2437                          head->read_var1 = head->read_var2 = NULL; head->read_step = 10;                                  break;
2438                            head->read_var1 = NULL;
2439                            head->read_var2 = NULL;
2440                            head->read_step = 10;
2441                  case 10:                  case 10:
2442                          if (ReadAddressGroupPolicy(head)) break;                          if (!ccs_read_address_group_policy(head))
2443                          head->read_eof = 1;                                  break;
2444                            head->read_var2 = NULL;
2445                            head->read_step = 11;
2446                    case 11:
2447                            if (!ccs_read_reserved_port_policy(head))
2448                                    break;
2449                            head->read_eof = true;
2450                          break;                          break;
2451                  default:                  default:
2452                          return -EINVAL;                          return -EINVAL;
# Line 1127  static int ReadExceptionPolicy(struct io Line 2455  static int ReadExceptionPolicy(struct io
2455          return 0;          return 0;
2456  }  }
2457    
2458  #endif  /* Path to the policy loader. The default is /sbin/ccs-init. */
2459    static const char *ccs_loader;
 /*************************  SYSTEM POLICY HANDLER  *************************/  
   
 #ifdef CONFIG_SAKURA  
2460    
2461  static int AddSystemPolicy(struct io_buffer *head)  /**
2462     * ccs_loader_setup - Specify the policy loader to use.
2463     *
2464     * @str: Path to the policy loader.
2465     *
2466     * Returns 0.
2467     */
2468    static int __init ccs_loader_setup(char *str)
2469  {  {
2470          char *data = head->write_buf;          ccs_loader = str;
2471          bool is_delete = 0;          return 0;
         if (!isRoot()) return -EPERM;  
         UpdateCounter(CCS_UPDATES_COUNTER_SYSTEM_POLICY);  
         if (strncmp(data, KEYWORD_DELETE, KEYWORD_DELETE_LEN) == 0) {  
                 data += KEYWORD_DELETE_LEN;  
                 is_delete = 1;  
         }  
         if (strncmp(data, KEYWORD_ALLOW_MOUNT, KEYWORD_ALLOW_MOUNT_LEN) == 0)  
                 return AddMountPolicy(data + KEYWORD_ALLOW_MOUNT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_DENY_UNMOUNT, KEYWORD_DENY_UNMOUNT_LEN) == 0)  
                 return AddNoUmountPolicy(data + KEYWORD_DENY_UNMOUNT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_ALLOW_CHROOT, KEYWORD_ALLOW_CHROOT_LEN) == 0)  
                 return AddChrootPolicy(data + KEYWORD_ALLOW_CHROOT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_ALLOW_PIVOT_ROOT, KEYWORD_ALLOW_PIVOT_ROOT_LEN) == 0)  
                 return AddPivotRootPolicy(data + KEYWORD_ALLOW_PIVOT_ROOT_LEN, is_delete);  
         if (strncmp(data, KEYWORD_DENY_AUTOBIND, KEYWORD_DENY_AUTOBIND_LEN) == 0)  
                 return AddReservedPortPolicy(data + KEYWORD_DENY_AUTOBIND_LEN, is_delete);  
         return -EINVAL;  
2472  }  }
2473    
2474  static int ReadSystemPolicy(struct io_buffer *head)  __setup("CCS_loader=", ccs_loader_setup);
2475    
2476    /**
2477     * ccs_policy_loader_exists - Check whether /sbin/ccs-init exists.
2478     *
2479     * Returns true if /sbin/ccs-init exists, false otherwise.
2480     */
2481    static bool ccs_policy_loader_exists(void)
2482  {  {
2483          if (!head->read_eof) {          /*
2484                  switch (head->read_step) {           * Don't activate MAC if the path given by 'CCS_loader=' option doesn't
2485                  case 0:           * exist. If the initrd includes /sbin/init but real-root-dev has not
2486                          if (!isRoot()) return -EPERM;           * mounted on / yet, activating MAC will block the system since
2487                          head->read_var2 = NULL; head->read_step = 1;           * policies are not loaded yet.
2488                  case 1:           * Thus, let do_execve() call this function everytime.
2489                          if (ReadMountPolicy(head)) break;           */
2490                          head->read_var2 = NULL; head->read_step = 2;          struct nameidata nd;
2491                  case 2:          if (!ccs_loader)
2492                          if (ReadNoUmountPolicy(head)) break;                  ccs_loader = "/sbin/ccs-init";
2493                          head->read_var2 = NULL; head->read_step = 3;          if (path_lookup(ccs_loader, ccs_lookup_flags, &nd)) {
2494                  case 3:                  printk(KERN_INFO "Not activating Mandatory Access Control now "
2495                          if (ReadChrootPolicy(head)) break;                         "since %s doesn't exist.\n", ccs_loader);
2496                          head->read_var2 = NULL; head->read_step = 4;                  return false;
                 case 4:  
                         if (ReadPivotRootPolicy(head)) break;  
                         head->read_var2 = NULL; head->read_step = 5;  
                 case 5:  
                         if (ReadReservedPortPolicy(head)) break;  
                         head->read_eof = 1;  
                         break;  
                 default:  
                         return -EINVAL;  
                 }  
2497          }          }
2498          return 0;  #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)
2499  }          path_put(&nd.path);
2500    #else
2501            path_release(&nd);
2502  #endif  #endif
2503            return true;
2504    }
2505    
2506  /*************************  POLICY LOADER  *************************/  #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0)
2507    /**
2508  static int profile_loaded = 0;   * ccs_run_loader - Start /sbin/ccs-init .
2509     *
2510  static const char *ccs_loader = NULL;   * @unused: Not used.
2511     *
2512  static int __init CCS_loader_Setup(char *str)   * Returns PID of /sbin/ccs-init on success, negative value otherwise.
2513     */
2514    static int ccs_run_loader(void *unused)
2515  {  {
2516          ccs_loader = str;          char *argv[2];
2517          return 0;          char *envp[3];
2518            printk(KERN_INFO "Calling %s to load policy. Please wait.\n",
2519                   ccs_loader);
2520            argv[0] = (char *) ccs_loader;
2521            argv[1] = NULL;
2522            envp[0] = "HOME=/";
2523            envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
2524            envp[2] = NULL;
2525            return exec_usermodehelper(argv[0], argv, envp);
2526  }  }
2527    #endif
2528    
2529  __setup("CCS_loader=", CCS_loader_Setup);  /**
2530     * ccs_load_policy - Run external policy loader to load policy.
2531  void CCS_LoadPolicy(const char *filename)   *
2532     * @filename: The program about to start.
2533     *
2534     * This function checks whether @filename is /sbin/init , and if so
2535     * invoke /sbin/ccs-init and wait for the termination of /sbin/ccs-init
2536     * and then continues invocation of /sbin/init.
2537     * /sbin/ccs-init reads policy files in /etc/ccs/ directory and
2538     * writes to /proc/ccs/ interfaces.
2539     *
2540     * Returns nothing.
2541     */
2542    void ccs_load_policy(const char *filename)
2543  {  {
2544          if (sbin_init_started) return;          if (ccs_policy_loaded)
2545          /*                  return;
          * Check filename is /sbin/init or /sbin/ccs-start .  
          * /sbin/ccs-start is a dummy filename in case where /sbin/init can't be passed.  
          * You can create /sbin/ccs-start by "ln -s /bin/true /sbin/ccs-start", for  
          * only the pathname is needed to activate Mandatory Access Control.  
          */  
         if (strcmp(filename, "/sbin/init") != 0 && strcmp(filename, "/sbin/ccs-start") != 0) return;  
2546          /*          /*
2547           * Don't activate MAC if the path given by 'CCS_loader=' option doesn't exist.           * Check filename is /sbin/init or /sbin/ccs-start.
2548           * 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
2549           * activating MAC will block the system since policies are not loaded yet.           * be passed.
2550           * So let do_execve() call this function everytime.           * You can create /sbin/ccs-start by "ln -s /bin/true /sbin/ccs-start".
2551           */           */
2552            if (strcmp(filename, "/sbin/init") &&
2553                strcmp(filename, "/sbin/ccs-start"))
2554                    return;
2555            if (!ccs_policy_loader_exists())
2556                    return;
2557    #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 0)
2558          {          {
2559                  struct nameidata nd;                  char *argv[2];
2560                  if (!ccs_loader) ccs_loader = "/sbin/ccs-init";                  char *envp[3];
2561                  if (path_lookup(ccs_loader, lookup_flags, &nd)) {                  printk(KERN_INFO "Calling %s to load policy. Please wait.\n",
2562                          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);  
2563                  argv[0] = (char *) ccs_loader;                  argv[0] = (char *) ccs_loader;
2564                  argv[1] = NULL;                  argv[1] = NULL;
2565                  envp[0] = "HOME=/";                  envp[0] = "HOME=/";
2566                  envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";                  envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
2567                  envp[2] = NULL;                  envp[2] = NULL;
 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0)  
2568                  call_usermodehelper(argv[0], argv, envp, 1);                  call_usermodehelper(argv[0], argv, envp, 1);
 #else  
                 call_usermodehelper(argv[0], argv, envp);  
 #endif  
                 while (!profile_loaded) {  
                         set_current_state(TASK_INTERRUPTIBLE);  
                         schedule_timeout(HZ / 10);  
                 }  
2569          }          }
2570  #ifdef CONFIG_SAKURA  #elif defined(TASK_DEAD)
2571          printk("SAKURA: 1.5.3-pre   2008/01/02\n");          {
2572  #endif                  /* Copied from kernel/kmod.c */
2573  #ifdef CONFIG_TOMOYO                  struct task_struct *task = current;
2574          printk("TOMOYO: 1.5.3-pre   2008/01/02\n");                  pid_t pid = kernel_thread(ccs_run_loader, NULL, 0);
2575  #endif                  sigset_t tmpsig;
2576          //if (!profile_loaded) panic("No profiles loaded. Run policy loader using 'init=' option.\n");                  spin_lock_irq(&task->sighand->siglock);
2577          printk("Mandatory Access Control activated.\n");                  tmpsig = task->blocked;
2578          sbin_init_started = 1;                  siginitsetinv(&task->blocked,
2579                                  sigmask(SIGKILL) | sigmask(SIGSTOP));
2580                    recalc_sigpending();
2581                    spin_unlock_irq(&current->sighand->siglock);
2582                    if (pid >= 0)
2583                            waitpid(pid, NULL, __WCLONE);
2584                    spin_lock_irq(&task->sighand->siglock);
2585                    task->blocked = tmpsig;
2586                    recalc_sigpending();
2587                    spin_unlock_irq(&task->sighand->siglock);
2588            }
2589    #else
2590            {
2591                    /* Copied from kernel/kmod.c */
2592                    struct task_struct *task = current;
2593                    pid_t pid = kernel_thread(ccs_run_loader, NULL, 0);
2594                    sigset_t tmpsig;
2595                    spin_lock_irq(&task->sigmask_lock);
2596                    tmpsig = task->blocked;
2597                    siginitsetinv(&task->blocked,
2598                                  sigmask(SIGKILL) | sigmask(SIGSTOP));
2599                    recalc_sigpending(task);
2600                    spin_unlock_irq(&task->sigmask_lock);
2601                    if (pid >= 0)
2602                            waitpid(pid, NULL, __WCLONE);
2603                    spin_lock_irq(&task->sigmask_lock);
2604                    task->blocked = tmpsig;
2605                    recalc_sigpending(task);
2606                    spin_unlock_irq(&task->sigmask_lock);
2607            }
2608    #endif
2609            printk(KERN_INFO "SAKURA: 1.7.0-pre   2009/05/28\n");
2610            printk(KERN_INFO "TOMOYO: 1.7.0-pre   2009/05/28\n");
2611            printk(KERN_INFO "Mandatory Access Control activated.\n");
2612            ccs_policy_loaded = true;
2613          ccs_log_level = KERN_WARNING;          ccs_log_level = KERN_WARNING;
2614          { /* Check all profiles currently assigned to domains are defined. */          { /* Check all profiles currently assigned to domains are defined. */
2615                  struct domain_info *domain;                  struct ccs_domain_info *domain;
2616                  list1_for_each_entry(domain, &domain_list, list) {                  list_for_each_entry_rcu(domain, &ccs_domain_list, list) {
2617                          const u8 profile = domain->profile;                          const u8 profile = domain->profile;
2618                          if (!profile_ptr[profile]) panic("Profile %u (used by '%s') not defined.\n", profile, domain->domainname->name);                          if (ccs_profile_ptr[profile])
2619                                    continue;
2620                            panic("Profile %u (used by '%s') not defined.\n",
2621                                  profile, domain->domainname->name);
2622                  }                  }
2623          }          }
2624  }  }
2625    
2626    /* Wait queue for ccs_query_list. */
2627    static DECLARE_WAIT_QUEUE_HEAD(ccs_query_wait);
2628    
2629  /*************************  MAC Decision Delayer  *************************/  /* Lock for manipulating ccs_query_list. */
2630    static DEFINE_SPINLOCK(ccs_query_list_lock);
 static DECLARE_WAIT_QUEUE_HEAD(query_wait);  
2631    
2632  static spinlock_t query_lock = SPIN_LOCK_UNLOCKED;  /* Structure for query. */
2633    struct ccs_query_entry {
 struct query_entry {  
2634          struct list_head list;          struct list_head list;
2635          char *query;          char *query;
2636          int query_len;          int query_len;