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