👨🏼‍💻 ‎‎‎‏‏ A customizable man-in-the-middle TCP proxy with out-of-the-box support for HTTP & HTTPS.

Overview

👨‍💻 mitm

A customizable man-in-the-middle TCP proxy with out-of-the-box support for HTTP & HTTPS.

Installing

pip install mitm

Note that OpenSSL 1.1.1 or greater is required.

Documentation

Documentation can be found here.

Using

Using the default values for the MITM class:

from mitm import MITM, protocol, middleware, crypto

mitm = MITM(
    host="127.0.0.1",
    port=8888,
    protocols=[protocol.HTTP],
    middlewares=[middleware.Log],
    buffer_size=8192,
    timeout=5,
    ssl_context=crypto.mitm_ssl_default_context(),
)
mitm.run()

This will start a proxy on port 8888 that is capable of intercepting all HTTP traffic (with support for CONNECT), and log all activity.

Protocols

mitm comes with a set of built-in protocols, and a way to add your own. Protocols and are used to implement custom application-layer protocols that interpret and route traffic. Out-of-the-box HTTP is available.

Middlewares

Middleware are used to implement event-driven behavior as it relates to the client and server connection. Out-of-the-box Log is available.

Example

Using the example above we can send a request to the server via another script:

import requests

proxies = {"http": "http://127.0.0.1:8888", "https": "http://127.0.0.1:8888"}
requests.get("https://httpbin.org/anything", proxies=proxies, verify=False)

Which will lead to the following being logged where mitm is running in:

2021-11-29 10:33:02 INFO     MITM started on 127.0.0.1:8888.
2021-11-29 10:33:03 INFO     Client 127.0.0.1:54771 has connected.
2021-11-29 10:33:03 INFO     Client to server:

	b'CONNECT httpbin.org:443 HTTP/1.0\r\n\r\n'

2021-11-29 10:33:03 INFO     Connected to server 18.232.227.86:443.
2021-11-29 10:33:03 INFO     Client to server:

	b'GET /anything HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-requests/2.26.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'

2021-11-29 10:33:03 INFO     Server to client:

	b'HTTP/1.1 200 OK\r\nDate: Mon, 29 Nov 2021 15:33:03 GMT\r\nContent-Type: application/json\r\nContent-Length: 396\r\nConnection: keep-alive\r\nServer: gunicorn/19.9.0\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Credentials: true\r\n\r\n{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {}, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.26.0", \n    "X-Amzn-Trace-Id": "Root=1-61a4f2af-2de4362101f0cab43f6407b1"\n  }, \n  "json": null, \n  "method": "GET", \n  "origin": "xxx.xx.xxx.xx", \n  "url": "https://httpbin.org/anything"\n}\n'

