xref: /openbmc/linux/security/apparmor/file.c (revision 060f03e9)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor mediation of files
6  *
7  * Copyright (C) 1998-2008 Novell/SUSE
8  * Copyright 2009-2010 Canonical Ltd.
9  */
10 
11 #include <linux/tty.h>
12 #include <linux/fdtable.h>
13 #include <linux/file.h>
14 #include <linux/fs.h>
15 #include <linux/mount.h>
16 
17 #include "include/apparmor.h"
18 #include "include/audit.h"
19 #include "include/cred.h"
20 #include "include/file.h"
21 #include "include/match.h"
22 #include "include/net.h"
23 #include "include/path.h"
24 #include "include/policy.h"
25 #include "include/label.h"
26 
27 static u32 map_mask_to_chr_mask(u32 mask)
28 {
29 	u32 m = mask & PERMS_CHRS_MASK;
30 
31 	if (mask & AA_MAY_GETATTR)
32 		m |= MAY_READ;
33 	if (mask & (AA_MAY_SETATTR | AA_MAY_CHMOD | AA_MAY_CHOWN))
34 		m |= MAY_WRITE;
35 
36 	return m;
37 }
38 
39 /**
40  * file_audit_cb - call back for file specific audit fields
41  * @ab: audit_buffer  (NOT NULL)
42  * @va: audit struct to audit values of  (NOT NULL)
43  */
44 static void file_audit_cb(struct audit_buffer *ab, void *va)
45 {
46 	struct common_audit_data *sa = va;
47 	kuid_t fsuid = current_fsuid();
48 	char str[10];
49 
50 	if (aad(sa)->request & AA_AUDIT_FILE_MASK) {
51 		aa_perm_mask_to_str(str, sizeof(str), aa_file_perm_chrs,
52 				    map_mask_to_chr_mask(aad(sa)->request));
53 		audit_log_format(ab, " requested_mask=\"%s\"", str);
54 	}
55 	if (aad(sa)->denied & AA_AUDIT_FILE_MASK) {
56 		aa_perm_mask_to_str(str, sizeof(str), aa_file_perm_chrs,
57 				    map_mask_to_chr_mask(aad(sa)->denied));
58 		audit_log_format(ab, " denied_mask=\"%s\"", str);
59 	}
60 	if (aad(sa)->request & AA_AUDIT_FILE_MASK) {
61 		audit_log_format(ab, " fsuid=%d",
62 				 from_kuid(&init_user_ns, fsuid));
63 		audit_log_format(ab, " ouid=%d",
64 				 from_kuid(&init_user_ns, aad(sa)->fs.ouid));
65 	}
66 
67 	if (aad(sa)->peer) {
68 		audit_log_format(ab, " target=");
69 		aa_label_xaudit(ab, labels_ns(aad(sa)->label), aad(sa)->peer,
70 				FLAG_VIEW_SUBNS, GFP_KERNEL);
71 	} else if (aad(sa)->fs.target) {
72 		audit_log_format(ab, " target=");
73 		audit_log_untrustedstring(ab, aad(sa)->fs.target);
74 	}
75 }
76 
77 /**
78  * aa_audit_file - handle the auditing of file operations
79  * @profile: the profile being enforced  (NOT NULL)
80  * @perms: the permissions computed for the request (NOT NULL)
81  * @op: operation being mediated
82  * @request: permissions requested
83  * @name: name of object being mediated (MAYBE NULL)
84  * @target: name of target (MAYBE NULL)
85  * @tlabel: target label (MAY BE NULL)
86  * @ouid: object uid
87  * @info: extra information message (MAYBE NULL)
88  * @error: 0 if operation allowed else failure error code
89  *
90  * Returns: %0 or error on failure
91  */
92 int aa_audit_file(struct aa_profile *profile, struct aa_perms *perms,
93 		  const char *op, u32 request, const char *name,
94 		  const char *target, struct aa_label *tlabel,
95 		  kuid_t ouid, const char *info, int error)
96 {
97 	int type = AUDIT_APPARMOR_AUTO;
98 	DEFINE_AUDIT_DATA(sa, LSM_AUDIT_DATA_TASK, AA_CLASS_FILE, op);
99 
100 	sa.u.tsk = NULL;
101 	aad(&sa)->request = request;
102 	aad(&sa)->name = name;
103 	aad(&sa)->fs.target = target;
104 	aad(&sa)->peer = tlabel;
105 	aad(&sa)->fs.ouid = ouid;
106 	aad(&sa)->info = info;
107 	aad(&sa)->error = error;
108 	sa.u.tsk = NULL;
109 
110 	if (likely(!aad(&sa)->error)) {
111 		u32 mask = perms->audit;
112 
113 		if (unlikely(AUDIT_MODE(profile) == AUDIT_ALL))
114 			mask = 0xffff;
115 
116 		/* mask off perms that are not being force audited */
117 		aad(&sa)->request &= mask;
118 
119 		if (likely(!aad(&sa)->request))
120 			return 0;
121 		type = AUDIT_APPARMOR_AUDIT;
122 	} else {
123 		/* only report permissions that were denied */
124 		aad(&sa)->request = aad(&sa)->request & ~perms->allow;
125 		AA_BUG(!aad(&sa)->request);
126 
127 		if (aad(&sa)->request & perms->kill)
128 			type = AUDIT_APPARMOR_KILL;
129 
130 		/* quiet known rejects, assumes quiet and kill do not overlap */
131 		if ((aad(&sa)->request & perms->quiet) &&
132 		    AUDIT_MODE(profile) != AUDIT_NOQUIET &&
133 		    AUDIT_MODE(profile) != AUDIT_ALL)
134 			aad(&sa)->request &= ~perms->quiet;
135 
136 		if (!aad(&sa)->request)
137 			return aad(&sa)->error;
138 	}
139 
140 	aad(&sa)->denied = aad(&sa)->request & ~perms->allow;
141 	return aa_audit(type, profile, &sa, file_audit_cb);
142 }
143 
144 static int path_name(const char *op, struct aa_label *label,
145 		     const struct path *path, int flags, char *buffer,
146 		     const char **name, struct path_cond *cond, u32 request)
147 {
148 	struct aa_profile *profile;
149 	const char *info = NULL;
150 	int error;
151 
152 	error = aa_path_name(path, flags, buffer, name, &info,
153 			     labels_profile(label)->disconnected);
154 	if (error) {
155 		fn_for_each_confined(label, profile,
156 			aa_audit_file(profile, &nullperms, op, request, *name,
157 				      NULL, NULL, cond->uid, info, error));
158 		return error;
159 	}
160 
161 	return 0;
162 }
163 
164 struct aa_perms default_perms = {};
165 /**
166  * aa_lookup_fperms - convert dfa compressed perms to internal perms
167  * @dfa: dfa to lookup perms for   (NOT NULL)
168  * @state: state in dfa
169  * @cond:  conditions to consider  (NOT NULL)
170  *
171  * TODO: convert from dfa + state to permission entry
172  *
173  * Returns: a pointer to a file permission set
174  */
175 struct aa_perms *aa_lookup_fperms(struct aa_policydb *file_rules,
176 				 aa_state_t state, struct path_cond *cond)
177 {
178 	unsigned int index = ACCEPT_TABLE(file_rules->dfa)[state];
179 
180 	if (!(file_rules->perms))
181 		return &default_perms;
182 
183 	if (uid_eq(current_fsuid(), cond->uid))
184 		return &(file_rules->perms[index]);
185 
186 	return &(file_rules->perms[index + 1]);
187 }
188 
189 /**
190  * aa_str_perms - find permission that match @name
191  * @dfa: to match against  (MAYBE NULL)
192  * @state: state to start matching in
193  * @name: string to match against dfa  (NOT NULL)
194  * @cond: conditions to consider for permission set computation  (NOT NULL)
195  * @perms: Returns - the permissions found when matching @name
196  *
197  * Returns: the final state in @dfa when beginning @start and walking @name
198  */
199 aa_state_t aa_str_perms(struct aa_policydb *file_rules, aa_state_t start,
200 			const char *name, struct path_cond *cond,
201 			struct aa_perms *perms)
202 {
203 	aa_state_t state;
204 	state = aa_dfa_match(file_rules->dfa, start, name);
205 	*perms = *(aa_lookup_fperms(file_rules, state, cond));
206 
207 	return state;
208 }
209 
210 static int __aa_path_perm(const char *op, struct aa_profile *profile,
211 			  const char *name, u32 request,
212 			  struct path_cond *cond, int flags,
213 			  struct aa_perms *perms)
214 {
215 	struct aa_ruleset *rules = list_first_entry(&profile->rules,
216 						    typeof(*rules), list);
217 	int e = 0;
218 
219 	if (profile_unconfined(profile))
220 		return 0;
221 	aa_str_perms(&(rules->file), rules->file.start[AA_CLASS_FILE],
222 		     name, cond, perms);
223 	if (request & ~perms->allow)
224 		e = -EACCES;
225 	return aa_audit_file(profile, perms, op, request, name, NULL, NULL,
226 			     cond->uid, NULL, e);
227 }
228 
229 
230 static int profile_path_perm(const char *op, struct aa_profile *profile,
231 			     const struct path *path, char *buffer, u32 request,
232 			     struct path_cond *cond, int flags,
233 			     struct aa_perms *perms)
234 {
235 	const char *name;
236 	int error;
237 
238 	if (profile_unconfined(profile))
239 		return 0;
240 
241 	error = path_name(op, &profile->label, path,
242 			  flags | profile->path_flags, buffer, &name, cond,
243 			  request);
244 	if (error)
245 		return error;
246 	return __aa_path_perm(op, profile, name, request, cond, flags,
247 			      perms);
248 }
249 
250 /**
251  * aa_path_perm - do permissions check & audit for @path
252  * @op: operation being checked
253  * @label: profile being enforced  (NOT NULL)
254  * @path: path to check permissions of  (NOT NULL)
255  * @flags: any additional path flags beyond what the profile specifies
256  * @request: requested permissions
257  * @cond: conditional info for this request  (NOT NULL)
258  *
259  * Returns: %0 else error if access denied or other error
260  */
261 int aa_path_perm(const char *op, struct aa_label *label,
262 		 const struct path *path, int flags, u32 request,
263 		 struct path_cond *cond)
264 {
265 	struct aa_perms perms = {};
266 	struct aa_profile *profile;
267 	char *buffer = NULL;
268 	int error;
269 
270 	flags |= PATH_DELEGATE_DELETED | (S_ISDIR(cond->mode) ? PATH_IS_DIR :
271 								0);
272 	buffer = aa_get_buffer(false);
273 	if (!buffer)
274 		return -ENOMEM;
275 	error = fn_for_each_confined(label, profile,
276 			profile_path_perm(op, profile, path, buffer, request,
277 					  cond, flags, &perms));
278 
279 	aa_put_buffer(buffer);
280 
281 	return error;
282 }
283 
284 /**
285  * xindex_is_subset - helper for aa_path_link
286  * @link: link permission set
287  * @target: target permission set
288  *
289  * test target x permissions are equal OR a subset of link x permissions
290  * this is done as part of the subset test, where a hardlink must have
291  * a subset of permissions that the target has.
292  *
293  * Returns: true if subset else false
294  */
295 static inline bool xindex_is_subset(u32 link, u32 target)
296 {
297 	if (((link & ~AA_X_UNSAFE) != (target & ~AA_X_UNSAFE)) ||
298 	    ((link & AA_X_UNSAFE) && !(target & AA_X_UNSAFE)))
299 		return false;
300 
301 	return true;
302 }
303 
304 static int profile_path_link(struct aa_profile *profile,
305 			     const struct path *link, char *buffer,
306 			     const struct path *target, char *buffer2,
307 			     struct path_cond *cond)
308 {
309 	struct aa_ruleset *rules = list_first_entry(&profile->rules,
310 						    typeof(*rules), list);
311 	const char *lname, *tname = NULL;
312 	struct aa_perms lperms = {}, perms;
313 	const char *info = NULL;
314 	u32 request = AA_MAY_LINK;
315 	aa_state_t state;
316 	int error;
317 
318 	error = path_name(OP_LINK, &profile->label, link, profile->path_flags,
319 			  buffer, &lname, cond, AA_MAY_LINK);
320 	if (error)
321 		goto audit;
322 
323 	/* buffer2 freed below, tname is pointer in buffer2 */
324 	error = path_name(OP_LINK, &profile->label, target, profile->path_flags,
325 			  buffer2, &tname, cond, AA_MAY_LINK);
326 	if (error)
327 		goto audit;
328 
329 	error = -EACCES;
330 	/* aa_str_perms - handles the case of the dfa being NULL */
331 	state = aa_str_perms(&(rules->file),
332 			     rules->file.start[AA_CLASS_FILE], lname,
333 			     cond, &lperms);
334 
335 	if (!(lperms.allow & AA_MAY_LINK))
336 		goto audit;
337 
338 	/* test to see if target can be paired with link */
339 	state = aa_dfa_null_transition(rules->file.dfa, state);
340 	aa_str_perms(&(rules->file), state, tname, cond, &perms);
341 
342 	/* force audit/quiet masks for link are stored in the second entry
343 	 * in the link pair.
344 	 */
345 	lperms.audit = perms.audit;
346 	lperms.quiet = perms.quiet;
347 	lperms.kill = perms.kill;
348 
349 	if (!(perms.allow & AA_MAY_LINK)) {
350 		info = "target restricted";
351 		lperms = perms;
352 		goto audit;
353 	}
354 
355 	/* done if link subset test is not required */
356 	if (!(perms.allow & AA_LINK_SUBSET))
357 		goto done_tests;
358 
359 	/* Do link perm subset test requiring allowed permission on link are
360 	 * a subset of the allowed permissions on target.
361 	 */
362 	aa_str_perms(&(rules->file), rules->file.start[AA_CLASS_FILE],
363 		     tname, cond, &perms);
364 
365 	/* AA_MAY_LINK is not considered in the subset test */
366 	request = lperms.allow & ~AA_MAY_LINK;
367 	lperms.allow &= perms.allow | AA_MAY_LINK;
368 
369 	request |= AA_AUDIT_FILE_MASK & (lperms.allow & ~perms.allow);
370 	if (request & ~lperms.allow) {
371 		goto audit;
372 	} else if ((lperms.allow & MAY_EXEC) &&
373 		   !xindex_is_subset(lperms.xindex, perms.xindex)) {
374 		lperms.allow &= ~MAY_EXEC;
375 		request |= MAY_EXEC;
376 		info = "link not subset of target";
377 		goto audit;
378 	}
379 
380 done_tests:
381 	error = 0;
382 
383 audit:
384 	return aa_audit_file(profile, &lperms, OP_LINK, request, lname, tname,
385 			     NULL, cond->uid, info, error);
386 }
387 
388 /**
389  * aa_path_link - Handle hard link permission check
390  * @label: the label being enforced  (NOT NULL)
391  * @old_dentry: the target dentry  (NOT NULL)
392  * @new_dir: directory the new link will be created in  (NOT NULL)
393  * @new_dentry: the link being created  (NOT NULL)
394  *
395  * Handle the permission test for a link & target pair.  Permission
396  * is encoded as a pair where the link permission is determined
397  * first, and if allowed, the target is tested.  The target test
398  * is done from the point of the link match (not start of DFA)
399  * making the target permission dependent on the link permission match.
400  *
401  * The subset test if required forces that permissions granted
402  * on link are a subset of the permission granted to target.
403  *
404  * Returns: %0 if allowed else error
405  */
406 int aa_path_link(struct aa_label *label, struct dentry *old_dentry,
407 		 const struct path *new_dir, struct dentry *new_dentry)
408 {
409 	struct path link = { .mnt = new_dir->mnt, .dentry = new_dentry };
410 	struct path target = { .mnt = new_dir->mnt, .dentry = old_dentry };
411 	struct path_cond cond = {
412 		d_backing_inode(old_dentry)->i_uid,
413 		d_backing_inode(old_dentry)->i_mode
414 	};
415 	char *buffer = NULL, *buffer2 = NULL;
416 	struct aa_profile *profile;
417 	int error;
418 
419 	/* buffer freed below, lname is pointer in buffer */
420 	buffer = aa_get_buffer(false);
421 	buffer2 = aa_get_buffer(false);
422 	error = -ENOMEM;
423 	if (!buffer || !buffer2)
424 		goto out;
425 
426 	error = fn_for_each_confined(label, profile,
427 			profile_path_link(profile, &link, buffer, &target,
428 					  buffer2, &cond));
429 out:
430 	aa_put_buffer(buffer);
431 	aa_put_buffer(buffer2);
432 	return error;
433 }
434 
435 static void update_file_ctx(struct aa_file_ctx *fctx, struct aa_label *label,
436 			    u32 request)
437 {
438 	struct aa_label *l, *old;
439 
440 	/* update caching of label on file_ctx */
441 	spin_lock(&fctx->lock);
442 	old = rcu_dereference_protected(fctx->label,
443 					lockdep_is_held(&fctx->lock));
444 	l = aa_label_merge(old, label, GFP_ATOMIC);
445 	if (l) {
446 		if (l != old) {
447 			rcu_assign_pointer(fctx->label, l);
448 			aa_put_label(old);
449 		} else
450 			aa_put_label(l);
451 		fctx->allow |= request;
452 	}
453 	spin_unlock(&fctx->lock);
454 }
455 
456 static int __file_path_perm(const char *op, struct aa_label *label,
457 			    struct aa_label *flabel, struct file *file,
458 			    u32 request, u32 denied, bool in_atomic)
459 {
460 	struct aa_profile *profile;
461 	struct aa_perms perms = {};
462 	vfsuid_t vfsuid = i_uid_into_vfsuid(file_mnt_idmap(file),
463 					    file_inode(file));
464 	struct path_cond cond = {
465 		.uid = vfsuid_into_kuid(vfsuid),
466 		.mode = file_inode(file)->i_mode
467 	};
468 	char *buffer;
469 	int flags, error;
470 
471 	/* revalidation due to label out of date. No revocation at this time */
472 	if (!denied && aa_label_is_subset(flabel, label))
473 		/* TODO: check for revocation on stale profiles */
474 		return 0;
475 
476 	flags = PATH_DELEGATE_DELETED | (S_ISDIR(cond.mode) ? PATH_IS_DIR : 0);
477 	buffer = aa_get_buffer(in_atomic);
478 	if (!buffer)
479 		return -ENOMEM;
480 
481 	/* check every profile in task label not in current cache */
482 	error = fn_for_each_not_in_set(flabel, label, profile,
483 			profile_path_perm(op, profile, &file->f_path, buffer,
484 					  request, &cond, flags, &perms));
485 	if (denied && !error) {
486 		/*
487 		 * check every profile in file label that was not tested
488 		 * in the initial check above.
489 		 *
490 		 * TODO: cache full perms so this only happens because of
491 		 * conditionals
492 		 * TODO: don't audit here
493 		 */
494 		if (label == flabel)
495 			error = fn_for_each(label, profile,
496 				profile_path_perm(op, profile, &file->f_path,
497 						  buffer, request, &cond, flags,
498 						  &perms));
499 		else
500 			error = fn_for_each_not_in_set(label, flabel, profile,
501 				profile_path_perm(op, profile, &file->f_path,
502 						  buffer, request, &cond, flags,
503 						  &perms));
504 	}
505 	if (!error)
506 		update_file_ctx(file_ctx(file), label, request);
507 
508 	aa_put_buffer(buffer);
509 
510 	return error;
511 }
512 
513 static int __file_sock_perm(const char *op, struct aa_label *label,
514 			    struct aa_label *flabel, struct file *file,
515 			    u32 request, u32 denied)
516 {
517 	struct socket *sock = (struct socket *) file->private_data;
518 	int error;
519 
520 	AA_BUG(!sock);
521 
522 	/* revalidation due to label out of date. No revocation at this time */
523 	if (!denied && aa_label_is_subset(flabel, label))
524 		return 0;
525 
526 	/* TODO: improve to skip profiles cached in flabel */
527 	error = aa_sock_file_perm(label, op, request, sock);
528 	if (denied) {
529 		/* TODO: improve to skip profiles checked above */
530 		/* check every profile in file label to is cached */
531 		last_error(error, aa_sock_file_perm(flabel, op, request, sock));
532 	}
533 	if (!error)
534 		update_file_ctx(file_ctx(file), label, request);
535 
536 	return error;
537 }
538 
539 /**
540  * aa_file_perm - do permission revalidation check & audit for @file
541  * @op: operation being checked
542  * @label: label being enforced   (NOT NULL)
543  * @file: file to revalidate access permissions on  (NOT NULL)
544  * @request: requested permissions
545  * @in_atomic: whether allocations need to be done in atomic context
546  *
547  * Returns: %0 if access allowed else error
548  */
549 int aa_file_perm(const char *op, struct aa_label *label, struct file *file,
550 		 u32 request, bool in_atomic)
551 {
552 	struct aa_file_ctx *fctx;
553 	struct aa_label *flabel;
554 	u32 denied;
555 	int error = 0;
556 
557 	AA_BUG(!label);
558 	AA_BUG(!file);
559 
560 	fctx = file_ctx(file);
561 
562 	rcu_read_lock();
563 	flabel  = rcu_dereference(fctx->label);
564 	AA_BUG(!flabel);
565 
566 	/* revalidate access, if task is unconfined, or the cached cred
567 	 * doesn't match or if the request is for more permissions than
568 	 * was granted.
569 	 *
570 	 * Note: the test for !unconfined(flabel) is to handle file
571 	 *       delegation from unconfined tasks
572 	 */
573 	denied = request & ~fctx->allow;
574 	if (unconfined(label) || unconfined(flabel) ||
575 	    (!denied && aa_label_is_subset(flabel, label))) {
576 		rcu_read_unlock();
577 		goto done;
578 	}
579 
580 	flabel  = aa_get_newest_label(flabel);
581 	rcu_read_unlock();
582 	/* TODO: label cross check */
583 
584 	if (file->f_path.mnt && path_mediated_fs(file->f_path.dentry))
585 		error = __file_path_perm(op, label, flabel, file, request,
586 					 denied, in_atomic);
587 
588 	else if (S_ISSOCK(file_inode(file)->i_mode))
589 		error = __file_sock_perm(op, label, flabel, file, request,
590 					 denied);
591 	aa_put_label(flabel);
592 
593 done:
594 	return error;
595 }
596 
597 static void revalidate_tty(struct aa_label *label)
598 {
599 	struct tty_struct *tty;
600 	int drop_tty = 0;
601 
602 	tty = get_current_tty();
603 	if (!tty)
604 		return;
605 
606 	spin_lock(&tty->files_lock);
607 	if (!list_empty(&tty->tty_files)) {
608 		struct tty_file_private *file_priv;
609 		struct file *file;
610 		/* TODO: Revalidate access to controlling tty. */
611 		file_priv = list_first_entry(&tty->tty_files,
612 					     struct tty_file_private, list);
613 		file = file_priv->file;
614 
615 		if (aa_file_perm(OP_INHERIT, label, file, MAY_READ | MAY_WRITE,
616 				 IN_ATOMIC))
617 			drop_tty = 1;
618 	}
619 	spin_unlock(&tty->files_lock);
620 	tty_kref_put(tty);
621 
622 	if (drop_tty)
623 		no_tty();
624 }
625 
626 static int match_file(const void *p, struct file *file, unsigned int fd)
627 {
628 	struct aa_label *label = (struct aa_label *)p;
629 
630 	if (aa_file_perm(OP_INHERIT, label, file, aa_map_file_to_perms(file),
631 			 IN_ATOMIC))
632 		return fd + 1;
633 	return 0;
634 }
635 
636 
637 /* based on selinux's flush_unauthorized_files */
638 void aa_inherit_files(const struct cred *cred, struct files_struct *files)
639 {
640 	struct aa_label *label = aa_get_newest_cred_label(cred);
641 	struct file *devnull = NULL;
642 	unsigned int n;
643 
644 	revalidate_tty(label);
645 
646 	/* Revalidate access to inherited open files. */
647 	n = iterate_fd(files, 0, match_file, label);
648 	if (!n) /* none found? */
649 		goto out;
650 
651 	devnull = dentry_open(&aa_null, O_RDWR, cred);
652 	if (IS_ERR(devnull))
653 		devnull = NULL;
654 	/* replace all the matching ones with this */
655 	do {
656 		replace_fd(n - 1, devnull, 0);
657 	} while ((n = iterate_fd(files, n, match_file, label)) != 0);
658 	if (devnull)
659 		fput(devnull);
660 out:
661 	aa_put_label(label);
662 }
663