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 
21 #include <asm/ioctls.h>
22 
23 #include "../../mount.h"
24 #include "../fdinfo.h"
25 #include "fanotify.h"
26 
27 #define FANOTIFY_DEFAULT_MAX_EVENTS	16384
28 #define FANOTIFY_DEFAULT_MAX_MARKS	8192
29 #define FANOTIFY_DEFAULT_MAX_LISTENERS	128
30 
31 /*
32  * All flags that may be specified in parameter event_f_flags of fanotify_init.
33  *
34  * Internal and external open flags are stored together in field f_flags of
35  * struct file. Only external open flags shall be allowed in event_f_flags.
36  * Internal flags like FMODE_NONOTIFY, FMODE_EXEC, FMODE_NOCMTIME shall be
37  * excluded.
38  */
39 #define	FANOTIFY_INIT_ALL_EVENT_F_BITS				( \
40 		O_ACCMODE	| O_APPEND	| O_NONBLOCK	| \
41 		__O_SYNC	| O_DSYNC	| O_CLOEXEC     | \
42 		O_LARGEFILE	| O_NOATIME	)
43 
44 extern const struct fsnotify_ops fanotify_fsnotify_ops;
45 
46 struct kmem_cache *fanotify_mark_cache __read_mostly;
47 struct kmem_cache *fanotify_event_cachep __read_mostly;
48 struct kmem_cache *fanotify_perm_event_cachep __read_mostly;
49 
50 /*
51  * Get an fsnotify notification event if one exists and is small
52  * enough to fit in "count". Return an error pointer if the count
53  * is not large enough.
54  *
55  * Called with the group->notification_lock held.
56  */
57 static struct fsnotify_event *get_one_event(struct fsnotify_group *group,
58 					    size_t count)
59 {
60 	assert_spin_locked(&group->notification_lock);
61 
62 	pr_debug("%s: group=%p count=%zd\n", __func__, group, count);
63 
64 	if (fsnotify_notify_queue_is_empty(group))
65 		return NULL;
66 
67 	if (FAN_EVENT_METADATA_LEN > count)
68 		return ERR_PTR(-EINVAL);
69 
70 	/* held the notification_lock the whole time, so this is the
71 	 * same event we peeked above */
72 	return fsnotify_remove_first_event(group);
73 }
74 
75 static int create_fd(struct fsnotify_group *group,
76 		     struct fanotify_event_info *event,
77 		     struct file **file)
78 {
79 	int client_fd;
80 	struct file *new_file;
81 
82 	pr_debug("%s: group=%p event=%p\n", __func__, group, event);
83 
84 	client_fd = get_unused_fd_flags(group->fanotify_data.f_flags);
85 	if (client_fd < 0)
86 		return client_fd;
87 
88 	/*
89 	 * we need a new file handle for the userspace program so it can read even if it was
90 	 * originally opened O_WRONLY.
91 	 */
92 	/* it's possible this event was an overflow event.  in that case dentry and mnt
93 	 * are NULL;  That's fine, just don't call dentry open */
94 	if (event->path.dentry && event->path.mnt)
95 		new_file = dentry_open(&event->path,
96 				       group->fanotify_data.f_flags | FMODE_NONOTIFY,
97 				       current_cred());
98 	else
99 		new_file = ERR_PTR(-EOVERFLOW);
100 	if (IS_ERR(new_file)) {
101 		/*
102 		 * we still send an event even if we can't open the file.  this
103 		 * can happen when say tasks are gone and we try to open their
104 		 * /proc files or we try to open a WRONLY file like in sysfs
105 		 * we just send the errno to userspace since there isn't much
106 		 * else we can do.
107 		 */
108 		put_unused_fd(client_fd);
109 		client_fd = PTR_ERR(new_file);
110 	} else {
111 		*file = new_file;
112 	}
113 
114 	return client_fd;
115 }
116 
117 static int fill_event_metadata(struct fsnotify_group *group,
118 			       struct fanotify_event_metadata *metadata,
119 			       struct fsnotify_event *fsn_event,
120 			       struct file **file)
121 {
122 	int ret = 0;
123 	struct fanotify_event_info *event;
124 
125 	pr_debug("%s: group=%p metadata=%p event=%p\n", __func__,
126 		 group, metadata, fsn_event);
127 
128 	*file = NULL;
129 	event = container_of(fsn_event, struct fanotify_event_info, fse);
130 	metadata->event_len = FAN_EVENT_METADATA_LEN;
131 	metadata->metadata_len = FAN_EVENT_METADATA_LEN;
132 	metadata->vers = FANOTIFY_METADATA_VERSION;
133 	metadata->reserved = 0;
134 	metadata->mask = fsn_event->mask & FAN_ALL_OUTGOING_EVENTS;
135 	metadata->pid = pid_vnr(event->tgid);
136 	if (unlikely(fsn_event->mask & FAN_Q_OVERFLOW))
137 		metadata->fd = FAN_NOFD;
138 	else {
139 		metadata->fd = create_fd(group, event, file);
140 		if (metadata->fd < 0)
141 			ret = metadata->fd;
142 	}
143 
144 	return ret;
145 }
146 
147 static struct fanotify_perm_event_info *dequeue_event(
148 				struct fsnotify_group *group, int fd)
149 {
150 	struct fanotify_perm_event_info *event, *return_e = NULL;
151 
152 	spin_lock(&group->notification_lock);
153 	list_for_each_entry(event, &group->fanotify_data.access_list,
154 			    fae.fse.list) {
155 		if (event->fd != fd)
156 			continue;
157 
158 		list_del_init(&event->fae.fse.list);
159 		return_e = event;
160 		break;
161 	}
162 	spin_unlock(&group->notification_lock);
163 
164 	pr_debug("%s: found return_re=%p\n", __func__, return_e);
165 
166 	return return_e;
167 }
168 
169 static int process_access_response(struct fsnotify_group *group,
170 				   struct fanotify_response *response_struct)
171 {
172 	struct fanotify_perm_event_info *event;
173 	int fd = response_struct->fd;
174 	int response = response_struct->response;
175 
176 	pr_debug("%s: group=%p fd=%d response=%d\n", __func__, group,
177 		 fd, response);
178 	/*
179 	 * make sure the response is valid, if invalid we do nothing and either
180 	 * userspace can send a valid response or we will clean it up after the
181 	 * timeout
182 	 */
183 	switch (response & ~FAN_AUDIT) {
184 	case FAN_ALLOW:
185 	case FAN_DENY:
186 		break;
187 	default:
188 		return -EINVAL;
189 	}
190 
191 	if (fd < 0)
192 		return -EINVAL;
193 
194 	if ((response & FAN_AUDIT) && !group->fanotify_data.audit)
195 		return -EINVAL;
196 
197 	event = dequeue_event(group, fd);
198 	if (!event)
199 		return -ENOENT;
200 
201 	event->response = response;
202 	wake_up(&group->fanotify_data.access_waitq);
203 
204 	return 0;
205 }
206 
207 static ssize_t copy_event_to_user(struct fsnotify_group *group,
208 				  struct fsnotify_event *event,
209 				  char __user *buf)
210 {
211 	struct fanotify_event_metadata fanotify_event_metadata;
212 	struct file *f;
213 	int fd, ret;
214 
215 	pr_debug("%s: group=%p event=%p\n", __func__, group, event);
216 
217 	ret = fill_event_metadata(group, &fanotify_event_metadata, event, &f);
218 	if (ret < 0)
219 		return ret;
220 
221 	fd = fanotify_event_metadata.fd;
222 	ret = -EFAULT;
223 	if (copy_to_user(buf, &fanotify_event_metadata,
224 			 fanotify_event_metadata.event_len))
225 		goto out_close_fd;
226 
227 	if (fanotify_is_perm_event(event->mask))
228 		FANOTIFY_PE(event)->fd = fd;
229 
230 	if (fd != FAN_NOFD)
231 		fd_install(fd, f);
232 	return fanotify_event_metadata.event_len;
233 
234 out_close_fd:
235 	if (fd != FAN_NOFD) {
236 		put_unused_fd(fd);
237 		fput(f);
238 	}
239 	return ret;
240 }
241 
242 /* intofiy userspace file descriptor functions */
243 static __poll_t fanotify_poll(struct file *file, poll_table *wait)
244 {
245 	struct fsnotify_group *group = file->private_data;
246 	__poll_t ret = 0;
247 
248 	poll_wait(file, &group->notification_waitq, wait);
249 	spin_lock(&group->notification_lock);
250 	if (!fsnotify_notify_queue_is_empty(group))
251 		ret = EPOLLIN | EPOLLRDNORM;
252 	spin_unlock(&group->notification_lock);
253 
254 	return ret;
255 }
256 
257 static ssize_t fanotify_read(struct file *file, char __user *buf,
258 			     size_t count, loff_t *pos)
259 {
260 	struct fsnotify_group *group;
261 	struct fsnotify_event *kevent;
262 	char __user *start;
263 	int ret;
264 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
265 
266 	start = buf;
267 	group = file->private_data;
268 
269 	pr_debug("%s: group=%p\n", __func__, group);
270 
271 	add_wait_queue(&group->notification_waitq, &wait);
272 	while (1) {
273 		spin_lock(&group->notification_lock);
274 		kevent = get_one_event(group, count);
275 		spin_unlock(&group->notification_lock);
276 
277 		if (IS_ERR(kevent)) {
278 			ret = PTR_ERR(kevent);
279 			break;
280 		}
281 
282 		if (!kevent) {
283 			ret = -EAGAIN;
284 			if (file->f_flags & O_NONBLOCK)
285 				break;
286 
287 			ret = -ERESTARTSYS;
288 			if (signal_pending(current))
289 				break;
290 
291 			if (start != buf)
292 				break;
293 
294 			wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
295 			continue;
296 		}
297 
298 		ret = copy_event_to_user(group, kevent, buf);
299 		if (unlikely(ret == -EOPENSTALE)) {
300 			/*
301 			 * We cannot report events with stale fd so drop it.
302 			 * Setting ret to 0 will continue the event loop and
303 			 * do the right thing if there are no more events to
304 			 * read (i.e. return bytes read, -EAGAIN or wait).
305 			 */
306 			ret = 0;
307 		}
308 
309 		/*
310 		 * Permission events get queued to wait for response.  Other
311 		 * events can be destroyed now.
312 		 */
313 		if (!fanotify_is_perm_event(kevent->mask)) {
314 			fsnotify_destroy_event(group, kevent);
315 		} else {
316 			if (ret <= 0) {
317 				FANOTIFY_PE(kevent)->response = FAN_DENY;
318 				wake_up(&group->fanotify_data.access_waitq);
319 			} else {
320 				spin_lock(&group->notification_lock);
321 				list_add_tail(&kevent->list,
322 					&group->fanotify_data.access_list);
323 				spin_unlock(&group->notification_lock);
324 			}
325 		}
326 		if (ret < 0)
327 			break;
328 		buf += ret;
329 		count -= ret;
330 	}
331 	remove_wait_queue(&group->notification_waitq, &wait);
332 
333 	if (start != buf && ret != -EFAULT)
334 		ret = buf - start;
335 	return ret;
336 }
337 
338 static ssize_t fanotify_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
339 {
340 	struct fanotify_response response = { .fd = -1, .response = -1 };
341 	struct fsnotify_group *group;
342 	int ret;
343 
344 	if (!IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS))
345 		return -EINVAL;
346 
347 	group = file->private_data;
348 
349 	if (count > sizeof(response))
350 		count = sizeof(response);
351 
352 	pr_debug("%s: group=%p count=%zu\n", __func__, group, count);
353 
354 	if (copy_from_user(&response, buf, count))
355 		return -EFAULT;
356 
357 	ret = process_access_response(group, &response);
358 	if (ret < 0)
359 		count = ret;
360 
361 	return count;
362 }
363 
364 static int fanotify_release(struct inode *ignored, struct file *file)
365 {
366 	struct fsnotify_group *group = file->private_data;
367 	struct fanotify_perm_event_info *event, *next;
368 	struct fsnotify_event *fsn_event;
369 
370 	/*
371 	 * Stop new events from arriving in the notification queue. since
372 	 * userspace cannot use fanotify fd anymore, no event can enter or
373 	 * leave access_list by now either.
374 	 */
375 	fsnotify_group_stop_queueing(group);
376 
377 	/*
378 	 * Process all permission events on access_list and notification queue
379 	 * and simulate reply from userspace.
380 	 */
381 	spin_lock(&group->notification_lock);
382 	list_for_each_entry_safe(event, next, &group->fanotify_data.access_list,
383 				 fae.fse.list) {
384 		pr_debug("%s: found group=%p event=%p\n", __func__, group,
385 			 event);
386 
387 		list_del_init(&event->fae.fse.list);
388 		event->response = FAN_ALLOW;
389 	}
390 
391 	/*
392 	 * Destroy all non-permission events. For permission events just
393 	 * dequeue them and set the response. They will be freed once the
394 	 * response is consumed and fanotify_get_response() returns.
395 	 */
396 	while (!fsnotify_notify_queue_is_empty(group)) {
397 		fsn_event = fsnotify_remove_first_event(group);
398 		if (!(fsn_event->mask & FAN_ALL_PERM_EVENTS)) {
399 			spin_unlock(&group->notification_lock);
400 			fsnotify_destroy_event(group, fsn_event);
401 			spin_lock(&group->notification_lock);
402 		} else {
403 			FANOTIFY_PE(fsn_event)->response = FAN_ALLOW;
404 		}
405 	}
406 	spin_unlock(&group->notification_lock);
407 
408 	/* Response for all permission events it set, wakeup waiters */
409 	wake_up(&group->fanotify_data.access_waitq);
410 
411 	/* matches the fanotify_init->fsnotify_alloc_group */
412 	fsnotify_destroy_group(group);
413 
414 	return 0;
415 }
416 
417 static long fanotify_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
418 {
419 	struct fsnotify_group *group;
420 	struct fsnotify_event *fsn_event;
421 	void __user *p;
422 	int ret = -ENOTTY;
423 	size_t send_len = 0;
424 
425 	group = file->private_data;
426 
427 	p = (void __user *) arg;
428 
429 	switch (cmd) {
430 	case FIONREAD:
431 		spin_lock(&group->notification_lock);
432 		list_for_each_entry(fsn_event, &group->notification_list, list)
433 			send_len += FAN_EVENT_METADATA_LEN;
434 		spin_unlock(&group->notification_lock);
435 		ret = put_user(send_len, (int __user *) p);
436 		break;
437 	}
438 
439 	return ret;
440 }
441 
442 static const struct file_operations fanotify_fops = {
443 	.show_fdinfo	= fanotify_show_fdinfo,
444 	.poll		= fanotify_poll,
445 	.read		= fanotify_read,
446 	.write		= fanotify_write,
447 	.fasync		= NULL,
448 	.release	= fanotify_release,
449 	.unlocked_ioctl	= fanotify_ioctl,
450 	.compat_ioctl	= fanotify_ioctl,
451 	.llseek		= noop_llseek,
452 };
453 
454 static int fanotify_find_path(int dfd, const char __user *filename,
455 			      struct path *path, unsigned int flags)
456 {
457 	int ret;
458 
459 	pr_debug("%s: dfd=%d filename=%p flags=%x\n", __func__,
460 		 dfd, filename, flags);
461 
462 	if (filename == NULL) {
463 		struct fd f = fdget(dfd);
464 
465 		ret = -EBADF;
466 		if (!f.file)
467 			goto out;
468 
469 		ret = -ENOTDIR;
470 		if ((flags & FAN_MARK_ONLYDIR) &&
471 		    !(S_ISDIR(file_inode(f.file)->i_mode))) {
472 			fdput(f);
473 			goto out;
474 		}
475 
476 		*path = f.file->f_path;
477 		path_get(path);
478 		fdput(f);
479 	} else {
480 		unsigned int lookup_flags = 0;
481 
482 		if (!(flags & FAN_MARK_DONT_FOLLOW))
483 			lookup_flags |= LOOKUP_FOLLOW;
484 		if (flags & FAN_MARK_ONLYDIR)
485 			lookup_flags |= LOOKUP_DIRECTORY;
486 
487 		ret = user_path_at(dfd, filename, lookup_flags, path);
488 		if (ret)
489 			goto out;
490 	}
491 
492 	/* you can only watch an inode if you have read permissions on it */
493 	ret = inode_permission(path->dentry->d_inode, MAY_READ);
494 	if (ret)
495 		path_put(path);
496 out:
497 	return ret;
498 }
499 
500 static __u32 fanotify_mark_remove_from_mask(struct fsnotify_mark *fsn_mark,
501 					    __u32 mask,
502 					    unsigned int flags,
503 					    int *destroy)
504 {
505 	__u32 oldmask = 0;
506 
507 	spin_lock(&fsn_mark->lock);
508 	if (!(flags & FAN_MARK_IGNORED_MASK)) {
509 		__u32 tmask = fsn_mark->mask & ~mask;
510 
511 		if (flags & FAN_MARK_ONDIR)
512 			tmask &= ~FAN_ONDIR;
513 
514 		oldmask = fsn_mark->mask;
515 		fsn_mark->mask = tmask;
516 	} else {
517 		__u32 tmask = fsn_mark->ignored_mask & ~mask;
518 		if (flags & FAN_MARK_ONDIR)
519 			tmask &= ~FAN_ONDIR;
520 		fsn_mark->ignored_mask = tmask;
521 	}
522 	*destroy = !(fsn_mark->mask | fsn_mark->ignored_mask);
523 	spin_unlock(&fsn_mark->lock);
524 
525 	return mask & oldmask;
526 }
527 
528 static int fanotify_remove_mark(struct fsnotify_group *group,
529 				fsnotify_connp_t *connp, __u32 mask,
530 				unsigned int flags)
531 {
532 	struct fsnotify_mark *fsn_mark = NULL;
533 	__u32 removed;
534 	int destroy_mark;
535 
536 	mutex_lock(&group->mark_mutex);
537 	fsn_mark = fsnotify_find_mark(connp, group);
538 	if (!fsn_mark) {
539 		mutex_unlock(&group->mark_mutex);
540 		return -ENOENT;
541 	}
542 
543 	removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags,
544 						 &destroy_mark);
545 	if (removed & fsnotify_conn_mask(fsn_mark->connector))
546 		fsnotify_recalc_mask(fsn_mark->connector);
547 	if (destroy_mark)
548 		fsnotify_detach_mark(fsn_mark);
549 	mutex_unlock(&group->mark_mutex);
550 	if (destroy_mark)
551 		fsnotify_free_mark(fsn_mark);
552 
553 	/* matches the fsnotify_find_mark() */
554 	fsnotify_put_mark(fsn_mark);
555 	return 0;
556 }
557 
558 static int fanotify_remove_vfsmount_mark(struct fsnotify_group *group,
559 					 struct vfsmount *mnt, __u32 mask,
560 					 unsigned int flags)
561 {
562 	return fanotify_remove_mark(group, &real_mount(mnt)->mnt_fsnotify_marks,
563 				    mask, flags);
564 }
565 
566 static int fanotify_remove_inode_mark(struct fsnotify_group *group,
567 				      struct inode *inode, __u32 mask,
568 				      unsigned int flags)
569 {
570 	return fanotify_remove_mark(group, &inode->i_fsnotify_marks, mask,
571 				    flags);
572 }
573 
574 static __u32 fanotify_mark_add_to_mask(struct fsnotify_mark *fsn_mark,
575 				       __u32 mask,
576 				       unsigned int flags)
577 {
578 	__u32 oldmask = -1;
579 
580 	spin_lock(&fsn_mark->lock);
581 	if (!(flags & FAN_MARK_IGNORED_MASK)) {
582 		__u32 tmask = fsn_mark->mask | mask;
583 
584 		if (flags & FAN_MARK_ONDIR)
585 			tmask |= FAN_ONDIR;
586 
587 		oldmask = fsn_mark->mask;
588 		fsn_mark->mask = tmask;
589 	} else {
590 		__u32 tmask = fsn_mark->ignored_mask | mask;
591 		if (flags & FAN_MARK_ONDIR)
592 			tmask |= FAN_ONDIR;
593 
594 		fsn_mark->ignored_mask = tmask;
595 		if (flags & FAN_MARK_IGNORED_SURV_MODIFY)
596 			fsn_mark->flags |= FSNOTIFY_MARK_FLAG_IGNORED_SURV_MODIFY;
597 	}
598 	spin_unlock(&fsn_mark->lock);
599 
600 	return mask & ~oldmask;
601 }
602 
603 static struct fsnotify_mark *fanotify_add_new_mark(struct fsnotify_group *group,
604 						   fsnotify_connp_t *connp,
605 						   unsigned int type)
606 {
607 	struct fsnotify_mark *mark;
608 	int ret;
609 
610 	if (atomic_read(&group->num_marks) > group->fanotify_data.max_marks)
611 		return ERR_PTR(-ENOSPC);
612 
613 	mark = kmem_cache_alloc(fanotify_mark_cache, GFP_KERNEL);
614 	if (!mark)
615 		return ERR_PTR(-ENOMEM);
616 
617 	fsnotify_init_mark(mark, group);
618 	ret = fsnotify_add_mark_locked(mark, connp, type, 0);
619 	if (ret) {
620 		fsnotify_put_mark(mark);
621 		return ERR_PTR(ret);
622 	}
623 
624 	return mark;
625 }
626 
627 
628 static int fanotify_add_mark(struct fsnotify_group *group,
629 			     fsnotify_connp_t *connp, unsigned int type,
630 			     __u32 mask, unsigned int flags)
631 {
632 	struct fsnotify_mark *fsn_mark;
633 	__u32 added;
634 
635 	mutex_lock(&group->mark_mutex);
636 	fsn_mark = fsnotify_find_mark(connp, group);
637 	if (!fsn_mark) {
638 		fsn_mark = fanotify_add_new_mark(group, connp, type);
639 		if (IS_ERR(fsn_mark)) {
640 			mutex_unlock(&group->mark_mutex);
641 			return PTR_ERR(fsn_mark);
642 		}
643 	}
644 	added = fanotify_mark_add_to_mask(fsn_mark, mask, flags);
645 	if (added & ~fsnotify_conn_mask(fsn_mark->connector))
646 		fsnotify_recalc_mask(fsn_mark->connector);
647 	mutex_unlock(&group->mark_mutex);
648 
649 	fsnotify_put_mark(fsn_mark);
650 	return 0;
651 }
652 
653 static int fanotify_add_vfsmount_mark(struct fsnotify_group *group,
654 				      struct vfsmount *mnt, __u32 mask,
655 				      unsigned int flags)
656 {
657 	return fanotify_add_mark(group, &real_mount(mnt)->mnt_fsnotify_marks,
658 				 FSNOTIFY_OBJ_TYPE_VFSMOUNT, mask, flags);
659 }
660 
661 static int fanotify_add_inode_mark(struct fsnotify_group *group,
662 				   struct inode *inode, __u32 mask,
663 				   unsigned int flags)
664 {
665 	pr_debug("%s: group=%p inode=%p\n", __func__, group, inode);
666 
667 	/*
668 	 * If some other task has this inode open for write we should not add
669 	 * an ignored mark, unless that ignored mark is supposed to survive
670 	 * modification changes anyway.
671 	 */
672 	if ((flags & FAN_MARK_IGNORED_MASK) &&
673 	    !(flags & FAN_MARK_IGNORED_SURV_MODIFY) &&
674 	    (atomic_read(&inode->i_writecount) > 0))
675 		return 0;
676 
677 	return fanotify_add_mark(group, &inode->i_fsnotify_marks,
678 				 FSNOTIFY_OBJ_TYPE_INODE, mask, flags);
679 }
680 
681 /* fanotify syscalls */
682 SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
683 {
684 	struct fsnotify_group *group;
685 	int f_flags, fd;
686 	struct user_struct *user;
687 	struct fanotify_event_info *oevent;
688 
689 	pr_debug("%s: flags=%d event_f_flags=%d\n",
690 		__func__, flags, event_f_flags);
691 
692 	if (!capable(CAP_SYS_ADMIN))
693 		return -EPERM;
694 
695 #ifdef CONFIG_AUDITSYSCALL
696 	if (flags & ~(FAN_ALL_INIT_FLAGS | FAN_ENABLE_AUDIT))
697 #else
698 	if (flags & ~FAN_ALL_INIT_FLAGS)
699 #endif
700 		return -EINVAL;
701 
702 	if (event_f_flags & ~FANOTIFY_INIT_ALL_EVENT_F_BITS)
703 		return -EINVAL;
704 
705 	switch (event_f_flags & O_ACCMODE) {
706 	case O_RDONLY:
707 	case O_RDWR:
708 	case O_WRONLY:
709 		break;
710 	default:
711 		return -EINVAL;
712 	}
713 
714 	user = get_current_user();
715 	if (atomic_read(&user->fanotify_listeners) > FANOTIFY_DEFAULT_MAX_LISTENERS) {
716 		free_uid(user);
717 		return -EMFILE;
718 	}
719 
720 	f_flags = O_RDWR | FMODE_NONOTIFY;
721 	if (flags & FAN_CLOEXEC)
722 		f_flags |= O_CLOEXEC;
723 	if (flags & FAN_NONBLOCK)
724 		f_flags |= O_NONBLOCK;
725 
726 	/* fsnotify_alloc_group takes a ref.  Dropped in fanotify_release */
727 	group = fsnotify_alloc_group(&fanotify_fsnotify_ops);
728 	if (IS_ERR(group)) {
729 		free_uid(user);
730 		return PTR_ERR(group);
731 	}
732 
733 	group->fanotify_data.user = user;
734 	atomic_inc(&user->fanotify_listeners);
735 	group->memcg = get_mem_cgroup_from_mm(current->mm);
736 
737 	oevent = fanotify_alloc_event(group, NULL, FS_Q_OVERFLOW, NULL);
738 	if (unlikely(!oevent)) {
739 		fd = -ENOMEM;
740 		goto out_destroy_group;
741 	}
742 	group->overflow_event = &oevent->fse;
743 
744 	if (force_o_largefile())
745 		event_f_flags |= O_LARGEFILE;
746 	group->fanotify_data.f_flags = event_f_flags;
747 	init_waitqueue_head(&group->fanotify_data.access_waitq);
748 	INIT_LIST_HEAD(&group->fanotify_data.access_list);
749 	switch (flags & FAN_ALL_CLASS_BITS) {
750 	case FAN_CLASS_NOTIF:
751 		group->priority = FS_PRIO_0;
752 		break;
753 	case FAN_CLASS_CONTENT:
754 		group->priority = FS_PRIO_1;
755 		break;
756 	case FAN_CLASS_PRE_CONTENT:
757 		group->priority = FS_PRIO_2;
758 		break;
759 	default:
760 		fd = -EINVAL;
761 		goto out_destroy_group;
762 	}
763 
764 	if (flags & FAN_UNLIMITED_QUEUE) {
765 		fd = -EPERM;
766 		if (!capable(CAP_SYS_ADMIN))
767 			goto out_destroy_group;
768 		group->max_events = UINT_MAX;
769 	} else {
770 		group->max_events = FANOTIFY_DEFAULT_MAX_EVENTS;
771 	}
772 
773 	if (flags & FAN_UNLIMITED_MARKS) {
774 		fd = -EPERM;
775 		if (!capable(CAP_SYS_ADMIN))
776 			goto out_destroy_group;
777 		group->fanotify_data.max_marks = UINT_MAX;
778 	} else {
779 		group->fanotify_data.max_marks = FANOTIFY_DEFAULT_MAX_MARKS;
780 	}
781 
782 	if (flags & FAN_ENABLE_AUDIT) {
783 		fd = -EPERM;
784 		if (!capable(CAP_AUDIT_WRITE))
785 			goto out_destroy_group;
786 		group->fanotify_data.audit = true;
787 	}
788 
789 	fd = anon_inode_getfd("[fanotify]", &fanotify_fops, group, f_flags);
790 	if (fd < 0)
791 		goto out_destroy_group;
792 
793 	return fd;
794 
795 out_destroy_group:
796 	fsnotify_destroy_group(group);
797 	return fd;
798 }
799 
800 static int do_fanotify_mark(int fanotify_fd, unsigned int flags, __u64 mask,
801 			    int dfd, const char  __user *pathname)
802 {
803 	struct inode *inode = NULL;
804 	struct vfsmount *mnt = NULL;
805 	struct fsnotify_group *group;
806 	struct fd f;
807 	struct path path;
808 	u32 valid_mask = FAN_ALL_EVENTS | FAN_EVENT_ON_CHILD;
809 	int ret;
810 
811 	pr_debug("%s: fanotify_fd=%d flags=%x dfd=%d pathname=%p mask=%llx\n",
812 		 __func__, fanotify_fd, flags, dfd, pathname, mask);
813 
814 	/* we only use the lower 32 bits as of right now. */
815 	if (mask & ((__u64)0xffffffff << 32))
816 		return -EINVAL;
817 
818 	if (flags & ~FAN_ALL_MARK_FLAGS)
819 		return -EINVAL;
820 	switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE | FAN_MARK_FLUSH)) {
821 	case FAN_MARK_ADD:		/* fallthrough */
822 	case FAN_MARK_REMOVE:
823 		if (!mask)
824 			return -EINVAL;
825 		break;
826 	case FAN_MARK_FLUSH:
827 		if (flags & ~(FAN_MARK_MOUNT | FAN_MARK_FLUSH))
828 			return -EINVAL;
829 		break;
830 	default:
831 		return -EINVAL;
832 	}
833 
834 	if (mask & FAN_ONDIR) {
835 		flags |= FAN_MARK_ONDIR;
836 		mask &= ~FAN_ONDIR;
837 	}
838 
839 	if (IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS))
840 		valid_mask |= FAN_ALL_PERM_EVENTS;
841 
842 	if (mask & ~valid_mask)
843 		return -EINVAL;
844 
845 	f = fdget(fanotify_fd);
846 	if (unlikely(!f.file))
847 		return -EBADF;
848 
849 	/* verify that this is indeed an fanotify instance */
850 	ret = -EINVAL;
851 	if (unlikely(f.file->f_op != &fanotify_fops))
852 		goto fput_and_out;
853 	group = f.file->private_data;
854 
855 	/*
856 	 * group->priority == FS_PRIO_0 == FAN_CLASS_NOTIF.  These are not
857 	 * allowed to set permissions events.
858 	 */
859 	ret = -EINVAL;
860 	if (mask & FAN_ALL_PERM_EVENTS &&
861 	    group->priority == FS_PRIO_0)
862 		goto fput_and_out;
863 
864 	if (flags & FAN_MARK_FLUSH) {
865 		ret = 0;
866 		if (flags & FAN_MARK_MOUNT)
867 			fsnotify_clear_vfsmount_marks_by_group(group);
868 		else
869 			fsnotify_clear_inode_marks_by_group(group);
870 		goto fput_and_out;
871 	}
872 
873 	ret = fanotify_find_path(dfd, pathname, &path, flags);
874 	if (ret)
875 		goto fput_and_out;
876 
877 	/* inode held in place by reference to path; group by fget on fd */
878 	if (!(flags & FAN_MARK_MOUNT))
879 		inode = path.dentry->d_inode;
880 	else
881 		mnt = path.mnt;
882 
883 	/* create/update an inode mark */
884 	switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE)) {
885 	case FAN_MARK_ADD:
886 		if (flags & FAN_MARK_MOUNT)
887 			ret = fanotify_add_vfsmount_mark(group, mnt, mask, flags);
888 		else
889 			ret = fanotify_add_inode_mark(group, inode, mask, flags);
890 		break;
891 	case FAN_MARK_REMOVE:
892 		if (flags & FAN_MARK_MOUNT)
893 			ret = fanotify_remove_vfsmount_mark(group, mnt, mask, flags);
894 		else
895 			ret = fanotify_remove_inode_mark(group, inode, mask, flags);
896 		break;
897 	default:
898 		ret = -EINVAL;
899 	}
900 
901 	path_put(&path);
902 fput_and_out:
903 	fdput(f);
904 	return ret;
905 }
906 
907 SYSCALL_DEFINE5(fanotify_mark, int, fanotify_fd, unsigned int, flags,
908 			      __u64, mask, int, dfd,
909 			      const char  __user *, pathname)
910 {
911 	return do_fanotify_mark(fanotify_fd, flags, mask, dfd, pathname);
912 }
913 
914 #ifdef CONFIG_COMPAT
915 COMPAT_SYSCALL_DEFINE6(fanotify_mark,
916 				int, fanotify_fd, unsigned int, flags,
917 				__u32, mask0, __u32, mask1, int, dfd,
918 				const char  __user *, pathname)
919 {
920 	return do_fanotify_mark(fanotify_fd, flags,
921 #ifdef __BIG_ENDIAN
922 				((__u64)mask0 << 32) | mask1,
923 #else
924 				((__u64)mask1 << 32) | mask0,
925 #endif
926 				 dfd, pathname);
927 }
928 #endif
929 
930 /*
931  * fanotify_user_setup - Our initialization function.  Note that we cannot return
932  * error because we have compiled-in VFS hooks.  So an (unlikely) failure here
933  * must result in panic().
934  */
935 static int __init fanotify_user_setup(void)
936 {
937 	fanotify_mark_cache = KMEM_CACHE(fsnotify_mark,
938 					 SLAB_PANIC|SLAB_ACCOUNT);
939 	fanotify_event_cachep = KMEM_CACHE(fanotify_event_info, SLAB_PANIC);
940 	if (IS_ENABLED(CONFIG_FANOTIFY_ACCESS_PERMISSIONS)) {
941 		fanotify_perm_event_cachep =
942 			KMEM_CACHE(fanotify_perm_event_info, SLAB_PANIC);
943 	}
944 
945 	return 0;
946 }
947 device_initcall(fanotify_user_setup);
948