Recursos · 72

Prevención de SSRF en importaciones

Importar una URL puede dar acceso involuntario a recursos internos.

Actualizado · 7 min

Pasillo seguro de servidores y redes sin personal Ilustración editorial generada con IA

Lo que esta guía ayuda a lograr

  • Definir destinos permitidos
  • Comprobar cada conexión
  • Probar sin servicios sensibles

Comprobación rápida

  • Valide destinos y redirecciones; pruebe bloqueos de red en un entorno autorizado y aislado.
  • Comprobar únicamente la URL inicial deja rutas de evasión.

Método paso a paso

  1. 1

    Definir destinos permitidos

    Decida qué orígenes necesita el importador y qué puertos y protocolos admite. Analice la URL con una biblioteca; una coincidencia de texto en el nombre no confirma el destino real.

    Mantenga la lista de destinos y excepciones justificadas.

  2. 2

    Comprobar cada conexión

    Compruebe las direcciones resueltas y cada salto de redirección. Una URL pública que termina en una dirección privada debe rechazarse antes de conectar; limite también tiempo y tamaño de respuesta.

    Conserve el destino inicial, los saltos y la decisión.

  3. 3

    Probar sin servicios sensibles

    Use un servidor de pruebas para redirecciones, respuestas lentas y archivos demasiado grandes. Observe que un destino rechazado no recibe conexión, sin consultar metadatos ni redes privadas reales.

    Guarde una matriz de rechazos y límites observados.

Caso de aceptación reproducible

Ejemplo ficticio: estos datos no describen clientes ni resultados observados.

Ver datos del caso
{
    "initial_host": "public.example",
    "redirect_host": "internal.example",
    "resolved_ip": "127.0.0.1",
    "network": "isolated-test"
}

Decisión esperada

La redirección llega a loopback. Bloquee esa ruta en el entorno de prueba aislado. Comprobar el nombre inicial no cubre el destino tras redirección. En el entorno aislado, desactivar el seguimiento automático y verificar que ninguna conexión alcance el bucle local. Esperar un rechazo trazable, sin recuperar contenido interno para demostrar el bloqueo.

Procedimiento de verificación

  1. Liste destinos y redes de importación permitidos.
  2. Pruebe redirección a loopback en aislamiento.
  3. Conserve dirección resuelta y bloqueo observado.

OWASP — Server Side Request Forgery Prevention

Ejemplo trabajado ficticio

Situación ilustrativa

Valide destinos y redirecciones; pruebe bloqueos de red en un entorno autorizado y aislado.

Decisión y pruebas esperadas

No. La resolución y las redirecciones pueden cambiar el destino; pruebe la cadena completa y las restricciones de salida de red.

Indicadores de gestión

IndicadorQué midePrimera acción
Conexiones no permitidasConexiones realizadas hacia destinos rechazadosDetener el importador y revisar el control de salida
Límites excedidosRespuestas que superan el presupuesto de tiempo o bytesInterrumpir la lectura y conservar el motivo

Errores comunes

  • Comprobar únicamente la URL inicial deja rutas de evasión.

Preguntas frecuentes

¿Comprobar solo la primera URL es suficiente?

No. La resolución y las redirecciones pueden cambiar el destino; pruebe la cadena completa y las restricciones de salida de red.

SSRF: URL y conexiones

Las notas detalladas de esta edición están disponibles en inglés.

SSRF: read the URL, then control the connection

Server-Side Request Forgery (SSRF) occurs when an application is induced to send a server request to a destination it should not reach. A report importer, link preview or AI agent tool may have network access unavailable to its user. The control must cover the destination actually reached, beyond the displayed string.

Fictional offline exercise: the 12 strings below are processed only by the maintenance Node runtime’s WHATWG URL parser. No DNS lookup or connection is performed. The .example domains are teaching fixtures; 2001:db8::10 belongs to RFC 3849’s IPv6 documentation prefix. These results are not a production SSRF validator.

The exercise’s local contract

The fictional connector accepts only an absolute HTTPS URL, without credentials, with hostname exactly reports.partner.example, effective port 443 and a normalized path starting with /reports/. Comparison uses parsed fields. This contract rejects a trailing dot and assumes no DNS equivalence. It does not cover query parameters, their interpretation by the remote service or business authorization.

For a known service, prefer a report identifier and reconstruct the URL on the server from a controlled origin and path. This exercise explains user-supplied URL pitfalls; it does not recommend exposing arbitrary URLs. Access to the whole Web needs a separate egress architecture and cannot be secured by copying this small allowlist.

