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