xref: /linux/security/landlock/tsync.c (revision fa20aeb95d72da9dd78a3c9b24e996b5d9219888)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Landlock - Cross-thread ruleset enforcement
4  *
5  * Copyright © 2025 Google LLC
6  */
7 
8 #include <linux/atomic.h>
9 #include <linux/cleanup.h>
10 #include <linux/completion.h>
11 #include <linux/cred.h>
12 #include <linux/errno.h>
13 #include <linux/overflow.h>
14 #include <linux/rcupdate.h>
15 #include <linux/sched.h>
16 #include <linux/sched/signal.h>
17 #include <linux/sched/task.h>
18 #include <linux/slab.h>
19 #include <linux/task_work.h>
20 
21 #include "cred.h"
22 #include "tsync.h"
23 
24 /*
25  * Shared state between multiple threads which are enforcing Landlock rulesets
26  * in lockstep with each other.
27  */
28 struct tsync_shared_context {
29 	/* The old and tentative new creds of the calling thread. */
30 	const struct cred *old_cred;
31 	const struct cred *new_cred;
32 
33 	/* True if sibling tasks need to set the no_new_privs flag. */
34 	bool set_no_new_privs;
35 
36 	/* An error encountered in preparation step, or 0. */
37 	atomic_t preparation_error;
38 
39 	/*
40 	 * Barrier after preparation step in restrict_one_thread.
41 	 * The calling thread waits for completion.
42 	 *
43 	 * Re-initialized on every round of looking for newly spawned threads.
44 	 */
45 	atomic_t num_preparing;
46 	struct completion all_prepared;
47 
48 	/* Sibling threads wait for completion. */
49 	struct completion ready_to_commit;
50 
51 	/*
52 	 * Barrier after commit step (used by syscall impl to wait for
53 	 * completion).
54 	 */
55 	atomic_t num_unfinished;
56 	struct completion all_finished;
57 };
58 
59 struct tsync_work {
60 	struct callback_head work;
61 	struct task_struct *task;
62 	struct tsync_shared_context *shared_ctx;
63 };
64 
65 /*
66  * restrict_one_thread - update a thread's Landlock domain in lockstep with the
67  * other threads in the same process
68  *
69  * When this is run, the same function gets run in all other threads in the same
70  * process (except for the calling thread which called landlock_restrict_self).
71  * The concurrently running invocations of restrict_one_thread coordinate
72  * through the shared ctx object to do their work in lockstep to implement
73  * all-or-nothing semantics for enforcing the new Landlock domain.
74  *
75  * Afterwards, depending on the presence of an error, all threads either commit
76  * or abort the prepared credentials.  The commit operation can not fail any
77  * more.
78  */
79 static void restrict_one_thread(struct tsync_shared_context *ctx)
80 {
81 	int err;
82 	struct cred *cred = NULL;
83 
84 	if (current_cred() == ctx->old_cred) {
85 		/*
86 		 * Switch out old_cred with new_cred, if possible.
87 		 *
88 		 * In the common case, where all threads initially point to the same
89 		 * struct cred, this optimization avoids creating separate redundant
90 		 * credentials objects for each, which would all have the same contents.
91 		 *
92 		 * Note: We are intentionally dropping the const qualifier here, because
93 		 * it is required by commit_creds() and abort_creds().
94 		 */
95 		cred = (struct cred *)get_cred(ctx->new_cred);
96 	} else {
97 		/* Else, prepare new creds and populate them. */
98 		cred = prepare_creds();
99 
100 		if (!cred) {
101 			atomic_set(&ctx->preparation_error, -ENOMEM);
102 
103 			/*
104 			 * Even on error, we need to adhere to the protocol and coordinate
105 			 * with concurrently running invocations.
106 			 */
107 			if (atomic_dec_return(&ctx->num_preparing) == 0)
108 				complete_all(&ctx->all_prepared);
109 
110 			goto out;
111 		}
112 
113 		landlock_cred_copy(landlock_cred(cred),
114 				   landlock_cred(ctx->new_cred));
115 	}
116 
117 	/*
118 	 * Barrier: Wait until all threads are done preparing.
119 	 * After this point, we can have no more failures.
120 	 */
121 	if (atomic_dec_return(&ctx->num_preparing) == 0)
122 		complete_all(&ctx->all_prepared);
123 
124 	/*
125 	 * Wait for signal from calling thread that it's safe to read the
126 	 * preparation error now and we are ready to commit (or abort).
127 	 */
128 	wait_for_completion(&ctx->ready_to_commit);
129 
130 	/* Abort the commit if any of the other threads had an error. */
131 	err = atomic_read(&ctx->preparation_error);
132 	if (err) {
133 		abort_creds(cred);
134 		goto out;
135 	}
136 
137 	/*
138 	 * Make sure that all sibling tasks fulfill the no_new_privs prerequisite.
139 	 * (This is in line with Seccomp's SECCOMP_FILTER_FLAG_TSYNC logic in
140 	 * kernel/seccomp.c)
141 	 */
142 	if (ctx->set_no_new_privs)
143 		task_set_no_new_privs(current);
144 
145 	commit_creds(cred);
146 
147 out:
148 	/* Notify the calling thread once all threads are done */
149 	if (atomic_dec_return(&ctx->num_unfinished) == 0)
150 		complete_all(&ctx->all_finished);
151 }
152 
153 /*
154  * restrict_one_thread_callback - task_work callback for restricting a thread
155  *
156  * Calls restrict_one_thread with the struct landlock_shared_tsync_context.
157  */
158 static void restrict_one_thread_callback(struct callback_head *work)
159 {
160 	struct tsync_work *ctx = container_of(work, struct tsync_work, work);
161 
162 	restrict_one_thread(ctx->shared_ctx);
163 }
164 
165 /*
166  * struct tsync_works - a growable array of per-task contexts
167  *
168  * The zero-initialized struct represents the empty array.
169  */
170 struct tsync_works {
171 	struct tsync_work **works;
172 	size_t size;
173 	size_t capacity;
174 };
175 
176 /*
177  * tsync_works_provide - provides a preallocated tsync_work for the given task
178  *
179  * This also stores a task pointer in the context and increments the reference
180  * count of the task.
181  *
182  * This function may fail in the case where we did not preallocate sufficient
183  * capacity.  This can legitimately happen if new threads get started after we
184  * grew the capacity.
185  *
186  * Return: A pointer to the preallocated context struct with task filled in, or
187  * NULL if preallocated context structs ran out.
188  */
189 static struct tsync_work *tsync_works_provide(struct tsync_works *s,
190 					      struct task_struct *task)
191 {
192 	struct tsync_work *ctx;
193 
194 	if (s->size >= s->capacity)
195 		return NULL;
196 
197 	ctx = s->works[s->size];
198 	s->size++;
199 
200 	ctx->task = get_task_struct(task);
201 	return ctx;
202 }
203 
204 /**
205  * tsync_works_trim - Put the last tsync_work element
206  *
207  * @s: TSYNC works to trim.
208  *
209  * Put the last task and decrement the size of @s.
210  *
211  * This helper does not cancel a running task, but just reset the last element
212  * to zero.
213  */
214 static void tsync_works_trim(struct tsync_works *s)
215 {
216 	struct tsync_work *ctx;
217 
218 	if (WARN_ON_ONCE(s->size <= 0))
219 		return;
220 
221 	ctx = s->works[s->size - 1];
222 
223 	/*
224 	 * For consistency, remove the task from ctx so that it does not look like
225 	 * we handed it a task_work.
226 	 */
227 	put_task_struct(ctx->task);
228 	*ctx = (typeof(*ctx)){};
229 
230 	/*
231 	 * Cancel the tsync_works_provide() change to recycle the reserved memory
232 	 * for the next thread, if any.  This also ensures that cancel_tsync_works()
233 	 * and tsync_works_release() do not see any NULL task pointers.
234 	 */
235 	s->size--;
236 }
237 
238 /*
239  * tsync_works_grow_by - preallocates space for n more contexts in s
240  *
241  * On a successful return, the subsequent n calls to tsync_works_provide() are
242  * guaranteed to succeed.  (size + n <= capacity)
243  *
244  * Return: 0 if sufficient space for n more elements could be provided, -ENOMEM
245  * on allocation errors, -EOVERFLOW in case of integer overflow.
246  */
247 static int tsync_works_grow_by(struct tsync_works *s, size_t n, gfp_t flags)
248 {
249 	size_t i;
250 	size_t new_capacity;
251 	struct tsync_work **works;
252 	struct tsync_work *work;
253 
254 	if (check_add_overflow(s->size, n, &new_capacity))
255 		return -EOVERFLOW;
256 
257 	/* No need to reallocate if s already has sufficient capacity. */
258 	if (new_capacity <= s->capacity)
259 		return 0;
260 
261 	works = krealloc_array(s->works, new_capacity, sizeof(s->works[0]),
262 			       flags);
263 	if (!works)
264 		return -ENOMEM;
265 
266 	s->works = works;
267 
268 	for (i = s->capacity; i < new_capacity; i++) {
269 		work = kzalloc_obj(*work, flags);
270 		if (!work) {
271 			/*
272 			 * Leave the object in a consistent state,
273 			 * but return an error.
274 			 */
275 			s->capacity = i;
276 			return -ENOMEM;
277 		}
278 		s->works[i] = work;
279 	}
280 	s->capacity = new_capacity;
281 	return 0;
282 }
283 
284 /*
285  * tsync_works_contains - checks for presence of task in s
286  */
287 static bool tsync_works_contains_task(const struct tsync_works *s,
288 				      const struct task_struct *task)
289 {
290 	size_t i;
291 
292 	for (i = 0; i < s->size; i++)
293 		if (s->works[i]->task == task)
294 			return true;
295 
296 	return false;
297 }
298 
299 /*
300  * tsync_works_release - frees memory held by s and drops all task references
301  *
302  * This does not free s itself, only the data structures held by it.
303  */
304 static void tsync_works_release(struct tsync_works *s)
305 {
306 	size_t i;
307 
308 	for (i = 0; i < s->size; i++) {
309 		if (WARN_ON_ONCE(!s->works[i]->task))
310 			continue;
311 
312 		put_task_struct(s->works[i]->task);
313 	}
314 
315 	for (i = 0; i < s->capacity; i++)
316 		kfree(s->works[i]);
317 
318 	kfree(s->works);
319 	s->works = NULL;
320 	s->size = 0;
321 	s->capacity = 0;
322 }
323 
324 /*
325  * count_additional_threads - counts the sibling threads that are not in works
326  */
327 static size_t count_additional_threads(const struct tsync_works *works)
328 {
329 	const struct task_struct *caller, *thread;
330 	size_t n = 0;
331 
332 	caller = current;
333 
334 	guard(rcu)();
335 
336 	for_each_thread(caller, thread) {
337 		/* Skip current, since it is initiating the sync. */
338 		if (thread == caller)
339 			continue;
340 
341 		/* Skip exited threads. */
342 		if (thread->flags & PF_EXITING)
343 			continue;
344 
345 		/* Skip threads that we have already seen. */
346 		if (tsync_works_contains_task(works, thread))
347 			continue;
348 
349 		n++;
350 	}
351 	return n;
352 }
353 
354 /*
355  * schedule_task_work - adds task_work for all eligible sibling threads
356  *                      which have not been scheduled yet
357  *
358  * For each added task_work, atomically increments shared_ctx->num_preparing and
359  * shared_ctx->num_unfinished.
360  *
361  * Return: True if at least one eligible sibling thread was found, false
362  * otherwise.
363  */
364 static bool schedule_task_work(struct tsync_works *works,
365 			       struct tsync_shared_context *shared_ctx)
366 {
367 	int err;
368 	const struct task_struct *caller;
369 	struct task_struct *thread;
370 	struct tsync_work *ctx;
371 	bool found_more_threads = false;
372 
373 	caller = current;
374 
375 	guard(rcu)();
376 
377 	for_each_thread(caller, thread) {
378 		/* Skip current, since it is initiating the sync. */
379 		if (thread == caller)
380 			continue;
381 
382 		/* Skip exited threads. */
383 		if (thread->flags & PF_EXITING)
384 			continue;
385 
386 		/* Skip threads that we already looked at. */
387 		if (tsync_works_contains_task(works, thread))
388 			continue;
389 
390 		/*
391 		 * We found a sibling thread that is not doing its task_work yet, and
392 		 * which might spawn new threads before our task work runs, so we need
393 		 * at least one more round in the outer loop.
394 		 */
395 		found_more_threads = true;
396 
397 		ctx = tsync_works_provide(works, thread);
398 		if (!ctx) {
399 			/*
400 			 * We ran out of preallocated contexts -- we need to try again with
401 			 * this thread at a later time!
402 			 * found_more_threads is already true at this point.
403 			 */
404 			break;
405 		}
406 
407 		ctx->shared_ctx = shared_ctx;
408 
409 		atomic_inc(&shared_ctx->num_preparing);
410 		atomic_inc(&shared_ctx->num_unfinished);
411 
412 		init_task_work(&ctx->work, restrict_one_thread_callback);
413 		err = task_work_add(thread, &ctx->work, TWA_SIGNAL);
414 		if (unlikely(err)) {
415 			/*
416 			 * task_work_add() only fails if the task is about to exit.  We
417 			 * checked that earlier, but it can happen as a race.  Resume
418 			 * without setting an error, as the task is probably gone in the
419 			 * next loop iteration.
420 			 */
421 			tsync_works_trim(works);
422 
423 			atomic_dec(&shared_ctx->num_preparing);
424 			atomic_dec(&shared_ctx->num_unfinished);
425 		}
426 	}
427 
428 	return found_more_threads;
429 }
430 
431 /*
432  * cancel_tsync_works - cancel all task works where it is possible
433  *
434  * Task works can be canceled as long as they are still queued and have not
435  * started running.  If they get canceled, we decrement
436  * shared_ctx->num_preparing and shared_ctx->num_unfished and mark the two
437  * completions if needed, as if the task was never scheduled.
438  */
439 static void cancel_tsync_works(const struct tsync_works *works,
440 			       struct tsync_shared_context *shared_ctx)
441 {
442 	size_t i;
443 
444 	for (i = 0; i < works->size; i++) {
445 		if (WARN_ON_ONCE(!works->works[i]->task))
446 			continue;
447 
448 		if (!task_work_cancel(works->works[i]->task,
449 				      &works->works[i]->work))
450 			continue;
451 
452 		/* After dequeueing, act as if the task work had executed. */
453 
454 		if (atomic_dec_return(&shared_ctx->num_preparing) == 0)
455 			complete_all(&shared_ctx->all_prepared);
456 
457 		if (atomic_dec_return(&shared_ctx->num_unfinished) == 0)
458 			complete_all(&shared_ctx->all_finished);
459 	}
460 }
461 
462 /*
463  * restrict_sibling_threads - enables a Landlock policy for all sibling threads
464  */
465 int landlock_restrict_sibling_threads(const struct cred *old_cred,
466 				      const struct cred *new_cred)
467 {
468 	int err;
469 	struct tsync_shared_context shared_ctx;
470 	struct tsync_works works = {};
471 	size_t newly_discovered_threads;
472 	bool found_more_threads;
473 
474 	atomic_set(&shared_ctx.preparation_error, 0);
475 	init_completion(&shared_ctx.all_prepared);
476 	init_completion(&shared_ctx.ready_to_commit);
477 	atomic_set(&shared_ctx.num_unfinished, 1);
478 	init_completion(&shared_ctx.all_finished);
479 	shared_ctx.old_cred = old_cred;
480 	shared_ctx.new_cred = new_cred;
481 	shared_ctx.set_no_new_privs = task_no_new_privs(current);
482 
483 	/*
484 	 * Serialize concurrent TSYNC operations to prevent deadlocks when
485 	 * multiple threads call landlock_restrict_self() simultaneously.
486 	 * If the lock is already held, we gracefully yield by restarting the
487 	 * syscall. This allows the current thread to process pending
488 	 * task_works before retrying.
489 	 */
490 	if (!down_write_trylock(&current->signal->exec_update_lock))
491 		return restart_syscall();
492 
493 	/*
494 	 * We schedule a pseudo-signal task_work for each of the calling task's
495 	 * sibling threads.  In the task work, each thread:
496 	 *
497 	 * 1) runs prepare_creds() and writes back the error to
498 	 *    shared_ctx.preparation_error, if needed.
499 	 *
500 	 * 2) signals that it's done with prepare_creds() to the calling task.
501 	 *    (completion "all_prepared").
502 	 *
503 	 * 3) waits for the completion "ready_to_commit".  This is sent by the
504 	 *    calling task after ensuring that all sibling threads have done
505 	 *    with the "preparation" stage.
506 	 *
507 	 *    After this barrier is reached, it's safe to read
508 	 *    shared_ctx.preparation_error.
509 	 *
510 	 * 4) reads shared_ctx.preparation_error and then either does commit_creds()
511 	 *    or abort_creds().
512 	 *
513 	 * 5) signals that it's done altogether (barrier synchronization
514 	 *    "all_finished")
515 	 *
516 	 * Unlike seccomp, which modifies sibling tasks directly, we do not need to
517 	 * acquire the cred_guard_mutex and sighand->siglock:
518 	 *
519 	 * - As in our case, all threads are themselves exchanging their own struct
520 	 *   cred through the credentials API, no locks are needed for that.
521 	 * - Our for_each_thread() loops are protected by RCU.
522 	 * - We do not acquire a lock to keep the list of sibling threads stable
523 	 *   between our for_each_thread loops.  If the list of available sibling
524 	 *   threads changes between these for_each_thread loops, we make up for
525 	 *   that by continuing to look for threads until they are all discovered
526 	 *   and have entered their task_work, where they are unable to spawn new
527 	 *   threads.
528 	 */
529 	do {
530 		/* In RCU read-lock, count the threads we need. */
531 		newly_discovered_threads = count_additional_threads(&works);
532 
533 		if (newly_discovered_threads == 0)
534 			break; /* done */
535 
536 		err = tsync_works_grow_by(&works, newly_discovered_threads,
537 					  GFP_KERNEL_ACCOUNT);
538 		if (err) {
539 			atomic_set(&shared_ctx.preparation_error, err);
540 			break;
541 		}
542 
543 		/*
544 		 * The "all_prepared" barrier is used locally to the loop body, this use
545 		 * of for_each_thread().  We can reset it on each loop iteration because
546 		 * all previous loop iterations are done with it already.
547 		 *
548 		 * num_preparing is initialized to 1 so that the counter can not go to 0
549 		 * and mark the completion as done before all task works are registered.
550 		 * We decrement it at the end of the loop body.
551 		 */
552 		atomic_set(&shared_ctx.num_preparing, 1);
553 		reinit_completion(&shared_ctx.all_prepared);
554 
555 		/*
556 		 * In RCU read-lock, schedule task work on newly discovered sibling
557 		 * tasks.
558 		 */
559 		found_more_threads = schedule_task_work(&works, &shared_ctx);
560 
561 		/*
562 		 * Decrement num_preparing for current, to undo that we initialized it
563 		 * to 1 a few lines above.
564 		 */
565 		if (atomic_dec_return(&shared_ctx.num_preparing) > 0) {
566 			if (wait_for_completion_interruptible(
567 				    &shared_ctx.all_prepared)) {
568 				/* In case of interruption, we need to retry the system call. */
569 				atomic_set(&shared_ctx.preparation_error,
570 					   -ERESTARTNOINTR);
571 
572 				/*
573 				 * Opportunistic improvement: try to cancel task
574 				 * works for tasks that did not start running
575 				 * yet. We do not have a guarantee that it
576 				 * cancels any of the enqueued task works
577 				 * because task_work_run() might already have
578 				 * dequeued them.
579 				 */
580 				cancel_tsync_works(&works, &shared_ctx);
581 
582 				/*
583 				 * Break the loop with error. The cleanup code
584 				 * after the loop unblocks the remaining
585 				 * task_works.
586 				 */
587 				break;
588 			}
589 		}
590 	} while (found_more_threads &&
591 		 !atomic_read(&shared_ctx.preparation_error));
592 
593 	/*
594 	 * We now have either (a) all sibling threads blocking and in "prepared"
595 	 * state in the task work, or (b) the preparation error is set. Ask all
596 	 * threads to commit (or abort).
597 	 */
598 	complete_all(&shared_ctx.ready_to_commit);
599 
600 	/*
601 	 * Decrement num_unfinished for current, to undo that we initialized it to 1
602 	 * at the beginning.
603 	 */
604 	if (atomic_dec_return(&shared_ctx.num_unfinished) > 0)
605 		wait_for_completion(&shared_ctx.all_finished);
606 
607 	tsync_works_release(&works);
608 	up_write(&current->signal->exec_update_lock);
609 	return atomic_read(&shared_ctx.preparation_error);
610 }
611