Skills Agentes

Filesystem Security

Úsalo al leer, escribir, incluir o borrar archivos con rutas derivadas de entrada de usuario. Previene path traversal, inclusión local de archivos y borrado arbitrario de archivos.

Oficial

Reemplaza a: unlink() directo, file_put_contents() sin WP_Filesystem, basename() como única protección contra traversal

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

103 tok en reposo

Paquete
3 archivos

13 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill filesystem-security --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Valida y confina rutas de archivo construidas con entrada de usuario antes de leer, incluir, escribir o borrar
  • Aplica validate_file, realpath y confinamiento a un directorio base permitido
  • Sustituye include/require/unlink directos por allowlists, WP_Filesystem y wp_delete_file()

Úsalo cuando

  • Construyes una ruta de archivo a partir de $_GET/$_POST/$_REQUEST
  • Usas include, require, readfile, file_get_contents o unlink con una ruta dinámica
  • Sirves descargas, exportaciones o logs según un parámetro de la petición
  • Usas WP_Filesystem para escrituras, borrados o creación de directorios

No lo uses cuando

    Qué lo activa

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

    • “Revisa si mi función de descarga de archivos es vulnerable a path traversal”
    • “Quiero borrar archivos subidos por el usuario de forma segura en WordPress”
    • “Ayúdame a securizar este include que usa $_GET['page']”

    SKILL.md

    En inglés

    Filesystem security

    When to use this skill

    Use this skill whenever code touches the filesystem with paths derived from input:

    • Building a file path from $_GET / $_POST / $_REQUEST.
    • include, require, readfile, file_get_contents, or unlink of a dynamic file.
    • Serving downloads, exports, or logs based on a request parameter.
    • Deleting files selected by the user.
    • Using WP_Filesystem for writes, deletes, or directory creation.

    Path traversal and local file inclusion are high-impact WordPress vulnerabilities — ../../wp-config.php or a malicious uploaded .php can expose secrets or achieve RCE.

    Related: see the file-upload-security skill for $_FILES handling and the object-injection-deserialization skill for uploaded data formats.

    Core principles (and why they matter)

    1. Never include / require a user-controlled path. That is remote/local code execution. Keep templates and includes hardcoded.
    2. Constrain every file operation to a known base directory. Resolve with realpath() and assert the result starts with the allowed base path.
    3. validate_file() catches traversal, drive letters, and : characters. A non-zero return value means the path is suspect.
    4. Use sanitize_file_name() and wp_normalize_path(). Normalize separators and strip dangerous characters before building paths.
    5. Use WordPress deletion helpers. wp_delete_file() and wp_delete_file_from_directory() are safer than raw unlink().
    6. Use WP_Filesystem for writes. It handles permissions, credentials, and stream wrappers consistently across hosts.

    Step-by-step implementation

    1. Reject any request that wants to include/require a file based on input; use a hardcoded allowlist of template files instead.
    2. For read/delete handlers:
      • Verify nonce + capability.
      • Sanitize the filename with sanitize_file_name().
      • Optionally run validate_file().
      • Build the target path under a known base directory.
      • Resolve with realpath() and confirm it stays under the base.
    3. For writes/deletes, prefer WP_Filesystem with request_filesystem_credentials().
    4. Never expose the full server path in errors or URLs.

    Supporting references

    Reference Load when
    Filesystem security checklist Before final verification of the filesystem security controls.
    Secure filesystem operations Implementing confined file reads and deletion, and writes through WP_Filesystem.

    Common AI mistakes / anti-patterns

    Mistake 1 — include $_GET['page']

    // ❌ Insecure: local/remote code execution.
    include 'templates/' . $_GET['page'] . '.php';
    
    // ✅ Secure: hardcoded allowlist of template files.
    $allowed = array( 'dashboard', 'settings', 'logs' );
    $page    = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : 'dashboard';
    if ( ! in_array( $page, $allowed, true ) ) {
        wp_die( esc_html__( 'Invalid page.', 'my-plugin' ), 400 );
    }
    include __DIR__ . '/templates/' . $page . '.php';
    

    Mistake 2 — unlink() of a user-named file

    // ❌ Insecure: arbitrary file deletion via traversal.
    unlink( WP_CONTENT_DIR . '/exports/' . $_POST['file'] );
    
    // ✅ Secure: sanitize, resolve, and confine to the base directory.
    $base    = realpath( WP_CONTENT_DIR . '/exports' );
    $request = sanitize_file_name( wp_unslash( $_POST['file'] ?? '' ) );
    $target  = realpath( $base . '/' . $request );
    
    if ( false === $target || strpos( $target, $base . DIRECTORY_SEPARATOR ) !== 0 ) {
        wp_die( esc_html__( 'Invalid file.', 'my-plugin' ), 400 );
    }
    
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( esc_html__( 'Forbidden.', 'my-plugin' ), 403 );
    }
    
    wp_delete_file( $target );
    

    Mistake 3 — readfile() without base-directory containment

    // ❌ Insecure: ../../wp-config.php is reachable.
    readfile( '/var/www/uploads/' . $_GET['file'] );
    
    // ✅ Secure: resolve and confine.
    $base    = realpath( wp_upload_dir()['basedir'] );
    $request = sanitize_file_name( wp_unslash( $_GET['file'] ?? '' ) );
    $target  = realpath( $base . '/' . $request );
    
    if ( false === $target || strpos( $target, $base . DIRECTORY_SEPARATOR ) !== 0 ) {
        wp_die( esc_html__( 'Invalid file.', 'my-plugin' ), 400 );
    }
    
    readfile( $target );
    

    Mistake 4 — Trusting basename() alone

    // ❌ Insecure: basename does not prevent traversal to siblings.
    $file = basename( $_GET['file'] );
    readfile( '/var/www/uploads/' . $file );
    
    // ✅ Secure: basename plus realpath containment.
    $base    = realpath( '/var/www/uploads' );
    $file    = basename( sanitize_file_name( wp_unslash( $_GET['file'] ?? '' ) ) );
    $target  = realpath( $base . '/' . $file );
    if ( false === $target || strpos( $target, $base . DIRECTORY_SEPARATOR ) !== 0 ) {
        wp_die( esc_html__( 'Invalid file.', 'my-plugin' ), 400 );
    }
    readfile( $target );
    

    Mistake 5 — Writing files with raw PHP functions

    // ❌ Insecure: no permission/credential handling, may fail on restrictive hosts.
    file_put_contents( $path, $data );
    
    // ✅ Secure: use WP_Filesystem after requesting credentials.
    function my_plugin_write_file( $path, $data ) {
        global $wp_filesystem;
    
        if ( ! function_exists( 'request_filesystem_credentials' ) ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
    
        $url   = admin_url( 'admin-post.php?action=my_plugin_save' );
        $creds = request_filesystem_credentials( $url );
        if ( false === $creds || ! WP_Filesystem( $creds ) ) {
            return new WP_Error( 'filesystem', __( 'Could not initialize filesystem.', 'my-plugin' ) );
        }
    
        return $wp_filesystem->put_contents( $path, $data, FS_CHMOD_FILE );
    }
    

    Correct code examples

    A complete safe file download/delete helper using base-directory containment is in references/secure-filesystem-operations.php.

    Checklist

    • No include / require uses user input; templates are selected from a hardcoded allowlist.
    • File paths are built under a known base directory.
    • realpath() resolves the final path and containment is verified.
    • Filenames pass through sanitize_file_name() and wp_normalize_path().
    • validate_file() returns 0 for paths that include user input.
    • File delete operations use wp_delete_file() or wp_delete_file_from_directory().
    • File writes use WP_Filesystem with request_filesystem_credentials().
    • State-changing handlers verify nonce + capability first.
    • Full server paths are not exposed in errors or URLs.

    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