Skills Agentes

Object Injection Deserialization

Úsalo cuando el código llame a unserialize, maybe_unserialize o guarde PHP serializado desde input no confiable; prioriza JSON y evita la inyección de objetos y RCE por cadenas POP.

Oficial

Reemplaza a: unserialize() / maybe_unserialize() sobre datos no confiables

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
1.7k tok

88 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 object-injection-deserialization --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Detecta llamadas a unserialize, maybe_unserialize o is_serialized sobre datos no confiables
  • Sustituye unserialize por json_encode/json_decode en intercambios de datos estructurados
  • Añade ['allowed_classes' => false] cuando unserialize es inevitable
  • Revisa que options, meta y transients no guarden blobs serializados de origen no confiable

Úsalo cuando

  • Código llama a unserialize(), maybe_unserialize() o is_serialized() sobre input de usuario
  • Se guardan arrays/objetos serializados en options, post meta, user meta o transients
  • Se importan datos desde ficheros, feeds o subidas que pueden contener PHP serializado
  • Se serializan objetos para cachear o migrar datos

No lo uses cuando

    Qué lo activa

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

    • “Revisa si uso unserialize() de forma insegura en este plugin”
    • “Quiero importar un fichero de configuración, ¿es seguro usar maybe_unserialize?”
    • “Audita el guardado de post meta con datos de $_POST”

    SKILL.md

    En inglés

    Object injection & deserialization security

    When to use this skill

    Use this skill whenever code touches PHP serialization:

    • Calling unserialize(), maybe_unserialize(), or is_serialized() on user input.
    • Storing serialized arrays/objects in options, post meta, user meta, or transients.
    • Importing data from files, feeds, or uploads that may contain serialized PHP.
    • Migrating or caching objects by serializing them.

    PHP object injection lets an attacker instantiate arbitrary objects and trigger magic methods (__wakeup(), __destruct(), __toString()) that form POP (property-oriented programming) chains, often leading to remote code execution.

    Core principles (and why they matter)

    1. Never unserialize() untrusted input. Anything from $_POST, $_GET, files, remote APIs, or cookies is untrusted.
    2. Prefer JSON for interchange. wp_json_encode() / json_decode() only produces arrays/stdClass and cannot instantiate PHP classes, breaking object-injection chains.
    3. maybe_unserialize() is still unserialize(). It just checks is_serialized() first. Do not use it on attacker-controlled data.
    4. If forced to unserialize, disable classes. Pass array( 'allowed_classes' => false ) (PHP 7.0+) to unserialize() so no objects are instantiated.
    5. Do not trust is_serialized() as a safety check. It only tells you the format; it does not make the payload safe.
    6. Keep serialized objects out of user-facing storage. Options and meta that users can influence should store JSON or scalar values.

    Step-by-step implementation

    1. Identify every unserialize(), maybe_unserialize(), and is_serialized() call.
    2. Determine whether the data is attacker-controllable. If yes, replace with JSON.
    3. For trusted internal serialization, use allowed_classes => false or a narrow allowlist of classes.
    4. Validate the decoded shape (expected keys/types) before use.
    5. Escape any values from the decoded data before output.

    Supporting references

    Reference Load when
    Object injection & deserialization checklist Before final verification of the object injection & deserialization controls.
    Secure deserialization and import Implementing validated JSON imports and disabling class instantiation where trusted deserialization is unavoidable.

    Common AI mistakes / anti-patterns

    Mistake 1 — unserialize() on $_POST

    // ❌ Insecure: arbitrary object instantiation.
    $data = unserialize( $_POST['config'] );
    
    // ✅ Secure: use JSON for user-supplied structured data.
    $raw  = isset( $_POST['config'] ) ? wp_unslash( $_POST['config'] ) : '';
    $data = json_decode( $raw, true );
    if ( ! is_array( $data ) ) {
        wp_die( esc_html__( 'Invalid configuration.', 'my-plugin' ), 400 );
    }
    $api_key = isset( $data['api_key'] ) ? sanitize_text_field( $data['api_key'] ) : '';
    

    Mistake 2 — Treating maybe_unserialize() as safe

    // ❌ Insecure: maybe_unserialize is unserialize with a format check.
    $config = maybe_unserialize( file_get_contents( $uploaded_file ) );
    
    // ✅ Secure: read and validate JSON instead.
    $raw      = file_get_contents( $uploaded_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
    $decoding = json_decode( $raw, true );
    if ( null === $decoding && json_last_error() !== JSON_ERROR_NONE ) {
        wp_die( esc_html__( 'Invalid import file.', 'my-plugin' ), 400 );
    }
    

    Mistake 3 — Trusting is_serialized()

    // ❌ Insecure: is_serialized only describes the format.
    if ( is_serialized( $value ) ) {
        $value = unserialize( $value ); // still dangerous
    }
    
    // ✅ Secure: if you must accept serialized data, disable class instantiation.
    if ( is_serialized( $value ) ) {
        $value = @unserialize( $value, array( 'allowed_classes' => false ) );
    }
    

    Mistake 4 — Storing user-supplied serialized blobs

    // ❌ Insecure: stores attacker-controlled serialized payload in meta.
    update_post_meta( $post_id, '_my_plugin_data', $_POST['data'] );
    
    // ✅ Secure: store JSON; validate and sanitize on read.
    $raw  = isset( $_POST['data'] ) ? wp_unslash( $_POST['data'] ) : '';
    $data = json_decode( $raw, true );
    if ( is_array( $data ) ) {
        update_post_meta( $post_id, '_my_plugin_data', wp_json_encode( $data ) );
    }
    

    Mistake 5 — Serializing objects for cache/transients without class restrictions

    // ❌ Risky: transient value can instantiate arbitrary objects on read.
    set_transient( 'my_plugin_state', serialize( $object ) );
    
    // ✅ Safer: store JSON or, if objects are required, a known shape with allowed_classes false.
    set_transient( 'my_plugin_state', wp_json_encode( $object ) );
    

    Correct code examples

    A safe importer that rejects serialized PHP and parses JSON is in references/secure-deserialization.php.

    Checklist

    • No unserialize() / maybe_unserialize() runs on user input, uploads, or remote data.
    • JSON is used for structured data interchange.
    • Where unserialize() is unavoidable, allowed_classes => false is set.
    • is_serialized() is not treated as a security check.
    • Serialized blobs are not stored from user-controlled sources.
    • Decoded JSON is validated for expected shape before use.
    • Values from decoded data are sanitized/escaped before output.

    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