# File Upload Security > Úsalo cuando un plugin o tema de WordPress acepte subidas de archivos o procese $_FILES, para prevenir subida arbitraria de archivos y RCE con listas blancas de MIME/extensión. Fuente: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/file-upload-security Markdown: https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/file-upload-security.md Repositorio: https://github.com/wpultimatesecurity/WordPress-Security-Skills Autor: wpultimatesecurity Licencia: MIT Actualizado: hace 2 meses Coste de contexto: 95 tok instalada, 2.4k tok al activarse, 3.5k tok con todos los archivos del bundle Bundle: 3 archivos, 14 KB Permisos que pide: ninguno declarado ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill file-upload-security --agent claude-code # Cursor npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill file-upload-security --agent cursor # Codex npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill file-upload-security --agent codex # Gemini CLI npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill file-upload-security --agent gemini # Windsurf npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill file-upload-security --agent windsurf # Cline npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill file-upload-security --agent cline ``` ## Qué hace - Aplica wp_handle_upload y wp_check_filetype_and_ext con una lista blanca de MIME/extensiones en vez de manejo manual de $_FILES - Bloquea tipos ejecutables (.php, .phtml, .htaccess) en directorios de subida servidos por web - Previene path traversal resolviendo rutas con realpath() y confinándolas a un directorio base permitido - Sanitiza nombres de archivo y evita concatenar el nombre del cliente en una ruta ## Cuándo usarla - Un plugin o tema de WordPress acepta subidas de archivos o procesa $_FILES - Se guardan archivos proporcionados por el usuario (avatares, importaciones, adjuntos, CSV/JSON) - Se construye una ruta de archivo a partir de entrada del usuario (descargas, include, readfile) - Se sirven o eliminan archivos según un parámetro de la petición ## Qué la activa - "Revisa si mi formulario de subida de archivos en WordPress es seguro" - "Audita este handler de $_FILES por vulnerabilidades de subida de archivos" - "¿Es seguro este código que construye una ruta a partir de $_GET['file']?" ## Antes de instalar - Los ejemplos usan sintaxis de PHP 7.4; comprueba cada API contra las versiones de WordPress/PHP objetivo. ## Archivos - SKILL.md — 9 KB - references/checklist.md — 902 B - references/secure-file-upload.php — 3 KB ## SKILL.md Reproducido tal cual desde wpultimatesecurity/WordPress-Security-Skills bajo MIT. Esta sección es el documento original y está en inglés. # File upload security ## When to use this skill Use this skill whenever code touches user-provided files or paths: - Handling `$_FILES` from a form (front-end or admin). - Saving uploads, avatars, imports, attachments, CSV/JSON imports. - Building a filesystem path from user input (download handlers, `include`, `readfile`). - Serving or deleting files based on a request parameter. Arbitrary file upload is one of the highest-severity WordPress bugs — an uploaded `.php` in a web-served directory is remote code execution. ## Core principles (and why they matter) 1. **Use `wp_handle_upload()`, not manual `move_uploaded_file()`.** Core validates the upload, applies the site's MIME rules, sanitizes the filename, and places the file in the uploads directory with a unique name. 2. **Allowlist types; never blocklist.** Decide which extensions/MIME types you accept and reject everything else. Blocklists miss variants (`.phtml`, `.php5`, `.pht`, double extensions). 3. **Verify the real type, not the claimed one.** The browser-supplied MIME and the extension can lie. `wp_check_filetype_and_ext()` checks extension vs. actual content. 4. **Never trust the client filename for a path.** Use `sanitize_file_name()` and let core assign the final name; never concatenate `$_FILES[...]['name']` into a path. 5. **Block executables from web-served upload dirs.** Don't allow `.php`/`.phtml`/`.htaccess` uploads; harden the uploads directory (see `wp-hardening-best-practices`). 6. **Prevent path traversal.** Validate any path built from input with `realpath()` and confirm it stays within an allowed base directory; reject `..` sequences. ## Step-by-step implementation 1. Verify nonce + capability (`upload_files` or stricter) before processing. 2. Require `wp_handle_upload()` with `array( 'test_form' => false )` (or set the action). 3. Validate the result with `wp_check_filetype_and_ext()` against an explicit allowlist. 4. Reject anything not on the allowlist; surface a clear error. 5. For path operations, resolve with `realpath()` and assert the prefix matches an allowed base; never `include`/`readfile` raw input. 6. Store the returned URL/path; escape on output. ### Supporting references | Reference | Load when | | --- | --- | | [File upload security checklist](references/checklist.md) | Before final verification of the file upload security controls. | | [Secure file upload handler](references/secure-file-upload.php) | Implementing the nonce-to-capability-to-validated-upload flow and optional media-library attachment. | ## Common AI mistakes / anti-patterns ### Mistake 1 — `move_uploaded_file()` straight from `$_FILES` ```php // ❌ Insecure: no type/extension validation, attacker-controlled filename → RCE. $name = $_FILES['file']['name']; move_uploaded_file( $_FILES['file']['tmp_name'], WP_CONTENT_DIR . '/uploads/' . $name ); ``` ```php // ✅ Secure: let core validate, sanitize, and place the file. if ( ! current_user_can( 'upload_files' ) ) { wp_die( esc_html__( 'Forbidden', 'my-plugin' ), 403 ); } require_once ABSPATH . 'wp-admin/includes/file.php'; $upload = wp_handle_upload( $_FILES['file'], array( 'test_form' => false ) ); if ( isset( $upload['error'] ) ) { wp_die( esc_html( $upload['error'] ) ); } $file_url = $upload['url']; ``` ### Mistake 2 — Trusting the client-provided MIME type ```php // ❌ Insecure: $_FILES['file']['type'] is set by the browser and forgeable. if ( 'image/png' === $_FILES['file']['type'] ) { save_it(); } ``` ```php // ✅ Secure: check actual extension/type and allowlist. $check = wp_check_filetype_and_ext( $_FILES['file']['tmp_name'], $_FILES['file']['name'] ); $allowed = array( 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg' ); if ( empty( $check['ext'] ) || ! isset( $allowed[ $check['ext'] ] ) ) { wp_die( esc_html__( 'File type not allowed.', 'my-plugin' ), 400 ); } ``` ### Mistake 3 — Blocklisting dangerous extensions ```php // ❌ Insecure: misses .phtml, .php5, .pht, .phar, case variants, double extensions. $ext = pathinfo( $name, PATHINFO_EXTENSION ); if ( 'php' === $ext ) { wp_die( 'No PHP files' ); } ``` ```php // ✅ Secure: allowlist exactly what you accept; reject everything else. $allowed_ext = array( 'png', 'jpg', 'jpeg', 'gif', 'pdf' ); $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) ); if ( ! in_array( $ext, $allowed_ext, true ) ) { wp_die( esc_html__( 'File type not allowed.', 'my-plugin' ), 400 ); } ``` ### Mistake 4 — Path traversal in a download/read handler ```php // ❌ Insecure: ../../wp-config.php is reachable. $file = $_GET['file']; readfile( '/var/www/uploads/' . $file ); ``` ```php // ✅ Secure: sanitize, resolve, and confine to the base directory. $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 5 — Widening allowed MIME types globally and forgetting it ```php // ❌ Risky: opens SVG (script-bearing) site-wide with no sanitization. add_filter( 'upload_mimes', function ( $m ) { $m['svg'] = 'image/svg+xml'; return $m; } ); ``` ```php // ✅ Safer: only if truly needed, sanitize SVGs and restrict to high-trust roles. // Prefer not allowing SVG. If required, sanitize markup server-side and gate by capability. add_filter( 'upload_mimes', function ( $m ) { if ( current_user_can( 'manage_options' ) ) { $m['svg'] = 'image/svg+xml'; // plus server-side SVG sanitization before storage } return $m; } ); ``` ### Mistake 6 — Trusting extension alone and missing double extensions ```php // ❌ Insecure: pathinfo can be fooled by file.php.jpg or .phtml variants. $ext = pathinfo( $name, PATHINFO_EXTENSION ); if ( 'jpg' === $ext ) { accept_upload(); } ``` ```php // ✅ Secure: use wp_check_filetype_and_ext() which inspects real MIME type and extension. $check = wp_check_filetype_and_ext( $tmp_name, $name, $allowed ); if ( empty( $check['ext'] ) || empty( $check['type'] ) ) { wp_die( esc_html__( 'Invalid file type.', 'my-plugin' ), 400 ); } ``` ### Mistake 7 — Serving uploaded files without path containment ```php // ❌ Insecure: download handler may escape the uploads directory. readfile( wp_upload_dir()['basedir'] . '/' . $_GET['file'] ); ``` ```php // ✅ Secure: resolve and confine to the uploads base directory. $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 ); ``` Related: see the `filesystem-security` skill for post-upload path handling and deletion. ## Correct code examples A complete secure upload handler (nonce + capability + `wp_handle_upload` + `wp_check_filetype_and_ext` allowlist + safe path handling) is in [`references/secure-file-upload.php`](references/secure-file-upload.php). ## Checklist - [ ] Upload handler checks nonce and the `upload_files` capability first. - [ ] Uses `wp_handle_upload()` (not raw `move_uploaded_file`). - [ ] Validates with `wp_check_filetype_and_ext()` against an explicit allowlist. - [ ] Accepts via allowlist; never relies on a blocklist of extensions. - [ ] Does not trust the client-supplied MIME type (`$_FILES[...]['type']`). - [ ] Filenames pass through `sanitize_file_name()` / are assigned by core. - [ ] Any path built from input is resolved with `realpath()` and confined to a base dir. - [ ] Executable types are not accepted into web-served directories. - [ ] SVG and other script-bearing types are sanitized or disallowed. ## Official references - [`wp_handle_upload()`](https://developer.wordpress.org/reference/functions/wp_handle_upload/) - [`wp_check_filetype_and_ext()`](https://developer.wordpress.org/reference/functions/wp_check_filetype_and_ext/) - [`sanitize_file_name()`](https://developer.wordpress.org/reference/functions/sanitize_file_name/) - [`wp_upload_dir()`](https://developer.wordpress.org/reference/functions/wp_upload_dir/) - [`upload_mimes` filter](https://developer.wordpress.org/reference/hooks/upload_mimes/) - [`media_handle_upload()`](https://developer.wordpress.org/reference/functions/media_handle_upload/) - [OWASP — File Upload Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html) ## Dónde encaja - Categoría: [Seguridad](https://skillsagentes.com/categorias/seguridad.md) — Auditorías, revisión de dependencias, manejo de secretos y modelado de amenazas. - Creador: [wpultimatesecurity](https://skillsagentes.com/creators/wpultimatesecurity.md) — 27 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Security Auditing Code Review](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/security-auditing-code-review.md): Ú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. - [Authentication Session Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/authentication-session-security.md): Ú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. - [Dependency Supply Chain Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/dependency-supply-chain-security.md): Ú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. - [Secure Plugin Development](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/secure-plugin-development.md): Ú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. - [Gutenberg Block Editor Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/gutenberg-block-editor-security.md): Ú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. ## Skills relacionadas - [Ai Llm Integration Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/ai-llm-integration-security.md): Ú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. - [Ajax Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/ajax-security.md): Ú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. - [Authentication Session Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/authentication-session-security.md): Ú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. - [Capability Permission Checks](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/capability-permission-checks.md): Protege operaciones privilegiadas en WordPress con current_user_can() usando la capability correcta (no el rol), checks por objeto y nonce, evitando escalada de privilegios y control de acceso roto. - [Cron Background Job Security](https://skillsagentes.com/skills/wpultimatesecurity/wordpress-security-skills/cron-background-job-security.md): Úsalo al programar eventos cron con wp_schedule_event / wp_schedule_single_event o al escribir el callback. Revalida la autorización contra el contexto guardado, no con current_user_can, y mantiene los secretos fuera de las URLs de cron. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)