security: Create file_truncate hook from path_truncate hook
[linux-block.git] / security / apparmor / lsm.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor LSM hooks.
6  *
7  * Copyright (C) 1998-2008 Novell/SUSE
8  * Copyright 2009-2010 Canonical Ltd.
9  */
10
11 #include <linux/lsm_hooks.h>
12 #include <linux/moduleparam.h>
13 #include <linux/mm.h>
14 #include <linux/mman.h>
15 #include <linux/mount.h>
16 #include <linux/namei.h>
17 #include <linux/ptrace.h>
18 #include <linux/ctype.h>
19 #include <linux/sysctl.h>
20 #include <linux/audit.h>
21 #include <linux/user_namespace.h>
22 #include <linux/netfilter_ipv4.h>
23 #include <linux/netfilter_ipv6.h>
24 #include <linux/zlib.h>
25 #include <net/sock.h>
26 #include <uapi/linux/mount.h>
27
28 #include "include/apparmor.h"
29 #include "include/apparmorfs.h"
30 #include "include/audit.h"
31 #include "include/capability.h"
32 #include "include/cred.h"
33 #include "include/file.h"
34 #include "include/ipc.h"
35 #include "include/net.h"
36 #include "include/path.h"
37 #include "include/label.h"
38 #include "include/policy.h"
39 #include "include/policy_ns.h"
40 #include "include/procattr.h"
41 #include "include/mount.h"
42 #include "include/secid.h"
43
44 /* Flag indicating whether initialization completed */
45 int apparmor_initialized;
46
47 union aa_buffer {
48         struct list_head list;
49         char buffer[1];
50 };
51
52 #define RESERVE_COUNT 2
53 static int reserve_count = RESERVE_COUNT;
54 static int buffer_count;
55
56 static LIST_HEAD(aa_global_buffers);
57 static DEFINE_SPINLOCK(aa_buffers_lock);
58
59 /*
60  * LSM hook functions
61  */
62
63 /*
64  * put the associated labels
65  */
66 static void apparmor_cred_free(struct cred *cred)
67 {
68         aa_put_label(cred_label(cred));
69         set_cred_label(cred, NULL);
70 }
71
72 /*
73  * allocate the apparmor part of blank credentials
74  */
75 static int apparmor_cred_alloc_blank(struct cred *cred, gfp_t gfp)
76 {
77         set_cred_label(cred, NULL);
78         return 0;
79 }
80
81 /*
82  * prepare new cred label for modification by prepare_cred block
83  */
84 static int apparmor_cred_prepare(struct cred *new, const struct cred *old,
85                                  gfp_t gfp)
86 {
87         set_cred_label(new, aa_get_newest_label(cred_label(old)));
88         return 0;
89 }
90
91 /*
92  * transfer the apparmor data to a blank set of creds
93  */
94 static void apparmor_cred_transfer(struct cred *new, const struct cred *old)
95 {
96         set_cred_label(new, aa_get_newest_label(cred_label(old)));
97 }
98
99 static void apparmor_task_free(struct task_struct *task)
100 {
101
102         aa_free_task_ctx(task_ctx(task));
103 }
104
105 static int apparmor_task_alloc(struct task_struct *task,
106                                unsigned long clone_flags)
107 {
108         struct aa_task_ctx *new = task_ctx(task);
109
110         aa_dup_task_ctx(new, task_ctx(current));
111
112         return 0;
113 }
114
115 static int apparmor_ptrace_access_check(struct task_struct *child,
116                                         unsigned int mode)
117 {
118         struct aa_label *tracer, *tracee;
119         int error;
120
121         tracer = __begin_current_label_crit_section();
122         tracee = aa_get_task_label(child);
123         error = aa_may_ptrace(tracer, tracee,
124                         (mode & PTRACE_MODE_READ) ? AA_PTRACE_READ
125                                                   : AA_PTRACE_TRACE);
126         aa_put_label(tracee);
127         __end_current_label_crit_section(tracer);
128
129         return error;
130 }
131
132 static int apparmor_ptrace_traceme(struct task_struct *parent)
133 {
134         struct aa_label *tracer, *tracee;
135         int error;
136
137         tracee = __begin_current_label_crit_section();
138         tracer = aa_get_task_label(parent);
139         error = aa_may_ptrace(tracer, tracee, AA_PTRACE_TRACE);
140         aa_put_label(tracer);
141         __end_current_label_crit_section(tracee);
142
143         return error;
144 }
145
146 /* Derived from security/commoncap.c:cap_capget */
147 static int apparmor_capget(struct task_struct *target, kernel_cap_t *effective,
148                            kernel_cap_t *inheritable, kernel_cap_t *permitted)
149 {
150         struct aa_label *label;
151         const struct cred *cred;
152
153         rcu_read_lock();
154         cred = __task_cred(target);
155         label = aa_get_newest_cred_label(cred);
156
157         /*
158          * cap_capget is stacked ahead of this and will
159          * initialize effective and permitted.
160          */
161         if (!unconfined(label)) {
162                 struct aa_profile *profile;
163                 struct label_it i;
164
165                 label_for_each_confined(i, label, profile) {
166                         if (COMPLAIN_MODE(profile))
167                                 continue;
168                         *effective = cap_intersect(*effective,
169                                                    profile->caps.allow);
170                         *permitted = cap_intersect(*permitted,
171                                                    profile->caps.allow);
172                 }
173         }
174         rcu_read_unlock();
175         aa_put_label(label);
176
177         return 0;
178 }
179
180 static int apparmor_capable(const struct cred *cred, struct user_namespace *ns,
181                             int cap, unsigned int opts)
182 {
183         struct aa_label *label;
184         int error = 0;
185
186         label = aa_get_newest_cred_label(cred);
187         if (!unconfined(label))
188                 error = aa_capable(label, cap, opts);
189         aa_put_label(label);
190
191         return error;
192 }
193
194 /**
195  * common_perm - basic common permission check wrapper fn for paths
196  * @op: operation being checked
197  * @path: path to check permission of  (NOT NULL)
198  * @mask: requested permissions mask
199  * @cond: conditional info for the permission request  (NOT NULL)
200  *
201  * Returns: %0 else error code if error or permission denied
202  */
203 static int common_perm(const char *op, const struct path *path, u32 mask,
204                        struct path_cond *cond)
205 {
206         struct aa_label *label;
207         int error = 0;
208
209         label = __begin_current_label_crit_section();
210         if (!unconfined(label))
211                 error = aa_path_perm(op, label, path, 0, mask, cond);
212         __end_current_label_crit_section(label);
213
214         return error;
215 }
216
217 /**
218  * common_perm_cond - common permission wrapper around inode cond
219  * @op: operation being checked
220  * @path: location to check (NOT NULL)
221  * @mask: requested permissions mask
222  *
223  * Returns: %0 else error code if error or permission denied
224  */
225 static int common_perm_cond(const char *op, const struct path *path, u32 mask)
226 {
227         struct user_namespace *mnt_userns = mnt_user_ns(path->mnt);
228         struct path_cond cond = {
229                 i_uid_into_mnt(mnt_userns, d_backing_inode(path->dentry)),
230                 d_backing_inode(path->dentry)->i_mode
231         };
232
233         if (!path_mediated_fs(path->dentry))
234                 return 0;
235
236         return common_perm(op, path, mask, &cond);
237 }
238
239 /**
240  * common_perm_dir_dentry - common permission wrapper when path is dir, dentry
241  * @op: operation being checked
242  * @dir: directory of the dentry  (NOT NULL)
243  * @dentry: dentry to check  (NOT NULL)
244  * @mask: requested permissions mask
245  * @cond: conditional info for the permission request  (NOT NULL)
246  *
247  * Returns: %0 else error code if error or permission denied
248  */
249 static int common_perm_dir_dentry(const char *op, const struct path *dir,
250                                   struct dentry *dentry, u32 mask,
251                                   struct path_cond *cond)
252 {
253         struct path path = { .mnt = dir->mnt, .dentry = dentry };
254
255         return common_perm(op, &path, mask, cond);
256 }
257
258 /**
259  * common_perm_rm - common permission wrapper for operations doing rm
260  * @op: operation being checked
261  * @dir: directory that the dentry is in  (NOT NULL)
262  * @dentry: dentry being rm'd  (NOT NULL)
263  * @mask: requested permission mask
264  *
265  * Returns: %0 else error code if error or permission denied
266  */
267 static int common_perm_rm(const char *op, const struct path *dir,
268                           struct dentry *dentry, u32 mask)
269 {
270         struct inode *inode = d_backing_inode(dentry);
271         struct user_namespace *mnt_userns = mnt_user_ns(dir->mnt);
272         struct path_cond cond = { };
273
274         if (!inode || !path_mediated_fs(dentry))
275                 return 0;
276
277         cond.uid = i_uid_into_mnt(mnt_userns, inode);
278         cond.mode = inode->i_mode;
279
280         return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
281 }
282
283 /**
284  * common_perm_create - common permission wrapper for operations doing create
285  * @op: operation being checked
286  * @dir: directory that dentry will be created in  (NOT NULL)
287  * @dentry: dentry to create   (NOT NULL)
288  * @mask: request permission mask
289  * @mode: created file mode
290  *
291  * Returns: %0 else error code if error or permission denied
292  */
293 static int common_perm_create(const char *op, const struct path *dir,
294                               struct dentry *dentry, u32 mask, umode_t mode)
295 {
296         struct path_cond cond = { current_fsuid(), mode };
297
298         if (!path_mediated_fs(dir->dentry))
299                 return 0;
300
301         return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
302 }
303
304 static int apparmor_path_unlink(const struct path *dir, struct dentry *dentry)
305 {
306         return common_perm_rm(OP_UNLINK, dir, dentry, AA_MAY_DELETE);
307 }
308
309 static int apparmor_path_mkdir(const struct path *dir, struct dentry *dentry,
310                                umode_t mode)
311 {
312         return common_perm_create(OP_MKDIR, dir, dentry, AA_MAY_CREATE,
313                                   S_IFDIR);
314 }
315
316 static int apparmor_path_rmdir(const struct path *dir, struct dentry *dentry)
317 {
318         return common_perm_rm(OP_RMDIR, dir, dentry, AA_MAY_DELETE);
319 }
320
321 static int apparmor_path_mknod(const struct path *dir, struct dentry *dentry,
322                                umode_t mode, unsigned int dev)
323 {
324         return common_perm_create(OP_MKNOD, dir, dentry, AA_MAY_CREATE, mode);
325 }
326
327 static int apparmor_path_truncate(const struct path *path)
328 {
329         return common_perm_cond(OP_TRUNC, path, MAY_WRITE | AA_MAY_SETATTR);
330 }
331
332 static int apparmor_file_truncate(struct file *file)
333 {
334         return apparmor_path_truncate(&file->f_path);
335 }
336
337 static int apparmor_path_symlink(const struct path *dir, struct dentry *dentry,
338                                  const char *old_name)
339 {
340         return common_perm_create(OP_SYMLINK, dir, dentry, AA_MAY_CREATE,
341                                   S_IFLNK);
342 }
343
344 static int apparmor_path_link(struct dentry *old_dentry, const struct path *new_dir,
345                               struct dentry *new_dentry)
346 {
347         struct aa_label *label;
348         int error = 0;
349
350         if (!path_mediated_fs(old_dentry))
351                 return 0;
352
353         label = begin_current_label_crit_section();
354         if (!unconfined(label))
355                 error = aa_path_link(label, old_dentry, new_dir, new_dentry);
356         end_current_label_crit_section(label);
357
358         return error;
359 }
360
361 static int apparmor_path_rename(const struct path *old_dir, struct dentry *old_dentry,
362                                 const struct path *new_dir, struct dentry *new_dentry,
363                                 const unsigned int flags)
364 {
365         struct aa_label *label;
366         int error = 0;
367
368         if (!path_mediated_fs(old_dentry))
369                 return 0;
370         if ((flags & RENAME_EXCHANGE) && !path_mediated_fs(new_dentry))
371                 return 0;
372
373         label = begin_current_label_crit_section();
374         if (!unconfined(label)) {
375                 struct user_namespace *mnt_userns = mnt_user_ns(old_dir->mnt);
376                 struct path old_path = { .mnt = old_dir->mnt,
377                                          .dentry = old_dentry };
378                 struct path new_path = { .mnt = new_dir->mnt,
379                                          .dentry = new_dentry };
380                 struct path_cond cond = {
381                         i_uid_into_mnt(mnt_userns, d_backing_inode(old_dentry)),
382                         d_backing_inode(old_dentry)->i_mode
383                 };
384
385                 if (flags & RENAME_EXCHANGE) {
386                         struct path_cond cond_exchange = {
387                                 i_uid_into_mnt(mnt_userns, d_backing_inode(new_dentry)),
388                                 d_backing_inode(new_dentry)->i_mode
389                         };
390
391                         error = aa_path_perm(OP_RENAME_SRC, label, &new_path, 0,
392                                              MAY_READ | AA_MAY_GETATTR | MAY_WRITE |
393                                              AA_MAY_SETATTR | AA_MAY_DELETE,
394                                              &cond_exchange);
395                         if (!error)
396                                 error = aa_path_perm(OP_RENAME_DEST, label, &old_path,
397                                                      0, MAY_WRITE | AA_MAY_SETATTR |
398                                                      AA_MAY_CREATE, &cond_exchange);
399                 }
400
401                 if (!error)
402                         error = aa_path_perm(OP_RENAME_SRC, label, &old_path, 0,
403                                              MAY_READ | AA_MAY_GETATTR | MAY_WRITE |
404                                              AA_MAY_SETATTR | AA_MAY_DELETE,
405                                              &cond);
406                 if (!error)
407                         error = aa_path_perm(OP_RENAME_DEST, label, &new_path,
408                                              0, MAY_WRITE | AA_MAY_SETATTR |
409                                              AA_MAY_CREATE, &cond);
410
411         }
412         end_current_label_crit_section(label);
413
414         return error;
415 }
416
417 static int apparmor_path_chmod(const struct path *path, umode_t mode)
418 {
419         return common_perm_cond(OP_CHMOD, path, AA_MAY_CHMOD);
420 }
421
422 static int apparmor_path_chown(const struct path *path, kuid_t uid, kgid_t gid)
423 {
424         return common_perm_cond(OP_CHOWN, path, AA_MAY_CHOWN);
425 }
426
427 static int apparmor_inode_getattr(const struct path *path)
428 {
429         return common_perm_cond(OP_GETATTR, path, AA_MAY_GETATTR);
430 }
431
432 static int apparmor_file_open(struct file *file)
433 {
434         struct aa_file_ctx *fctx = file_ctx(file);
435         struct aa_label *label;
436         int error = 0;
437
438         if (!path_mediated_fs(file->f_path.dentry))
439                 return 0;
440
441         /* If in exec, permission is handled by bprm hooks.
442          * Cache permissions granted by the previous exec check, with
443          * implicit read and executable mmap which are required to
444          * actually execute the image.
445          */
446         if (current->in_execve) {
447                 fctx->allow = MAY_EXEC | MAY_READ | AA_EXEC_MMAP;
448                 return 0;
449         }
450
451         label = aa_get_newest_cred_label(file->f_cred);
452         if (!unconfined(label)) {
453                 struct user_namespace *mnt_userns = file_mnt_user_ns(file);
454                 struct inode *inode = file_inode(file);
455                 struct path_cond cond = {
456                         i_uid_into_mnt(mnt_userns, inode),
457                         inode->i_mode
458                 };
459
460                 error = aa_path_perm(OP_OPEN, label, &file->f_path, 0,
461                                      aa_map_file_to_perms(file), &cond);
462                 /* todo cache full allowed permissions set and state */
463                 fctx->allow = aa_map_file_to_perms(file);
464         }
465         aa_put_label(label);
466
467         return error;
468 }
469
470 static int apparmor_file_alloc_security(struct file *file)
471 {
472         struct aa_file_ctx *ctx = file_ctx(file);
473         struct aa_label *label = begin_current_label_crit_section();
474
475         spin_lock_init(&ctx->lock);
476         rcu_assign_pointer(ctx->label, aa_get_label(label));
477         end_current_label_crit_section(label);
478         return 0;
479 }
480
481 static void apparmor_file_free_security(struct file *file)
482 {
483         struct aa_file_ctx *ctx = file_ctx(file);
484
485         if (ctx)
486                 aa_put_label(rcu_access_pointer(ctx->label));
487 }
488
489 static int common_file_perm(const char *op, struct file *file, u32 mask,
490                             bool in_atomic)
491 {
492         struct aa_label *label;
493         int error = 0;
494
495         /* don't reaudit files closed during inheritance */
496         if (file->f_path.dentry == aa_null.dentry)
497                 return -EACCES;
498
499         label = __begin_current_label_crit_section();
500         error = aa_file_perm(op, label, file, mask, in_atomic);
501         __end_current_label_crit_section(label);
502
503         return error;
504 }
505
506 static int apparmor_file_receive(struct file *file)
507 {
508         return common_file_perm(OP_FRECEIVE, file, aa_map_file_to_perms(file),
509                                 false);
510 }
511
512 static int apparmor_file_permission(struct file *file, int mask)
513 {
514         return common_file_perm(OP_FPERM, file, mask, false);
515 }
516
517 static int apparmor_file_lock(struct file *file, unsigned int cmd)
518 {
519         u32 mask = AA_MAY_LOCK;
520
521         if (cmd == F_WRLCK)
522                 mask |= MAY_WRITE;
523
524         return common_file_perm(OP_FLOCK, file, mask, false);
525 }
526
527 static int common_mmap(const char *op, struct file *file, unsigned long prot,
528                        unsigned long flags, bool in_atomic)
529 {
530         int mask = 0;
531
532         if (!file || !file_ctx(file))
533                 return 0;
534
535         if (prot & PROT_READ)
536                 mask |= MAY_READ;
537         /*
538          * Private mappings don't require write perms since they don't
539          * write back to the files
540          */
541         if ((prot & PROT_WRITE) && !(flags & MAP_PRIVATE))
542                 mask |= MAY_WRITE;
543         if (prot & PROT_EXEC)
544                 mask |= AA_EXEC_MMAP;
545
546         return common_file_perm(op, file, mask, in_atomic);
547 }
548
549 static int apparmor_mmap_file(struct file *file, unsigned long reqprot,
550                               unsigned long prot, unsigned long flags)
551 {
552         return common_mmap(OP_FMMAP, file, prot, flags, GFP_ATOMIC);
553 }
554
555 static int apparmor_file_mprotect(struct vm_area_struct *vma,
556                                   unsigned long reqprot, unsigned long prot)
557 {
558         return common_mmap(OP_FMPROT, vma->vm_file, prot,
559                            !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0,
560                            false);
561 }
562
563 static int apparmor_sb_mount(const char *dev_name, const struct path *path,
564                              const char *type, unsigned long flags, void *data)
565 {
566         struct aa_label *label;
567         int error = 0;
568
569         /* Discard magic */
570         if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
571                 flags &= ~MS_MGC_MSK;
572
573         flags &= ~AA_MS_IGNORE_MASK;
574
575         label = __begin_current_label_crit_section();
576         if (!unconfined(label)) {
577                 if (flags & MS_REMOUNT)
578                         error = aa_remount(label, path, flags, data);
579                 else if (flags & MS_BIND)
580                         error = aa_bind_mount(label, path, dev_name, flags);
581                 else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE |
582                                   MS_UNBINDABLE))
583                         error = aa_mount_change_type(label, path, flags);
584                 else if (flags & MS_MOVE)
585                         error = aa_move_mount(label, path, dev_name);
586                 else
587                         error = aa_new_mount(label, dev_name, path, type,
588                                              flags, data);
589         }
590         __end_current_label_crit_section(label);
591
592         return error;
593 }
594
595 static int apparmor_sb_umount(struct vfsmount *mnt, int flags)
596 {
597         struct aa_label *label;
598         int error = 0;
599
600         label = __begin_current_label_crit_section();
601         if (!unconfined(label))
602                 error = aa_umount(label, mnt, flags);
603         __end_current_label_crit_section(label);
604
605         return error;
606 }
607
608 static int apparmor_sb_pivotroot(const struct path *old_path,
609                                  const struct path *new_path)
610 {
611         struct aa_label *label;
612         int error = 0;
613
614         label = aa_get_current_label();
615         if (!unconfined(label))
616                 error = aa_pivotroot(label, old_path, new_path);
617         aa_put_label(label);
618
619         return error;
620 }
621
622 static int apparmor_getprocattr(struct task_struct *task, const char *name,
623                                 char **value)
624 {
625         int error = -ENOENT;
626         /* released below */
627         const struct cred *cred = get_task_cred(task);
628         struct aa_task_ctx *ctx = task_ctx(current);
629         struct aa_label *label = NULL;
630
631         if (strcmp(name, "current") == 0)
632                 label = aa_get_newest_label(cred_label(cred));
633         else if (strcmp(name, "prev") == 0  && ctx->previous)
634                 label = aa_get_newest_label(ctx->previous);
635         else if (strcmp(name, "exec") == 0 && ctx->onexec)
636                 label = aa_get_newest_label(ctx->onexec);
637         else
638                 error = -EINVAL;
639
640         if (label)
641                 error = aa_getprocattr(label, value);
642
643         aa_put_label(label);
644         put_cred(cred);
645
646         return error;
647 }
648
649 static int apparmor_setprocattr(const char *name, void *value,
650                                 size_t size)
651 {
652         char *command, *largs = NULL, *args = value;
653         size_t arg_size;
654         int error;
655         DEFINE_AUDIT_DATA(sa, LSM_AUDIT_DATA_NONE, OP_SETPROCATTR);
656
657         if (size == 0)
658                 return -EINVAL;
659
660         /* AppArmor requires that the buffer must be null terminated atm */
661         if (args[size - 1] != '\0') {
662                 /* null terminate */
663                 largs = args = kmalloc(size + 1, GFP_KERNEL);
664                 if (!args)
665                         return -ENOMEM;
666                 memcpy(args, value, size);
667                 args[size] = '\0';
668         }
669
670         error = -EINVAL;
671         args = strim(args);
672         command = strsep(&args, " ");
673         if (!args)
674                 goto out;
675         args = skip_spaces(args);
676         if (!*args)
677                 goto out;
678
679         arg_size = size - (args - (largs ? largs : (char *) value));
680         if (strcmp(name, "current") == 0) {
681                 if (strcmp(command, "changehat") == 0) {
682                         error = aa_setprocattr_changehat(args, arg_size,
683                                                          AA_CHANGE_NOFLAGS);
684                 } else if (strcmp(command, "permhat") == 0) {
685                         error = aa_setprocattr_changehat(args, arg_size,
686                                                          AA_CHANGE_TEST);
687                 } else if (strcmp(command, "changeprofile") == 0) {
688                         error = aa_change_profile(args, AA_CHANGE_NOFLAGS);
689                 } else if (strcmp(command, "permprofile") == 0) {
690                         error = aa_change_profile(args, AA_CHANGE_TEST);
691                 } else if (strcmp(command, "stack") == 0) {
692                         error = aa_change_profile(args, AA_CHANGE_STACK);
693                 } else
694                         goto fail;
695         } else if (strcmp(name, "exec") == 0) {
696                 if (strcmp(command, "exec") == 0)
697                         error = aa_change_profile(args, AA_CHANGE_ONEXEC);
698                 else if (strcmp(command, "stack") == 0)
699                         error = aa_change_profile(args, (AA_CHANGE_ONEXEC |
700                                                          AA_CHANGE_STACK));
701                 else
702                         goto fail;
703         } else
704                 /* only support the "current" and "exec" process attributes */
705                 goto fail;
706
707         if (!error)
708                 error = size;
709 out:
710         kfree(largs);
711         return error;
712
713 fail:
714         aad(&sa)->label = begin_current_label_crit_section();
715         aad(&sa)->info = name;
716         aad(&sa)->error = error = -EINVAL;
717         aa_audit_msg(AUDIT_APPARMOR_DENIED, &sa, NULL);
718         end_current_label_crit_section(aad(&sa)->label);
719         goto out;
720 }
721
722 /**
723  * apparmor_bprm_committing_creds - do task cleanup on committing new creds
724  * @bprm: binprm for the exec  (NOT NULL)
725  */
726 static void apparmor_bprm_committing_creds(struct linux_binprm *bprm)
727 {
728         struct aa_label *label = aa_current_raw_label();
729         struct aa_label *new_label = cred_label(bprm->cred);
730
731         /* bail out if unconfined or not changing profile */
732         if ((new_label->proxy == label->proxy) ||
733             (unconfined(new_label)))
734                 return;
735
736         aa_inherit_files(bprm->cred, current->files);
737
738         current->pdeath_signal = 0;
739
740         /* reset soft limits and set hard limits for the new label */
741         __aa_transition_rlimits(label, new_label);
742 }
743
744 /**
745  * apparmor_bprm_committed_cred - do cleanup after new creds committed
746  * @bprm: binprm for the exec  (NOT NULL)
747  */
748 static void apparmor_bprm_committed_creds(struct linux_binprm *bprm)
749 {
750         /* clear out temporary/transitional state from the context */
751         aa_clear_task_ctx_trans(task_ctx(current));
752
753         return;
754 }
755
756 static void apparmor_current_getsecid_subj(u32 *secid)
757 {
758         struct aa_label *label = aa_get_current_label();
759         *secid = label->secid;
760         aa_put_label(label);
761 }
762
763 static void apparmor_task_getsecid_obj(struct task_struct *p, u32 *secid)
764 {
765         struct aa_label *label = aa_get_task_label(p);
766         *secid = label->secid;
767         aa_put_label(label);
768 }
769
770 static int apparmor_task_setrlimit(struct task_struct *task,
771                 unsigned int resource, struct rlimit *new_rlim)
772 {
773         struct aa_label *label = __begin_current_label_crit_section();
774         int error = 0;
775
776         if (!unconfined(label))
777                 error = aa_task_setrlimit(label, task, resource, new_rlim);
778         __end_current_label_crit_section(label);
779
780         return error;
781 }
782
783 static int apparmor_task_kill(struct task_struct *target, struct kernel_siginfo *info,
784                               int sig, const struct cred *cred)
785 {
786         struct aa_label *cl, *tl;
787         int error;
788
789         if (cred) {
790                 /*
791                  * Dealing with USB IO specific behavior
792                  */
793                 cl = aa_get_newest_cred_label(cred);
794                 tl = aa_get_task_label(target);
795                 error = aa_may_signal(cl, tl, sig);
796                 aa_put_label(cl);
797                 aa_put_label(tl);
798                 return error;
799         }
800
801         cl = __begin_current_label_crit_section();
802         tl = aa_get_task_label(target);
803         error = aa_may_signal(cl, tl, sig);
804         aa_put_label(tl);
805         __end_current_label_crit_section(cl);
806
807         return error;
808 }
809
810 /**
811  * apparmor_sk_alloc_security - allocate and attach the sk_security field
812  */
813 static int apparmor_sk_alloc_security(struct sock *sk, int family, gfp_t flags)
814 {
815         struct aa_sk_ctx *ctx;
816
817         ctx = kzalloc(sizeof(*ctx), flags);
818         if (!ctx)
819                 return -ENOMEM;
820
821         SK_CTX(sk) = ctx;
822
823         return 0;
824 }
825
826 /**
827  * apparmor_sk_free_security - free the sk_security field
828  */
829 static void apparmor_sk_free_security(struct sock *sk)
830 {
831         struct aa_sk_ctx *ctx = SK_CTX(sk);
832
833         SK_CTX(sk) = NULL;
834         aa_put_label(ctx->label);
835         aa_put_label(ctx->peer);
836         kfree(ctx);
837 }
838
839 /**
840  * apparmor_sk_clone_security - clone the sk_security field
841  */
842 static void apparmor_sk_clone_security(const struct sock *sk,
843                                        struct sock *newsk)
844 {
845         struct aa_sk_ctx *ctx = SK_CTX(sk);
846         struct aa_sk_ctx *new = SK_CTX(newsk);
847
848         if (new->label)
849                 aa_put_label(new->label);
850         new->label = aa_get_label(ctx->label);
851
852         if (new->peer)
853                 aa_put_label(new->peer);
854         new->peer = aa_get_label(ctx->peer);
855 }
856
857 /**
858  * apparmor_socket_create - check perms before creating a new socket
859  */
860 static int apparmor_socket_create(int family, int type, int protocol, int kern)
861 {
862         struct aa_label *label;
863         int error = 0;
864
865         AA_BUG(in_interrupt());
866
867         label = begin_current_label_crit_section();
868         if (!(kern || unconfined(label)))
869                 error = af_select(family,
870                                   create_perm(label, family, type, protocol),
871                                   aa_af_perm(label, OP_CREATE, AA_MAY_CREATE,
872                                              family, type, protocol));
873         end_current_label_crit_section(label);
874
875         return error;
876 }
877
878 /**
879  * apparmor_socket_post_create - setup the per-socket security struct
880  *
881  * Note:
882  * -   kernel sockets currently labeled unconfined but we may want to
883  *     move to a special kernel label
884  * -   socket may not have sk here if created with sock_create_lite or
885  *     sock_alloc. These should be accept cases which will be handled in
886  *     sock_graft.
887  */
888 static int apparmor_socket_post_create(struct socket *sock, int family,
889                                        int type, int protocol, int kern)
890 {
891         struct aa_label *label;
892
893         if (kern) {
894                 label = aa_get_label(kernel_t);
895         } else
896                 label = aa_get_current_label();
897
898         if (sock->sk) {
899                 struct aa_sk_ctx *ctx = SK_CTX(sock->sk);
900
901                 aa_put_label(ctx->label);
902                 ctx->label = aa_get_label(label);
903         }
904         aa_put_label(label);
905
906         return 0;
907 }
908
909 /**
910  * apparmor_socket_bind - check perms before bind addr to socket
911  */
912 static int apparmor_socket_bind(struct socket *sock,
913                                 struct sockaddr *address, int addrlen)
914 {
915         AA_BUG(!sock);
916         AA_BUG(!sock->sk);
917         AA_BUG(!address);
918         AA_BUG(in_interrupt());
919
920         return af_select(sock->sk->sk_family,
921                          bind_perm(sock, address, addrlen),
922                          aa_sk_perm(OP_BIND, AA_MAY_BIND, sock->sk));
923 }
924
925 /**
926  * apparmor_socket_connect - check perms before connecting @sock to @address
927  */
928 static int apparmor_socket_connect(struct socket *sock,
929                                    struct sockaddr *address, int addrlen)
930 {
931         AA_BUG(!sock);
932         AA_BUG(!sock->sk);
933         AA_BUG(!address);
934         AA_BUG(in_interrupt());
935
936         return af_select(sock->sk->sk_family,
937                          connect_perm(sock, address, addrlen),
938                          aa_sk_perm(OP_CONNECT, AA_MAY_CONNECT, sock->sk));
939 }
940
941 /**
942  * apparmor_socket_listen - check perms before allowing listen
943  */
944 static int apparmor_socket_listen(struct socket *sock, int backlog)
945 {
946         AA_BUG(!sock);
947         AA_BUG(!sock->sk);
948         AA_BUG(in_interrupt());
949
950         return af_select(sock->sk->sk_family,
951                          listen_perm(sock, backlog),
952                          aa_sk_perm(OP_LISTEN, AA_MAY_LISTEN, sock->sk));
953 }
954
955 /**
956  * apparmor_socket_accept - check perms before accepting a new connection.
957  *
958  * Note: while @newsock is created and has some information, the accept
959  *       has not been done.
960  */
961 static int apparmor_socket_accept(struct socket *sock, struct socket *newsock)
962 {
963         AA_BUG(!sock);
964         AA_BUG(!sock->sk);
965         AA_BUG(!newsock);
966         AA_BUG(in_interrupt());
967
968         return af_select(sock->sk->sk_family,
969                          accept_perm(sock, newsock),
970                          aa_sk_perm(OP_ACCEPT, AA_MAY_ACCEPT, sock->sk));
971 }
972
973 static int aa_sock_msg_perm(const char *op, u32 request, struct socket *sock,
974                             struct msghdr *msg, int size)
975 {
976         AA_BUG(!sock);
977         AA_BUG(!sock->sk);
978         AA_BUG(!msg);
979         AA_BUG(in_interrupt());
980
981         return af_select(sock->sk->sk_family,
982                          msg_perm(op, request, sock, msg, size),
983                          aa_sk_perm(op, request, sock->sk));
984 }
985
986 /**
987  * apparmor_socket_sendmsg - check perms before sending msg to another socket
988  */
989 static int apparmor_socket_sendmsg(struct socket *sock,
990                                    struct msghdr *msg, int size)
991 {
992         return aa_sock_msg_perm(OP_SENDMSG, AA_MAY_SEND, sock, msg, size);
993 }
994
995 /**
996  * apparmor_socket_recvmsg - check perms before receiving a message
997  */
998 static int apparmor_socket_recvmsg(struct socket *sock,
999                                    struct msghdr *msg, int size, int flags)
1000 {
1001         return aa_sock_msg_perm(OP_RECVMSG, AA_MAY_RECEIVE, sock, msg, size);
1002 }
1003
1004 /* revaliation, get/set attr, shutdown */
1005 static int aa_sock_perm(const char *op, u32 request, struct socket *sock)
1006 {
1007         AA_BUG(!sock);
1008         AA_BUG(!sock->sk);
1009         AA_BUG(in_interrupt());
1010
1011         return af_select(sock->sk->sk_family,
1012                          sock_perm(op, request, sock),
1013                          aa_sk_perm(op, request, sock->sk));
1014 }
1015
1016 /**
1017  * apparmor_socket_getsockname - check perms before getting the local address
1018  */
1019 static int apparmor_socket_getsockname(struct socket *sock)
1020 {
1021         return aa_sock_perm(OP_GETSOCKNAME, AA_MAY_GETATTR, sock);
1022 }
1023
1024 /**
1025  * apparmor_socket_getpeername - check perms before getting remote address
1026  */
1027 static int apparmor_socket_getpeername(struct socket *sock)
1028 {
1029         return aa_sock_perm(OP_GETPEERNAME, AA_MAY_GETATTR, sock);
1030 }
1031
1032 /* revaliation, get/set attr, opt */
1033 static int aa_sock_opt_perm(const char *op, u32 request, struct socket *sock,
1034                             int level, int optname)
1035 {
1036         AA_BUG(!sock);
1037         AA_BUG(!sock->sk);
1038         AA_BUG(in_interrupt());
1039
1040         return af_select(sock->sk->sk_family,
1041                          opt_perm(op, request, sock, level, optname),
1042                          aa_sk_perm(op, request, sock->sk));
1043 }
1044
1045 /**
1046  * apparmor_socket_getsockopt - check perms before getting socket options
1047  */
1048 static int apparmor_socket_getsockopt(struct socket *sock, int level,
1049                                       int optname)
1050 {
1051         return aa_sock_opt_perm(OP_GETSOCKOPT, AA_MAY_GETOPT, sock,
1052                                 level, optname);
1053 }
1054
1055 /**
1056  * apparmor_socket_setsockopt - check perms before setting socket options
1057  */
1058 static int apparmor_socket_setsockopt(struct socket *sock, int level,
1059                                       int optname)
1060 {
1061         return aa_sock_opt_perm(OP_SETSOCKOPT, AA_MAY_SETOPT, sock,
1062                                 level, optname);
1063 }
1064
1065 /**
1066  * apparmor_socket_shutdown - check perms before shutting down @sock conn
1067  */
1068 static int apparmor_socket_shutdown(struct socket *sock, int how)
1069 {
1070         return aa_sock_perm(OP_SHUTDOWN, AA_MAY_SHUTDOWN, sock);
1071 }
1072
1073 #ifdef CONFIG_NETWORK_SECMARK
1074 /**
1075  * apparmor_socket_sock_rcv_skb - check perms before associating skb to sk
1076  *
1077  * Note: can not sleep may be called with locks held
1078  *
1079  * dont want protocol specific in __skb_recv_datagram()
1080  * to deny an incoming connection  socket_sock_rcv_skb()
1081  */
1082 static int apparmor_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
1083 {
1084         struct aa_sk_ctx *ctx = SK_CTX(sk);
1085
1086         if (!skb->secmark)
1087                 return 0;
1088
1089         return apparmor_secmark_check(ctx->label, OP_RECVMSG, AA_MAY_RECEIVE,
1090                                       skb->secmark, sk);
1091 }
1092 #endif
1093
1094
1095 static struct aa_label *sk_peer_label(struct sock *sk)
1096 {
1097         struct aa_sk_ctx *ctx = SK_CTX(sk);
1098
1099         if (ctx->peer)
1100                 return ctx->peer;
1101
1102         return ERR_PTR(-ENOPROTOOPT);
1103 }
1104
1105 /**
1106  * apparmor_socket_getpeersec_stream - get security context of peer
1107  *
1108  * Note: for tcp only valid if using ipsec or cipso on lan
1109  */
1110 static int apparmor_socket_getpeersec_stream(struct socket *sock,
1111                                              char __user *optval,
1112                                              int __user *optlen,
1113                                              unsigned int len)
1114 {
1115         char *name;
1116         int slen, error = 0;
1117         struct aa_label *label;
1118         struct aa_label *peer;
1119
1120         label = begin_current_label_crit_section();
1121         peer = sk_peer_label(sock->sk);
1122         if (IS_ERR(peer)) {
1123                 error = PTR_ERR(peer);
1124                 goto done;
1125         }
1126         slen = aa_label_asxprint(&name, labels_ns(label), peer,
1127                                  FLAG_SHOW_MODE | FLAG_VIEW_SUBNS |
1128                                  FLAG_HIDDEN_UNCONFINED, GFP_KERNEL);
1129         /* don't include terminating \0 in slen, it breaks some apps */
1130         if (slen < 0) {
1131                 error = -ENOMEM;
1132         } else {
1133                 if (slen > len) {
1134                         error = -ERANGE;
1135                 } else if (copy_to_user(optval, name, slen)) {
1136                         error = -EFAULT;
1137                         goto out;
1138                 }
1139                 if (put_user(slen, optlen))
1140                         error = -EFAULT;
1141 out:
1142                 kfree(name);
1143
1144         }
1145
1146 done:
1147         end_current_label_crit_section(label);
1148
1149         return error;
1150 }
1151
1152 /**
1153  * apparmor_socket_getpeersec_dgram - get security label of packet
1154  * @sock: the peer socket
1155  * @skb: packet data
1156  * @secid: pointer to where to put the secid of the packet
1157  *
1158  * Sets the netlabel socket state on sk from parent
1159  */
1160 static int apparmor_socket_getpeersec_dgram(struct socket *sock,
1161                                             struct sk_buff *skb, u32 *secid)
1162
1163 {
1164         /* TODO: requires secid support */
1165         return -ENOPROTOOPT;
1166 }
1167
1168 /**
1169  * apparmor_sock_graft - Initialize newly created socket
1170  * @sk: child sock
1171  * @parent: parent socket
1172  *
1173  * Note: could set off of SOCK_CTX(parent) but need to track inode and we can
1174  *       just set sk security information off of current creating process label
1175  *       Labeling of sk for accept case - probably should be sock based
1176  *       instead of task, because of the case where an implicitly labeled
1177  *       socket is shared by different tasks.
1178  */
1179 static void apparmor_sock_graft(struct sock *sk, struct socket *parent)
1180 {
1181         struct aa_sk_ctx *ctx = SK_CTX(sk);
1182
1183         if (!ctx->label)
1184                 ctx->label = aa_get_current_label();
1185 }
1186
1187 #ifdef CONFIG_NETWORK_SECMARK
1188 static int apparmor_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
1189                                       struct request_sock *req)
1190 {
1191         struct aa_sk_ctx *ctx = SK_CTX(sk);
1192
1193         if (!skb->secmark)
1194                 return 0;
1195
1196         return apparmor_secmark_check(ctx->label, OP_CONNECT, AA_MAY_CONNECT,
1197                                       skb->secmark, sk);
1198 }
1199 #endif
1200
1201 /*
1202  * The cred blob is a pointer to, not an instance of, an aa_task_ctx.
1203  */
1204 struct lsm_blob_sizes apparmor_blob_sizes __lsm_ro_after_init = {
1205         .lbs_cred = sizeof(struct aa_task_ctx *),
1206         .lbs_file = sizeof(struct aa_file_ctx),
1207         .lbs_task = sizeof(struct aa_task_ctx),
1208 };
1209
1210 static struct security_hook_list apparmor_hooks[] __lsm_ro_after_init = {
1211         LSM_HOOK_INIT(ptrace_access_check, apparmor_ptrace_access_check),
1212         LSM_HOOK_INIT(ptrace_traceme, apparmor_ptrace_traceme),
1213         LSM_HOOK_INIT(capget, apparmor_capget),
1214         LSM_HOOK_INIT(capable, apparmor_capable),
1215
1216         LSM_HOOK_INIT(sb_mount, apparmor_sb_mount),
1217         LSM_HOOK_INIT(sb_umount, apparmor_sb_umount),
1218         LSM_HOOK_INIT(sb_pivotroot, apparmor_sb_pivotroot),
1219
1220         LSM_HOOK_INIT(path_link, apparmor_path_link),
1221         LSM_HOOK_INIT(path_unlink, apparmor_path_unlink),
1222         LSM_HOOK_INIT(path_symlink, apparmor_path_symlink),
1223         LSM_HOOK_INIT(path_mkdir, apparmor_path_mkdir),
1224         LSM_HOOK_INIT(path_rmdir, apparmor_path_rmdir),
1225         LSM_HOOK_INIT(path_mknod, apparmor_path_mknod),
1226         LSM_HOOK_INIT(path_rename, apparmor_path_rename),
1227         LSM_HOOK_INIT(path_chmod, apparmor_path_chmod),
1228         LSM_HOOK_INIT(path_chown, apparmor_path_chown),
1229         LSM_HOOK_INIT(path_truncate, apparmor_path_truncate),
1230         LSM_HOOK_INIT(inode_getattr, apparmor_inode_getattr),
1231
1232         LSM_HOOK_INIT(file_open, apparmor_file_open),
1233         LSM_HOOK_INIT(file_receive, apparmor_file_receive),
1234         LSM_HOOK_INIT(file_permission, apparmor_file_permission),
1235         LSM_HOOK_INIT(file_alloc_security, apparmor_file_alloc_security),
1236         LSM_HOOK_INIT(file_free_security, apparmor_file_free_security),
1237         LSM_HOOK_INIT(mmap_file, apparmor_mmap_file),
1238         LSM_HOOK_INIT(file_mprotect, apparmor_file_mprotect),
1239         LSM_HOOK_INIT(file_lock, apparmor_file_lock),
1240         LSM_HOOK_INIT(file_truncate, apparmor_file_truncate),
1241
1242         LSM_HOOK_INIT(getprocattr, apparmor_getprocattr),
1243         LSM_HOOK_INIT(setprocattr, apparmor_setprocattr),
1244
1245         LSM_HOOK_INIT(sk_alloc_security, apparmor_sk_alloc_security),
1246         LSM_HOOK_INIT(sk_free_security, apparmor_sk_free_security),
1247         LSM_HOOK_INIT(sk_clone_security, apparmor_sk_clone_security),
1248
1249         LSM_HOOK_INIT(socket_create, apparmor_socket_create),
1250         LSM_HOOK_INIT(socket_post_create, apparmor_socket_post_create),
1251         LSM_HOOK_INIT(socket_bind, apparmor_socket_bind),
1252         LSM_HOOK_INIT(socket_connect, apparmor_socket_connect),
1253         LSM_HOOK_INIT(socket_listen, apparmor_socket_listen),
1254         LSM_HOOK_INIT(socket_accept, apparmor_socket_accept),
1255         LSM_HOOK_INIT(socket_sendmsg, apparmor_socket_sendmsg),
1256         LSM_HOOK_INIT(socket_recvmsg, apparmor_socket_recvmsg),
1257         LSM_HOOK_INIT(socket_getsockname, apparmor_socket_getsockname),
1258         LSM_HOOK_INIT(socket_getpeername, apparmor_socket_getpeername),
1259         LSM_HOOK_INIT(socket_getsockopt, apparmor_socket_getsockopt),
1260         LSM_HOOK_INIT(socket_setsockopt, apparmor_socket_setsockopt),
1261         LSM_HOOK_INIT(socket_shutdown, apparmor_socket_shutdown),
1262 #ifdef CONFIG_NETWORK_SECMARK
1263         LSM_HOOK_INIT(socket_sock_rcv_skb, apparmor_socket_sock_rcv_skb),
1264 #endif
1265         LSM_HOOK_INIT(socket_getpeersec_stream,
1266                       apparmor_socket_getpeersec_stream),
1267         LSM_HOOK_INIT(socket_getpeersec_dgram,
1268                       apparmor_socket_getpeersec_dgram),
1269         LSM_HOOK_INIT(sock_graft, apparmor_sock_graft),
1270 #ifdef CONFIG_NETWORK_SECMARK
1271         LSM_HOOK_INIT(inet_conn_request, apparmor_inet_conn_request),
1272 #endif
1273
1274         LSM_HOOK_INIT(cred_alloc_blank, apparmor_cred_alloc_blank),
1275         LSM_HOOK_INIT(cred_free, apparmor_cred_free),
1276         LSM_HOOK_INIT(cred_prepare, apparmor_cred_prepare),
1277         LSM_HOOK_INIT(cred_transfer, apparmor_cred_transfer),
1278
1279         LSM_HOOK_INIT(bprm_creds_for_exec, apparmor_bprm_creds_for_exec),
1280         LSM_HOOK_INIT(bprm_committing_creds, apparmor_bprm_committing_creds),
1281         LSM_HOOK_INIT(bprm_committed_creds, apparmor_bprm_committed_creds),
1282
1283         LSM_HOOK_INIT(task_free, apparmor_task_free),
1284         LSM_HOOK_INIT(task_alloc, apparmor_task_alloc),
1285         LSM_HOOK_INIT(current_getsecid_subj, apparmor_current_getsecid_subj),
1286         LSM_HOOK_INIT(task_getsecid_obj, apparmor_task_getsecid_obj),
1287         LSM_HOOK_INIT(task_setrlimit, apparmor_task_setrlimit),
1288         LSM_HOOK_INIT(task_kill, apparmor_task_kill),
1289
1290 #ifdef CONFIG_AUDIT
1291         LSM_HOOK_INIT(audit_rule_init, aa_audit_rule_init),
1292         LSM_HOOK_INIT(audit_rule_known, aa_audit_rule_known),
1293         LSM_HOOK_INIT(audit_rule_match, aa_audit_rule_match),
1294         LSM_HOOK_INIT(audit_rule_free, aa_audit_rule_free),
1295 #endif
1296
1297         LSM_HOOK_INIT(secid_to_secctx, apparmor_secid_to_secctx),
1298         LSM_HOOK_INIT(secctx_to_secid, apparmor_secctx_to_secid),
1299         LSM_HOOK_INIT(release_secctx, apparmor_release_secctx),
1300 };
1301
1302 /*
1303  * AppArmor sysfs module parameters
1304  */
1305
1306 static int param_set_aabool(const char *val, const struct kernel_param *kp);
1307 static int param_get_aabool(char *buffer, const struct kernel_param *kp);
1308 #define param_check_aabool param_check_bool
1309 static const struct kernel_param_ops param_ops_aabool = {
1310         .flags = KERNEL_PARAM_OPS_FL_NOARG,
1311         .set = param_set_aabool,
1312         .get = param_get_aabool
1313 };
1314
1315 static int param_set_aauint(const char *val, const struct kernel_param *kp);
1316 static int param_get_aauint(char *buffer, const struct kernel_param *kp);
1317 #define param_check_aauint param_check_uint
1318 static const struct kernel_param_ops param_ops_aauint = {
1319         .set = param_set_aauint,
1320         .get = param_get_aauint
1321 };
1322
1323 static int param_set_aacompressionlevel(const char *val,
1324                                         const struct kernel_param *kp);
1325 static int param_get_aacompressionlevel(char *buffer,
1326                                         const struct kernel_param *kp);
1327 #define param_check_aacompressionlevel param_check_int
1328 static const struct kernel_param_ops param_ops_aacompressionlevel = {
1329         .set = param_set_aacompressionlevel,
1330         .get = param_get_aacompressionlevel
1331 };
1332
1333 static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp);
1334 static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp);
1335 #define param_check_aalockpolicy param_check_bool
1336 static const struct kernel_param_ops param_ops_aalockpolicy = {
1337         .flags = KERNEL_PARAM_OPS_FL_NOARG,
1338         .set = param_set_aalockpolicy,
1339         .get = param_get_aalockpolicy
1340 };
1341
1342 static int param_set_audit(const char *val, const struct kernel_param *kp);
1343 static int param_get_audit(char *buffer, const struct kernel_param *kp);
1344
1345 static int param_set_mode(const char *val, const struct kernel_param *kp);
1346 static int param_get_mode(char *buffer, const struct kernel_param *kp);
1347
1348 /* Flag values, also controllable via /sys/module/apparmor/parameters
1349  * We define special types as we want to do additional mediation.
1350  */
1351
1352 /* AppArmor global enforcement switch - complain, enforce, kill */
1353 enum profile_mode aa_g_profile_mode = APPARMOR_ENFORCE;
1354 module_param_call(mode, param_set_mode, param_get_mode,
1355                   &aa_g_profile_mode, S_IRUSR | S_IWUSR);
1356
1357 /* whether policy verification hashing is enabled */
1358 bool aa_g_hash_policy = IS_ENABLED(CONFIG_SECURITY_APPARMOR_HASH_DEFAULT);
1359 #ifdef CONFIG_SECURITY_APPARMOR_HASH
1360 module_param_named(hash_policy, aa_g_hash_policy, aabool, S_IRUSR | S_IWUSR);
1361 #endif
1362
1363 /* whether policy exactly as loaded is retained for debug and checkpointing */
1364 bool aa_g_export_binary = IS_ENABLED(CONFIG_SECURITY_APPARMOR_EXPORT_BINARY);
1365 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1366 module_param_named(export_binary, aa_g_export_binary, aabool, 0600);
1367 #endif
1368
1369 /* policy loaddata compression level */
1370 int aa_g_rawdata_compression_level = Z_DEFAULT_COMPRESSION;
1371 module_param_named(rawdata_compression_level, aa_g_rawdata_compression_level,
1372                    aacompressionlevel, 0400);
1373
1374 /* Debug mode */
1375 bool aa_g_debug = IS_ENABLED(CONFIG_SECURITY_APPARMOR_DEBUG_MESSAGES);
1376 module_param_named(debug, aa_g_debug, aabool, S_IRUSR | S_IWUSR);
1377
1378 /* Audit mode */
1379 enum audit_mode aa_g_audit;
1380 module_param_call(audit, param_set_audit, param_get_audit,
1381                   &aa_g_audit, S_IRUSR | S_IWUSR);
1382
1383 /* Determines if audit header is included in audited messages.  This
1384  * provides more context if the audit daemon is not running
1385  */
1386 bool aa_g_audit_header = true;
1387 module_param_named(audit_header, aa_g_audit_header, aabool,
1388                    S_IRUSR | S_IWUSR);
1389
1390 /* lock out loading/removal of policy
1391  * TODO: add in at boot loading of policy, which is the only way to
1392  *       load policy, if lock_policy is set
1393  */
1394 bool aa_g_lock_policy;
1395 module_param_named(lock_policy, aa_g_lock_policy, aalockpolicy,
1396                    S_IRUSR | S_IWUSR);
1397
1398 /* Syscall logging mode */
1399 bool aa_g_logsyscall;
1400 module_param_named(logsyscall, aa_g_logsyscall, aabool, S_IRUSR | S_IWUSR);
1401
1402 /* Maximum pathname length before accesses will start getting rejected */
1403 unsigned int aa_g_path_max = 2 * PATH_MAX;
1404 module_param_named(path_max, aa_g_path_max, aauint, S_IRUSR);
1405
1406 /* Determines how paranoid loading of policy is and how much verification
1407  * on the loaded policy is done.
1408  * DEPRECATED: read only as strict checking of load is always done now
1409  * that none root users (user namespaces) can load policy.
1410  */
1411 bool aa_g_paranoid_load = IS_ENABLED(CONFIG_SECURITY_APPARMOR_PARANOID_LOAD);
1412 module_param_named(paranoid_load, aa_g_paranoid_load, aabool, S_IRUGO);
1413
1414 static int param_get_aaintbool(char *buffer, const struct kernel_param *kp);
1415 static int param_set_aaintbool(const char *val, const struct kernel_param *kp);
1416 #define param_check_aaintbool param_check_int
1417 static const struct kernel_param_ops param_ops_aaintbool = {
1418         .set = param_set_aaintbool,
1419         .get = param_get_aaintbool
1420 };
1421 /* Boot time disable flag */
1422 static int apparmor_enabled __lsm_ro_after_init = 1;
1423 module_param_named(enabled, apparmor_enabled, aaintbool, 0444);
1424
1425 static int __init apparmor_enabled_setup(char *str)
1426 {
1427         unsigned long enabled;
1428         int error = kstrtoul(str, 0, &enabled);
1429         if (!error)
1430                 apparmor_enabled = enabled ? 1 : 0;
1431         return 1;
1432 }
1433
1434 __setup("apparmor=", apparmor_enabled_setup);
1435
1436 /* set global flag turning off the ability to load policy */
1437 static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp)
1438 {
1439         if (!apparmor_enabled)
1440                 return -EINVAL;
1441         if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1442                 return -EPERM;
1443         return param_set_bool(val, kp);
1444 }
1445
1446 static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp)
1447 {
1448         if (!apparmor_enabled)
1449                 return -EINVAL;
1450         if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1451                 return -EPERM;
1452         return param_get_bool(buffer, kp);
1453 }
1454
1455 static int param_set_aabool(const char *val, const struct kernel_param *kp)
1456 {
1457         if (!apparmor_enabled)
1458                 return -EINVAL;
1459         if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1460                 return -EPERM;
1461         return param_set_bool(val, kp);
1462 }
1463
1464 static int param_get_aabool(char *buffer, const struct kernel_param *kp)
1465 {
1466         if (!apparmor_enabled)
1467                 return -EINVAL;
1468         if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1469                 return -EPERM;
1470         return param_get_bool(buffer, kp);
1471 }
1472
1473 static int param_set_aauint(const char *val, const struct kernel_param *kp)
1474 {
1475         int error;
1476
1477         if (!apparmor_enabled)
1478                 return -EINVAL;
1479         /* file is ro but enforce 2nd line check */
1480         if (apparmor_initialized)
1481                 return -EPERM;
1482
1483         error = param_set_uint(val, kp);
1484         aa_g_path_max = max_t(uint32_t, aa_g_path_max, sizeof(union aa_buffer));
1485         pr_info("AppArmor: buffer size set to %d bytes\n", aa_g_path_max);
1486
1487         return error;
1488 }
1489
1490 static int param_get_aauint(char *buffer, const struct kernel_param *kp)
1491 {
1492         if (!apparmor_enabled)
1493                 return -EINVAL;
1494         if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1495                 return -EPERM;
1496         return param_get_uint(buffer, kp);
1497 }
1498
1499 /* Can only be set before AppArmor is initialized (i.e. on boot cmdline). */
1500 static int param_set_aaintbool(const char *val, const struct kernel_param *kp)
1501 {
1502         struct kernel_param kp_local;
1503         bool value;
1504         int error;
1505
1506         if (apparmor_initialized)
1507                 return -EPERM;
1508
1509         /* Create local copy, with arg pointing to bool type. */
1510         value = !!*((int *)kp->arg);
1511         memcpy(&kp_local, kp, sizeof(kp_local));
1512         kp_local.arg = &value;
1513
1514         error = param_set_bool(val, &kp_local);
1515         if (!error)
1516                 *((int *)kp->arg) = *((bool *)kp_local.arg);
1517         return error;
1518 }
1519
1520 /*
1521  * To avoid changing /sys/module/apparmor/parameters/enabled from Y/N to
1522  * 1/0, this converts the "int that is actually bool" back to bool for
1523  * display in the /sys filesystem, while keeping it "int" for the LSM
1524  * infrastructure.
1525  */
1526 static int param_get_aaintbool(char *buffer, const struct kernel_param *kp)
1527 {
1528         struct kernel_param kp_local;
1529         bool value;
1530
1531         /* Create local copy, with arg pointing to bool type. */
1532         value = !!*((int *)kp->arg);
1533         memcpy(&kp_local, kp, sizeof(kp_local));
1534         kp_local.arg = &value;
1535
1536         return param_get_bool(buffer, &kp_local);
1537 }
1538
1539 static int param_set_aacompressionlevel(const char *val,
1540                                         const struct kernel_param *kp)
1541 {
1542         int error;
1543
1544         if (!apparmor_enabled)
1545                 return -EINVAL;
1546         if (apparmor_initialized)
1547                 return -EPERM;
1548
1549         error = param_set_int(val, kp);
1550
1551         aa_g_rawdata_compression_level = clamp(aa_g_rawdata_compression_level,
1552                                                Z_NO_COMPRESSION,
1553                                                Z_BEST_COMPRESSION);
1554         pr_info("AppArmor: policy rawdata compression level set to %u\n",
1555                 aa_g_rawdata_compression_level);
1556
1557         return error;
1558 }
1559
1560 static int param_get_aacompressionlevel(char *buffer,
1561                                         const struct kernel_param *kp)
1562 {
1563         if (!apparmor_enabled)
1564                 return -EINVAL;
1565         if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1566                 return -EPERM;
1567         return param_get_int(buffer, kp);
1568 }
1569
1570 static int param_get_audit(char *buffer, const struct kernel_param *kp)
1571 {
1572         if (!apparmor_enabled)
1573                 return -EINVAL;
1574         if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1575                 return -EPERM;
1576         return sprintf(buffer, "%s", audit_mode_names[aa_g_audit]);
1577 }
1578
1579 static int param_set_audit(const char *val, const struct kernel_param *kp)
1580 {
1581         int i;
1582
1583         if (!apparmor_enabled)
1584                 return -EINVAL;
1585         if (!val)
1586                 return -EINVAL;
1587         if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1588                 return -EPERM;
1589
1590         i = match_string(audit_mode_names, AUDIT_MAX_INDEX, val);
1591         if (i < 0)
1592                 return -EINVAL;
1593
1594         aa_g_audit = i;
1595         return 0;
1596 }
1597
1598 static int param_get_mode(char *buffer, const struct kernel_param *kp)
1599 {
1600         if (!apparmor_enabled)
1601                 return -EINVAL;
1602         if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1603                 return -EPERM;
1604
1605         return sprintf(buffer, "%s", aa_profile_mode_names[aa_g_profile_mode]);
1606 }
1607
1608 static int param_set_mode(const char *val, const struct kernel_param *kp)
1609 {
1610         int i;
1611
1612         if (!apparmor_enabled)
1613                 return -EINVAL;
1614         if (!val)
1615                 return -EINVAL;
1616         if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1617                 return -EPERM;
1618
1619         i = match_string(aa_profile_mode_names, APPARMOR_MODE_NAMES_MAX_INDEX,
1620                          val);
1621         if (i < 0)
1622                 return -EINVAL;
1623
1624         aa_g_profile_mode = i;
1625         return 0;
1626 }
1627
1628 char *aa_get_buffer(bool in_atomic)
1629 {
1630         union aa_buffer *aa_buf;
1631         bool try_again = true;
1632         gfp_t flags = (GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
1633
1634 retry:
1635         spin_lock(&aa_buffers_lock);
1636         if (buffer_count > reserve_count ||
1637             (in_atomic && !list_empty(&aa_global_buffers))) {
1638                 aa_buf = list_first_entry(&aa_global_buffers, union aa_buffer,
1639                                           list);
1640                 list_del(&aa_buf->list);
1641                 buffer_count--;
1642                 spin_unlock(&aa_buffers_lock);
1643                 return &aa_buf->buffer[0];
1644         }
1645         if (in_atomic) {
1646                 /*
1647                  * out of reserve buffers and in atomic context so increase
1648                  * how many buffers to keep in reserve
1649                  */
1650                 reserve_count++;
1651                 flags = GFP_ATOMIC;
1652         }
1653         spin_unlock(&aa_buffers_lock);
1654
1655         if (!in_atomic)
1656                 might_sleep();
1657         aa_buf = kmalloc(aa_g_path_max, flags);
1658         if (!aa_buf) {
1659                 if (try_again) {
1660                         try_again = false;
1661                         goto retry;
1662                 }
1663                 pr_warn_once("AppArmor: Failed to allocate a memory buffer.\n");
1664                 return NULL;
1665         }
1666         return &aa_buf->buffer[0];
1667 }
1668
1669 void aa_put_buffer(char *buf)
1670 {
1671         union aa_buffer *aa_buf;
1672
1673         if (!buf)
1674                 return;
1675         aa_buf = container_of(buf, union aa_buffer, buffer[0]);
1676
1677         spin_lock(&aa_buffers_lock);
1678         list_add(&aa_buf->list, &aa_global_buffers);
1679         buffer_count++;
1680         spin_unlock(&aa_buffers_lock);
1681 }
1682
1683 /*
1684  * AppArmor init functions
1685  */
1686
1687 /**
1688  * set_init_ctx - set a task context and profile on the first task.
1689  *
1690  * TODO: allow setting an alternate profile than unconfined
1691  */
1692 static int __init set_init_ctx(void)
1693 {
1694         struct cred *cred = (__force struct cred *)current->real_cred;
1695
1696         set_cred_label(cred, aa_get_label(ns_unconfined(root_ns)));
1697
1698         return 0;
1699 }
1700
1701 static void destroy_buffers(void)
1702 {
1703         union aa_buffer *aa_buf;
1704
1705         spin_lock(&aa_buffers_lock);
1706         while (!list_empty(&aa_global_buffers)) {
1707                 aa_buf = list_first_entry(&aa_global_buffers, union aa_buffer,
1708                                          list);
1709                 list_del(&aa_buf->list);
1710                 spin_unlock(&aa_buffers_lock);
1711                 kfree(aa_buf);
1712                 spin_lock(&aa_buffers_lock);
1713         }
1714         spin_unlock(&aa_buffers_lock);
1715 }
1716
1717 static int __init alloc_buffers(void)
1718 {
1719         union aa_buffer *aa_buf;
1720         int i, num;
1721
1722         /*
1723          * A function may require two buffers at once. Usually the buffers are
1724          * used for a short period of time and are shared. On UP kernel buffers
1725          * two should be enough, with more CPUs it is possible that more
1726          * buffers will be used simultaneously. The preallocated pool may grow.
1727          * This preallocation has also the side-effect that AppArmor will be
1728          * disabled early at boot if aa_g_path_max is extremly high.
1729          */
1730         if (num_online_cpus() > 1)
1731                 num = 4 + RESERVE_COUNT;
1732         else
1733                 num = 2 + RESERVE_COUNT;
1734
1735         for (i = 0; i < num; i++) {
1736
1737                 aa_buf = kmalloc(aa_g_path_max, GFP_KERNEL |
1738                                  __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
1739                 if (!aa_buf) {
1740                         destroy_buffers();
1741                         return -ENOMEM;
1742                 }
1743                 aa_put_buffer(&aa_buf->buffer[0]);
1744         }
1745         return 0;
1746 }
1747
1748 #ifdef CONFIG_SYSCTL
1749 static int apparmor_dointvec(struct ctl_table *table, int write,
1750                              void *buffer, size_t *lenp, loff_t *ppos)
1751 {
1752         if (!aa_current_policy_admin_capable(NULL))
1753                 return -EPERM;
1754         if (!apparmor_enabled)
1755                 return -EINVAL;
1756
1757         return proc_dointvec(table, write, buffer, lenp, ppos);
1758 }
1759
1760 static struct ctl_path apparmor_sysctl_path[] = {
1761         { .procname = "kernel", },
1762         { }
1763 };
1764
1765 static struct ctl_table apparmor_sysctl_table[] = {
1766         {
1767                 .procname       = "unprivileged_userns_apparmor_policy",
1768                 .data           = &unprivileged_userns_apparmor_policy,
1769                 .maxlen         = sizeof(int),
1770                 .mode           = 0600,
1771                 .proc_handler   = apparmor_dointvec,
1772         },
1773         {
1774                 .procname       = "apparmor_display_secid_mode",
1775                 .data           = &apparmor_display_secid_mode,
1776                 .maxlen         = sizeof(int),
1777                 .mode           = 0600,
1778                 .proc_handler   = apparmor_dointvec,
1779         },
1780
1781         { }
1782 };
1783
1784 static int __init apparmor_init_sysctl(void)
1785 {
1786         return register_sysctl_paths(apparmor_sysctl_path,
1787                                      apparmor_sysctl_table) ? 0 : -ENOMEM;
1788 }
1789 #else
1790 static inline int apparmor_init_sysctl(void)
1791 {
1792         return 0;
1793 }
1794 #endif /* CONFIG_SYSCTL */
1795
1796 #if defined(CONFIG_NETFILTER) && defined(CONFIG_NETWORK_SECMARK)
1797 static unsigned int apparmor_ip_postroute(void *priv,
1798                                           struct sk_buff *skb,
1799                                           const struct nf_hook_state *state)
1800 {
1801         struct aa_sk_ctx *ctx;
1802         struct sock *sk;
1803
1804         if (!skb->secmark)
1805                 return NF_ACCEPT;
1806
1807         sk = skb_to_full_sk(skb);
1808         if (sk == NULL)
1809                 return NF_ACCEPT;
1810
1811         ctx = SK_CTX(sk);
1812         if (!apparmor_secmark_check(ctx->label, OP_SENDMSG, AA_MAY_SEND,
1813                                     skb->secmark, sk))
1814                 return NF_ACCEPT;
1815
1816         return NF_DROP_ERR(-ECONNREFUSED);
1817
1818 }
1819
1820 static const struct nf_hook_ops apparmor_nf_ops[] = {
1821         {
1822                 .hook =         apparmor_ip_postroute,
1823                 .pf =           NFPROTO_IPV4,
1824                 .hooknum =      NF_INET_POST_ROUTING,
1825                 .priority =     NF_IP_PRI_SELINUX_FIRST,
1826         },
1827 #if IS_ENABLED(CONFIG_IPV6)
1828         {
1829                 .hook =         apparmor_ip_postroute,
1830                 .pf =           NFPROTO_IPV6,
1831                 .hooknum =      NF_INET_POST_ROUTING,
1832                 .priority =     NF_IP6_PRI_SELINUX_FIRST,
1833         },
1834 #endif
1835 };
1836
1837 static int __net_init apparmor_nf_register(struct net *net)
1838 {
1839         return nf_register_net_hooks(net, apparmor_nf_ops,
1840                                     ARRAY_SIZE(apparmor_nf_ops));
1841 }
1842
1843 static void __net_exit apparmor_nf_unregister(struct net *net)
1844 {
1845         nf_unregister_net_hooks(net, apparmor_nf_ops,
1846                                 ARRAY_SIZE(apparmor_nf_ops));
1847 }
1848
1849 static struct pernet_operations apparmor_net_ops = {
1850         .init = apparmor_nf_register,
1851         .exit = apparmor_nf_unregister,
1852 };
1853
1854 static int __init apparmor_nf_ip_init(void)
1855 {
1856         int err;
1857
1858         if (!apparmor_enabled)
1859                 return 0;
1860
1861         err = register_pernet_subsys(&apparmor_net_ops);
1862         if (err)
1863                 panic("Apparmor: register_pernet_subsys: error %d\n", err);
1864
1865         return 0;
1866 }
1867 __initcall(apparmor_nf_ip_init);
1868 #endif
1869
1870 static int __init apparmor_init(void)
1871 {
1872         int error;
1873
1874         error = aa_setup_dfa_engine();
1875         if (error) {
1876                 AA_ERROR("Unable to setup dfa engine\n");
1877                 goto alloc_out;
1878         }
1879
1880         error = aa_alloc_root_ns();
1881         if (error) {
1882                 AA_ERROR("Unable to allocate default profile namespace\n");
1883                 goto alloc_out;
1884         }
1885
1886         error = apparmor_init_sysctl();
1887         if (error) {
1888                 AA_ERROR("Unable to register sysctls\n");
1889                 goto alloc_out;
1890
1891         }
1892
1893         error = alloc_buffers();
1894         if (error) {
1895                 AA_ERROR("Unable to allocate work buffers\n");
1896                 goto alloc_out;
1897         }
1898
1899         error = set_init_ctx();
1900         if (error) {
1901                 AA_ERROR("Failed to set context on init task\n");
1902                 aa_free_root_ns();
1903                 goto buffers_out;
1904         }
1905         security_add_hooks(apparmor_hooks, ARRAY_SIZE(apparmor_hooks),
1906                                 "apparmor");
1907
1908         /* Report that AppArmor successfully initialized */
1909         apparmor_initialized = 1;
1910         if (aa_g_profile_mode == APPARMOR_COMPLAIN)
1911                 aa_info_message("AppArmor initialized: complain mode enabled");
1912         else if (aa_g_profile_mode == APPARMOR_KILL)
1913                 aa_info_message("AppArmor initialized: kill mode enabled");
1914         else
1915                 aa_info_message("AppArmor initialized");
1916
1917         return error;
1918
1919 buffers_out:
1920         destroy_buffers();
1921 alloc_out:
1922         aa_destroy_aafs();
1923         aa_teardown_dfa_engine();
1924
1925         apparmor_enabled = false;
1926         return error;
1927 }
1928
1929 DEFINE_LSM(apparmor) = {
1930         .name = "apparmor",
1931         .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
1932         .enabled = &apparmor_enabled,
1933         .blobs = &apparmor_blob_sizes,
1934         .init = apparmor_init,
1935 };