Showing posts with label UDF. Show all posts
Showing posts with label UDF. Show all posts

HackTheBox Noter Machine: A Deep Dive into Flask Cookie Exploitation and MySQL Raptor UDF for RCE

The digital shadows lengthen, and the hum of servers is a constant reminder of the battles waged in the dark. Today, we're not just patching holes; we're dissecting a machine, peeling back layers of code to expose its vulnerabilities. This is HackTheBox's Noter machine, a playground for those who understand that true security comes from knowing how the enemy operates. We'll crack Flask session cookies, forge credentials, and leverage a potent MySQL exploit to achieve Remote Code Execution on a modern distro. This isn't for the faint of heart; it's for the architects of defense who need to understand the blueprints of attack.

Publish Date: September 3, 2022

Table of Contents

Initial Reconnaissance: Nmap and User Enumeration

Every breach begins with reconnaissance. Our first step on the Noter machine is a thorough Nmap scan. We fan out our probes, looking for open ports and services that might be broadcasting vulnerabilities. Beyond the standard HTTP/S ports, we're hunting for anything unusual. The web application itself is the primary target. Once we identify the web service, registration becomes our next play. Standard user enumeration techniques quickly reveal their hand: error messages subtly leak valid usernames. This is a classic oversight – a red flag for any seasoned defender.

Web Application Probing: Beyond the Obvious

With a list of potential usernames, the web application's surface area expands. We start poking around, employing tools like ffuf to match patterns and confirm our enumerated users. The real work begins when we start testing for common web vulnerabilities. IDOR, SSTI – we throw the usual suspects at it. Today, they don't bite. This often means the vulnerability lies deeper, or in a less conventional vector. The application token, the cookie it hands over, becomes our next point of focus.

The Cookie Crumbles: Flask Session Hijacking

The cookie is more than just a session identifier; it's a potential gateway. We quickly identify it as a Flask session cookie. These are often signed, and if the signing secret is weak or compromised, the cookie can be forged. Our initial attempts to crack it with Hashcat, bombarding it with common wordlists, fail. The payload length might be the culprit, or perhaps the secret itself is too robust. This is where specialized tools come into play. Enter Flask-Unsign. This utility is designed specifically to tackle Flask session cookies, either by cracking the secret or by allowing us to forge a valid-looking cookie. We feed it the target cookie, and it reveals the underlying structure. With a bit of manipulation, we forge a cookie that presents us to the application not as an anonymous user, but as the 'Blue User'.

Gaining Foothold: Credentials and Source Code Analysis

The forged cookie works. We're in, authenticated as 'Blue User'. This privileged access grants us a critical piece of information: the ftp_admin password. With this credential, we access the FTP server and retrieve the application's source code. Now, the real detective work begins. Comparing the source code version we just downloaded with a potential earlier version (if available or implied) using a diff tool can reveal changes, and more importantly, introduce new vulnerabilities or highlight deprecated ones. This is where we pivot from exploitation to in-depth code review, the defender's true advantage.

Unearthing the RCE: Command Injection and md-to-pdf

Our source code analysis flags a potential command injection vulnerability within the 'export note' function. We attempt to exploit it directly, but the sanitization proves effective. Undeterred, we dive deeper into the function's dependencies. This is where modern applications often reveal their weaknesses: third-party libraries. We discover that md-to-pdf, a Node.js library used for rendering notes to PDF, is susceptible to Remote Code Execution. This is a critical find. A library designed for content conversion becomes the vector for full system compromise.

Escalation Pathways: LinPEAS and the UDF Gambit

Now that we have a foothold, the next logical step is privilege escalation. We deploy LinPEAS, a script designed to quickly identify potential privilege escalation vectors on Linux systems. While it scans, we prepare our more advanced payload. The target is MySQL, specifically its User-Defined Functions (UDFs). These functions allow extending MySQL's capabilities, and if we can inject a malicious UDF, we can leverage MySQL's permissions to execute arbitrary commands on the host operating system.

The MySQL Raptor Exploit: Achieving Persistent RCE

Our initial attempts with a known Raptor exploit variant are met with failure. The version we pulled is not compatible with the current system configuration. This highlights the importance of understanding the target environment thoroughly before deploying exploits. We need to identify the correct path for our raptor_udf library. By checking variables like %plugin%, we can deduce the expected location. With the correct version of Raptor and knowledge of the plugin directory, we can finally execute commands through MySQL. A function like do_system_init in a compatible Raptor version allows us to execute arbitrary code, achieving persistent Remote Code Execution on this modern Linux distribution.

Veredicto del Ingeniero: Lessons Learned and Future Defenses

