<p>Besides the LD_PRELOAD trick , and Linux Kernel Modules that replace a certain syscall with one provided by you , is there any possibility to intercept a syscall ( open for example ) , so that it first goes through your function , before it reaches the actual open ?</p>

[{'answer_id': 69884, 'author': 'DJ Capelis', 'author_id': 10943, 'author_profile': 'https://Stackoverflow.com/users/10943', 'pm_score': 4, 'selected': False, 'text': '<p>Why can\'t you / don\'t want to use the <a href="https://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick">LD_PRELOAD trick</a>?</p>\n\n<p>Example code here:</p>\n\n<pre><code>/*\n * File: soft_atimes.c\n * Author: D.J. Capelis\n *\n * Compile:\n * gcc -fPIC -c -o soft_atimes.o soft_atimes.c\n * gcc -shared -o soft_atimes.so soft_atimes.o -ldl\n *\n * Use:\n * LD_PRELOAD="./soft_atimes.so" command\n *\n * Copyright 2007 Regents of the University of California\n */\n\n#define _GNU_SOURCE\n#include &lt;dlfcn.h&gt;\n#define _FCNTL_H\n#include &lt;sys/types.h&gt;\n#include &lt;bits/fcntl.h&gt;\n#include &lt;stddef.h&gt;\n\nextern int errorno;\n\nint __thread (*_open)(const char * pathname, int flags, ...) = NULL;\nint __thread (*_open64)(const char * pathname, int flags, ...) = NULL;\n\nint open(const char * pathname, int flags, mode_t mode)\n{\n    if (NULL == _open) {\n        _open = (int (*)(const char * pathname, int flags, ...)) dlsym(RTLD_NEXT, "open");\n    }\n    if(flags &amp; O_CREAT)\n        return _open(pathname, flags | O_NOATIME, mode);\n    else\n        return _open(pathname, flags | O_NOATIME, 0);\n}\n\nint open64(const char * pathname, int flags, mode_t mode)\n{\n    if (NULL == _open64) {\n        _open64 = (int (*)(const char * pathname, int flags, ...)) dlsym(RTLD_NEXT, "open64");\n    }\n    if(flags &amp; O_CREAT)\n        return _open64(pathname, flags | O_NOATIME, mode);\n    else\n        return _open64(pathname, flags | O_NOATIME, 0);\n}\n</code></pre>\n\n<p>From what I understand... it is pretty much the LD_PRELOAD trick or a kernel module.  There\'s not a whole lot of middle ground unless you want to run it under an emulator which can trap out to your function or do code re-writing on the actual binary to trap out to your function.</p>\n\n<p>Assuming you can\'t modify the program and can\'t (or don\'t want to) modify the kernel, the LD_PRELOAD approach is the best one, assuming your application is fairly standard and isn\'t actually one that\'s maliciously trying to get past your interception.  (In which case you will need one of the other techniques.)</p>\n'}, {'answer_id': 69958, 'author': 'sztanpet', 'author_id': 5832, 'author_profile': 'https://Stackoverflow.com/users/5832', 'pm_score': 2, 'selected': True, 'text': '<p>if you really need a solution you might be interested in the DR rootkit that accomplishes just this, <a href="http://www.immunityinc.com/downloads/linux_rootkit_source.tbz2" rel="nofollow noreferrer">http://www.immunityinc.com/downloads/linux_rootkit_source.tbz2</a> the article about it is here <a href="http://www.theregister.co.uk/2008/09/04/linux_rootkit_released/" rel="nofollow noreferrer">http://www.theregister.co.uk/2008/09/04/linux_rootkit_released/</a></p>\n'}, {'answer_id': 69972, 'author': 'DJ Capelis', 'author_id': 10943, 'author_profile': 'https://Stackoverflow.com/users/10943', 'pm_score': 2, 'selected': False, 'text': '<p>I don\'t have the syntax to do this gracefully with an LKM offhand, but this article provides a good overview of what you\'d need to do:  <a href="http://www.linuxjournal.com/article/4378" rel="nofollow noreferrer">http://www.linuxjournal.com/article/4378</a></p>\n\n<p>You could also just patch the sys_open function.  It starts on line 1084 of file/open.c as of linux-2.6.26.</p>\n\n<p>You might also see if you can\'t use inotify, systemtap or SELinux to do all this logging for you without you having to build a new system.</p>\n'}, {'answer_id': 71214, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.valgrind.org" rel="noreferrer">Valgrind</a> can be used to intercept any function call. If you need to intercept a system call in your finished product then this will be no use. However, if you are try to intercept during development then it can be very useful. I have frequently used this technique to intercept hashing functions so that I can control the returned hash for testing purposes.</p>\n\n<p>In case you are not aware, Valgrind is mainly used for finding memory leaks and other memory related errors. But the underlying technology is basically an x86 emulator. It emulates your program and intercepts calls to malloc/free etc. The good thing is, you do not need to recompile to use it.</p>\n\n<p>Valgrind has a feature that they term <em>Function Wrapping</em>, which is used to control the interception of functions.  See section 3.2 of the <a href="http://www.valgrind.org/docs/manual/valgrind_manual.pdf" rel="noreferrer">Valgrind manual</a> for details. You can setup function wrapping for any function you like. Once the call is intercepted the alternative function that you provide is then invoked. </p>\n'}, {'answer_id': 72606, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 2, 'selected': False, 'text': "<p>If you just want to <em>watch</em> what's opened, you want to look at the ptrace() function, or the source code of the commandline strace utility.  If you actually want to <em>intercept</em> the call, to maybe make it do something else, I think the options you listed - LD_PRELOAD or a kernel module - are your only options.</p>\n"}, {'answer_id': 78361, 'author': 'Johan Dahlin', 'author_id': 14337, 'author_profile': 'https://Stackoverflow.com/users/14337', 'pm_score': 2, 'selected': False, 'text': '<p>If you just want to do it for debugging purposes look into strace, which is built in top of the ptrace(2) system call which allows you to hook up code when a system call is done. See the PTRACE_SYSCALL part of the man page.</p>\n'}, {'answer_id': 79901, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Some applications can trick strace/ptrace not to run, so the only real option I\'ve had is using systemtap</p>\n\n<p>Systemtap can intercept a bunch of system calls if need be due to its wild card matching. Systemtap is not C, but a separate language.  In basic mode, the systemtap should prevent you from doing stupid things, but it also can run in "expert mode" that falls back to allowing a developer to use C if that is required.</p>\n\n<p>It does not require you to patch your kernel (Or at least shouldn\'t), and once a module has been compiled, you can copy it from a test/development box and insert it (via insmod) on a production system.</p>\n\n<p>I have yet to find a linux application that has found a way to work around/avoid getting caught by systemtap.</p>\n'}, {'answer_id': 4744025, 'author': 'Troy Rose', 'author_id': 582528, 'author_profile': 'https://Stackoverflow.com/users/582528', 'pm_score': 1, 'selected': False, 'text': '<p>Sounds like you need auditd.</p>\n\n<p>Auditd allows global tracking of all syscalls or accesses to files, with logging. You can set keys for specific events that you are interested in.</p>\n'}, {'answer_id': 57713437, 'author': 'Jaime Hablutzel', 'author_id': 320594, 'author_profile': 'https://Stackoverflow.com/users/320594', 'pm_score': 1, 'selected': False, 'text': '<p>Using SystemTap may be an option. </p>\n\n<p>For Ubuntu, install it as indicated in <a href="https://wiki.ubuntu.com/Kernel/Systemtap" rel="nofollow noreferrer">https://wiki.ubuntu.com/Kernel/Systemtap</a>.</p>\n\n<p>Then just execute the following and you will be listening on all <code>openat</code> syscalls:</p>\n\n<pre><code># stap -e \'probe syscall.openat { printf("%s(%s)\\n", name, argstr) }\'\nopenat(AT_FDCWD, "/dev/fb0", O_RDWR)\nopenat(AT_FDCWD, "/sys/devices/virtual/tty/tty0/active", O_RDONLY)\nopenat(AT_FDCWD, "/sys/devices/virtual/tty/tty0/active", O_RDONLY)\nopenat(AT_FDCWD, "/dev/tty1", O_RDONLY)\n</code></pre>\n'}, {'answer_id': 69852132, 'author': 'Timmmm', 'author_id': 265521, 'author_profile': 'https://Stackoverflow.com/users/265521', 'pm_score': 3, 'selected': False, 'text': '<p>First lets eliminate some non-answers that other people have given:</p>\n<ul>\n<li>Use <code>LD_PRELOAD</code>. Yeah you said &quot;Besides <code>LD_PRELOAD</code>...&quot; in the question but apparently that isn\'t enough for some people. This isn\'t a good option because it only works if the program uses libc which isn\'t necessarily the case.</li>\n<li>Use Systemtap. Yeah you said &quot;Besides ... Linux Kernel Modules&quot; in the question but apparently that isn\'t enough for some people. This isn\'t a good option because you have to load a custom kernal module which is a major pain in the arse and also requires root.</li>\n<li>Valgrind. This does sort of work but it works be simulating the CPU so it\'s really slow and really complicated. Fine if you\'re just doing this for one-off debugging. Not really an option if you\'re doing something production-worthy.</li>\n<li>Various syscall auditing things. I don\'t think logging syscalls counts as &quot;intercepting&quot; them. We clearly want to modify the syscall parameters / return values or redirect the program through some other code.</li>\n</ul>\n<p>However there are other possibilities not mentioned here yet. Note I\'m new to all this stuff and haven\'t tried any of it yet so I may be wrong about some things.</p>\n<h2>Rewrite the code</h2>\n<p>In theory you could use some kind of custom loader that rewrites the syscall instructions to jump to a custom handler instead. But I think that would be an absolute nightmare to implement.</p>\n<h2>kprobes</h2>\n<p><a href="https://www.kernel.org/doc/Documentation/kprobes.txt" rel="nofollow noreferrer">kprobes</a> are some kind of kernel instrumentation system. They only have read-only access to anything so you can\'t use them to intercept syscalls, only log them.</p>\n<h2>ptrace</h2>\n<p><a href="https://linux.die.net/man/2/ptrace" rel="nofollow noreferrer">ptrace</a> is the API that debuggers like GDB use to do their debugging. There is a <code>PTRACE_SYSCALL</code> option which will pause execution just before/after syscalls. From there you can do pretty much whatever you like in the same way that GDB can. <a href="https://www.alfonsobeato.net/c/modifying-system-call-arguments-with-ptrace/" rel="nofollow noreferrer">Here\'s an article about how to modify syscall paramters using ptrace</a>. However it apparently has high overhead.</p>\n<h2>Seccomp</h2>\n<p><a href="https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt" rel="nofollow noreferrer">Seccomp</a> is a system that is design to allow you to <em>filter</em> syscalls. You can\'t modify the arguments, but you <em>can</em> block them or return custom errors. Seccomp filters are BPF programs. If you\'re not familiar, they are basically arbitrary programs that users can run in a kernel-space VM. This avoids the user/kernel context switch which makes them faster than ptrace.</p>\n<p>While you can\'t modify arguments directly from your BPF program you <em>can</em> return <code>SECCOMP_RET_TRACE</code> which will trigger a <code>ptrace</code>ing parent to break. So it\'s basically the same as <code>PTRACE_SYSCALL</code> except you get to run a program in kernel space to decide whether you want to actually intercept a syscall based on its arguments. So it should be faster if you only want to intercept some syscalls (e.g. <code>open()</code> with specific paths).</p>\n<p>I think this is probably the best option. <a href="https://www.alfonsobeato.net/tag/seccomp/" rel="nofollow noreferrer">Here\'s an article about it from the same author as the one above</a>. <strike>Note they use classic BPF instead of eBPF but I guess you can use eBPF too.</strike></p>\n<p>Edit: Actually you can only use classic BPF, not eBPF. There\'s <a href="https://lwn.net/Articles/857228/" rel="nofollow noreferrer">a LWN article about it</a>.</p>\n<p>Here are some related questions. The first one is definitely worth reading.</p>\n<ul>\n<li><a href="https://stackoverflow.com/questions/43003805/can-ebpf-modify-the-return-value-or-parameters-of-a-syscall/43268462#43268462">Can eBPF modify the return value or parameters of a syscall?</a></li>\n<li><a href="https://stackoverflow.com/questions/67045211/intercept-only-syscall-with-ptrace-singlestep">Intercept only syscall with PTRACE_SINGLESTEP</a></li>\n<li><a href="https://stackoverflow.com/questions/10688707/is-this-is-a-good-way-to-intercept-system-calls">Is this is a good way to intercept system calls?</a></li>\n<li><a href="https://stackoverflow.com/questions/11291632/minimal-overhead-way-of-intercepting-system-calls-without-modifying-the-kernel">Minimal overhead way of intercepting system calls without modifying the kernel</a></li>\n</ul>\n<p>There\'s also a good article about manipulating syscalls via ptrace <a href="https://nullprogram.com/blog/2018/06/23/" rel="nofollow noreferrer">here</a>.</p>\n'}]
['https://Stackoverflow.com/questions/69859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11234/']