xref: /linux/kernel/cred.c (revision 6b3f7af57881f6d6250c6dcc4d910fe8e855a607)
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 		/* mm-less tasks share init_task's exec_state */
388 		if (task->mm)
389 			task_exec_state_set_dumpable(suid_dumpable);
390 		task->pdeath_signal = 0;
391 		/*
392 		 * If a task drops privileges and becomes nondumpable,
393 		 * the dumpability change must become visible before
394 		 * the credential change; otherwise, a __ptrace_may_access()
395 		 * racing with this change may be able to attach to a task it
396 		 * shouldn't be able to attach to (as if the task had dropped
397 		 * privileges without becoming nondumpable).
398 		 * Pairs with a read barrier in __ptrace_may_access().
399 		 */
400 		smp_wmb();
401 	}
402 
403 	/* alter the thread keyring */
404 	if (!uid_eq(new->fsuid, old->fsuid))
405 		key_fsuid_changed(new);
406 	if (!gid_eq(new->fsgid, old->fsgid))
407 		key_fsgid_changed(new);
408 
409 	/* do it
410 	 * RLIMIT_NPROC limits on user->processes have already been checked
411 	 * in set_user().
412 	 */
413 	if (new->user != old->user || new->user_ns != old->user_ns)
414 		inc_rlimit_ucounts(new->ucounts, UCOUNT_RLIMIT_NPROC, 1);
415 
416 	rcu_assign_pointer(task->real_cred, new);
417 	rcu_assign_pointer(task->cred, new);
418 	if (new->user != old->user || new->user_ns != old->user_ns)
419 		dec_rlimit_ucounts(old->ucounts, UCOUNT_RLIMIT_NPROC, 1);
420 	if (new->user_ns != old->user_ns)
421 		switch_cred_namespaces(old, new);
422 
423 	/* send notifications */
424 	if (!uid_eq(new->uid,   old->uid)  ||
425 	    !uid_eq(new->euid,  old->euid) ||
426 	    !uid_eq(new->suid,  old->suid) ||
427 	    !uid_eq(new->fsuid, old->fsuid))
428 		proc_id_connector(task, PROC_EVENT_UID);
429 
430 	if (!gid_eq(new->gid,   old->gid)  ||
431 	    !gid_eq(new->egid,  old->egid) ||
432 	    !gid_eq(new->sgid,  old->sgid) ||
433 	    !gid_eq(new->fsgid, old->fsgid))
434 		proc_id_connector(task, PROC_EVENT_GID);
435 
436 	/* release the old obj and subj refs both */
437 	put_cred_many(old, 2);
438 	return 0;
439 }
440 EXPORT_SYMBOL(commit_creds);
441 
442 /**
443  * abort_creds - Discard a set of credentials and unlock the current task
444  * @new: The credentials that were going to be applied
445  *
446  * Discard a set of credentials that were under construction and unlock the
447  * current task.
448  */
449 void abort_creds(struct cred *new)
450 {
451 	kdebug("abort_creds(%p{%ld})", new,
452 	       atomic_long_read(&new->usage));
453 
454 	BUG_ON(atomic_long_read(&new->usage) < 1);
455 	put_cred(new);
456 }
457 EXPORT_SYMBOL(abort_creds);
458 
459 /**
460  * cred_fscmp - Compare two credentials with respect to filesystem access.
461  * @a: The first credential
462  * @b: The second credential
463  *
464  * cred_cmp() will return zero if both credentials have the same
465  * fsuid, fsgid, and supplementary groups.  That is, if they will both
466  * provide the same access to files based on mode/uid/gid.
467  * If the credentials are different, then either -1 or 1 will
468  * be returned depending on whether @a comes before or after @b
469  * respectively in an arbitrary, but stable, ordering of credentials.
470  *
471  * Return: -1, 0, or 1 depending on comparison
472  */
473 int cred_fscmp(const struct cred *a, const struct cred *b)
474 {
475 	struct group_info *ga, *gb;
476 	int g;
477 
478 	if (a == b)
479 		return 0;
480 	if (uid_lt(a->fsuid, b->fsuid))
481 		return -1;
482 	if (uid_gt(a->fsuid, b->fsuid))
483 		return 1;
484 
485 	if (gid_lt(a->fsgid, b->fsgid))
486 		return -1;
487 	if (gid_gt(a->fsgid, b->fsgid))
488 		return 1;
489 
490 	ga = a->group_info;
491 	gb = b->group_info;
492 	if (ga == gb)
493 		return 0;
494 	if (ga == NULL)
495 		return -1;
496 	if (gb == NULL)
497 		return 1;
498 	if (ga->ngroups < gb->ngroups)
499 		return -1;
500 	if (ga->ngroups > gb->ngroups)
501 		return 1;
502 
503 	for (g = 0; g < ga->ngroups; g++) {
504 		if (gid_lt(ga->gid[g], gb->gid[g]))
505 			return -1;
506 		if (gid_gt(ga->gid[g], gb->gid[g]))
507 			return 1;
508 	}
509 	return 0;
510 }
511 EXPORT_SYMBOL(cred_fscmp);
512 
513 int set_cred_ucounts(struct cred *new)
514 {
515 	struct ucounts *new_ucounts, *old_ucounts = new->ucounts;
516 
517 	/*
518 	 * This optimization is needed because alloc_ucounts() uses locks
519 	 * for table lookups.
520 	 */
521 	if (old_ucounts->ns == new->user_ns && uid_eq(old_ucounts->uid, new->uid))
522 		return 0;
523 
524 	if (!(new_ucounts = alloc_ucounts(new->user_ns, new->uid)))
525 		return -EAGAIN;
526 
527 	new->ucounts = new_ucounts;
528 	put_ucounts(old_ucounts);
529 
530 	return 0;
531 }
532 
533 /*
534  * initialise the credentials stuff
535  */
536 void __init cred_init(void)
537 {
538 	/* allocate a slab in which we can store credentials */
539 	cred_jar = KMEM_CACHE(cred,
540 			      SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT);
541 }
542 
543 /**
544  * prepare_kernel_cred - Prepare a set of credentials for a kernel service
545  * @daemon: A userspace daemon to be used as a reference
546  *
547  * Prepare a set of credentials for a kernel service.  This can then be used to
548  * override a task's own credentials so that work can be done on behalf of that
549  * task that requires a different subjective context.
550  *
551  * @daemon is used to provide a base cred, with the security data derived from
552  * that; if this is "&init_task", they'll be set to 0, no groups, full
553  * capabilities, and no keys.
554  *
555  * The caller may change these controls afterwards if desired.
556  *
557  * Returns the new credentials or NULL if out of memory.
558  */
559 struct cred *prepare_kernel_cred(struct task_struct *daemon)
560 {
561 	const struct cred *old;
562 	struct cred *new;
563 
564 	if (WARN_ON_ONCE(!daemon))
565 		return NULL;
566 
567 	new = kmem_cache_alloc(cred_jar, GFP_KERNEL);
568 	if (!new)
569 		return NULL;
570 
571 	kdebug("prepare_kernel_cred() alloc %p", new);
572 
573 	old = get_task_cred(daemon);
574 
575 	*new = *old;
576 	new->non_rcu = 0;
577 	atomic_long_set(&new->usage, 1);
578 	get_uid(new->user);
579 	get_user_ns(new->user_ns);
580 	get_group_info(new->group_info);
581 
582 #ifdef CONFIG_KEYS
583 	new->session_keyring = NULL;
584 	new->process_keyring = NULL;
585 	new->thread_keyring = NULL;
586 	new->request_key_auth = NULL;
587 	new->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
588 #endif
589 
590 #ifdef CONFIG_SECURITY
591 	new->security = NULL;
592 #endif
593 	new->ucounts = get_ucounts(new->ucounts);
594 	if (!new->ucounts)
595 		goto error;
596 
597 	if (security_prepare_creds(new, old, GFP_KERNEL_ACCOUNT) < 0)
598 		goto error;
599 
600 	put_cred(old);
601 	return new;
602 
603 error:
604 	put_cred(new);
605 	put_cred(old);
606 	return NULL;
607 }
608 EXPORT_SYMBOL(prepare_kernel_cred);
609 
610 /**
611  * set_security_override - Set the security ID in a set of credentials
612  * @new: The credentials to alter
613  * @secid: The LSM security ID to set
614  *
615  * Set the LSM security ID in a set of credentials so that the subjective
616  * security is overridden when an alternative set of credentials is used.
617  */
618 int set_security_override(struct cred *new, u32 secid)
619 {
620 	return security_kernel_act_as(new, secid);
621 }
622 EXPORT_SYMBOL(set_security_override);
623 
624 /**
625  * set_create_files_as - Set the LSM file create context in a set of credentials
626  * @new: The credentials to alter
627  * @inode: The inode to take the context from
628  *
629  * Change the LSM file creation context in a set of credentials to be the same
630  * as the object context of the specified inode, so that the new inodes have
631  * the same MAC context as that inode.
632  */
633 int set_create_files_as(struct cred *new, struct inode *inode)
634 {
635 	if (!uid_valid(inode->i_uid) || !gid_valid(inode->i_gid))
636 		return -EINVAL;
637 	new->fsuid = inode->i_uid;
638 	new->fsgid = inode->i_gid;
639 	return security_kernel_create_files_as(new, inode);
640 }
641 EXPORT_SYMBOL(set_create_files_as);
642