2021-11-29 10:33:08 INFO     Client has disconnected.
2021-11-29 10:33:08 INFO     Server has disconnected.
Comments
  • Make installing certificates easier.

    Make installing certificates easier.

    A few issues/discussion posts have been opened regarding mitm's certificates & and its use with Chrome. It would be a nice addition to have an easy method for installing certificates on different machines.

    enhancement 
    opened by synchronizing 11
  • Use without having to use verify=False

    Use without having to use verify=False

    Hello, I wanted to know if it was possible to use this project without having to use verify=False. I heard this was possible by installing a certificate. Not using verify=False while doing requests will make my program crash because of SSL errors

    question 
    opened by Zorkai 11
  • TypeError: ClassTask.__init__() got an unexpected keyword argument 'run_forever'

    TypeError: ClassTask.__init__() got an unexpected keyword argument 'run_forever'

    Hello, here I am again!

    EDIT: If I knew how to fix this I'd make a PR, sorry in advance!

    Code (from examples):

    from mitm import MITM, protocol, middleware, crypto
    
    mitm = MITM(
        host="127.0.0.1",
        port=8888,
        protocols=[protocol.HTTP],
        middlewares=[middleware.Log],
        buffer_size=8192,
        timeout=5,
        ssl_context=crypto.mitm_ssl_default_context(),
        start=False,
    )
    mitm.start()
    

    Output error:

    Traceback (most recent call last):
      File "c:\Users\Slimakoi\Desktop\Coding\test\falling_new.py", line 3, in <module>
        mitm = MITM(
      File "C:\Program Files\Python310\lib\site-packages\mitm\mitm.py", line 65, in __init__
        super().__init__(
    TypeError: ClassTask.__init__() got an unexpected keyword argument 'run_forever'
    
    bug 
    opened by Slimakoi 6
  • Performance bogs down with normal web use.

    Performance bogs down with normal web use.

    G'day,

    I tried using the proxy as a normal HTTPs proxy for normal web-browsing. It seems like it struggles with a backlog of requests and does things sequentially.

    I'm not sure if it's built for this kind of purpose, but it's what I intend on using it for so any help in getting it to run slightly smoother would be of great help!

    Cheers,

    Mitch

    opened by Mitch0S 4
  • Circular import error

    Circular import error

    G'day!

    I just got around to trying the 1.3.0 release. I created a fresh project on PyCharm, using Python 3.10 - When running the following code:

    from mitm import MITM, CertificateAuthority, middleware, protocol
    from pathlib import Path
    
    # Loads the CA certificate.
    path = Path("")
    ca = CertificateAuthority.init(path=path)
    
    # Starts the MITM server.
    mitm = MITM(
        host="127.0.0.1",
        port=8888,
        protocols=[protocol.HTTP],
        middlewares=[middleware.Log],
        buffer_size=8192,
        timeout=5,
        ca=ca,
    )
    mitm.run()
    

    It throws this error:

    Traceback (most recent call last):
      File "/Users/myname/PycharmProjects/ComputerScience/misc/mitm.py", line 1, in <module>
        from mitm import CertificateAuthority, middleware, protocol
      File "/Users/myname/PycharmProjects/ComputerScience/misc/mitm.py", line 1, in <module>
        from mitm import CertificateAuthority, middleware, protocol
    ImportError: cannot import name 'CertificateAuthority' from partially initialized module 'mitm' (most likely due to a circular import) (/Users/myname/PycharmProjects/ComputerScience/misc/mitm.py)
    
    opened by Mitch0S 4
  • Not decoding requests

    Not decoding requests

    Hey, I'm using your example in the Middleware section in the readme of the project.

    But I'm only getting following :

    py main.py
    2021-11-09 18:27:17 INFO     Booting up server on 127.0.0.1:8888.
    2021-11-09 18:27:18 INFO     Client 127.0.0.1:62708 has connected.
    2021-11-09 18:27:19 INFO     Successfully closed connection with 127.0.0.1:62708.
    

    When running the following script:

    import requests
    
    proxies = {"http": "http://127.0.0.1:8888", "https": "http://127.0.0.1:8888"}
    requests.get("https://httpbin.org/anything", proxies=proxies, verify=False)
    

    I'd like to be able to see the headers, the content, etc of the request

    bug documentation 
    opened by Zorkai 3
  • Create a test suite for the project.

    Create a test suite for the project.

    A testing suite needs to be built for the project. I'm currently unsure how to go about this, and so any suggestions are welcomed.

    I've tried to use Pytest for this, but I've had major issues booting up the server and having it run in the background before tests.

    enhancement 
    opened by synchronizing 1
  • AttributeError: module 'mitm.crypto' has no attribute 'mitm_ssl_context'

    AttributeError: module 'mitm.crypto' has no attribute 'mitm_ssl_context'

    Code (from examples):

    from mitm import MITM, protocol, middleware, crypto
    
    mitm = MITM(
        host="127.0.0.1",
        port=8888,
        protocols=[protocol.HTTP],
        middlewares=[middleware.Log],
        buffer_size=8192,
        timeout=5,
        ssl_context=crypto.mitm_ssl_context(),
        start=False,
    )
    mitm.start()
    

    Error:

    C:\Users\Slimakoi\Desktop\Coding>main.py
    Traceback (most recent call last):
      File "C:\Users\Slimakoi\Desktop\Coding\main.py", line 10, in <module>
        ssl_context=crypto.mitm_ssl_context(),
    AttributeError: module 'mitm.crypto' has no attribute 'mitm_ssl_context'
    
    bug documentation 
    opened by Slimakoi 1
  • Deal with hanging connections and unknown protocols.

    Deal with hanging connections and unknown protocols.

    As of right now mitm does not deal with hanging connections and unknown protocols very well. httpq will hang if the client never provide the correct bytes:

    https://github.com/synchronizing/mitm/blob/5b9ae6306eae029aa6da1efa130a534ca223657c/mitm/mitm.py#L117-L121

    Probable solution:

    (a) Check if client.at_eof directly on the while loop, and (b) Read up to n bytes. If we don't have a valid HTTP first line by then, the client is sending some other protocol.

    enhancement 
    opened by synchronizing 1
  • Improve performance.

    Improve performance.

    As mentioned by #18, mitm has a bottleneck that does not allow it to be used in conjunction with normal web use.

    This PR increases performance by caching ssl.SSLContext that are generated by mitm so that it does not have to save/load from disk on every request.

    opened by synchronizing 0
  • mitm.Protocol now handles the connection.

    mitm.Protocol now handles the connection.

    Currently mitm.MITM is the location in which the relaying of data between the client and server occurs. This PR moves this relaying mechanism to inside of the individual protocols, and making Protocol (similar to Middleware now) into an objects as opposed to classes. This PR changes the mitm.Protocol to have the following methods:

    class Protocol:
        def __init__(
            self,
            bytes_needed: int = 8192,
            buffer_size: int = 8192,
            timeout: int = 5,
            keep_alive: bool = True,
            ca: CertificateAuthority = CertificateAuthority(),
            middlewares: List[Middleware] = [],
        )
        async def resolve(self, connection: Connection, data: bytes) -> Optional[Tuple[str, int, bool]]
        async def connect(self, connection: Connection, host: str, port: int, tls: bool, data: bytes)
        async def handle(self, connection: Connection)
    

    Where resolve resolves the initial data coming in from the client (resolves what the destination server is); connect connects to the clients destination server; and handle handles the relaying of data between the client and server. This allows better customization on how the data should be relayed between client/server. As a result of the new class, mitm.MITM has changed to a simpler API as well:

    class MITM:
        def __init__(
            self,
            host: str = "127.0.0.1",
            port: int = 8888,
            protocols: List[protocol.Protocol] = [protocol.HTTP],
            middlewares: List[middleware.Middleware] = [middleware.Log],
            ca: CertificateAuthority = None,
            run: bool = False,
        )
    

    This should, in theory, allow a caching mechanism to be build on top of a protocol - as suggested by #9.


    Todo

    • [x] Convert mitm.Protocol from a class object to an instantiated object.
    • [x] Transfer buffer_size, timeout, and keep_alive to the individual protocols.
    • [x] Update documentation & type hints.
    enhancement 
    opened by synchronizing 0
Releases(v1.4.2)
Network Dynaimcs Simulation

A Final Year Project in CUHK, Autumn 2021 Network Dynaimcs Simulation Files param.h edit all the variables & settings here simulate.c the main program

Likchun 0 Mar 28, 2022
This repository contain sample code of gRPC Communication between Python and GoLang

This repository contain sample code of gRPC Communication between Python and GoLang, the Server is running on GoLang while Python is running the client

Abdullahi Muhammad 2 Nov 29, 2021
Python code that get the name and ip address of a computer/laptop

IP Address This is a python code that provides the name and the internet protocol address of the computer. You need to install socket pip install sock

CODE 2 Feb 21, 2022
Network-Shredder is a python based NIDS.

Network-Shredder is a python based NIDS.

Oussama RAHALI 9 Dec 13, 2022
订阅转换,添加免流host

普通订阅转免流订阅 原理 将原来的订阅解析后添加免流host 使用方法 服务器域名/&&订阅链接&&免流host&&转换后服务器前缀 我这里已经在服务器上搭建好了

163 Apr 01, 2022
This is a zeep based SOAP client wrapper for simple communication with the Bricknode SOAP API.

This is a zeep based SOAP client wrapper for simple communication with the Bricknode SOAP API.

Nord Fondkommission AB 2 Dec 15, 2021
pureSxS - A tool to export Component Based Servicing packages from a full Windows installation

pureSxS A tool to export Component Based Servicing packages from a full Windows installation. Usage pureSxS.py source_mum destination pureSxS wor

Gamers Against Weed 3 Oct 03, 2022
WARP+ uses Cloudflare’s virtual private backbone, known as Argo, to achieve higher speeds and ensure your connection is encrypted across the long haul of the Internet

WARP+ uses Cloudflare’s virtual private backbone, known as Argo, to achieve higher speeds and ensure your connection is encrypted across the long haul of the Internet

Rivane Rasetiansyah 3 Apr 01, 2022
euserv auto-renew script - A Python script which can help you renew your free EUserv IPv6 VPS.

eu_ex eu_ex means EUserv_extend. A Python script which can help you renew your free EUserv IPv6 VPS. This Script can check the VPS amount in your acco

A beam of light 92 Jan 25, 2022
Repo used to maintain all notes and scripts developed during my DevNet Expert studies

DevNet Expert Studies Exam Date: TBD (Waiting for registration to open) This repository will be used to track my progress and maintain all notes/scrip

Dan 32 Dec 11, 2022
mitm6 is a pentesting tool that exploits the default configuration of Windows to take over the default DNS server.

mitm6 is a pentesting tool that exploits the default configuration of Windows to take over the default DNS server.

Fox-IT 1.3k Jan 05, 2023
Network monitoring tool

netmeter If you are looking for a tool to monitor your network interfaces, here you are. See netmeter-exporter to export Prometheus metrics. Installat

Saeid Bostandoust 97 Dec 03, 2022
API for concurrency connections

Multi-connection-server-API API for concurrency connections difference between this server and the echo server is the call to lsock.setblocking(False)

Muziwandile Nkomo 1 Jan 04, 2022
Python module to interface with Tuya WiFi smart devices

TinyTuya Python module to interface with Tuya WiFi smart devices Description This python module controls and monitors Tuya compatible WiFi Smart Devic

Jason Cox 365 Dec 26, 2022
A python socket.io client for Roboteur

Roboteur Client Example TODO Basic setup Install the requirements: $ pip install -r requirements.txt Run the application: $ python -m roboteur_client

Barry Buck 1 Oct 13, 2021
Jogo da forca simples com conexão entre cliente e servidor utilizando TCP.

JogoDaForcaTCP Um jogo da forca simples com conexão entre cliente e servidor utilizando o protocólo TCP. Como jogar: Habilite a porta 20000, inicie o

Kelvin Santos 1 Dec 01, 2021
A Python package for handling free proxies from sslproxies.org

SSLProxies Get free working proxy from https://www.sslproxies.org/ and use it in your script This is a port/rewrite of free-proxy with additional feat

Nate Harris 2 Mar 17, 2022
DNSStager is an open-source project based on Python used to hide and transfer your payload using DNS.

What is DNSStager? DNSStager is an open-source project based on Python used to hide and transfer your payload using DNS. DNSStager will create a malic

Askar 547 Dec 20, 2022
Modern Denial-of-service ToolKit for python

💣 Impulse Modern Denial-of-service ToolKit 💻 Main window 📡 Methods: Method Target Description SMS PHONE Sends a massive amount of SMS messages and

1 Nov 29, 2021
Python script to stop qBittorrent from torrenting without VPN for users with static IP.

Python script to stop qBittorrent from torrenting without VPN for users with static IP.

voidoak_ 1 Oct 25, 2021