]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/lsm/apparmor.c
apparmor: allow various remount,bind options
[mirror_lxc.git] / src / lxc / lsm / apparmor.c
1 /* apparmor
2 *
3 * Copyright © 2012 Serge Hallyn <serge.hallyn@ubuntu.com>.
4 * Copyright © 2012 Canonical Ltd.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21 #ifndef _GNU_SOURCE
22 #define _GNU_SOURCE 1
23 #endif
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <sys/mount.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <sys/vfs.h>
31 #include <unistd.h>
32
33 #include "caps.h"
34 #include "conf.h"
35 #include "config.h"
36 #include "initutils.h"
37 #include "log.h"
38 #include "lsm.h"
39 #include "parse.h"
40 #include "raw_syscalls.h"
41 #include "utils.h"
42
43 lxc_log_define(apparmor, lsm);
44
45 /* set by lsm_apparmor_drv_init if true */
46 static int aa_enabled = 0;
47 static bool aa_parser_available = false;
48 static bool aa_supports_unix = false;
49 static bool aa_can_stack = false;
50 static bool aa_is_stacked = false;
51 static bool aa_admin = false;
52
53 static int mount_features_enabled = 0;
54
55 #define AA_DEF_PROFILE "lxc-container-default"
56 #define AA_DEF_PROFILE_CGNS "lxc-container-default-cgns"
57 #define AA_MOUNT_RESTR "/sys/kernel/security/apparmor/features/mount/mask"
58 #define AA_ENABLED_FILE "/sys/module/apparmor/parameters/enabled"
59 #define AA_UNCHANGED "unchanged"
60 #define AA_GENERATED "generated"
61
62 #define AA_CMD_LOAD 'r'
63 #define AA_CMD_UNLOAD 'R'
64 #define AA_CMD_PARSE 'Q'
65
66 static const char AA_PROFILE_BASE[] =
67 " ### Base profile\n"
68 " capability,\n"
69 " dbus,\n"
70 " file,\n"
71 " network,\n"
72 " umount,\n"
73 "\n"
74 " # Allow us to receive signals from anywhere.\n"
75 " signal (receive),\n"
76 "\n"
77 " # Allow us to send signals to ourselves\n"
78 " signal peer=@{profile_name},\n"
79 "\n"
80 " # Allow other processes to read our /proc entries, futexes, perf tracing and\n"
81 " # kcmp for now (they will need 'read' in the first place). Administrators can\n"
82 " # override with:\n"
83 " # deny ptrace (readby) ...\n"
84 " ptrace (readby),\n"
85 "\n"
86 " # Allow other processes to trace us by default (they will need 'trace' in\n"
87 " # the first place). Administrators can override with:\n"
88 " # deny ptrace (tracedby) ...\n"
89 " ptrace (tracedby),\n"
90 "\n"
91 " # Allow us to ptrace ourselves\n"
92 " ptrace peer=@{profile_name},\n"
93 "\n"
94 " # ignore DENIED message on / remount\n"
95 " deny mount options=(ro, remount) -> /,\n"
96 " deny mount options=(ro, remount, silent) -> /,\n"
97 "\n"
98 " # allow tmpfs mounts everywhere\n"
99 " mount fstype=tmpfs,\n"
100 "\n"
101 " # allow hugetlbfs mounts everywhere\n"
102 " mount fstype=hugetlbfs,\n"
103 "\n"
104 " # allow mqueue mounts everywhere\n"
105 " mount fstype=mqueue,\n"
106 "\n"
107 " # allow fuse mounts everywhere\n"
108 " mount fstype=fuse,\n"
109 " mount fstype=fuse.*,\n"
110 "\n"
111 " # deny access under /proc/bus to avoid e.g. messing with pci devices directly\n"
112 " deny @{PROC}/bus/** wklx,\n"
113 "\n"
114 " # deny writes in /proc/sys/fs but allow binfmt_misc to be mounted\n"
115 " mount fstype=binfmt_misc -> /proc/sys/fs/binfmt_misc/,\n"
116 " deny @{PROC}/sys/fs/** wklx,\n"
117 "\n"
118 " # allow efivars to be mounted, writing to it will be blocked though\n"
119 " mount fstype=efivarfs -> /sys/firmware/efi/efivars/,\n"
120 "\n"
121 " # block some other dangerous paths\n"
122 " deny @{PROC}/kcore rwklx,\n"
123 " deny @{PROC}/sysrq-trigger rwklx,\n"
124 "\n"
125 " # deny writes in /sys except for /sys/fs/cgroup, also allow\n"
126 " # fusectl, securityfs and debugfs to be mounted there (read-only)\n"
127 " mount fstype=fusectl -> /sys/fs/fuse/connections/,\n"
128 " mount fstype=securityfs -> /sys/kernel/security/,\n"
129 " mount fstype=debugfs -> /sys/kernel/debug/,\n"
130 " deny mount fstype=debugfs -> /var/lib/ureadahead/debugfs/,\n"
131 " mount fstype=proc -> /proc/,\n"
132 " mount fstype=sysfs -> /sys/,\n"
133 " mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,\n"
134 " deny /sys/firmware/efi/efivars/** rwklx,\n"
135 " # note, /sys/kernel/security/** handled below\n"
136 " mount options=(ro, nosuid, nodev, noexec, remount, strictatime) -> /sys/fs/cgroup/,\n"
137 "\n"
138 " # deny reads from debugfs\n"
139 " deny /sys/kernel/debug/{,**} rwklx,\n"
140 "\n"
141 " # allow paths to be made slave, shared, private or unbindable\n"
142 " # FIXME: This currently doesn't work due to the apparmor parser treating those as allowing all mounts.\n"
143 "# mount options=(rw,make-slave) -> **,\n"
144 "# mount options=(rw,make-rslave) -> **,\n"
145 "# mount options=(rw,make-shared) -> **,\n"
146 "# mount options=(rw,make-rshared) -> **,\n"
147 "# mount options=(rw,make-private) -> **,\n"
148 "# mount options=(rw,make-rprivate) -> **,\n"
149 "# mount options=(rw,make-unbindable) -> **,\n"
150 "# mount options=(rw,make-runbindable) -> **,\n"
151 "\n"
152 " # allow bind-mounts of anything except /proc, /sys and /dev\n"
153 " mount options=(rw,bind) /[^spd]*{,/**},\n"
154 " mount options=(rw,bind) /d[^e]*{,/**},\n"
155 " mount options=(rw,bind) /de[^v]*{,/**},\n"
156 " mount options=(rw,bind) /dev/.[^l]*{,/**},\n"
157 " mount options=(rw,bind) /dev/.l[^x]*{,/**},\n"
158 " mount options=(rw,bind) /dev/.lx[^c]*{,/**},\n"
159 " mount options=(rw,bind) /dev/.lxc?*{,/**},\n"
160 " mount options=(rw,bind) /dev/[^.]*{,/**},\n"
161 " mount options=(rw,bind) /dev?*{,/**},\n"
162 " mount options=(rw,bind) /p[^r]*{,/**},\n"
163 " mount options=(rw,bind) /pr[^o]*{,/**},\n"
164 " mount options=(rw,bind) /pro[^c]*{,/**},\n"
165 " mount options=(rw,bind) /proc?*{,/**},\n"
166 " mount options=(rw,bind) /s[^y]*{,/**},\n"
167 " mount options=(rw,bind) /sy[^s]*{,/**},\n"
168 " mount options=(rw,bind) /sys?*{,/**},\n"
169 "\n"
170 " # allow various ro-bind-*re*-mounts\n"
171 " mount options=(ro,remount,bind),\n"
172 " mount options=(ro,remount,bind,nosuid),\n"
173 " mount options=(ro,remount,bind,noexec),\n"
174 " mount options=(ro,remount,bind,nodev),\n"
175 " mount options=(ro,remount,bind,nosuid,noexec),\n"
176 " mount options=(ro,remount,bind,noexec,nodev),\n"
177 " mount options=(ro,remount,bind,nodev,nosuid),\n"
178 " mount options=(ro,remount,bind,nosuid,noexec,nodev),\n"
179 "\n"
180 " # allow moving mounts except for /proc, /sys and /dev\n"
181 " mount options=(rw,move) /[^spd]*{,/**},\n"
182 " mount options=(rw,move) /d[^e]*{,/**},\n"
183 " mount options=(rw,move) /de[^v]*{,/**},\n"
184 " mount options=(rw,move) /dev/.[^l]*{,/**},\n"
185 " mount options=(rw,move) /dev/.l[^x]*{,/**},\n"
186 " mount options=(rw,move) /dev/.lx[^c]*{,/**},\n"
187 " mount options=(rw,move) /dev/.lxc?*{,/**},\n"
188 " mount options=(rw,move) /dev/[^.]*{,/**},\n"
189 " mount options=(rw,move) /dev?*{,/**},\n"
190 " mount options=(rw,move) /p[^r]*{,/**},\n"
191 " mount options=(rw,move) /pr[^o]*{,/**},\n"
192 " mount options=(rw,move) /pro[^c]*{,/**},\n"
193 " mount options=(rw,move) /proc?*{,/**},\n"
194 " mount options=(rw,move) /s[^y]*{,/**},\n"
195 " mount options=(rw,move) /sy[^s]*{,/**},\n"
196 " mount options=(rw,move) /sys?*{,/**},\n"
197 "\n"
198 " # generated by: lxc-generate-aa-rules.py container-rules.base\n"
199 " deny /proc/sys/[^kn]*{,/**} wklx,\n"
200 " deny /proc/sys/k[^e]*{,/**} wklx,\n"
201 " deny /proc/sys/ke[^r]*{,/**} wklx,\n"
202 " deny /proc/sys/ker[^n]*{,/**} wklx,\n"
203 " deny /proc/sys/kern[^e]*{,/**} wklx,\n"
204 " deny /proc/sys/kerne[^l]*{,/**} wklx,\n"
205 " deny /proc/sys/kernel/[^smhd]*{,/**} wklx,\n"
206 " deny /proc/sys/kernel/d[^o]*{,/**} wklx,\n"
207 " deny /proc/sys/kernel/do[^m]*{,/**} wklx,\n"
208 " deny /proc/sys/kernel/dom[^a]*{,/**} wklx,\n"
209 " deny /proc/sys/kernel/doma[^i]*{,/**} wklx,\n"
210 " deny /proc/sys/kernel/domai[^n]*{,/**} wklx,\n"
211 " deny /proc/sys/kernel/domain[^n]*{,/**} wklx,\n"
212 " deny /proc/sys/kernel/domainn[^a]*{,/**} wklx,\n"
213 " deny /proc/sys/kernel/domainna[^m]*{,/**} wklx,\n"
214 " deny /proc/sys/kernel/domainnam[^e]*{,/**} wklx,\n"
215 " deny /proc/sys/kernel/domainname?*{,/**} wklx,\n"
216 " deny /proc/sys/kernel/h[^o]*{,/**} wklx,\n"
217 " deny /proc/sys/kernel/ho[^s]*{,/**} wklx,\n"
218 " deny /proc/sys/kernel/hos[^t]*{,/**} wklx,\n"
219 " deny /proc/sys/kernel/host[^n]*{,/**} wklx,\n"
220 " deny /proc/sys/kernel/hostn[^a]*{,/**} wklx,\n"
221 " deny /proc/sys/kernel/hostna[^m]*{,/**} wklx,\n"
222 " deny /proc/sys/kernel/hostnam[^e]*{,/**} wklx,\n"
223 " deny /proc/sys/kernel/hostname?*{,/**} wklx,\n"
224 " deny /proc/sys/kernel/m[^s]*{,/**} wklx,\n"
225 " deny /proc/sys/kernel/ms[^g]*{,/**} wklx,\n"
226 " deny /proc/sys/kernel/msg*/** wklx,\n"
227 " deny /proc/sys/kernel/s[^he]*{,/**} wklx,\n"
228 " deny /proc/sys/kernel/se[^m]*{,/**} wklx,\n"
229 " deny /proc/sys/kernel/sem*/** wklx,\n"
230 " deny /proc/sys/kernel/sh[^m]*{,/**} wklx,\n"
231 " deny /proc/sys/kernel/shm*/** wklx,\n"
232 " deny /proc/sys/kernel?*{,/**} wklx,\n"
233 " deny /proc/sys/n[^e]*{,/**} wklx,\n"
234 " deny /proc/sys/ne[^t]*{,/**} wklx,\n"
235 " deny /proc/sys/net?*{,/**} wklx,\n"
236 " deny /sys/[^fdck]*{,/**} wklx,\n"
237 " deny /sys/c[^l]*{,/**} wklx,\n"
238 " deny /sys/cl[^a]*{,/**} wklx,\n"
239 " deny /sys/cla[^s]*{,/**} wklx,\n"
240 " deny /sys/clas[^s]*{,/**} wklx,\n"
241 " deny /sys/class/[^n]*{,/**} wklx,\n"
242 " deny /sys/class/n[^e]*{,/**} wklx,\n"
243 " deny /sys/class/ne[^t]*{,/**} wklx,\n"
244 " deny /sys/class/net?*{,/**} wklx,\n"
245 " deny /sys/class?*{,/**} wklx,\n"
246 " deny /sys/d[^e]*{,/**} wklx,\n"
247 " deny /sys/de[^v]*{,/**} wklx,\n"
248 " deny /sys/dev[^i]*{,/**} wklx,\n"
249 " deny /sys/devi[^c]*{,/**} wklx,\n"
250 " deny /sys/devic[^e]*{,/**} wklx,\n"
251 " deny /sys/device[^s]*{,/**} wklx,\n"
252 " deny /sys/devices/[^v]*{,/**} wklx,\n"
253 " deny /sys/devices/v[^i]*{,/**} wklx,\n"
254 " deny /sys/devices/vi[^r]*{,/**} wklx,\n"
255 " deny /sys/devices/vir[^t]*{,/**} wklx,\n"
256 " deny /sys/devices/virt[^u]*{,/**} wklx,\n"
257 " deny /sys/devices/virtu[^a]*{,/**} wklx,\n"
258 " deny /sys/devices/virtua[^l]*{,/**} wklx,\n"
259 " deny /sys/devices/virtual/[^n]*{,/**} wklx,\n"
260 " deny /sys/devices/virtual/n[^e]*{,/**} wklx,\n"
261 " deny /sys/devices/virtual/ne[^t]*{,/**} wklx,\n"
262 " deny /sys/devices/virtual/net?*{,/**} wklx,\n"
263 " deny /sys/devices/virtual?*{,/**} wklx,\n"
264 " deny /sys/devices?*{,/**} wklx,\n"
265 " deny /sys/f[^s]*{,/**} wklx,\n"
266 " deny /sys/fs/[^c]*{,/**} wklx,\n"
267 " deny /sys/fs/c[^g]*{,/**} wklx,\n"
268 " deny /sys/fs/cg[^r]*{,/**} wklx,\n"
269 " deny /sys/fs/cgr[^o]*{,/**} wklx,\n"
270 " deny /sys/fs/cgro[^u]*{,/**} wklx,\n"
271 " deny /sys/fs/cgrou[^p]*{,/**} wklx,\n"
272 " deny /sys/fs/cgroup?*{,/**} wklx,\n"
273 " deny /sys/fs?*{,/**} wklx,\n"
274 ;
275
276 static const char AA_PROFILE_UNIX_SOCKETS[] =
277 "\n"
278 " ### Feature: unix\n"
279 " # Allow receive via unix sockets from anywhere\n"
280 " unix (receive),\n"
281 "\n"
282 " # Allow all unix sockets in the container\n"
283 " unix peer=(label=@{profile_name}),\n"
284 ;
285
286 static const char AA_PROFILE_CGROUP_NAMESPACES[] =
287 "\n"
288 " ### Feature: cgroup namespace\n"
289 " mount fstype=cgroup -> /sys/fs/cgroup/**,\n"
290 " mount fstype=cgroup2 -> /sys/fs/cgroup/**,\n"
291 ;
292
293 /* '_BASE' because we still need to append generated change_profile rules */
294 static const char AA_PROFILE_STACKING_BASE[] =
295 "\n"
296 " ### Feature: apparmor stacking\n"
297 " ### Configuration: apparmor profile loading (in namespace)\n"
298 " deny /sys/k[^e]*{,/**} wklx,\n"
299 " deny /sys/ke[^r]*{,/**} wklx,\n"
300 " deny /sys/ker[^n]*{,/**} wklx,\n"
301 " deny /sys/kern[^e]*{,/**} wklx,\n"
302 " deny /sys/kerne[^l]*{,/**} wklx,\n"
303 " deny /sys/kernel/[^s]*{,/**} wklx,\n"
304 " deny /sys/kernel/s[^e]*{,/**} wklx,\n"
305 " deny /sys/kernel/se[^c]*{,/**} wklx,\n"
306 " deny /sys/kernel/sec[^u]*{,/**} wklx,\n"
307 " deny /sys/kernel/secu[^r]*{,/**} wklx,\n"
308 " deny /sys/kernel/secur[^i]*{,/**} wklx,\n"
309 " deny /sys/kernel/securi[^t]*{,/**} wklx,\n"
310 " deny /sys/kernel/securit[^y]*{,/**} wklx,\n"
311 " deny /sys/kernel/security/[^a]*{,/**} wklx,\n"
312 " deny /sys/kernel/security/a[^p]*{,/**} wklx,\n"
313 " deny /sys/kernel/security/ap[^p]*{,/**} wklx,\n"
314 " deny /sys/kernel/security/app[^a]*{,/**} wklx,\n"
315 " deny /sys/kernel/security/appa[^r]*{,/**} wklx,\n"
316 " deny /sys/kernel/security/appar[^m]*{,/**} wklx,\n"
317 " deny /sys/kernel/security/apparm[^o]*{,/**} wklx,\n"
318 " deny /sys/kernel/security/apparmo[^r]*{,/**} wklx,\n"
319 " deny /sys/kernel/security/apparmor?*{,/**} wklx,\n"
320 " deny /sys/kernel/security?*{,/**} wklx,\n"
321 " deny /sys/kernel?*{,/**} wklx,\n"
322 ;
323
324 static const char AA_PROFILE_NO_STACKING[] =
325 "\n"
326 " ### Feature: apparmor stacking (not present)\n"
327 " deny /sys/k*{,/**} rwklx,\n"
328 ;
329
330 /* '_BASE' because we need to append change_profile for stacking */
331 static const char AA_PROFILE_NESTING_BASE[] =
332 "\n"
333 " ### Configuration: nesting\n"
334 " pivot_root,\n"
335 " ptrace,\n"
336 " signal,\n"
337 "\n"
338 /* NOTE: See conf.c's "nesting_helpers" for details. */
339 " deny /dev/.lxc/proc/** rw,\n"
340 " deny /dev/.lxc/sys/** rw,\n"
341 "\n"
342 " mount fstype=proc -> /usr/lib/*/lxc/**,\n"
343 " mount fstype=sysfs -> /usr/lib/*/lxc/**,\n"
344 " mount options=(rw,bind),\n"
345 " mount options=(rw,rbind),\n"
346 " mount options=(rw,make-rshared),\n"
347 "\n"
348 /* FIXME: What's the state here on apparmor's side? */
349 " # there doesn't seem to be a way to ask for:\n"
350 " # mount options=(ro,nosuid,nodev,noexec,remount,bind),\n"
351 " # as we always get mount to $cdir/proc/sys with those flags denied\n"
352 " # So allow all mounts until that is straightened out:\n"
353 " mount,\n"
354 ;
355
356 static const char AA_PROFILE_UNPRIVILEGED[] =
357 "\n"
358 " ### Configuration: unprivileged container\n"
359 " pivot_root,\n"
360 "\n"
361 " # Allow modifying mount propagation\n"
362 " mount options=(rw,make-slave) -> **,\n"
363 " mount options=(rw,make-rslave) -> **,\n"
364 " mount options=(rw,make-shared) -> **,\n"
365 " mount options=(rw,make-rshared) -> **,\n"
366 " mount options=(rw,make-private) -> **,\n"
367 " mount options=(rw,make-rprivate) -> **,\n"
368 " mount options=(rw,make-unbindable) -> **,\n"
369 " mount options=(rw,make-runbindable) -> **,\n"
370 "\n"
371 " # Allow all bind-mounts\n"
372 " mount options=(rw,bind),\n"
373 " mount options=(rw,rbind),\n"
374 "\n"
375 " # Allow remounting things read-only\n"
376 " mount options=(ro,remount),\n"
377 ;
378
379 static bool check_mount_feature_enabled(void)
380 {
381 return mount_features_enabled == 1;
382 }
383
384 static void load_mount_features_enabled(void)
385 {
386 struct stat statbuf;
387 int ret;
388
389 ret = stat(AA_MOUNT_RESTR, &statbuf);
390 if (ret == 0)
391 mount_features_enabled = 1;
392 }
393
394 /* aa_getcon is not working right now. Use our hand-rolled version below */
395 static int apparmor_enabled(void)
396 {
397 FILE *fin;
398 char e;
399 int ret;
400
401 fin = fopen_cloexec(AA_ENABLED_FILE, "r");
402 if (!fin)
403 return 0;
404 ret = fscanf(fin, "%c", &e);
405 fclose(fin);
406 if (ret == 1 && e == 'Y') {
407 load_mount_features_enabled();
408 return 1;
409 }
410
411 return 0;
412 }
413
414 static char *apparmor_process_label_get(pid_t pid)
415 {
416 char path[100], *space;
417 int ret;
418 char *buf = NULL, *newbuf;
419 int sz = 0;
420 FILE *f;
421
422 ret = snprintf(path, 100, "/proc/%d/attr/current", pid);
423 if (ret < 0 || ret >= 100) {
424 ERROR("path name too long");
425 return NULL;
426 }
427 again:
428 f = fopen_cloexec(path, "r");
429 if (!f) {
430 SYSERROR("opening %s", path);
431 free(buf);
432 return NULL;
433 }
434 sz += 1024;
435 newbuf = realloc(buf, sz);
436 if (!newbuf) {
437 free(buf);
438 ERROR("out of memory");
439 fclose(f);
440 return NULL;
441 }
442 buf = newbuf;
443 memset(buf, 0, sz);
444 ret = fread(buf, 1, sz - 1, f);
445 fclose(f);
446 if (ret < 0) {
447 ERROR("reading %s", path);
448 free(buf);
449 return NULL;
450 }
451 if (ret >= sz)
452 goto again;
453 space = strchr(buf, '\n');
454 if (space)
455 *space = '\0';
456 space = strchr(buf, ' ');
457 if (space)
458 *space = '\0';
459 return buf;
460 }
461
462 /*
463 * Probably makes sense to reorganize these to only read
464 * the label once
465 */
466 static bool apparmor_am_unconfined(void)
467 {
468 char *p = apparmor_process_label_get(lxc_raw_getpid());
469 bool ret = false;
470 if (!p || strcmp(p, "unconfined") == 0)
471 ret = true;
472 free(p);
473 return ret;
474 }
475
476 static bool aa_needs_transition(char *curlabel)
477 {
478 if (!curlabel)
479 return false;
480 if (strcmp(curlabel, "unconfined") == 0)
481 return false;
482 if (strcmp(curlabel, "/usr/bin/lxc-start") == 0)
483 return false;
484 return true;
485 }
486
487 static inline void uint64hex(char *buf, uint64_t num)
488 {
489 size_t i;
490
491 buf[16] = 0;
492 for (i = 16; i--;) {
493 char c = (char)(num & 0xf);
494 buf[i] = c + (c < 0xa ? '0' : 'a' - 0xa);
495 num >>= 4;
496 }
497 }
498
499 static inline char *shorten_apparmor_name(char *name)
500 {
501 size_t len = strlen(name);
502 if (len + 7 > 253) {
503 uint64_t hash;
504 hash = fnv_64a_buf(name, len, FNV1A_64_INIT);
505 name = must_realloc(name, 16 + 1);
506 uint64hex(name, hash);
507 }
508
509 return name;
510 }
511
512 /* Replace slashes with hyphens */
513 static inline void sanitize_path(char *path)
514 {
515 size_t i;
516
517 for (i = 0; path[i]; i++)
518 if (path[i] == '/')
519 path[i] = '-';
520 }
521
522 static inline char *apparmor_dir(const char *ctname, const char *lxcpath)
523 {
524 return must_make_path(lxcpath, ctname, "apparmor", NULL);
525 }
526
527
528 static inline char *apparmor_profile_full(const char *ctname, const char *lxcpath)
529 {
530 return shorten_apparmor_name(must_concat("lxc-", ctname, "_<", lxcpath, ">", NULL));
531 }
532
533 /* Like apparmor_profile_full() but with slashes replaced by hyphens */
534 static inline char *apparmor_namespace(const char *ctname, const char *lxcpath)
535 {
536 char *full;
537
538 full = apparmor_profile_full(ctname, lxcpath);
539 sanitize_path(full);
540
541 return full;
542 }
543
544 /* FIXME: This is currently run only in the context of a constructor (via the
545 * initial lsm_init() called due to its __attribute__((constructor)), so we
546 * do not have ERROR/... macros available, so there are some fprintf(stderr)s
547 * in there.
548 */
549 static bool check_apparmor_parser_version()
550 {
551 struct lxc_popen_FILE *parserpipe;
552 int rc;
553 int major = 0, minor = 0, micro = 0;
554
555 parserpipe = lxc_popen("apparmor_parser --version");
556 if (!parserpipe) {
557 fprintf(stderr, "Failed to run check for apparmor_parser\n");
558 return false;
559 }
560
561 rc = fscanf(parserpipe->f, "AppArmor parser version %d.%d.%d", &major, &minor, &micro);
562 if (rc < 1) {
563 lxc_pclose(parserpipe);
564 /* We stay silent for now as this most likely means the shell
565 * lxc_popen executed failed to find the apparmor_parser binary.
566 * See the FIXME comment above for details.
567 */
568 return false;
569 }
570
571 rc = lxc_pclose(parserpipe);
572 if (rc < 0) {
573 fprintf(stderr, "Error waiting for child process\n");
574 return false;
575 }
576 if (rc != 0) {
577 fprintf(stderr, "'apparmor_parser --version' executed with an error status\n");
578 return false;
579 }
580
581 aa_supports_unix = (major > 2) ||
582 (major == 2 && minor > 10) ||
583 (major == 2 && minor == 10 && micro >= 95);
584
585 return true;
586 }
587
588 static bool file_is_yes(const char *path)
589 {
590 ssize_t rd;
591 int fd;
592 char buf[8]; /* we actually just expect "yes" or "no" */
593
594 fd = open(path, O_RDONLY | O_CLOEXEC);
595 if (fd < 0)
596 return false;
597
598 rd = lxc_read_nointr(fd, buf, sizeof(buf));
599 close(fd);
600
601 return rd >= 4 && strncmp(buf, "yes\n", 4) == 0;
602 }
603
604 static bool apparmor_can_stack()
605 {
606 int major, minor, scanned;
607 FILE *f;
608
609 if (!file_is_yes("/sys/kernel/security/apparmor/features/domain/stack"))
610 return false;
611
612 f = fopen_cloexec("/sys/kernel/security/apparmor/features/domain/version", "r");
613 if (!f)
614 return false;
615
616 scanned = fscanf(f, "%d.%d", &major, &minor);
617 fclose(f);
618 if (scanned != 2)
619 return false;
620
621 return major > 1 || (major == 1 && minor >= 2);
622 }
623
624 static void must_append_sized_full(char **buf, size_t *bufsz, const char *data,
625 size_t size, bool append_newline)
626 {
627 size_t newsize = *bufsz + size;
628
629 if (append_newline)
630 ++newsize;
631
632 *buf = must_realloc(*buf, newsize);
633 memcpy(*buf + *bufsz, data, size);
634
635 if (append_newline)
636 (*buf)[newsize - 1] = '\n';
637
638 *bufsz = newsize;
639 }
640
641 static void must_append_sized(char **buf, size_t *bufsz, const char *data, size_t size)
642 {
643 return must_append_sized_full(buf, bufsz, data, size, false);
644 }
645
646 static bool is_privileged(struct lxc_conf *conf)
647 {
648 return lxc_list_empty(&conf->id_map);
649 }
650
651 static char *get_apparmor_profile_content(struct lxc_conf *conf, const char *lxcpath)
652 {
653 char *profile, *profile_name_full;
654 size_t size;
655 struct lxc_list *it;
656
657 profile_name_full = apparmor_profile_full(conf->name, lxcpath);
658
659 profile = must_concat(
660 "#include <tunables/global>\n"
661 "profile \"", profile_name_full, "\" flags=(attach_disconnected,mediate_deleted) {\n",
662 NULL);
663 size = strlen(profile);
664
665 must_append_sized(&profile, &size, AA_PROFILE_BASE,
666 STRARRAYLEN(AA_PROFILE_BASE));
667
668 if (aa_supports_unix)
669 must_append_sized(&profile, &size, AA_PROFILE_UNIX_SOCKETS,
670 STRARRAYLEN(AA_PROFILE_UNIX_SOCKETS));
671
672 if (file_exists("/proc/self/ns/cgroup"))
673 must_append_sized(&profile, &size, AA_PROFILE_CGROUP_NAMESPACES,
674 STRARRAYLEN(AA_PROFILE_CGROUP_NAMESPACES));
675
676 if (aa_can_stack && !aa_is_stacked) {
677 char *namespace, *temp;
678
679 must_append_sized(&profile, &size, AA_PROFILE_STACKING_BASE,
680 STRARRAYLEN(AA_PROFILE_STACKING_BASE));
681
682 namespace = apparmor_namespace(conf->name, lxcpath);
683 temp = must_concat(" change_profile -> \":", namespace, ":*\",\n"
684 " change_profile -> \":", namespace, "://*\",\n",
685 NULL);
686 free(namespace);
687
688 must_append_sized(&profile, &size, temp, strlen(temp));
689 free(temp);
690 } else {
691 must_append_sized(&profile, &size, AA_PROFILE_NO_STACKING,
692 STRARRAYLEN(AA_PROFILE_NO_STACKING));
693 }
694
695 if (conf->lsm_aa_allow_nesting) {
696 must_append_sized(&profile, &size, AA_PROFILE_NESTING_BASE,
697 STRARRAYLEN(AA_PROFILE_NESTING_BASE));
698
699 if (!aa_can_stack || aa_is_stacked) {
700 char *temp;
701
702 temp = must_concat(" change_profile -> \"",
703 profile_name_full, "\",\n", NULL);
704 must_append_sized(&profile, &size, temp, strlen(temp));
705 free(temp);
706 }
707 }
708
709 if (!is_privileged(conf) || am_host_unpriv())
710 must_append_sized(&profile, &size, AA_PROFILE_UNPRIVILEGED,
711 STRARRAYLEN(AA_PROFILE_UNPRIVILEGED));
712
713 lxc_list_for_each(it, &conf->lsm_aa_raw) {
714 const char *line = it->elem;
715
716 must_append_sized_full(&profile, &size, line, strlen(line), true);
717 }
718
719 /* include terminating \0 byte */
720 must_append_sized(&profile, &size, "}\n", 3);
721
722 free(profile_name_full);
723
724 return profile;
725 }
726
727 /*
728 * apparmor_parser creates a cache file using the parsed file's name as a name.
729 * This means there may be multiple containers with the same name but different
730 * lxcpaths. Therefore we need a sanitized version of the complete profile name
731 * as profile file-name.
732 * We already get this exactly from apparmor_namespace().
733 */
734 static char *make_apparmor_profile_path(const char *ctname, const char *lxcpath)
735 {
736 char *ret, *filename;
737
738 filename = apparmor_namespace(ctname, lxcpath);
739 ret = must_make_path(lxcpath, ctname, "apparmor", filename, NULL);
740 free(filename);
741
742 return ret;
743 }
744
745 static char *make_apparmor_namespace_path(const char *ctname, const char *lxcpath)
746 {
747 char *ret, *namespace;
748
749 namespace = apparmor_namespace(ctname, lxcpath);
750 ret = must_make_path("/sys/kernel/security/apparmor/policy/namespaces", namespace, NULL);
751 free(namespace);
752
753 return ret;
754 }
755
756 static bool make_apparmor_namespace(struct lxc_conf *conf, const char *lxcpath)
757 {
758 char *path;
759
760 if (!aa_can_stack || aa_is_stacked)
761 return true;
762
763 path = make_apparmor_namespace_path(conf->name, lxcpath);
764 errno = 0;
765 if (mkdir(path, 0755) < 0 && errno != EEXIST) {
766 SYSERROR("Error creating AppArmor namespace: %s", path);
767 free(path);
768 return false;
769 }
770 free(path);
771
772 return true;
773 }
774
775 static void remove_apparmor_namespace(struct lxc_conf *conf, const char *lxcpath)
776 {
777 char *path;
778
779 path = make_apparmor_namespace_path(conf->name, lxcpath);
780 if (rmdir(path) != 0)
781 SYSERROR("Error removing AppArmor namespace");
782 free(path);
783 }
784
785 struct apparmor_parser_args {
786 char cmd;
787 char *file;
788 };
789
790 static int apparmor_parser_exec(void *data)
791 {
792 struct apparmor_parser_args *args = data;
793 char cmdbuf[] = { '-', args->cmd, 'W', 'L', 0 };
794
795 execlp("apparmor_parser", "apparmor_parser", cmdbuf, APPARMOR_CACHE_DIR, args->file, NULL);
796
797 return -1;
798 }
799
800 static int run_apparmor_parser(char command,
801 struct lxc_conf *conf,
802 const char *lxcpath)
803 {
804 char output[PATH_MAX];
805 int ret;
806 struct apparmor_parser_args args = {
807 .cmd = command,
808 .file = make_apparmor_profile_path(conf->name, lxcpath),
809 };
810
811 ret = run_command(output, sizeof(output), apparmor_parser_exec, (void*)&args);
812 if (ret < 0) {
813 ERROR("Failed to run apparmor_parser on \"%s\": %s", args.file, output);
814 ret = -1;
815 }
816
817
818 free(args.file);
819 return ret;
820 }
821
822 static void remove_apparmor_profile(struct lxc_conf *conf, const char *lxcpath)
823 {
824 char *path;
825
826 /* It's ok if these deletes fail: if the container was never started,
827 * we'll have never written a profile or cached it.
828 */
829
830 path = make_apparmor_profile_path(conf->name, lxcpath);
831 (void)unlink(path);
832 free(path);
833
834 /* Also remove the apparmor/ subdirectory */
835 path = apparmor_dir(conf->name, lxcpath);
836 (void)rmdir(path);
837 free(path);
838 }
839
840 static int load_apparmor_profile(struct lxc_conf *conf, const char *lxcpath)
841 {
842 struct stat profile_sb;
843 size_t content_len;
844 int ret = -1;
845 size_t old_len = 0;
846 char *profile_path = NULL, *old_content = NULL, *new_content = NULL;
847 int profile_fd = -1;
848
849 if (!make_apparmor_namespace(conf, lxcpath))
850 return -1;
851
852 /* In order to avoid forcing a profile parse (potentially slow) on
853 * every container start, let's use apparmor's binary policy cache,
854 * which checks mtime of the files to figure out if the policy needs to
855 * be regenerated.
856 *
857 * Since it uses mtimes, we shouldn't just always write out our local
858 * apparmor template; instead we should check to see whether the
859 * template is the same as ours. If it isn't we should write our
860 * version out so that the new changes are reflected and we definitely
861 * force a recompile.
862 */
863
864 profile_path = make_apparmor_profile_path(conf->name, lxcpath);
865 profile_fd = open(profile_path, O_RDONLY | O_CLOEXEC);
866 if (profile_fd >= 0) {
867 if (fstat(profile_fd, &profile_sb) < 0) {
868 SYSERROR("Error accessing old profile from %s",
869 profile_path);
870 goto out;
871 }
872 old_len = profile_sb.st_size;
873 old_content = lxc_strmmap(NULL, old_len, PROT_READ,
874 MAP_PRIVATE, profile_fd, 0);
875 if (!old_content) {
876 SYSERROR("Failed to mmap old profile from %s",
877 profile_path);
878 goto out;
879 }
880 } else if (errno != ENOENT) {
881 SYSERROR("Error reading old profile from %s", profile_path);
882 goto out;
883 }
884
885 new_content = get_apparmor_profile_content(conf, lxcpath);
886 if (!new_content)
887 goto out;
888
889 content_len = strlen(new_content);
890
891 if (!old_content || old_len != content_len || memcmp(old_content, new_content, content_len) != 0) {
892 char *path;
893
894 ret = mkdir_p(APPARMOR_CACHE_DIR, 0755);
895 if (ret < 0) {
896 SYSERROR("Error creating AppArmor profile cache directory " APPARMOR_CACHE_DIR);
897 goto out;
898 }
899
900 path = apparmor_dir(conf->name, lxcpath);
901 ret = mkdir_p(path, 0755);
902 if (ret < 0) {
903 SYSERROR("Error creating AppArmor profile directory: %s", path);
904 free(path);
905 goto out;
906 }
907 free(path);
908
909 ret = lxc_write_to_file(profile_path, new_content, content_len, false, 0600);
910 if (ret < 0) {
911 SYSERROR("Error writing profile to %s", profile_path);
912 goto out;
913 }
914 }
915
916 ret = run_apparmor_parser(AA_CMD_LOAD, conf, lxcpath);
917 if (ret != 0)
918 goto out_remove_profile;
919
920 conf->lsm_aa_profile_created = true;
921
922 goto out_ok;
923
924 out_remove_profile:
925 remove_apparmor_profile(conf, lxcpath);
926 out:
927 remove_apparmor_namespace(conf, lxcpath);
928 out_ok:
929 if (profile_fd >= 0) {
930 if (old_content)
931 lxc_strmunmap(old_content, old_len);
932 close(profile_fd);
933 }
934 free(profile_path);
935 free(new_content);
936 return ret;
937 }
938
939 /*
940 * Ensure that the container's policy namespace is unloaded to free kernel
941 * memory. This does not delete the policy from disk or cache.
942 */
943 static void apparmor_cleanup(struct lxc_conf *conf, const char *lxcpath)
944 {
945 if (!aa_admin)
946 return;
947
948 if (!conf->lsm_aa_profile_created)
949 return;
950
951 remove_apparmor_namespace(conf, lxcpath);
952 (void)run_apparmor_parser(AA_CMD_UNLOAD, conf, lxcpath);
953
954 remove_apparmor_profile(conf, lxcpath);
955 }
956
957 static int apparmor_prepare(struct lxc_conf *conf, const char *lxcpath)
958 {
959 int ret = -1;
960 const char *label;
961 char *curlabel = NULL, *genlabel = NULL;
962
963 if (!aa_enabled) {
964 ERROR("AppArmor not enabled");
965 return -1;
966 }
967
968 label = conf->lsm_aa_profile;
969
970 /* user may request that we just ignore apparmor */
971 if (label && strcmp(label, AA_UNCHANGED) == 0) {
972 INFO("AppArmor profile unchanged per user request");
973 conf->lsm_aa_profile_computed = must_copy_string(label);
974 return 0;
975 }
976
977 if (label && strcmp(label, AA_GENERATED) == 0) {
978 if (!aa_parser_available) {
979 ERROR("Cannot use generated profile: apparmor_parser not available");
980 goto out;
981 }
982
983 /* auto-generate profile based on available/requested security features */
984 if (load_apparmor_profile(conf, lxcpath) != 0) {
985 ERROR("Failed to load generated AppArmor profile");
986 goto out;
987 }
988
989 genlabel = apparmor_profile_full(conf->name, lxcpath);
990 if (!genlabel) {
991 ERROR("Failed to build AppArmor profile name");
992 goto out;
993 }
994
995 if (aa_can_stack && !aa_is_stacked) {
996 char *namespace = apparmor_namespace(conf->name, lxcpath);
997 size_t llen = strlen(genlabel);
998 must_append_sized(&genlabel, &llen, "//&:", STRARRAYLEN("//&:"));
999 must_append_sized(&genlabel, &llen, namespace, strlen(namespace));
1000 must_append_sized(&genlabel, &llen, ":", STRARRAYLEN(":") + 1); /* with the nul byte */
1001 free(namespace);
1002 }
1003
1004 label = genlabel;
1005 }
1006
1007 curlabel = apparmor_process_label_get(lxc_raw_getpid());
1008
1009 if (!aa_can_stack && aa_needs_transition(curlabel)) {
1010 /* we're already confined, and stacking isn't supported */
1011
1012 if (!label || strcmp(curlabel, label) == 0) {
1013 /* no change requested */
1014 ret = 0;
1015 goto out;
1016 }
1017
1018 ERROR("Already AppArmor confined, but new label requested.");
1019 goto out;
1020 }
1021
1022 if (!label) {
1023 if (cgns_supported())
1024 label = AA_DEF_PROFILE_CGNS;
1025 else
1026 label = AA_DEF_PROFILE;
1027 }
1028
1029 if (!check_mount_feature_enabled() && strcmp(label, "unconfined") != 0) {
1030 WARN("Incomplete AppArmor support in your kernel");
1031 if (!conf->lsm_aa_allow_incomplete) {
1032 ERROR("If you really want to start this container, set");
1033 ERROR("lxc.apparmor.allow_incomplete = 1");
1034 ERROR("in your container configuration file");
1035 goto out;
1036 }
1037 }
1038
1039 conf->lsm_aa_profile_computed = must_copy_string(label);
1040 ret = 0;
1041
1042 out:
1043 if (genlabel) {
1044 free(genlabel);
1045 if (ret != 0)
1046 apparmor_cleanup(conf, lxcpath);
1047 }
1048 free(curlabel);
1049 return ret;
1050 }
1051
1052 /*
1053 * apparmor_process_label_set: Set AppArmor process profile
1054 *
1055 * @label : the profile to set
1056 * @conf : the container configuration to use if @label is NULL
1057 * @default : use the default profile if @label is NULL
1058 * @on_exec : this is ignored. Apparmor profile will be changed immediately
1059 *
1060 * Returns 0 on success, < 0 on failure
1061 *
1062 * Notes: This relies on /proc being available.
1063 */
1064 static int apparmor_process_label_set(const char *inlabel, struct lxc_conf *conf,
1065 bool on_exec)
1066 {
1067 int label_fd, ret;
1068 pid_t tid;
1069 const char *label;
1070
1071 if (!aa_enabled) {
1072 ERROR("AppArmor not enabled");
1073 return -1;
1074 }
1075
1076 label = inlabel ? inlabel : conf->lsm_aa_profile_computed;
1077 if (!label) {
1078 ERROR("LSM wasn't prepared");
1079 return -1;
1080 }
1081
1082 /* user may request that we just ignore apparmor */
1083 if (strcmp(label, AA_UNCHANGED) == 0) {
1084 INFO("AppArmor profile unchanged per user request");
1085 return 0;
1086 }
1087
1088 if (strcmp(label, "unconfined") == 0 && apparmor_am_unconfined()) {
1089 INFO("AppArmor profile unchanged");
1090 return 0;
1091 }
1092 tid = lxc_raw_gettid();
1093 label_fd = lsm_process_label_fd_get(tid, on_exec);
1094 if (label_fd < 0) {
1095 SYSERROR("Failed to change AppArmor profile to %s", label);
1096 return -1;
1097 }
1098
1099 ret = lsm_process_label_set_at(label_fd, label, on_exec);
1100 close(label_fd);
1101 if (ret < 0) {
1102 ERROR("Failed to change AppArmor profile to %s", label);
1103 return -1;
1104 }
1105
1106 INFO("Changed AppArmor profile to %s", label);
1107 return 0;
1108 }
1109
1110 static struct lsm_drv apparmor_drv = {
1111 .name = "AppArmor",
1112 .enabled = apparmor_enabled,
1113 .process_label_get = apparmor_process_label_get,
1114 .process_label_set = apparmor_process_label_set,
1115 .prepare = apparmor_prepare,
1116 .cleanup = apparmor_cleanup,
1117 };
1118
1119 struct lsm_drv *lsm_apparmor_drv_init(void)
1120 {
1121 bool have_mac_admin = false;
1122
1123 if (!apparmor_enabled())
1124 return NULL;
1125
1126 /* We only support generated profiles when apparmor_parser is usable */
1127 if (!check_apparmor_parser_version())
1128 goto out;
1129
1130 aa_parser_available = true;
1131
1132 aa_can_stack = apparmor_can_stack();
1133 if (aa_can_stack)
1134 aa_is_stacked = file_is_yes("/sys/kernel/security/apparmor/.ns_stacked");
1135
1136 #if HAVE_LIBCAP
1137 have_mac_admin = lxc_proc_cap_is_set(CAP_SETGID, CAP_EFFECTIVE);
1138 #endif
1139
1140 if (!have_mac_admin)
1141 WARN("Per-container AppArmor profiles are disabled because the mac_admin capability is missing");
1142 else if (am_host_unpriv() && !aa_is_stacked)
1143 WARN("Per-container AppArmor profiles are disabled because LXC is running in an unprivileged container without stacking");
1144 else
1145 aa_admin = true;
1146
1147 out:
1148 aa_enabled = 1;
1149 return &apparmor_drv;
1150 }