repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_htpasswd.py | test/mitmproxy/utils/test_htpasswd.py | from pathlib import Path
import pytest
from mitmproxy.utils import htpasswd
def test_sha1():
ht = htpasswd.HtpasswdFile(
"user1:{SHA}8FePHnF0saQcTqjG4X96ijuIySo=\n"
"user2:{SHA}i+UhJqb95FCnFio2UdWJu1HpV50=\n"
"user3:{SHA}3ipNV1GrBtxPmHFC21fCbVCSXIo=:extra\n"
)
assert ht.check_password("user1", "pass1")
assert ht.check_password("user2", "pass2")
assert ht.check_password("user3", "pass3")
assert not ht.check_password("user1", "pass2")
assert not ht.check_password("wronguser", "testpassword")
def test_bcrypt():
ht = htpasswd.HtpasswdFile(
"user_bcrypt:$2b$05$opH8g9/PUhK6HVSnhdX7P.oB6MTMOlIlXgb4THm1Adh12t4IuqMsK\n"
)
assert ht.check_password("user_bcrypt", "pass")
assert not ht.check_password("user_bcrypt", "wrong")
@pytest.mark.parametrize(
"file_content, err_msg",
[
("malformed", "Malformed htpasswd line"),
(":malformed", "Malformed htpasswd line"),
("user_md5:$apr1$....", "Unsupported htpasswd format"),
("user_ssha:{SSHA}...", "Unsupported htpasswd format"),
("user_plain:pass", "Unsupported htpasswd format"),
("user_crypt:..j8N8I28nVM", "Unsupported htpasswd format"),
("user_empty_pw:", "Unsupported htpasswd format"),
],
)
def test_errors(file_content, err_msg):
with pytest.raises(ValueError, match=err_msg):
htpasswd.HtpasswdFile(file_content)
def test_from_file(tdata):
assert htpasswd.HtpasswdFile.from_file(
Path(tdata.path("mitmproxy/data/htpasswd"))
).users
def test_file_not_found():
with pytest.raises(OSError, match="Htpasswd file not found"):
htpasswd.HtpasswdFile.from_file(Path("/nonexistent"))
def test_empty_and_comments():
ht = htpasswd.HtpasswdFile("\n# comment\n \n\t# another comment\n")
assert not ht.users
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_sliding_window.py | test/mitmproxy/utils/test_sliding_window.py | from mitmproxy.utils import sliding_window
def test_simple():
y = list(sliding_window.window(range(1000, 1005), 1, 2))
assert y == [
# prev this next next2
(None, 1000, 1001, 1002),
(1000, 1001, 1002, 1003),
(1001, 1002, 1003, 1004),
(1002, 1003, 1004, None),
(1003, 1004, None, None),
]
def test_is_lazy():
done = False
def gen():
nonlocal done
done = True
yield 42
x = sliding_window.window(gen(), 1, 1)
assert not done
assert list(x)
assert done
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_typecheck.py | test/mitmproxy/utils/test_typecheck.py | import io
import typing
from collections.abc import Sequence
from typing import Any
from typing import Optional
from typing import TextIO
from typing import Union
import pytest
from mitmproxy.utils import typecheck
class TBase:
def __init__(self, bar: int):
pass
class T(TBase):
def __init__(self, foo: str):
super().__init__(42)
def test_check_option_type():
typecheck.check_option_type("foo", 42, int)
typecheck.check_option_type("foo", 42, float)
with pytest.raises(TypeError):
typecheck.check_option_type("foo", 42, str)
with pytest.raises(TypeError):
typecheck.check_option_type("foo", None, str)
with pytest.raises(TypeError):
typecheck.check_option_type("foo", b"foo", str)
def test_check_union():
typecheck.check_option_type("foo", 42, Union[int, str])
typecheck.check_option_type("foo", "42", Union[int, str])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", [], Union[int, str])
def test_check_tuple():
typecheck.check_option_type("foo", (42, "42"), tuple[int, str])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", None, tuple[int, str])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", (), tuple[int, str])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", (42, 42), tuple[int, str])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", ("42", 42), tuple[int, str])
def test_check_sequence():
typecheck.check_option_type("foo", [10], Sequence[int])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", ["foo"], Sequence[int])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", [10, "foo"], Sequence[int])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", [b"foo"], Sequence[str])
with pytest.raises(TypeError):
typecheck.check_option_type("foo", "foo", Sequence[str])
def test_check_io():
typecheck.check_option_type("foo", io.StringIO(), TextIO)
with pytest.raises(TypeError):
typecheck.check_option_type("foo", "foo", TextIO)
def test_check_any():
typecheck.check_option_type("foo", 42, Any)
typecheck.check_option_type("foo", object(), Any)
typecheck.check_option_type("foo", None, Any)
def test_typesec_to_str():
assert (typecheck.typespec_to_str(str)) == "str"
assert (typecheck.typespec_to_str(Sequence[str])) == "sequence of str"
assert (typecheck.typespec_to_str(Optional[str])) == "optional str"
assert (typecheck.typespec_to_str(Optional[int])) == "optional int"
with pytest.raises(NotImplementedError):
typecheck.typespec_to_str(dict)
def test_typing_aliases():
assert (typecheck.typespec_to_str(typing.Sequence[str])) == "sequence of str"
typecheck.check_option_type("foo", [10], typing.Sequence[int])
typecheck.check_option_type("foo", (42, "42"), tuple[int, str])
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_vt_codes.py | test/mitmproxy/utils/test_vt_codes.py | import io
from mitmproxy.utils.vt_codes import ensure_supported
def test_simple():
assert not ensure_supported(io.StringIO())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_asyncio_utils.py | test/mitmproxy/utils/test_asyncio_utils.py | import asyncio
import gc
import sys
import pytest
from mitmproxy.utils import asyncio_utils
async def ttask():
await asyncio.sleep(0)
asyncio_utils.set_current_task_debug_info(name="newname")
await asyncio.sleep(999)
async def test_simple(monkeypatch):
monkeypatch.setenv("PYTEST_CURRENT_TEST", "test_foo")
task = asyncio_utils.create_task(
ttask(), name="ttask", keep_ref=True, client=("127.0.0.1", 42313)
)
assert (
asyncio_utils.task_repr(task)
== "127.0.0.1:42313: ttask [created in test_foo] (age: 0s)"
)
await asyncio.sleep(0)
await asyncio.sleep(0)
assert "newname" in asyncio_utils.task_repr(task)
delattr(task, "created")
assert asyncio_utils.task_repr(task)
async def _raise():
raise RuntimeError()
async def test_install_exception_handler():
e = asyncio.Event()
with asyncio_utils.install_exception_handler(lambda *_, **__: e.set()):
t = asyncio.create_task(_raise())
await asyncio.sleep(0)
assert t.done()
del t
gc.collect()
await e.wait()
async def test_eager_task_factory():
x = False
async def task():
nonlocal x
x = True
# assert that override works...
assert type(asyncio.get_event_loop_policy()) is asyncio.DefaultEventLoopPolicy
with asyncio_utils.set_eager_task_factory():
_ = asyncio.create_task(task())
if sys.version_info >= (3, 12):
# ...and the context manager is effective
assert x
@pytest.fixture()
def event_loop_policy(request):
# override EagerTaskCreationEventLoopPolicy from top-level conftest
return asyncio.DefaultEventLoopPolicy()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/__init__.py | test/mitmproxy/utils/__init__.py | python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false | |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_arg_check.py | test/mitmproxy/utils/test_arg_check.py | import contextlib
import io
from unittest import mock
import pytest
from mitmproxy.utils import arg_check
@pytest.mark.parametrize(
"arg, output",
[
(["-T"], "-T is deprecated, please use --mode transparent instead"),
(["-U"], "-U is deprecated, please use --mode upstream:SPEC instead"),
(
["--confdir"],
"--confdir is deprecated.\n"
"Please use `--set confdir=value` instead.\n"
"To show all options and their default values use --options",
),
(
["--palette"],
"--palette is deprecated.\n"
"Please use `--set console_palette=value` instead.\n"
"To show all options and their default values use --options",
),
(
["--wfile"],
"--wfile is deprecated.\nPlease use `--save-stream-file` instead.",
),
(["--eventlog"], "--eventlog has been removed."),
(
["--nonanonymous"],
"--nonanonymous is deprecated.\n"
"Please use `--proxyauth SPEC` instead.\n"
'SPEC Format: "username:pass", "any" to accept any user/pass combination,\n'
'"@path" to use an Apache htpasswd file, or\n'
'"ldap[s]:url_server_ldap[:port]:dn_auth:password:dn_subtree[?search_filter_key=...]" '
"for LDAP authentication.",
),
(
["--replacements"],
"--replacements is deprecated.\n"
"Please use `--modify-body` or `--modify-headers` instead.",
),
(
["--underscore_option"],
"--underscore_option uses underscores, please use hyphens --underscore-option",
),
],
)
def test_check_args(arg, output):
f = io.StringIO()
with contextlib.redirect_stdout(f):
with mock.patch("sys.argv") as m:
m.__getitem__.return_value = arg
arg_check.check()
assert f.getvalue().strip() == output
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_debug.py | test/mitmproxy/utils/test_debug.py | import io
import sys
from unittest import mock
import pytest
from mitmproxy.utils import debug
@pytest.mark.parametrize("precompiled", [True, False])
def test_dump_system_info_precompiled(precompiled):
sys.frozen = None
with mock.patch.object(sys, "frozen", precompiled):
assert ("binary" in debug.dump_system_info()) == precompiled
def test_dump_info():
cs = io.StringIO()
debug.dump_info(None, None, file=cs)
assert cs.getvalue()
assert "Tasks" not in cs.getvalue()
async def test_dump_info_async():
cs = io.StringIO()
debug.dump_info(None, None, file=cs)
assert "Tasks" in cs.getvalue()
def test_dump_stacks():
cs = io.StringIO()
debug.dump_stacks(None, None, file=cs)
assert cs.getvalue()
def test_register_info_dumpers():
debug.register_info_dumpers()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_spec.py | test/mitmproxy/utils/test_spec.py | import pytest
from mitmproxy.utils.spec import parse_spec
def test_parse_spec():
flow_filter, subject, replacement = parse_spec("/foo/bar/voing")
assert flow_filter.pattern == "foo"
assert subject == "bar"
assert replacement == "voing"
flow_filter, subject, replacement = parse_spec("/bar/voing")
assert flow_filter(1) is True
assert subject == "bar"
assert replacement == "voing"
with pytest.raises(ValueError, match="Invalid number of parameters"):
parse_spec("/")
with pytest.raises(ValueError, match="Invalid filter expression"):
parse_spec("/~b/one/two")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_signals.py | test/mitmproxy/utils/test_signals.py | from unittest import mock
import pytest
from mitmproxy.utils.signals import AsyncSignal
from mitmproxy.utils.signals import SyncSignal
def test_sync_signal() -> None:
m = mock.Mock()
s = SyncSignal(lambda event: None)
s.connect(m)
s.send("foo")
assert m.call_args_list == [mock.call("foo")]
class Foo:
called = None
def bound(self, event):
self.called = event
f = Foo()
s.connect(f.bound)
s.send(event="bar")
assert f.called == "bar"
assert m.call_args_list == [mock.call("foo"), mock.call(event="bar")]
s.disconnect(m)
s.send("baz")
assert f.called == "baz"
assert m.call_count == 2
def err(event):
raise RuntimeError
s.connect(err)
with pytest.raises(RuntimeError):
s.send(42)
def test_signal_weakref() -> None:
def m1():
pass
def m2():
pass
s = SyncSignal(lambda: None)
s.connect(m1)
s.connect(m2)
del m2
s.send()
assert len(s.receivers) == 1
def test_sync_signal_async_receiver() -> None:
s = SyncSignal(lambda: None)
with pytest.raises(AssertionError):
s.connect(mock.AsyncMock())
async def test_async_signal() -> None:
s = AsyncSignal(lambda event: None)
m1 = mock.AsyncMock()
m2 = mock.Mock()
s.connect(m1)
s.connect(m2)
await s.send("foo")
assert m1.call_args_list == m2.call_args_list == [mock.call("foo")]
s.disconnect(m2)
await s.send("bar")
assert m1.call_count == 2
assert m2.call_count == 1
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_emoji.py | test/mitmproxy/utils/test_emoji.py | from mitmproxy.tools.console.common import SYMBOL_MARK
from mitmproxy.utils import emoji
def test_emoji():
assert emoji.emoji[":default:"] == SYMBOL_MARK
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_strutils.py | test/mitmproxy/utils/test_strutils.py | import pytest
from mitmproxy.utils import strutils
def test_always_bytes():
assert strutils.always_bytes(bytes(range(256))) == bytes(range(256))
assert strutils.always_bytes("foo") == b"foo"
with pytest.raises(ValueError):
strutils.always_bytes("\u2605", "ascii")
with pytest.raises(TypeError):
strutils.always_bytes(42, "ascii")
def test_always_str():
with pytest.raises(TypeError):
strutils.always_str(42)
assert strutils.always_str("foo") == "foo"
assert strutils.always_str(b"foo") == "foo"
assert strutils.always_str(None) is None
def test_escape_control_characters():
assert strutils.escape_control_characters("one") == "one"
assert strutils.escape_control_characters("\00ne") == ".ne"
assert strutils.escape_control_characters("\nne") == "\nne"
assert strutils.escape_control_characters("\nne", False) == ".ne"
assert strutils.escape_control_characters("\u2605") == "\u2605"
assert (
strutils.escape_control_characters(bytes(bytearray(range(128))).decode())
== ".........\t\n..\r.................. !\"#$%&'()*+,-./0123456789:;<"
"=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~."
)
assert (
strutils.escape_control_characters(bytes(bytearray(range(128))).decode(), False)
== "................................ !\"#$%&'()*+,-./0123456789:;<"
"=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~."
)
with pytest.raises(ValueError):
strutils.escape_control_characters(b"foo")
def test_bytes_to_escaped_str():
assert strutils.bytes_to_escaped_str(b"foo") == "foo"
assert strutils.bytes_to_escaped_str(b"\b") == r"\x08"
assert strutils.bytes_to_escaped_str(rb"&!?=\)") == r"&!?=\\)"
assert strutils.bytes_to_escaped_str(b"\xc3\xbc") == r"\xc3\xbc"
assert strutils.bytes_to_escaped_str(b"'") == r"'"
assert strutils.bytes_to_escaped_str(b'"') == r'"'
assert strutils.bytes_to_escaped_str(b"'", escape_single_quotes=True) == r"\'"
assert strutils.bytes_to_escaped_str(b'"', escape_single_quotes=True) == r'"'
assert strutils.bytes_to_escaped_str(b"\r\n\t") == "\\r\\n\\t"
assert strutils.bytes_to_escaped_str(b"\r\n\t", True) == "\r\n\t"
assert strutils.bytes_to_escaped_str(b"\n", False) == r"\n"
assert strutils.bytes_to_escaped_str(b"\n", True) == "\n"
assert strutils.bytes_to_escaped_str(b"\\n", True) == "\\ \\ n".replace(" ", "")
assert strutils.bytes_to_escaped_str(b"\\\n", True) == "\\ \\ \n".replace(" ", "")
assert strutils.bytes_to_escaped_str(b"\\\\n", True) == "\\ \\ \\ \\ n".replace(
" ", ""
)
with pytest.raises(ValueError):
strutils.bytes_to_escaped_str("such unicode")
def test_escaped_str_to_bytes():
assert strutils.escaped_str_to_bytes("foo") == b"foo"
assert strutils.escaped_str_to_bytes("\x08") == b"\b"
assert strutils.escaped_str_to_bytes("&!?=\\\\)") == rb"&!?=\)"
assert strutils.escaped_str_to_bytes("\\x08") == b"\b"
assert strutils.escaped_str_to_bytes("&!?=\\\\)") == rb"&!?=\)"
assert strutils.escaped_str_to_bytes("\u00fc") == b"\xc3\xbc"
with pytest.raises(ValueError):
strutils.escaped_str_to_bytes(b"very byte")
def test_is_mostly_bin():
assert not strutils.is_mostly_bin(b"foo\xff")
assert strutils.is_mostly_bin(b"foo" + b"\xff" * 10)
assert not strutils.is_mostly_bin(b"")
assert strutils.is_mostly_bin(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09")
# shift UTF8 break point
# π
is four bytes in UTF-8, so we're breaking the 100 chars barrier.
assert not strutils.is_mostly_bin(b"" + 50 * "π
".encode())
assert not strutils.is_mostly_bin(b"a" + 50 * "π
".encode())
assert not strutils.is_mostly_bin(b"aa" + 50 * "π
".encode())
assert not strutils.is_mostly_bin(b"aaa" + 50 * "π
".encode())
assert not strutils.is_mostly_bin(b"aaaa" + 50 * "π
".encode())
assert not strutils.is_mostly_bin(b"aaaaa" + 50 * "π
".encode())
# only utf8 continuation chars
assert strutils.is_mostly_bin(150 * b"\x80")
def test_is_xml():
assert not strutils.is_xml(b"")
assert not strutils.is_xml(b"foo")
assert strutils.is_xml(b"<foo")
assert strutils.is_xml(b" \n<foo")
def test_clean_hanging_newline():
s = "foo\n"
assert strutils.clean_hanging_newline(s) == "foo"
assert strutils.clean_hanging_newline("foo") == "foo"
def test_hexdump():
assert list(strutils.hexdump(b"one\0" * 10))
ESCAPE_QUOTES = [
"'" + strutils.SINGLELINE_CONTENT + strutils.NO_ESCAPE + "'",
'"' + strutils.SINGLELINE_CONTENT + strutils.NO_ESCAPE + '"',
]
def test_split_special_areas():
assert strutils.split_special_areas("foo", ESCAPE_QUOTES) == ["foo"]
assert strutils.split_special_areas("foo 'bar' baz", ESCAPE_QUOTES) == [
"foo ",
"'bar'",
" baz",
]
assert strutils.split_special_areas("""foo 'b\\'a"r' baz""", ESCAPE_QUOTES) == [
"foo ",
"'b\\'a\"r'",
" baz",
]
assert strutils.split_special_areas(
"foo\n/*bar\nbaz*/\nqux", [r"/\*[\s\S]+?\*/"]
) == ["foo\n", "/*bar\nbaz*/", "\nqux"]
assert strutils.split_special_areas("foo\n//bar\nbaz", [r"//.+$"]) == [
"foo\n",
"//bar",
"\nbaz",
]
def test_escape_special_areas():
assert (
strutils.escape_special_areas('foo "bar" baz', ESCAPE_QUOTES, "*")
== 'foo "bar" baz'
)
esc = strutils.escape_special_areas('foo "b*r" b*z', ESCAPE_QUOTES, "*")
assert esc == 'foo "b\ue02ar" b*z'
assert strutils.unescape_special_areas(esc) == 'foo "b*r" b*z'
@pytest.mark.parametrize(
"content,n,expected",
[
("foo\nbar\nbaz", 1, "foo\n"),
("foo\nbar\nbaz", 2, "foo\nbar\n"),
("foo\nbar", 100, "foo\nbar"),
("\nbar", 1, "\n"),
],
)
def test_cut_after_n_newlines(content, n, expected):
assert strutils.cut_after_n_lines(content, n) == expected
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/utils/test_human.py | test/mitmproxy/utils/test_human.py | import time
import pytest
from mitmproxy.utils import human
def test_format_timestamp():
assert human.format_timestamp(time.time())
def test_format_timestamp_with_milli():
assert human.format_timestamp_with_milli(time.time())
def test_parse_size():
assert human.parse_size("0") == 0
assert human.parse_size("0b") == 0
assert human.parse_size("1") == 1
assert human.parse_size("1k") == 1024
assert human.parse_size("1m") == 1024**2
assert human.parse_size("1g") == 1024**3
with pytest.raises(ValueError):
human.parse_size("1f")
with pytest.raises(ValueError):
human.parse_size("ak")
assert human.parse_size(None) is None
def test_pretty_size():
assert human.pretty_size(0) == "0b"
assert human.pretty_size(100) == "100b"
assert human.pretty_size(1024) == "1.0k"
assert human.pretty_size(1024 + 512) == "1.5k"
assert human.pretty_size(1024 * 1024) == "1.0m"
assert human.pretty_size(10 * 1024 * 1024) == "10.0m"
assert human.pretty_size(100 * 1024 * 1024) == "100m"
def test_pretty_duration():
assert human.pretty_duration(0.00001) == "0ms"
assert human.pretty_duration(0.0001) == "0ms"
assert human.pretty_duration(0.001) == "1ms"
assert human.pretty_duration(0.01) == "10ms"
assert human.pretty_duration(0.1) == "100ms"
assert human.pretty_duration(1) == "1.00s"
assert human.pretty_duration(10) == "10.0s"
assert human.pretty_duration(100) == "100s"
assert human.pretty_duration(1000) == "1000s"
assert human.pretty_duration(10000) == "10000s"
assert human.pretty_duration(1.123) == "1.12s"
assert human.pretty_duration(0.123) == "123ms"
assert human.pretty_duration(None) == ""
def test_format_address():
assert human.format_address(("::1", "54010", "0", "0")) == "[::1]:54010"
assert (
human.format_address(("::ffff:127.0.0.1", "54010", "0", "0"))
== "127.0.0.1:54010"
)
assert human.format_address(("127.0.0.1", "54010")) == "127.0.0.1:54010"
assert human.format_address(("example.com", "54010")) == "example.com:54010"
assert human.format_address(("::", "8080")) == "*:8080"
assert human.format_address(("0.0.0.0", "8080")) == "*:8080"
assert human.format_address(None) == "<no address>"
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_javascript.py | test/mitmproxy/contentviews/test__view_javascript.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_javascript import beautify
from mitmproxy.contentviews._view_javascript import javascript
def test_view_javascript():
assert javascript.prettify(b"[1, 2, 3]", Metadata())
assert javascript.prettify(b"[1, 2, 3", Metadata())
assert javascript.prettify(b"function(a){[1, 2, 3]}", Metadata()) == (
"function(a) {\n [1, 2, 3]\n}\n"
)
assert javascript.prettify(b"\xfe", Metadata()) # invalid utf-8
@pytest.mark.parametrize(
"filename",
[
"simple.js",
],
)
def test_format_xml(filename, tdata):
path = tdata.path("mitmproxy/contentviews/test_js_data/" + filename)
with open(path) as f:
input = f.read()
with open("-formatted.".join(path.rsplit(".", 1))) as f:
expected = f.read()
js = beautify(input)
assert js == expected
def test_render_priority():
assert javascript.render_priority(
b"data", Metadata(content_type="application/x-javascript")
)
assert javascript.render_priority(
b"data", Metadata(content_type="application/javascript")
)
assert javascript.render_priority(b"data", Metadata(content_type="text/javascript"))
assert not javascript.render_priority(b"data", Metadata(content_type="text/plain"))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_socketio.py | test/mitmproxy/contentviews/test__view_socketio.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_socketio import EngineIO
from mitmproxy.contentviews._view_socketio import parse_packet
from mitmproxy.contentviews._view_socketio import socket_io
from mitmproxy.contentviews._view_socketio import SocketIO
from mitmproxy.test import tflow
def test_parse_packet():
assert parse_packet(b"0payload") == (EngineIO.OPEN, b"payload")
assert parse_packet(b"40") == (SocketIO.CONNECT, b"")
assert parse_packet(b"40payload") == (SocketIO.CONNECT, b"payload")
def test_view():
with pytest.raises(Exception):
socket_io.prettify(b"HTTP/1.1", Metadata())
with pytest.raises(Exception):
socket_io.prettify(b"GET", Metadata())
assert socket_io.prettify(b"0", Metadata())
assert socket_io.prettify(b"6", Metadata())
assert socket_io.prettify(b"40", Metadata())
with pytest.raises(Exception):
socket_io.prettify(b"4", Metadata())
assert socket_io.prettify(b"42", Metadata())
assert socket_io.prettify(b"42eventdata", Metadata())
assert socket_io.prettify(b"2", Metadata()) == ""
def test_render_priority():
assert not socket_io.render_priority(b"", Metadata())
flow = tflow.twebsocketflow()
assert not socket_io.render_priority(b"", Metadata(flow=flow))
assert not socket_io.render_priority(b"message", Metadata(flow=flow))
flow.request.path = b"/asdf/socket.io/?..."
assert socket_io.render_priority(b"message", Metadata(flow=flow))
assert not socket_io.render_priority(b"", Metadata(flow=flow))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_graphql.py | test/mitmproxy/contentviews/test__view_graphql.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_graphql import format_graphql
from mitmproxy.contentviews._view_graphql import format_query_list
from mitmproxy.contentviews._view_graphql import graphql
def test_render_priority():
assert 2 == graphql.render_priority(
b"""{"query": "query P { \\n }"}""", Metadata(content_type="application/json")
)
assert 2 == graphql.render_priority(
b"""[{"query": "query P { \\n }"}]""", Metadata(content_type="application/json")
)
assert 0 == graphql.render_priority(
b"""[{"query": "query P { \\n }"}]""", Metadata(content_type="text/html")
)
assert 0 == graphql.render_priority(
b"""[{"xquery": "query P { \\n }"}]""",
Metadata(content_type="application/json"),
)
assert 0 == graphql.render_priority(
b"""[]""", Metadata(content_type="application/json")
)
assert 0 == graphql.render_priority(b"}", Metadata(content_type="application/json"))
def test_format_graphql():
assert format_graphql({"query": "query P { \\n }"})
def test_format_query_list():
assert format_query_list([{"query": "query P { \\n }"}])
def test_view_graphql():
assert graphql.prettify(
b"""{"query": "query P { \\n }"}""", Metadata(content_type="application/json")
)
assert graphql.prettify(
b"""[{"query": "query P { \\n }"}]""", Metadata(content_type="application/json")
)
with pytest.raises(ValueError):
assert graphql.prettify(b'"valid json"', Metadata())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__api.py | test/mitmproxy/contentviews/test__api.py | import typing
from pathlib import Path
from ruamel.yaml import YAML
import mitmproxy_rs.syntax_highlight
from mitmproxy.contentviews._api import Contentview
from mitmproxy.contentviews._api import InteractiveContentview
from mitmproxy.contentviews._api import Metadata
from mitmproxy.contentviews._api import SyntaxHighlight
from mitmproxy.contentviews._view_raw import raw
from mitmproxy.test import tflow
from mitmproxy_rs.contentviews import _test_inspect_metadata
from mitmproxy_rs.contentviews import msgpack
class ExampleContentview(InteractiveContentview):
def prettify(self, data: bytes, metadata: Metadata) -> str:
return data.decode()
def reencode(self, prettified: str, metadata: Metadata) -> bytes:
return prettified.encode()
class FailingPrettifyContentview(Contentview):
def prettify(self, data, metadata):
raise ValueError("prettify error")
def render_priority(self, data: bytes, metadata: Metadata) -> float:
return 1
class FailingRenderPriorityContentview(Contentview):
def prettify(self, data, metadata):
return data.decode()
def render_priority(self, data: bytes, metadata: Metadata) -> float:
raise ValueError("render_priority error")
def test_simple():
view = ExampleContentview()
assert view.name == "Example"
assert view.render_priority(b"test", Metadata()) == 0
assert view.syntax_highlight == "none"
assert not (view < view)
def test_default_impls():
t = ExampleContentview()
assert t.name == "Example"
assert t.syntax_highlight == "none"
assert t.render_priority(b"data", Metadata()) == 0
assert t < raw
assert not raw < t
class TestRustInterop:
def test_syntaxhighlight_matches(self):
assert (
list(typing.get_args(SyntaxHighlight.__value__))
== mitmproxy_rs.syntax_highlight.languages()
)
def test_compare(self):
assert msgpack < raw
assert not raw < msgpack
assert not msgpack < msgpack
def test_metadata(self):
"""Ensure that metadata roundtrips properly."""
f = tflow.tflow()
f.request.headers["HoSt"] = "example.com"
meta = Metadata(
content_type="text/html",
flow=f,
http_message=f.request,
protobuf_definitions=Path("example.proto"),
)
out = _test_inspect_metadata.prettify(b"", meta)
actual = YAML(typ="safe", pure=True).load(out)
assert actual == {
"content_type": "text/html",
"headers": {"host": "example.com"},
"is_http_request": True,
"path": "/path",
"protobuf_definitions": "example.proto",
}
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__utils.py | test/mitmproxy/contentviews/test__utils.py | from mitmproxy import tcp
from mitmproxy.contentviews._utils import byte_pairs_to_str_pairs
from mitmproxy.contentviews._utils import get_data
from mitmproxy.contentviews._utils import make_metadata
from mitmproxy.contentviews._utils import merge_repeated_keys
from mitmproxy.contentviews._utils import yaml_dumps
from mitmproxy.contentviews._utils import yaml_loads
from mitmproxy.test import taddons
from mitmproxy.test import tflow
class TestMetadata:
def test_make_metadata_http(self):
with taddons.context():
f = tflow.tflow()
metadata = make_metadata(f.request, f)
assert metadata.http_message == f.request
assert metadata.flow == f
assert metadata.content_type is None
f = tflow.tflow(resp=True)
f.response.headers["content-type"] = "application/json"
metadata = make_metadata(f.response, f)
assert metadata.http_message == f.response
assert metadata.flow == f
assert metadata.content_type == "application/json"
def test_make_metadata_tcp(self):
with taddons.context():
f = tflow.ttcpflow()
msg = f.messages[0]
metadata = make_metadata(msg, f)
assert metadata.tcp_message == msg
assert metadata.flow == f
def test_make_metadata_udp(self):
with taddons.context():
f = tflow.tudpflow()
msg = f.messages[0]
metadata = make_metadata(msg, f)
assert metadata.udp_message == msg
assert metadata.flow == f
def test_make_metadata_websocket(self):
with taddons.context():
f = tflow.twebsocketflow()
msg = f.websocket.messages[0]
metadata = make_metadata(msg, f)
assert metadata.websocket_message == msg
assert metadata.flow == f
def test_make_metadata_dns(self):
with taddons.context():
f = tflow.tdnsflow()
msg = f.request
metadata = make_metadata(msg, f)
assert metadata.dns_message == msg
assert metadata.flow == f
class TestGetData:
def test_get_data_regular_content(self):
msg = tcp.TCPMessage(True, b"hello")
content, enc = get_data(msg)
assert content == b"hello"
assert enc == ""
def test_get_data_http(self):
f = tflow.tflow()
f.request.headers["content-encoding"] = "gzip"
f.request.content = b"content"
assert f.request.raw_content != f.request.content
content, enc = get_data(f.request)
assert content == b"content"
assert enc == "[decoded gzip]"
def test_get_data_http_decode_error(self):
f = tflow.tflow()
f.request.headers["content-encoding"] = "gzip"
f.request.raw_content = b"invalid"
content, enc = get_data(f.request)
assert content == b"invalid"
assert enc == "[cannot decode]"
def test_yaml_dumps():
assert yaml_dumps({}) == ""
assert yaml_dumps({"foo": "bar"}) == "foo: bar\n"
def test_yaml_loads():
assert yaml_loads("") is None
assert yaml_loads("foo: bar\n") == {"foo": "bar"}
def test_merge_repeated_keys():
assert merge_repeated_keys([]) == {}
assert merge_repeated_keys([("foo", "bar")]) == {"foo": "bar"}
assert merge_repeated_keys([("foo", "bar"), ("foo", "baz")]) == {
"foo": ["bar", "baz"]
}
assert merge_repeated_keys(
[
("foo", "bar"),
("foo", "baz"),
("foo", "qux"),
("bar", "quux"),
]
) == {"foo": ["bar", "baz", "qux"], "bar": "quux"}
def test_byte_pairs_to_str_pairs():
assert list(byte_pairs_to_str_pairs([(b"foo", b"bar")])) == [("foo", "bar")]
assert list(byte_pairs_to_str_pairs([(b"\xfa", b"\xff")])) == [(r"\xfa", r"\xff")]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_json.py | test/mitmproxy/contentviews/test__view_json.py | import pytest
from mitmproxy.contentviews import json_view
from mitmproxy.contentviews import Metadata
def test_view_json():
meta = Metadata()
assert json_view.prettify(b"null", meta)
assert json_view.prettify(b"{}", meta)
with pytest.raises(ValueError):
assert not json_view.prettify(b"{", meta)
assert json_view.prettify(b"[1, 2, 3, 4, 5]", meta)
assert json_view.prettify(b'{"foo" : 3}', meta)
assert json_view.prettify(b'{"foo": true, "nullvalue": null}', meta)
assert json_view.prettify(b"[]", meta)
assert json_view.syntax_highlight == "yaml"
def test_view_json_nonascii():
"""https://github.com/mitmproxy/mitmproxy/issues/7739"""
assert (
json_view.prettify('{"a": "ζ₯ζ¬θͺ"}'.encode(), Metadata())
== '{\n "a": "ζ₯ζ¬θͺ"\n}'
)
def test_render_priority():
assert json_view.render_priority(b"data", Metadata(content_type="application/json"))
assert json_view.render_priority(
b"data", Metadata(content_type="application/json-rpc")
)
assert json_view.render_priority(
b"data", Metadata(content_type="application/vnd.api+json")
)
assert json_view.render_priority(
b"data", Metadata(content_type="application/acme+json")
)
assert not json_view.render_priority(b"data", Metadata(content_type="text/plain"))
assert not json_view.render_priority(b"", Metadata(content_type="application/json"))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test_base.py | test/mitmproxy/contentviews/test_base.py | import pytest
from mitmproxy.contentviews import base
def test_format_dict():
d = {"one": "two", "three": "four"}
with pytest.deprecated_call():
f_d = base.format_dict(d)
assert next(f_d)
d = {"adsfa": ""}
with pytest.deprecated_call():
f_d = base.format_dict(d)
assert next(f_d)
d = {}
with pytest.deprecated_call():
f_d = base.format_dict(d)
with pytest.raises(StopIteration):
next(f_d)
def test_format_pairs():
d = [("a", "c"), ("b", "d")]
with pytest.deprecated_call():
f_d = base.format_pairs(d)
assert next(f_d)
d = [("abc", "")]
with pytest.deprecated_call():
f_d = base.format_pairs(d)
assert next(f_d)
d = []
with pytest.deprecated_call():
f_d = base.format_pairs(d)
with pytest.raises(StopIteration):
next(f_d)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test___init__.py | test/mitmproxy/contentviews/test___init__.py | from .test__api import FailingPrettifyContentview
from mitmproxy.contentviews import ContentviewRegistry
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews import prettify_message
from mitmproxy.contentviews import raw
from mitmproxy.contentviews import registry
from mitmproxy.test import taddons
from mitmproxy.test import tflow
def test_view_selection():
assert registry.get_view(b"foo", Metadata()).name == "Raw"
assert (
registry.get_view(b"<html></html>", Metadata(content_type="text/html")).name
== "XML/HTML"
)
assert (
registry.get_view(b"foo", Metadata(content_type="text/flibble")).name == "Raw"
)
assert (
registry.get_view(b"<xml></xml>", Metadata(content_type="text/flibble")).name
== "XML/HTML"
)
assert (
registry.get_view(b"<svg></svg>", Metadata(content_type="image/svg+xml")).name
== "XML/HTML"
)
assert (
registry.get_view(b"{}", Metadata(content_type="application/acme+json")).name
== "JSON"
)
assert (
registry.get_view(
b"verybinary", Metadata(content_type="image/new-magic-image-format")
).name
== "Image"
)
assert registry.get_view(b"\xff" * 30, Metadata()).name == "Hex Dump"
assert registry.get_view(b"", Metadata()).name == "Raw"
class TestPrettifyMessage:
def test_empty_content(self):
with taddons.context():
f = tflow.tflow()
f.request.content = None
result = prettify_message(f.request, f)
assert result.text == "Content is missing."
assert result.syntax_highlight == "error"
assert result.view_name is None
def test_hex_stream(self):
with taddons.context():
f = tflow.tflow()
f.request.content = b"content"
result = prettify_message(f.request, f, "hex stream")
assert result.text == "636f6e74656e74" # hex representation of "content"
assert result.syntax_highlight == "none"
assert result.view_name == "Hex Stream"
def test_view_failure_auto(self):
registry = ContentviewRegistry()
with taddons.context():
f = tflow.tflow()
f.request.content = b"content"
failing_view = FailingPrettifyContentview()
registry.register(failing_view)
registry.register(raw)
result = prettify_message(f.request, f, registry=registry)
assert result.text == "content"
assert result.syntax_highlight == "none"
assert result.view_name == "Raw"
assert "[failed to parse as FailingPrettify]" in result.description
def test_view_failure_explicit(self):
registry = ContentviewRegistry()
with taddons.context():
f = tflow.tflow()
f.request.content = b"content"
failing_view = FailingPrettifyContentview()
registry.register(failing_view)
result = prettify_message(f.request, f, "failing", registry=registry)
assert "Couldn't parse as FailingPrettify" in result.text
assert result.syntax_highlight == "error"
assert result.view_name == "FailingPrettify"
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_raw.py | test/mitmproxy/contentviews/test__view_raw.py | from mitmproxy.contentviews._api import Metadata
from mitmproxy.contentviews._view_raw import raw
def test_view_raw():
meta = Metadata()
assert raw.prettify(b"foo", meta)
# unicode
assert raw.prettify("π« ".encode(), meta) == "π« "
# invalid utf8
assert raw.prettify(b"\xff", meta) == r"\xff"
def test_render_priority():
assert raw.render_priority(b"data", Metadata()) == 0.1
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__compat.py | test/mitmproxy/contentviews/test__compat.py | from unittest import mock
import pytest
from mitmproxy.contentviews import _compat
from mitmproxy.contentviews.base import View
with pytest.deprecated_call():
class MockView(View):
def __init__(self, name: str = "mock"):
self._name = name
self.syntax_highlight = "python"
def __call__(self, data, content_type=None, flow=None, http_message=None):
return "description", [[("text", "content")]]
@property
def name(self) -> str:
return self._name
def render_priority(
self, data, content_type=None, flow=None, http_message=None
):
return 1.0
def test_legacy_contentview():
mock_view = MockView()
legacy_view = _compat.LegacyContentview(mock_view)
# Test name property
assert legacy_view.name == "mock"
# Test syntax_highlight property
assert legacy_view.syntax_highlight == "python"
# Test render_priority
data = b"test data"
metadata = _compat.Metadata(content_type="text/plain", flow=None, http_message=None)
assert legacy_view.render_priority(data, metadata) == 1.0
# Test prettify
result = legacy_view.prettify(data, metadata)
assert result == "content"
def test_get():
mock_view = MockView()
# Test with existing view
with mock.patch("mitmproxy.contentviews.registry", {"mock": mock_view}):
with pytest.deprecated_call():
view = _compat.get("mock")
assert view == mock_view
# Test with non-existent view
with mock.patch("mitmproxy.contentviews.registry", {}):
with pytest.deprecated_call():
view = _compat.get("nonexistent")
assert view is None
def test_remove():
# The remove function is deprecated and does nothing, but we should still test it
mock_view = MockView()
with pytest.deprecated_call():
_compat.remove(mock_view) # Should not raise any exceptions
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_mqtt.py | test/mitmproxy/contentviews/test__view_mqtt.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_mqtt import mqtt
@pytest.mark.parametrize(
"data,expected_text",
[
pytest.param(b"\xc0\x00", "[PINGREQ]", id="PINGREQ"),
pytest.param(b"\xd0\x00", "[PINGRESP]", id="PINGRESP"),
pytest.param(
b"\x90\x00", "Packet type SUBACK is not supported yet!", id="SUBACK"
),
pytest.param(
b"\xa0\x00",
"Packet type UNSUBSCRIBE is not supported yet!",
id="UNSUBSCRIBE",
),
pytest.param(
b"\x82\x31\x00\x03\x00\x2cxxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/in\x01",
"[SUBSCRIBE] sent topic filters: 'xxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/in'",
id="SUBSCRIBE",
),
pytest.param(
b"""\x32\x9a\x01\x00\x2dxxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/out\x00\x04"""
b"""{"body":{"parameters":null},"header":{"from":"56:6F:5E:6A:01:05","messageId":"connected","type":"event"}}""",
"""[PUBLISH] '{"body":{"parameters":null},"header":{"from":"56:6F:5E:6A:01:05","""
""""messageId":"connected","type":"event"}}' to topic 'xxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/out'""",
id="PUBLISH",
),
pytest.param(
b"""\x10\xba\x01\x00\x04MQTT\x04\x06\x00\x1e\x00\x1156:6F:5E:6A:01:05\x00-"""
b"""xxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/out"""
b"""\x00l{"body":{"parameters":null},"header":{"from":"56:6F:5E:6A:01:05","messageId":"disconnected","type":"event"}}""",
(
"[CONNECT]\n"
"\n"
"Client Id: 56:6F:5E:6A:01:05\n"
"Will Topic: xxxx/yy/zzzzzz/56:6F:5E:6A:01:05/messages/out\n"
"Will Message: "
'{"body":{"parameters":null},"header":{"from":"56:6F:5E:6A:01:05","messageId":"disconnected","type":"event"}}\n'
"User Name: None\n"
"Password: None\n"
),
id="CONNECT",
),
],
)
def test_view_mqtt(data, expected_text):
"""testing helper for single line messages"""
assert mqtt.prettify(data, Metadata()) == expected_text
@pytest.mark.parametrize("data", [b"\xc0\xff\xff\xff\xff"])
def test_mqtt_malformed(data):
with pytest.raises(Exception):
mqtt.prettify(data, Metadata())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_wbxml.py | test/mitmproxy/contentviews/test__view_wbxml.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_wbxml import wbxml
datadir = "mitmproxy/contentviews/test_wbxml_data/"
def test_wbxml(tdata):
assert wbxml.prettify(b"\x03\x01\x6a\x00", Metadata()) == '<?xml version="1.0" ?>\n'
with pytest.raises(Exception):
wbxml.prettify(b"foo", Metadata())
# File taken from https://github.com/davidpshaw/PyWBXMLDecoder/tree/master/wbxml_samples
path = tdata.path(datadir + "data.wbxml")
with open(path, "rb") as f:
input = f.read()
with open("-formatted.".join(path.rsplit(".", 1))) as f:
expected = f.read()
assert wbxml.prettify(input, Metadata()) == expected
def test_render_priority():
assert wbxml.render_priority(
b"data", Metadata(content_type="application/vnd.wap.wbxml")
)
assert wbxml.render_priority(
b"data", Metadata(content_type="application/vnd.ms-sync.wbxml")
)
assert not wbxml.render_priority(b"data", Metadata(content_type="text/plain"))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__registry.py | test/mitmproxy/contentviews/test__registry.py | from unittest import mock
from mitmproxy.contentviews._api import Metadata
from mitmproxy.contentviews._registry import ContentviewRegistry
from test.mitmproxy.contentviews.test__api import ExampleContentview
from test.mitmproxy.contentviews.test__api import FailingRenderPriorityContentview
def test_register_triggers_on_change():
registry = ContentviewRegistry()
view = ExampleContentview()
callback = mock.Mock()
registry.on_change.connect(callback)
registry.register(view)
callback.assert_called_once_with(view)
def test_replace_view_triggers_on_change_and_logs(caplog):
registry = ContentviewRegistry()
view1 = ExampleContentview()
view2 = ExampleContentview()
callback = mock.Mock()
registry.on_change.connect(callback)
registry.register(view1)
callback.reset_mock()
with caplog.at_level("INFO"):
registry.register(view2)
callback.assert_called_once_with(view2)
assert "Replacing existing example contentview." in caplog.text
def test_dunder_methods():
registry = ContentviewRegistry()
view = ExampleContentview()
registry.register(view)
assert list(registry) == ["example"]
assert registry["example"] == view
assert registry["EXAMPLE"] == view
assert len(registry) == 1
assert registry.available_views() == ["auto", "example"]
def test_get_view_unknown_name(caplog):
registry = ContentviewRegistry()
view = ExampleContentview()
registry.register(view)
with caplog.at_level("WARNING"):
result = registry.get_view(b"data", Metadata(), "unknown")
assert result == view
assert "Unknown contentview 'unknown', selecting best match instead." in caplog.text
def test_render_priority_error(caplog):
registry = ContentviewRegistry()
view = FailingRenderPriorityContentview()
registry.register(view)
registry.register(ExampleContentview)
v = registry.get_view(b"data", Metadata())
assert v.name == "Example"
assert "Error in FailingRenderPriority.render_priority" in caplog.text
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_css.py | test/mitmproxy/contentviews/test__view_css.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_css import css
@pytest.mark.parametrize(
"filename",
[
"animation-keyframe.css",
"blank-lines-and-spaces.css",
"block-comment.css",
"empty-rule.css",
"import-directive.css",
"indentation.css",
"media-directive.css",
"quoted-string.css",
"selectors.css",
"simple.css",
],
)
def test_beautify(filename, tdata):
path = tdata.path("mitmproxy/contentviews/test_css_data/" + filename)
with open(path, "rb") as f:
input = f.read()
with open("-formatted.".join(path.rsplit(".", 1))) as f:
expected = f.read()
formatted = css.prettify(input, Metadata())
assert formatted == expected
def test_simple():
meta = Metadata()
assert css.prettify(b"#foo{color:red}", meta) == "#foo {\n color: red\n}\n"
assert css.prettify(b"", meta) == "\n"
assert (
css.prettify(b"console.log('not really css')", meta)
== "console.log('not really css')\n"
)
def test_render_priority():
assert css.render_priority(b"data", Metadata(content_type="text/css"))
assert not css.render_priority(b"data", Metadata(content_type="text/plain"))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/__init__.py | test/mitmproxy/contentviews/__init__.py | python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false | |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_urlencoded.py | test/mitmproxy/contentviews/test__view_urlencoded.py | from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_urlencoded import urlencoded
from mitmproxy.net.http import url
def test_view_urlencoded():
d = url.encode([("one", "two"), ("three", "four")]).encode()
assert urlencoded.prettify(d, Metadata()) == "one: two\nthree: four\n"
d = url.encode([("adsfa", "")]).encode()
assert urlencoded.prettify(d, Metadata()) == "adsfa: ''\n"
assert urlencoded.prettify(b"\xff\x00", Metadata()) == "\\xff\\x00: ''\n"
def test_render_priority():
assert urlencoded.render_priority(
b"data", Metadata(content_type="application/x-www-form-urlencoded")
)
assert not urlencoded.render_priority(b"data", Metadata(content_type="text/plain"))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_http3.py | test/mitmproxy/contentviews/test__view_http3.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_http3 import http3
from mitmproxy.tcp import TCPMessage
from mitmproxy.test import tflow
@pytest.mark.parametrize(
"data",
[
# HEADERS
b"\x01\x1d\x00\x00\xd1\xc1\xd7P\x8a\x08\x9d\\\x0b\x81p\xdcx\x0f\x03_P\x88%\xb6P\xc3\xab\xbc\xda\xe0\xdd",
# broken HEADERS
b"\x01\x1d\x00\x00\xd1\xc1\xd7P\x8a\x08\x9d\\\x0b\x81p\xdcx\x0f\x03_P\x88%\xb6P\xc3\xab\xff\xff\xff\xff",
# headers + data
(
b"\x01@I\x00\x00\xdb_'\x93I|\xa5\x89\xd3M\x1fj\x12q\xd8\x82\xa6\x0bP\xb0\xd0C\x1b_M\x90\xd0bXt\x1eT\xad\x8f~\xfdp"
b"\xeb\xc8\xc0\x97\x07V\x96\xd0z\xbe\x94\x08\x94\xdcZ\xd4\x10\x04%\x02\xe5\xc6\xde\xb8\x17\x14\xc5\xa3\x7fT\x03315"
b'\x00A;<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">\r\n<HTML><HEAD><'
b'TITLE>Not Found</TITLE>\r\n<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>\r\n<BOD'
b"Y><h2>Not Found</h2>\r\n<hr><p>HTTP Error 404. The requested resource is not found.</p>\r\n</BODY></HTML>\r\n"
),
b"",
],
)
def test_view_http3(data):
t = tflow.ttcpflow(messages=[TCPMessage(from_client=len(data) > 16, content=data)])
t.metadata["quic_is_unidirectional"] = False
assert http3.prettify(b"", Metadata(flow=t, tcp_message=t.messages[0])) or not data
@pytest.mark.parametrize(
"data",
[
# SETTINGS
b"\x00\x04\r\x06\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x07\x00",
# unknown setting
b"\x00\x04\r\x3f\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x07\x00",
# out of bounds
b"\x00\x04\r\x06\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x42\x00",
# incomplete
b"\x00\x04\r\x06\xff\xff\xff",
# QPACK encoder stream
b"\x02",
],
)
def test_view_http3_unidirectional(data):
t = tflow.ttcpflow(messages=[TCPMessage(from_client=len(data) > 16, content=data)])
t.metadata["quic_is_unidirectional"] = True
assert http3.prettify(b"", Metadata(flow=t, tcp_message=t.messages[0]))
def test_render_priority():
assert not http3.render_priority(b"random stuff", Metadata())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_multipart.py | test/mitmproxy/contentviews/test__view_multipart.py | import pytest
from mitmproxy import http
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_multipart import multipart
def meta(content_type: str) -> Metadata:
return Metadata(
content_type=content_type.split(";")[0],
http_message=http.Request.make(
"POST", "https://example.com/", headers={"content-type": content_type}
),
)
def test_view_multipart():
v = b"""
--AaB03x
Content-Disposition: form-data; name="submit-name"
Larry
--AaB03x
""".strip()
assert (
multipart.prettify(v, meta("multipart/form-data; boundary=AaB03x"))
== "submit-name: Larry\n"
)
with pytest.raises(ValueError):
assert not multipart.prettify(v, Metadata())
assert not multipart.prettify(v, meta("multipart/form-data"))
assert not multipart.prettify(v, meta("unparseable"))
def test_render_priority():
assert multipart.render_priority(
b"data", Metadata(content_type="multipart/form-data")
)
assert not multipart.render_priority(b"data", Metadata(content_type="text/plain"))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_xml_html.py | test/mitmproxy/contentviews/test__view_xml_html.py | import pytest
from mitmproxy import http
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_xml_html import tokenize
from mitmproxy.contentviews._view_xml_html import xml_html
datadir = "mitmproxy/contentviews/test_xml_html_data/"
def test_simple(tdata):
assert xml_html.prettify(b"foo", Metadata()) == "foo\n"
assert xml_html.prettify(b"<html></html>", Metadata()) == "<html></html>\n"
assert xml_html.prettify(b"<>", Metadata()) == "<>\n"
assert xml_html.prettify(b"<p", Metadata()) == "<p\n"
with open(tdata.path(datadir + "simple.html")) as f:
input = f.read()
tokens = tokenize(input)
assert str(next(tokens)) == "Tag(<!DOCTYPE html>)"
def test_use_text():
meta1 = Metadata()
meta2 = Metadata(
http_message=http.Response.make(
content=b"\xf8",
)
)
assert xml_html.prettify(b"\xf8", meta1) != "ΓΈ\n"
assert xml_html.prettify(b"\xf8", meta2) == "ΓΈ\n"
@pytest.mark.parametrize(
"filename", ["simple.html", "cdata.xml", "comment.xml", "inline.html", "test.html"]
)
def test_format_xml(filename, tdata):
path = tdata.path(datadir + filename)
with open(path, "rb") as f:
input = f.read()
with open("-formatted.".join(path.rsplit(".", 1))) as f:
expected = f.read()
assert xml_html.prettify(input, Metadata()) == expected
def test_render_priority():
assert xml_html.render_priority(b"data", Metadata(content_type="text/xml"))
assert xml_html.render_priority(b"data", Metadata(content_type="text/xml"))
assert xml_html.render_priority(b"data", Metadata(content_type="text/html"))
assert not xml_html.render_priority(b"data", Metadata(content_type="text/plain"))
assert not xml_html.render_priority(b"", Metadata(content_type="text/xml"))
assert xml_html.render_priority(b"<html/>", Metadata())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_dns.py | test/mitmproxy/contentviews/test__view_dns.py | import struct
import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_dns import dns
from mitmproxy.tcp import TCPMessage
DNS_HTTPS_RECORD_RESPONSE = bytes.fromhex(
"00008180000100010000000107746c732d656368036465760000410001c00c004100010000003c00520001000005004b0049fe0d00"
"452b00200020015881d41a3e2ef8f2208185dc479245d20624ddd0918a8056f2e26af47e2628000800010001000100034012707562"
"6c69632e746c732d6563682e646576000000002904d0000000000000"
)
DNS_A_QUERY = bytes.fromhex("002a0100000100000000000003646e7306676f6f676c650000010001")
TCP_MESSAGE = struct.pack("!H", len(DNS_A_QUERY)) + DNS_A_QUERY
def test_simple():
assert (
dns.prettify(DNS_HTTPS_RECORD_RESPONSE, Metadata())
== r"""id: 0
query: false
op_code: QUERY
authoritative_answer: false
truncation: false
recursion_desired: true
recursion_available: true
response_code: NOERROR
questions:
- name: tls-ech.dev
type: HTTPS
class: IN
answers:
- name: tls-ech.dev
type: HTTPS
class: IN
ttl: 60
data:
target_name: ''
priority: 1
ech: \x00I\xfe\r\x00E+\x00 \x00 \x01X\x81\xd4\x1a>.\xf8\xf2
\x81\x85\xdcG\x92E\xd2\x06$\xdd\xd0\x91\x8a\x80V\xf2\xe2j\xf4~&(\x00\x08\x00\x01\x00\x01\x00\x01\x00\x03@\x12public.tls-ech.dev\x00\x00
authorities: []
additionals:
- name: ''
type: OPT
class: CLASS(1232)
ttl: 0
data: 0x
size: 82
"""
)
def test_invalid():
with pytest.raises(Exception):
dns.prettify(b"foobar", Metadata())
def test_tcp():
assert "type: A" in dns.prettify(
TCP_MESSAGE, Metadata(tcp_message=TCPMessage(False, TCP_MESSAGE, 946681204.2))
)
def test_roundtrip():
meta = Metadata()
assert dns.reencode(dns.prettify(DNS_A_QUERY, meta), meta) == DNS_A_QUERY
def test_render_priority():
assert dns.render_priority(b"", Metadata(content_type="application/dns-message"))
assert not dns.render_priority(b"", Metadata(content_type="text/plain"))
assert not dns.render_priority(b"", Metadata())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/test__view_query.py | test/mitmproxy/contentviews/test__view_query.py | import pytest
from mitmproxy.contentviews import Metadata
from mitmproxy.contentviews._view_query import query
from mitmproxy.test import tutils
def test_view_query():
d = ""
req = tutils.treq()
req.query = [("foo", "bar"), ("foo", "baz")]
out = query.prettify(d, Metadata(http_message=req))
assert out == "foo:\n- bar\n- baz\n"
with pytest.raises(ValueError):
query.prettify(d, Metadata())
def test_render_priority():
req = tutils.treq()
req.query = [("foo", "bar"), ("foo", "baz")]
assert query.render_priority(b"", Metadata(http_message=req))
assert not query.render_priority(b"", Metadata())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/_view_image/test_view.py | test/mitmproxy/contentviews/_view_image/test_view.py | from mitmproxy.contentviews import image
from mitmproxy.contentviews import Metadata
def test_view_image(tdata):
for img in [
"mitmproxy/data/image.png",
"mitmproxy/data/image.gif",
"mitmproxy/data/all.jpeg",
"mitmproxy/data/image.ico",
]:
with open(tdata.path(img), "rb") as f:
desc = image.prettify(f.read(), Metadata())
assert img.split(".")[-1].upper() in desc
assert image.prettify(b"flibble", Metadata()) == ("# Unknown Image\n")
def test_render_priority():
assert image.render_priority(b"", Metadata(content_type="image/png"))
assert image.render_priority(b"", Metadata(content_type="image/jpeg"))
assert image.render_priority(b"", Metadata(content_type="image/gif"))
assert image.render_priority(b"", Metadata(content_type="image/vnd.microsoft.icon"))
assert image.render_priority(b"", Metadata(content_type="image/x-icon"))
assert image.render_priority(b"", Metadata(content_type="image/webp"))
assert image.render_priority(
b"", Metadata(content_type="image/future-unknown-format-42")
)
assert not image.render_priority(b"", Metadata(content_type="image/svg+xml"))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/_view_image/test_image_parser.py | test/mitmproxy/contentviews/_view_image/test_image_parser.py | import pytest
from mitmproxy.contentviews._view_image import image_parser
@pytest.mark.parametrize(
"filename, metadata",
{
# no textual data
"mitmproxy/data/image_parser/ct0n0g04.png": [
("Format", "Portable network graphics"),
("Size", "32 x 32 px"),
("gamma", "1.0"),
],
# with textual data
"mitmproxy/data/image_parser/ct1n0g04.png": [
("Format", "Portable network graphics"),
("Size", "32 x 32 px"),
("gamma", "1.0"),
("Title", "PngSuite"),
("Author", "Willem A.J. van Schaik\n(willem@schaik.com)"),
("Copyright", "Copyright Willem van Schaik, Singapore 1995-96"),
(
"Description",
"A compilation of a set of images created to test the\n"
"various color-types of the PNG format. Included are\nblack&white, color,"
" paletted, with alpha channel, with\ntransparency formats. All bit-depths"
" allowed according\nto the spec are present.",
),
("Software", 'Created on a NeXTstation color using "pnmtopng".'),
("Disclaimer", "Freeware."),
],
# with compressed textual data
"mitmproxy/data/image_parser/ctzn0g04.png": [
("Format", "Portable network graphics"),
("Size", "32 x 32 px"),
("gamma", "1.0"),
("Title", "PngSuite"),
("Author", "Willem A.J. van Schaik\n(willem@schaik.com)"),
("Copyright", "Copyright Willem van Schaik, Singapore 1995-96"),
(
"Description",
"A compilation of a set of images created to test the\n"
"various color-types of the PNG format. Included are\nblack&white, color,"
" paletted, with alpha channel, with\ntransparency formats. All bit-depths"
" allowed according\nto the spec are present.",
),
("Software", 'Created on a NeXTstation color using "pnmtopng".'),
("Disclaimer", "Freeware."),
],
# UTF-8 international text - english
"mitmproxy/data/image_parser/cten0g04.png": [
("Format", "Portable network graphics"),
("Size", "32 x 32 px"),
("gamma", "1.0"),
("Title", "PngSuite"),
("Author", "Willem van Schaik (willem@schaik.com)"),
("Copyright", "Copyright Willem van Schaik, Canada 2011"),
(
"Description",
"A compilation of a set of images created to test the "
"various color-types of the PNG format. Included are black&white, color,"
" paletted, with alpha channel, with transparency formats. All bit-depths"
" allowed according to the spec are present.",
),
("Software", 'Created on a NeXTstation color using "pnmtopng".'),
("Disclaimer", "Freeware."),
],
# check gamma value
"mitmproxy/data/image_parser/g07n0g16.png": [
("Format", "Portable network graphics"),
("Size", "32 x 32 px"),
("gamma", "0.7"),
],
# check aspect value
"mitmproxy/data/image_parser/aspect.png": [
("Format", "Portable network graphics"),
("Size", "1280 x 798 px"),
("aspect", "72 x 72"),
("date:create", "2012-07-11T14:04:52-07:00"),
("date:modify", "2012-07-11T14:04:52-07:00"),
],
}.items(),
)
def test_parse_png(filename, metadata, tdata):
with open(tdata.path(filename), "rb") as f:
assert metadata == image_parser.parse_png(f.read())
@pytest.mark.parametrize(
"filename, metadata",
{
# check comment
"mitmproxy/data/image_parser/hopper.gif": [
("Format", "Compuserve GIF"),
("Version", "GIF89a"),
("Size", "128 x 128 px"),
("background", "0"),
("comment", "b'File written by Adobe Photoshop\\xa8 4.0'"),
],
# check background
"mitmproxy/data/image_parser/chi.gif": [
("Format", "Compuserve GIF"),
("Version", "GIF89a"),
("Size", "320 x 240 px"),
("background", "248"),
("comment", "b'Created with GIMP'"),
],
# check working with color table
"mitmproxy/data/image_parser/iss634.gif": [
("Format", "Compuserve GIF"),
("Version", "GIF89a"),
("Size", "245 x 245 px"),
("background", "0"),
],
}.items(),
)
def test_parse_gif(filename, metadata, tdata):
with open(tdata.path(filename), "rb") as f:
assert metadata == image_parser.parse_gif(f.read())
@pytest.mark.parametrize(
"filename, metadata",
{
# check app0
"mitmproxy/data/image_parser/example.jpg": [
("Format", "JPEG (ISO 10918)"),
("jfif_version", "(1, 1)"),
("jfif_density", "(96, 96)"),
("jfif_unit", "1"),
("Size", "256 x 256 px"),
],
# check com
"mitmproxy/data/image_parser/comment.jpg": [
("Format", "JPEG (ISO 10918)"),
("jfif_version", "(1, 1)"),
("jfif_density", "(96, 96)"),
("jfif_unit", "1"),
("comment", "mitmproxy test image"),
("Size", "256 x 256 px"),
],
# check app1
"mitmproxy/data/image_parser/app1.jpeg": [
("Format", "JPEG (ISO 10918)"),
("jfif_version", "(1, 1)"),
("jfif_density", "(72, 72)"),
("jfif_unit", "1"),
("make", "Canon"),
("model", "Canon PowerShot A60"),
("modify_date", "2004:07:16 18:46:04"),
("Size", "717 x 558 px"),
],
# check multiple segments
"mitmproxy/data/image_parser/all.jpeg": [
("Format", "JPEG (ISO 10918)"),
("jfif_version", "(1, 1)"),
("jfif_density", "(300, 300)"),
("jfif_unit", "1"),
(
"comment",
"BARTOLOMEO DI FRUOSINO\r\n(b. ca. 1366, Firenze, d. 1441, "
"Firenze)\r\n\r\nInferno, from the Divine Comedy by Dante (Folio 1v)"
"\r\n1430-35\r\nTempera, gold, and silver on parchment, 365 x 265 mm"
"\r\nBiblioth\\xe8que Nationale, Paris\r\n\r\nThe codex in Paris "
"contains the text of the Inferno, the first of three books of the Divine "
"Comedy, the masterpiece of the Florentine poet Dante Alighieri (1265-1321)."
" The codex begins with two full-page illuminations. On folio 1v Dante and "
"Virgil stand within the doorway of Hell at the upper left and observe its "
"nine different zones. Dante and Virgil are to wade through successive "
"circles teeming with images of the damned. The gates of Hell appear in "
"the middle, a scarlet row of open sarcophagi before them. Devils orchestrate"
" the movements of the wretched souls.\r\n\r\nThe vision of the fiery "
'inferno follows a convention established by <A onclick="return OpenOther'
'(\'/html/n/nardo/strozzi3.html\')" HREF="/html/n/nardo/strozzi3.html">'
"Nardo di Cione's fresco</A> in the church of Santa Maria Novella, Florence."
" Of remarkable vivacity and intensity of expression, the illumination is "
"executed in Bartolomeo's late style.\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
"--- Keywords: --------------\r\n\r\nAuthor: BARTOLOMEO DI FRUOSINO"
"\r\nTitle: Inferno, from the Divine Comedy by Dante (Folio 1v)\r\nTime-line:"
" 1401-1450\r\nSchool: Italian\r\nForm: illumination\r\nType: other\r\n",
),
("Size", "750 x 1055 px"),
],
}.items(),
)
def test_parse_jpeg(filename, metadata, tdata):
with open(tdata.path(filename), "rb") as f:
assert metadata == image_parser.parse_jpeg(f.read())
# fmt: off
@pytest.mark.parametrize(
"filename, metadata",
{
"mitmproxy/data/image.ico": [
("Format", "ICO"),
("Number of images", "3"),
(
"Image 1",
"Size: {} x {}\n"
"{: >18}Bits per pixel: {}\n"
"{: >18}PNG: {}".format(48, 48, "", 24, "", False),
),
(
"Image 2",
"Size: {} x {}\n"
"{: >18}Bits per pixel: {}\n"
"{: >18}PNG: {}".format(32, 32, "", 24, "", False),
),
(
"Image 3",
"Size: {} x {}\n"
"{: >18}Bits per pixel: {}\n"
"{: >18}PNG: {}".format(16, 16, "", 24, "", False),
),
]
}.items(),
)
def test_ico(filename, metadata, tdata):
with open(tdata.path(filename), "rb") as f:
assert metadata == image_parser.parse_ico(f.read())
# fmt: on
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/contentviews/_view_image/__init__.py | test/mitmproxy/contentviews/_view_image/__init__.py | python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false | |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/script/test_concurrent.py | test/mitmproxy/script/test_concurrent.py | import asyncio
import os
import time
import pytest
from mitmproxy.test import taddons
from mitmproxy.test import tflow
class TestConcurrent:
@pytest.mark.parametrize(
"addon", ["concurrent_decorator.py", "concurrent_decorator_class.py"]
)
async def test_concurrent(self, addon, tdata):
with taddons.context() as tctx:
sc = tctx.script(tdata.path(f"mitmproxy/data/addonscripts/{addon}"))
f1, f2 = tflow.tflow(), tflow.tflow()
start = time.time()
await asyncio.gather(
tctx.cycle(sc, f1),
tctx.cycle(sc, f2),
)
end = time.time()
# This test may fail on overloaded CI systems, increase upper bound if necessary.
if os.environ.get("CI"):
assert 0.5 <= end - start
else:
assert 0.5 <= end - start < 1
def test_concurrent_err(self, tdata, caplog):
with taddons.context() as tctx:
tctx.script(
tdata.path("mitmproxy/data/addonscripts/concurrent_decorator_err.py")
)
assert "decorator not supported" in caplog.text
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/script/__init__.py | test/mitmproxy/script/__init__.py | python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false | |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/import_error.py | test/mitmproxy/data/addonscripts/import_error.py | import nonexistent
nonexistent.foo()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/stream_modify.py | test/mitmproxy/data/addonscripts/stream_modify.py | import logging
def modify(chunks):
for chunk in chunks:
yield chunk.replace(b"foo", b"bar")
def running():
logging.info("stream_modify running")
def responseheaders(flow):
flow.response.stream = modify
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/tcp_stream_modify.py | test/mitmproxy/data/addonscripts/tcp_stream_modify.py | def tcp_message(flow):
message = flow.messages[-1]
if not message.from_client:
message.content = message.content.replace(b"foo", b"bar")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/error.py | test/mitmproxy/data/addonscripts/error.py | import logging
def load(loader):
logging.info("error load")
def request(flow):
raise ValueError("Error!")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/load_error.py | test/mitmproxy/data/addonscripts/load_error.py | def load(_):
raise ValueError()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/concurrent_decorator_class.py | test/mitmproxy/data/addonscripts/concurrent_decorator_class.py | import time
from mitmproxy.script import concurrent
class ConcurrentClass:
@concurrent
def request(self, flow):
time.sleep(0.25)
@concurrent
async def requestheaders(self, flow):
time.sleep(0.25)
addons = [ConcurrentClass()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/concurrent_decorator.py | test/mitmproxy/data/addonscripts/concurrent_decorator.py | import time
from mitmproxy.script import concurrent
@concurrent
def request(flow):
time.sleep(0.25)
@concurrent
async def requestheaders(flow):
time.sleep(0.25)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/shutdown.py | test/mitmproxy/data/addonscripts/shutdown.py | from mitmproxy import ctx
def running():
ctx.master.shutdown()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/addon.py | test/mitmproxy/data/addonscripts/addon.py | import logging
event_log = []
class Addon:
@property
def event_log(self):
return event_log
def load(self, opts):
logging.info("addon running")
event_log.append("addonload")
def configure(self, updated):
event_log.append("addonconfigure")
def configure(updated):
event_log.append("scriptconfigure")
def load(loader):
event_log.append("scriptload")
addons = [Addon()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/configure.py | test/mitmproxy/data/addonscripts/configure.py | from typing import Optional
from mitmproxy import exceptions
class OptionAddon:
def load(self, loader):
loader.add_option(
name="optionaddon",
typespec=Optional[int],
default=None,
help="Option Addon",
)
def configure(self, updates):
raise exceptions.OptionsError("Options Error")
addons = [OptionAddon()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/concurrent_decorator_err.py | test/mitmproxy/data/addonscripts/concurrent_decorator_err.py | from mitmproxy.script import concurrent
@concurrent
def load(v):
pass
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/same_filename/addon.py | test/mitmproxy/data/addonscripts/same_filename/addon.py | foo = 42
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/recorder/e.py | test/mitmproxy/data/addonscripts/recorder/e.py | import recorder
addons = [recorder.Recorder("e")]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/recorder/b.py | test/mitmproxy/data/addonscripts/recorder/b.py | import recorder
addons = [recorder.Recorder("b")]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/recorder/a.py | test/mitmproxy/data/addonscripts/recorder/a.py | import recorder
addons = [recorder.Recorder("a")]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/recorder/recorder.py | test/mitmproxy/data/addonscripts/recorder/recorder.py | import logging
from mitmproxy import hooks
class Recorder:
call_log = []
def __init__(self, name="recorder"):
self.name = name
def __getattr__(self, attr):
if attr in hooks.all_hooks and attr != "add_log":
def prox(*args, **kwargs):
lg = (self.name, attr, args, kwargs)
logging.info(str(lg))
self.call_log.append(lg)
logging.debug(f"{self.name} {attr}")
return prox
raise AttributeError
addons = [Recorder()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/addonscripts/recorder/c.py | test/mitmproxy/data/addonscripts/recorder/c.py | import recorder
addons = [recorder.Recorder("c")]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/data/servercert/generate.py | test/mitmproxy/data/servercert/generate.py | import pathlib
import shutil
src = pathlib.Path("../../net/data/verificationcerts")
here = pathlib.Path(".")
shutil.copy(src / "9da13359.0", "9da13359.0")
for x in ["self-signed", "trusted-leaf", "trusted-root"]:
(here / f"{x}.pem").write_text(
(src / f"{x}.crt").read_text() + (src / f"{x}.key").read_text()
)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/io/test_io.py | test/mitmproxy/io/test_io.py | import io
from pathlib import Path
import pytest
from hypothesis import example
from hypothesis import given
from hypothesis.strategies import binary
from mitmproxy import exceptions
from mitmproxy import version
from mitmproxy.io import FlowReader
from mitmproxy.io import tnetstring
here = Path(__file__).parent.parent / "data"
class TestFlowReader:
@given(binary())
@example(b"51:11:12345678901#4:this,8:true!0:~,4:true!0:]4:\\x00,~}")
@example(b"0:")
@example(b"0:~")
def test_fuzz(self, data):
f = io.BytesIO(data)
reader = FlowReader(f)
try:
for _ in reader.stream():
pass
except exceptions.FlowReadException:
pass # should never raise anything else.
@pytest.mark.parametrize(
"file", [pytest.param(x, id=x.stem) for x in here.glob("har_files/*.har")]
)
def test_har(self, file):
with open(file, "rb") as f:
reader = FlowReader(f)
try:
for _ in reader.stream():
pass
except exceptions.FlowReadException:
pass # should never raise anything else.
def test_empty(self):
assert list(FlowReader(io.BytesIO(b"")).stream()) == []
def test_unknown_type(self):
with pytest.raises(exceptions.FlowReadException, match="Unknown flow type"):
weird_flow = tnetstring.dumps(
{"type": "unknown", "version": version.FLOW_FORMAT_VERSION}
)
for _ in FlowReader(io.BytesIO(weird_flow)).stream():
pass
def test_cannot_migrate(self):
with pytest.raises(
exceptions.FlowReadException,
match="cannot read files with flow format version 0",
):
for _ in FlowReader(io.BytesIO(b"14:7:version;1:0#}")).stream():
pass
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/io/test_har.py | test/mitmproxy/io/test_har.py | import json
from pathlib import Path
import pytest
from mitmproxy import exceptions
from mitmproxy.io.har import fix_headers
from mitmproxy.io.har import request_to_flow
from mitmproxy.tools.web.app import flow_to_json
data_dir = Path(__file__).parent.parent / "data"
def hardcode_variable_fields_for_tests(flow: dict) -> None:
flow["id"] = "hardcoded_for_test"
flow["timestamp_created"] = 0
flow["server_conn"]["id"] = "hardcoded_for_test"
flow["client_conn"]["id"] = "hardcoded_for_test"
def file_to_flows(path_name: Path) -> list[dict]:
file_json = json.loads(path_name.read_bytes())["log"]["entries"]
flows = []
for entry in file_json:
expected = request_to_flow(entry)
flow_json = flow_to_json(expected)
hardcode_variable_fields_for_tests(flow_json)
flows.append(flow_json)
return flows
def test_corrupt():
file_json = json.loads(
Path(data_dir / "corrupted_har/broken_headers.json").read_bytes()
)
with pytest.raises(exceptions.OptionsError):
fix_headers(file_json["headers"])
@pytest.mark.parametrize(
"har_file", [pytest.param(x, id=x.stem) for x in data_dir.glob("har_files/*.har")]
)
def test_har_to_flow(har_file: Path):
expected_file = har_file.with_suffix(".json")
expected_flows = json.loads(expected_file.read_bytes())
actual_flows = file_to_flows(har_file)
for expected, actual in zip(expected_flows, actual_flows):
actual = json.loads(json.dumps(actual))
assert actual == expected
if __name__ == "__main__":
for path_name in data_dir.glob("har_files/*.har"):
print(path_name)
flows = file_to_flows(path_name)
with open(data_dir / f"har_files/{path_name.stem}.json", "w") as f:
json.dump(flows, f, indent=4)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/io/test_compat.py | test/mitmproxy/io/test_compat.py | import pytest
from mitmproxy import exceptions
from mitmproxy import io
@pytest.mark.parametrize(
"dumpfile, url, count",
[
["dumpfile-011.mitm", "https://example.com/", 1],
["dumpfile-018.mitm", "https://www.example.com/", 1],
["dumpfile-019.mitm", "https://webrv.rtb-seller.com/", 1],
["dumpfile-7-websocket.mitm", "https://echo.websocket.org/", 6],
["dumpfile-7.mitm", "https://example.com/", 2],
["dumpfile-10.mitm", "https://example.com/", 1],
["dumpfile-19.mitm", "https://cloudflare-quic.com/", 1],
],
)
def test_load(tdata, dumpfile, url, count):
with open(tdata.path("mitmproxy/data/" + dumpfile), "rb") as f:
flow_reader = io.FlowReader(f)
flows = list(flow_reader.stream())
assert len(flows) == count
assert flows[-1].request.url.startswith(url)
def test_cannot_convert(tdata):
with open(tdata.path("mitmproxy/data/dumpfile-010.mitm"), "rb") as f:
flow_reader = io.FlowReader(f)
with pytest.raises(exceptions.FlowReadException):
list(flow_reader.stream())
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/io/test_tnetstring.py | test/mitmproxy/io/test_tnetstring.py | import io
import math
import random
import struct
import unittest
from mitmproxy.io import tnetstring
MAXINT = 2 ** (struct.Struct("i").size * 8 - 1) - 1
# fmt: off
FORMAT_EXAMPLES = {
b'0:}': {},
b'0:]': [],
b'51:5:hello,39:11:12345678901#4:this,4:true!0:~4:\x00\x00\x00\x00,]}':
{b'hello': [12345678901, b'this', True, None, b'\x00\x00\x00\x00']},
b'5:12345#': 12345,
b'12:this is cool,': b'this is cool',
b'19:this is unicode \xe2\x98\x85;': 'this is unicode \u2605',
b'0:,': b'',
b'0:;': '',
b'0:~': None,
b'4:true!': True,
b'5:false!': False,
b'10:\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00,': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'24:5:12345#5:67890#5:xxxxx,]': [12345, 67890, b'xxxxx'],
b'18:3:0.1^3:0.2^3:0.3^]': [0.1, 0.2, 0.3],
b'243:238:233:228:223:218:213:208:203:198:193:188:183:178:173:168:163:158:153:148:143:138:133:128:123:118:113:108:103:99:95:91:87:83:79:75:71:67:63:59:55:51:47:43:39:35:31:27:23:19:15:11:hello-there,]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]': [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[b'hello-there']]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] # noqa
}
# fmt: on
def get_random_object(random=random, depth=0):
"""Generate a random serializable object."""
# The probability of generating a scalar value increases as the depth increase.
# This ensures that we bottom out eventually.
if random.randint(depth, 10) <= 4:
what = random.randint(0, 1)
if what == 0:
n = random.randint(0, 10)
lst = []
for _ in range(n):
lst.append(get_random_object(random, depth + 1))
return lst
if what == 1:
n = random.randint(0, 10)
d = {}
for _ in range(n):
n = random.randint(0, 100)
k = str([random.randint(32, 126) for _ in range(n)])
d[k] = get_random_object(random, depth + 1)
return d
else:
what = random.randint(0, 4)
if what == 0:
return None
if what == 1:
return True
if what == 2:
return False
if what == 3:
if random.randint(0, 1) == 0:
return random.randint(0, MAXINT)
else:
return -1 * random.randint(0, MAXINT)
n = random.randint(0, 100)
return bytes(random.randint(32, 126) for _ in range(n))
class Test_Format(unittest.TestCase):
def test_roundtrip_format_examples(self):
for data, expect in FORMAT_EXAMPLES.items():
self.assertEqual(expect, tnetstring.loads(data))
self.assertEqual(expect, tnetstring.loads(tnetstring.dumps(expect)))
self.assertEqual((expect, b""), tnetstring.pop(memoryview(data)))
def test_roundtrip_format_random(self):
for _ in range(10):
v = get_random_object()
self.assertEqual(v, tnetstring.loads(tnetstring.dumps(v)))
self.assertEqual((v, b""), tnetstring.pop(memoryview(tnetstring.dumps(v))))
def test_roundtrip_format_unicode(self):
for _ in range(10):
v = get_random_object()
self.assertEqual(v, tnetstring.loads(tnetstring.dumps(v)))
self.assertEqual((v, b""), tnetstring.pop(memoryview(tnetstring.dumps(v))))
def test_roundtrip_big_integer(self):
# Recent Python versions do not like ints above 4300 digits, https://github.com/python/cpython/issues/95778
i1 = math.factorial(1557)
s = tnetstring.dumps(i1)
i2 = tnetstring.loads(s)
self.assertEqual(i1, i2)
class Test_FileLoading(unittest.TestCase):
def test_roundtrip_file_examples(self):
for data, expect in FORMAT_EXAMPLES.items():
s = io.BytesIO()
s.write(data)
s.write(b"OK")
s.seek(0)
self.assertEqual(expect, tnetstring.load(s))
self.assertEqual(b"OK", s.read())
s = io.BytesIO()
tnetstring.dump(expect, s)
s.write(b"OK")
s.seek(0)
self.assertEqual(expect, tnetstring.load(s))
self.assertEqual(b"OK", s.read())
def test_roundtrip_file_random(self):
for _ in range(10):
v = get_random_object()
s = io.BytesIO()
tnetstring.dump(v, s)
s.write(b"OK")
s.seek(0)
self.assertEqual(v, tnetstring.load(s))
self.assertEqual(b"OK", s.read())
def test_error_on_absurd_lengths(self):
s = io.BytesIO()
s.write(b"1000000000000:pwned!,")
s.seek(0)
with self.assertRaises(ValueError):
tnetstring.load(s)
self.assertEqual(s.read(1), b":")
def suite():
loader = unittest.TestLoader()
suite = unittest.TestSuite()
suite.addTest(loader.loadTestsFromTestCase(Test_Format))
suite.addTest(loader.loadTestsFromTestCase(Test_FileLoading))
return suite
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/mitmproxy/platform/test_pf.py | test/mitmproxy/platform/test_pf.py | import sys
import pytest
from mitmproxy.platform import pf
class TestLookup:
def test_simple(self, tdata):
if sys.platform == "freebsd10":
p = tdata.path("mitmproxy/data/pf02")
else:
p = tdata.path("mitmproxy/data/pf01")
with open(p, "rb") as f:
d = f.read()
assert pf.lookup("192.168.1.111", 40000, d) == ("5.5.5.5", 80)
assert pf.lookup("::ffff:192.168.1.111", 40000, d) == ("5.5.5.5", 80)
with pytest.raises(Exception, match="Could not resolve original destination"):
pf.lookup("192.168.1.112", 40000, d)
with pytest.raises(Exception, match="Could not resolve original destination"):
pf.lookup("192.168.1.111", 40001, d)
assert pf.lookup("2a01:e35:8bae:50f0:396f:e6c7:f4f1:f3db", 40002, d) == (
"2a03:2880:f21f:c5:face:b00c::167",
443,
)
with pytest.raises(Exception, match="Could not resolve original destination"):
pf.lookup("2a01:e35:8bae:50f0:396f:e6c7:f4f1:f3db", 40003, d)
with pytest.raises(Exception, match="Could not resolve original destination"):
pf.lookup("2a01:e35:face:face:face:face:face:face", 40003, d)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/linkify-changelog.py | test/helper_tools/linkify-changelog.py | #!/usr/bin/env python3
import re
from pathlib import Path
changelog = Path(__file__).parent / "../../CHANGELOG.md"
text = changelog.read_text(encoding="utf8")
text, n = re.subn(
r"\s*\(([^)]+)#(\d+)\)",
"\n (\\1[#\\2](https://github.com/mitmproxy/mitmproxy/issues/\\2))",
text,
)
changelog.write_text(text, encoding="utf8")
print(f"Linkified {n} issues and users.")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/loggrep.py | test/helper_tools/loggrep.py | #!/usr/bin/env python3
import fileinput
import re
import sys
if __name__ == "__main__":
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} port filenames")
sys.exit()
port = sys.argv[1]
matches = False
for line in fileinput.input(sys.argv[2:]):
if re.search(r"^\[|(\d+\.){3}", line):
matches = port in line
if matches:
print(line, end="")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/hunt_memory_leaks.py | test/helper_tools/hunt_memory_leaks.py | import collections
import gc
import os
import signal
from mitmproxy import flow
def load(loader):
signal.signal(signal.SIGUSR1, debug1)
signal.signal(signal.SIGUSR2, debug2)
print(f"Debug signal registered. Run the following commands for diagnostics:")
print()
print(f" kill -s USR1 {os.getpid()}")
print(f" kill -s USR2 {os.getpid()}")
print()
def debug1(*_):
print()
print("Before GC")
print("=======")
print("gc.get_stats", gc.get_stats())
print("gc.get_count", gc.get_count())
print("gc.get_threshold", gc.get_threshold())
gc.collect()
print()
print("After GC")
print("=======")
print("gc.get_stats", gc.get_stats())
print("gc.get_count", gc.get_count())
print("gc.get_threshold", gc.get_threshold())
print()
print("Memory")
print("=======")
for t, count in collections.Counter(
[str(type(o)) for o in gc.get_objects()]
).most_common(50):
print(count, t)
def debug2(*_):
print()
print("Flow References")
print("=======")
# gc.collect()
objs = tuple(gc.get_objects())
ignore = {id(objs)} # noqa
flows = 0
for i in range(len(objs)):
try:
is_flow = isinstance(objs[i], flow.Flow)
except Exception:
continue
if is_flow:
flows += 1
# print_refs(objs[i], ignore, set())
# break
del objs
print(f"{flows} flows found.")
def print_refs(x, ignore: set, seen: set, depth: int = 0, max_depth: int = 10):
if id(x) in ignore:
return
if id(x) in seen:
print(
" " * depth
+ "β "
+ repr(str(x))[1:60]
+ f" (\x1b[31mseen\x1b[0m: {id(x):x})"
)
return
else:
if depth == 0:
print("- " + repr(str(x))[1:60] + f" ({id(x):x})")
else:
print(" " * depth + "β " + repr(str(x))[1:60] + f" ({id(x):x})")
seen.add(id(x))
if depth == max_depth:
return
referrers = tuple(gc.get_referrers(x))
ignore.add(id(referrers))
for ref in referrers:
print_refs(ref, ignore, seen, depth + 1, max_depth)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/memoryleak2.py | test/helper_tools/memoryleak2.py | import secrets
from pathlib import Path
import objgraph
from mitmproxy import certs
if __name__ == "__main__":
store = certs.CertStore.from_store(
path=Path("~/.mitmproxy/").expanduser(), basename="mitmproxy", key_size=2048
)
store.STORE_CAP = 5
for _ in range(5):
store.get_cert(
commonname=secrets.token_hex(16).encode(), sans=[], organization=None
)
objgraph.show_growth()
for _ in range(20):
store.get_cert(
commonname=secrets.token_hex(16).encode(), sans=[], organization=None
)
print("====")
objgraph.show_growth()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/memoryleak.py | test/helper_tools/memoryleak.py | import gc
import threading
from OpenSSL import SSL
from pympler import muppy
from pympler import refbrowser
# import os
# os.environ["TK_LIBRARY"] = r"C:\Python27\tcl\tcl8.5"
# os.environ["TCL_LIBRARY"] = r"C:\Python27\tcl\tcl8.5"
# Also noteworthy: guppy, objgraph
step = 0
__memory_locals__ = True
def str_fun(obj):
if isinstance(obj, dict):
if "__memory_locals__" in obj:
return "(-locals-)"
if "self" in obj and isinstance(obj["self"], refbrowser.InteractiveBrowser):
return "(-browser-)"
return (
str(id(obj))
+ ": "
+ str(obj)[:100].replace("\r\n", "\\r\\n").replace("\n", "\\n")
)
def request(ctx, flow):
global step, ssl
print("==========")
print(f"GC: {gc.collect()}")
print(f"Threads: {threading.active_count()}")
step += 1
if step == 1:
all_objects = muppy.get_objects()
ssl = muppy.filter(all_objects, SSL.Connection)[0]
if step == 2:
ib = refbrowser.InteractiveBrowser(ssl, 2, str_fun, repeat=False)
del ssl # do this to unpollute view
ib.main(True)
# print("\r\n".join(str(x)[:100] for x in gc.get_referrers(ssl)))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/dumperview.py | test/helper_tools/dumperview.py | #!/usr/bin/env python3
import asyncio
import click
from mitmproxy.addons import dumper
from mitmproxy.test import taddons
from mitmproxy.test import tflow
def run_async(coro):
"""
Run the given async function in a new event loop.
This allows async functions to be called synchronously.
"""
loop = asyncio.new_event_loop()
try:
return loop.run_until_complete(coro)
finally:
loop.close()
def show(flow_detail, flows):
d = dumper.Dumper()
with taddons.context() as ctx:
ctx.configure(d, flow_detail=flow_detail)
for f in flows:
run_async(ctx.cycle(d, f))
@click.group()
def cli():
pass
@cli.command()
@click.option("--level", default=1, help="Detail level")
def tcp(level):
f1 = tflow.ttcpflow()
show(level, [f1])
@cli.command()
@click.option("--level", default=1, help="Detail level")
def udp(level):
f1 = tflow.tudpflow()
show(level, [f1])
@cli.command()
@click.option("--level", default=1, help="Detail level")
def large(level):
f1 = tflow.tflow(resp=True)
f1.response.headers["content-type"] = "text/html"
f1.response.content = b"foo bar voing\n" * 100
show(level, [f1])
@cli.command()
@click.option("--level", default=1, help="Detail level")
def small(level):
f1 = tflow.tflow(resp=True)
f1.response.headers["content-type"] = "text/html"
f1.response.content = b"<html><body>Hello!</body></html>"
f2 = tflow.tflow(err=True)
show(
level,
[
f1,
f2,
],
)
if __name__ == "__main__":
cli()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/passive_close.py | test/helper_tools/passive_close.py | import socketserver
from time import sleep
class service(socketserver.BaseRequestHandler):
def handle(self):
data = "dummy"
print("Client connected with ", self.client_address)
while True:
self.request.send(
"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 7\r\n\r\ncontent"
)
data = self.request.recv(1024)
if not len(data):
print("Connection closed by remote: ", self.client_address)
sleep(3600)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
server = ThreadedTCPServer(("", 1520), service)
server.serve_forever()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/test/helper_tools/inspect_dumpfile.py | test/helper_tools/inspect_dumpfile.py | #!/usr/bin/env python3
from pprint import pprint
import click
from mitmproxy.io import tnetstring
def read_tnetstring(input):
# tnetstring throw a ValueError on EOF, which is hard to catch
# because they raise ValueErrors for a couple of other reasons.
# Check for EOF to avoid this.
if not input.read(1):
return None
else:
input.seek(-1, 1)
return tnetstring.load(input)
@click.command()
@click.argument("input", type=click.File("rb"))
def inspect(input):
"""
pretty-print a dumpfile
"""
while True:
data = read_tnetstring(input)
if not data:
break
pprint(data)
if __name__ == "__main__":
inspect()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/build.py | docs/build.py | #!/usr/bin/env python3
import shutil
import subprocess
from pathlib import Path
here = Path(__file__).parent
for script in sorted((here / "scripts").glob("*.py")):
print(f"Generating output for {script.name}...")
out = subprocess.check_output(["python3", script.absolute()], cwd=here, text=True)
if out:
(here / "src" / "generated" / f"{script.stem}.html").write_text(
out, encoding="utf8"
)
if (here / "public").exists():
shutil.rmtree(here / "public")
subprocess.run(["hugo"], cwd=here / "src", check=True)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/api-events.py | docs/scripts/api-events.py | #!/usr/bin/env python3
import contextlib
import inspect
import textwrap
import typing
from pathlib import Path
from mitmproxy import addonmanager
from mitmproxy import hooks
from mitmproxy import log
from mitmproxy.proxy import layer
from mitmproxy.proxy import server_hooks
from mitmproxy.proxy.layers import dns
from mitmproxy.proxy.layers import modes
from mitmproxy.proxy.layers import quic
from mitmproxy.proxy.layers import tcp
from mitmproxy.proxy.layers import tls
from mitmproxy.proxy.layers import udp
from mitmproxy.proxy.layers import websocket
from mitmproxy.proxy.layers.http import _hooks as http
known = set()
def category(name: str, desc: str, hooks: list[type[hooks.Hook]]) -> None:
all_params = [
list(inspect.signature(hook.__init__, eval_str=True).parameters.values())[1:]
for hook in hooks
]
# slightly overengineered, but this was fun to write. Β―\_(γ)_/Β―
imports = set()
types = set()
for params in all_params:
for param in params:
try:
imports.add(inspect.getmodule(param.annotation).__name__)
for t in typing.get_args(param.annotation):
imports.add(inspect.getmodule(t).__name__)
except AttributeError:
raise ValueError(f"Missing type annotation: {params}")
imports.discard("builtins")
if types:
print(f"from typing import {', '.join(sorted(types))}")
print("import logging")
for imp in sorted(imports):
print(f"import {imp}")
print()
print(f"class {name}Events:")
print(f' """{desc}"""')
first = True
for hook, params in zip(hooks, all_params):
if first:
first = False
else:
print()
if hook.name in known:
raise RuntimeError(f"Already documented: {hook}")
known.add(hook.name)
doc = inspect.getdoc(hook)
print(f" @staticmethod")
print(f" def {hook.name}({', '.join(str(p) for p in params)}):")
print(textwrap.indent(f'"""\n{doc}\n"""', " "))
if params:
print(
f' logging.info(f"{hook.name}: {" ".join("{" + p.name + "=}" for p in params)}")'
)
else:
print(f' logging.info("{hook.name}")')
print("")
outfile = Path(__file__).parent.parent / "src" / "generated" / "events.py"
with outfile.open("w") as f, contextlib.redirect_stdout(f):
print("# This file is autogenerated, do not edit manually.")
category(
"Lifecycle",
"",
[
addonmanager.LoadHook,
hooks.RunningHook,
hooks.ConfigureHook,
hooks.DoneHook,
],
)
category(
"Connection",
"",
[
server_hooks.ClientConnectedHook,
server_hooks.ClientDisconnectedHook,
server_hooks.ServerConnectHook,
server_hooks.ServerConnectedHook,
server_hooks.ServerDisconnectedHook,
server_hooks.ServerConnectErrorHook,
],
)
category(
"HTTP",
"",
[
http.HttpRequestHeadersHook,
http.HttpRequestHook,
http.HttpResponseHeadersHook,
http.HttpResponseHook,
http.HttpErrorHook,
http.HttpConnectHook,
http.HttpConnectUpstreamHook,
http.HttpConnectedHook,
http.HttpConnectErrorHook,
],
)
category(
"DNS",
"",
[
dns.DnsRequestHook,
dns.DnsResponseHook,
dns.DnsErrorHook,
],
)
category(
"TCP",
"",
[
tcp.TcpStartHook,
tcp.TcpMessageHook,
tcp.TcpEndHook,
tcp.TcpErrorHook,
],
)
category(
"UDP",
"",
[
udp.UdpStartHook,
udp.UdpMessageHook,
udp.UdpEndHook,
udp.UdpErrorHook,
],
)
category(
"QUIC",
"",
[
quic.QuicStartClientHook,
quic.QuicStartServerHook,
],
)
category(
"TLS",
"",
[
tls.TlsClienthelloHook,
tls.TlsStartClientHook,
tls.TlsStartServerHook,
tls.TlsEstablishedClientHook,
tls.TlsEstablishedServerHook,
tls.TlsFailedClientHook,
tls.TlsFailedServerHook,
],
)
category(
"WebSocket",
"",
[
websocket.WebsocketStartHook,
websocket.WebsocketMessageHook,
websocket.WebsocketEndHook,
],
)
category(
"SOCKS5",
"",
[
modes.Socks5AuthHook,
],
)
category(
"AdvancedLifecycle",
"",
[
layer.NextLayerHook,
hooks.UpdateHook,
log.AddLogHook,
],
)
not_documented = set(hooks.all_hooks.keys()) - known
if not_documented:
raise RuntimeError(f"Not documented: {not_documented}")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/filters.py | docs/scripts/filters.py | #!/usr/bin/env python3
from mitmproxy import flowfilter
print('<table class="table filtertable"><tbody>')
for i in flowfilter.help:
print("<tr><th>%s</th><td>%s</td></tr>" % i)
print("</tbody></table>")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/api-render.py | docs/scripts/api-render.py | #!/usr/bin/env python3
import os
import shutil
import textwrap
from pathlib import Path
import pdoc.render_helpers
here = Path(__file__).parent
if os.environ.get("DOCS_ARCHIVE", False):
edit_url_map = {}
else:
edit_url_map = {
"mitmproxy": "https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/",
}
pdoc.render.configure(
template_directory=here / "pdoc-template",
edit_url_map=edit_url_map,
search=False,
)
# We can't configure Hugo, but we can configure pdoc.
pdoc.render_helpers.formatter.cssclass = "chroma pdoc-code"
modules = [
"mitmproxy.addonmanager",
"mitmproxy.certs",
"mitmproxy.connection",
"mitmproxy.contentviews",
"mitmproxy.coretypes.multidict",
"mitmproxy.dns",
"mitmproxy.flow",
"mitmproxy.http",
"mitmproxy.net.server_spec",
"mitmproxy.proxy.context",
"mitmproxy.proxy.mode_specs",
"mitmproxy.proxy.server_hooks",
"mitmproxy.tcp",
"mitmproxy.tls",
"mitmproxy.udp",
"mitmproxy.websocket",
here / ".." / "src" / "generated" / "events.py",
]
pdoc.pdoc(*modules, output_directory=here / ".." / "src" / "generated" / "api")
api_content = here / ".." / "src" / "content" / "api"
if api_content.exists():
shutil.rmtree(api_content)
api_content.mkdir()
for module in modules:
if isinstance(module, Path):
continue
filename = f"api/{module.replace('.', '/')}.html"
(api_content / f"{module}.md").write_bytes(
textwrap.dedent(
f"""
---
title: "{module}"
url: "{filename}"
menu: api
---
{{{{< readfile file="/generated/{filename}" >}}}}
"""
).encode()
)
(here / "../src/content/api/_index.md").write_text(
textwrap.dedent(
f"""\
---
title: "API Reference"
---
"""
),
newline="\n",
)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/examples.py | docs/scripts/examples.py | #!/usr/bin/env python3
import re
from pathlib import Path
here = Path(__file__).absolute().parent
example_dir = here / ".." / "src" / "examples" / "addons"
examples = example_dir.glob("*.py")
overview = []
listings = []
for example in examples:
code = example.read_text()
slug = str(example.with_suffix("").relative_to(example_dir))
slug = re.sub(r"[^a-zA-Z]", "-", slug)
match = re.search(
r'''
^
(?:[#][^\n]*\n)? # there might be a shebang
"""
\s*
(.+?)
\s*
(?:\n\n|""") # stop on empty line or end of comment
''',
code,
re.VERBOSE,
)
if match:
comment = " β " + match.group(1)
else:
comment = ""
overview.append(f" * [{example.name}](#{slug}){comment}\n")
listings.append(
f"""
<h3 id="{slug}">Example: {example.name}</h3>
```python
{code.strip()}
```
"""
)
print(
f"""
# Addon Examples
### Dedicated Example Addons
{"".join(overview)}
### Built-In Addons
Much of mitmproxyβs own functionality is defined in
[a suite of built-in addons](https://github.com/mitmproxy/mitmproxy/tree/main/mitmproxy/addons),
implementing everything from functionality like anticaching and sticky cookies to our onboarding webapp.
The built-in addons make for instructive reading, and you will quickly see that quite complex functionality
can often boil down to a very small, completely self-contained modules.
### Additional Community Examples
Additional examples contributed by the mitmproxy community can be found
[on GitHub](https://github.com/mitmproxy/mitmproxy/tree/main/examples/contrib).
-------------------------
{"".join(listings)}
"""
)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/options.py | docs/scripts/options.py | #!/usr/bin/env python3
import asyncio
from mitmproxy import options
from mitmproxy import optmanager
from mitmproxy.tools import console
from mitmproxy.tools import dump
from mitmproxy.tools import web
masters = {
"mitmproxy": console.master.ConsoleMaster,
"mitmdump": dump.DumpMaster,
"mitmweb": web.master.WebMaster,
}
unified_options = {}
async def dump():
for tool_name, master in masters.items():
opts = options.Options()
_ = master(opts)
for key, option in optmanager.dump_dicts(opts).items():
if key in unified_options:
unified_options[key]["tools"].append(tool_name)
else:
unified_options[key] = option
unified_options[key]["tools"] = [tool_name]
asyncio.run(dump())
print(
"""
<table class=\"table optiontable\">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
""".strip()
)
for key, option in sorted(unified_options.items(), key=lambda t: t[0]):
print(
f"""
<tr id="{key}">
<th>
{key}<a class="anchor" href="#{key}"></a><br/>
{" ".join(["<span class='badge'>{}</span>".format(t) for t in option["tools"]])}</th>
<td>{option["type"]}</td>
<td>{option["help"]}<br/>
Default: {option["default"]}
{"<br/>Choices: {}".format(", ".join(option["choices"])) if option["choices"] else ""}
</td>
</tr>
""".strip()
)
print("</tbody></table>")
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/clirecording/clidirector.py | docs/scripts/clirecording/clidirector.py | import json
import random
import subprocess
import threading
import time
from typing import NamedTuple
import libtmux
class InstructionSpec(NamedTuple):
instruction: str
time_from: float
time_to: float
class CliDirector:
def __init__(self):
self.record_start = None
self.pause_between_keys = 0.2
self.instructions: list[InstructionSpec] = []
def start(self, filename: str, width: int = 0, height: int = 0) -> libtmux.Session:
self.start_session(width, height)
self.start_recording(filename)
return self.tmux_session
def start_session(self, width: int = 0, height: int = 0) -> libtmux.Session:
self.tmux_server = libtmux.Server()
self.tmux_session = self.tmux_server.new_session(
session_name="asciinema_recorder", kill_session=True
)
self.tmux_pane = self.tmux_session.attached_window.attached_pane
self.tmux_version = self.tmux_pane.display_message("#{version}", True)
if width and height:
self.resize_window(width, height)
self.pause(3)
return self.tmux_session
def start_recording(self, filename: str) -> None:
self.asciinema_proc = subprocess.Popen(
[
"asciinema",
"rec",
"-y",
"--overwrite",
"-c",
"tmux attach -t asciinema_recorder",
filename,
]
)
self.pause(1.5)
self.record_start = time.time()
def resize_window(self, width: int, height: int) -> None:
subprocess.Popen(
["resize", "-s", str(height), str(width)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
def end(self) -> None:
self.end_recording()
self.end_session()
def end_recording(self) -> None:
self.asciinema_proc.terminate()
self.asciinema_proc.wait(timeout=5)
self.record_start = None
self.instructions = []
def end_session(self) -> None:
self.tmux_session.kill_session()
def press_key(
self, keys: str, count=1, pause: float | None = None, target=None
) -> None:
if pause is None:
pause = self.pause_between_keys
if target is None:
target = self.tmux_pane
for i in range(count):
if keys == " ":
keys = "Space"
target.send_keys(cmd=keys, enter=False, suppress_history=False)
# inspired by https://github.com/dmotz/TuringType
real_pause = random.uniform(0, pause) + 0.4 * pause
if keys == "Space":
real_pause += 1.5 * pause
elif keys == ".":
real_pause += pause
elif random.random() > 0.75:
real_pause += pause
elif random.random() > 0.95:
real_pause += 2 * pause
self.pause(real_pause)
def type(self, keys: str, pause: float | None = None, target=None) -> None:
if pause is None:
pause = self.pause_between_keys
if target is None:
target = self.tmux_pane
target.select_pane()
for key in keys:
self.press_key(key, pause=pause, target=target)
def exec(self, keys: str, target=None) -> None:
if target is None:
target = self.tmux_pane
self.type(keys, target=target)
self.pause(1.25)
self.press_key("Enter", target=target)
self.pause(0.5)
def focus_pane(self, pane: libtmux.Pane, set_active_pane: bool = True) -> None:
pane.select_pane()
if set_active_pane:
self.tmux_pane = pane
def pause(self, seconds: float) -> None:
time.sleep(seconds)
def run_external(self, command: str) -> None:
subprocess.run(command, shell=True)
def message(
self,
msg: str,
duration: int | None = None,
add_instruction: bool = True,
instruction_html: str = "",
) -> None:
if duration is None:
duration = len(msg) * 0.08 # seconds
self.tmux_session.set_option(
"display-time", int(duration * 1000)
) # milliseconds
self.tmux_pane.display_message(" " + msg)
if add_instruction or instruction_html:
if not instruction_html:
instruction_html = msg
self.instruction(instruction=instruction_html, duration=duration)
self.pause(duration + 0.5)
def popup(self, content: str, duration: int = 4) -> None:
# todo: check if installed tmux version supports display-popup
# tmux's display-popup is blocking, so we close it in a separate thread
t = threading.Thread(target=self.close_popup, args=[duration])
t.start()
lines = content.splitlines()
self.tmux_pane.cmd("display-popup", "", *lines)
t.join()
def close_popup(self, duration: float = 0) -> None:
self.pause(duration)
self.tmux_pane.cmd("display-popup", "-C")
def instruction(
self, instruction: str, duration: float = 3, time_from: float | None = None
) -> None:
if time_from is None:
time_from = self.current_time
self.instructions.append(
InstructionSpec(
instruction=str(len(self.instructions) + 1) + ". " + instruction,
time_from=round(time_from, 1),
time_to=round(time_from + duration, 1),
)
)
def save_instructions(self, output_path: str) -> None:
instr_as_dicts = []
for instr in self.instructions:
instr_as_dicts.append(instr._asdict())
with open(output_path, "w", encoding="utf-8") as f:
json.dump(instr_as_dicts, f, ensure_ascii=False, indent=4)
@property
def current_time(self) -> float:
now = time.time()
return round(now - self.record_start, 1)
@property
def current_pane(self) -> libtmux.Pane:
return self.tmux_pane
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/clirecording/screenplays.py | docs/scripts/clirecording/screenplays.py | #!/usr/bin/env python3
from clidirector import CliDirector
def record_user_interface(d: CliDirector):
tmux = d.start_session(width=120, height=36)
window = tmux.attached_window
d.start_recording("recordings/mitmproxy_user_interface.cast")
d.message(
"Welcome to the mitmproxy tutorial. In this lesson we cover the user interface."
)
d.pause(1)
d.exec("mitmproxy")
d.pause(3)
d.message("This is the default view of mitmproxy.")
d.message("mitmproxy adds rows to the view as new requests come in.")
d.message("Letβs generate some requests using `curl` in a separate terminal.")
pane_top = d.current_pane
pane_bottom = window.split_window(attach=True)
pane_bottom.resize_pane(height=12)
d.focus_pane(pane_bottom)
d.pause(2)
d.type("curl")
d.message("Use curlβs `--proxy` option to configure mitmproxy as a proxy.")
d.type(" --proxy http://127.0.0.1:8080")
d.message("We use the text-based weather service `wttr.in`.")
d.exec(' "http://wttr.in/Dunedin?0"')
d.pause(2)
d.press_key("Up")
d.press_key("Left", count=3)
d.press_key("BSpace", count=7)
d.exec("Innsbruck")
d.pause(2)
d.exec("exit", target=pane_bottom)
d.focus_pane(pane_top)
d.message("You see the requests to `wttr.in` in the list of flows.")
d.message("mitmproxy is controlled using keyboard shortcuts.")
d.message("Use your arrow keys `β` and `β` to change the focused flow (`>>`).")
d.press_key("Down", pause=0.5)
d.press_key("Up", pause=0.5)
d.press_key("Down", pause=0.5)
d.press_key("Up", pause=0.5)
d.message("The focused flow (`>>`) is used as a target for various commands.")
d.message("One such command shows the flow details, it is bound to `ENTER`.")
d.message("Press `ENTER` to view the details of the focused flow.")
d.press_key("Enter")
d.message("The flow details view has 3 panes: request, response, and detail.")
d.message("Use your arrow keys `β` and `β` to switch between panes.")
d.press_key("Right", count=2, pause=2.5)
d.press_key("Left", count=2, pause=1)
d.message(
"Press `q` to exit the current view.",
)
d.type("q")
d.message("Press `?` to get a list of all available keyboard shortcuts.")
d.type("?")
d.pause(2)
d.press_key("Down", count=20, pause=0.25)
d.message("Tip: Remember the `?` shortcut. It works in every view.")
d.message("Press `q` to exit the current view.")
d.type("q")
d.message("Each shortcut is internally bound to a command.")
d.message("You can also execute commands directly (without using shortcuts).")
d.message("Press `:` to open the command prompt at the bottom.")
d.type(":")
d.message("Enter `console.view.flow @focus`.")
d.type("console.view.flow @focus")
d.message("The command `console.view.flow` opens the details view for a flow.")
d.message("The argument `@focus` defines the target flow.")
d.message("Press `ENTER` to execute the command.")
d.press_key("Enter")
d.message(
"Commands unleash the full power of mitmproxy, i.e., to configure interceptions."
)
d.message("You now know basics of mitmproxyβs UI and how to control it.")
d.pause(1)
d.message("In the next lesson you will learn to intercept flows.")
d.save_instructions("recordings/mitmproxy_user_interface_instructions.json")
d.end()
def record_intercept_requests(d: CliDirector):
tmux = d.start_session(width=120, height=36)
window = tmux.attached_window
d.start_recording("recordings/mitmproxy_intercept_requests.cast")
d.message(
"Welcome to the mitmproxy tutorial. In this lesson we cover the interception of requests."
)
d.pause(1)
d.exec("mitmproxy")
d.pause(3)
d.message("We first need to configure mitmproxy to intercept requests.")
d.message(
"Press `i` to prepopulate mitmproxyβs command prompt with `set intercept ''`."
)
d.type("i")
d.pause(2)
d.message(
"We use the flow filter expression `~u <regex>` to only intercept specific URLs."
)
d.message(
"Additionally, we use the filter `~q` to only intercept requests, but not responses."
)
d.message("We combine both flow filters using `&`.")
d.message(
"Enter `~u /Dunedin & ~q` between the quotes of the `set intercept` command and press `ENTER`."
)
d.exec("~u /Dunedin & ~q")
d.message("The bottom bar shows that the interception has been configured.")
d.message("Letβs generate a request using `curl` in a separate terminal.")
pane_top = d.current_pane
pane_bottom = window.split_window(attach=True)
pane_bottom.resize_pane(height=12)
d.focus_pane(pane_bottom)
d.pause(2)
d.exec('curl --proxy http://127.0.0.1:8080 "http://wttr.in/Dunedin?0"')
d.pause(2)
d.focus_pane(pane_top)
d.message("You see a new line in in the list of flows.")
d.message(
"The new flow is displayed in red to indicate that it has been intercepted."
)
d.message(
"Put the focus (`>>`) on the intercepted flow. This is already the case in our example."
)
d.message("Press `a` to resume this flow without making any changes.")
d.type("a")
d.pause(2)
d.focus_pane(pane_bottom)
d.message("Submit another request and focus its flow.")
d.press_key("Up")
d.press_key("Enter")
d.pause(2)
d.focus_pane(pane_top)
d.press_key("Down")
d.pause(1)
d.message(
"Press `X` to kill this flow, i.e., discard it without forwarding it to its final destination `wttr.in`."
)
d.type("X")
d.pause(3)
d.message("In the next lesson you will learn to modify intercepted flows.")
d.save_instructions("recordings/mitmproxy_intercept_requests_instructions.json")
d.end()
def record_modify_requests(d: CliDirector):
tmux = d.start_session(width=120, height=36)
window = tmux.attached_window
d.start_recording("recordings/mitmproxy_modify_requests.cast")
d.message(
"Welcome to the mitmproxy tutorial. In this lesson we cover the modification of intercepted requests."
)
d.pause(1)
d.exec("mitmproxy")
d.pause(3)
d.message(
"We configure and use the same interception rule as in the last tutorial."
)
d.message(
"Press `i` to prepopulate mitmproxyβs command prompt, enter the flow filter `~u /Dunedin & ~q`, and press `ENTER`."
)
d.type("i")
d.pause(2)
d.exec("~u /Dunedin & ~q")
d.message("Letβs generate a request using `curl` in a separate terminal.")
pane_top = d.current_pane
pane_bottom = window.split_window(attach=True)
pane_bottom.resize_pane(height=12)
d.focus_pane(pane_bottom)
d.pause(2)
d.exec('curl --proxy http://127.0.0.1:8080 "http://wttr.in/Dunedin?0"')
d.pause(2)
d.focus_pane(pane_top)
d.message("We now want to modify the intercepted request.")
d.message(
"Put the focus (`>>`) on the intercepted flow. This is already the case in our example."
)
d.message("Press `ENTER` to open the details view for the intercepted flow.")
d.press_key("Enter")
d.message("Press `e` to edit the intercepted flow.")
d.type("e")
d.message("mitmproxy asks which part to modify.")
d.message("Select `path` by using your arrow keys and press `ENTER`.")
d.press_key("Down", count=3, pause=0.5)
d.pause(1)
d.press_key("Enter")
d.message(
"mitmproxy shows all path components line by line, in our example its just `Dunedin`."
)
d.message("Press `ENTER` to modify the selected path component.")
d.press_key("Down", pause=2)
d.press_key("Enter")
d.message("Replace `Dunedin` with `Innsbruck`.")
d.press_key("BSpace", count=7, pause=0.5)
d.type("Innsbruck", pause=0.5)
d.message("Press `ESC` to confirm your change.")
d.press_key("Escape")
d.message("Press `q` to go back to the flow details view.")
d.type("q")
d.message("Press `a` to resume the intercepted flow.")
d.type("a")
d.pause(2)
d.message(
"You see that the request URL was modified and `wttr.in` replied with the weather report for `Innsbruck`."
)
d.message("In the next lesson you will learn to replay flows.")
d.save_instructions("recordings/mitmproxy_modify_requests_instructions.json")
d.end()
def record_replay_requests(d: CliDirector):
tmux = d.start_session(width=120, height=36)
window = tmux.attached_window
d.start_recording("recordings/mitmproxy_replay_requests.cast")
d.message(
"Welcome to the mitmproxy tutorial. In this lesson we cover replaying requests."
)
d.pause(1)
d.exec("mitmproxy")
d.pause(3)
d.message(
"Letβs generate a request that we can replay. We use `curl` in a separate terminal."
)
pane_top = d.current_pane
pane_bottom = window.split_window(attach=True)
pane_bottom.resize_pane(height=12)
d.focus_pane(pane_bottom)
d.pause(2)
d.exec('curl --proxy http://127.0.0.1:8080 "http://wttr.in/Dunedin?0"')
d.pause(2)
d.focus_pane(pane_top)
d.message("We now want to replay the this request.")
d.message(
"Put the focus (`>>`) on the request that should be replayed. This is already the case in our example."
)
d.message("Press `r` to replay the request.")
d.type("r")
d.message(
"Note that no new rows are added for replayed flows, but the existing row is updated."
)
d.message(
"Every time you press `r`, mitmproxy sends this request to the server again and updates the flow."
)
d.press_key("r", count=4, pause=1)
d.message("You can also modify a flow before replaying it.")
d.message("It works as shown in the previous lesson, by pressing `e`.")
d.message(
"Congratulations! You have completed all lessons of the mitmproxy tutorial."
)
d.save_instructions("recordings/mitmproxy_replay_requests_instructions.json")
d.end()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/docs/scripts/clirecording/record.py | docs/scripts/clirecording/record.py | #!/usr/bin/env python3
import screenplays
from clidirector import CliDirector
if __name__ == "__main__":
director = CliDirector()
screenplays.record_user_interface(director)
screenplays.record_intercept_requests(director)
screenplays.record_modify_requests(director)
screenplays.record_replay_requests(director)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/test_xss_scanner.py | examples/contrib/test_xss_scanner.py | import pytest
import requests
from examples.complex import xss_scanner as xss
from mitmproxy.test import tflow
from mitmproxy.test import tutils
class TestXSSScanner:
def test_get_XSS_info(self):
# First type of exploit: <script>PAYLOAD</script>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><script>%s</script><html>" % xss.FULL_PAYLOAD,
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"</script><script>alert(0)</script><script>",
xss.FULL_PAYLOAD.decode("utf-8"),
)
assert xss_info == expected_xss_info
xss_info = xss.get_XSS_data(
b"<html><script>%s</script><html>"
% xss.FULL_PAYLOAD.replace(b"'", b"%27").replace(b'"', b"%22"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"</script><script>alert(0)</script><script>",
xss.FULL_PAYLOAD.replace(b"'", b"%27")
.replace(b'"', b"%22")
.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b"<html><script>%s</script><html>"
% xss.FULL_PAYLOAD.replace(b"'", b"%27")
.replace(b'"', b"%22")
.replace(b"/", b"%2F"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Second type of exploit: <script>t='PAYLOAD'</script>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><script>t='%s';</script></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b'"', b"%22"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"';alert(0);g='",
xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b'"', b"%22")
.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b"<html><script>t='%s';</script></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b'"', b"%22")
.replace(b"'", b"%22"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Third type of exploit: <script>t="PAYLOAD"</script>
# Exploitable:
xss_info = xss.get_XSS_data(
b'<html><script>t="%s";</script></html>'
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b"'", b"%27"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
'";alert(0);g="',
xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b"'", b"%27")
.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b'<html><script>t="%s";</script></html>'
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b"'", b"%27")
.replace(b'"', b"%22"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Fourth type of exploit: <a href='PAYLOAD'>Test</a>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href='%s'>Test</a></html>" % xss.FULL_PAYLOAD,
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"'><script>alert(0)</script>",
xss.FULL_PAYLOAD.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href='OtherStuff%s'>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"'", b"%27"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Fifth type of exploit: <a href="PAYLOAD">Test</a>
# Exploitable:
xss_info = xss.get_XSS_data(
b'<html><a href="%s">Test</a></html>'
% xss.FULL_PAYLOAD.replace(b"'", b"%27"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
'"><script>alert(0)</script>',
xss.FULL_PAYLOAD.replace(b"'", b"%27").decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b'<html><a href="OtherStuff%s">Test</a></html>'
% xss.FULL_PAYLOAD.replace(b"'", b"%27").replace(b'"', b"%22"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Sixth type of exploit: <a href=PAYLOAD>Test</a>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href=%s>Test</a></html>" % xss.FULL_PAYLOAD,
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"><script>alert(0)</script>",
xss.FULL_PAYLOAD.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable
xss_info = xss.get_XSS_data(
b"<html><a href=OtherStuff%s>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b"=", b"%3D"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Seventh type of exploit: <html>PAYLOAD</html>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><b>%s</b></html>" % xss.FULL_PAYLOAD,
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"<script>alert(0)</script>",
xss.FULL_PAYLOAD.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable
xss_info = xss.get_XSS_data(
b"<html><b>%s</b></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b"/", b"%2F"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Eighth type of exploit: <a href=PAYLOAD>Test</a>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href=%s>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C").replace(b">", b"%3E"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"Javascript:alert(0)",
xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href=OtherStuff%s>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b"=", b"%3D"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Ninth type of exploit: <a href="STUFF PAYLOAD">Test</a>
# Exploitable:
xss_info = xss.get_XSS_data(
b'<html><a href="STUFF %s">Test</a></html>'
% xss.FULL_PAYLOAD.replace(b"<", b"%3C").replace(b">", b"%3E"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
'" onmouseover="alert(0)" t="',
xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b'<html><a href="STUFF %s">Test</a></html>'
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b'"', b"%22"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Tenth type of exploit: <a href='STUFF PAYLOAD'>Test</a>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href='STUFF %s'>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C").replace(b">", b"%3E"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
"' onmouseover='alert(0)' t='",
xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href='STUFF %s'>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b"'", b"%22"),
"https://example.com",
"End of URL",
)
assert xss_info is None
# Eleventh type of exploit: <a href=STUFF_PAYLOAD>Test</a>
# Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href=STUFF%s>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C").replace(b">", b"%3E"),
"https://example.com",
"End of URL",
)
expected_xss_info = xss.XSSData(
"https://example.com",
"End of URL",
" onmouseover=alert(0) t=",
xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.decode("utf-8"),
)
assert xss_info == expected_xss_info
# Non-Exploitable:
xss_info = xss.get_XSS_data(
b"<html><a href=STUFF_%s>Test</a></html>"
% xss.FULL_PAYLOAD.replace(b"<", b"%3C")
.replace(b">", b"%3E")
.replace(b"=", b"%3D"),
"https://example.com",
"End of URL",
)
assert xss_info is None
def test_get_SQLi_data(self):
sqli_data = xss.get_SQLi_data(
"<html>SQL syntax MySQL</html>",
"<html></html>",
"https://example.com",
"End of URL",
)
expected_sqli_data = xss.SQLiData(
"https://example.com", "End of URL", "SQL syntax.*MySQL", "MySQL"
)
assert sqli_data == expected_sqli_data
sqli_data = xss.get_SQLi_data(
"<html>SQL syntax MySQL</html>",
"<html>SQL syntax MySQL</html>",
"https://example.com",
"End of URL",
)
assert sqli_data is None
def test_inside_quote(self):
assert not xss.inside_quote("'", b"no", 0, b"no")
assert xss.inside_quote("'", b"yes", 0, b"'yes'")
assert xss.inside_quote("'", b"yes", 1, b"'yes'otherJunk'yes'more")
assert not xss.inside_quote("'", b"longStringNotInIt", 1, b"short")
def test_paths_to_text(self):
text = xss.paths_to_text(
"""<html><head><h1>STRING</h1></head>
<script>STRING</script>
<a href=STRING></a></html>""",
"STRING",
)
expected_text = ["/html/head/h1", "/html/script"]
assert text == expected_text
assert xss.paths_to_text("""<html></html>""", "STRING") == []
def mocked_requests_vuln(*args, headers=None, cookies=None):
class MockResponse:
def __init__(self, html, headers=None, cookies=None):
self.text = html
return MockResponse("<html>%s</html>" % xss.FULL_PAYLOAD)
def mocked_requests_invuln(*args, headers=None, cookies=None):
class MockResponse:
def __init__(self, html, headers=None, cookies=None):
self.text = html
return MockResponse("<html></html>")
def test_test_end_of_url_injection(self, get_request_vuln):
xss_info = xss.test_end_of_URL_injection(
"<html></html>", "https://example.com/index.html", {}
)[0]
expected_xss_info = xss.XSSData(
"https://example.com/index.html/1029zxcs'd\"ao<ac>so[sb]po(pc)se;sl/bsl\\eq=3847asd",
"End of URL",
"<script>alert(0)</script>",
"1029zxcs\\'d\"ao<ac>so[sb]po(pc)se;sl/bsl\\\\eq=3847asd",
)
sqli_info = xss.test_end_of_URL_injection(
"<html></html>", "https://example.com/", {}
)[1]
assert xss_info == expected_xss_info
assert sqli_info is None
def test_test_referer_injection(self, get_request_vuln):
xss_info = xss.test_referer_injection(
"<html></html>", "https://example.com/", {}
)[0]
expected_xss_info = xss.XSSData(
"https://example.com/",
"Referer",
"<script>alert(0)</script>",
"1029zxcs\\'d\"ao<ac>so[sb]po(pc)se;sl/bsl\\\\eq=3847asd",
)
sqli_info = xss.test_referer_injection(
"<html></html>", "https://example.com/", {}
)[1]
assert xss_info == expected_xss_info
assert sqli_info is None
def test_test_user_agent_injection(self, get_request_vuln):
xss_info = xss.test_user_agent_injection(
"<html></html>", "https://example.com/", {}
)[0]
expected_xss_info = xss.XSSData(
"https://example.com/",
"User Agent",
"<script>alert(0)</script>",
"1029zxcs\\'d\"ao<ac>so[sb]po(pc)se;sl/bsl\\\\eq=3847asd",
)
sqli_info = xss.test_user_agent_injection(
"<html></html>", "https://example.com/", {}
)[1]
assert xss_info == expected_xss_info
assert sqli_info is None
def test_test_query_injection(self, get_request_vuln):
xss_info = xss.test_query_injection(
"<html></html>", "https://example.com/vuln.php?cmd=ls", {}
)[0]
expected_xss_info = xss.XSSData(
"https://example.com/vuln.php?cmd=1029zxcs'd\"ao<ac>so[sb]po(pc)se;sl/bsl\\eq=3847asd",
"Query",
"<script>alert(0)</script>",
"1029zxcs\\'d\"ao<ac>so[sb]po(pc)se;sl/bsl\\\\eq=3847asd",
)
sqli_info = xss.test_query_injection(
"<html></html>", "https://example.com/vuln.php?cmd=ls", {}
)[1]
assert xss_info == expected_xss_info
assert sqli_info is None
@pytest.fixture(scope="function")
def get_request_vuln(self, monkeypatch):
monkeypatch.setattr(requests, "get", self.mocked_requests_vuln)
@pytest.fixture(scope="function")
def get_request_invuln(self, monkeypatch):
monkeypatch.setattr(requests, "get", self.mocked_requests_invuln)
@pytest.fixture(scope="function")
def mock_gethostbyname(self, monkeypatch):
def gethostbyname(domain):
claimed_domains = ["google.com"]
if domain not in claimed_domains:
from socket import gaierror
raise gaierror("[Errno -2] Name or service not known")
else:
return "216.58.221.46"
monkeypatch.setattr("socket.gethostbyname", gethostbyname)
def test_find_unclaimed_URLs(self, logger, mock_gethostbyname):
xss.find_unclaimed_URLs(
'<html><script src="http://google.com"></script></html>',
"https://example.com",
)
assert logger.args == []
xss.find_unclaimed_URLs(
'<html><script src="http://unclaimedDomainName.com"></script></html>',
"https://example.com",
)
assert (
logger.args[0]
== 'XSS found in https://example.com due to unclaimed URL "http://unclaimedDomainName.com".'
)
xss.find_unclaimed_URLs(
'<html><iframe src="http://unclaimedDomainName.com"></iframe></html>',
"https://example.com",
)
assert (
logger.args[1]
== 'XSS found in https://example.com due to unclaimed URL "http://unclaimedDomainName.com".'
)
xss.find_unclaimed_URLs(
'<html><link rel="stylesheet" href="http://unclaimedDomainName.com"></html>',
"https://example.com",
)
assert (
logger.args[2]
== 'XSS found in https://example.com due to unclaimed URL "http://unclaimedDomainName.com".'
)
def test_log_XSS_data(self, logger):
xss.log_XSS_data(None)
assert logger.args == []
# self, url: str, injection_point: str, exploit: str, line: str
xss.log_XSS_data(
xss.XSSData("https://example.com", "Location", "String", "Line of HTML")
)
assert logger.args[0] == "===== XSS Found ===="
assert logger.args[1] == "XSS URL: https://example.com"
assert logger.args[2] == "Injection Point: Location"
assert logger.args[3] == "Suggested Exploit: String"
assert logger.args[4] == "Line: Line of HTML"
def test_log_SQLi_data(self, logger):
xss.log_SQLi_data(None)
assert logger.args == []
xss.log_SQLi_data(
xss.SQLiData("https://example.com", "Location", "Oracle.*Driver", "Oracle")
)
assert logger.args[0] == "===== SQLi Found ====="
assert logger.args[1] == "SQLi URL: https://example.com"
assert logger.args[2] == "Injection Point: Location"
assert logger.args[3] == "Regex used: Oracle.*Driver"
def test_get_cookies(self):
mocked_req = tutils.treq()
mocked_req.cookies = [("cookieName2", "cookieValue2")]
mocked_flow = tflow.tflow(req=mocked_req)
# It only uses the request cookies
assert xss.get_cookies(mocked_flow) == {"cookieName2": "cookieValue2"}
def test_response(self, get_request_invuln, logger):
mocked_flow = tflow.tflow(
req=tutils.treq(path=b"index.html?q=1"),
resp=tutils.tresp(content=b"<html></html>"),
)
xss.response(mocked_flow)
assert logger.args == []
def test_data_equals(self):
xssData = xss.XSSData("a", "b", "c", "d")
sqliData = xss.SQLiData("a", "b", "c", "d")
assert xssData == xssData
assert sqliData == sqliData
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/ntlm_upstream_proxy.py | examples/contrib/ntlm_upstream_proxy.py | import base64
import binascii
import logging
import socket
from typing import Any
from typing import Optional
from ntlm_auth import gss_channel_bindings
from ntlm_auth import ntlm
from mitmproxy import addonmanager
from mitmproxy import ctx
from mitmproxy import http
from mitmproxy.net.http import http1
from mitmproxy.proxy import commands
from mitmproxy.proxy import layer
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.layers.http import HttpConnectUpstreamHook
from mitmproxy.proxy.layers.http import HttpLayer
from mitmproxy.proxy.layers.http import HttpStream
from mitmproxy.proxy.layers.http._upstream_proxy import HttpUpstreamProxy
class NTLMUpstreamAuth:
"""
This addon handles authentication to systems upstream from us for the
upstream proxy and reverse proxy mode. There are 3 cases:
- Upstream proxy CONNECT requests should have authentication added, and
subsequent already connected requests should not.
- Upstream proxy regular requests
- Reverse proxy regular requests (CONNECT is invalid in this mode)
"""
def load(self, loader: addonmanager.Loader) -> None:
logging.info("NTLMUpstreamAuth loader")
loader.add_option(
name="upstream_ntlm_auth",
typespec=Optional[str],
default=None,
help="""
Add HTTP NTLM authentication to upstream proxy requests.
Format: username:password.
""",
)
loader.add_option(
name="upstream_ntlm_domain",
typespec=Optional[str],
default=None,
help="""
Add HTTP NTLM domain for authentication to upstream proxy requests.
""",
)
loader.add_option(
name="upstream_proxy_address",
typespec=Optional[str],
default=None,
help="""
upstream poxy address.
""",
)
loader.add_option(
name="upstream_ntlm_compatibility",
typespec=int,
default=3,
help="""
Add HTTP NTLM compatibility for authentication to upstream proxy requests.
Valid values are 0-5 (Default: 3)
""",
)
logging.debug("AddOn: NTLM Upstream Authentication - Loaded")
def running(self):
def extract_flow_from_context(context: Context) -> http.HTTPFlow:
if context and context.layers:
for x in context.layers:
if isinstance(x, HttpLayer):
for _, stream in x.streams.items():
return (
stream.flow if isinstance(stream, HttpStream) else None
)
def build_connect_flow(
context: Context, connect_header: tuple
) -> http.HTTPFlow:
flow = extract_flow_from_context(context)
if not flow:
logging.error("failed to build connect flow")
raise
flow.request.content = b"" # we should send empty content for handshake
header_name, header_value = connect_header
flow.request.headers.add(header_name, header_value)
return flow
def patched_start_handshake(self) -> layer.CommandGenerator[None]:
assert self.conn.address
self.ntlm_context = CustomNTLMContext(ctx)
proxy_authorization = self.ntlm_context.get_ntlm_start_negotiate_message()
self.flow = build_connect_flow(
self.context, ("Proxy-Authorization", proxy_authorization)
)
yield HttpConnectUpstreamHook(self.flow)
raw = http1.assemble_request(self.flow.request)
yield commands.SendData(self.tunnel_connection, raw)
def extract_proxy_authenticate_msg(response_head: list) -> str:
for header in response_head:
if b"Proxy-Authenticate" in header:
challenge_message = str(bytes(header).decode("utf-8"))
try:
token = challenge_message.split(": ")[1]
except IndexError:
logging.error("Failed to extract challenge_message")
raise
return token
def patched_receive_handshake_data(
self, data
) -> layer.CommandGenerator[tuple[bool, str | None]]:
self.buf += data
response_head = self.buf.maybe_extract_lines()
if response_head:
response_head = [bytes(x) for x in response_head]
try:
response = http1.read_response_head(response_head)
except ValueError:
return True, None
challenge_message = extract_proxy_authenticate_msg(response_head)
if 200 <= response.status_code < 300:
if self.buf:
yield from self.receive_data(data)
del self.buf
return True, None
else:
if not challenge_message:
return True, None
proxy_authorization = (
self.ntlm_context.get_ntlm_challenge_response_message(
challenge_message
)
)
self.flow = build_connect_flow(
self.context, ("Proxy-Authorization", proxy_authorization)
)
raw = http1.assemble_request(self.flow.request)
yield commands.SendData(self.tunnel_connection, raw)
return False, None
else:
return False, None
HttpUpstreamProxy.start_handshake = patched_start_handshake
HttpUpstreamProxy.receive_handshake_data = patched_receive_handshake_data
def done(self):
logging.info("close ntlm session")
addons = [NTLMUpstreamAuth()]
class CustomNTLMContext:
def __init__(
self,
ctx,
preferred_type: str = "NTLM",
cbt_data: gss_channel_bindings.GssChannelBindingsStruct = None,
):
# TODO:// take care the cbt_data
auth: str = ctx.options.upstream_ntlm_auth
domain: str = str(ctx.options.upstream_ntlm_domain).upper()
ntlm_compatibility: int = ctx.options.upstream_ntlm_compatibility
username, password = tuple(auth.split(":"))
workstation = socket.gethostname().upper()
logging.debug(f'\nntlm context with the details: "{domain}\\{username}", *****')
self.preferred_type = preferred_type
self.ntlm_context = ntlm.NtlmContext(
username=username,
password=password,
domain=domain,
workstation=workstation,
ntlm_compatibility=ntlm_compatibility,
cbt_data=cbt_data,
)
def get_ntlm_start_negotiate_message(self) -> str:
negotiate_message = self.ntlm_context.step()
negotiate_message_base_64_in_bytes = base64.b64encode(negotiate_message)
negotiate_message_base_64_ascii = negotiate_message_base_64_in_bytes.decode(
"ascii"
)
negotiate_message_base_64_final = (
f"{self.preferred_type} {negotiate_message_base_64_ascii}"
)
logging.debug(
f"{self.preferred_type} Authentication, negotiate message: {negotiate_message_base_64_final}"
)
return negotiate_message_base_64_final
def get_ntlm_challenge_response_message(self, challenge_message: str) -> Any:
challenge_message = challenge_message.replace(self.preferred_type + " ", "", 1)
try:
challenge_message_ascii_bytes = base64.b64decode(
challenge_message, validate=True
)
except binascii.Error as err:
logging.debug(
f"{self.preferred_type} Authentication fail with error {err.__str__()}"
)
return False
authenticate_message = self.ntlm_context.step(challenge_message_ascii_bytes)
negotiate_message_base_64 = "{} {}".format(
self.preferred_type, base64.b64encode(authenticate_message).decode("ascii")
)
logging.debug(
f"{self.preferred_type} Authentication, response to challenge message: {negotiate_message_base_64}"
)
return negotiate_message_base_64
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/search.py | examples/contrib/search.py | import logging
import re
from collections.abc import Sequence
from json import dumps
from mitmproxy import command
from mitmproxy import flow
MARKER = ":mag:"
RESULTS_STR = "Search Results: "
class Search:
def __init__(self):
self.exp = None
@command.command("search")
def _search(self, flows: Sequence[flow.Flow], regex: str) -> None:
"""
Defines a command named "search" that matches
the given regular expression against most parts
of each request/response included in the selected flows.
Usage: from the flow list view, type ":search" followed by
a space, then a flow selection expression; e.g., "@shown",
then the desired regular expression to perform the search.
Alternatively, define a custom shortcut in keys.yaml; e.g.:
-
key: "/"
ctx: ["flowlist"]
cmd: "console.command search @shown "
Flows containing matches to the expression will be marked
with the magnifying glass emoji, and their comments will
contain JSON-formatted search results.
To view flow comments, enter the flow view
and navigate to the detail tab.
"""
try:
self.exp = re.compile(regex)
except re.error as e:
logging.error(e)
return
for _flow in flows:
# Erase previous results while preserving other comments:
comments = list()
for c in _flow.comment.split("\n"):
if c.startswith(RESULTS_STR):
break
comments.append(c)
_flow.comment = "\n".join(comments)
if _flow.marked == MARKER:
_flow.marked = False
results = {k: v for k, v in self.flow_results(_flow).items() if v}
if results:
comments.append(RESULTS_STR)
comments.append(dumps(results, indent=2))
_flow.comment = "\n".join(comments)
_flow.marked = MARKER
def header_results(self, message):
results = {k: self.exp.findall(v) for k, v in message.headers.items()}
return {k: v for k, v in results.items() if v}
def flow_results(self, _flow):
results = dict()
results.update({"flow_comment": self.exp.findall(_flow.comment)})
if _flow.request is not None:
results.update({"request_path": self.exp.findall(_flow.request.path)})
results.update({"request_headers": self.header_results(_flow.request)})
if _flow.request.text:
results.update({"request_body": self.exp.findall(_flow.request.text)})
if _flow.response is not None:
results.update({"response_headers": self.header_results(_flow.response)})
if _flow.response.text:
results.update({"response_body": self.exp.findall(_flow.response.text)})
return results
addons = [Search()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/remote-debug.py | examples/contrib/remote-debug.py | """
This script enables remote debugging of the mitmproxy console *UI* with PyCharm.
For general debugging purposes, it is easier to just debug mitmdump within PyCharm.
Usage:
- pip install pydevd on the mitmproxy machine
- Open the Run/Debug Configuration dialog box in PyCharm, and select the
Python Remote Debug configuration type.
- Debugging works in the way that mitmproxy connects to the debug server
on startup. Specify host and port that mitmproxy can use to reach your
PyCharm instance on startup.
- Adjust this inline script accordingly.
- Start debug server in PyCharm
- Set breakpoints
- Start mitmproxy -s remote_debug.py
"""
def load(_):
import pydevd_pycharm
pydevd_pycharm.settrace(
"localhost", port=5678, stdoutToServer=True, stderrToServer=True, suspend=False
)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/all_markers.py | examples/contrib/all_markers.py | from mitmproxy import command
from mitmproxy import ctx
from mitmproxy.utils import emoji
@command.command("all.markers")
def all_markers():
"Create a new flow showing all marker values"
for marker in emoji.emoji:
ctx.master.commands.call(
"view.flows.create", "get", f"https://example.com/{marker}"
)
ctx.master.commands.call("flow.mark", [ctx.master.view[-1]], marker)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/block_dns_over_https.py | examples/contrib/block_dns_over_https.py | """
This module is for blocking DNS over HTTPS requests.
It loads a blocklist of IPs and hostnames that are known to serve DNS over HTTPS requests.
It also uses headers, query params, and paths to detect DoH (and block it)
"""
import logging
# known DoH providers' hostnames and IP addresses to block
default_blocklist: dict = {
"hostnames": [
"dns.adguard.com",
"dns-family.adguard.com",
"dns.google",
"cloudflare-dns.com",
"mozilla.cloudflare-dns.com",
"security.cloudflare-dns.com",
"family.cloudflare-dns.com",
"dns.quad9.net",
"dns9.quad9.net",
"dns10.quad9.net",
"dns11.quad9.net",
"doh.opendns.com",
"doh.familyshield.opendns.com",
"doh.cleanbrowsing.org",
"doh.xfinity.com",
"dohdot.coxlab.net",
"odvr.nic.cz",
"doh.dnslify.com",
"dns.nextdns.io",
"dns.dnsoverhttps.net",
"doh.crypto.sx",
"doh.powerdns.org",
"doh-fi.blahdns.com",
"doh-jp.blahdns.com",
"doh-de.blahdns.com",
"doh.ffmuc.net",
"dns.dns-over-https.com",
"doh.securedns.eu",
"dns.rubyfish.cn",
"dns.containerpi.com",
"dns.containerpi.com",
"dns.containerpi.com",
"doh-2.seby.io",
"doh.seby.io",
"commons.host",
"doh.dnswarden.com",
"doh.dnswarden.com",
"doh.dnswarden.com",
"dns-nyc.aaflalo.me",
"dns.aaflalo.me",
"doh.applied-privacy.net",
"doh.captnemo.in",
"doh.tiar.app",
"doh.tiarap.org",
"doh.dns.sb",
"rdns.faelix.net",
"doh.li",
"doh.armadillodns.net",
"jp.tiar.app",
"jp.tiarap.org",
"doh.42l.fr",
"dns.hostux.net",
"dns.hostux.net",
"dns.aa.net.uk",
"adblock.mydns.network",
"ibksturm.synology.me",
"jcdns.fun",
"ibuki.cgnat.net",
"dns.twnic.tw",
"example.doh.blockerdns.com",
"dns.digitale-gesellschaft.ch",
"doh.libredns.gr",
"doh.centraleu.pi-dns.com",
"doh.northeu.pi-dns.com",
"doh.westus.pi-dns.com",
"doh.eastus.pi-dns.com",
"dns.flatuslifir.is",
"private.canadianshield.cira.ca",
"protected.canadianshield.cira.ca",
"family.canadianshield.cira.ca",
"dns.google.com",
"dns.google.com",
],
"ips": [
"104.16.248.249",
"104.16.248.249",
"104.16.249.249",
"104.16.249.249",
"104.18.2.55",
"104.18.26.128",
"104.18.27.128",
"104.18.3.55",
"104.18.44.204",
"104.18.44.204",
"104.18.45.204",
"104.18.45.204",
"104.182.57.196",
"104.236.178.232",
"104.24.122.53",
"104.24.123.53",
"104.28.0.106",
"104.28.1.106",
"104.31.90.138",
"104.31.91.138",
"115.159.131.230",
"116.202.176.26",
"116.203.115.192",
"136.144.215.158",
"139.59.48.222",
"139.99.222.72",
"146.112.41.2",
"146.112.41.3",
"146.185.167.43",
"149.112.112.10",
"149.112.112.11",
"149.112.112.112",
"149.112.112.9",
"149.112.121.10",
"149.112.121.20",
"149.112.121.30",
"149.112.122.10",
"149.112.122.20",
"149.112.122.30",
"159.69.198.101",
"168.235.81.167",
"172.104.93.80",
"172.65.3.223",
"174.138.29.175",
"174.68.248.77",
"176.103.130.130",
"176.103.130.131",
"176.103.130.132",
"176.103.130.134",
"176.56.236.175",
"178.62.214.105",
"185.134.196.54",
"185.134.197.54",
"185.213.26.187",
"185.216.27.142",
"185.228.168.10",
"185.228.168.168",
"185.235.81.1",
"185.26.126.37",
"185.26.126.37",
"185.43.135.1",
"185.95.218.42",
"185.95.218.43",
"195.30.94.28",
"2001:148f:fffe::1",
"2001:19f0:7001:3259:5400:2ff:fe71:bc9",
"2001:19f0:7001:5554:5400:2ff:fe57:3077",
"2001:19f0:7001:5554:5400:2ff:fe57:3077",
"2001:19f0:7001:5554:5400:2ff:fe57:3077",
"2001:4860:4860::8844",
"2001:4860:4860::8888",
"2001:4b98:dc2:43:216:3eff:fe86:1d28",
"2001:558:fe21:6b:96:113:151:149",
"2001:608:a01::3",
"2001:678:888:69:c45d:2738:c3f2:1878",
"2001:8b0::2022",
"2001:8b0::2023",
"2001:c50:ffff:1:101:101:101:101",
"210.17.9.228",
"217.169.20.22",
"217.169.20.23",
"2400:6180:0:d0::5f73:4001",
"2400:8902::f03c:91ff:feda:c514",
"2604:180:f3::42",
"2604:a880:1:20::51:f001",
"2606:4700::6810:f8f9",
"2606:4700::6810:f9f9",
"2606:4700::6812:1a80",
"2606:4700::6812:1b80",
"2606:4700::6812:237",
"2606:4700::6812:337",
"2606:4700:3033::6812:2ccc",
"2606:4700:3033::6812:2dcc",
"2606:4700:3033::6818:7b35",
"2606:4700:3034::681c:16a",
"2606:4700:3035::6818:7a35",
"2606:4700:3035::681f:5a8a",
"2606:4700:3036::681c:6a",
"2606:4700:3036::681f:5b8a",
"2606:4700:60:0:a71e:6467:cef8:2a56",
"2620:10a:80bb::10",
"2620:10a:80bb::20",
"2620:10a:80bb::30",
"2620:10a:80bc::10",
"2620:10a:80bc::20",
"2620:10a:80bc::30",
"2620:119:fc::2",
"2620:119:fc::3",
"2620:fe::10",
"2620:fe::11",
"2620:fe::9",
"2620:fe::fe:10",
"2620:fe::fe:11",
"2620:fe::fe:9",
"2620:fe::fe",
"2a00:5a60::ad1:ff",
"2a00:5a60::ad2:ff",
"2a00:5a60::bad1:ff",
"2a00:5a60::bad2:ff",
"2a00:d880:5:bf0::7c93",
"2a01:4f8:1c0c:8233::1",
"2a01:4f8:1c1c:6b4b::1",
"2a01:4f8:c2c:52bf::1",
"2a01:4f9:c010:43ce::1",
"2a01:4f9:c01f:4::abcd",
"2a01:7c8:d002:1ef:5054:ff:fe40:3703",
"2a01:9e00::54",
"2a01:9e00::55",
"2a01:9e01::54",
"2a01:9e01::55",
"2a02:1205:34d5:5070:b26e:bfff:fe1d:e19b",
"2a03:4000:38:53c::2",
"2a03:b0c0:0:1010::e9a:3001",
"2a04:bdc7:100:70::abcd",
"2a05:fc84::42",
"2a05:fc84::43",
"2a07:a8c0::",
"2a0d:4d00:81::1",
"2a0d:5600:33:3::abcd",
"35.198.2.76",
"35.231.247.227",
"45.32.55.94",
"45.67.219.208",
"45.76.113.31",
"45.77.180.10",
"45.90.28.0",
"46.101.66.244",
"46.227.200.54",
"46.227.200.55",
"46.239.223.80",
"8.8.4.4",
"8.8.8.8",
"83.77.85.7",
"88.198.91.187",
"9.9.9.10",
"9.9.9.11",
"9.9.9.9",
"94.130.106.88",
"95.216.181.228",
"95.216.212.177",
"96.113.151.148",
],
}
# additional hostnames to block
additional_doh_names: list[str] = ["dns.google.com"]
# additional IPs to block
additional_doh_ips: list[str] = []
doh_hostnames, doh_ips = default_blocklist["hostnames"], default_blocklist["ips"]
# convert to sets for faster lookups
doh_hostnames = set(doh_hostnames)
doh_ips = set(doh_ips)
def _has_dns_message_content_type(flow):
"""
Check if HTTP request has a DNS-looking 'Content-Type' header
:param flow: mitmproxy flow
:return: True if 'Content-Type' header is DNS-looking, False otherwise
"""
doh_content_types = ["application/dns-message"]
if "Content-Type" in flow.request.headers:
if flow.request.headers["Content-Type"] in doh_content_types:
return True
return False
def _request_has_dns_query_string(flow):
"""
Check if the query string of a request contains the parameter 'dns'
:param flow: mitmproxy flow
:return: True is 'dns' is a parameter in the query string, False otherwise
"""
return "dns" in flow.request.query
def _request_is_dns_json(flow):
"""
Check if the request looks like DoH with JSON.
The only known implementations of DoH with JSON are Cloudflare and Google.
For more info, see:
- https://developers.cloudflare.com/1.1.1.1/dns-over-https/json-format/
- https://developers.google.com/speed/public-dns/docs/doh/json
:param flow: mitmproxy flow
:return: True is request looks like DNS JSON, False otherwise
"""
# Header 'Accept: application/dns-json' is required in Cloudflare's DoH JSON API
# or they return a 400 HTTP response code
if "Accept" in flow.request.headers:
if flow.request.headers["Accept"] == "application/dns-json":
return True
# Google's DoH JSON API is https://dns.google/resolve
path = flow.request.path.split("?")[0]
if flow.request.host == "dns.google" and path == "/resolve":
return True
return False
def _request_has_doh_looking_path(flow):
"""
Check if the path looks like it's DoH.
Most common one is '/dns-query', likely because that's what's in the RFC
:param flow: mitmproxy flow
:return: True if path looks like it's DoH, otherwise False
"""
doh_paths = [
"/dns-query", # used in example in RFC 8484 (see https://tools.ietf.org/html/rfc8484#section-4.1.1)
]
path = flow.request.path.split("?")[0]
return path in doh_paths
def _requested_hostname_is_in_doh_blocklist(flow):
"""
Check if server hostname is in our DoH provider blocklist.
The current blocklist is taken from https://github.com/curl/curl/wiki/DNS-over-HTTPS.
:param flow: mitmproxy flow
:return: True if server's hostname is in DoH blocklist, otherwise False
"""
hostname = flow.request.host
ip = flow.server_conn.address
return hostname in doh_hostnames or hostname in doh_ips or ip in doh_ips
doh_request_detection_checks = [
_has_dns_message_content_type,
_request_has_dns_query_string,
_request_is_dns_json,
_requested_hostname_is_in_doh_blocklist,
_request_has_doh_looking_path,
]
def request(flow):
for check in doh_request_detection_checks:
is_doh = check(flow)
if is_doh:
logging.warning(
'[DoH Detection] DNS over HTTPS request detected via method "%s"'
% check.__name__
)
flow.kill()
break
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/change_upstream_proxy.py | examples/contrib/change_upstream_proxy.py | from mitmproxy import http
from mitmproxy.connection import Server
from mitmproxy.net.server_spec import ServerSpec
# This scripts demonstrates how mitmproxy can switch to a second/different upstream proxy
# in upstream proxy mode.
#
# Usage: mitmdump
# -s change_upstream_proxy.py
# --mode upstream:http://default-upstream-proxy:8080/
# --set connection_strategy=lazy
# --set upstream_cert=false
#
# If you want to change the target server, you should modify flow.request.host and flow.request.port
def proxy_address(flow: http.HTTPFlow) -> tuple[str, int]:
# Poor man's loadbalancing: route every second domain through the alternative proxy.
if hash(flow.request.host) % 2 == 1:
return ("localhost", 8082)
else:
return ("localhost", 8081)
def request(flow: http.HTTPFlow) -> None:
address = proxy_address(flow)
is_proxy_change = address != flow.server_conn.via[1]
server_connection_already_open = flow.server_conn.timestamp_start is not None
if is_proxy_change and server_connection_already_open:
# server_conn already refers to an existing connection (which cannot be modified),
# so we need to replace it with a new server connection object.
flow.server_conn = Server(address=flow.server_conn.address)
flow.server_conn.via = ServerSpec(("http", address))
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/tls_passthrough.py | examples/contrib/tls_passthrough.py | """
This addon allows conditional TLS Interception based on a user-defined strategy.
Example:
> mitmdump -s tls_passthrough.py
1. curl --proxy http://localhost:8080 https://example.com --insecure
// works - we'll also see the contents in mitmproxy
2. curl --proxy http://localhost:8080 https://example.com
// fails with a certificate error, which we will also see in mitmproxy
3. curl --proxy http://localhost:8080 https://example.com
// works again, but mitmproxy does not intercept and we do *not* see the contents
"""
import collections
import logging
import random
from abc import ABC
from abc import abstractmethod
from enum import Enum
from mitmproxy import connection
from mitmproxy import ctx
from mitmproxy import tls
from mitmproxy.addonmanager import Loader
from mitmproxy.utils import human
class InterceptionResult(Enum):
SUCCESS = 1
FAILURE = 2
SKIPPED = 3
class TlsStrategy(ABC):
def __init__(self):
# A server_address -> interception results mapping
self.history = collections.defaultdict(lambda: collections.deque(maxlen=200))
@abstractmethod
def should_intercept(self, server_address: connection.Address) -> bool:
raise NotImplementedError()
def record_success(self, server_address):
self.history[server_address].append(InterceptionResult.SUCCESS)
def record_failure(self, server_address):
self.history[server_address].append(InterceptionResult.FAILURE)
def record_skipped(self, server_address):
self.history[server_address].append(InterceptionResult.SKIPPED)
class ConservativeStrategy(TlsStrategy):
"""
Conservative Interception Strategy - only intercept if there haven't been any failed attempts
in the history.
"""
def should_intercept(self, server_address: connection.Address) -> bool:
return InterceptionResult.FAILURE not in self.history[server_address]
class ProbabilisticStrategy(TlsStrategy):
"""
Fixed probability that we intercept a given connection.
"""
def __init__(self, p: float):
self.p = p
super().__init__()
def should_intercept(self, server_address: connection.Address) -> bool:
return random.uniform(0, 1) < self.p
class MaybeTls:
strategy: TlsStrategy
def load(self, loader: Loader):
loader.add_option(
"tls_strategy",
int,
0,
"TLS passthrough strategy. If set to 0, connections will be passed through after the first unsuccessful "
"handshake. If set to 0 < p <= 100, connections with be passed through with probability p.",
)
def configure(self, updated):
if "tls_strategy" not in updated:
return
if ctx.options.tls_strategy > 0:
self.strategy = ProbabilisticStrategy(ctx.options.tls_strategy / 100)
else:
self.strategy = ConservativeStrategy()
@staticmethod
def get_addr(server: connection.Server):
# .peername may be unset in upstream proxy mode, so we need a fallback.
return server.peername or server.address
def tls_clienthello(self, data: tls.ClientHelloData):
server_address = self.get_addr(data.context.server)
if not self.strategy.should_intercept(server_address):
logging.info(f"TLS passthrough: {human.format_address(server_address)}.")
data.ignore_connection = True
self.strategy.record_skipped(server_address)
def tls_established_client(self, data: tls.TlsData):
server_address = self.get_addr(data.context.server)
logging.info(
f"TLS handshake successful: {human.format_address(server_address)}"
)
self.strategy.record_success(server_address)
def tls_failed_client(self, data: tls.TlsData):
server_address = self.get_addr(data.context.server)
logging.info(f"TLS handshake failed: {human.format_address(server_address)}")
self.strategy.record_failure(server_address)
addons = [MaybeTls()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/modify_body_inject_iframe.py | examples/contrib/modify_body_inject_iframe.py | # (this script works best with --anticache)
from bs4 import BeautifulSoup
from mitmproxy import ctx
from mitmproxy import http
class Injector:
def load(self, loader):
loader.add_option("iframe", str, "", "IFrame to inject")
def response(self, flow: http.HTTPFlow) -> None:
if ctx.options.iframe:
html = BeautifulSoup(flow.response.content, "html.parser")
if html.body:
iframe = html.new_tag(
"iframe", src=ctx.options.iframe, frameborder=0, height=0, width=0
)
html.body.insert(0, iframe)
flow.response.content = str(html).encode("utf8")
addons = [Injector()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/suppress_error_responses.py | examples/contrib/suppress_error_responses.py | """
This script suppresses the 502 Bad Gateway messages, mitmproxy sends if the server is not responsing correctly.
For example, this functionality can be helpful if mitmproxy is used in between a web scanner and a web application.
Without this script, if the web application under test crashes, mitmproxy will send 502 Bad Gateway responses.
These responses are irritating the web application scanner since they obfuscate the actual problem.
"""
from mitmproxy import http
from mitmproxy.exceptions import HttpSyntaxException
def error(self, flow: http.HTTPFlow):
"""Kills the flow if it has an error different to HTTPSyntaxException.
Sometimes, web scanners generate malformed HTTP syntax on purpose and we do not want to kill these requests.
"""
if flow.error is not None and not isinstance(flow.error, HttpSyntaxException):
flow.kill()
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/check_ssl_pinning.py | examples/contrib/check_ssl_pinning.py | import ipaddress
import time
import OpenSSL
import mitmproxy
from mitmproxy import ctx
from mitmproxy.certs import Cert
# Certificate for client connection is generated in dummy_cert() in certs.py. Monkeypatching
# the function to generate test cases for SSL Pinning.
def monkey_dummy_cert(privkey, cacert, commonname, sans):
ss = []
for i in sans:
try:
ipaddress.ip_address(i.decode("ascii"))
except ValueError:
# Change values in Certificate's Alt Name as well.
if ctx.options.certwrongCN:
ss.append(b"DNS:%sm" % i)
else:
ss.append(b"DNS:%s" % i)
else:
ss.append(b"IP:%s" % i)
ss = b", ".join(ss)
cert = OpenSSL.crypto.X509()
if ctx.options.certbeginon:
# Set certificate start time somewhere in the future
cert.gmtime_adj_notBefore(3600 * 48)
else:
cert.gmtime_adj_notBefore(-3600 * 48)
if ctx.options.certexpire:
# sets the expire date of the certificate in the past.
cert.gmtime_adj_notAfter(-3600 * 24)
else:
cert.gmtime_adj_notAfter(94608000) # = 24 * 60 * 60 * 365 * 3
cert.set_issuer(cacert.get_subject())
if commonname is not None and len(commonname) < 64:
if ctx.options.certwrongCN:
# append an extra char to make certs common name different than original one.
# APpending a char in the end of the domain name.
new_cn = commonname + b"m"
cert.get_subject().CN = new_cn
else:
cert.get_subject().CN = commonname
cert.set_serial_number(int(time.time() * 10000))
if ss:
cert.set_version(2)
cert.add_extensions(
[OpenSSL.crypto.X509Extension(b"subjectAltName", False, ss)]
)
cert.set_pubkey(cacert.get_pubkey())
cert.sign(privkey, "sha256")
return Cert(cert)
class CheckSSLPinning:
def load(self, loader):
loader.add_option(
"certbeginon",
bool,
False,
"""
Sets SSL Certificate's 'Begins On' time in future.
""",
)
loader.add_option(
"certexpire",
bool,
False,
"""
Sets SSL Certificate's 'Expires On' time in the past.
""",
)
loader.add_option(
"certwrongCN",
bool,
False,
"""
Sets SSL Certificate's CommonName(CN) different from the domain name.
""",
)
def clientconnect(self, layer):
mitmproxy.certs.dummy_cert = monkey_dummy_cert
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/dns_spoofing.py | examples/contrib/dns_spoofing.py | """
This script makes it possible to use mitmproxy in scenarios where IP spoofing
has been used to redirect connections to mitmproxy. The way this works is that
we rely on either the TLS Server Name Indication (SNI) or the Host header of the
HTTP request. Of course, this is not foolproof - if an HTTPS connection comes
without SNI, we don't know the actual target and cannot construct a certificate
that looks valid. Similarly, if there's no Host header or a spoofed Host header,
we're out of luck as well. Using transparent mode is the better option most of
the time.
Usage:
mitmproxy
-p 443
-s dns_spoofing.py
# Used as the target location if neither SNI nor host header are present.
--mode reverse:http://example.com/
# To avoid auto rewriting of host header by the reverse proxy target.
--set keep_host_header
mitmdump
-p 80
--mode reverse:http://localhost:443/
(Setting up a single proxy instance and using iptables to redirect to it
works as well)
"""
import re
# This regex extracts splits the host header into host and port.
# Handles the edge case of IPv6 addresses containing colons.
# https://bugzilla.mozilla.org/show_bug.cgi?id=45891
parse_host_header = re.compile(r"^(?P<host>[^:]+|\[.+\])(?::(?P<port>\d+))?$")
class Rerouter:
def request(self, flow):
if flow.client_conn.tls_established:
flow.request.scheme = "https"
sni = flow.client_conn.sni
port = 443
else:
flow.request.scheme = "http"
sni = None
port = 80
host_header = flow.request.host_header
m = parse_host_header.match(host_header)
if m:
host_header = m.group("host").strip("[]")
if m.group("port"):
port = int(m.group("port"))
flow.request.host_header = host_header
flow.request.host = sni or host_header
flow.request.port = port
addons = [Rerouter()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/link_expander.py | examples/contrib/link_expander.py | # This script determines if request is an HTML webpage and if so seeks out
# relative links (<a href="./about.html">) and expands them to absolute links
# In practice this can be used to front an indexing spider that may not have the capability to expand relative page links.
# Usage: mitmdump -s link_expander.py or mitmproxy -s link_expander.py
import re
from urllib.parse import urljoin
def response(flow):
if (
"Content-Type" in flow.response.headers
and flow.response.headers["Content-Type"].find("text/html") != -1
):
pageUrl = flow.request.url
pageText = flow.response.text
pattern = (
r"<a\s+(?:[^>]*?\s+)?href=(?P<delimiter>[\"'])"
r"(?P<link>(?!https?:\/\/|ftps?:\/\/|\/\/|#|javascript:|mailto:).*?)(?P=delimiter)"
)
rel_matcher = re.compile(pattern, flags=re.IGNORECASE)
rel_matches = rel_matcher.finditer(pageText)
map_dict = {}
for match_num, match in enumerate(rel_matches):
(delimiter, rel_link) = match.group("delimiter", "link")
abs_link = urljoin(pageUrl, rel_link)
map_dict["{0}{1}{0}".format(delimiter, rel_link)] = "{0}{1}{0}".format(
delimiter, abs_link
)
for map in map_dict.items():
pageText = pageText.replace(*map)
# Uncomment the following to print the expansion mapping
# print("{0} -> {1}".format(*map))
flow.response.text = pageText
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/har_dump.py | examples/contrib/har_dump.py | """
This addon is now part of mitmproxy! See mitmproxy/addons/savehar.py.
"""
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/jsondump.py | examples/contrib/jsondump.py | """
This script serializes the entire traffic dump, including websocket traffic,
as JSON, and either sends it to a URL or writes to a file. The serialization
format is optimized for Elasticsearch; the script can be used to send all
captured traffic to Elasticsearch directly.
Usage:
mitmproxy
--mode reverse:http://example.com/
-s examples/complex/jsondump.py
Configuration:
Send to a URL:
cat > ~/.mitmproxy/config.yaml <<EOF
dump_destination: "https://elastic.search.local/my-index/my-type"
# Optional Basic auth:
dump_username: "never-gonna-give-you-up"
dump_password: "never-gonna-let-you-down"
# Optional base64 encoding of content fields
# to store as binary fields in Elasticsearch:
dump_encodecontent: true
EOF
Dump to a local file:
cat > ~/.mitmproxy/config.yaml <<EOF
dump_destination: "/user/rastley/output.log"
EOF
"""
import base64
import json
import logging
from queue import Queue
from threading import Lock
from threading import Thread
import requests
from mitmproxy import ctx
FILE_WORKERS = 1
HTTP_WORKERS = 10
class JSONDumper:
"""
JSONDumper performs JSON serialization and some extra processing
for out-of-the-box Elasticsearch support, and then either writes
the result to a file or sends it to a URL.
"""
def __init__(self):
self.outfile = None
self.transformations = None
self.encode = None
self.url = None
self.lock = None
self.auth = None
self.queue = Queue()
def done(self):
self.queue.join()
if self.outfile:
self.outfile.close()
fields = {
"timestamp": (
("error", "timestamp"),
("request", "timestamp_start"),
("request", "timestamp_end"),
("response", "timestamp_start"),
("response", "timestamp_end"),
("client_conn", "timestamp_start"),
("client_conn", "timestamp_end"),
("client_conn", "timestamp_tls_setup"),
("server_conn", "timestamp_start"),
("server_conn", "timestamp_end"),
("server_conn", "timestamp_tls_setup"),
("server_conn", "timestamp_tcp_setup"),
),
"ip": (
("server_conn", "source_address"),
("server_conn", "ip_address"),
("server_conn", "address"),
("client_conn", "address"),
),
"ws_messages": (("messages",),),
"headers": (
("request", "headers"),
("response", "headers"),
),
"content": (
("request", "content"),
("response", "content"),
),
}
def _init_transformations(self):
self.transformations = [
{
"fields": self.fields["headers"],
"func": dict,
},
{
"fields": self.fields["timestamp"],
"func": lambda t: int(t * 1000),
},
{
"fields": self.fields["ip"],
"func": lambda addr: {
"host": addr[0].replace("::ffff:", ""),
"port": addr[1],
},
},
{
"fields": self.fields["ws_messages"],
"func": lambda ms: [
{
"type": m[0],
"from_client": m[1],
"content": base64.b64encode(bytes(m[2], "utf-8"))
if self.encode
else m[2],
"timestamp": int(m[3] * 1000),
}
for m in ms
],
},
]
if self.encode:
self.transformations.append(
{
"fields": self.fields["content"],
"func": base64.b64encode,
}
)
@staticmethod
def transform_field(obj, path, func):
"""
Apply a transformation function `func` to a value
under the specified `path` in the `obj` dictionary.
"""
for key in path[:-1]:
if not (key in obj and obj[key]):
return
obj = obj[key]
if path[-1] in obj and obj[path[-1]]:
obj[path[-1]] = func(obj[path[-1]])
@classmethod
def convert_to_strings(cls, obj):
"""
Recursively convert all list/dict elements of type `bytes` into strings.
"""
if isinstance(obj, dict):
return {
cls.convert_to_strings(key): cls.convert_to_strings(value)
for key, value in obj.items()
}
elif isinstance(obj, list) or isinstance(obj, tuple):
return [cls.convert_to_strings(element) for element in obj]
elif isinstance(obj, bytes):
return str(obj)[2:-1]
return obj
def worker(self):
while True:
frame = self.queue.get()
self.dump(frame)
self.queue.task_done()
def dump(self, frame):
"""
Transform and dump (write / send) a data frame.
"""
for tfm in self.transformations:
for field in tfm["fields"]:
self.transform_field(frame, field, tfm["func"])
frame = self.convert_to_strings(frame)
if self.outfile:
self.lock.acquire()
self.outfile.write(json.dumps(frame) + "\n")
self.lock.release()
else:
requests.post(self.url, json=frame, auth=(self.auth or None))
@staticmethod
def load(loader):
"""
Extra options to be specified in `~/.mitmproxy/config.yaml`.
"""
loader.add_option(
"dump_encodecontent", bool, False, "Encode content as base64."
)
loader.add_option(
"dump_destination",
str,
"jsondump.out",
"Output destination: path to a file or URL.",
)
loader.add_option(
"dump_username", str, "", "Basic auth username for URL destinations."
)
loader.add_option(
"dump_password", str, "", "Basic auth password for URL destinations."
)
def configure(self, _):
"""
Determine the destination type and path, initialize the output
transformation rules.
"""
self.encode = ctx.options.dump_encodecontent
if ctx.options.dump_destination.startswith("http"):
self.outfile = None
self.url = ctx.options.dump_destination
logging.info("Sending all data frames to %s" % self.url)
if ctx.options.dump_username and ctx.options.dump_password:
self.auth = (ctx.options.dump_username, ctx.options.dump_password)
logging.info("HTTP Basic auth enabled.")
else:
self.outfile = open(ctx.options.dump_destination, "a")
self.url = None
self.lock = Lock()
logging.info("Writing all data frames to %s" % ctx.options.dump_destination)
self._init_transformations()
for i in range(FILE_WORKERS if self.outfile else HTTP_WORKERS):
t = Thread(target=self.worker)
t.daemon = True
t.start()
def response(self, flow):
"""
Dump request/response pairs.
"""
self.queue.put(flow.get_state())
def error(self, flow):
"""
Dump errors.
"""
self.queue.put(flow.get_state())
def websocket_end(self, flow):
"""
Dump websocket messages once the connection ends.
Alternatively, you can replace `websocket_end` with
`websocket_message` if you want the messages to be
dumped one at a time with full metadata. Warning:
this takes up _a lot_ of space.
"""
self.queue.put(flow.get_state())
addons = [JSONDumper()] # pylint: disable=invalid-name
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/httpdump.py | examples/contrib/httpdump.py | #!/usr/bin/env python
# dump content to files based on a filter
# usage: mitmdump -s httpdump.py "~ts application/json"
#
# options:
# - dumper_folder: content dump destination folder (default: ./httpdump)
# - open_browser: open integrated browser with proxy configured at start (default: true)
#
# remember to add your own mitmproxy authoritative certs in your browser/os!
# certs docs: https://docs.mitmproxy.org/stable/concepts-certificates/
# filter expressions docs: https://docs.mitmproxy.org/stable/concepts-filters/
import logging
import mimetypes
import os
from pathlib import Path
from mitmproxy import ctx
from mitmproxy import flowfilter
from mitmproxy import http
class HTTPDump:
def load(self, loader):
self.filter = ctx.options.dumper_filter
loader.add_option(
name="dumper_folder",
typespec=str,
default="httpdump",
help="content dump destination folder",
)
loader.add_option(
name="open_browser",
typespec=bool,
default=True,
help="open integrated browser at start",
)
def running(self):
if ctx.options.open_browser:
ctx.master.commands.call("browser.start")
def configure(self, updated):
if "dumper_filter" in updated:
self.filter = ctx.options.dumper_filter
def response(self, flow: http.HTTPFlow) -> None:
if flowfilter.match(self.filter, flow):
self.dump(flow)
def dump(self, flow: http.HTTPFlow):
if not flow.response:
return
# create dir
folder = Path(ctx.options.dumper_folder) / flow.request.host
if not folder.exists():
os.makedirs(folder)
# calculate path
path = "-".join(flow.request.path_components)
filename = "-".join([path, flow.id])
content_type = flow.response.headers.get("content-type", "").split(";")[0]
ext = mimetypes.guess_extension(content_type) or ""
filepath = folder / f"{filename}{ext}"
# dump to file
if flow.response.content:
with open(filepath, "wb") as f:
f.write(flow.response.content)
logging.info(f"Saved! {filepath}")
addons = [HTTPDump()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/test_jsondump.py | examples/contrib/test_jsondump.py | import base64
import json
import requests_mock
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy.test import tutils
example_dir = tutils.test_data.push("../examples")
class TestJSONDump:
def echo_response(self, request, context):
self.request = {"json": request.json(), "headers": request.headers}
return ""
def flow(self, resp_content=b"message"):
times = dict(
timestamp_start=746203272,
timestamp_end=746203272,
)
# Create a dummy flow for testing
return tflow.tflow(
req=tutils.treq(method=b"GET", **times),
resp=tutils.tresp(content=resp_content, **times),
)
def test_simple(self, tmpdir):
with taddons.context() as tctx:
a = tctx.script(example_dir.path("complex/jsondump.py"))
path = str(tmpdir.join("jsondump.out"))
tctx.configure(a, dump_destination=path)
tctx.invoke(a, "response", self.flow())
tctx.invoke(a, "done")
with open(path) as inp:
entry = json.loads(inp.readline())
assert entry["response"]["content"] == "message"
def test_contentencode(self, tmpdir):
with taddons.context() as tctx:
a = tctx.script(example_dir.path("complex/jsondump.py"))
path = str(tmpdir.join("jsondump.out"))
content = b"foo" + b"\xff" * 10
tctx.configure(a, dump_destination=path, dump_encodecontent=True)
tctx.invoke(a, "response", self.flow(resp_content=content))
tctx.invoke(a, "done")
with open(path) as inp:
entry = json.loads(inp.readline())
assert entry["response"]["content"] == base64.b64encode(content).decode(
"utf-8"
)
def test_http(self, tmpdir):
with requests_mock.Mocker() as mock:
mock.post("http://my-server", text=self.echo_response)
with taddons.context() as tctx:
a = tctx.script(example_dir.path("complex/jsondump.py"))
tctx.configure(
a,
dump_destination="http://my-server",
dump_username="user",
dump_password="pass",
)
tctx.invoke(a, "response", self.flow())
tctx.invoke(a, "done")
assert self.request["json"]["response"]["content"] == "message"
assert self.request["headers"]["Authorization"] == "Basic dXNlcjpwYXNz"
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/xss_scanner.py | examples/contrib/xss_scanner.py | r"""
__ __ _____ _____ _____
\ \ / // ____/ ____| / ____|
\ V /| (___| (___ | (___ ___ __ _ _ __ _ __ ___ _ __
> < \___ \\___ \ \___ \ / __/ _` | '_ \| '_ \ / _ \ '__|
/ . \ ____) |___) | ____) | (_| (_| | | | | | | | __/ |
/_/ \_\_____/_____/ |_____/ \___\__,_|_| |_|_| |_|\___|_|
This script automatically scans all visited webpages for XSS and SQLi vulnerabilities.
Usage: mitmproxy -s xss_scanner.py
This script scans for vulnerabilities by injecting a fuzzing payload (see PAYLOAD below) into 4 different places
and examining the HTML to look for XSS and SQLi injection vulnerabilities. The XSS scanning functionality works by
looking to see whether it is possible to inject HTML based off of of where the payload appears in the page and what
characters are escaped. In addition, it also looks for any script tags that load javascript from unclaimed domains.
The SQLi scanning functionality works by using regular expressions to look for errors from a number of different
common databases. Since it is only looking for errors, it will not find blind SQLi vulnerabilities.
The 4 places it injects the payload into are:
1. URLs (e.g. https://example.com/ -> https://example.com/PAYLOAD/)
2. Queries (e.g. https://example.com/index.html?a=b -> https://example.com/index.html?a=PAYLOAD)
3. Referers (e.g. The referer changes from https://example.com to PAYLOAD)
4. User Agents (e.g. The UA changes from Chrome to PAYLOAD)
Reports from this script show up in the event log (viewable by pressing e) and formatted like:
===== XSS Found ====
XSS URL: http://daviddworken.com/vulnerableUA.php
Injection Point: User Agent
Suggested Exploit: <script>alert(0)</script>
Line: 1029zxcs'd"ao<ac>so[sb]po(pc)se;sl/bsl\eq=3847asd
"""
import logging
import re
import socket
from html.parser import HTMLParser
from typing import NamedTuple
from typing import Optional
from urllib.parse import urlparse
import requests
from mitmproxy import http
# The actual payload is put between a frontWall and a backWall to make it easy
# to locate the payload with regular expressions
FRONT_WALL = b"1029zxc"
BACK_WALL = b"3847asd"
PAYLOAD = b"""s'd"ao<ac>so[sb]po(pc)se;sl/bsl\\eq="""
FULL_PAYLOAD = FRONT_WALL + PAYLOAD + BACK_WALL
# A XSSData is a named tuple with the following fields:
# - url -> str
# - injection_point -> str
# - exploit -> str
# - line -> str
class XSSData(NamedTuple):
url: str
injection_point: str
exploit: str
line: str
# A SQLiData is named tuple with the following fields:
# - url -> str
# - injection_point -> str
# - regex -> str
# - dbms -> str
class SQLiData(NamedTuple):
url: str
injection_point: str
regex: str
dbms: str
VulnData = tuple[Optional[XSSData], Optional[SQLiData]]
Cookies = dict[str, str]
def get_cookies(flow: http.HTTPFlow) -> Cookies:
"""Return a dict going from cookie names to cookie values
- Note that it includes both the cookies sent in the original request and
the cookies sent by the server"""
return {name: value for name, value in flow.request.cookies.fields}
def find_unclaimed_URLs(body, requestUrl):
"""Look for unclaimed URLs in script tags and log them if found"""
def getValue(attrs: list[tuple[str, str]], attrName: str) -> str | None:
for name, value in attrs:
if attrName == name:
return value
return None
class ScriptURLExtractor(HTMLParser):
script_URLs: list[str] = []
def handle_starttag(self, tag, attrs):
if (tag == "script" or tag == "iframe") and "src" in [
name for name, value in attrs
]:
self.script_URLs.append(getValue(attrs, "src"))
if (
tag == "link"
and getValue(attrs, "rel") == "stylesheet"
and "href" in [name for name, value in attrs]
):
self.script_URLs.append(getValue(attrs, "href"))
parser = ScriptURLExtractor()
parser.feed(body)
for url in parser.script_URLs:
url_parser = urlparse(url)
domain = url_parser.netloc
try:
socket.gethostbyname(domain)
except socket.gaierror:
logging.error(f'XSS found in {requestUrl} due to unclaimed URL "{url}".')
def test_end_of_URL_injection(
original_body: str, request_URL: str, cookies: Cookies
) -> VulnData:
"""Test the given URL for XSS via injection onto the end of the URL and
log the XSS if found"""
parsed_URL = urlparse(request_URL)
path = parsed_URL.path
if path != "" and path[-1] != "/": # ensure the path ends in a /
path += "/"
path += FULL_PAYLOAD.decode(
"utf-8"
) # the path must be a string while the payload is bytes
url = parsed_URL._replace(path=path).geturl()
body = requests.get(url, cookies=cookies).text.lower()
xss_info = get_XSS_data(body, url, "End of URL")
sqli_info = get_SQLi_data(body, original_body, url, "End of URL")
return xss_info, sqli_info
def test_referer_injection(
original_body: str, request_URL: str, cookies: Cookies
) -> VulnData:
"""Test the given URL for XSS via injection into the referer and
log the XSS if found"""
body = requests.get(
request_URL, headers={"referer": FULL_PAYLOAD}, cookies=cookies
).text.lower()
xss_info = get_XSS_data(body, request_URL, "Referer")
sqli_info = get_SQLi_data(body, original_body, request_URL, "Referer")
return xss_info, sqli_info
def test_user_agent_injection(
original_body: str, request_URL: str, cookies: Cookies
) -> VulnData:
"""Test the given URL for XSS via injection into the user agent and
log the XSS if found"""
body = requests.get(
request_URL, headers={"User-Agent": FULL_PAYLOAD}, cookies=cookies
).text.lower()
xss_info = get_XSS_data(body, request_URL, "User Agent")
sqli_info = get_SQLi_data(body, original_body, request_URL, "User Agent")
return xss_info, sqli_info
def test_query_injection(original_body: str, request_URL: str, cookies: Cookies):
"""Test the given URL for XSS via injection into URL queries and
log the XSS if found"""
parsed_URL = urlparse(request_URL)
query_string = parsed_URL.query
# queries is a list of parameters where each parameter is set to the payload
queries = [
query.split("=")[0] + "=" + FULL_PAYLOAD.decode("utf-8")
for query in query_string.split("&")
]
new_query_string = "&".join(queries)
new_URL = parsed_URL._replace(query=new_query_string).geturl()
body = requests.get(new_URL, cookies=cookies).text.lower()
xss_info = get_XSS_data(body, new_URL, "Query")
sqli_info = get_SQLi_data(body, original_body, new_URL, "Query")
return xss_info, sqli_info
def log_XSS_data(xss_info: XSSData | None) -> None:
"""Log information about the given XSS to mitmproxy"""
# If it is None, then there is no info to log
if not xss_info:
return
logging.error("===== XSS Found ====")
logging.error("XSS URL: %s" % xss_info.url)
logging.error("Injection Point: %s" % xss_info.injection_point)
logging.error("Suggested Exploit: %s" % xss_info.exploit)
logging.error("Line: %s" % xss_info.line)
def log_SQLi_data(sqli_info: SQLiData | None) -> None:
"""Log information about the given SQLi to mitmproxy"""
if not sqli_info:
return
logging.error("===== SQLi Found =====")
logging.error("SQLi URL: %s" % sqli_info.url)
logging.error("Injection Point: %s" % sqli_info.injection_point)
logging.error("Regex used: %s" % sqli_info.regex)
logging.error("Suspected DBMS: %s" % sqli_info.dbms)
return
def get_SQLi_data(
new_body: str, original_body: str, request_URL: str, injection_point: str
) -> SQLiData | None:
"""Return a SQLiDict if there is a SQLi otherwise return None
String String URL String -> (SQLiDict or None)"""
# Regexes taken from Damn Small SQLi Scanner: https://github.com/stamparm/DSSS/blob/master/dsss.py#L17
DBMS_ERRORS = {
"MySQL": (
r"SQL syntax.*MySQL",
r"Warning.*mysql_.*",
r"valid MySQL result",
r"MySqlClient\.",
),
"PostgreSQL": (
r"PostgreSQL.*ERROR",
r"Warning.*\Wpg_.*",
r"valid PostgreSQL result",
r"Npgsql\.",
),
"Microsoft SQL Server": (
r"Driver.* SQL[\-\_\ ]*Server",
r"OLE DB.* SQL Server",
r"(\W|\A)SQL Server.*Driver",
r"Warning.*mssql_.*",
r"(\W|\A)SQL Server.*[0-9a-fA-F]{8}",
r"(?s)Exception.*\WSystem\.Data\.SqlClient\.",
r"(?s)Exception.*\WRoadhouse\.Cms\.",
),
"Microsoft Access": (
r"Microsoft Access Driver",
r"JET Database Engine",
r"Access Database Engine",
),
"Oracle": (
r"\bORA-[0-9][0-9][0-9][0-9]",
r"Oracle error",
r"Oracle.*Driver",
r"Warning.*\Woci_.*",
r"Warning.*\Wora_.*",
),
"IBM DB2": (r"CLI Driver.*DB2", r"DB2 SQL error", r"\bdb2_\w+\("),
"SQLite": (
r"SQLite/JDBCDriver",
r"SQLite.Exception",
r"System.Data.SQLite.SQLiteException",
r"Warning.*sqlite_.*",
r"Warning.*SQLite3::",
r"\[SQLITE_ERROR\]",
),
"Sybase": (
r"(?i)Warning.*sybase.*",
r"Sybase message",
r"Sybase.*Server message.*",
),
}
for dbms, regexes in DBMS_ERRORS.items():
for regex in regexes: # type: ignore
if re.search(regex, new_body, re.IGNORECASE) and not re.search(
regex, original_body, re.IGNORECASE
):
return SQLiData(request_URL, injection_point, regex, dbms)
return None
# A qc is either ' or "
def inside_quote(
qc: str, substring_bytes: bytes, text_index: int, body_bytes: bytes
) -> bool:
"""Whether the Numberth occurrence of the first string in the second
string is inside quotes as defined by the supplied QuoteChar"""
substring = substring_bytes.decode("utf-8")
body = body_bytes.decode("utf-8")
num_substrings_found = 0
in_quote = False
for index, char in enumerate(body):
# Whether the next chunk of len(substring) chars is the substring
next_part_is_substring = (not (index + len(substring) > len(body))) and (
body[index : index + len(substring)] == substring
)
# Whether this char is escaped with a \
is_not_escaped = (index - 1 < 0 or index - 1 > len(body)) or (
body[index - 1] != "\\"
)
if char == qc and is_not_escaped:
in_quote = not in_quote
if next_part_is_substring:
if num_substrings_found == text_index:
return in_quote
num_substrings_found += 1
return False
def paths_to_text(html: str, string: str) -> list[str]:
"""Return list of Paths to a given str in the given HTML tree
- Note that it does a BFS"""
def remove_last_occurence_of_sub_string(string: str, substr: str) -> str:
"""Delete the last occurrence of substr from str
String String -> String
"""
index = string.rfind(substr)
return string[:index] + string[index + len(substr) :]
class PathHTMLParser(HTMLParser):
currentPath = ""
paths: list[str] = []
def handle_starttag(self, tag, attrs):
self.currentPath += "/" + tag
def handle_endtag(self, tag):
self.currentPath = remove_last_occurence_of_sub_string(
self.currentPath, "/" + tag
)
def handle_data(self, data):
if string in data:
self.paths.append(self.currentPath)
parser = PathHTMLParser()
parser.feed(html)
return parser.paths
def get_XSS_data(
body: str | bytes, request_URL: str, injection_point: str
) -> XSSData | None:
"""Return a XSSDict if there is a XSS otherwise return None"""
def in_script(text, index, body) -> bool:
"""Whether the Numberth occurrence of the first string in the second
string is inside a script tag"""
paths = paths_to_text(body.decode("utf-8"), text.decode("utf-8"))
try:
path = paths[index]
return "script" in path
except IndexError:
return False
def in_HTML(text: bytes, index: int, body: bytes) -> bool:
"""Whether the Numberth occurrence of the first string in the second
string is inside the HTML but not inside a script tag or part of
a HTML attribute"""
# if there is a < then lxml will interpret that as a tag, so only search for the stuff before it
text = text.split(b"<")[0]
paths = paths_to_text(body.decode("utf-8"), text.decode("utf-8"))
try:
path = paths[index]
return "script" not in path
except IndexError:
return False
def inject_javascript_handler(html: str) -> bool:
"""Whether you can inject a Javascript:alert(0) as a link"""
class injectJSHandlerHTMLParser(HTMLParser):
injectJSHandler = False
def handle_starttag(self, tag, attrs):
for name, value in attrs:
if name == "href" and value.startswith(FRONT_WALL.decode("utf-8")):
self.injectJSHandler = True
parser = injectJSHandlerHTMLParser()
parser.feed(html)
return parser.injectJSHandler
# Only convert the body to bytes if needed
if isinstance(body, str):
body = bytes(body, "utf-8")
# Regex for between 24 and 72 (aka 24*3) characters encapsulated by the walls
regex = re.compile(b"""%s.{24,72}?%s""" % (FRONT_WALL, BACK_WALL))
matches = regex.findall(body)
for index, match in enumerate(matches):
# Where the string is injected into the HTML
in_script_val = in_script(match, index, body)
in_HTML_val = in_HTML(match, index, body)
in_tag = not in_script_val and not in_HTML_val
in_single_quotes = inside_quote("'", match, index, body)
in_double_quotes = inside_quote('"', match, index, body)
# Whether you can inject:
inject_open_angle = b"ao<ac" in match # open angle brackets
inject_close_angle = b"ac>so" in match # close angle brackets
inject_single_quotes = b"s'd" in match # single quotes
inject_double_quotes = b'd"ao' in match # double quotes
inject_slash = b"sl/bsl" in match # forward slashes
inject_semi = b"se;sl" in match # semicolons
inject_equals = b"eq=" in match # equals sign
if (
in_script_val and inject_slash and inject_open_angle and inject_close_angle
): # e.g. <script>PAYLOAD</script>
return XSSData(
request_URL,
injection_point,
"</script><script>alert(0)</script><script>",
match.decode("utf-8"),
)
elif (
in_script_val and in_single_quotes and inject_single_quotes and inject_semi
): # e.g. <script>t='PAYLOAD';</script>
return XSSData(
request_URL, injection_point, "';alert(0);g='", match.decode("utf-8")
)
elif (
in_script_val and in_double_quotes and inject_double_quotes and inject_semi
): # e.g. <script>t="PAYLOAD";</script>
return XSSData(
request_URL, injection_point, '";alert(0);g="', match.decode("utf-8")
)
elif (
in_tag
and in_single_quotes
and inject_single_quotes
and inject_open_angle
and inject_close_angle
and inject_slash
):
# e.g. <a href='PAYLOAD'>Test</a>
return XSSData(
request_URL,
injection_point,
"'><script>alert(0)</script>",
match.decode("utf-8"),
)
elif (
in_tag
and in_double_quotes
and inject_double_quotes
and inject_open_angle
and inject_close_angle
and inject_slash
):
# e.g. <a href="PAYLOAD">Test</a>
return XSSData(
request_URL,
injection_point,
'"><script>alert(0)</script>',
match.decode("utf-8"),
)
elif (
in_tag
and not in_double_quotes
and not in_single_quotes
and inject_open_angle
and inject_close_angle
and inject_slash
):
# e.g. <a href=PAYLOAD>Test</a>
return XSSData(
request_URL,
injection_point,
"><script>alert(0)</script>",
match.decode("utf-8"),
)
elif inject_javascript_handler(
body.decode("utf-8")
): # e.g. <html><a href=PAYLOAD>Test</a>
return XSSData(
request_URL,
injection_point,
"Javascript:alert(0)",
match.decode("utf-8"),
)
elif (
in_tag and in_double_quotes and inject_double_quotes and inject_equals
): # e.g. <a href="PAYLOAD">Test</a>
return XSSData(
request_URL,
injection_point,
'" onmouseover="alert(0)" t="',
match.decode("utf-8"),
)
elif (
in_tag and in_single_quotes and inject_single_quotes and inject_equals
): # e.g. <a href='PAYLOAD'>Test</a>
return XSSData(
request_URL,
injection_point,
"' onmouseover='alert(0)' t='",
match.decode("utf-8"),
)
elif (
in_tag and not in_single_quotes and not in_double_quotes and inject_equals
): # e.g. <a href=PAYLOAD>Test</a>
return XSSData(
request_URL,
injection_point,
" onmouseover=alert(0) t=",
match.decode("utf-8"),
)
elif (
in_HTML_val
and not in_script_val
and inject_open_angle
and inject_close_angle
and inject_slash
): # e.g. <html>PAYLOAD</html>
return XSSData(
request_URL,
injection_point,
"<script>alert(0)</script>",
match.decode("utf-8"),
)
else:
return None
return None
# response is mitmproxy's entry point
def response(flow: http.HTTPFlow) -> None:
assert flow.response
cookies_dict = get_cookies(flow)
resp = flow.response.get_text(strict=False)
assert resp
# Example: http://xss.guru/unclaimedScriptTag.html
find_unclaimed_URLs(resp, flow.request.url)
results = test_end_of_URL_injection(resp, flow.request.url, cookies_dict)
log_XSS_data(results[0])
log_SQLi_data(results[1])
# Example: https://daviddworken.com/vulnerableReferer.php
results = test_referer_injection(resp, flow.request.url, cookies_dict)
log_XSS_data(results[0])
log_SQLi_data(results[1])
# Example: https://daviddworken.com/vulnerableUA.php
results = test_user_agent_injection(resp, flow.request.url, cookies_dict)
log_XSS_data(results[0])
log_SQLi_data(results[1])
if "?" in flow.request.url:
# Example: https://daviddworken.com/vulnerable.php?name=
results = test_query_injection(resp, flow.request.url, cookies_dict)
log_XSS_data(results[0])
log_SQLi_data(results[1])
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/portfile.py | examples/contrib/portfile.py | import json
import pathlib
from typing import Optional
from mitmproxy import ctx
class PortFile:
def load(self, loader):
loader.add_option(
name="datadir",
typespec=Optional[str],
default=None,
help="Creates `portfile` mapping proxies (by mode spec) to the port "
"they use in the provided directory.",
)
def running(self):
if not ctx.options.datadir:
return
datadir = pathlib.Path(ctx.options.datadir)
if not datadir.is_dir():
ctx.log.warning("%s is not a directory", datadir)
return
proxies = ctx.master.addons.get("proxyserver")
modemap = {
instance.mode.full_spec: addr[1]
for instance in proxies.servers
# assumes all listen_addrs of a given instance are bound
# to the same port, but as far as I can tell mitmproxy
# works very hard to try and make it so
if (addr := next(iter(instance.listen_addrs), None))
}
with datadir.joinpath("portfile").open("w", encoding="utf-8") as fp:
json.dump(modemap, fp)
addons = [PortFile()]
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/http_manipulate_cookies.py | examples/contrib/http_manipulate_cookies.py | """
This script is an example of how to manipulate cookies both outgoing (requests)
and ingoing (responses). In particular, this script inserts a cookie (specified
in a json file) into every request (overwriting any existing cookie of the same
name), and removes cookies from every response that have a certain set of names
specified in the variable (set) FILTER_COOKIES.
Usage:
mitmproxy -s examples/contrib/http_manipulate_cookies.py
Note:
this was created as a response to SO post:
https://stackoverflow.com/questions/55358072/cookie-manipulation-in-mitmproxy-requests-and-responses
"""
import json
from mitmproxy import http
PATH_TO_COOKIES = "./cookies.json" # insert your path to the cookie file here
FILTER_COOKIES = {
"mycookie",
"_ga",
} # update this to the specific cookie names you want to remove
# NOTE: use a set for lookup efficiency
# -- Helper functions --
def load_json_cookies() -> list[dict[str, str | None]]:
"""
Load a particular json file containing a list of cookies.
"""
with open(PATH_TO_COOKIES) as f:
return json.load(f)
# NOTE: or just hardcode the cookies as [{"name": "", "value": ""}]
def stringify_cookies(cookies: list[dict[str, str | None]]) -> str:
"""
Creates a cookie string from a list of cookie dicts.
"""
return "; ".join(
[
f"{c['name']}={c['value']}"
if c.get("value", None) is not None
else f"{c['name']}"
for c in cookies
]
)
def parse_cookies(cookie_string: str) -> list[dict[str, str | None]]:
"""
Parses a cookie string into a list of cookie dicts.
"""
return [
{"name": g[0], "value": g[1]} if len(g) == 2 else {"name": g[0], "value": None}
for g in [
k.split("=", 1) for k in [c.strip() for c in cookie_string.split(";")] if k
]
]
# -- Main interception functionality --
def request(flow: http.HTTPFlow) -> None:
"""Add a specific set of cookies to every request."""
# obtain any cookies from the request
_req_cookies_str = flow.request.headers.get("cookie", "")
req_cookies = parse_cookies(_req_cookies_str)
# add our cookies to the original cookies from the request
all_cookies = req_cookies + load_json_cookies()
# NOTE: by adding it to the end we should overwrite any existing cookies
# of the same name but if you want to be more careful you can iterate over
# the req_cookies and remove the ones you want to overwrite first.
# modify the request with the combined cookies
flow.request.headers["cookie"] = stringify_cookies(all_cookies)
def response(flow: http.HTTPFlow) -> None:
"""Remove a specific cookie from every response."""
set_cookies_str = flow.response.headers.get_all("set-cookie")
# NOTE: According to docs, for use with the "Set-Cookie" and "Cookie" headers, either use `Response.cookies` or see `Headers.get_all`.
set_cookies_str_modified: list[str] = []
if set_cookies_str:
for cookie in set_cookies_str:
resp_cookies = parse_cookies(cookie)
# remove the cookie we want to remove
resp_cookies = [c for c in resp_cookies if c["name"] not in FILTER_COOKIES]
# append the modified cookies to the list that will change the requested cookies
set_cookies_str_modified.append(stringify_cookies(resp_cookies))
# modify the request with the combined cookies
flow.response.headers.set_all("set-cookie", set_cookies_str_modified)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
mitmproxy/mitmproxy | https://github.com/mitmproxy/mitmproxy/blob/e6aa924bb411a9687b91920b8d094af37bc02b90/examples/contrib/custom_next_layer.py | examples/contrib/custom_next_layer.py | """
This addon demonstrates how to override next_layer to modify the protocol in use.
In this example, we are forcing connections to example.com:443 to instead go as plaintext
to example.com:80.
Example usage:
- mitmdump -s custom_next_layer.py
- curl -x localhost:8080 -k https://example.com
"""
import logging
from mitmproxy import ctx
from mitmproxy.proxy import layer
from mitmproxy.proxy import layers
def running():
# We change the connection strategy to lazy so that next_layer happens before we actually connect upstream.
# Alternatively we could also change the server address in `server_connect`.
ctx.options.connection_strategy = "lazy"
def next_layer(nextlayer: layer.NextLayer):
logging.info(
f"{nextlayer.context=}\n"
f"{nextlayer.data_client()[:70]=}\n"
f"{nextlayer.data_server()[:70]=}\n"
)
if nextlayer.context.server.address == ("example.com", 443):
nextlayer.context.server.address = ("example.com", 80)
# We are disabling ALPN negotiation as our curl client would otherwise agree on HTTP/2,
# which our example server here does not accept for plaintext connections.
nextlayer.context.client.alpn = b""
# We know all layers that come next: First negotiate TLS with the client, then do simple TCP passthrough.
# Setting only one layer here would also work, in that case next_layer would be called again after TLS establishment.
nextlayer.layer = layers.ClientTLSLayer(nextlayer.context)
nextlayer.layer.child_layer = layers.TCPLayer(nextlayer.context)
| python | MIT | e6aa924bb411a9687b91920b8d094af37bc02b90 | 2026-01-04T14:40:00.086164Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.