예제 #1
0
파일: tamper.py 프로젝트: saalmaan/tamper
    def handle_request(self, msg):
        f = flow.FlowMaster.handle_request(self, msg)

        fullURL = f.request.scheme + '://' + f.request.host
        if ((f.request.scheme == 'http' and f.request.port == 80) == False and
            (f.request.scheme == 'https' and f.request.port == 443) == False):
            fullURL = fullURL + ':' + str(f.request.port)
        fullURL = fullURL + f.request.path

        send_message(json.dumps({'method': 'log', 'message': fullURL}))

        if (f.request.host == 'mitm.it'):
            path = f.request.path

            if path.find('?') > -1:
                path = path[:path.find('?')]

            if path == '/':
                path = '/index.html'

            mimeType = ''
            if path.rfind('.') > -1:
                extension = path[path.rfind('.') + 1:]
                if extension == 'html':
                    mimeType = 'text/html'
                elif extension == 'css':
                    mimeType = 'text/css'
                elif extension == 'cer':
                    mimeType = 'application/pkix-cert'
                elif extension == 'pem':
                    mimeType = 'application/x-pem-file'
                elif extension == 'p12':
                    mimeType = 'application/x-pkcs12'

            responseHeaders = ODictCaseless([('content-type', mimeType)])

            try:
                if path in [
                        '/mitmproxy-ca-cert.cer', '/mitmproxy-ca-cert.pem',
                        '/mitmproxy-ca-cert.p12'
                ]:
                    with open(expanduser('~/.mitmproxy' + path),
                              'rb') as certfile:
                        content = certfile.read()
                elif path in ['/index.html', '/mitmproxy.css']:
                    with open(sys.prefix + '/tamper-files' + path,
                              'rb') as uifile:
                        content = uifile.read()

                responseHeaders['Content-Length'] = [len(content)]

                resp = HTTPResponse([1, 1], 200, 'OK', responseHeaders,
                                    content)
                msg.reply(resp)
            except:
                resp = HTTPResponse([1, 1], 404, 'Not Found',
                                    ODictCaseless([]), '')
                msg.reply(resp)

        for url in urlsToProxy:
            regexURL = '^' + re.escape(url['url']).replace('\\*', '.*?') + '$'
            if (re.match(regexURL, fullURL) and url['isEnabled'] == True):
                send_message(
                    json.dumps({
                        'method':
                        'log',
                        'message':
                        'Serving cached file (' + url['cachedFilename'] + ')'
                    }))
                localFile = open(self._cachedFilesPath + url['cachedFilename'],
                                 'r')
                content = localFile.read()
                localFile.close()

                responseHeaders = []
                hasViaHeader = False
                for header in url['responseHeaders']:
                    if (header['name'].lower() != 'content-encoding'):
                        if (header['name'].lower() == 'via'):
                            hasViaHeader = True
                            if (header['value'].find('tamper') == -1):
                                header['value'] += ', tamper'

                        responseHeaders.append(
                            (header['name'], header['value']))

                if (not hasViaHeader):
                    responseHeaders.append(['via', 'tamper'])

                responseHeaders.append(
                    ['Cache-Control', 'no-cache, no-store, must-revalidate'])
                responseHeaders.append(['Pragma', 'no-cache'])
                responseHeaders.append(['Expires', '0'])

                resp = HTTPResponse([1, 1], 200, 'OK',
                                    ODictCaseless(responseHeaders), content)
                msg.reply(resp)
                break

        if 'Accept-Encoding' in f.request.headers:
            f.request.headers['Accept-Encoding'] = ['none']

        if f:
            msg.reply()

        return f
예제 #2
0
    def handle_request(self, msg):
        f = flow.FlowMaster.handle_request(self, msg)

        fullURL = f.request.scheme + '://' + f.request.host
        if ((f.request.scheme == 'http' and f.request.port == 80) == False and (f.request.scheme == 'https' and f.request.port == 443) == False):
            fullURL = fullURL + ':' + str(f.request.port)
        fullURL = fullURL + f.request.path

        send_message(json.dumps({'method': 'log', 'message': fullURL}))

        if (f.request.host == 'mitm.it'):
            path = f.request.path

            if path.find('?') > -1:
                path = path[:path.find('?')]

            if path == '/':
                path = '/index.html'

            mimeType = '';
            if path.rfind('.') > -1:
                extension = path[path.rfind('.') + 1:]
                if extension == 'html':
                    mimeType = 'text/html'
                elif extension == 'css':
                    mimeType = 'text/css'
                elif extension == 'cer':
                    mimeType = 'application/pkix-cert'
                elif extension == 'pem':
                    mimeType = 'application/x-pem-file'
                elif extension == 'p12':
                    mimeType = 'application/x-pkcs12'

            responseHeaders = ODictCaseless([('content-type', mimeType)])

            try:
                if path in ['/mitmproxy-ca-cert.cer', '/mitmproxy-ca-cert.pem', '/mitmproxy-ca-cert.p12']:
                    with open(expanduser('~/.mitmproxy' + path), 'rb') as certfile:
                        content = certfile.read()
                elif path in ['/index.html', '/mitmproxy.css']:
                    with open(sys.prefix + '/tamper-cert' + path, 'rb') as uifile:
                        content = uifile.read()

                responseHeaders['Content-Length'] = [len(content)]

                resp = HTTPResponse([1,1], 200, 'OK', responseHeaders, content)
                msg.reply(resp)
            except:
                resp = HTTPResponse([1,1], 404, 'Not Found', ODictCaseless([]), '')
                msg.reply(resp)

        for url in urlsToProxy:
            regexURL = '^' + re.escape(url['url']).replace('\\*', '.*?') + '$'
            if (re.match(regexURL, fullURL) and url['isEnabled'] == True):
                send_message(json.dumps({'method': 'log', 'message': 'Serving cached file (' + url['cachedFilename'] + ')'}))
                localFile = open(self._cachedFilesPath + url['cachedFilename'], 'r');
                content = localFile.read()
                localFile.close();

                responseHeaders = []
                hasViaHeader = False
                for header in url['responseHeaders']:
                    if (header['name'].lower() != 'content-encoding'):
                        if (header['name'].lower() == 'via'):
                            hasViaHeader = True
                            if (header['value'].find('tamper') == -1):
                                header['value'] += ', tamper'

                        responseHeaders.append((header['name'], header['value']))

                if (not hasViaHeader):
                    responseHeaders.append(['via', 'tamper'])

                responseHeaders.append(['Cache-Control', 'no-cache, no-store, must-revalidate'])
                responseHeaders.append(['Pragma', 'no-cache'])
                responseHeaders.append(['Expires', '0'])

                resp = HTTPResponse([1,1], 200, 'OK', ODictCaseless(responseHeaders), content)
                msg.reply(resp)
                break


        if 'Accept-Encoding' in f.request.headers:
            f.request.headers['Accept-Encoding'] = ['none']

        if f:
            msg.reply()

        return f
예제 #3
0
파일: tamper.py 프로젝트: Deradon/tamper
    def handle_request(self, msg):
        f = flow.FlowMaster.handle_request(self, msg)

        fullURL = f.request.scheme + "://" + f.request.host
        if (f.request.scheme == "http" and f.request.port == 80) == False and (
            f.request.scheme == "https" and f.request.port == 443
        ) == False:
            fullURL = fullURL + ":" + str(f.request.port)
        fullURL = fullURL + f.request.path

        send_message(json.dumps({"method": "log", "message": fullURL}))

        if f.request.host == "mitm.it":
            path = f.request.path

            if path.find("?") > -1:
                path = path[: path.find("?")]

            if path == "/":
                path = "/index.html"

            mimeType = ""
            if path.rfind(".") > -1:
                extension = path[path.rfind(".") + 1 :]
                if extension == "html":
                    mimeType = "text/html"
                elif extension == "css":
                    mimeType = "text/css"
                elif extension == "cer":
                    mimeType = "application/pkix-cert"
                elif extension == "pem":
                    mimeType = "application/x-pem-file"
                elif extension == "p12":
                    mimeType = "application/x-pkcs12"

            responseHeaders = ODictCaseless([("content-type", mimeType)])

            try:
                if path in ["/mitmproxy-ca-cert.cer", "/mitmproxy-ca-cert.pem", "/mitmproxy-ca-cert.p12"]:
                    with open(expanduser("~/.mitmproxy" + path), "rb") as certfile:
                        content = certfile.read()
                elif path in ["/index.html", "/mitmproxy.css"]:
                    with open(sys.prefix + "/tamper-files" + path, "rb") as uifile:
                        content = uifile.read()

                responseHeaders["Content-Length"] = [len(content)]

                resp = HTTPResponse([1, 1], 200, "OK", responseHeaders, content)
                msg.reply(resp)
            except:
                resp = HTTPResponse([1, 1], 404, "Not Found", ODictCaseless([]), "")
                msg.reply(resp)

        for url in urlsToProxy:
            regexURL = "^" + re.escape(url["url"]).replace("\\*", ".*?") + "$"
            if re.match(regexURL, fullURL) and url["isEnabled"] == True:
                send_message(
                    json.dumps({"method": "log", "message": "Serving cached file (" + url["cachedFilename"] + ")"})
                )
                localFile = open(self._cachedFilesPath + url["cachedFilename"], "r")
                content = localFile.read()
                localFile.close()

                responseHeaders = []
                hasViaHeader = False
                for header in url["responseHeaders"]:
                    if header["name"].lower() != "content-encoding":
                        if header["name"].lower() == "via":
                            hasViaHeader = True
                            if header["value"].find("tamper") == -1:
                                header["value"] += ", tamper"

                        responseHeaders.append((str(header["name"]), str(header["value"])))

                if not hasViaHeader:
                    responseHeaders.append(["via", "tamper"])

                responseHeaders.append(["Cache-Control", "no-cache, no-store, must-revalidate"])
                responseHeaders.append(["Pragma", "no-cache"])
                responseHeaders.append(["Expires", "0"])

                resp = HTTPResponse([1, 1], 200, "OK", ODictCaseless(responseHeaders), content)
                msg.reply(resp)
                break

        if "Accept-Encoding" in f.request.headers:
            f.request.headers["Accept-Encoding"] = ["none"]

        if f:
            msg.reply()

        return f