Four controls, four pieces of evidence
Four controls, four pieces of evidence Four separate controls: contract and parser, resolution and connection, each redirect, and response limits. Passing the first does not validate the others. 1 · Contract and parser Origin, port, path and credentials 2 · Resolution and connection Validated address actually used 3 · Each redirect New target, same destination policy 4 · Response and resources Timeouts, size and expected type A parseable URL is not network authorization.
  1. 1 · Contract and parser — Origin, port, path and credentials
  2. 2 · Resolution and connection — Validated address actually used
  3. 3 · Each redirect — New target, same destination policy
  4. 4 · Response and resources — Timeouts, size and expected type

12 fictional URLs: observed result and limits

Each disclosure shows the original string, computed fields and the decision of the local contract alone. “Continue to resolution” means network checks remain outstanding. A hostname matching the contract is neither resolved nor declared safe.

U01 · Expected name, unknown network

Original string
https://reports.partner.example/reports/daily.json

Serialized URL
https://reports.partner.example/reports/daily.json
Scheme
https:
Hostname
reports.partner.example
Effective port
443
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Continue to resolution — network unchecked

The string meets the contract, but no address is known. DNS validation, enforcement of the validated address at connection time and a network policy remain necessary.

U02 · Uppercase host and explicit HTTPS port

Original string
https://REPORTS.PARTNER.EXAMPLE:443/reports/daily.json

Serialized URL
https://reports.partner.example/reports/daily.json
Scheme
https:
Hostname
reports.partner.example
Effective port
443
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Continue to resolution — network unchecked

The parser lowercases the hostname and removes the default HTTPS port from serialization. The effective port remains 443; comparing parsed fields separates presentation from destination.

U03 · The reassuring name is before @

Original string
https://reports.partner.example@untrusted.example/reports/daily.json

Serialized URL
https://reports.partner.example@untrusted.example/reports/daily.json
Scheme
https:
Hostname
untrusted.example
Effective port
443
Username
reports.partner.example
Password present
No
Normalized path
/reports/daily.json

Reject under the local contract

Contract reasons:

  • Hostname differs from the exact allowlist
  • Embedded credentials are forbidden

The parser places reports.partner.example in username. The actual hostname is untrusted.example: finding an allowed substring in the whole URL does not control its destination.

U04 · An added suffix changes the host

Original string
https://reports.partner.example.untrusted.example/reports/daily.json

Serialized URL
https://reports.partner.example.untrusted.example/reports/daily.json
Scheme
https:
Hostname
reports.partner.example.untrusted.example
Effective port
443
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Reject under the local contract

Contract reasons:

  • Hostname differs from the exact allowlist

This hostname ends in untrusted.example. Exact comparison fails even though the expected name appears at the beginning. The contract uses neither substring matching nor a permissive expression.

U05 · Same host, different port

Original string
https://reports.partner.example:8443/reports/daily.json

Serialized URL
https://reports.partner.example:8443/reports/daily.json
Scheme
https:
Hostname
reports.partner.example
Effective port
8443
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Reject under the local contract

Contract reasons:

  • Effective port is not 443

The effective port is 8443. Allowing a hostname must not open every service available on its other ports.

U06 · HTTP does not meet HTTPS

Original string
http://reports.partner.example/reports/daily.json

Serialized URL
http://reports.partner.example/reports/daily.json
Scheme
http:
Hostname
reports.partner.example
Effective port
80
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Reject under the local contract

Contract reasons:

  • Scheme is not HTTPS
  • Effective port is not 443

The HTTP scheme and default port 80 differ from the HTTPS/443 contract. Silently rewriting the string would hide the original request; keep the decision explicit.

U07 · The .. segment changes the path

Original string
https://reports.partner.example/reports/../admin/status

Serialized URL
https://reports.partner.example/admin/status
Scheme
https:
Hostname
reports.partner.example
Effective port
443
Username
Absent
Password present
No
Normalized path
/admin/status

Reject under the local contract

Contract reasons:

  • Path is outside the /reports/ prefix

The parser resolves /reports/../admin/status to /admin/status. A prefix test on the raw string would decide differently. Even after normalization, the service’s path interpretation must remain controlled.

U08 · An encoded host character is normalized

Original string
https://%72eports.partner.example/reports/daily.json

Serialized URL
https://reports.partner.example/reports/daily.json
Scheme
https:
Hostname
reports.partner.example
Effective port
443
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Continue to resolution — network unchecked

The initial %72 becomes r in the computed hostname for this special HTTPS URL. The result matches U01; this provides no evidence about DNS, TLS or business authorization.

U09 · Trailing dot: an exact contract

Original string
https://reports.partner.example./reports/daily.json

Serialized URL
https://reports.partner.example./reports/daily.json
Scheme
https:
Hostname
reports.partner.example.
Effective port
443
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Reject under the local contract

