]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man7/fanotify.7
fanotify_mark.2, fanotify.7: Document FAN_OPEN_EXEC and FAN_OPEN_EXEC_PERM
[thirdparty/man-pages.git] / man7 / fanotify.7
1 .\" Copyright (C) 2013, Heinrich Schuchardt <xypron.glpk@gmx.de>
2 .\" and Copyright (C) 2014, Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of
10 .\" this manual under the conditions for verbatim copying, provided that
11 .\" the entire resulting derived work is distributed under the terms of
12 .\" a permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume.
16 .\" no responsibility for errors or omissions, or for damages resulting.
17 .\" from the use of the information contained herein. The author(s) may.
18 .\" not have taken the same level of care in the production of this.
19 .\" manual, which is licensed free of charge, as they might when working.
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .TH FANOTIFY 7 2017-09-15 "Linux" "Linux Programmer's Manual"
26 .SH NAME
27 fanotify \- monitoring filesystem events
28 .SH DESCRIPTION
29 The fanotify API provides notification and interception of
30 filesystem events.
31 Use cases include virus scanning and hierarchical storage management.
32 Currently, only a limited set of events is supported.
33 In particular, there is no support for create, delete, and move events.
34 (See
35 .BR inotify (7)
36 for details of an API that does notify those events.)
37 .PP
38 Additional capabilities compared to the
39 .BR inotify (7)
40 API include the ability to monitor all of the objects
41 in a mounted filesystem,
42 the ability to make access permission decisions, and the
43 possibility to read or modify files before access by other applications.
44 .PP
45 The following system calls are used with this API:
46 .BR fanotify_init (2),
47 .BR fanotify_mark (2),
48 .BR read (2),
49 .BR write (2),
50 and
51 .BR close (2).
52 .SS fanotify_init(), fanotify_mark(), and notification groups
53 The
54 .BR fanotify_init (2)
55 system call creates and initializes an fanotify notification group
56 and returns a file descriptor referring to it.
57 .PP
58 An fanotify notification group is a kernel-internal object that holds
59 a list of files, directories, and mount points for which events shall be
60 created.
61 .PP
62 For each entry in an fanotify notification group, two bit masks exist: the
63 .I mark
64 mask and the
65 .I ignore
66 mask.
67 The mark mask defines file activities for which an event shall be created.
68 The ignore mask defines activities for which no event shall be generated.
69 Having these two types of masks permits a mount point or directory to be
70 marked for receiving events, while at the same time ignoring events for
71 specific objects under that mount point or directory.
72 .PP
73 The
74 .BR fanotify_mark (2)
75 system call adds a file, directory, or mount to a notification group
76 and specifies which events
77 shall be reported (or ignored), or removes or modifies such an entry.
78 .PP
79 A possible usage of the ignore mask is for a file cache.
80 Events of interest for a file cache are modification of a file and closing
81 of the same.
82 Hence, the cached directory or mount point is to be marked to receive these
83 events.
84 After receiving the first event informing that a file has been modified,
85 the corresponding cache entry will be invalidated.
86 No further modification events for this file are of interest until the file
87 is closed.
88 Hence, the modify event can be added to the ignore mask.
89 Upon receiving the close event, the modify event can be removed from the
90 ignore mask and the file cache entry can be updated.
91 .PP
92 The entries in the fanotify notification groups refer to files and
93 directories via their inode number and to mounts via their mount ID.
94 If files or directories are renamed or moved within the same mount,
95 the respective entries survive.
96 If files or directories are deleted or moved to another mount or if mounts are
97 unmounted, the corresponding entries are deleted.
98 .SS The event queue
99 As events occur on the filesystem objects monitored by a notification group,
100 the fanotify system generates events that are collected in a queue.
101 These events can then be read (using
102 .BR read (2)
103 or similar)
104 from the fanotify file descriptor
105 returned by
106 .BR fanotify_init (2).
107 .PP
108 Two types of events are generated:
109 .I notification
110 events and
111 .I permission
112 events.
113 Notification events are merely informative
114 and require no action to be taken by
115 the receiving application except for closing the file descriptor passed
116 in the event (see below).
117 Permission events are requests to the receiving application to decide
118 whether permission for a file access shall be granted.
119 For these events, the recipient must write a response which decides whether
120 access is granted or not.
121 .PP
122 An event is removed from the event queue of the fanotify group
123 when it has been read.
124 Permission events that have been read are kept in an internal list of the
125 fanotify group until either a permission decision has been taken by
126 writing to the fanotify file descriptor or the fanotify file descriptor
127 is closed.
128 .SS Reading fanotify events
129 Calling
130 .BR read (2)
131 for the file descriptor returned by
132 .BR fanotify_init (2)
133 blocks (if the flag
134 .B FAN_NONBLOCK
135 is not specified in the call to
136 .BR fanotify_init (2))
137 until either a file event occurs or the call is interrupted by a signal
138 (see
139 .BR signal (7)).
140 .PP
141 After a successful
142 .BR read (2),
143 the read buffer contains one or more of the following structures:
144 .PP
145 .in +4n
146 .EX
147 struct fanotify_event_metadata {
148 __u32 event_len;
149 __u8 vers;
150 __u8 reserved;
151 __u16 metadata_len;
152 __aligned_u64 mask;
153 __s32 fd;
154 __s32 pid;
155 };
156 .EE
157 .in
158 .PP
159 For performance reasons, it is recommended to use a large
160 buffer size (for example, 4096 bytes),
161 so that multiple events can be retrieved by a single
162 .BR read (2).
163 .PP
164 The return value of
165 .BR read (2)
166 is the number of bytes placed in the buffer,
167 or \-1 in case of an error (but see BUGS).
168 .PP
169 The fields of the
170 .I fanotify_event_metadata
171 structure are as follows:
172 .TP
173 .I event_len
174 This is the length of the data for the current event and the offset
175 to the next event in the buffer.
176 In the current implementation, the value of
177 .I event_len
178 is always
179 .BR FAN_EVENT_METADATA_LEN .
180 However, the API is designed to allow
181 variable-length structures to be returned in the future.
182 .TP
183 .I vers
184 This field holds a version number for the structure.
185 It must be compared to
186 .B FANOTIFY_METADATA_VERSION
187 to verify that the structures returned at run time match
188 the structures defined at compile time.
189 In case of a mismatch, the application should abandon trying to use the
190 fanotify file descriptor.
191 .TP
192 .I reserved
193 This field is not used.
194 .TP
195 .I metadata_len
196 This is the length of the structure.
197 The field was introduced to facilitate the implementation of
198 optional headers per event type.
199 No such optional headers exist in the current implementation.
200 .TP
201 .I mask
202 This is a bit mask describing the event (see below).
203 .TP
204 .I fd
205 This is an open file descriptor for the object being accessed, or
206 .B FAN_NOFD
207 if a queue overflow occurred.
208 The file descriptor can be used to access the contents
209 of the monitored file or directory.
210 The reading application is responsible for closing this file descriptor.
211 .IP
212 When calling
213 .BR fanotify_init (2),
214 the caller may specify (via the
215 .I event_f_flags
216 argument) various file status flags that are to be set
217 on the open file description that corresponds to this file descriptor.
218 In addition, the (kernel-internal)
219 .B FMODE_NONOTIFY
220 file status flag is set on the open file description.
221 This flag suppresses fanotify event generation.
222 Hence, when the receiver of the fanotify event accesses the notified file or
223 directory using this file descriptor, no additional events will be created.
224 .TP
225 .I pid
226 This is the ID of the process that caused the event.
227 A program listening to fanotify events can compare this PID
228 to the PID returned by
229 .BR getpid (2),
230 to determine whether the event is caused by the listener itself,
231 or is due to a file access by another process.
232 .PP
233 The bit mask in
234 .I mask
235 indicates which events have occurred for a single filesystem object.
236 Multiple bits may be set in this mask,
237 if more than one event occurred for the monitored filesystem object.
238 In particular,
239 consecutive events for the same filesystem object and originating from the
240 same process may be merged into a single event, with the exception that two
241 permission events are never merged into one queue entry.
242 .PP
243 The bits that may appear in
244 .I mask
245 are as follows:
246 .TP
247 .B FAN_ACCESS
248 A file or a directory (but see BUGS) was accessed (read).
249 .TP
250 .B FAN_OPEN
251 A file or a directory was opened.
252 .TP
253 .B FAN_OPEN_EXEC
254 A file was opened with the intent to be executed.
255 See
256 .B NOTES
257 in
258 .BR fanotify_mark (2)
259 for additional details.
260 .TP
261 .B FAN_MODIFY
262 A file was modified.
263 .TP
264 .B FAN_CLOSE_WRITE
265 A file that was opened for writing
266 .RB ( O_WRONLY
267 or
268 .BR O_RDWR )
269 was closed.
270 .TP
271 .B FAN_CLOSE_NOWRITE
272 A file or directory that was opened read-only
273 .RB ( O_RDONLY )
274 was closed.
275 .TP
276 .B FAN_Q_OVERFLOW
277 The event queue exceeded the limit of 16384 entries.
278 This limit can be overridden by specifying the
279 .BR FAN_UNLIMITED_QUEUE
280 flag when calling
281 .BR fanotify_init (2).
282 .TP
283 .B FAN_ACCESS_PERM
284 An application wants to read a file or directory, for example using
285 .BR read (2)
286 or
287 .BR readdir (2).
288 The reader must write a response (as described below)
289 that determines whether the permission to
290 access the filesystem object shall be granted.
291 .TP
292 .B FAN_OPEN_PERM
293 An application wants to open a file or directory.
294 The reader must write a response that determines whether the permission to
295 open the filesystem object shall be granted.
296 .TP
297 .B FAN_OPEN_EXEC_PERM
298 An application wants to open a file for execution.
299 The reader must write a response that determines whether the permission to
300 open the filesystem object for execution shall be granted.
301 See
302 .B NOTES
303 in
304 .BR fanotify_mark (2)
305 for additional details.
306 .PP
307 To check for any close event, the following bit mask may be used:
308 .TP
309 .B FAN_CLOSE
310 A file was closed.
311 This is a synonym for:
312 .IP
313 FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE
314 .PP
315 The following macros are provided to iterate over a buffer containing
316 fanotify event metadata returned by a
317 .BR read (2)
318 from an fanotify file descriptor:
319 .TP
320 .B FAN_EVENT_OK(meta, len)
321 This macro checks the remaining length
322 .I len
323 of the buffer
324 .I meta
325 against the length of the metadata structure and the
326 .I event_len
327 field of the first metadata structure in the buffer.
328 .TP
329 .B FAN_EVENT_NEXT(meta, len)
330 This macro uses the length indicated in the
331 .I event_len
332 field of the metadata structure pointed to by
333 .IR meta
334 to calculate the address of the next metadata structure that follows
335 .IR meta .
336 .I len
337 is the number of bytes of metadata that currently remain in the buffer.
338 The macro returns a pointer to the next metadata structure that follows
339 .IR meta ,
340 and reduces
341 .I len
342 by the number of bytes in the metadata structure that
343 has been skipped over (i.e., it subtracts
344 .IR meta\->event_len
345 from
346 .IR len ).
347 .PP
348 In addition, there is:
349 .TP
350 .B FAN_EVENT_METADATA_LEN
351 This macro returns the size (in bytes) of the structure
352 .IR fanotify_event_metadata .
353 This is the minimum size (and currently the only size) of any event metadata.
354 .\"
355 .SS Monitoring an fanotify file descriptor for events
356 When an fanotify event occurs, the fanotify file descriptor indicates as
357 readable when passed to
358 .BR epoll (7),
359 .BR poll (2),
360 or
361 .BR select (2).
362 .SS Dealing with permission events
363 For permission events, the application must
364 .BR write (2)
365 a structure of the following form to the
366 fanotify file descriptor:
367 .PP
368 .in +4n
369 .EX
370 struct fanotify_response {
371 __s32 fd;
372 __u32 response;
373 };
374 .EE
375 .in
376 .PP
377 The fields of this structure are as follows:
378 .TP
379 .I fd
380 This is the file descriptor from the structure
381 .IR fanotify_event_metadata .
382 .TP
383 .I response
384 This field indicates whether or not the permission is to be granted.
385 Its value must be either
386 .B FAN_ALLOW
387 to allow the file operation or
388 .B FAN_DENY
389 to deny the file operation.
390 .PP
391 If access is denied, the requesting application call will receive an
392 .BR EPERM
393 error.
394 .SS Closing the fanotify file descriptor
395 .PP
396 When all file descriptors referring to the fanotify notification group are
397 closed, the fanotify group is released and its resources
398 are freed for reuse by the kernel.
399 Upon
400 .BR close (2),
401 outstanding permission events will be set to allowed.
402 .SS /proc/[pid]/fdinfo
403 The file
404 .I /proc/[pid]/fdinfo/[fd]
405 contains information about fanotify marks for file descriptor
406 .I fd
407 of process
408 .IR pid .
409 See
410 .BR proc (5)
411 for details.
412 .SH ERRORS
413 In addition to the usual errors for
414 .BR read (2),
415 the following errors can occur when reading from the
416 fanotify file descriptor:
417 .TP
418 .B EINVAL
419 The buffer is too small to hold the event.
420 .TP
421 .B EMFILE
422 The per-process limit on the number of open files has been reached.
423 See the description of
424 .B RLIMIT_NOFILE
425 in
426 .BR getrlimit (2).
427 .TP
428 .B ENFILE
429 The system-wide limit on the total number of open files has been reached.
430 See
431 .I /proc/sys/fs/file-max
432 in
433 .BR proc (5).
434 .TP
435 .B ETXTBSY
436 This error is returned by
437 .BR read (2)
438 if
439 .B O_RDWR
440 or
441 .B O_WRONLY
442 was specified in the
443 .I event_f_flags
444 argument when calling
445 .BR fanotify_init (2)
446 and an event occurred for a monitored file that is currently being executed.
447 .PP
448 In addition to the usual errors for
449 .BR write (2),
450 the following errors can occur when writing to the fanotify file descriptor:
451 .TP
452 .B EINVAL
453 Fanotify access permissions are not enabled in the kernel configuration
454 or the value of
455 .I response
456 in the response structure is not valid.
457 .TP
458 .B ENOENT
459 The file descriptor
460 .I fd
461 in the response structure is not valid.
462 This may occur when a response for the permission event has already been
463 written.
464 .SH VERSIONS
465 The fanotify API was introduced in version 2.6.36 of the Linux kernel and
466 enabled in version 2.6.37.
467 Fdinfo support was added in version 3.8.
468 .SH CONFORMING TO
469 The fanotify API is Linux-specific.
470 .SH NOTES
471 The fanotify API is available only if the kernel was built with the
472 .B CONFIG_FANOTIFY
473 configuration option enabled.
474 In addition, fanotify permission handling is available only if the
475 .B CONFIG_FANOTIFY_ACCESS_PERMISSIONS
476 configuration option is enabled.
477 .SS Limitations and caveats
478 Fanotify reports only events that a user-space program triggers through the
479 filesystem API.
480 As a result,
481 it does not catch remote events that occur on network filesystems.
482 .PP
483 The fanotify API does not report file accesses and modifications that
484 may occur because of
485 .BR mmap (2),
486 .BR msync (2),
487 and
488 .BR munmap (2).
489 .PP
490 Events for directories are created only if the directory itself is opened,
491 read, and closed.
492 Adding, removing, or changing children of a marked directory does not create
493 events for the monitored directory itself.
494 .PP
495 Fanotify monitoring of directories is not recursive:
496 to monitor subdirectories under a directory,
497 additional marks must be created.
498 (But note that the fanotify API provides no way of detecting when a
499 subdirectory has been created under a marked directory,
500 which makes recursive monitoring difficult.)
501 Monitoring mounts offers the capability to monitor a whole directory tree.
502 .PP
503 The event queue can overflow.
504 In this case, events are lost.
505 .SH BUGS
506 Before Linux 3.19,
507 .BR fallocate (2)
508 did not generate fanotify events.
509 Since Linux 3.19,
510 .\" commit 820c12d5d6c0890bc93dd63893924a13041fdc35
511 calls to
512 .BR fallocate (2)
513 generate
514 .B FAN_MODIFY
515 events.
516 .PP
517 As of Linux 3.17,
518 the following bugs exist:
519 .IP * 3
520 On Linux, a filesystem object may be accessible through multiple paths,
521 for example, a part of a filesystem may be remounted using the
522 .IR \-\-bind
523 option of
524 .BR mount (8).
525 A listener that marked a mount will be notified only of events that were
526 triggered for a filesystem object using the same mount.
527 Any other event will pass unnoticed.
528 .IP *
529 .\" FIXME . A patch was proposed.
530 When an event is generated,
531 no check is made to see whether the user ID of the
532 receiving process has authorization to read or write the file
533 before passing a file descriptor for that file.
534 This poses a security risk, when the
535 .B CAP_SYS_ADMIN
536 capability is set for programs executed by unprivileged users.
537 .IP *
538 If a call to
539 .BR read (2)
540 processes multiple events from the fanotify queue and an error occurs,
541 the return value will be the total length of the events successfully
542 copied to the user-space buffer before the error occurred.
543 The return value will not be \-1, and
544 .I errno
545 will not be set.
546 Thus, the reading application has no way to detect the error.
547 .SH EXAMPLE
548 The following program demonstrates the usage of the fanotify API.
549 It marks the mount point passed as a command-line argument
550 and waits for events of type
551 .B FAN_OPEN_PERM
552 and
553 .BR FAN_CLOSE_WRITE .
554 When a permission event occurs, a
555 .B FAN_ALLOW
556 response is given.
557 .PP
558 The following output was recorded while editing the file
559 .IR /home/user/temp/notes .
560 Before the file was opened, a
561 .B FAN_OPEN_PERM
562 event occurred.
563 After the file was closed, a
564 .B FAN_CLOSE_WRITE
565 event occurred.
566 Execution of the program ends when the user presses the ENTER key.
567 .SS Example output
568 .in +4n
569 .EX
570 # ./fanotify_example /home
571 Press enter key to terminate.
572 Listening for events.
573 FAN_OPEN_PERM: File /home/user/temp/notes
574 FAN_CLOSE_WRITE: File /home/user/temp/notes
575
576 Listening for events stopped.
577 .EE
578 .in
579 .SS Program source
580 \&
581 .EX
582 #define _GNU_SOURCE /* Needed to get O_LARGEFILE definition */
583 #include <errno.h>
584 #include <fcntl.h>
585 #include <limits.h>
586 #include <poll.h>
587 #include <stdio.h>
588 #include <stdlib.h>
589 #include <sys/fanotify.h>
590 #include <unistd.h>
591
592 /* Read all available fanotify events from the file descriptor 'fd' */
593
594 static void
595 handle_events(int fd)
596 {
597 const struct fanotify_event_metadata *metadata;
598 struct fanotify_event_metadata buf[200];
599 ssize_t len;
600 char path[PATH_MAX];
601 ssize_t path_len;
602 char procfd_path[PATH_MAX];
603 struct fanotify_response response;
604
605 /* Loop while events can be read from fanotify file descriptor */
606
607 for(;;) {
608
609 /* Read some events */
610
611 len = read(fd, (void *) &buf, sizeof(buf));
612 if (len == \-1 && errno != EAGAIN) {
613 perror("read");
614 exit(EXIT_FAILURE);
615 }
616
617 /* Check if end of available data reached */
618
619 if (len <= 0)
620 break;
621
622 /* Point to the first event in the buffer */
623
624 metadata = buf;
625
626 /* Loop over all events in the buffer */
627
628 while (FAN_EVENT_OK(metadata, len)) {
629
630 /* Check that run\-time and compile\-time structures match */
631
632 if (metadata\->vers != FANOTIFY_METADATA_VERSION) {
633 fprintf(stderr,
634 "Mismatch of fanotify metadata version.\\n");
635 exit(EXIT_FAILURE);
636 }
637
638 /* metadata\->fd contains either FAN_NOFD, indicating a
639 queue overflow, or a file descriptor (a nonnegative
640 integer). Here, we simply ignore queue overflow. */
641
642 if (metadata\->fd >= 0) {
643
644 /* Handle open permission event */
645
646 if (metadata\->mask & FAN_OPEN_PERM) {
647 printf("FAN_OPEN_PERM: ");
648
649 /* Allow file to be opened */
650
651 response.fd = metadata\->fd;
652 response.response = FAN_ALLOW;
653 write(fd, &response,
654 sizeof(struct fanotify_response));
655 }
656
657 /* Handle closing of writable file event */
658
659 if (metadata\->mask & FAN_CLOSE_WRITE)
660 printf("FAN_CLOSE_WRITE: ");
661
662 /* Retrieve and print pathname of the accessed file */
663
664 snprintf(procfd_path, sizeof(procfd_path),
665 "/proc/self/fd/%d", metadata\->fd);
666 path_len = readlink(procfd_path, path,
667 sizeof(path) \- 1);
668 if (path_len == \-1) {
669 perror("readlink");
670 exit(EXIT_FAILURE);
671 }
672
673 path[path_len] = '\\0';
674 printf("File %s\\n", path);
675
676 /* Close the file descriptor of the event */
677
678 close(metadata\->fd);
679 }
680
681 /* Advance to next event */
682
683 metadata = FAN_EVENT_NEXT(metadata, len);
684 }
685 }
686 }
687
688 int
689 main(int argc, char *argv[])
690 {
691 char buf;
692 int fd, poll_num;
693 nfds_t nfds;
694 struct pollfd fds[2];
695
696 /* Check mount point is supplied */
697
698 if (argc != 2) {
699 fprintf(stderr, "Usage: %s MOUNT\\n", argv[0]);
700 exit(EXIT_FAILURE);
701 }
702
703 printf("Press enter key to terminate.\\n");
704
705 /* Create the file descriptor for accessing the fanotify API */
706
707 fd = fanotify_init(FAN_CLOEXEC | FAN_CLASS_CONTENT | FAN_NONBLOCK,
708 O_RDONLY | O_LARGEFILE);
709 if (fd == \-1) {
710 perror("fanotify_init");
711 exit(EXIT_FAILURE);
712 }
713
714 /* Mark the mount for:
715 \- permission events before opening files
716 \- notification events after closing a write\-enabled
717 file descriptor */
718
719 if (fanotify_mark(fd, FAN_MARK_ADD | FAN_MARK_MOUNT,
720 FAN_OPEN_PERM | FAN_CLOSE_WRITE, AT_FDCWD,
721 argv[1]) == \-1) {
722 perror("fanotify_mark");
723 exit(EXIT_FAILURE);
724 }
725
726 /* Prepare for polling */
727
728 nfds = 2;
729
730 /* Console input */
731
732 fds[0].fd = STDIN_FILENO;
733 fds[0].events = POLLIN;
734
735 /* Fanotify input */
736
737 fds[1].fd = fd;
738 fds[1].events = POLLIN;
739
740 /* This is the loop to wait for incoming events */
741
742 printf("Listening for events.\\n");
743
744 while (1) {
745 poll_num = poll(fds, nfds, \-1);
746 if (poll_num == \-1) {
747 if (errno == EINTR) /* Interrupted by a signal */
748 continue; /* Restart poll() */
749
750 perror("poll"); /* Unexpected error */
751 exit(EXIT_FAILURE);
752 }
753
754 if (poll_num > 0) {
755 if (fds[0].revents & POLLIN) {
756
757 /* Console input is available: empty stdin and quit */
758
759 while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\\n')
760 continue;
761 break;
762 }
763
764 if (fds[1].revents & POLLIN) {
765
766 /* Fanotify events are available */
767
768 handle_events(fd);
769 }
770 }
771 }
772
773 printf("Listening for events stopped.\\n");
774 exit(EXIT_SUCCESS);
775 }
776 .EE
777 .SH SEE ALSO
778 .ad l
779 .BR fanotify_init (2),
780 .BR fanotify_mark (2),
781 .BR inotify (7)