From 7093e50826ebc24b551a26d4e0882ee504817679 Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Tue, 11 Nov 2025 17:02:35 +0100 Subject: [PATCH] Add example addon for DNS flows (#7973) * add example addon for DNS flows * [autofix.ci] apply automated fixes * fix mypy --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> --- CHANGELOG.md | 2 ++ examples/addons/dns-simple.py | 38 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 examples/addons/dns-simple.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 884878d09..b6499c52c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ ([#7933](https://github.com/mitmproxy/mitmproxy/pull/7933), @caiquejjx, @mhils) - Fix various issues in infer_content_encoding ([#7928](https://github.com/mitmproxy/mitmproxy/pull/7928), @xu-cheng) +- Add example addon to spoof DNS responses. + ([#7973](https://github.com/mitmproxy/mitmproxy/pull/7973), @mhils) - Gracefully handle decoding of raw binary payloads that previously caused "Raw cannot decode" or "failed to parse as JSON" errors ([#7940](https://github.com/mitmproxy/mitmproxy/pull/7940), @AdityaPatadiya) diff --git a/examples/addons/dns-simple.py b/examples/addons/dns-simple.py new file mode 100644 index 000000000..69c742d7c --- /dev/null +++ b/examples/addons/dns-simple.py @@ -0,0 +1,38 @@ +""" +Spoof DNS responses. + +In this example, we fiddle with IPv6 (AAAA) records: + - For example.com, `::1` is returned. + (domain is hosted on localhost) + - For example.org, an NXDOMAIN error is returned. + (domain does not exist) + - For all other domains, return a non-error response without any records. + (domain exists, but has no IPv6 configured) +""" + +import ipaddress +import logging + +from mitmproxy import dns + + +def dns_request(flow: dns.DNSFlow) -> None: + q = flow.request.question + if q and q.type == dns.types.AAAA: + logging.info(f"Spoofing IPv6 records for {q.name}...") + if q.name == "example.com": + flow.response = flow.request.succeed( + [ + dns.ResourceRecord( + name="example.com", + type=dns.types.AAAA, + class_=dns.classes.IN, + ttl=dns.ResourceRecord.DEFAULT_TTL, + data=ipaddress.ip_address("::1").packed, + ) + ] + ) + elif q.name == "example.org": + flow.response = flow.request.fail(dns.response_codes.NXDOMAIN) + else: + flow.response = flow.request.succeed([])