Pesquisa de VulnerabilidadeVulnerability Research
Outra visão para SSRFAnother Vision for SSRF
Quando o cenário interno não rende nada e o SSRF parece de baixo impacto, dá pra usar o server-side pra chegar no client-side — e roubar cookies HttpOnly / SameSite que um XSS jamais alcançaria, mirando account takeover.When the internal scenario yields nothing and the SSRF looks low-impact, you can use the server-side to reach the client-side — and steal HttpOnly / SameSite cookies that an XSS could never touch, aiming straight at account takeover.
- CVE ID
- Severity
- Affected
- Vendor
- Disclosure
- Researcher
- phor3nsic_br — @phor3nsic_br
Por muito tempo eu testei falhas de SSRF procurando serviços e portas da rede interna, usando essa informação pra obter dados interessantes ou chegar num RCE. Mas nos últimos dias caí em situações em que eu não tinha um cenário interno: tinha uma boa falha, só que o impacto dela seria baixo. Até que surgiu uma ideia massa — e eu queria dividir ela com você!For a long time I tested SSRF bugs looking for services and ports on the internal network, using that info to grab interesting data or reach an RCE. But over the last few days I ran into situations where I had no internal scenario: I had a good bug, but its impact would be low. Until a great idea came up — and I wanted to share it with you!
ConteúdoContents
O que é SSRFWhat is SSRF
Por mais que eu acredite que mais da metade dos leitores que estão vendo este artigo já saibam o que é SSRF (Server Side Request Forgery), deixo aqui a descrição e a referência pra facilitar o entendimento de todo mundo:As much as I believe more than half of the readers seeing this article already know what SSRF (Server Side Request Forgery) is, I'll leave the description and reference here to make it easier for everyone to follow:
"A aplicação alvo pode ter uma funcionalidade de importar dados de uma URL, publicar dados numa URL ou, de outra forma, ler dados de uma URL que pode ser adulterada. O atacante modifica as chamadas a essa funcionalidade fornecendo uma URL completamente diferente ou manipulando como as URLs são montadas (path traversal etc.).""The target application may have functionality for importing data from a URL, publishing data to a URL or otherwise reading data from a URL that can be tampered with. The attacker modifies the calls to this functionality by supplying a completely different URL or by manipulating how URLs are built (path traversal etc.)."
A visão comumCommon Vision
Lendo tudo o que se escreve sobre SSRF, a gente tem uma linha de raciocínio bem definida pra entender — talvez porque seja a mais comentada por todo mundo: um atacante manipula a request do lado servidor pra ganhar acesso a dados internos.Reading all the write-ups about SSRF, we end up with one line of reasoning to follow — maybe because it's the one everybody talks about the most: an attacker manipulates the server-side request to gain access to internal data.
Só que as empresas, sabendo do problema, segregam esses hosts, de modo que o atacante não consiga tirar nada da rede interna, limitando o acesso a portas e implementando uma série de restrições onde o SSRF não seria aceito por programas de bug bounty, nem pelo cliente.But companies, aware of the possible problem, segregate these hosts so the attacker can't get anything from the internal network, limiting access to ports and putting in a series of restrictions where SSRF wouldn't be accepted by bug bounty programs, or by the client.
Ok, então o SSRF se limita só a isso? Não tem mais nada que a gente possa fazer?Okay, so is SSRF limited to just that? Is there nothing else we can do?
Outra visãoAnother Vision
SSRF para Account TakeoverSSRF To Account Takeover
Antes de continuar: durante a escrita deste texto, o canal Bug Bounty Reports Explained, do @gregxsunday, trouxe outra visão bem legal sobre SSRF+Phishing, que vale conferir. Mas, ainda assim, aqui a gente vai tratar de um outro ponto de vista!Before continuing: while I was writing this, the Bug Bounty Reports Explained channel by @gregxsunday put out another cool view on SSRF+Phishing that's worth a watch. Still, here we'll deal with yet another point of view!
O conceito que eu trago é usar o server-side pra chegar no client-side — e mesmo assim conseguir uma criticidade alta, porque o objetivo final é alcançar o usuário e os dados dele, por meio de um SSRF num sub/domínio.The concept I bring is to use the server-side to reach the client-side, and we still get a high criticality, because the end goal is to reach the user and their data, through an SSRF in a sub/domain.
Pra chegar no client-side, a gente precisa que o nosso SSRF reflita os headers usados pelo cliente — algo comum em SSRF que vai servir de proxy, em que o atacante pode definir um proxy na aplicação.To reach the client-side, we need our SSRF to reflect the headers used by the client — this is common in SSRF that will serve as a proxy, where the attacker can define a proxy in the application.
Fazendo isso, a gente tem algo parecido com um subdomain takeover, já que consegue assumir todo o conteúdo que transita por aquele subdomínio. Isso já é bem impactante no caso de um domínio, mas no caso de um subdomínio fora de escopo, ou de um ambiente de dev, pode não ter tanto efeito — não há tantas requests diretas pra regiões assim, e a empresa pode informar que aquilo não está sob o controle dela, reduzindo o impacto da vulnerabilidade.By doing this we have something similar to a subdomain takeover, since we can take over all the content that transits to that subdomain. This is already very impactful in the case of a domain, but in the case of an out-of-scope subdomain, or a dev environment, it may not have as much effect — there aren't many direct requests to regions like that, and the company can say it's not under their control, reducing the impact of the vulnerability.
Vamos pra outra funcionalidade. A gente precisa de cookies de autenticação/sessão de aplicações no mesmo domínio do SSRF.Let's move on to another functionality. We need authentication/session cookies for applications on the same domain as the SSRF.
Exemplo:Example:
Se o SSRF está em ssrf.dev.example.com, a gente precisa achar uma aplicação com autenticação em *.example.com que tenha os cookies setados assim:If the SSRF is on ssrf.dev.example.com, we need to find an application with authentication on *.example.com that has cookies set as follows:
Set-cookie: session=SECRET_SESSION, domain=.example.com, HttpOnly
Repare que o cookie está sendo setado de forma que pode trafegar livremente entre todos os subdomínios de *.example.com.Note that the cookie is being set so that it can move freely between all subdomains of *.example.com.
A maioria da gente sabe que, se um cookie tem a flag HttpOnly, ele não pode ser obtido por uma falha de XSS. Se você não sabe, dá uma lida:Most of us know that if a cookie has the HttpOnly flag it can't be obtained through an XSS bug. If you don't know, give it a read:
Então, mesmo que a gente tenha um XSS em qualquer subdomínio de example.com, não dá pra capturar os cookies — mas ainda dá pra reusá-los com fetch. Leia mais aqui.So, even if we have an XSS on any subdomain of example.com, we can't capture the cookies — but we can still reuse them with fetch. Read more here.
No caso de o Set-Cookie estar aplicando SameSite desta forma:In case the Set-Cookie is deploying SameSite this way:
Set-cookie: session=SECRET_SESSION, domain=.example.com, HttpOnly, SameSite=Lax
A gente não conseguiria nem pegar os cookies, nem reusá-los com fetch via XSS, por causa da implementação do SameSite.We could neither get the cookies nor reuse them with fetch through an XSS, due to the SameSite implementation.
Ok, ok, ok...Ok, Ok, Ok...
A gente não consegue obter nem reusar os cookies por um XSS — mas a gente consegue roubar esses cookies por um SSRF!We cannot obtain or reuse cookies through an XSS — but we can steal these cookies through an SSRF!
A request carrega os cookies, e eles podem ser obtidos pelos logs do servidor que está monitorando as requests.The request carries cookies, and they can be obtained through logs from the server that's monitoring the requests.
O atacante precisa fazer com que o SSRF direcione as requests pro servidor dele, e então disponibilizar o conteúdo desse servidor por meio do domínio vulnerável. Mandando a URL do servidor pra vítima, ela de algum jeito acessa a URL. Logo o atacante vai pegar o cookie de sessão pelos logs!The attacker must make the SSRF direct requests to their server, and then make that server's content available through the vulnerable domain. By sending the server URL to the victim, the victim somehow accesses the URL. Soon the attacker will get the session cookie through their logs!
Simples e um pouco estranho, né? Pra deixar mais fácil, vamos seguir com um exemplo de lab.Simple and a little weird, right? To make it easier, we'll follow with an example lab.
LabLab
Ao acessar o app.localhost.io, a gente recebe um cookie com a flag HttpOnly e domain=.localhost.io:When accessing app.localhost.io we receive a cookie with the HttpOnly flag and domain=.localhost.io:
HttpOnly e domain=.localhost.io.Session cookie issued with HttpOnly and domain=.localhost.io.Se a gente tentar pegar esse cookie via XSS, nem vê ele, por causa do HttpOnly:If we try to get that cookie through an XSS, we won't even see it due to HttpOnly:
HttpOnly o esconde de document.cookie.The XSS can't see the cookie: HttpOnly hides it from document.cookie.Porém, se a gente usa um SSRF como descrito acima, nossos cookies são enviados pro servidor de destino.However, if we use an SSRF as described above, our cookies are sent to the destination server.
Se a gente redireciona a request pro nosso servidor, dá pra ver as requests e pegar os cookies da vítima:If we redirect the request to our server, we can view the requests and get the victim's cookies:
ConclusãoConclusion
Eu poderia deixar esse SSRF de lado por não conseguir acessar o que eu queria ver. Mas quando a gente para de seguir uma lista de pensamentos, consegue pensar de outro jeito.I could let this SSRF go because I couldn't access what I wanted to see. But when we stop following a list of thoughts, we can think differently.
O conceito de hacking é muito falado: "pense fora da caixa". Só que a gente para de pensar numa caixinha pequena e passa a pensar em caixas maiores. A verdade é: não caia em caixa nenhuma, pense acima dos limites impostos — a beleza pode estar do outro lado das bordas.The concept of hacking gets talked about a lot: "think outside of the box." But we go from thinking inside a small box to thinking in bigger boxes. The truth is: don't fall into any box, think beyond the limits that were planted — the beauty can be on the other side of the edges.
ReferênciasReferences
- OWASP — Server Side Request Forgery.OWASP — Server Side Request Forgery. https://owasp.org/www-community/attacks/Server_Side_Request_Forgery
- MDN — Cookies HTTP (flag HttpOnly).MDN — HTTP Cookies (HttpOnly flag). https://developer.mozilla.org/docs/Web/HTTP/Cookies
- MDN — Usando a Fetch API (request com credenciais).MDN — Using the Fetch API (request with credentials). https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#sending_a_request_with_credentials_included
- MDN — Atributo SameSite do Set-Cookie.MDN — Set-Cookie SameSite attribute. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
- Bug Bounty Reports Explained (@gregxsunday) — SSRF + Phishing.Bug Bounty Reports Explained (@gregxsunday) — SSRF + Phishing. https://www.youtube.com/watch?v=z1FpSFG2KpY