πŸ‘¨πŸΌβ€πŸ’» β€Žβ€Žβ€Žβ€β€ 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)
This is the code repository for the USENIX Security 2021 paper, "Weaponizing Middleboxes for TCP Reflected Amplification".

weaponizing-censors Censors pose a threat to the entire Internet. In this work, we show that censoring middleboxes and firewalls can be weaponized by

UMD Breakerspace 119 Dec 31, 2022
Truetool - A TrueCharts automatic and bulk update utility

truetool A easy tool for frequently used TrueNAS SCALE CLI utilities. Previously

TrueCharts 125 Jan 04, 2023
VRF-StarkNet - Contracts for verifiable randomness on StarkNet

VRF-StarkNet Contracts for verifiable randomness on StarkNet Motivation Deployed

Non 32 Oct 30, 2022
Dos attack a Bluetooth connection!

Bluetooth Denial of service Script made for attacking Bluetooth Devices By Samrat Katwal. Warning This project was created only for fun purposes and p

Samrat 1 Oct 29, 2021
A vpn that sits in your browser, accessible via a website

VPNInYourBrowser A vpn that sits in your browser, accessible via a website Example setup: https://VPNInBrowser.jaffa42.repl.co Setup Put the code onto

1 Jan 20, 2022
Burp Extension that copies a request and builds a FFUF skeleton

ffuf is gaining a lot of traction within the infosec community as a fast portable web fuzzer. It has been compared and aligned (kinda) to Burp's Intruder functionality. Thus, Copy As FFUF is trying t

Desmond Miles 81 Dec 22, 2022
PySocks lets you send traffic through SOCKS proxy servers.

PySocks lets you send traffic through SOCKS proxy servers. It is a modern fork of SocksiPy with bug fixes and extra features. Acts as a drop-i

1.1k Dec 07, 2022
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
Docker container for demoing Wi-Fi calling stack.

VoWiFiLocalDemo - Docker container that runs StrongSwan and Kamailio to demonstrate how Wi-Fi calling works on smartphones.

18 Nov 12, 2022
A simple implementation of an RPC toolkit

Simple RPC With Raw Sockets Repository for the Data network course project: Introduction In this project, you will attempt to code a simple implementa

Milad Samimifar 1 Mar 25, 2022
This is a Client-Server-System which can send audio from a microphone from the server to client and in the other direction.

Audio-Streaming-Python This is a Client-Server-System which can send audio from a microphone from the server to client and in the other direction. You

VFX / Videoeffects Creator 0 Jan 05, 2023
MoreIP δΈ€ζ¬ΎεŸΊδΊŽPythonηš„ι’ε‘ MacOS/Linux η”¨ζˆ·η”¨δΊŽζŸ₯θ―’IP/εŸŸεδΏ‘ζ―ηš„ζ—₯常渗透小ε·₯ε…·

MoreIP δΈ€ζ¬ΎεŸΊδΊŽPythonηš„ι’ε‘ MacOS/Linux η”¨ζˆ·η”¨δΊŽζŸ₯θ―’IP/εŸŸεδΏ‘ζ―ηš„ζ—₯常渗透小ε·₯ε…·

xq17 9 Sep 21, 2022
Arp Spoofer using Python 3.

ARP Spoofer / Wifi Killer By Auax Run: Run the application with the following command: python3 spoof.py -t target_ip_address -lh host_ip_address I

Auax 6 Sep 15, 2022
netpy - more than implementation of netcat 🐍πŸ”₯

netpy - more than implementation of netcat 🐍πŸ”₯

Mahmoud S. ElGammal 1 Jan 26, 2022
Terminal based chat - networking project with sockets in python

Terminal based chat - networking project with sockets in python

2 Jan 24, 2022
This program ingests a Cisco "sh ip arp" as a text file and produces the list of vendors seen in the file

IP-ARP-Vendor_lookup This program ingests a Cisco "sh ip arp" as a text file and produces the list of vendors seen in the file Why? Answers the questi

Stew Alexander 1 Dec 24, 2022
A p2p chat app for zephyr

A p2p chat app for zephyr

L3gacy B3ta 4 Jun 02, 2021
pfSense integration with Home Assistant

hass-pfsense Join pfSense with home-assistant! hass-pfsense uses the built-in xmlrpc service of pfSense for all interactions. No special plugins or so

Travis Glenn Hansen 105 Dec 24, 2022
The AKS cluster provisioner provisions AKS clusters :-)

Overview The AKS cluster provisioner provisions AKS clusters :-) It uses the Azure CLI to configure VNet and subnets before creating the cluster itsel

Gigi Sayfan 1 Nov 10, 2021
Simple local RPG turn-based to play while learn something using the anki system

Simple local RPG turn-based to play while learn something using the anki system

Raphael Kieling 5 Aug 02, 2022