17

I have a librandom.so library and a main exectuable which was compiled as follows:

$ clang++ -o main main.o -lrandom -L. -Wl,-rpath,"\$ORIGIN"

They are both in the same directory. Since main has $ORIGIN in its rpath, it works fine - ./main returns without errors.

Now, I'm setting main to run with setuid as root:

$ sudo chown root main
$ sudo chmod a+s main
$ ./main

I expected main to fail since $ORIGIN is not expanded in setuid applications. Surprisingly, it works.

If I run main from another directory, though, it does fail as expected:

$ cd /tmp    
$ /path/to/main
/path/to/main: error while loading shared libraries: librandom.so: cannot open shared object file: No such file or directory

Why does it work when I run main from its containing directory?

Amir Rachum
  • 76,817
  • 74
  • 166
  • 248

1 Answers1

7

I expected main to fail since $ORIGIN is not expanded in setuid applications. Surprisingly, it works.

Glibc has a long history of expanding $ORIGIN even for suid binaries (see e.g. CVE-2010-3847). The motivation behind this is that suid binaries that use $ORIGIN for rpath are broken by design so Glibc developers were never very bothered to fix this. Some downstream distros provided patches on top of stock Glibc which disable ORIGIN-expansion so exact situation depends on your distro.

Funny enough, only free-standing $ORIGIN will be expanded - if you replace it with e.g. $ORIGIN/libs it'll start to fail.

Why does it work when I run main from its containing directory?

Once you move your file, $ORIGIN will expand to different folder which no longer contains the required library.

yugr
  • 19,769
  • 3
  • 51
  • 96
  • 1
    Regarding the second parts - I'm not moving the file, just the current directory. `$ORIGIN` is relative to the location of the executable, not the current working directory. – Amir Rachum Nov 28 '16 at 21:11
  • Right. It seems Ubuntu uses variant of Glibc patch that expands `$ORIGIN` to empty string (e.g. described in [this comment](https://sourceware.org/bugzilla/show_bug.cgi?id=12393#c0)). Dynamic linker will then treat this as CWD which would explain the behavior. You can probably [report this to developers](https://bugs.launchpad.net/ubuntu/) but I doubt they'll be interested. – yugr Nov 29 '16 at 06:05