xref: /linux/security/yama/yama_lsm.c (revision c532de5a67a70f8533d495f8f2aaa9a0491c3ad0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Yama Linux Security Module
4  *
5  * Author: Kees Cook <keescook@chromium.org>
6  *
7  * Copyright (C) 2010 Canonical, Ltd.
8  * Copyright (C) 2011 The Chromium OS Authors.
9  */
10 
11 #include <linux/lsm_hooks.h>
12 #include <linux/sysctl.h>
13 #include <linux/ptrace.h>
14 #include <linux/prctl.h>
15 #include <linux/ratelimit.h>
16 #include <linux/workqueue.h>
17 #include <linux/string_helpers.h>
18 #include <linux/task_work.h>
19 #include <linux/sched.h>
20 #include <linux/spinlock.h>
21 #include <uapi/linux/lsm.h>
22 
23 #define YAMA_SCOPE_DISABLED	0
24 #define YAMA_SCOPE_RELATIONAL	1
25 #define YAMA_SCOPE_CAPABILITY	2
26 #define YAMA_SCOPE_NO_ATTACH	3
27 
28 static int ptrace_scope = YAMA_SCOPE_RELATIONAL;
29 
30 /* describe a ptrace relationship for potential exception */
31 struct ptrace_relation {
32 	struct task_struct *tracer;
33 	struct task_struct *tracee;
34 	bool invalid;
35 	struct list_head node;
36 	struct rcu_head rcu;
37 };
38 
39 static LIST_HEAD(ptracer_relations);
40 static DEFINE_SPINLOCK(ptracer_relations_lock);
41 
42 static void yama_relation_cleanup(struct work_struct *work);
43 static DECLARE_WORK(yama_relation_work, yama_relation_cleanup);
44 
45 struct access_report_info {
46 	struct callback_head work;
47 	const char *access;
48 	struct task_struct *target;
49 	struct task_struct *agent;
50 };
51 
52 static void __report_access(struct callback_head *work)
53 {
54 	struct access_report_info *info =
55 		container_of(work, struct access_report_info, work);
56 	char *target_cmd, *agent_cmd;
57 
58 	target_cmd = kstrdup_quotable_cmdline(info->target, GFP_KERNEL);
59 	agent_cmd = kstrdup_quotable_cmdline(info->agent, GFP_KERNEL);
60 
61 	pr_notice_ratelimited(
62 		"ptrace %s of \"%s\"[%d] was attempted by \"%s\"[%d]\n",
63 		info->access, target_cmd, info->target->pid, agent_cmd,
64 		info->agent->pid);
65 
66 	kfree(agent_cmd);
67 	kfree(target_cmd);
68 
69 	put_task_struct(info->agent);
70 	put_task_struct(info->target);
71 	kfree(info);
72 }
73 
74 /* defers execution because cmdline access can sleep */
75 static void report_access(const char *access, struct task_struct *target,
76 				struct task_struct *agent)
77 {
78 	struct access_report_info *info;
79 	char agent_comm[sizeof(agent->comm)];
80 
81 	assert_spin_locked(&target->alloc_lock); /* for target->comm */
82 
83 	if (current->flags & PF_KTHREAD) {
84 		/* I don't think kthreads call task_work_run() before exiting.
85 		 * Imagine angry ranting about procfs here.
86 		 */
87 		pr_notice_ratelimited(
88 		    "ptrace %s of \"%s\"[%d] was attempted by \"%s\"[%d]\n",
89 		    access, target->comm, target->pid,
90 		    get_task_comm(agent_comm, agent), agent->pid);
91 		return;
92 	}
93 
94 	info = kmalloc(sizeof(*info), GFP_ATOMIC);
95 	if (!info)
96 		return;
97 	init_task_work(&info->work, __report_access);
98 	get_task_struct(target);
99 	get_task_struct(agent);
100 	info->access = access;
101 	info->target = target;
102 	info->agent = agent;
103 	if (task_work_add(current, &info->work, TWA_RESUME) == 0)
104 		return; /* success */
105 
106 	WARN(1, "report_access called from exiting task");
107 	put_task_struct(target);
108 	put_task_struct(agent);
109 	kfree(info);
110 }
111 
112 /**
113  * yama_relation_cleanup - remove invalid entries from the relation list
114  * @work: unused
115  *
116  */
117 static void yama_relation_cleanup(struct work_struct *work)
118 {
119 	struct ptrace_relation *relation;
120 
121 	spin_lock(&ptracer_relations_lock);
122 	rcu_read_lock();
123 	list_for_each_entry_rcu(relation, &ptracer_relations, node) {
124 		if (relation->invalid) {
125 			list_del_rcu(&relation->node);
126 			kfree_rcu(relation, rcu);
127 		}
128 	}
129 	rcu_read_unlock();
130 	spin_unlock(&ptracer_relations_lock);
131 }
132 
133 /**
134  * yama_ptracer_add - add/replace an exception for this tracer/tracee pair
135  * @tracer: the task_struct of the process doing the ptrace
136  * @tracee: the task_struct of the process to be ptraced
137  *
138  * Each tracee can have, at most, one tracer registered. Each time this
139  * is called, the prior registered tracer will be replaced for the tracee.
140  *
141  * Returns 0 if relationship was added, -ve on error.
142  */
143 static int yama_ptracer_add(struct task_struct *tracer,
144 			    struct task_struct *tracee)
145 {
146 	struct ptrace_relation *relation, *added;
147 
148 	added = kmalloc(sizeof(*added), GFP_KERNEL);
149 	if (!added)
150 		return -ENOMEM;
151 
152 	added->tracee = tracee;
153 	added->tracer = tracer;
154 	added->invalid = false;
155 
156 	spin_lock(&ptracer_relations_lock);
157 	rcu_read_lock();
158 	list_for_each_entry_rcu(relation, &ptracer_relations, node) {
159 		if (relation->invalid)
160 			continue;
161 		if (relation->tracee == tracee) {
162 			list_replace_rcu(&relation->node, &added->node);
163 			kfree_rcu(relation, rcu);
164 			goto out;
165 		}
166 	}
167 
168 	list_add_rcu(&added->node, &ptracer_relations);
169 
170 out:
171 	rcu_read_unlock();
172 	spin_unlock(&ptracer_relations_lock);
173 	return 0;
174 }
175 
176 /**
177  * yama_ptracer_del - remove exceptions related to the given tasks
178  * @tracer: remove any relation where tracer task matches
179  * @tracee: remove any relation where tracee task matches
180  */
181 static void yama_ptracer_del(struct task_struct *tracer,
182 			     struct task_struct *tracee)
183 {
184 	struct ptrace_relation *relation;
185 	bool marked = false;
186 
187 	rcu_read_lock();
188 	list_for_each_entry_rcu(relation, &ptracer_relations, node) {
189 		if (relation->invalid)
190 			continue;
191 		if (relation->tracee == tracee ||
192 		    (tracer && relation->tracer == tracer)) {
193 			relation->invalid = true;
194 			marked = true;
195 		}
196 	}
197 	rcu_read_unlock();
198 
199 	if (marked)
200 		schedule_work(&yama_relation_work);
201 }
202 
203 /**
204  * yama_task_free - check for task_pid to remove from exception list
205  * @task: task being removed
206  */
207 static void yama_task_free(struct task_struct *task)
208 {
209 	yama_ptracer_del(task, task);
210 }
211 
212 /**
213  * yama_task_prctl - check for Yama-specific prctl operations
214  * @option: operation
215  * @arg2: argument
216  * @arg3: argument
217  * @arg4: argument
218  * @arg5: argument
219  *
220  * Return 0 on success, -ve on error.  -ENOSYS is returned when Yama
221  * does not handle the given option.
222  */
223 static int yama_task_prctl(int option, unsigned long arg2, unsigned long arg3,
224 			   unsigned long arg4, unsigned long arg5)
225 {
226 	int rc = -ENOSYS;
227 	struct task_struct *myself = current;
228 
229 	switch (option) {
230 	case PR_SET_PTRACER:
231 		/* Since a thread can call prctl(), find the group leader
232 		 * before calling _add() or _del() on it, since we want
233 		 * process-level granularity of control. The tracer group
234 		 * leader checking is handled later when walking the ancestry
235 		 * at the time of PTRACE_ATTACH check.
236 		 */
237 		rcu_read_lock();
238 		if (!thread_group_leader(myself))
239 			myself = rcu_dereference(myself->group_leader);
240 		get_task_struct(myself);
241 		rcu_read_unlock();
242 
243 		if (arg2 == 0) {
244 			yama_ptracer_del(NULL, myself);
245 			rc = 0;
246 		} else if (arg2 == PR_SET_PTRACER_ANY || (int)arg2 == -1) {
247 			rc = yama_ptracer_add(NULL, myself);
248 		} else {
249 			struct task_struct *tracer;
250 
251 			tracer = find_get_task_by_vpid(arg2);
252 			if (!tracer) {
253 				rc = -EINVAL;
254 			} else {
255 				rc = yama_ptracer_add(tracer, myself);
256 				put_task_struct(tracer);
257 			}
258 		}
259 
260 		put_task_struct(myself);
261 		break;
262 	}
263 
264 	return rc;
265 }
266 
267 /**
268  * task_is_descendant - walk up a process family tree looking for a match
269  * @parent: the process to compare against while walking up from child
270  * @child: the process to start from while looking upwards for parent
271  *
272  * Returns 1 if child is a descendant of parent, 0 if not.
273  */
274 static int task_is_descendant(struct task_struct *parent,
275 			      struct task_struct *child)
276 {
277 	int rc = 0;
278 	struct task_struct *walker = child;
279 
280 	if (!parent || !child)
281 		return 0;
282 
283 	rcu_read_lock();
284 	if (!thread_group_leader(parent))
285 		parent = rcu_dereference(parent->group_leader);
286 	while (walker->pid > 0) {
287 		if (!thread_group_leader(walker))
288 			walker = rcu_dereference(walker->group_leader);
289 		if (walker == parent) {
290 			rc = 1;
291 			break;
292 		}
293 		walker = rcu_dereference(walker->real_parent);
294 	}
295 	rcu_read_unlock();
296 
297 	return rc;
298 }
299 
300 /**
301  * ptracer_exception_found - tracer registered as exception for this tracee
302  * @tracer: the task_struct of the process attempting ptrace
303  * @tracee: the task_struct of the process to be ptraced
304  *
305  * Returns 1 if tracer has a ptracer exception ancestor for tracee.
306  */
307 static int ptracer_exception_found(struct task_struct *tracer,
308 				   struct task_struct *tracee)
309 {
310 	int rc = 0;
311 	struct ptrace_relation *relation;
312 	struct task_struct *parent = NULL;
313 	bool found = false;
314 
315 	rcu_read_lock();
316 
317 	/*
318 	 * If there's already an active tracing relationship, then make an
319 	 * exception for the sake of other accesses, like process_vm_rw().
320 	 */
321 	parent = ptrace_parent(tracee);
322 	if (parent != NULL && same_thread_group(parent, tracer)) {
323 		rc = 1;
324 		goto unlock;
325 	}
326 
327 	/* Look for a PR_SET_PTRACER relationship. */
328 	if (!thread_group_leader(tracee))
329 		tracee = rcu_dereference(tracee->group_leader);
330 	list_for_each_entry_rcu(relation, &ptracer_relations, node) {
331 		if (relation->invalid)
332 			continue;
333 		if (relation->tracee == tracee) {
334 			parent = relation->tracer;
335 			found = true;
336 			break;
337 		}
338 	}
339 
340 	if (found && (parent == NULL || task_is_descendant(parent, tracer)))
341 		rc = 1;
342 
343 unlock:
344 	rcu_read_unlock();
345 
346 	return rc;
347 }
348 
349 /**
350  * yama_ptrace_access_check - validate PTRACE_ATTACH calls
351  * @child: task that current task is attempting to ptrace
352  * @mode: ptrace attach mode
353  *
354  * Returns 0 if following the ptrace is allowed, -ve on error.
355  */
356 static int yama_ptrace_access_check(struct task_struct *child,
357 				    unsigned int mode)
358 {
359 	int rc = 0;
360 
361 	/* require ptrace target be a child of ptracer on attach */
362 	if (mode & PTRACE_MODE_ATTACH) {
363 		switch (ptrace_scope) {
364 		case YAMA_SCOPE_DISABLED:
365 			/* No additional restrictions. */
366 			break;
367 		case YAMA_SCOPE_RELATIONAL:
368 			rcu_read_lock();
369 			if (!pid_alive(child))
370 				rc = -EPERM;
371 			if (!rc && !task_is_descendant(current, child) &&
372 			    !ptracer_exception_found(current, child) &&
373 			    !ns_capable(__task_cred(child)->user_ns, CAP_SYS_PTRACE))
374 				rc = -EPERM;
375 			rcu_read_unlock();
376 			break;
377 		case YAMA_SCOPE_CAPABILITY:
378 			rcu_read_lock();
379 			if (!ns_capable(__task_cred(child)->user_ns, CAP_SYS_PTRACE))
380 				rc = -EPERM;
381 			rcu_read_unlock();
382 			break;
383 		case YAMA_SCOPE_NO_ATTACH:
384 		default:
385 			rc = -EPERM;
386 			break;
387 		}
388 	}
389 
390 	if (rc && (mode & PTRACE_MODE_NOAUDIT) == 0)
391 		report_access("attach", child, current);
392 
393 	return rc;
394 }
395 
396 /**
397  * yama_ptrace_traceme - validate PTRACE_TRACEME calls
398  * @parent: task that will become the ptracer of the current task
399  *
400  * Returns 0 if following the ptrace is allowed, -ve on error.
401  */
402 static int yama_ptrace_traceme(struct task_struct *parent)
403 {
404 	int rc = 0;
405 
406 	/* Only disallow PTRACE_TRACEME on more aggressive settings. */
407 	switch (ptrace_scope) {
408 	case YAMA_SCOPE_CAPABILITY:
409 		if (!has_ns_capability(parent, current_user_ns(), CAP_SYS_PTRACE))
410 			rc = -EPERM;
411 		break;
412 	case YAMA_SCOPE_NO_ATTACH:
413 		rc = -EPERM;
414 		break;
415 	}
416 
417 	if (rc) {
418 		task_lock(current);
419 		report_access("traceme", current, parent);
420 		task_unlock(current);
421 	}
422 
423 	return rc;
424 }
425 
426 static const struct lsm_id yama_lsmid = {
427 	.name = "yama",
428 	.id = LSM_ID_YAMA,
429 };
430 
431 static struct security_hook_list yama_hooks[] __ro_after_init = {
432 	LSM_HOOK_INIT(ptrace_access_check, yama_ptrace_access_check),
433 	LSM_HOOK_INIT(ptrace_traceme, yama_ptrace_traceme),
434 	LSM_HOOK_INIT(task_prctl, yama_task_prctl),
435 	LSM_HOOK_INIT(task_free, yama_task_free),
436 };
437 
438 #ifdef CONFIG_SYSCTL
439 static int yama_dointvec_minmax(const struct ctl_table *table, int write,
440 				void *buffer, size_t *lenp, loff_t *ppos)
441 {
442 	struct ctl_table table_copy;
443 
444 	if (write && !capable(CAP_SYS_PTRACE))
445 		return -EPERM;
446 
447 	/* Lock the max value if it ever gets set. */
448 	table_copy = *table;
449 	if (*(int *)table_copy.data == *(int *)table_copy.extra2)
450 		table_copy.extra1 = table_copy.extra2;
451 
452 	return proc_dointvec_minmax(&table_copy, write, buffer, lenp, ppos);
453 }
454 
455 static int max_scope = YAMA_SCOPE_NO_ATTACH;
456 
457 static struct ctl_table yama_sysctl_table[] = {
458 	{
459 		.procname       = "ptrace_scope",
460 		.data           = &ptrace_scope,
461 		.maxlen         = sizeof(int),
462 		.mode           = 0644,
463 		.proc_handler   = yama_dointvec_minmax,
464 		.extra1         = SYSCTL_ZERO,
465 		.extra2         = &max_scope,
466 	},
467 };
468 static void __init yama_init_sysctl(void)
469 {
470 	if (!register_sysctl("kernel/yama", yama_sysctl_table))
471 		panic("Yama: sysctl registration failed.\n");
472 }
473 #else
474 static inline void yama_init_sysctl(void) { }
475 #endif /* CONFIG_SYSCTL */
476 
477 static int __init yama_init(void)
478 {
479 	pr_info("Yama: becoming mindful.\n");
480 	security_add_hooks(yama_hooks, ARRAY_SIZE(yama_hooks), &yama_lsmid);
481 	yama_init_sysctl();
482 	return 0;
483 }
484 
485 DEFINE_LSM(yama) = {
486 	.name = "yama",
487 	.init = yama_init,
488 };
489