👨🏼‍💻 ‎‎‎‏‏ 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)
Pesquise, filtre e obtenha informações sobre animes. ( Módulo PIP )

Pesquise, filtre e obtenha informações sobre animes. ( Módulo PIP )

AimCaffe 3 Jan 30, 2022
Socialhome is best described as a federated personal profile with social networking functionality

Description Socialhome is best described as a federated personal profile with social networking functionality. Users can create rich content using Mar

Jason Robinson 332 Dec 30, 2022
InfraGenie is allows you to split out your infrastructure project into separate independent pieces, each with its own terraform state.

🧞 InfraGenie InfraGenie is allows you to split out your infrastructure project into separate independent pieces, each with its own terraform state. T

Digger 53 Nov 23, 2022
A python tool auto change proxy or ip after dealy time set by user

Auto proxy Ghost This tool auto change proxy or ip after dealy time set by user how to run 1. Install required file ./requirements.sh 2.Enter command

Harsh Tagra 0 Feb 23, 2022
A simple DHCP server and client simulation with python

About The Project This is a simple DHCP server and client simulation. I implemented it for computer network course spring 2021 The client can request

shakiba 3 Feb 08, 2022
Decentra Network is an open source blockchain that combines speed, security and decentralization.

Decentra Network is an open source blockchain that combines speed, security and decentralization. Decentra Network has very high speeds, scalability, asymptotic security and complete decentralization

Decentra Network 74 Nov 22, 2022
This Tool can help enginners and biggener in network, the tool help you to find of any ip with subnet mask that can calucate them and show you ( Availble IP's , Subnet Mask, Network-ID, Broadcast-ID )

This Tool can help enginners and biggener in network, the tool help you to find of any ip with subnet mask that can calucate them and show you ( Availble IP's , Subnet Mask, Network-ID, Broadcast-ID

12 Dec 13, 2022
A python shell / chat bot for XMPP and cloud services

XMPP_Shell_Bot A python shell / chat bot for XMPP and cloud services, designed for penetration testers to bypass network filters. To better understand

Abdulkareem Aldeek 1 Jan 09, 2022
Using AWS's API Gateway + Lambda + Python to run a simple websocket application. For learning/testing

Using AWS's API Gateway + Lambda + Python to run a simple websocket application. For learning/testing. The AWS Resources seemed overly complex and were missing some critical gotchas in setting up a s

Seth Miller 15 Dec 23, 2022
Official ProtonVPN Linux app

ProtonVPN Linux App Copyright (c) 2021 Proton Technologies AG This repository holds the ProtonVPN Linux App. For licensing information see COPYING. Fo

ProtonVPN 288 Jan 01, 2023
Simple python script for automated network scans with random name generator(useful for CTF boxes).

📄 Automated NMAP script Description Simple python script for automated network scans with random name generator(useful for CTF boxes). Requirements 1

Dhmos Funk 2 Oct 29, 2021
Huawei firewall automatically updates Chinese ip to target IP group.

Huawei firewall automatically updates Chinese ip to target IP group.

Lundaa 0 Jan 11, 2022
BLE parser for passive BLE advertisements

This pypi package is parsing BLE advertisements to readable data for several sensors and can be used for device tracking, as long as the MAC address is static. The parser was originally developed as

Ernst Klamer 19 Dec 26, 2022
Tool for ROS 2 IP Discovery + System Monitoring

Monitor the status of computers on a network using the DDS function of ROS2.

Ar-Ray 33 Apr 03, 2022
Query protocol and response

whois Query protocol and response _MᵃˢᵗᵉʳBᵘʳⁿᵗ_ _ ( ) _ ( )( ) _ | | ( ) | || |__ _ (_) ___ | | | | | || _ `\ /'_`\ | |/',__) |

MasterBurnt 4 Sep 05, 2021
A lightweight python script that can monitor the T-Mobile Home Internet Nokia 5G Gateway for band and connectivity and reboot as needed.

tmo-monitor A lightweight Python 3 script that can monitor the T-Mobile Home Internet Nokia 5G Gateway for band and connectivity and reboot as needed.

61 Dec 17, 2022
GlokyPortScannar is a really fast tool to scan TCP ports implemented in Python.

GlokyPortScannar is a really fast tool to scan TCP ports implemented in Python. Installation: This program requires Python 3.9. Linux

gl0ky 5 Jun 25, 2022
MQTT Explorer - MQTT Subscriber client to explore topic hierarchies

mqtt-explorer MQTT Explorer - MQTT Subscriber client to explore topic hierarchies Overview The MQTT Explorer subscriber client is designed to explore

Gambit Communications, Inc. 4 Jun 19, 2022
A SOCKS proxy server implemented with the powerful python cooperative concurrency framework asyncio.

asyncio-socks-server A SOCKS proxy server implemented with the powerful python cooperative concurrency framework asyncio. Features Supports both TCP a

Amaindex 164 Dec 30, 2022
Connects to databases or sftp server based on configured environmental variables.

Myconnections Connects to Oracle databases or sftp servers depending on configured environmental variables. VERY IMPORTANT: VPN must exist. Installati

0 Jan 02, 2022