The Noter machine is a masterclass in layering vulnerabilities. It starts with basic enumeration flaws, moves to sophisticated cookie manipulation using specialized tools, and culminates in exploiting a third-party library for initial RCE, followed by a potent MySQL UDF exploit for privilege escalation.

  • Defensive Insight: Never underestimate the security implications of third-party libraries and service dependencies. Robust input validation and sandboxing are paramount, especially for functions that interact with the operating system.
  • Credential Management: Weaknesses in web application registration and the insecure handling of session state are prime targets. Always enforce secure cookie policies and strong session management.
  • MySQL Security: The MySQL Raptor UDF exploit is a powerful reminder of the risks associated with allowing direct command execution through database functions. Limit who can create UDFs and ensure the plugin directory is secured.

This machine teaches us that defense is not a static configuration; it's a dynamic understanding of attack vectors. By dissecting these challenges, we build stronger shields.

Arsenal del Operador/Analista

  • Web Application Proxies: Burp Suite Pro, OWASP ZAP
  • Fuzzing Tools: ffuf, dirb, gobuster
  • Session Cracking: Flask-Unsign, Hashcat
  • Code Analysis: VS Code, Sublime Text, `diff`
  • Privilege Escalation: LinPEAS, GTFOBins
  • Database Exploitation: Metasploit (for general payloads), custom scripts for MySQL UDFs
  • Learning Platforms: HackTheBox, TryHackMe
  • Essential Reading: "The Web Application Hacker's Handbook", "Black Hat Python"

Taller Defensivo: Fortaleciendo la Protección contra UDFs Maliciosas en MySQL

  1. Auditar Permisos de SYS_CONFIG: Restringir los permisos para modificar configuraciones del sistema, especialmente aquellas relacionadas con el directorio de plugins de MySQL.
  2. Monitorear el Directorio de Plugins: Configurar alertas y auditorías regulares sobre el directorio de plugins de MySQL. Cualquier archivo nuevo o modificado que no sea legítimo debe ser marcado.
  3. Utilizar Versiones de MySQL Actualizadas: Mantener MySQL actualizado reduce la superficie de ataque. Las versiones más nuevas a menudo corrigen fallos de seguridad que podrían ser explotados por UDFs maliciosas.
  4. Implementar Listas Blancas para UDFs: Si es posible, configurar MySQL o el sistema operativo para permitir solo la carga de UDFs conocidas y aprobadas.
  5. Segregación de Red y Acceso a la BD: Limitar el acceso a los servidores de bases de datos solo a las aplicaciones y usuarios que realmente lo necesitan.

Preguntas Frecuentes

  • ¿Qué es un Flask Session Cookie y por qué es un objetivo?
    Un Flask Session Cookie es un mecanismo de seguridad utilizado por aplicaciones web construidas con el framework Flask para mantener el estado de la sesión del usuario. Si el secreto utilizado para firmar la cookie es débil o se filtra, un atacante puede falsificar una cookie para impersonar a otro usuario o para obtener privilegios elevados.
  • ¿Cómo funciona el exploit MySQL Raptor UDF?
    El exploit MySQL Raptor UDF permite a un atacante cargar una biblioteca maliciosa (.so en Linux) como una función definida por el usuario en MySQL. Si el servidor MySQL tiene suficientes privilegios, puede usar esta UDF para ejecutar comandos arbitrarios en el sistema operativo subyacente.
  • ¿Por qué falló mi intento inicial de crackear la cookie con Hashcat?
    Hashcat es excelente para crackear contraseñas y hashes, pero las cookies de sesión de Flask a menudo contienen datos serializados o estructuras complejas que pueden ser demasiado largas o no estar en el formato esperado por Hashcat para su procesamiento eficiente. Herramientas especializadas como Flask-Unsign están diseñadas para manejar estas peculiaridades.
  • ¿Qué es 'md-to-pdf' y por qué es vulnerable?
    'md-to-pdf' es una librería de Node.js que convierte archivos Markdown a PDF. Las vulnerabilidades de RCE en tales librerías a menudo surgen cuando procesan entradas de usuario sin la sanitización adecuada, permitiendo la inyección de comandos del sistema operativo a través de argumentos maliciosos pasados al proceso de generación de PDF.

El Contrato: Asegura el Perímetro contra Dependencias Peligrosas

Ahora que has visto cómo una librería de terceros se convirtió en la llave de entrada, tu contrato es simple: audita tus propias dependencias. Identifica cada librería externa en tus proyectos. ¿Están actualizadas? ¿Son de fuentes confiables? ¿Se validan las entradas de usuario antes de pasarlas a estas librerías? Documenta tu hallazgo y presenta un plan de mitigación propuesto para la próxima auditoría de seguridad. El código es un ecosistema; una sola planta podrida puede enfermar a todo el jardín.