Avoid CSRF, XSSI, and cross-origin information leaks.
Updated
Safe and secure
¿Por qué debería preocuparse por aislar sus recursos Web?
Many web applications are vulnerable to cross-origin attacks such as cross-site request spoofing (CSRF), cross-site scripting (XSSI), time attacks, cross-origin information leaks or channel lateral de ejecución especulativa (Spectrum) attacks.
Get metadata The headers de solicitud le permiten implementar un sólido mecanismo de defensa en profundidad, una política de aislamiento de recursos, para proteger su aplicación contra estos ataques comunes de origen cruzado.
Es común que los recursos expuestos por una determinada aplicación web solo los cargue la propia aplicación y no otros sitios web. En tales casos, la implementación de una política de aislamiento de recursos basada en los encabezados de solicitud de obtención de metadata requiere poco esfuerzo y, al mismo tiempo, protege la aplicación de ataques entre sitios.
Compatibilidad del browser
Los encabezados de solicitud de obtención de metadatos se admiten a partir de Chrome 76 y en otros browsers basados en Chromium, y están en desarrollo en Firefox. Ver Browser compatibility for up-to-date information on browser compatibility.
Background
Muchos ataques entre sitios son posibles porque la web está abierta de forma predeterminada y su server de aplicaciones no puede protegerse fácilmente de la comunicación que se origina en aplicaciones externas. Un ataque típico de origen cruzado es la falsificación de solicitudes entre sitios (CSRF), en la que un atacante atrae a un Username a un sitio que controla y luego envía un formulario al servidor en el que el usuario está conectado. Dado que el servidor no puede saber si la solicitud se originó en otro domain (entre sitios) y el navegador adjunta automáticamente cookies a las solicitudes entre sitios, el servidor ejecutará la acción solicitada por el atacante en nombre del usuario.
Otros ataques entre sitios, como la inclusión de scripts entre sitios (XSSI) o las fugas de información de origen cruzado, son de naturaleza similar a CSRF y dependen de la carga de recursos de una aplicación de la víctima en un documento controlado por el atacante y de la filtración de información sobre las aplicaciones de la víctima. Dado que las aplicaciones no pueden distinguir fácilmente las solicitudes confiables de las no confiables, no pueden descartar el traffic malicioso entre sitios.
Aside from the resource attacks described above, window references it can also lead to cross-origin information leaks and Specter attacks. You can prevent them by setting the Cross-Origin-Opener-Policy
response header to same-origin
.
Introducing Fetch Metadata
Los encabezados de solicitud de Fetch Metadata son una nueva característica de seguridad de la plataforma web diseñada para ayudar a los servidores a defenderse contra ataques de origen cruzado. Al proporcionar información sobre el contexto de una solicitud HTTP en un conjunto de Sec-Fetch- *
headers, allow the responding server to apply security policies before processing the request. This allows developers to decide whether to accept or reject a request based on the way it was made and the context in which it will be used, allowing them to respond only to legitimate requests made by their own application.
Same origin
Requests originating from sites served by your own server (same origin) will continue to work.
Cross-site
The server may reject malicious cross-site requests due to the additional context in the HTTP request provided by Sec-Fetch- *
headers.
Sec-Fetch-Site
Sec-Fetch-Site
tells the server which site sent the request. The browser sets this value to one of the following:
same-origin
, if the request was made by your own application (eg.site.example
)same-site
, si la solicitud fue realizada por un subdomain de su sitio (p. ej.bar.site.example
)none
, si la solicitud fue causada explícitamente por la interacción de un usuario con el user agent (por ejemplo, al hacer clic en un marcador)cross-site
, if the request was submitted by another website (eg.evil.example
)
Sec-Fetch-Mode
Sec-Fetch-Mode
indicates the mode of the request. This roughly corresponds to the type of request and allows you to distinguish resource loads from navigation requests. For example, a destination of navigate
indicates a top-level navigation request while no-cors
indicates resource requests such as uploading an image.
Sec-Fetch-Dest
Sec-Fetch-Dest
submit a request destination (for example, if a script
or a img
caused the browser to request a resource).
The additional information these request headers provide is quite simple, but the additional context allows you to build powerful server-side security logic, also known as Resource Isolation Policy, with just a few lines of code.
Implement a resource isolation policy
A resource isolation policy prevents your resources from being requested by external websites. Blocking such traffic mitigates common cross-site web vulnerabilities such as CSRF, XSSI, timing attacks, and cross-origin information leaks. This policy can be enabled for all endpoints of your application and will allow all resource requests coming from your own application, as well as direct browsing (via an HTTP GET
request). Endpoints that are supposed to be loaded in a cross-site context (for example, endpoints loaded using CORS) can be excluded from this logic.
Step 1: Allow requests from browsers that do not send Fetch Metadata
Since not all browsers support fetching metadata, you must allow requests that are not set Sec-Fetch- *
headers checking for the presence of sec-fetch-site
.
All the following examples are python code.
if not req['sec-fetch-site']:
return True
Caution:
Since Fetch Metadata is only supported by modern browsers, it should be used as a defense-in-depth protection and not as your main line of defense.
Step 2: Allow requests started on the same site and in the browser
Any request that does not originate from a cross-origin context (such as evil.example
) will be allowed. In particular, these are requests that:
- It comes from your own application (for example, a request from the same origin where
site.example
requestssite.example / foo.json
will always be allowed). - It comes from your subdomains.
- They are explicitly caused by a user's interaction with the user agent (for example, direct navigation or clicking on a bookmark, etc.).
if req['sec-fetch-site'] in ('same-origin', 'same-site', 'none'):
return True
En caso de que sus subdominios no sean completamente confiables, puede hacer que la política be más estricta bloqueando las solicitudes de los subdominios eliminando el same-site
value.
Step 3: enable simple top-level iframing and navigation
To make sure your site can still be linked from other sites, you need to allow simple (HTTP GET
) top-level navigation.
if req['sec-fetch-mode'] == 'navigate' and req.method == 'GET'
and req['sec-fetch-dest'] not in ('object', 'embed'):
return True
The above logic protects your application endpoints from being used as resources by other websites, but will allow top-level navigation and embedding (for example, loading into a <iframe>). Para mejorar aún más la seguridad, puede usar los encabezados de Obtener metadatos para restringir la navegación entre sitios a solo un conjunto permitido de páginas.
Step 4: disable the endpoints that are intended to serve cross-site traffic (optional)
In some cases, your application may provide resources that must be loaded between sites. These resources must be exempted per path or per endpoint. Examples of these endpoints are:
- Endpoints Intended for Cross-Origin Access: If your application is providing endpoints that are
CORS
enabled, you must explicitly exclude them from resource isolation to ensure that cross-site requests to these endpoints are still possible. - Public resources (for example, images, styles, etc.): Any public and unauthenticated resources that must be cross-origin loadable from other sites can also be exempted.
if req.path in ('/my_CORS_endpoint', '/favicon.png'):
return True
Caution:
Before excluding parts of your application from these security restrictions, make sure they are static and do not contain sensitive user information.
Step 5: decline all other requests that are cross-site and non-browsing
Any other cross-site The request will be rejected by this Resource Isolation Policy and thus protect your application from common cross-site attacks.
By default, requests that violate your policy should be rejected with a HTTP 403
answer. But depending on your use case, you can also consider other actions, such as:
- Just logging violations. This is especially useful when testing policy for compatibility and finding endpoints that may need to be bypassed.
- Modify the request. En ciertos escenarios, considere realizar otras acciones como redirigir a su página de destino y eliminar las credenciales de autenticación (por ejemplo, cookies). Sin embargo, tenga en cuenta que esto podría debilitar las protecciones de una política basada en Obtener metadatos.
Example: El siguiente código demuestra una implementación completa de una política sólida de aislamiento de recursos en el servidor o como un software intermedio para denegar solicitudes de recursos entre sitios potencialmente maliciosos, al tiempo que permite solicitudes de navegación simples:
def allow_request(req):
if not req['sec-fetch-site']:
return True
if req['sec-fetch-site'] in ('same-origin', 'same-site', 'none'):
return True
if req['sec-fetch-mode'] == 'navigate' and req.method == 'GET'
and req['sec-fetch-dest'] not in ('object', 'embed'):
return True
if req.path in ('/my_CORS_endpoint', '/favicon.png'):
return True
return False
Implement a resource isolation policy
- Install a module like the code snippet above to record and monitor how your site behaves and make sure the restrictions don't affect legitimate traffic.
- Fix potential violations by exempting legitimate cross-origin endpoints.
- Enforce the policy by discarding requests that do not comply.
Identify and correct policy violations
It is recommended that you test your policy without side effects by first enabling it in reporting mode in your server-side code. Alternatively, you can implement this logic in middleware or a reverse proxy that logs any violations that your policy might cause when applied to production traffic.
A partir de nuestra experiencia en la implementación de una Política de aislamiento de recursos de búsqueda de metadatos en Google, la mayoría de las aplicaciones son compatibles de forma predeterminada con dicha política y rara vez requieren la exención de extremos para permitir el tráfico entre sitios.
Applying a resource isolation policy
Once you have verified that your policy does not affect legitimate production traffic, you are ready to enforce the restrictions, ensuring that other sites will not be able to request your resources and protecting your users from cross-site attacks.
Caution:
Make sure to reject invalid requests before running authentication checks or any other request processing to avoid revealing time sensitive information.
Other readings