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