Contract reasons:

  • Hostname differs from the exact allowlist

The hostname retains its final dot in this WHATWG result. The teaching profile requires exact equality and rejects it. A production policy must document its normalization and apply it consistently.

U10 · Relative reference without a base URL

Original string
//reports.partner.example/reports/daily.json

Cannot parse an absolute URL without a base

Reject: parser failure

Without a base, new URL rejects this reference beginning with //. Adding a base elsewhere could change the result: the validator and client must use the same parsing model.

U11 · Expected host with embedded username

Original string
https://training@reports.partner.example/reports/daily.json

Serialized URL
https://training@reports.partner.example/reports/daily.json
Scheme
https:
Hostname
reports.partner.example
Effective port
443
Username
training
Password present
No
Normalized path
/reports/daily.json

Reject under the local contract

Contract reasons:

  • Embedded credentials are forbidden

The expected hostname is insufficient: username contains training. The profile forbids all embedded credentials. This fictional value is neither an account nor a secret.

U12 · Documentation IPv6 address

Original string
https://[2001:db8::10]/reports/daily.json

Serialized URL
https://[2001:db8::10]/reports/daily.json
Scheme
https:
Hostname
[2001:db8::10]
Effective port
443
Username
Absent
Password present
No
Normalized path
/reports/daily.json

Reject under the local contract

Contract reasons:

  • Hostname differs from the exact allowlist

The parser accepts bracketed IPv6 syntax, but the contract allows no IP literal. This prefix is reserved for documentation and must not be described as an operational Internet destination.

From the checked name to the actual destination

From the checked name to the actual destination
Fictional situationMissing evidence or changeExpected decision
N01 · Repeated lookupThe application validates one answer; the client resolves again and receives an internal address.Block the unchecked second lookup. Connect only to an address validated against the destination policy.
N02 · 302 responseLocation names a different host, port or path.Disable automatic redirect following. If controlled redirects are a product requirement, parse and validate every new target before connecting.
N03 · Egress proxyThe proxy resolves the name and chooses the destination; its rules are unknown to the application.Do not claim a verified destination. Document enforcement and evidence at the component that actually establishes the connection.
N04 · Failure fallbackA new A/AAAA address, retry or fallback is attempted.Apply the same policy to every address and attempt; no fallback path may bypass enforcement.
N05 · Excessive responseThe allowed destination returns a large stream or unexpected content.Enforce client timeouts and size limits, check the expected type and handle content separately. No universal threshold is invented here.

Binding a connection to the validated address does not mean disabling TLS: preserve the original hostname for HTTP Host, SNI and certificate verification. The component opening the connection must enforce the binding; an earlier DNS observation does not prove it. Network rules complement application checks, including local, private, loopback and link-local destinations in both IPv4 and IPv6.

Cloud metadata: a separate control

In EC2, “token required” enforces IMDSv2; “token optional” permits IMDSv1 or IMDSv2. Enabling the IPv6 endpoint is an explicit option. Check these settings on the relevant instances: merely naming IMDSv2 in documentation does not prove their configuration. Protecting metadata replaces neither egress isolation nor controls on other internal services.

Six records for an SSRF acceptance review

  • The business need and the services, ports and operations actually required.
  • Parser and HTTP client versions, with expected negative-case results.
  • The IPv4/IPv6 address policy and where it is enforced before connection.
  • Evidence linking the validated destination to the connection, including proxies, retries and fallback.
  • The redirect decision and response bounds, tested in an authorized environment.
  • Minimized logs: decision, necessary target information and correlation, without copying passwords, tokens or sensitive parameters.

The 12 cases, four controls and six records are a local editorial method, not OWASP certification. The parser supplies fields; the sources describe risks and controls. “Reject” and “continue” labels do not predict the behavior of your HTTP stack.

Primary sources and scope

Sources reviewed on

Archivos: cuarentena y retirada

Las notas detalladas de esta edición están disponibles en inglés.

Retrieved content still needs checks before release

Uploading a document or fetching it by URL does not decide its availability. Originals and derivatives need to retain version, checks and access state through every read.

  • Isolate received files before processing and release.
  • Reject results targeting an older content version or control decision.
  • Check permissions and withdrawal for previews and originals alike.

View the three journeys and late task results →

Sources reviewed on · OWASP · File Upload Cheat Sheet · OWASP · Authorization Cheat Sheet · WHATWG · HTML input accept · PostgreSQL 18 · Transaction isolation

Referencias oficiales

Las referencias respaldan el método. Adapte los controles a su contexto; no constituyen certificación. Los títulos de referencia originales y los documentos fuente pueden estar en otro idioma.

Referencias consultadas el .