Logotipo de File Upload Security

File Upload Security

Organización
wpultimatesecurity
file-upload-security

Use when a WordPress plugin or theme accepts file uploads, processes $_FILES, saves user-provided files, or generates file paths from input. Uses wp_handle_upload and wp_check_filetype_and_ext with a MIME/extension allowlist, blocks executable types, and prevents path traversal. Prevents arbitrary file upload and RCE. Apply proactively to any upload or file-writing code path.

Descripción general

Editorwpultimatesecurity
RepositorioWordPress-Security-Skills
Nombre de la habilidadfile-upload-security
Estrellas
54
Forks
3
Archivos incluidos
2
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Archivos incluidos: 2

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por wpultimatesecurity en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA File Upload Security en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/wpultimatesecurity/WordPress-Security-Skills/tree/dev/skills/file-upload-security
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wpultimatesecurity/WordPress-Security-Skills.git /tmp/WordPress-Security-Skills
mkdir -p .claude/skills
cp -r /tmp/WordPress-Security-Skills/skills/file-upload-security .claude/skills/file-upload-security
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa File Upload Security en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga File Upload Security automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que File Upload Security no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

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

ReferenceLoad when
File upload security checklistBefore final verification of the file upload security controls.
Secure file upload handlerImplementing 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.

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

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Son archivos de solo lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de IA File Upload Security?

Use when a WordPress plugin or theme accepts file uploads, processes $_FILES, saves user-provided files, or generates file paths from input. Uses wp_handle_upload and wp_check_filetype_and_ext with a MIME/extension allowlist, blocks executable types, and prevents path traversal. Prevents arbitrary file upload and RCE. Apply proactively to any upload or file-writing code path.

¿Por qué usar File Upload Security en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. File Upload Security está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo File Upload Security en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/wpultimatesecurity/WordPress-Security-Skills/tree/dev/skills/file-upload-security. TypingMind lee el archivo SKILL.md de esa carpeta, empaqueta los archivos de la carpeta e instala el conjunto como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar File Upload Security?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar File Upload Security?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar File Upload Security con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA File Upload Security?

Sí. wpultimatesecurity la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