diff --git a/src/network-services-pentesting/pentesting-web/special-http-headers.md b/src/network-services-pentesting/pentesting-web/special-http-headers.md index aea766edf..ed2c71439 100644 --- a/src/network-services-pentesting/pentesting-web/special-http-headers.md +++ b/src/network-services-pentesting/pentesting-web/special-http-headers.md @@ -26,7 +26,7 @@ Rewrite **IP source**: - `True-Client-IP: 127.0.0.1` - `Cluster-Client-IP: 127.0.0.1` - `Via: 1.0 fred, 1.1 127.0.0.1` -- `Connection: close, X-Forwarded-For` (Verifique os cabeçalhos hop-by-hop) +- `Connection: close, X-Forwarded-For` (Check hop-by-hop headers) Rewrite **location**: @@ -35,10 +35,11 @@ Rewrite **location**: ## Hop-by-Hop headers -Um cabeçalho hop-by-hop é um cabeçalho que foi projetado para ser processado e consumido pelo proxy que está lidando com a solicitação, ao contrário de um cabeçalho de ponta a ponta. +A hop-by-hop header is a header which is designed to be processed and consumed by the proxy currently handling the request, as opposed to an end-to-end header. - `Connection: close, X-Forwarded-For` + {{#ref}} ../../pentesting-web/abusing-hop-by-hop-headers.md {{#endref}} @@ -48,58 +49,78 @@ Um cabeçalho hop-by-hop é um cabeçalho que foi projetado para ser processado - `Content-Length: 30` - `Transfer-Encoding: chunked` + {{#ref}} ../../pentesting-web/http-request-smuggling/ {{#endref}} +## The Expect header + +It's posible for the client to send the header `Expect: 100-continue` and then the server could respond with `HTTP/1.1 100 Continue` to allow the client to continue sending the body of the request. However, some proxies don't really llike this header. + +Interesting results of `Expect: 100-continue`: +- Sending a HEAD request with a body the server didn't took into account that HEAD requests don't have body and keep the connection open until it timed out. +- Another servers sent extrange data: Random data read from the socket in the response, secret keys or even it allowed to prevent the front-end from removing header values. +- It also caused a `0.CL` desync cause the backend responded with a 400 response isntead of a 100 response, but the proxy front-end was prepared to send the body of the initial request, so it sends it and the backend takes it as new request. +- Sending an `Expect: y 100-continue` variation also caused the `0.CL` desync. +- A similar error where the backend responded with a 404 generated a `CL.0` desync because the malicious request indicates a `Content-Length` so the backend sends the malicious request + the `Content-Length` bytes of the next request (of a victim), this desyncs the queue cause the backend sends the 404 request for the malicious request + the repsonse of the victim requests, but the front end thought that only 1 request was sent, so the second response is sent to a seond victim request and the the reponse of taht one is sent to the next one... + +For more info about HTTP Request Smuggling check: + +{{#ref}} +../../pentesting-web/http-request-smuggling/ +{{#endref}} + + ## Cache Headers -**Cabeçalhos de Cache do Servidor**: +**Server Cache Headers**: + +- **`X-Cache`** in the response may have the value **`miss`** when the request wasn't cached and the value **`hit`** when it is cached +- Similar behaviour in the header **`Cf-Cache-Status`** +- **`Cache-Control`** indicates if a resource is being cached and when will be the next time the resource will be cached again: `Cache-Control: public, max-age=1800` +- **`Vary`** is often used in the response to **indicate additional headers** that are treated as **part of the cache key** even if they are normally unkeyed. +- **`Age`** defines the times in seconds the object has been in the proxy cache. +- **`Server-Timing: cdn-cache; desc=HIT`** also indicates that a resource was cached -- **`X-Cache`** na resposta pode ter o valor **`miss`** quando a solicitação não foi armazenada em cache e o valor **`hit`** quando está armazenada em cache -- Comportamento semelhante no cabeçalho **`Cf-Cache-Status`** -- **`Cache-Control`** indica se um recurso está sendo armazenado em cache e quando será a próxima vez que o recurso será armazenado em cache novamente: `Cache-Control: public, max-age=1800` -- **`Vary`** é frequentemente usado na resposta para **indicar cabeçalhos adicionais** que são tratados como **parte da chave de cache**, mesmo que normalmente não sejam indexados. -- **`Age`** define o tempo em segundos que o objeto esteve no cache do proxy. -- **`Server-Timing: cdn-cache; desc=HIT`** também indica que um recurso foi armazenado em cache {{#ref}} ../../pentesting-web/cache-deception/ {{#endref}} -**Cabeçalhos de Cache Local**: +**Local Cache headers**: -- `Clear-Site-Data`: Cabeçalho para indicar o cache que deve ser removido: `Clear-Site-Data: "cache", "cookies"` -- `Expires`: Contém a data/hora em que a resposta deve expirar: `Expires: Wed, 21 Oct 2015 07:28:00 GMT` -- `Pragma: no-cache` igual a `Cache-Control: no-cache` -- `Warning`: O cabeçalho HTTP geral **`Warning`** contém informações sobre possíveis problemas com o status da mensagem. Mais de um cabeçalho `Warning` pode aparecer em uma resposta. `Warning: 110 anderson/1.3.37 "Response is stale"` +- `Clear-Site-Data`: Header to indicate the cache that should be removed: `Clear-Site-Data: "cache", "cookies"` +- `Expires`: Contains date/time when the response should expire: `Expires: Wed, 21 Oct 2015 07:28:00 GMT` +- `Pragma: no-cache` same as `Cache-Control: no-cache` +- `Warning`: The **`Warning`** general HTTP header contains information about possible problems with the status of the message. More than one `Warning` header may appear in a response. `Warning: 110 anderson/1.3.37 "Response is stale"` ## Conditionals -- Solicitações usando esses cabeçalhos: **`If-Modified-Since`** e **`If-Unmodified-Since`** serão respondidas com dados apenas se o cabeçalho de resposta **`Last-Modified`** contiver um horário diferente. -- Solicitações condicionais usando **`If-Match`** e **`If-None-Match`** usam um valor Etag para que o servidor web envie o conteúdo da resposta se os dados (Etag) mudaram. O `Etag` é retirado da resposta HTTP. -- O valor **Etag** é geralmente **calculado com base** no **conteúdo** da resposta. Por exemplo, `ETag: W/"37-eL2g8DEyqntYlaLp5XLInBWsjWI"` indica que o `Etag` é o **Sha1** de **37 bytes**. +- Requests using these headers: **`If-Modified-Since`** and **`If-Unmodified-Since`** will be responded with data only if the response header**`Last-Modified`** contains a different time. +- Conditional requests using **`If-Match`** and **`If-None-Match`** use an Etag value so the web server will send the content of the response if the data (Etag) has changed. The `Etag` is taken from the HTTP response. +- The **Etag** value is usually **calculated based** on the **content** of the response. For example, `ETag: W/"37-eL2g8DEyqntYlaLp5XLInBWsjWI"` indicates that the `Etag` is the **Sha1** of **37 bytes**. ## Range requests -- **`Accept-Ranges`**: Indica se o servidor suporta solicitações de intervalo e, se sim, em qual unidade o intervalo pode ser expresso. `Accept-Ranges: ` -- **`Range`**: Indica a parte de um documento que o servidor deve retornar. Por exemplo, `Range:80-100` retornará os bytes 80 a 100 da resposta original com um código de status 206 Partial Content. Também lembre-se de remover o cabeçalho `Accept-Encoding` da solicitação. -- Isso pode ser útil para obter uma resposta com código JavaScript refletido arbitrário que, de outra forma, poderia ser escapado. Mas para abusar disso, você precisaria injetar esses cabeçalhos na solicitação. -- **`If-Range`**: Cria uma solicitação de intervalo condicional que só é atendida se o etag ou a data fornecidos corresponderem ao recurso remoto. Usado para evitar o download de dois intervalos de versões incompatíveis do recurso. -- **`Content-Range`**: Indica onde em uma mensagem de corpo completo uma mensagem parcial pertence. +- **`Accept-Ranges`**: Indicates if the server supports range requests, and if so in which unit the range can be expressed. `Accept-Ranges: ` +- **`Range`**: Indicates the part of a document that the server should return. For emxaple, `Range:80-100` will return the bytes 80 to 100 of the original response with a status code of 206 Partial Content. Also remember to remove the `Accept-Encoding` header from the request. +- This could be useful to get a repsonse with arbitrary reflected javascript code that otherwise could be escaped. But to abuse this you would need to inject this headers in the request. +- **`If-Range`**: Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource. +- **`Content-Range`**: Indicates where in a full body message a partial message belongs. ## Message body information -- **`Content-Length`:** O tamanho do recurso, em número decimal de bytes. -- **`Content-Type`**: Indica o tipo de mídia do recurso -- **`Content-Encoding`**: Usado para especificar o algoritmo de compressão. -- **`Content-Language`**: Descreve a(s) língua(s) humana(s) destinadas ao público, permitindo que um usuário diferencie de acordo com a própria língua preferida. -- **`Content-Location`**: Indica uma localização alternativa para os dados retornados. +- **`Content-Length`:** The size of the resource, in decimal number of bytes. +- **`Content-Type`**: Indicates the media type of the resource +- **`Content-Encoding`**: Used to specify the compression algorithm. +- **`Content-Language`**: Describes the human language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. +- **`Content-Location`**: Indicates an alternate location for the returned data. -Do ponto de vista de um pentest, essas informações são geralmente "inúteis", mas se o recurso estiver **protegido** por um 401 ou 403 e você conseguir encontrar alguma **maneira** de **obter** essas **informações**, isso pode ser **interessante.**\ -Por exemplo, uma combinação de **`Range`** e **`Etag`** em uma solicitação HEAD pode vazar o conteúdo da página via solicitações HEAD: +From a pentest point of view this information is usually "useless", but if the resource is **protected** by a 401 or 403 and you can find some **way** to **get** this **info**, this could be **interesting.**\ +For example a combination of **`Range`** and **`Etag`** in a HEAD request can leak the content of the page via HEAD requests: -- Uma solicitação com o cabeçalho `Range: bytes=20-20` e com uma resposta contendo `ETag: W/"1-eoGvPlkaxxP4HqHv6T3PNhV9g3Y"` está vazando que o SHA1 do byte 20 é `ETag: eoGvPlkaxxP4HqHv6T3PNhV9g3Y` +- A request with the header `Range: bytes=20-20` and with a response containing `ETag: W/"1-eoGvPlkaxxP4HqHv6T3PNhV9g3Y"` is leaking that the SHA1 of the byte 20 is `ETag: eoGvPlkaxxP4HqHv6T3PNhV9g3Y` ## Server Info @@ -108,28 +129,29 @@ Por exemplo, uma combinação de **`Range`** e **`Etag`** em uma solicitação H ## Controls -- **`Allow`**: Este cabeçalho é usado para comunicar os métodos HTTP que um recurso pode manipular. Por exemplo, pode ser especificado como `Allow: GET, POST, HEAD`, indicando que o recurso suporta esses métodos. -- **`Expect`**: Utilizado pelo cliente para transmitir expectativas que o servidor precisa atender para que a solicitação seja processada com sucesso. Um caso de uso comum envolve o cabeçalho `Expect: 100-continue`, que sinaliza que o cliente pretende enviar um grande payload de dados. O cliente aguarda uma resposta `100 (Continue)` antes de prosseguir com a transmissão. Esse mecanismo ajuda a otimizar o uso da rede, aguardando a confirmação do servidor. +- **`Allow`**: This header is used to communicate the HTTP methods a resource can handle. For example, it might be specified as `Allow: GET, POST, HEAD`, indicating that the resource supports these methods. +- **`Expect`**: Utilized by the client to convey expectations that the server needs to meet for the request to be processed successfully. A common use case involves the `Expect: 100-continue` header, which signals that the client intends to send a large data payload. The client looks for a `100 (Continue)` response before proceeding with the transmission. This mechanism helps in optimizing network usage by awaiting server confirmation. ## Downloads -- O cabeçalho **`Content-Disposition`** nas respostas HTTP direciona se um arquivo deve ser exibido **inline** (dentro da página da web) ou tratado como um **anexo** (baixado). Por exemplo: +- The **`Content-Disposition`** header in HTTP responses directs whether a file should be displayed **inline** (within the webpage) or treated as an **attachment** (downloaded). For instance: ``` Content-Disposition: attachment; filename="filename.jpg" ``` -Isso significa que o arquivo nomeado "filename.jpg" é destinado a ser baixado e salvo. +Isso significa que o arquivo chamado "filename.jpg" destina-se a ser baixado e salvo. ## Cabeçalhos de Segurança ### Content Security Policy (CSP) + {{#ref}} ../../pentesting-web/content-security-policy-csp-bypass/ {{#endref}} -### **Tipos Confiáveis** +### **Trusted Types** -Ao impor Tipos Confiáveis através do CSP, as aplicações podem ser protegidas contra ataques DOM XSS. Tipos Confiáveis garantem que apenas objetos especificamente elaborados, em conformidade com políticas de segurança estabelecidas, possam ser usados em chamadas de API web perigosas, garantindo assim que o código JavaScript esteja seguro por padrão. +Ao aplicar Trusted Types via CSP, as aplicações podem ser protegidas contra ataques DOM XSS. Trusted Types garantem que apenas objetos especificamente criados, em conformidade com as políticas de segurança estabelecidas, possam ser usados em chamadas de APIs web perigosas, protegendo assim o código JavaScript por padrão. ```javascript // Feature detection if (window.trustedTypes && trustedTypes.createPolicy) { @@ -148,74 +170,75 @@ el.innerHTML = escaped // Results in safe assignment. ``` ### **X-Content-Type-Options** -Este cabeçalho previne a detecção de tipo MIME, uma prática que pode levar a vulnerabilidades XSS. Ele garante que os navegadores respeitem os tipos MIME especificados pelo servidor. +Este cabeçalho evita a inspeção de tipo MIME, uma prática que pode levar a vulnerabilidades XSS. Ele assegura que os navegadores respeitem os tipos MIME especificados pelo servidor. ``` X-Content-Type-Options: nosniff ``` ### **X-Frame-Options** -Para combater clickjacking, este cabeçalho restringe como documentos podem ser incorporados em ``, `