1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/fanotify.h>
3 #include <linux/fcntl.h>
4 #include <linux/file.h>
5 #include <linux/fs.h>
6 #include <linux/anon_inodes.h>
7 #include <linux/fsnotify_backend.h>
8 #include <linux/init.h>
9 #include <linux/mount.h>
10 #include <linux/namei.h>
11 #include <linux/poll.h>
12 #include <linux/security.h>
13 #include <linux/syscalls.h>
14 #include <linux/slab.h>
15 #include <linux/types.h>
16 #include <linux/uaccess.h>
17 #include <linux/compat.h>
18 #include <linux/sched/signal.h>
19 #include <linux/memcontrol.h>
20 #include <linux/statfs.h>
21 #include <linux/exportfs.h>
22 
23 #include <asm/ioctls.h>
24 
25 #include "../../mount.h"
26 #include "../fdinfo.h"
27 #include "fanotify.h"
28 
29 #define FANOTIFY_DEFAULT_MAX_EVENTS	16384
30 #define FANOTIFY_DEFAULT_MAX_MARKS	8192
31 #define FANOTIFY_DEFAULT_MAX_LISTENERS	128
32 
33 /*
34  * All flags that may be specified in parameter event_f_flags of fanotify_init.
35  *
36  * Internal and external open flags are stored together in field f_flags of
37  * struct file. Only external open flags shall be allowed in event_f_flags.
38  * Internal flags like FMODE_NONOTIFY, FMODE_EXEC, FMODE_NOCMTIME shall be
39  * excluded.
40  */
41 #define	FANOTIFY_INIT_ALL_EVENT_F_BITS				( \
42 		O_ACCMODE	| O_APPEND	| O_NONBLOCK	| \
43 		__O_SYNC	| O_DSYNC	| O_CLOEXEC     | \
44 		O_LARGEFILE	| O_NOATIME	)
45 
46 extern const struct fsnotify_ops fanotify_fsnotify_ops;
47 
48 struct kmem_cache *fanotify_mark_cache __read_mostly;
49 struct kmem_cache *fanotify_fid_event_cachep __read_mostly;
50 struct kmem_cache *fanotify_path_event_cachep __read_mostly;
51 struct kmem_cache *fanotify_perm_event_cachep __read_mostly;
52 
53 #define FANOTIFY_EVENT_ALIGN 4
54 #define FANOTIFY_INFO_HDR_LEN \
55 	(sizeof(struct fanotify_event_info_fid) + sizeof(struct file_handle))
56 
57 static int fanotify_fid_info_len(int fh_len, int name_len)
58 {
59 	int info_len = fh_len;
60 
61 	if (name_len)
62 		info_len += name_len + 1;
63 
64 	return roundup(FANOTIFY_INFO_HDR_LEN + info_len, FANOTIFY_EVENT_ALIGN);
65 }
66 
67 static int fanotify_event_info_len(struct fanotify_event *event)
68 {
69 	int info_len = 0;
70 	int fh_len = fanotify_event_object_fh_len(event);
71 
72 	if (fh_len)
73 		info_len += fanotify_fid_info_len(fh_len, 0);
74 
75 	if (fanotify_event_name_len(event)) {
76 		struct fanotify_name_event *fne = FANOTIFY_NE(event);
77 
78 		info_len += fanotify_fid_info_len(fne->dir_fh.len,
79 						  fne->name_len);
80 	}
81 
82 	return info_len;
83 }
84 
85 /*
86  * Get an fanotify notification event if one exists and is small
87  * enough to fit in "count". Return an error pointer if the count
88  * is not large enough. When permission event is dequeued, its state is
89  * updated accordingly.
90  */
91 static struct fanotify_event *get_one_event(struct fsnotify_group *group,
92 					    size_t count)
93 {
94 	size_t event_size = FAN_EVENT_METADATA_LEN;
95 	struct fanotify_event *event = NULL;
96 
97 	pr_debug("%s: group=%p count=%zd\n", __func__, group, count);
98 
99 	spin_lock(&group->notification_lock);
100 	if (fsnotify_notify_queue_is_empty(group))
101 		goto out;
102 
103 	if (FAN_GROUP_FLAG(group, FAN_REPORT_FID)) {
104 		event_size += fanotify_event_info_len(
105 			FANOTIFY_E(fsnotify_peek_first_event(group)));
106 	}
107 
108 	if (event_size > count) {
109 		event = ERR_PTR(-EINVAL);
110 		goto out;
111 	}
112 	event = FANOTIFY_E(fsnotify_remove_first_event(group));
113 	if (fanotify_is_perm_event(event->mask))
114 		FANOTIFY_PERM(event)->state = FAN_EVENT_REPORTED;
115 out:
116 	spin_unlock(&group->notification_lock);
117 	return event;
118 }
119 
120 static int create_fd(struct fsnotify_group *group, struct path *path,
121 		     struct file **file)
122 {
123 	int client_fd;
124 	struct file *new_file;
125 
126 	client_fd = get_unused_fd_flags(group->fanotify_data.f_flags);
127 	if (client_fd < 0)
128 		return client_fd;
129 
130 	/*
131 	 * we need a new file handle for the userspace program so it can read even if it was
132 	 * originally opened O_WRONLY.
133 	 */
134 	new_file = dentry_open(path,
135 			       group->fanotify_data.f_flags | FMODE_NONOTIFY,
136 			       current_cred());
137 	if (IS_ERR(new_file)) {
138 		/*
139 		 * we still send an event even if we can't open the file.  this
140 		 * can happen when say tasks are gone and we try to open their
141 		 * /proc files or we try to open a WRONLY file like in sysfs
142 		 * we just send the errno to userspace since there isn't much
143 		 * else we can do.
144 		 */
145 		put_unused_fd(client_fd);
146 		client_fd = PTR_ERR(new_file);
147 	} else {
148 		*file = new_file;
149 	}
150 
151 	return client_fd;
152 }
153 
154 /*
155  * Finish processing of permission event by setting it to ANSWERED state and
156  * drop group->notification_lock.
157  */
158 static void finish_permission_event(struct fsnotify_group *group,
159 				    struct fanotify_perm_event *event,
160 				    unsigned int response)
161 				    __releases(&group->notification_lock)
162 {
163 	bool destroy = false;
164 
165 	assert_spin_locked(&group->notification_lock);
166 	event->response = response;
167 	if (event->state == FAN_EVENT_CANCELED)
168 		destroy = true;
169 	else
170 		event->state = FAN_EVENT_ANSWERED;
171 	spin_unlock(&group->notification_lock);
172 	if (destroy)
173 		fsnotify_destroy_event(group, &event->fae.fse);
174 }
175 
176 static int process_access_response(struct fsnotify_group *group,
177 				   struct fanotify_response *response_struct)
178 {
179 	struct fanotify_perm_event *event;
180 	int fd = response_struct->fd;
181 	int response = response_struct->response;
182 
183 	pr_debug("%s: group=%p fd=%d response=%d\n", __func__, group,
184 		 fd, response);
185 	/*
186 	 * make sure the response is valid, if invalid we do nothing and either
187 	 * userspace can send a valid response or we will clean it up after the
188 	 * timeout
189 	 */
190 	switch (response & ~FAN_AUDIT) {
191 	case FAN_ALLOW:
192 	case FAN_DENY:
193 		break;
194 	default:
195 		return -EINVAL;
196 	}
197 
198 	if (fd < 0)
199 		return -EINVAL;
200 
201 	if ((response & FAN_AUDIT) && !FAN_GROUP_FLAG(group, FAN_ENABLE_AUDIT))
202 		return -EINVAL;
203 
204 	spin_lock(&group->notification_lock);
205 	list_for_each_entry(event, &group->fanotify_data.access_list,
206 			    fae.fse.list) {
207 		if (event->fd != fd)
208 			continue;
209 
210 		list_del_init(&event->fae.fse.list);
211 		finish_permission_event(group, event, response);
212 		wake_up(&group->fanotify_data.access_waitq);
213 		return 0;
214 	}
215 	spin_unlock(&group->notification_lock);
216 
217 	return -ENOENT;
218 }
219 
220 static int copy_info_to_user(__kernel_fsid_t *fsid, struct fanotify_fh *fh,
221 			     const char *name, size_t name_len,
222 			     char __user *buf, size_t count)
223 {
224 	struct fanotify_event_info_fid info = { };
225 	struct file_handle handle = { };
226 	unsigned char bounce[FANOTIFY_INLINE_FH_LEN], *fh_buf;
227 	size_t fh_len = fh ? fh->len : 0;
228 	size_t info_len = fanotify_fid_info_len(fh_len, name_len);
229 	size_t len = info_len;
230 
231 	pr_debug("%s: fh_len=%zu name_len=%zu, info_len=%zu, count=%zu\n",
232 		 __func__, fh_len, name_len, info_len, count);
233 
234 	if (!fh_len || (name && !name_len))
235 		return 0;
236 
237 	if (WARN_ON_ONCE(len < sizeof(info) || len > count))
238 		return -EFAULT;
239 
240 	/*
241 	 * Copy event info fid header followed by variable sized file handle
242 	 * and optionally followed by variable sized filename.
243 	 */
244 	info.hdr.info_type = name_len ? FAN_EVENT_INFO_TYPE_DFID_NAME :
245 					FAN_EVENT_INFO_TYPE_FID;
246 	info.hdr.len = len;
247 	info.fsid = *fsid;
248 	if (copy_to_user(buf, &info, sizeof(info)))
249 		return -EFAULT;
250 
251 	buf += sizeof(info);
252 	len -= sizeof(info);
253 	if (WARN_ON_ONCE(len < sizeof(handle)))
254 		return -EFAULT;
255 
256 	handle.handle_type = fh->type;
257 	handle.handle_bytes = fh_len;
258 	if (copy_to_user(buf, &handle, sizeof(handle)))
259 		return -EFAULT;
260 
261 	buf += sizeof(handle);
262 	len -= sizeof(handle);
263 	if (WARN_ON_ONCE(len < fh_len))
264 		return -EFAULT;
265 
266 	/*
267 	 * For an inline fh and inline file name, copy through stack to exclude
268 	 * the copy from usercopy hardening protections.
269 	 */
270 	fh_buf = fanotify_fh_buf(fh);
271 	if (fh_len <= FANOTIFY_INLINE_FH_LEN) {
272 		memcpy(bounce, fh_buf, fh_len);
273 		fh_buf = bounce;
274 	}
275 	if (copy_to_user(buf, fh_buf, fh_len))
276 		return -EFAULT;
277 
278 	buf += fh_len;
279 	len -= fh_len;
280 
281 	if (name_len) {
282 		/* Copy the filename with terminating null */
283 		name_len++;
284 		if (WARN_ON_ONCE(len < name_len))
285 			return -EFAULT;
286 
287 		if (copy_to_user(buf, name, name_len))
288 			return -EFAULT;
289 
290 		buf += name_len;
291 		len -= name_len;
292 	}
293 
294 	/* Pad with 0's */
295 	WARN_ON_ONCE(len < 0 || len >= FANOTIFY_EVENT_ALIGN);
296 	if (len > 0 && clear_user(buf, len))
297 		return -EFAULT;
298 
299 	return info_len;
300 }
301 
302 static ssize_t copy_event_to_user(struct fsnotify_group *group,
303 				  struct fanotify_event *event,
304 				  char __user *buf, size_t count)
305 {
306 	struct fanotify_event_metadata metadata;
307 	struct path *path = fanotify_event_path(event);
308 	struct file *f = NULL;
309 	int ret, fd = FAN_NOFD;
310 
311 	pr_debug("%s: group=%p event=%p\n", __func__, group, event);
312 
313 	metadata.event_len = FAN_EVENT_METADATA_LEN +
314 					fanotify_event_info_len(event);
315 	metadata.metadata_len = FAN_EVENT_METADATA_LEN;
316 	metadata.vers = FANOTIFY_METADATA_VERSION;
317 	metadata.reserved = 0;
318 	metadata.mask = event->mask & FANOTIFY_OUTGOING_EVENTS;
319 	metadata.pid = pid_vnr(event->pid);
320 
321 	if (path && path->mnt && path->dentry) {
322 		fd = create_fd(group, path, &f);
323 		if (fd < 0)
324 			return fd;
325 	}
326 	metadata.fd = fd;
327 
328 	ret = -EFAULT;
329 	/*
330 	 * Sanity check copy size in case get_one_event() and
331 	 * fill_event_metadata() event_len sizes ever get out of sync.
332 	 */
333 	if (WARN_ON_ONCE(metadata.event_len > count))
334 		goto out_close_fd;
335 
336 	if (copy_to_user(buf, &metadata, FAN_EVENT_METADATA_LEN))
337 		goto out_close_fd;
338 
339 	buf += FAN_EVENT_METADATA_LEN;
340 	count -= FAN_EVENT_METADATA_LEN;
341 
342 	if (fanotify_is_perm_event(event->mask))
343 		FANOTIFY_PERM(event)->fd = fd;
344 
345 	if (f)
346 		fd_install(fd, f);
347 
348 	/* Event info records order is: dir fid + name, child fid */
349 	if (fanotify_event_name_len(event)) {
350 		struct fanotify_name_event *fne = FANOTIFY_NE(event);
351 
352 		ret = copy_info_to_user(fanotify_event_fsid(event),
353 					fanotify_event_dir_fh(event),
354 					fne->name, fne->name_len,
355 					buf, count);
356 		if (ret < 0)
357 			return ret;
358 
359 		buf += ret;
360 		count -= ret;
361 	}
362 
363 	if (fanotify_event_object_fh_len(event)) {
364 		ret = copy_info_to_user(fanotify_event_fsid(event),
365 					fanotify_event_object_fh(event),
366 					NULL, 0, buf, count);
367 		if (ret < 0)
368 			return ret;
369 
370 		buf += ret;
371 		count -= ret;
372 	}
373 
374 	return metadata.event_len;
375 
376 out_close_fd:
377 	if (fd != FAN_NOFD) {
378 		put_unused_fd(fd);
379 		fput(f);
380 	}
381 	return ret;
382 }
383 
384 /* intofiy userspace file descriptor functions */
385 static __poll_t fanotify_poll(struct file *file, poll_table *wait)
386 {
387 	struct fsnotify_group *group = file->private_data;
388 	__poll_t ret = 0;
389 
390 	poll_wait(file, &group->notification_waitq, wait);
391 	spin_lock(&group->notification_lock);
392 	if (!fsnotify_notify_queue_is_empty(group))
393 		ret = EPOLLIN | EPOLLRDNORM;
394 	spin_unlock(&group->notification_lock);
395 
396 	return ret;
397 }
398 
399 static ssize_t fanotify_read(struct file *file, char __user *buf,
400 			     size_t count, loff_t *pos)
401 {
402 	struct fsnotify_group *group;
403 	struct fanotify_event *event;
404 	char __user *start;
405 	int ret;
406 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
407 
408 	start = buf;
409 	group = file->private_data;
410 
411 	pr_debug("%s: group=%p\n", __func__, group);
412 
413 	add_wait_queue(&group->notification_waitq, &wait);
414 	while (1) {
415 		event = get_one_event(group, count);
416 		if (IS_ERR(event)) {
417 			ret = PTR_ERR(event);
418 			break;
419 		}
420 
421 		if (!event) {
422 			ret = -EAGAIN;
423 			if (file->f_flags & O_NONBLOCK)
424 				break;
425 
426 			ret = -ERESTARTSYS;
427 			if (signal_pending(current))
428 				break;
429 
430 			if (start != buf)
431 				break;
432 
433 			wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
434 			continue;
435 		}
436 
437 		ret = copy_event_to_user(group, event, buf, count);
438 		if (unlikely(ret == -EOPENSTALE)) {
439 			/*
440 			 * We cannot report events with stale fd so drop it.
441 			 * Setting ret to 0 will continue the event loop and
442 			 * do the right thing if there are no more events to
443 			 * read (i.e. return bytes read, -EAGAIN or wait).
444 			 */
445 			ret = 0;
446 		}
447 
448 		/*
449 		 * Permission events get queued to wait for response.  Other
450 		 * events can be destroyed now.
451 		 */
452 		if (!fanotify_is_perm_event(event->mask)) {
453 			fsnotify_destroy_event(group, &event->fse);
454 		} else {
455 			if (ret <= 0) {
456 				spin_lock(&group->notification_lock);
457 				finish_permission_event(group,
458 					FANOTIFY_PERM(event), FAN_DENY);
459 				wake_up(&group->fanotify_data.access_waitq);
460 			} else {
461 				spin_lock(&group->notification_lock);
462 				list_add_tail(&event->fse.list,
463 					&group->fanotify_data.access_list);
464 				spin_unlock(&group->notification_lock);
465 			}
466 		}
467 		if (ret < 0)
468 			break;
469 		buf += ret;
470 		count -= ret;
471 	}
472 	remove_wait_queue(&group->notification_waitq, &wait);
473 
474 	if (start != buf && ret != -EFAULT)
475 		ret = buf - start;
476 	return ret;
477 }
478 
479 static ssize_t fanotify_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
480 {
481 	struct fanotify_response response = { .fd = -1, .response = -1 };
482 	struct fsnotify_group *group;
483 	int ret;
484 
485 	if (!IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS))
486 		return -EINVAL;
487 
488 	group = file->private_data;
489 
490 	if (count > sizeof(response))
491 		count = sizeof(response);
492 
493 	pr_debug("%s: group=%p count=%zu\n", __func__, group, count);
494 
495 	if (copy_from_user(&response, buf, count))
496 		return -EFAULT;
497 
498 	ret = process_access_response(group, &response);
499 	if (ret < 0)
500 		count = ret;
501 
502 	return count;
503 }
504 
505 static int fanotify_release(struct inode *ignored, struct file *file)
506 {
507 	struct fsnotify_group *group = file->private_data;
508 
509 	/*
510 	 * Stop new events from arriving in the notification queue. since
511 	 * userspace cannot use fanotify fd anymore, no event can enter or
512 	 * leave access_list by now either.
513 	 */
514 	fsnotify_group_stop_queueing(group);
515 
516 	/*
517 	 * Process all permission events on access_list and notification queue
518 	 * and simulate reply from userspace.
519 	 */
520 	spin_lock(&group->notification_lock);
521 	while (!list_empty(&group->fanotify_data.access_list)) {
522 		struct fanotify_perm_event *event;
523 
524 		event = list_first_entry(&group->fanotify_data.access_list,
525 				struct fanotify_perm_event, fae.fse.list);
526 		list_del_init(&event->fae.fse.list);
527 		finish_permission_event(group, event, FAN_ALLOW);
528 		spin_lock(&group->notification_lock);
529 	}
530 
531 	/*
532 	 * Destroy all non-permission events. For permission events just
533 	 * dequeue them and set the response. They will be freed once the
534 	 * response is consumed and fanotify_get_response() returns.
535 	 */
536 	while (!fsnotify_notify_queue_is_empty(group)) {
537 		struct fanotify_event *event;
538 
539 		event = FANOTIFY_E(fsnotify_remove_first_event(group));
540 		if (!(event->mask & FANOTIFY_PERM_EVENTS)) {
541 			spin_unlock(&group->notification_lock);
542 			fsnotify_destroy_event(group, &event->fse);
543 		} else {
544 			finish_permission_event(group, FANOTIFY_PERM(event),
545 						FAN_ALLOW);
546 		}
547 		spin_lock(&group->notification_lock);
548 	}
549 	spin_unlock(&group->notification_lock);
550 
551 	/* Response for all permission events it set, wakeup waiters */
552 	wake_up(&group->fanotify_data.access_waitq);
553 
554 	/* matches the fanotify_init->fsnotify_alloc_group */
555 	fsnotify_destroy_group(group);
556 
557 	return 0;
558 }
559 
560 static long fanotify_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
561 {
562 	struct fsnotify_group *group;
563 	struct fsnotify_event *fsn_event;
564 	void __user *p;
565 	int ret = -ENOTTY;
566 	size_t send_len = 0;
567 
568 	group = file->private_data;
569 
570 	p = (void __user *) arg;
571 
572 	switch (cmd) {
573 	case FIONREAD:
574 		spin_lock(&group->notification_lock);
575 		list_for_each_entry(fsn_event, &group->notification_list, list)
576 			send_len += FAN_EVENT_METADATA_LEN;
577 		spin_unlock(&group->notification_lock);
578 		ret = put_user(send_len, (int __user *) p);
579 		break;
580 	}
581 
582 	return ret;
583 }
584 
585 static const struct file_operations fanotify_fops = {
586 	.show_fdinfo	= fanotify_show_fdinfo,
587 	.poll		= fanotify_poll,
588 	.read		= fanotify_read,
589 	.write		= fanotify_write,
590 	.fasync		= NULL,
591 	.release	= fanotify_release,
592 	.unlocked_ioctl	= fanotify_ioctl,
593 	.compat_ioctl	= compat_ptr_ioctl,
594 	.llseek		= noop_llseek,
595 };
596 
597 static int fanotify_find_path(int dfd, const char __user *filename,
598 			      struct path *path, unsigned int flags, __u64 mask,
599 			      unsigned int obj_type)
600 {
601 	int ret;
602 
603 	pr_debug("%s: dfd=%d filename=%p flags=%x\n", __func__,
604 		 dfd, filename, flags);
605 
606 	if (filename == NULL) {
607 		struct fd f = fdget(dfd);
608 
609 		ret = -EBADF;
610 		if (!f.file)
611 			goto out;
612 
613 		ret = -ENOTDIR;
614 		if ((flags & FAN_MARK_ONLYDIR) &&
615 		    !(S_ISDIR(file_inode(f.file)->i_mode))) {
616 			fdput(f);
617 			goto out;
618 		}
619 
620 		*path = f.file->f_path;
621 		path_get(path);
622 		fdput(f);
623 	} else {
624 		unsigned int lookup_flags = 0;
625 
626 		if (!(flags & FAN_MARK_DONT_FOLLOW))
627 			lookup_flags |= LOOKUP_FOLLOW;
628 		if (flags & FAN_MARK_ONLYDIR)
629 			lookup_flags |= LOOKUP_DIRECTORY;
630 
631 		ret = user_path_at(dfd, filename, lookup_flags, path);
632 		if (ret)
633 			goto out;
634 	}
635 
636 	/* you can only watch an inode if you have read permissions on it */
637 	ret = inode_permission(path->dentry->d_inode, MAY_READ);
638 	if (ret) {
639 		path_put(path);
640 		goto out;
641 	}
642 
643 	ret = security_path_notify(path, mask, obj_type);
644 	if (ret)
645 		path_put(path);
646 
647 out:
648 	return ret;
649 }
650 
651 static __u32 fanotify_mark_remove_from_mask(struct fsnotify_mark *fsn_mark,
652 					    __u32 mask,
653 					    unsigned int flags,
654 					    int *destroy)
655 {
656 	__u32 oldmask = 0;
657 
658 	spin_lock(&fsn_mark->lock);
659 	if (!(flags & FAN_MARK_IGNORED_MASK)) {
660 		oldmask = fsn_mark->mask;
661 		fsn_mark->mask &= ~mask;
662 	} else {
663 		fsn_mark->ignored_mask &= ~mask;
664 	}
665 	*destroy = !(fsn_mark->mask | fsn_mark->ignored_mask);
666 	spin_unlock(&fsn_mark->lock);
667 
668 	return mask & oldmask;
669 }
670 
671 static int fanotify_remove_mark(struct fsnotify_group *group,
672 				fsnotify_connp_t *connp, __u32 mask,
673 				unsigned int flags)
674 {
675 	struct fsnotify_mark *fsn_mark = NULL;
676 	__u32 removed;
677 	int destroy_mark;
678 
679 	mutex_lock(&group->mark_mutex);
680 	fsn_mark = fsnotify_find_mark(connp, group);
681 	if (!fsn_mark) {
682 		mutex_unlock(&group->mark_mutex);
683 		return -ENOENT;
684 	}
685 
686 	removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags,
687 						 &destroy_mark);
688 	if (removed & fsnotify_conn_mask(fsn_mark->connector))
689 		fsnotify_recalc_mask(fsn_mark->connector);
690 	if (destroy_mark)
691 		fsnotify_detach_mark(fsn_mark);
692 	mutex_unlock(&group->mark_mutex);
693 	if (destroy_mark)
694 		fsnotify_free_mark(fsn_mark);
695 
696 	/* matches the fsnotify_find_mark() */
697 	fsnotify_put_mark(fsn_mark);
698 	return 0;
699 }
700 
701 static int fanotify_remove_vfsmount_mark(struct fsnotify_group *group,
702 					 struct vfsmount *mnt, __u32 mask,
703 					 unsigned int flags)
704 {
705 	return fanotify_remove_mark(group, &real_mount(mnt)->mnt_fsnotify_marks,
706 				    mask, flags);
707 }
708 
709 static int fanotify_remove_sb_mark(struct fsnotify_group *group,
710 				      struct super_block *sb, __u32 mask,
711 				      unsigned int flags)
712 {
713 	return fanotify_remove_mark(group, &sb->s_fsnotify_marks, mask, flags);
714 }
715 
716 static int fanotify_remove_inode_mark(struct fsnotify_group *group,
717 				      struct inode *inode, __u32 mask,
718 				      unsigned int flags)
719 {
720 	return fanotify_remove_mark(group, &inode->i_fsnotify_marks, mask,
721 				    flags);
722 }
723 
724 static __u32 fanotify_mark_add_to_mask(struct fsnotify_mark *fsn_mark,
725 				       __u32 mask,
726 				       unsigned int flags)
727 {
728 	__u32 oldmask = -1;
729 
730 	spin_lock(&fsn_mark->lock);
731 	if (!(flags & FAN_MARK_IGNORED_MASK)) {
732 		oldmask = fsn_mark->mask;
733 		fsn_mark->mask |= mask;
734 	} else {
735 		fsn_mark->ignored_mask |= mask;
736 		if (flags & FAN_MARK_IGNORED_SURV_MODIFY)
737 			fsn_mark->flags |= FSNOTIFY_MARK_FLAG_IGNORED_SURV_MODIFY;
738 	}
739 	spin_unlock(&fsn_mark->lock);
740 
741 	return mask & ~oldmask;
742 }
743 
744 static struct fsnotify_mark *fanotify_add_new_mark(struct fsnotify_group *group,
745 						   fsnotify_connp_t *connp,
746 						   unsigned int type,
747 						   __kernel_fsid_t *fsid)
748 {
749 	struct fsnotify_mark *mark;
750 	int ret;
751 
752 	if (atomic_read(&group->num_marks) > group->fanotify_data.max_marks)
753 		return ERR_PTR(-ENOSPC);
754 
755 	mark = kmem_cache_alloc(fanotify_mark_cache, GFP_KERNEL);
756 	if (!mark)
757 		return ERR_PTR(-ENOMEM);
758 
759 	fsnotify_init_mark(mark, group);
760 	ret = fsnotify_add_mark_locked(mark, connp, type, 0, fsid);
761 	if (ret) {
762 		fsnotify_put_mark(mark);
763 		return ERR_PTR(ret);
764 	}
765 
766 	return mark;
767 }
768 
769 
770 static int fanotify_add_mark(struct fsnotify_group *group,
771 			     fsnotify_connp_t *connp, unsigned int type,
772 			     __u32 mask, unsigned int flags,
773 			     __kernel_fsid_t *fsid)
774 {
775 	struct fsnotify_mark *fsn_mark;
776 	__u32 added;
777 
778 	mutex_lock(&group->mark_mutex);
779 	fsn_mark = fsnotify_find_mark(connp, group);
780 	if (!fsn_mark) {
781 		fsn_mark = fanotify_add_new_mark(group, connp, type, fsid);
782 		if (IS_ERR(fsn_mark)) {
783 			mutex_unlock(&group->mark_mutex);
784 			return PTR_ERR(fsn_mark);
785 		}
786 	}
787 	added = fanotify_mark_add_to_mask(fsn_mark, mask, flags);
788 	if (added & ~fsnotify_conn_mask(fsn_mark->connector))
789 		fsnotify_recalc_mask(fsn_mark->connector);
790 	mutex_unlock(&group->mark_mutex);
791 
792 	fsnotify_put_mark(fsn_mark);
793 	return 0;
794 }
795 
796 static int fanotify_add_vfsmount_mark(struct fsnotify_group *group,
797 				      struct vfsmount *mnt, __u32 mask,
798 				      unsigned int flags, __kernel_fsid_t *fsid)
799 {
800 	return fanotify_add_mark(group, &real_mount(mnt)->mnt_fsnotify_marks,
801 				 FSNOTIFY_OBJ_TYPE_VFSMOUNT, mask, flags, fsid);
802 }
803 
804 static int fanotify_add_sb_mark(struct fsnotify_group *group,
805 				struct super_block *sb, __u32 mask,
806 				unsigned int flags, __kernel_fsid_t *fsid)
807 {
808 	return fanotify_add_mark(group, &sb->s_fsnotify_marks,
809 				 FSNOTIFY_OBJ_TYPE_SB, mask, flags, fsid);
810 }
811 
812 static int fanotify_add_inode_mark(struct fsnotify_group *group,
813 				   struct inode *inode, __u32 mask,
814 				   unsigned int flags, __kernel_fsid_t *fsid)
815 {
816 	pr_debug("%s: group=%p inode=%p\n", __func__, group, inode);
817 
818 	/*
819 	 * If some other task has this inode open for write we should not add
820 	 * an ignored mark, unless that ignored mark is supposed to survive
821 	 * modification changes anyway.
822 	 */
823 	if ((flags & FAN_MARK_IGNORED_MASK) &&
824 	    !(flags & FAN_MARK_IGNORED_SURV_MODIFY) &&
825 	    inode_is_open_for_write(inode))
826 		return 0;
827 
828 	return fanotify_add_mark(group, &inode->i_fsnotify_marks,
829 				 FSNOTIFY_OBJ_TYPE_INODE, mask, flags, fsid);
830 }
831 
832 /* fanotify syscalls */
833 SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
834 {
835 	struct fsnotify_group *group;
836 	int f_flags, fd;
837 	struct user_struct *user;
838 	struct fanotify_event *oevent;
839 
840 	pr_debug("%s: flags=%x event_f_flags=%x\n",
841 		 __func__, flags, event_f_flags);
842 
843 	if (!capable(CAP_SYS_ADMIN))
844 		return -EPERM;
845 
846 #ifdef CONFIG_AUDITSYSCALL
847 	if (flags & ~(FANOTIFY_INIT_FLAGS | FAN_ENABLE_AUDIT))
848 #else
849 	if (flags & ~FANOTIFY_INIT_FLAGS)
850 #endif
851 		return -EINVAL;
852 
853 	if (event_f_flags & ~FANOTIFY_INIT_ALL_EVENT_F_BITS)
854 		return -EINVAL;
855 
856 	switch (event_f_flags & O_ACCMODE) {
857 	case O_RDONLY:
858 	case O_RDWR:
859 	case O_WRONLY:
860 		break;
861 	default:
862 		return -EINVAL;
863 	}
864 
865 	if ((flags & FAN_REPORT_FID) &&
866 	    (flags & FANOTIFY_CLASS_BITS) != FAN_CLASS_NOTIF)
867 		return -EINVAL;
868 
869 	user = get_current_user();
870 	if (atomic_read(&user->fanotify_listeners) > FANOTIFY_DEFAULT_MAX_LISTENERS) {
871 		free_uid(user);
872 		return -EMFILE;
873 	}
874 
875 	f_flags = O_RDWR | FMODE_NONOTIFY;
876 	if (flags & FAN_CLOEXEC)
877 		f_flags |= O_CLOEXEC;
878 	if (flags & FAN_NONBLOCK)
879 		f_flags |= O_NONBLOCK;
880 
881 	/* fsnotify_alloc_group takes a ref.  Dropped in fanotify_release */
882 	group = fsnotify_alloc_group(&fanotify_fsnotify_ops);
883 	if (IS_ERR(group)) {
884 		free_uid(user);
885 		return PTR_ERR(group);
886 	}
887 
888 	group->fanotify_data.user = user;
889 	group->fanotify_data.flags = flags;
890 	atomic_inc(&user->fanotify_listeners);
891 	group->memcg = get_mem_cgroup_from_mm(current->mm);
892 
893 	oevent = fanotify_alloc_event(group, NULL, FS_Q_OVERFLOW, NULL,
894 				      FSNOTIFY_EVENT_NONE, NULL, NULL);
895 	if (unlikely(!oevent)) {
896 		fd = -ENOMEM;
897 		goto out_destroy_group;
898 	}
899 	group->overflow_event = &oevent->fse;
900 
901 	if (force_o_largefile())
902 		event_f_flags |= O_LARGEFILE;
903 	group->fanotify_data.f_flags = event_f_flags;
904 	init_waitqueue_head(&group->fanotify_data.access_waitq);
905 	INIT_LIST_HEAD(&group->fanotify_data.access_list);
906 	switch (flags & FANOTIFY_CLASS_BITS) {
907 	case FAN_CLASS_NOTIF:
908 		group->priority = FS_PRIO_0;
909 		break;
910 	case FAN_CLASS_CONTENT:
911 		group->priority = FS_PRIO_1;
912 		break;
913 	case FAN_CLASS_PRE_CONTENT:
914 		group->priority = FS_PRIO_2;
915 		break;
916 	default:
917 		fd = -EINVAL;
918 		goto out_destroy_group;
919 	}
920 
921 	if (flags & FAN_UNLIMITED_QUEUE) {
922 		fd = -EPERM;
923 		if (!capable(CAP_SYS_ADMIN))
924 			goto out_destroy_group;
925 		group->max_events = UINT_MAX;
926 	} else {
927 		group->max_events = FANOTIFY_DEFAULT_MAX_EVENTS;
928 	}
929 
930 	if (flags & FAN_UNLIMITED_MARKS) {
931 		fd = -EPERM;
932 		if (!capable(CAP_SYS_ADMIN))
933 			goto out_destroy_group;
934 		group->fanotify_data.max_marks = UINT_MAX;
935 	} else {
936 		group->fanotify_data.max_marks = FANOTIFY_DEFAULT_MAX_MARKS;
937 	}
938 
939 	if (flags & FAN_ENABLE_AUDIT) {
940 		fd = -EPERM;
941 		if (!capable(CAP_AUDIT_WRITE))
942 			goto out_destroy_group;
943 	}
944 
945 	fd = anon_inode_getfd("[fanotify]", &fanotify_fops, group, f_flags);
946 	if (fd < 0)
947 		goto out_destroy_group;
948 
949 	return fd;
950 
951 out_destroy_group:
952 	fsnotify_destroy_group(group);
953 	return fd;
954 }
955 
956 /* Check if filesystem can encode a unique fid */
957 static int fanotify_test_fid(struct path *path, __kernel_fsid_t *fsid)
958 {
959 	__kernel_fsid_t root_fsid;
960 	int err;
961 
962 	/*
963 	 * Make sure path is not in filesystem with zero fsid (e.g. tmpfs).
964 	 */
965 	err = vfs_get_fsid(path->dentry, fsid);
966 	if (err)
967 		return err;
968 
969 	if (!fsid->val[0] && !fsid->val[1])
970 		return -ENODEV;
971 
972 	/*
973 	 * Make sure path is not inside a filesystem subvolume (e.g. btrfs)
974 	 * which uses a different fsid than sb root.
975 	 */
976 	err = vfs_get_fsid(path->dentry->d_sb->s_root, &root_fsid);
977 	if (err)
978 		return err;
979 
980 	if (root_fsid.val[0] != fsid->val[0] ||
981 	    root_fsid.val[1] != fsid->val[1])
982 		return -EXDEV;
983 
984 	/*
985 	 * We need to make sure that the file system supports at least
986 	 * encoding a file handle so user can use name_to_handle_at() to
987 	 * compare fid returned with event to the file handle of watched
988 	 * objects. However, name_to_handle_at() requires that the
989 	 * filesystem also supports decoding file handles.
990 	 */
991 	if (!path->dentry->d_sb->s_export_op ||
992 	    !path->dentry->d_sb->s_export_op->fh_to_dentry)
993 		return -EOPNOTSUPP;
994 
995 	return 0;
996 }
997 
998 static int fanotify_events_supported(struct path *path, __u64 mask)
999 {
1000 	/*
1001 	 * Some filesystems such as 'proc' acquire unusual locks when opening
1002 	 * files. For them fanotify permission events have high chances of
1003 	 * deadlocking the system - open done when reporting fanotify event
1004 	 * blocks on this "unusual" lock while another process holding the lock
1005 	 * waits for fanotify permission event to be answered. Just disallow
1006 	 * permission events for such filesystems.
1007 	 */
1008 	if (mask & FANOTIFY_PERM_EVENTS &&
1009 	    path->mnt->mnt_sb->s_type->fs_flags & FS_DISALLOW_NOTIFY_PERM)
1010 		return -EINVAL;
1011 	return 0;
1012 }
1013 
1014 static int do_fanotify_mark(int fanotify_fd, unsigned int flags, __u64 mask,
1015 			    int dfd, const char  __user *pathname)
1016 {
1017 	struct inode *inode = NULL;
1018 	struct vfsmount *mnt = NULL;
1019 	struct fsnotify_group *group;
1020 	struct fd f;
1021 	struct path path;
1022 	__kernel_fsid_t __fsid, *fsid = NULL;
1023 	u32 valid_mask = FANOTIFY_EVENTS | FANOTIFY_EVENT_FLAGS;
1024 	unsigned int mark_type = flags & FANOTIFY_MARK_TYPE_BITS;
1025 	unsigned int obj_type;
1026 	int ret;
1027 
1028 	pr_debug("%s: fanotify_fd=%d flags=%x dfd=%d pathname=%p mask=%llx\n",
1029 		 __func__, fanotify_fd, flags, dfd, pathname, mask);
1030 
1031 	/* we only use the lower 32 bits as of right now. */
1032 	if (mask & ((__u64)0xffffffff << 32))
1033 		return -EINVAL;
1034 
1035 	if (flags & ~FANOTIFY_MARK_FLAGS)
1036 		return -EINVAL;
1037 
1038 	switch (mark_type) {
1039 	case FAN_MARK_INODE:
1040 		obj_type = FSNOTIFY_OBJ_TYPE_INODE;
1041 		break;
1042 	case FAN_MARK_MOUNT:
1043 		obj_type = FSNOTIFY_OBJ_TYPE_VFSMOUNT;
1044 		break;
1045 	case FAN_MARK_FILESYSTEM:
1046 		obj_type = FSNOTIFY_OBJ_TYPE_SB;
1047 		break;
1048 	default:
1049 		return -EINVAL;
1050 	}
1051 
1052 	switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE | FAN_MARK_FLUSH)) {
1053 	case FAN_MARK_ADD:		/* fallthrough */
1054 	case FAN_MARK_REMOVE:
1055 		if (!mask)
1056 			return -EINVAL;
1057 		break;
1058 	case FAN_MARK_FLUSH:
1059 		if (flags & ~(FANOTIFY_MARK_TYPE_BITS | FAN_MARK_FLUSH))
1060 			return -EINVAL;
1061 		break;
1062 	default:
1063 		return -EINVAL;
1064 	}
1065 
1066 	if (IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS))
1067 		valid_mask |= FANOTIFY_PERM_EVENTS;
1068 
1069 	if (mask & ~valid_mask)
1070 		return -EINVAL;
1071 
1072 	f = fdget(fanotify_fd);
1073 	if (unlikely(!f.file))
1074 		return -EBADF;
1075 
1076 	/* verify that this is indeed an fanotify instance */
1077 	ret = -EINVAL;
1078 	if (unlikely(f.file->f_op != &fanotify_fops))
1079 		goto fput_and_out;
1080 	group = f.file->private_data;
1081 
1082 	/*
1083 	 * group->priority == FS_PRIO_0 == FAN_CLASS_NOTIF.  These are not
1084 	 * allowed to set permissions events.
1085 	 */
1086 	ret = -EINVAL;
1087 	if (mask & FANOTIFY_PERM_EVENTS &&
1088 	    group->priority == FS_PRIO_0)
1089 		goto fput_and_out;
1090 
1091 	/*
1092 	 * Events with data type inode do not carry enough information to report
1093 	 * event->fd, so we do not allow setting a mask for inode events unless
1094 	 * group supports reporting fid.
1095 	 * inode events are not supported on a mount mark, because they do not
1096 	 * carry enough information (i.e. path) to be filtered by mount point.
1097 	 */
1098 	if (mask & FANOTIFY_INODE_EVENTS &&
1099 	    (!FAN_GROUP_FLAG(group, FAN_REPORT_FID) ||
1100 	     mark_type == FAN_MARK_MOUNT))
1101 		goto fput_and_out;
1102 
1103 	if (flags & FAN_MARK_FLUSH) {
1104 		ret = 0;
1105 		if (mark_type == FAN_MARK_MOUNT)
1106 			fsnotify_clear_vfsmount_marks_by_group(group);
1107 		else if (mark_type == FAN_MARK_FILESYSTEM)
1108 			fsnotify_clear_sb_marks_by_group(group);
1109 		else
1110 			fsnotify_clear_inode_marks_by_group(group);
1111 		goto fput_and_out;
1112 	}
1113 
1114 	ret = fanotify_find_path(dfd, pathname, &path, flags,
1115 			(mask & ALL_FSNOTIFY_EVENTS), obj_type);
1116 	if (ret)
1117 		goto fput_and_out;
1118 
1119 	if (flags & FAN_MARK_ADD) {
1120 		ret = fanotify_events_supported(&path, mask);
1121 		if (ret)
1122 			goto path_put_and_out;
1123 	}
1124 
1125 	if (FAN_GROUP_FLAG(group, FAN_REPORT_FID)) {
1126 		ret = fanotify_test_fid(&path, &__fsid);
1127 		if (ret)
1128 			goto path_put_and_out;
1129 
1130 		fsid = &__fsid;
1131 	}
1132 
1133 	/* inode held in place by reference to path; group by fget on fd */
1134 	if (mark_type == FAN_MARK_INODE)
1135 		inode = path.dentry->d_inode;
1136 	else
1137 		mnt = path.mnt;
1138 
1139 	/* create/update an inode mark */
1140 	switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE)) {
1141 	case FAN_MARK_ADD:
1142 		if (mark_type == FAN_MARK_MOUNT)
1143 			ret = fanotify_add_vfsmount_mark(group, mnt, mask,
1144 							 flags, fsid);
1145 		else if (mark_type == FAN_MARK_FILESYSTEM)
1146 			ret = fanotify_add_sb_mark(group, mnt->mnt_sb, mask,
1147 						   flags, fsid);
1148 		else
1149 			ret = fanotify_add_inode_mark(group, inode, mask,
1150 						      flags, fsid);
1151 		break;
1152 	case FAN_MARK_REMOVE:
1153 		if (mark_type == FAN_MARK_MOUNT)
1154 			ret = fanotify_remove_vfsmount_mark(group, mnt, mask,
1155 							    flags);
1156 		else if (mark_type == FAN_MARK_FILESYSTEM)
1157 			ret = fanotify_remove_sb_mark(group, mnt->mnt_sb, mask,
1158 						      flags);
1159 		else
1160 			ret = fanotify_remove_inode_mark(group, inode, mask,
1161 							 flags);
1162 		break;
1163 	default:
1164 		ret = -EINVAL;
1165 	}
1166 
1167 path_put_and_out:
1168 	path_put(&path);
1169 fput_and_out:
1170 	fdput(f);
1171 	return ret;
1172 }
1173 
1174 SYSCALL_DEFINE5(fanotify_mark, int, fanotify_fd, unsigned int, flags,
1175 			      __u64, mask, int, dfd,
1176 			      const char  __user *, pathname)
1177 {
1178 	return do_fanotify_mark(fanotify_fd, flags, mask, dfd, pathname);
1179 }
1180 
1181 #ifdef CONFIG_COMPAT
1182 COMPAT_SYSCALL_DEFINE6(fanotify_mark,
1183 				int, fanotify_fd, unsigned int, flags,
1184 				__u32, mask0, __u32, mask1, int, dfd,
1185 				const char  __user *, pathname)
1186 {
1187 	return do_fanotify_mark(fanotify_fd, flags,
1188 #ifdef __BIG_ENDIAN
1189 				((__u64)mask0 << 32) | mask1,
1190 #else
1191 				((__u64)mask1 << 32) | mask0,
1192 #endif
1193 				 dfd, pathname);
1194 }
1195 #endif
1196 
1197 /*
1198  * fanotify_user_setup - Our initialization function.  Note that we cannot return
1199  * error because we have compiled-in VFS hooks.  So an (unlikely) failure here
1200  * must result in panic().
1201  */
1202 static int __init fanotify_user_setup(void)
1203 {
1204 	BUILD_BUG_ON(HWEIGHT32(FANOTIFY_INIT_FLAGS) != 8);
1205 	BUILD_BUG_ON(HWEIGHT32(FANOTIFY_MARK_FLAGS) != 9);
1206 
1207 	fanotify_mark_cache = KMEM_CACHE(fsnotify_mark,
1208 					 SLAB_PANIC|SLAB_ACCOUNT);
1209 	fanotify_fid_event_cachep = KMEM_CACHE(fanotify_fid_event,
1210 					       SLAB_PANIC);
1211 	fanotify_path_event_cachep = KMEM_CACHE(fanotify_path_event,
1212 						SLAB_PANIC);
1213 	if (IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS)) {
1214 		fanotify_perm_event_cachep =
1215 			KMEM_CACHE(fanotify_perm_event, SLAB_PANIC);
1216 	}
1217 
1218 	return 0;
1219 }
1220 device_initcall(fanotify_user_setup);
1221