I'm attempting to do function hooking of readdir(). I want to be able to intercept a readdir() call only if a specific path is opened. Essentially, I want to reverse opendir() in that I want to be able to recover the directory path from a DIR struct.
I am aware one way of doing this is just opening the directory I want to intercept and comparing both structs, but the directory I am looking to intercept have exactly the same files I don't want to intercept in other directories. Is there a way to do what I am looking for?
If we had control of the actual target program source, we could just add calls surrounding the desired calls.
However, I'm going to assume that you want to be able to "spy" on a given binary program.
We can do this by creating a shared library (e.g.
spy.so) that interceptsopendir/readddir/closedirusingdlsymet. al.When we want to spy on a given program, we do:
This "spy" library will:
SPYDIR, a colon separated list of directories (similar toPATH).opendircall, it will check the argument against this "desired/passive" list.DIR *return value from [the real]opendirreaddiris intercepted, theDIR *argument is matched within the active list. If a match, we "intercept" thereaddirclosediris called, it removes the corresponding entry from the active list [if any].Here is the shared "spy" library source (
spy.c). It is annotated:Here is a test program (
test.c):Build and run with this
Makefile:Here is the sample output. In the demo, note that the "intercepted" calls replace the first character of the filename with
%: