Пример #1
0
 def map_local_file(self, flow):
     _host = flow.request.host
     if _host in self.local_rule:
         (rule, pathname) = self.local_rule[_host], flow.request.path.split("?")[0]
         for match in rule:
             if match in pathname:
                 local_file = rule[match] + pathname.replace('/', sep).replace(match, '', 1).lstrip(sep)
                 #process hash filename like my_program_xxxxxx.js to local_file my_program_.js'
                 striped_file = re.sub(r'[a-f0-9]{6}\.(js|css|jpg|png|jpeg|gif)$', r'.\1', local_file)
                 if path.isfile(local_file) or path.isfile(striped_file):
                     if path.exists(striped_file): local_file = striped_file
                     content_type = mimetypes.guess_type(local_file)[0]
                     if content_type is None: break
                     body = str(open(local_file).read()).encode('utf-8')
                     header = self.custom_header(_host, content_type, len(body))
                     _response = HTTPResponse(b"HTTP/1.1", 200, "local", header, body, is_replay=True)
                     flow.response = _response
                     self.log("\n%s\n%s\nReplied with Local File:\n%s\n%s\n%s\n" % (flow.request.path, '='*80, '-'*80, local_file, "-"*80))
                     break
                 elif _host == 'config.qq.com':
                     header = self.custom_header(_host, 'text/html', 0)
                     flow.response = HTTPResponse(b"HTTP/1.1", 404, "not found", header, '', is_replay=True)
                     self.log("\n%s\n%s\nReplied with empty file%s\n" % (flow.request.path, '=' * 80, '-' * 80))
                     break
     elif DEFAULT_PROXY is not None:
         self.proxy_request_to_upstream(flow, DEFAULT_PROXY)
Пример #2
0
    def request(self, flow):
        try:
            flow.response = self.create_response(flow.request)
        except ConnectionError:
            # If TCP Rst Configured
            if self.on_rst:
                self.logger.debug("Got TCP Rst, While TCP Rst Configured")
                self.multitor.new_identity()
                # Set Response
                try:
                    flow.response = self.create_response(flow.request)
                except Exception as error:
                    self.logger.error(
                        "Got Unknown Error (after second TCP Rst) %s" % error)
                    flow.response = HTTPResponse.make(
                        400, "Unknown Error (after second TCP Rst) %s" % error)
                    return
            else:
                self.logger.error("Got TCP Rst, While TCP Rst Not Configured")
                flow.response = HTTPResponse.make(400, "Got TCP Rst")
                return
        except Exception as error:
            self.logger.error("Got Unknown Error %s" % error)
            flow.response = HTTPResponse.make(400, "Unknown Error %s" % error)
            return

        # If String Found In Response Content
        if self.on_string and self.on_string in flow.response.text:
            self.logger.debug("String Found In Response Content")
            self.multitor.new_identity()
            # Set Response
            flow.response = self.create_response(flow.request)

        # If Regex Found In Response Content
        if self.on_regex and re.search(self.on_regex, flow.response.text,
                                       re.IGNORECASE):
            self.logger.debug("Regex Found In Response Content")
            self.multitor.new_identity()
            # Set Response
            flow.response = self.create_response(flow.request)

        # If Counter Raised To The Configured Number
        if self.on_count and next(self.counter) >= self.on_count:
            self.logger.debug("Counter Raised To The Configured Number")
            self.counter = itertools.count(1)
            self.multitor.new_identity()

        # If A Specific Status Code Returned
        if self.on_error_code and self.on_error_code == flow.response.status_code:
            self.logger.debug("Specific Status Code Returned")
            self.multitor.new_identity()
            # Set Response
            flow.response = self.create_response(flow.request)
Пример #3
0
def request(flow):
    if LOG_LEVEL is None:
        start()
    _changeHeader(flow.request.headers, 'Proxy-Connection')
    _changeHeader(flow.request.headers, 'X-Requested-With')
    flow.remote_server = True
    flow.own_response = False
    if '127.0.0.1' in flow.request.pretty_host:
        urls = flow.request.url.split('/')
        flow.request.url = '/'.join(urls[:2] + urls[3:])
        flow.remote_server = False
    host = flow.request.pretty_host
    if host.endswith('.ssl'):
        flow.request.scheme = 'https'
        flow.request.port = 443
        flow.request.url = flow.request.url.replace('.ssl/', '/', 1)
    if flow.request.scheme != 'https' and FORCE_HTTPS:
        flow.request.scheme = 'https'
        newUrl = _sanitizeLocation(flow.request.url)
        flow.response = HTTPResponse.make(301, '', {'Location': newUrl})
        flow.own_response = True
        return
    if flow.remote_server and PDF_PORT and flow.request.url.endswith('.pdf'):
        parts = _sanitizeLocation(flow.request.url).split('/')
        flow.request.port = int(PDF_PORT)
        newUrl = '/'.join(parts[:2] + ['127.0.0.1:' + PDF_PORT] + parts[2:])
        flow.response = HTTPResponse.make(302, '', {'Location': newUrl})
        flow.own_response = True
        return
    _changeHeader(flow.request.headers, 'Referer', '.ssl')
    _changeHeader(flow.request.headers, 'Origin', '.ssl')
    _changeHeader(flow.request.headers, 'User-Agent', TOR_UA)
    _changeHeader(
        flow.request.headers, 'Accept',
        'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
    _changeHeader(flow.request.headers, 'Accept-Language', 'en-US,en;q=0.5')
    uirh = 'Upgrade-Insecure-Requests'
    if not _iGet(flow.request.headers, uirh, None):
        flow.request.headers[uirh] = '1'
    newReqData = re.sub(b'http%3A%2F%2F' + dnsRegExp + b'.ssl',
                        b'https%3A%2F%2F' + b'\\1',
                        flow.request.content,
                        flags=re.IGNORECASE)
    # Touch content only if needed:
    if newReqData != flow.request.content:
        if LOG_LEVEL > 0:
            print('newReqData !=;', flow.request.url)
        flow.request.content = newReqData
    if LOG_LEVEL > 0:
        print('requestH(' + flow.request.url + ')', flow.request.headers)
    if LOG_LEVEL > 1:
        print('requestC(' + flow.request.url + ')', flow.request.content)
Пример #4
0
    def request(self, flow):
        if (flow.request.pretty_host == prettyHost
                and flow.request.method == reqMethod):
            if (flow.request.pretty_url == prettyURL):
                if self.process != None:
                    self.process.terminate()

                flow.request.decode()
                uForm = json.loads(flow.request.content)

                quizMatch = self.regex.match(flow.request.headers['referer'])
                quiz = quizMatch.group(1)

                runDir = os.path.dirname(os.path.abspath(__file__))
                runExec = os.path.join(runDir, 'MentiMemer')

                ctx.log.info("Calling \'" + runExec + "\'")

                self.process = Popen([
                    runExec, quiz, uForm['question'], uForm['question_type'],
                    json.dumps(uForm['vote'], ensure_ascii=False)
                ],
                                     cwd=runDir)
        elif (flow.request.pretty_host == stopHost):
            if self.process != None:
                self.process.terminate()
                self.process = None

            flow.response = HTTPResponse(
                "HTTP/1.1", 200, "OK", Headers(Content_Type="text/html"),
                b'<!DOCTYPE html><html><body><big style=\"font-size: 5em\">Stopped auto-send</big></body></html>'
            )
Пример #5
0
def replaceImage(flow):
    attrs = dict((x.lower(), y) for x, y in flow.response.headers.items())
    if "content-type" in attrs:
        if "image" in attrs[
                'content-type'] and not "svg" in attrs['content-type']:
            if flow.response.status_code == 304:
                content = flow.response.content
            else:
                content = requests.get(flow.request.url).content
            if len(content) == 0:
                return flow
            try:
                img = Image.open(io.BytesIO(content))
                size = img.size
                if size[0] > 40 and size[1] > 40:
                    filename = random.choice(os.listdir("images"))
                    img = resizeImg("images/" + filename, size[0], size[1])
                    #content = img.make_blob()
                    imgByteArr = io.BytesIO()
                    img.save(imgByteArr, format='JPEG')
                    content = imgByteArr.getvalue()
                    responseHeaders = {'Content-Length': str(len(content))}
                    responseHeaders['Content-Type'] = "image/jpg"
                    #import pdb;pdb.set_trace()
                    resp = HTTPResponse.make(status_code=200,
                                             headers=responseHeaders,
                                             content=content)
                    flow.response = resp

            except:
                PrintException()
    return flow
def replaceImage(flow):
    attrs = dict((x.lower(), y) for x, y in flow.response.headers.items())
    if "content-type" in attrs:
        if "image" in attrs['content-type'] and not "svg" in attrs['content-type']:
            if flow.response.status_code == 304:
                content = flow.response.content
            else:
                content = requests.get(flow.request.url).content
            if len(content) == 0:
                return flow
            try:
                img = Image.open(io.BytesIO(content))
                size = img.size
                if size[0] > 40 and size[1] > 40:
                    filename = random.choice(os.listdir("images"))
                    img = resizeImg("images/" + filename, size[0], size[1])
                    #content = img.make_blob()
                    imgByteArr = io.BytesIO()
                    img.save(imgByteArr, format='BMP')
                    content = imgByteArr.getvalue()
                    responseHeaders = {'Content-Length':str(len(content))}
                    responseHeaders['Content-Type'] = "image/bmp"
                    #import pdb;pdb.set_trace()
                    resp = HTTPResponse.make(status_code=200, headers=responseHeaders, content=content)
                    flow.response = resp

            except:
                PrintException()
    return flow
Пример #7
0
 def request(self, flow: HTTPFlow):
     if flow.request.host in self.ServersList and flow.request.path.startswith(
             "/charBuild/setDefaultSkill"):
         self.info("Receive default skill change change request")
         req = json.loads(flow.request.get_text())
         self.tBuilder.chars[str(
             req["charInstId"]
         )]["defaultSkillIndex"] = req["defaultSkillIndex"]
         resp = {
             "playerDataDelta": {
                 "deleted": {},
                 "modified": {
                     "troop": {
                         "chars": {
                             str(req["charInstId"]): {
                                 "defaultSkillIndex":
                                 req["defaultSkillIndex"]
                             }
                         }
                     }
                 }
             }
         }
         self.info("make response")
         flow.response = HTTPResponse.make(
             200, json.dumps(resp),
             {"Content-Type": "application/json; charset=utf-8"})
         self.info("Reply Complete")
Пример #8
0
 def request(self, flow: HTTPFlow):
     """
         {
             "charInstId": 9,
             "skinId": "char_123_fang#1"
         }
     """
     if self.inServersList(
             flow.request.host) and flow.request.path.startswith(
                 "/charBuild/changeCharSkin"):
         self.info("Receive skin change request")
         req = json.loads(flow.request.get_text())
         resp = {
             "playerDataDelta": {
                 "deleted": {},
                 "modified": {
                     "troop": {
                         "chars": {
                             str(req["charInstId"]): {
                                 "skin": req["skinId"]
                             }
                         }
                     }
                 }
             }
         }
         self.info("make response")
         self.tBuilder.chars[str(req["charInstId"])]["skin"] = req["skinId"]
         flow.response = HTTPResponse.make(
             200, json.dumps(resp),
             {"Content-Type": "application/json; charset=utf-8"})
         self.info("Reply Complete")
Пример #9
0
def request(context, flow):
    rewrite = False
    mockresp = open("mock/success.json", "r").read()

    flow.request.oldpath = flow.request.path
    # if flow.request.path.endswith("/api/2/account/api/"):
    #     flow.request.path = "/api/2/account/myapitest"
    if flow.request.path.startswith(
            "/api/2/account/my/profile/plan/circlesswitch/upgrade/"):
        rewrite = True
    if flow.request.path.startswith(
            "/api/2/account/my/profile/id/digits/verify/get/"):
        mockresp = open("mock/my_profile_id_digits_verify_get.json",
                        "r").read()
        rewrite = True
    if flow.request.path.startswith(
            "/api/2/account/my/portin/request/cancel/"):
        rewrite = True

    print("\nRequest : " + str(flow.request.oldpath) + "\n")
    # print("Request Rewrite : " + str(flow.request.path)+"\n")
    print("\nRequest Body : " + str(flow.request.content) + "\n")

    if rewrite:
        time.sleep(0.3)
        resp = HTTPResponse(
            "HTTP/1.1", 200, "OK",
            Headers(Content_Type="application/json; charset=utf-8"), mockresp)
        flow.reply(resp)
        print("\nResponse : " + str(flow.response.content) + "\n")
Пример #10
0
 def to_mitmproxy(self) -> HTTPResponse:
     return HTTPResponse(
         http_version='HTTP/1.1',
         status_code=self.status_code,
         reason=self.status_message,
         headers=self.headers.to_mitmproxy(),
         content=self.body,
     )
Пример #11
0
 def request(self, flow):
     if self.pred(flow):
         try:
             if flow.request.method == 'GET':
                 row = self.st.get_row_by_url(flow.request.url)
                 if row is None:
                     ctx.log.info('@ not found: {}'.format(flow.request.url))
                     flow.response = HTTPResponse.make(404, content=flow.request.url)
                 else:
                     ctx.log.info('@ using row: {}'.format(row))
                     flow.response = HTTPResponse.make(
                         content=self.st.get_blob(row.hash),
                         headers={
                             'content-type': row.content_type
                             },
                         )
         except Exception as e:
             flow.response = HTTPResponse.make(500, content=str(e))
Пример #12
0
 def homepage_refresh(self, flow, url):
     flow.direct_response = True
     environ = {}
     environ['webrec.template_params'] = {'url': url}
     resp_data = self.home_redir_view.render_to_string(environ).encode(
         'utf-8')
     flow.response = HTTPResponse.make(
         200, resp_data, {'Content-Type': 'text/html; charset=utf-8'})
     return True
Пример #13
0
def request(flow):
    url = flow.request.pretty_url
    host = flow.request.pretty_host
    print('request():', host, url)
    if any(map(lambda s: host.startswith(s), ignoreHosts)):
        return
    resp = HTTPResponse.make(
        303, url, {
            'Content_Type': "text/html",
            'Location': url.replace('http://', 'https://', 1)
        })
    now = time.time()
    if insecure_urls[url] + 61 > now:
        resp = HTTPResponse.make(500, "mitm seen before" + url, {})
    if len(insecure_urls) > 5 * 1024:
        print('request(): insecure_urls.clear()')
        insecure_urls.clear()
    insecure_urls[url] = now
    flow.response = resp
Пример #14
0
	def block_telemetry(flow: HTTPFlow):
		if config.block_telemetry and flow.request.path.startswith('/telemetry'):
			flow.request.text = '{}'  # Just in case

			flow.response = HTTPResponse.make(200, '{}')
			flow.response.headers.add('Content-Type', 'application/json')
			flow.response.headers.add('server', 'eos-gateway')
			flow.response.headers.add('access-control-allow-origin', '*')
			flow.response.headers.add('x-epic-correlation-id', '12345678-1234-1234-1234-123456789abc')

			log.info('Blocked telemetry request from Epic Games')
Пример #15
0
 def response_config_rule(self, flow):
     (_host, _path) = flow.request.host, flow.request.path
     header = self.custom_header(_host, 'text/plain', 7)
     header['location'] = 'http://' + _host + _path
     _response = HTTPResponse(b"HTTP/1.1",
                              200,
                              'ok',
                              header,
                              content=b'{ret:0}',
                              is_replay=True)
     flow.response = _response
Пример #16
0
    def request(self, flow):
        error_message = None
        try:
            flow.response = self.create_response(flow.request)
        except ConnectionError:
            # If TCP Rst Configured
            if self.on_rst:
                self.logger.debug("Got TCP Rst, While TCP Rst Configured")
                self.multitor.new_identity()
                # Set Response
                try:
                    flow.response = self.create_response(flow.request)
                except Exception as error:
                    error_message = f"Got Error: {error}"
            else:
                error_message = "Got TCP Rst, While TCP Rst Not Configured"
        except Exception as error:
            error_message = f"Got Error: {error}"

        # When There Is No Response
        if error_message:
            self.logger.error(error_message)
            flow.response = HTTPResponse.make(
                status_code=500,
                content=error_message,
                headers={"Server": f"pymultitor/{__version__}"})
            return

            # If String Found In Response Content
        if self.on_string and self.on_string in flow.response.text:
            self.logger.debug("String Found In Response Content")
            self.multitor.new_identity()
            # Set Response
            flow.response = self.create_response(flow.request)

        # If Regex Found In Response Content
        if self.on_regex and re.search(self.on_regex, flow.response.text,
                                       re.IGNORECASE):
            self.logger.debug("Regex Found In Response Content")
            self.multitor.new_identity()
            # Set Response
            flow.response = self.create_response(flow.request)

        # If Counter Raised To The Configured Number
        if self.on_count and not next(self.counter) % self.on_count:
            self.logger.debug("Counter Raised To The Configured Number")
            self.multitor.new_identity()

        # If A Specific Status Code Returned
        if self.on_error_code and self.on_error_code == flow.response.status_code:
            self.logger.debug("Specific Status Code Returned")
            self.multitor.new_identity()
            # Set Response
            flow.response = self.create_response(flow.request)
Пример #17
0
 def redirect_https_to_http(flow):
     (_host, _path) = flow.request.host, flow.request.path
     header = Smarthost.custom_header(_host, None, 0)
     header['location'] = 'http://' + _host + _path
     _response = HTTPResponse(b"HTTP/1.1",
                              302,
                              'redirect temporary',
                              header,
                              '',
                              is_replay=True)
     flow.response = _response
Пример #18
0
def _load_http_response(o: http_pb2.HTTPResponse) -> HTTPResponse:
    d: dict = {}
    _move_attrs(o, d, ['http_version', 'status_code', 'reason',
                       'content', 'timestamp_start', 'timestamp_end'])
    if d['content'] is None:
        d['content'] = b""
    d["headers"] = []
    for header in o.headers:
        d["headers"].append((bytes(header.name, "utf-8"), bytes(header.value, "utf-8")))

    return HTTPResponse(**d)
Пример #19
0
def request(flow):
    global rules

    req = flow.request
    # accept = flow.request.headers["Accept"]
    # log("accept: %s" % flow.request.accept)

    options = {'domain': req.host}

    if IMAGE_MATCHER.search(req.path):
        options["image"] = True
    elif SCRIPT_MATCHER.search(req.path):
        options["script"] = True
    elif STYLESHEET_MATCHER.search(req.path):
        options["stylesheet"] = True

    if rules.should_block(req.url, options):
        log("vvvvvvvvvvvvvvvvvvvv BLOCKED vvvvvvvvvvvvvvvvvvvvvvvvvvv")
        log("accept: %s" % flow.request.headers.get("Accept"))
        log("blocked-url: %s" % flow.request.url)
        log("^^^^^^^^^^^^^^^^^^^^ BLOCKED ^^^^^^^^^^^^^^^^^^^^^^^^^^^")

        # resp = HTTPResponse((1,1), 404, "OK",
        #     ODictCaseless([["Content-Type", "text/html"]]),
        #     "A terrible ad has been removed!")

        # HTTPResponse(http_version, status_code, reason, headers, content, timestamp_start=None, timestamp_end=None)

        # resp = HTTPResponse(
        #     (1,1),
        #     200,
        #     "OK",
        #     ODictCaseless(
        #         [
        #             ["Content-Type", "text/html"]
        #         ]
        #     ),
        #     "BLOCKED."
        # )

        resp = HTTPResponse(
            (1,1),
            200,
            "OK",
            Headers(content_type="text/html"),
            "BLOCKED."
        )

        flow.reply(resp)
    else:
        log("url: %s" % flow.request.url)
Пример #20
0
 def request(self, flow: HTTPFlow):
     """MITMProxy addon event interface for outgoing request."""
     try:
         request = MITMRequest.from_mitmproxy(flow.request)
         response = self.process_request(request).to_mitmproxy()
         flow.response = response
     except DoNotIntercept as e:
         # Let the request pass through, by not interrupting the flow, but log it
         logger.warning(str(e))
     except Exception as e:
         flow.response = HTTPResponse.make(
             status_code=getattr(e, 'http_status_code', 500),
             content=str(e),
             headers={'Content-Type': 'text/plain'})
Пример #21
0
    def create_response(self, request):
        response = requests.request(method=request.method,
                                    url=request.url,
                                    data=request.content,
                                    headers=request.headers,
                                    allow_redirects=False,
                                    verify=not self.insecure,
                                    proxies=self.multitor.proxy)

        return HTTPResponse.make(
            status_code=response.status_code,
            content=response.content,
            headers=dict(response.headers),
        )
Пример #22
0
    def tampper_fields(self, flow):
        rules = self.reuse_header
        req = flow.request
        _host = req.host
        _url = req.pretty_url
        _headers = req.headers if req.headers is not None else {}
        _querys = req.query if req.query is not None else {}

        if _host in self.reuse_header:
            rule = self.reuse_header[_host]
            match, cnt, vals = rule['matches'], 0, []
            _check = _querys if rule['is_query'] == 1 else _headers

            if 'url_match' in rule:
                if _url.find(rule['url_match']) == -1:
                    return

            for k, v in enumerate(match):
                if v in _check and len(_check[v]) > 0:
                    cnt += 1
                    vals.append(_check[v])
            if cnt == len(match):
                self.reuse_header[_host]['values'] = vals
            elif len(rule['values']) == len(match):
                vals = self.reuse_header[_host]['values']
                for k, v in enumerate(match):
                    val = urllib.quote(vals[k].encode('utf-8'))
                    if rule['is_query'] == 1:
                        if _url.find(v + '=') > -1:
                            _url = re.sub(r''.join([v, '=[^&]*?']), _url,
                                          r'%s%s<1>' % (v, val))
                        else:
                            flag = '&' if _url.find('?') != -1 else '?'
                            _url += '%s%s=%s' % (flag, v, val)
                    else:
                        req.request.headers[v] = vals[k]
                if rule['is_query'] == 1:
                    header = Headers(host=_host)
                    header['location'] = _url
                    header["Connection"] = 'closed'
                    header["Content-Length"] = '0'
                    flow.is_replay = True
                    flow.response = HTTPResponse(b"HTTP/1.1",
                                                 302,
                                                 'redirect temporary',
                                                 header,
                                                 b'',
                                                 is_replay=True)
Пример #23
0
def request(flow):
    host = flow.request.headers.get('Host', '')
    if host.endswith('.https'):
        flow.request.scheme = 'https'
        flow.request.port = 443
        origHost = host.replace('.https', '')
        flow.request.host = origHost
    elif host.endswith('.http'):
        flow.request.scheme = 'http'
        flow.request.port = 80
        origHost = host.replace('.http', '')
        flow.request.host = origHost
    else:
        flow.response = HTTPResponse.make(418)
    if False:
        print('requestH(' + flow.request.url + ')', flow.request.headers)
Пример #24
0
	def block_playtime(flow: HTTPFlow):
		if config.block_playtime and flow.request.path.startswith('/library/api/public/playtime/'):
			original_playtime = json.loads(flow.request.text)
			flow.request.text = '{}'  # Just in case

			correlation_id = flow.request.headers.get('X-Epic-Correlation-ID')
			if m := re.match(r"UE4-(\w+)", correlation_id):
				device_id = m.group(1)
			else:
				device_id = '123456789abcdef01234567890abcdef'

			flow.response = HTTPResponse.make(204)
			flow.response.headers.add('x-epic-device-id', device_id)
			flow.response.headers.add('x-epic-correlation-id', correlation_id)
			flow.response.headers.add('x-envoy-upstream-service-time', '10')  # ?
			flow.response.headers.add('server', 'istio-envoy')

			log.info('Blocked playtime request from Epic Games')
			log.debug(f'\n{json.dumps(original_playtime, indent=4)}')
Пример #25
0
    def create_response(self, request):
        response = requests.request(method=request.method,
                                    url=request.url,
                                    data=request.content,
                                    headers=request.headers,
                                    allow_redirects=False,
                                    verify=not self.insecure,
                                    proxies=self.multitor.proxy,
                                    stream=False)

        # Content-Length and Transfer-Encoding set. This is expressly forbidden by RFC 7230 sec 3.3.2.
        if response.headers.get("Transfer-Encoding") == "chunked":
            response.headers.pop("Transfer-Encoding")

        return HTTPResponse.make(
            status_code=response.status_code,
            content=response.content,
            headers=dict(response.headers),
        )
Пример #26
0
 def request(self, flow: HTTPFlow):
     if flow.request.host in self.ServersList and flow.request.path.startswith(
             "/quest/battleStart"):
         req = json.loads(flow.request.get_text())
         if (req["stageId"] != "main_08-16"):
             return
         self.info("Receive JT8-2 battle start request")
         fakeData = {
             "apFailReturn": 20,
             "battleId": "6c86c7c0-3373-11eb-9784-0d36b8275660",
             "isApProtect": 0,
             "notifyPowerScoreNotEnoughIfFailed": False,
             "playerDataDelta": {
                 "deleted": {},
                 "modified": {
                     # "dungeon": {
                     #     "stages": {
                     #         "main_07-01": {
                     #             "completeTimes": 1,
                     #             "hasBattleReplay": 1,
                     #             "noCostCnt": 0,
                     #             "practiceTimes": 0,
                     #             "stageId": "main_07-01",
                     #             "startTimes": 2,
                     #             "state": 3
                     #         }
                     #     }
                     # }
                 }
             },
             "result": 0
         }
         flow.response = HTTPResponse.make(
             200, json.dumps(fakeData),
             {"Content-Type": "application/json; charset=utf-8"})
         self.info("complete")
def request(flow):
    global rules

    req = flow.request

    options = {'domain': req.host}

    db_insert(req.host)
    with open('hostname.txt', 'a') as f:
        f.write(f"{req.host} ===> url {flow.request.url}\n \n\n\n\n")

    if IMAGE_MATCHER.search(req.path):
        options["image"] = True
    elif SCRIPT_MATCHER.search(req.path):
        options["script"] = True
    elif STYLESHEET_MATCHER.search(req.path):
        options["stylesheet"] = True

    if rules.should_block(req.url, options):
        log("vvvvvvvvvvvvvvvvvvvv BLOCKED vvvvvvvvvvvvvvvvvvvvvvvvvvv")
        with open('block_sites.txt', 'a') as file:
            file.write(
                f'{flow.request.url} ===> header: {flow.request.headers.get("Accept")}\n'
            )
            file.write(f'options {options}\n\n\n\n\n')
        log("accept: %s" % flow.request.headers.get("Accept"))
        log("blocked-url: %s" % flow.request.url)
        log("^^^^^^^^^^^^^^^^^^^^ BLOCKED ^^^^^^^^^^^^^^^^^^^^^^^^^^^")

        flow.response = HTTPResponse.make(404, b"OK",
                                          {"Content-Type": "text/html"})

        # HTTPResponse(http_version, status_code, reason, headers, content, timestamp_start=None, timestamp_end=None)

    else:
        log("url: %s" % flow.request.url)
Пример #28
0
 def perform(self, flow, qs):
     flow.response = HTTPResponse.make(
         302,
         b"",
         {"Location": self.build_destination(qs)}
     )
Пример #29
0
 def homepage_redir(self, flow, redir_url):
     flow.request.host = self.fwd_host
     flow.response = HTTPResponse.make(303, b'', {'Location': redir_url})
     return True
    # gzipped utf-8-encoded "Hello, world!"
    'body': b'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaIQ\x04\x00 ^\x04\x8a',
    'headers': {
        'Content-Type': ['text/plain; charset=UTF-8'],
        'Date': ['Wed, 21 Mar 2018 12:47:18 GMT'],
        'Server': ['nginx/1.12.2'],
        'Content-Encoding': ['gzip']
    }
}

