Skills Agentes

Http Api Ssrf Prevention

Úsalo cuando un plugin o tema haga peticiones HTTP salientes con la HTTP API de WordPress y la URL dependa de datos de usuario, opciones o webhooks, para prevenir SSRF.

Oficial
Estrellas
57

en todo el repo

Actividad
50

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
3

últimos 90 días

Contexto
2k tok

102 tok en reposo

Paquete
3 archivos

11 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill http-api-ssrf-prevention --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Sustituye wp_remote_get/post por wp_safe_remote_* con validación de host y wp_http_validate_url
  • Aplica allowlist de hosts permitidos en lugar de blocklist para peticiones salientes
  • Añade comprobación de is_wp_error() y código de respuesta antes de usar los datos
  • Exige escapar el cuerpo de la respuesta HTTP antes de mostrarlo

Úsalo cuando

  • Un plugin o tema hace peticiones HTTP salientes con wp_remote_get, wp_remote_post o wp_remote_request
  • Parte de la URL procede de entrada de usuario, opciones o webhooks
  • Se construye una URL a partir de $_GET, $_POST, opciones o configuración remota

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • “Revisa este código que hace wp_remote_get con una URL de $_POST”
    • “Implementa un webhook seguro que valide la URL antes de hacer la petición”
    • “¿Cómo evito SSRF al llamar a una API externa desde mi plugin de WordPress?”

    SKILL.md

    En inglés

    HTTP API & SSRF prevention

    When to use this skill

    Use this skill whenever code makes an outbound HTTP request:

    • Fetching a user-supplied URL (webhook, import, avatar, feed, oEmbed-like lookup).
    • Calling an external API from a setting, form, or scheduled job.
    • Using wp_remote_get(), wp_remote_post(), or wp_remote_request().
    • Building a URL from $_GET, $_POST, options, or remote configuration.

    If any part of the URL is influenced by users or remote state, treat it as an SSRF sink. wp_safe_remote_*() runs wp_http_validate_url() on the URL and every redirect, blocking private/loopback ranges by default.

    Related: see the rest-api-security skill for inbound REST endpoints and the input-sanitization-validation skill for general URL sanitization.

    Core principles (and why they matter)

    1. wp_safe_remote_*() for untrusted URLs. wp_safe_remote_get() and wp_safe_remote_post() set reject_unsafe_urls, which validates the URL and redirects against private/loopback ranges.
    2. Allowlist hosts, don't blocklist. A blocklist will miss metadata.google.internal, localhost aliases, IP-encoding tricks, and redirect chains. Allow only the hosts and ports you intend to call.
    3. Validate before the request. Run wp_http_validate_url() or compare the parsed host against an allowlist before calling the HTTP API.
    4. Check is_wp_error() and the response code. A failed request can leak internal error messages or be confused with valid data.
    5. Escape fetched data before output. The response body is untrusted input; escape or sanitize it before rendering.
    6. Don't follow redirects blindly. wp_safe_remote_*() validates redirect targets, but if you manually chase redirects you may re-enter internal space.

    Step-by-step implementation

    1. Determine whether the URL is trusted (hardcoded, signed) or untrusted (user input).
    2. For untrusted URLs:
      • Parse the host and compare it to an explicit allowlist.
      • Run wp_http_validate_url() as an additional guard.
      • Use wp_safe_remote_get() / wp_safe_remote_post().
    3. For trusted URLs, wp_remote_*() is acceptable but still validate the shape.
    4. Handle is_wp_error() and check the response code with wp_remote_retrieve_response_code().
    5. Sanitize or escape the response body before use/output.
    6. Log failures without exposing secrets or internal network details.

    Supporting references

    Reference Load when
    HTTP API & SSRF prevention checklist Before final verification of the http api & ssrf prevention controls.
    Secure outbound HTTP request Implementing allowlisted webhook delivery with safe HTTP requests and response handling.

    Common AI mistakes / anti-patterns

    Mistake 1 — wp_remote_get() on user input with no validation

    // ❌ Insecure: SSRF to internal services, metadata endpoints, or localhost.
    $response = wp_remote_get( $_POST['url'] );
    
    // ✅ Secure: allowlist host, validate URL, use safe remote, check errors.
    $url = isset( $_POST['url'] ) ? esc_url_raw( wp_unslash( $_POST['url'] ) ) : '';
    $allowed_hosts = array( 'api.example.com', 'hooks.example.com' );
    $host          = wp_parse_url( $url, PHP_URL_HOST );
    
    if ( ! $host || ! in_array( strtolower( $host ), $allowed_hosts, true ) ) {
        wp_die( esc_html__( 'Invalid URL.', 'my-plugin' ), 400 );
    }
    
    if ( ! wp_http_validate_url( $url ) ) {
        wp_die( esc_html__( 'URL is not safe.', 'my-plugin' ), 400 );
    }
    
    $response = wp_safe_remote_get( $url );
    if ( is_wp_error( $response ) ) {
        wp_die( esc_html__( 'Request failed.', 'my-plugin' ), 502 );
    }
    $code = wp_remote_retrieve_response_code( $response );
    if ( 200 !== $code ) {
        wp_die( esc_html__( 'Unexpected response.', 'my-plugin' ), 502 );
    }
    $body = wp_remote_retrieve_body( $response );
    

    Mistake 2 — Trusting the URL scheme without checking

    // ❌ Insecure: file://, ftp://, gopher://, or php:// wrappers may be reachable.
    $response = wp_remote_get( $_POST['url'] );
    
    // ✅ Secure: wp_http_validate_url() allows only http/https.
    if ( ! wp_http_validate_url( $url ) ) {
        wp_die( esc_html__( 'Only HTTP/HTTPS URLs are allowed.', 'my-plugin' ), 400 );
    }
    

    Mistake 3 — Reflecting fetched body unescaped

    // ❌ Insecure: fetched HTML/JSON may contain XSS payloads.
    echo wp_remote_retrieve_body( $response );
    
    // ✅ Secure: treat the body as untrusted and escape for the output context.
    $body = wp_remote_retrieve_body( $response );
    echo '<pre>' . esc_html( $body ) . '</pre>';
    

    Mistake 4 — Allowing internal IPs through a host allowlist bypass

    // ❌ Insecure: resolves to 127.0.0.1 or metadata service.
    $allowed_hosts = array( 'localhost', '169.254.169.254' );
    
    // ✅ Secure: do not allow localhost or link-local ranges; rely on wp_http_validate_url.
    $allowed_hosts = array( 'api.example.com' );
    

    Mistake 5 — Ignoring is_wp_error()

    // ❌ Insecure: $response['body'] may not exist; errors may leak internals.
    $body = $response['body'];
    
    // ✅ Secure: branch on is_wp_error() before reading the response.
    if ( is_wp_error( $response ) ) {
        error_log( 'HTTP request failed: ' . $response->get_error_message() );
        return false;
    }
    $body = wp_remote_retrieve_body( $response );
    

    Correct code examples

    A complete, copy-paste-ready webhook fetch handler with host allowlist + safe remote + response validation is in references/secure-http-request.php.

    Checklist

    • Untrusted URLs use wp_safe_remote_get() / wp_safe_remote_post().
    • The host is allowlisted before the request is made.
    • wp_http_validate_url() is used as an additional guard.
    • Only http/https schemes are accepted.
    • is_wp_error() is checked before reading the response.
    • The response code is validated.
    • Fetched data is sanitized/escaped before output or storage.
    • Failures are logged without exposing secrets or internal network details.
    • Redirect chains are validated (safe remote does this automatically).

    Official references

    Reproducido de wpultimatesecurity/WordPress-Security-Skills bajo licencia MIT. Leer esta página en markdown.

    Archivos

    3 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Detalles

    Categoría
    Seguridad
    Licencia
    MIT
    Recursos incluidos
    referencias
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de wpultimatesecurity/WordPress-Security-Skills

    Este repo incluye 27 skills. Si instalas uno, normalmente ya tienes los demás. Ver el pack WordPress-Security-Skills entero y su comando de instalación

    Úsalo al auditar o revisar código de un plugin o tema WordPress existente, triar un informe de vulnerabilidad o endurecer código heredado, con una metodología sistemática.

    Costo de contexto al activarse
    3.8k tok
    Tamaño del paquete
    9 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.

    Costo de contexto al activarse
    4.9k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando un plugin o tema empaquete una librería de terceros, cargue un asset desde un CDN, ejecute código remoto, use Composer o prepare el zip distribuible.

    Costo de contexto al activarse
    4.5k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al iniciar un plugin o tema de WordPress, al añadir hooks o funciones que manejan peticiones, opciones o salida; establece la línea base segura por defecto.

    Costo de contexto al activarse
    2k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al construir bloques dinámicos o funciones del editor de bloques: render_callback, ServerSideRender, datos REST o register_rest_field, para evitar XSS almacenado y control de acceso roto.

    Costo de contexto al activarse
    2.6k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al escribir código para WordPress multisite: switch_to_blog, páginas de red, get_sites o capacidades que difieren entre sitio y red. Evita fugas de datos entre sitios y escaladas de privilegios de red.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Skills relacionados

    Úsalo al construir o revisar funciones de plugin o tema de WordPress que llaman a un LLM: chatbots, generación de contenido, RAG, agentes con herramientas, Abilities API o exposición MCP.

    Costo de contexto al activarse
    3.6k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al registrar o manejar AJAX en WordPress vía admin-ajax.php: verifica el nonce, comprueba permisos, sanitiza cada campo y responde con wp_send_json_*, evitando CSRF e inyecciones.

    Costo de contexto al activarse
    3.1k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.

    Costo de contexto al activarse
    4.9k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad