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