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