xref: /linux/kernel/cred.c (revision 7fc2cd2e4b398c57c9cf961cfea05eadbf34c05c)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Task credentials management - see Documentation/security/credentials.rst
3  *
4  * Copyright (C) 2008 Red Hat, Inc. All Rights Reserved.
5  * Written by David Howells (dhowells@redhat.com)
6  */
7 
8 #define pr_fmt(fmt) "CRED: " fmt
9 
10 #include <linux/export.h>
11 #include <linux/cred.h>
12 #include <linux/slab.h>
13 #include <linux/sched.h>
14 #include <linux/sched/coredump.h>
15 #include <linux/key.h>
16 #include <linux/keyctl.h>
17 #include <linux/init_task.h>
18 #include <linux/security.h>
19 #include <linux/binfmts.h>
20 #include <linux/cn_proc.h>
21 #include <linux/uidgid.h>
22 
23 #if 0
24 #define kdebug(FMT, ...)						\
25 	printk("[%-5.5s%5u] " FMT "\n",					\
26 	       current->comm, current->pid, ##__VA_ARGS__)
27 #else
28 #define kdebug(FMT, ...)						\
29 do {									\
30 	if (0)								\
31 		no_printk("[%-5.5s%5u] " FMT "\n",			\
32 			  current->comm, current->pid, ##__VA_ARGS__);	\
33 } while (0)
34 #endif
35 
36 static struct kmem_cache *cred_jar;
37 
38 /*
39  * The RCU callback to actually dispose of a set of credentials
40  */
41 static void put_cred_rcu(struct rcu_head *rcu)
42 {
43 	struct cred *cred = container_of(rcu, struct cred, rcu);
44 
45 	kdebug("put_cred_rcu(%p)", cred);
46 
47 	if (atomic_long_read(&cred->usage) != 0)
48 		panic("CRED: put_cred_rcu() sees %p with usage %ld\n",
49 		      cred, atomic_long_read(&cred->usage));
50 
51 	security_cred_free(cred);
52 	key_put(cred->session_keyring);
53 	key_put(cred->process_keyring);
54 	key_put(cred->thread_keyring);
55 	key_put(cred->request_key_auth);
56 	if (cred->group_info)
57 		put_group_info(cred->group_info);
58 	free_uid(cred->user);
59 	if (cred->ucounts)
60 		put_ucounts(cred->ucounts);
61 	put_user_ns(cred->user_ns);
62 	kmem_cache_free(cred_jar, cred);
63 }
64 
65 /**
66  * __put_cred - Destroy a set of credentials
67  * @cred: The record to release
68  *
69  * Destroy a set of credentials on which no references remain.
70  */
71 void __put_cred(struct cred *cred)
72 {
73 	kdebug("__put_cred(%p{%ld})", cred,
74 	       atomic_long_read(&cred->usage));
75 
76 	BUG_ON(atomic_long_read(&cred->usage) != 0);
77 	BUG_ON(cred == current->cred);
78 	BUG_ON(cred == current->real_cred);
79 
80 	if (cred->non_rcu)
81 		put_cred_rcu(&cred->rcu);
82 	else
83 		call_rcu(&cred->rcu, put_cred_rcu);
84 }
85 EXPORT_SYMBOL(__put_cred);
86 
87 /*
88  * Clean up a task's credentials when it exits
89  */
90 void exit_creds(struct task_struct *tsk)
91 {
92 	struct cred *real_cred, *cred;
93 
94 	kdebug("exit_creds(%u,%p,%p,{%ld})", tsk->pid, tsk->real_cred, tsk->cred,
95 	       atomic_long_read(&tsk->cred->usage));
96 
97 	real_cred = (struct cred *) tsk->real_cred;
98 	tsk->real_cred = NULL;
99 
100 	cred = (struct cred *) tsk->cred;
101 	tsk->cred = NULL;
102 
103 	if (real_cred == cred) {
104 		put_cred_many(cred, 2);
105 	} else {
106 		put_cred(real_cred);
107 		put_cred(cred);
108 	}
109 
110 #ifdef CONFIG_KEYS_REQUEST_CACHE
111 	key_put(tsk->cached_requested_key);
112 	tsk->cached_requested_key = NULL;
113 #endif
114 }
115 
116 /**
117  * get_task_cred - Get another task's objective credentials
118  * @task: The task to query
119  *
120  * Get the objective credentials of a task, pinning them so that they can't go
121  * away.  Accessing a task's credentials directly is not permitted.
122  *
123  * The caller must also make sure task doesn't get deleted, either by holding a
124  * ref on task or by holding tasklist_lock to prevent it from being unlinked.
125  */
126 const struct cred *get_task_cred(struct task_struct *task)
127 {
128 	const struct cred *cred;
129 
130 	rcu_read_lock();
131 
132 	do {
133 		cred = __task_cred((task));
134 		BUG_ON(!cred);
135 	} while (!get_cred_rcu(cred));
136 
137 	rcu_read_unlock();
138 	return cred;
139 }
140 EXPORT_SYMBOL(get_task_cred);
141 
142 /*
143  * Allocate blank credentials, such that the credentials can be filled in at a
144  * later date without risk of ENOMEM.
145  */
146 struct cred *cred_alloc_blank(void)
147 {
148 	struct cred *new;
149 
150 	new = kmem_cache_zalloc(cred_jar, GFP_KERNEL);
151 	if (!new)
152 		return NULL;
153 
154 	atomic_long_set(&new->usage, 1);
155 	if (security_cred_alloc_blank(new, GFP_KERNEL_ACCOUNT) < 0)
156 		goto error;
157 
158 	return new;
159 
160 error:
161 	abort_creds(new);
162 	return NULL;
163 }
164 
165 /**
166  * prepare_creds - Prepare a new set of credentials for modification
167  *
168  * Prepare a new set of task credentials for modification.  A task's creds
169  * shouldn't generally be modified directly, therefore this function is used to
170  * prepare a new copy, which the caller then modifies and then commits by
171  * calling commit_creds().
172  *
173  * Preparation involves making a copy of the objective creds for modification.
174  *
175  * Returns a pointer to the new creds-to-be if successful, NULL otherwise.
176  *
177  * Call commit_creds() or abort_creds() to clean up.
178  */
179 struct cred *prepare_creds(void)
180 {
181 	struct task_struct *task = current;
182 	const struct cred *old;
183 	struct cred *new;
184 
185 	new = kmem_cache_alloc(cred_jar, GFP_KERNEL);
186 	if (!new)
187 		return NULL;
188 
189 	kdebug("prepare_creds() alloc %p", new);
190 
191 	old = task->cred;
192 	memcpy(new, old, sizeof(struct cred));
193 
194 	new->non_rcu = 0;
195 	atomic_long_set(&new->usage, 1);
196 	get_group_info(new->group_info);
197 	get_uid(new->user);
198 	get_user_ns(new->user_ns);
199 
200 #ifdef CONFIG_KEYS
201 	key_get(new->session_keyring);
202 	key_get(new->process_keyring);
203 	key_get(new->thread_keyring);
204 	key_get(new->request_key_auth);
205 #endif
206 
207 #ifdef CONFIG_SECURITY
208 	new->security = NULL;
209 #endif
210 
211 	new->ucounts = get_ucounts(new->ucounts);
212 	if (!new->ucounts)
213 		goto error;
214 
215 	if (security_prepare_creds(new, old, GFP_KERNEL_ACCOUNT) < 0)
216 		goto error;
217 
218 	return new;
219 
220 error:
221 	abort_creds(new);
222 	return NULL;
223 }
224 EXPORT_SYMBOL(prepare_creds);
225 
226 /*
227  * Prepare credentials for current to perform an execve()
228  * - The caller must hold ->cred_guard_mutex
229  */
230 struct cred *prepare_exec_creds(void)
231 {
232 	struct cred *new;
233 
234 	new = prepare_creds();
235 	if (!new)
236 		return new;
237 
238 #ifdef CONFIG_KEYS
239 	/* newly exec'd tasks don't get a thread keyring */
240 	key_put(new->thread_keyring);
241 	new->thread_keyring = NULL;
242 
243 	/* inherit the session keyring; new process keyring */
244 	key_put(new->process_keyring);
245 	new->process_keyring = NULL;
246 #endif
247 
248 	new->suid = new->fsuid = new->euid;
249 	new->sgid = new->fsgid = new->egid;
250 
251 	return new;
252 }
253 
254 /*
255  * Copy credentials for the new process created by fork()
256  *
257  * We share if we can, but under some circumstances we have to generate a new
258  * set.
259  *
260  * The new process gets the current process's subjective credentials as its
261  * objective and subjective credentials
262  */
263 int copy_creds(struct task_struct *p, u64 clone_flags)
264 {
265 	struct cred *new;
266 	int ret;
267 
268 #ifdef CONFIG_KEYS_REQUEST_CACHE
269 	p->cached_requested_key = NULL;
270 #endif
271 
272 	if (
273 #ifdef CONFIG_KEYS
274 		!p->cred->thread_keyring &&
275 #endif
276 		clone_flags & CLONE_THREAD
277 	    ) {
278 		p->real_cred = get_cred_many(p->cred, 2);
279 		kdebug("share_creds(%p{%ld})",
280 		       p->cred, atomic_long_read(&p->cred->usage));
281 		inc_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
282 		get_cred_namespaces(p);
283 		return 0;
284 	}
285 
286 	new = prepare_creds();
287 	if (!new)
288 		return -ENOMEM;
289 
290 	if (clone_flags & CLONE_NEWUSER) {
291 		ret = create_user_ns(new);
292 		if (ret < 0)
293 			goto error_put;
294 		ret = set_cred_ucounts(new);
295 		if (ret < 0)
296 			goto error_put;
297 	}
298 
299 #ifdef CONFIG_KEYS
300 	/* new threads get their own thread keyrings if their parent already
301 	 * had one */
302 	if (new->thread_keyring) {
303 		key_put(new->thread_keyring);
304 		new->thread_keyring = NULL;
305 		if (clone_flags & CLONE_THREAD)
306 			install_thread_keyring_to_cred(new);
307 	}
308 
309 	/* The process keyring is only shared between the threads in a process;
310 	 * anything outside of those threads doesn't inherit.
311 	 */
312 	if (!(clone_flags & CLONE_THREAD)) {
313 		key_put(new->process_keyring);
314 		new->process_keyring = NULL;
315 	}
316 #endif
317 
318 	p->cred = p->real_cred = get_cred(new);
319 	inc_rlimit_ucounts(task_ucounts(p), UCOUNT_RLIMIT_NPROC, 1);
320 	get_cred_namespaces(p);
321 
322 	return 0;
323 
324 error_put:
325 	put_cred(new);
326 	return ret;
327 }
328 
329 static bool cred_cap_issubset(const struct cred *set, const struct cred *subset)
330 {
331 	const struct user_namespace *set_ns = set->user_ns;
332 	const struct user_namespace *subset_ns = subset->user_ns;
333 
334 	/* If the two credentials are in the same user namespace see if
335 	 * the capabilities of subset are a subset of set.
336 	 */
337 	if (set_ns == subset_ns)
338 		return cap_issubset(subset->cap_permitted, set->cap_permitted);
339 
340 	/* The credentials are in a different user namespaces
341 	 * therefore one is a subset of the other only if a set is an
342 	 * ancestor of subset and set->euid is owner of subset or one
343 	 * of subsets ancestors.
344 	 */
345 	for (;subset_ns != &init_user_ns; subset_ns = subset_ns->parent) {
346 		if ((set_ns == subset_ns->parent)  &&
347 		    uid_eq(subset_ns->owner, set->euid))
348 			return true;
349 	}
350 
351 	return false;
352 }
353 
354 /**
355  * commit_creds - Install new credentials upon the current task
356  * @new: The credentials to be assigned
357  *
358  * Install a new set of credentials to the current task, using RCU to replace
359  * the old set.  Both the objective and the subjective credentials pointers are
360  * updated.  This function may not be called if the subjective credentials are
361  * in an overridden state.
362  *
363  * This function eats the caller's reference to the new credentials.
364  *
365  * Always returns 0 thus allowing this function to be tail-called at the end
366  * of, say, sys_setgid().
367  */
368 int commit_creds(struct cred *new)
369 {
370 	struct task_struct *task = current;
371 	const struct cred *old = task->real_cred;
372 
373 	kdebug("commit_creds(%p{%ld})", new,
374 	       atomic_long_read(&new->usage));
375 
376 	BUG_ON(task->cred != old);
377 	BUG_ON(atomic_long_read(&new->usage) < 1);
378 
379 	get_cred(new); /* we will require a ref for the subj creds too */
380 
381 	/* dumpability changes */
382 	if (!uid_eq(old->euid, new->euid) ||
383 	    !gid_eq(old->egid, new->egid) ||
384 	    !uid_eq(old->fsuid, new->fsuid) ||
385 	    !gid_eq(old->fsgid, new->fsgid) ||
386 	    !cred_cap_issubset(old, new)) {
387 		if (task->mm)
388 			set_dumpable(task->mm, suid_dumpable);
389 		task->pdeath_signal = 0;
390 		/*
391 		 * If a task drops privileges and becomes nondumpable,
392 		 * the dumpability change must become visible before
393 		 * the credential change; otherwise, a __ptrace_may_access()
394 		 * racing with this change may be able to attach to a task it
395 		 * shouldn't be able to attach to (as if the task had dropped
396 		 * privileges without becoming nondumpable).
397 		 * Pairs with a read barrier in __ptrace_may_access().
398 		 */
399 		smp_wmb();
400 	}
401 
402 	/* alter the thread keyring */
403 	if (!uid_eq(new->fsuid, old->fsuid))
404 		key_fsuid_changed(new);
405 	if (!gid_eq(new->fsgid, old->fsgid))
406 		key_fsgid_changed(new);
407 
408 	/* do it
409 	 * RLIMIT_NPROC limits on user->processes have already been checked
410 	 * in set_user().
411 	 */
412 	if (new->user != old->user || new->user_ns != old->user_ns)
413 		inc_rlimit_ucounts(new->ucounts, UCOUNT_RLIMIT_NPROC, 1);
414 
415 	rcu_assign_pointer(task->real_cred, new);
416 	rcu_assign_pointer(task->cred, new);
417 	if (new->user != old->user || new->user_ns != old->user_ns)
418 		dec_rlimit_ucounts(old->ucounts, UCOUNT_RLIMIT_NPROC, 1);
419 	if (new->user_ns != old->user_ns)
420 		switch_cred_namespaces(old, new);
421 
422 	/* send notifications */
423 	if (!uid_eq(new->uid,   old->uid)  ||
424 	    !uid_eq(new->euid,  old->euid) ||
425 	    !uid_eq(new->suid,  old->suid) ||
426 	    !uid_eq(new->fsuid, old->fsuid))
427 		proc_id_connector(task, PROC_EVENT_UID);
428 
429 	if (!gid_eq(new->gid,   old->gid)  ||
430 	    !gid_eq(new->egid,  old->egid) ||
431 	    !gid_eq(new->sgid,  old->sgid) ||
432 	    !gid_eq(new->fsgid, old->fsgid))
433 		proc_id_connector(task, PROC_EVENT_GID);
434 
435 	/* release the old obj and subj refs both */
436 	put_cred_many(old, 2);
437 	return 0;
438 }
439 EXPORT_SYMBOL(commit_creds);
440 
441 /**
442  * abort_creds - Discard a set of credentials and unlock the current task
443  * @new: The credentials that were going to be applied
444  *
445  * Discard a set of credentials that were under construction and unlock the
446  * current task.
447  */
448 void abort_creds(struct cred *new)
449 {
450 	kdebug("abort_creds(%p{%ld})", new,
451 	       atomic_long_read(&new->usage));
452 
453 	BUG_ON(atomic_long_read(&new->usage) < 1);
454 	put_cred(new);
455 }
456 EXPORT_SYMBOL(abort_creds);
457 
458 /**
459  * cred_fscmp - Compare two credentials with respect to filesystem access.
460  * @a: The first credential
461  * @b: The second credential
462  *
463  * cred_cmp() will return zero if both credentials have the same
464  * fsuid, fsgid, and supplementary groups.  That is, if they will both
465  * provide the same access to files based on mode/uid/gid.
466  * If the credentials are different, then either -1 or 1 will
467  * be returned depending on whether @a comes before or after @b
468  * respectively in an arbitrary, but stable, ordering of credentials.
469  *
470  * Return: -1, 0, or 1 depending on comparison
471  */
472 int cred_fscmp(const struct cred *a, const struct cred *b)
473 {
474 	struct group_info *ga, *gb;
475 	int g;
476 
477 	if (a == b)
478 		return 0;
479 	if (uid_lt(a->fsuid, b->fsuid))
480 		return -1;
481 	if (uid_gt(a->fsuid, b->fsuid))
482 		return 1;
483 
484 	if (gid_lt(a->fsgid, b->fsgid))
485 		return -1;
486 	if (gid_gt(a->fsgid, b->fsgid))
487 		return 1;
488 
489 	ga = a->group_info;
490 	gb = b->group_info;
491 	if (ga == gb)
492 		return 0;
493 	if (ga == NULL)
494 		return -1;
495 	if (gb == NULL)
496 		return 1;
497 	if (ga->ngroups < gb->ngroups)
498 		return -1;
499 	if (ga->ngroups > gb->ngroups)
500 		return 1;
501 
502 	for (g = 0; g < ga->ngroups; g++) {
503 		if (gid_lt(ga->gid[g], gb->gid[g]))
504 			return -1;
505 		if (gid_gt(ga->gid[g], gb->gid[g]))
506 			return 1;
507 	}
508 	return 0;
509 }
510 EXPORT_SYMBOL(cred_fscmp);
511 
512 int set_cred_ucounts(struct cred *new)
513 {
514 	struct ucounts *new_ucounts, *old_ucounts = new->ucounts;
515 
516 	/*
517 	 * This optimization is needed because alloc_ucounts() uses locks
518 	 * for table lookups.
519 	 */
520 	if (old_ucounts->ns == new->user_ns && uid_eq(old_ucounts->uid, new->uid))
521 		return 0;
522 
523 	if (!(new_ucounts = alloc_ucounts(new->user_ns, new->uid)))
524 		return -EAGAIN;
525 
526 	new->ucounts = new_ucounts;
527 	put_ucounts(old_ucounts);
528 
529 	return 0;
530 }
531 
532 /*
533  * initialise the credentials stuff
534  */
535 void __init cred_init(void)
536 {
537 	/* allocate a slab in which we can store credentials */
538 	cred_jar = KMEM_CACHE(cred,
539 			      SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT);
540 }
541 
542 /**
543  * prepare_kernel_cred - Prepare a set of credentials for a kernel service
544  * @daemon: A userspace daemon to be used as a reference
545  *
546  * Prepare a set of credentials for a kernel service.  This can then be used to
547  * override a task's own credentials so that work can be done on behalf of that
548  * task that requires a different subjective context.
549  *
550  * @daemon is used to provide a base cred, with the security data derived from
551  * that; if this is "&init_task", they'll be set to 0, no groups, full
552  * capabilities, and no keys.
553  *
554  * The caller may change these controls afterwards if desired.
555  *
556  * Returns the new credentials or NULL if out of memory.
557  */
558 struct cred *prepare_kernel_cred(struct task_struct *daemon)
559 {
560 	const struct cred *old;
561 	struct cred *new;
562 
563 	if (WARN_ON_ONCE(!daemon))
564 		return NULL;
565 
566 	new = kmem_cache_alloc(cred_jar, GFP_KERNEL);
567 	if (!new)
568 		return NULL;
569 
570 	kdebug("prepare_kernel_cred() alloc %p", new);
571 
572 	old = get_task_cred(daemon);
573 
574 	*new = *old;
575 	new->non_rcu = 0;
576 	atomic_long_set(&new->usage, 1);
577 	get_uid(new->user);
578 	get_user_ns(new->user_ns);
579 	get_group_info(new->group_info);
580 
581 #ifdef CONFIG_KEYS
582 	new->session_keyring = NULL;
583 	new->process_keyring = NULL;
584 	new->thread_keyring = NULL;
585 	new->request_key_auth = NULL;
586 	new->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
587 #endif
588 
589 #ifdef CONFIG_SECURITY
590 	new->security = NULL;
591 #endif
592 	new->ucounts = get_ucounts(new->ucounts);
593 	if (!new->ucounts)
594 		goto error;
595 
596 	if (security_prepare_creds(new, old, GFP_KERNEL_ACCOUNT) < 0)
597 		goto error;
598 
599 	put_cred(old);
600 	return new;
601 
602 error:
603 	put_cred(new);
604 	put_cred(old);
605 	return NULL;
606 }
607 EXPORT_SYMBOL(prepare_kernel_cred);
608 
609 /**
610  * set_security_override - Set the security ID in a set of credentials
611  * @new: The credentials to alter
612  * @secid: The LSM security ID to set
613  *
614  * Set the LSM security ID in a set of credentials so that the subjective
615  * security is overridden when an alternative set of credentials is used.
616  */
617 int set_security_override(struct cred *new, u32 secid)
618 {
619 	return security_kernel_act_as(new, secid);
620 }
621 EXPORT_SYMBOL(set_security_override);
622 
623 /**
624  * set_security_override_from_ctx - Set the security ID in a set of credentials
625  * @new: The credentials to alter
626  * @secctx: The LSM security context to generate the security ID from.
627  *
628  * Set the LSM security ID in a set of credentials so that the subjective
629  * security is overridden when an alternative set of credentials is used.  The
630  * security ID is specified in string form as a security context to be
631  * interpreted by the LSM.
632  */
633 int set_security_override_from_ctx(struct cred *new, const char *secctx)
634 {
635 	u32 secid;
636 	int ret;
637 
638 	ret = security_secctx_to_secid(secctx, strlen(secctx), &secid);
639 	if (ret < 0)
640 		return ret;
641 
642 	return set_security_override(new, secid);
643 }
644 EXPORT_SYMBOL(set_security_override_from_ctx);
645 
646 /**
647  * set_create_files_as - Set the LSM file create context in a set of credentials
648  * @new: The credentials to alter
649  * @inode: The inode to take the context from
650  *
651  * Change the LSM file creation context in a set of credentials to be the same
652  * as the object context of the specified inode, so that the new inodes have
653  * the same MAC context as that inode.
654  */
655 int set_create_files_as(struct cred *new, struct inode *inode)
656 {
657 	if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
658 		return -EINVAL;
659 	new->fsuid = inode->i_uid;
660 	new->fsgid = inode->i_gid;
661 	return security_kernel_create_files_as(new, inode);
662 }
663 EXPORT_SYMBOL(set_create_files_as);
664