Skills Agentes

Multisite Security

Ú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.

Oficial
Estrellas
57

en todo el repo

Actividad
54

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
4

últimos 90 días

Contexto
2.3k tok

106 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 multisite-security --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Valida blog_id antes de usarlo en switch_to_blog() y comprueba la pertenencia del usuario al sitio
  • Empareja siempre switch_to_blog() con restore_current_blog()
  • Vuelve a comprobar capacidades tras cambiar de sitio con current_user_can()
  • Usa manage_network/manage_network_options en vez de manage_options para acciones de red
  • Evita guardar datos por sitio en site_transient, site_option o cachés globales compartidas

Úsalo cuando

  • Código que usa switch_to_blog() para acceder a datos de otro sitio
  • Páginas de administración de red con network_admin_menu
  • Enumeración de sitios con get_sites()
  • Lectura de un blog_id desde un parámetro de petición o URL

No lo uses cuando

    Qué lo activa

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

    • “Añade una página de administración de red para gestionar todos los sitios”
    • “Crea una función que cambie a otro blog con switch_to_blog y lea sus posts”
    • “Revisa este código multisite que usa is_super_admin para permisos de red”

    SKILL.md

    En inglés

    Multisite security

    When to use this skill

    Use this skill whenever code runs on a WordPress multisite network:

    • Using switch_to_blog() to access another site's data.
    • Adding network admin pages (network_admin_menu).
    • Enumerating sites with get_sites().
    • Reading a blog_id from a request parameter or URL.
    • Performing actions that affect the whole network vs. a single site.

    On multisite, site administrator and network administrator are different roles. Network-level actions require manage_network or manage_network_options, and switch_to_blog() must always be paired with restore_current_blog().

    Related: see the capability-permission-checks skill for single-site capability patterns.

    Core principles (and why they matter)

    1. Site admin != network admin. A site administrator can do almost anything on their own site, but they must not manage network settings or access other sites' data. Network actions need manage_network / manage_network_options.
    2. Always pair switch_to_blog() with restore_current_blog(). Forgetting to restore leaves the rest of the request running in the wrong site context, leaking or corrupting data.
    3. Re-check capabilities after switching. Capabilities are evaluated in the current site context. After switch_to_blog(), the capability context changes; re-verify current_user_can() or user_can() if you act on the new site.
    4. Never trust a blog_id from input. Validate it against allowed sites (e.g., sites the current user belongs to, or the network allowlist) before switching.
    5. Keep per-site data isolated. Do not store site A's data in site B's options or tables unless the user explicitly authorized cross-site access.
    6. is_super_admin() is for network-level checks only. Prefer current_user_can( 'manage_network' ) for capabilities.

    Step-by-step implementation

    1. Check is_multisite() before running multisite-specific code.
    2. For network admin pages, gate with current_user_can( 'manage_network_options' ).
    3. For site actions that read a blog_id from input:
      • Cast to integer.
      • Confirm the site exists (get_site()).
      • Confirm the current user may act on it (user_can( $user_id, 'manage_sites' ) or membership checks).
    4. Wrap the operation in switch_to_blog() / restore_current_blog().
    5. After switching, re-check capabilities if the action is privileged.
    6. Return errors rather than silently failing or defaulting to the current site.

    Supporting references

    Reference Load when
    Multisite security checklist Before final verification of the multisite security controls.
    Secure multisite operations Implementing validated site switching, membership checks, context restoration, and network option updates.

    Common AI mistakes / anti-patterns

    Mistake 1 — switch_to_blog() with an unvalidated blog id

    // ❌ Insecure: any blog id can be requested, including sites the user does not own.
    $blog_id = (int) $_GET['blog_id'];
    switch_to_blog( $blog_id );
    $posts = get_posts();
    restore_current_blog();
    
    // ✅ Secure: validate the blog id and the user's relationship to it.
    $blog_id = isset( $_GET['blog_id'] ) ? absint( $_GET['blog_id'] ) : 0;
    $site    = get_site( $blog_id );
    if ( ! $site || ! is_user_member_of_blog( get_current_user_id(), $blog_id ) ) {
        wp_die( esc_html__( 'Invalid site.', 'my-plugin' ), 403 );
    }
    
    switch_to_blog( $blog_id );
    $posts = get_posts();
    restore_current_blog();
    

    Mistake 2 — Forgetting restore_current_blog()

    // ❌ Risky: subsequent code runs in the switched context.
    foreach ( $blog_ids as $blog_id ) {
        switch_to_blog( $blog_id );
        do_something();
    }
    
    // ✅ Secure: restore after each switch.
    foreach ( $blog_ids as $blog_id ) {
        switch_to_blog( $blog_id );
        do_something();
        restore_current_blog();
    }
    

    Mistake 3 — Using manage_options for a network action

    // ❌ Insecure: site admins have manage_options but cannot manage the network.
    if ( current_user_can( 'manage_options' ) ) {
        update_site_option( 'my_plugin_network_key', $value );
    }
    
    // ✅ Secure: network actions require manage_network / manage_network_options.
    if ( ! current_user_can( 'manage_network_options' ) ) {
        wp_die( esc_html__( 'You do not have permission to manage network options.', 'my-plugin' ), 403 );
    }
    update_site_option( 'my_plugin_network_key', $value );
    

    Mistake 4 — Leaking data after a switch

    // ❌ Insecure: data fetched under site B is echoed on site A without re-checking.
    switch_to_blog( $blog_id );
    $title = get_bloginfo( 'name' );
    restore_current_blog();
    echo $title;
    
    // ✅ Secure: validate the user may read the target site, then escape output.
    if ( ! is_user_member_of_blog( get_current_user_id(), $blog_id ) ) {
        return;
    }
    switch_to_blog( $blog_id );
    $title = get_bloginfo( 'name' );
    restore_current_blog();
    echo esc_html( $title );
    

    Mistake 5 — Assuming is_super_admin() covers every case

    // ❌ Less precise: is_super_admin checks the super-admin list, not a capability.
    if ( is_super_admin() ) {
        // do network thing
    }
    
    // ✅ Secure: prefer the explicit network capability.
    if ( current_user_can( 'manage_network' ) ) {
        // do network thing
    }
    

    Mistake 6 — Per-site data in a network-wide cache or option

    // ❌ Insecure: site_transient and a global cache group are shared by every
    // site, so site A's private member list is served to site B's visitors.
    $members = get_site_transient( 'my_plugin_members' );
    if ( false === $members ) {
        $members = my_plugin_query_members();
        set_site_transient( 'my_plugin_members', $members, HOUR_IN_SECONDS );
    }
    
    // ✅ Secure: per-site storage (or a key that includes the blog ID).
    $members = get_transient( 'my_plugin_members' );
    if ( false === $members ) {
        $members = my_plugin_query_members();
        set_transient( 'my_plugin_members', $members, HOUR_IN_SECONDS );
    }
    

    Also check wp_cache_add_global_groups() calls and custom tables without a blog_id column: shared storage must never hold per-site private data.

    Correct code examples

    A complete network-safe routine that validates a blog id, switches context, and restores it is in references/secure-multisite-operations.php.

    Checklist

    • Multisite-specific code checks is_multisite() first.
    • Network admin actions use manage_network / manage_network_options.
    • blog_id values from input are cast to integers and validated.
    • The user is confirmed to be a member of / allowed on the target site before switching.
    • Every switch_to_blog() has a matching restore_current_blog().
    • Capabilities are re-checked after switching sites if the action is privileged.
    • Per-site data is not leaked into another site's context.
    • is_super_admin() is used only where the super-admin list is the correct gate.
    • Per-site data never goes into *_site_transient, *_site_option, global cache groups, or shared tables without a blog ID in the key.
    • Users removed from a site lose access to that site's REST, AJAX, and export paths (is_user_member_of_blog() rechecked, not cached).

    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.

    Antes de instalar

    Pensado para código que corre en una red WordPress multisite (is_multisite()).

    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 mostrar o imprimir cualquier valor dinámico en PHP o plantillas de WordPress, escapando en el punto de salida con esc_html, esc_attr, esc_url, esc_js, esc_textarea o wp_kses_post para prevenir XSS.

    Costo de contexto al activarse
    2.4k 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