TEST_MITM_RESPONSE = HTTPResponse(
    http_version='HTTP/1.1',
    status_code=200,
    reason='OK',
    headers=Headers(fields=[
        (b'Content-Type', b'text/plain; charset=ISO-8859-2'),
        (b'Date', b'Wed, 21 Mar 2018 12:47:18 GMT'),
        (b'Server', b'nginx/1.12.2'),
    ]),
    content=b'Witaj, \xb6wiecie!',
)

TEST_MITM_RESPONSE_GZIP = HTTPResponse(
    http_version='HTTP/1.1',
    status_code=200,
    reason='OK',
    headers=Headers(fields=[
        (b'Content-Type', b'text/plain; charset=UTF-8'),
        (b'Date', b'Wed, 21 Mar 2018 12:47:18 GMT'),
        (b'Server', b'nginx/1.12.2'),
        (b'Content-Encoding', b'gzip'),
Пример #31
0
 def block_telemetry(flow: HTTPFlow):
     if config.block_telemetry and flow.request.path.startswith(
             '/ratt/telm'):
         flow.response = HTTPResponse.make(500, 'No more spying')
         log.debug('Blocked telemetry request from Origin')
Пример #32
0
    def request(self, flow: HTTPFlow):
        if self.inServersList(
                flow.request.host) and flow.request.path.startswith(
                    "/gacha/tenAdvancedGacha"):
            respData = {
                "gachaResultList": [],
                "playerDataDelta": {
                    "deleted": {},
                    "modified": {}
                },
                "result": 0
            }
            self.info("十连中...")
            charlist = self.getTen()
            for charId, rarity in charlist:
                gacha = {}
                gacha["isNew"] = 0
                gacha["charId"] = charId
                cdata = self.tBuilder.getCharData(charId)
                if cdata == None:
                    continue
                gacha["charInstId"] = cdata["instId"]
                if rarity == "5":
                    gacha["itemGet"] = [{
                        "count": 15,
                        "id": "4004",
                        "type": "HGG_SHD"
                    }, {
                        "count": 1,
                        "id": "p_" + charId,
                        "type": "MATERIAL"
                    }]
                if rarity == "4":
                    gacha["itemGet"] = [{
                        "count": 8,
                        "id": "4004",
                        "type": "HGG_SHD"
                    }, {
                        "count": 1,
                        "id": "p_" + charId,
                        "type": "MATERIAL"
                    }]
                if rarity == "3":
                    gacha["itemGet"] = [{
                        "count": 30,
                        "id": "4005",
                        "type": "LGG_SHD"
                    }, {
                        "count": 1,
                        "id": "p_" + charId,
                        "type": "MATERIAL"
                    }]
                if rarity == "2":
                    gacha["itemGet"] = [{
                        "count": 5,
                        "id": "4005",
                        "type": "LGG_SHD"
                    }, {
                        "count": 1,
                        "id": "p_" + charId,
                        "type": "MATERIAL"
                    }]
                respData["gachaResultList"].append(gacha)
            flow.response = HTTPResponse.make(
                200, json.dumps(respData),
                {"Content-Type": "application/json; charset=utf-8"})
            self.info("完成")
        if self.inServersList(
                flow.request.host) and flow.request.path.startswith(
                    "/gacha/advancedGacha"):
            respData = {
                "charGet": {},
                "playerDataDelta": {
                    "deleted": {},
                    "modified": {}
                },
                "result": 0
            }
            self.info("单抽中...")
            charId, rarity = self.getOne()
            gacha = {}
            gacha["isNew"] = 0
            gacha["charId"] = charId
            cdata = self.tBuilder.getCharData(charId)
            gacha["charInstId"] = cdata["instId"]
            if rarity == "5":
                gacha["itemGet"] = [{
                    "count": 15,
                    "id": "4004",
                    "type": "HGG_SHD"
                }, {
                    "count": 1,
                    "id": "p_" + charId,
                    "type": "MATERIAL"
                }]
            if rarity == "4":
                gacha["itemGet"] = [{
                    "count": 8,
                    "id": "4004",
                    "type": "HGG_SHD"
                }, {
                    "count": 1,
                    "id": "p_" + charId,
                    "type": "MATERIAL"
                }]
            if rarity == "3":
                gacha["itemGet"] = [{
                    "count": 30,
                    "id": "4005",
                    "type": "LGG_SHD"
                }, {
                    "count": 1,
                    "id": "p_" + charId,
                    "type": "MATERIAL"
                }]
            if rarity == "2":
                gacha["itemGet"] = [{
                    "count": 5,
                    "id": "4005",
                    "type": "LGG_SHD"
                }, {
                    "count": 1,
                    "id": "p_" + charId,
                    "type": "MATERIAL"
                }]

            respData["charGet"] = gacha
            flow.response = HTTPResponse.make(
                200, json.dumps(respData),
                {"Content-Type": "application/json; charset=utf-8"})
            self.info("完成")