<commit_before>"""
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 json
import re
import os
import urllib.request
from typing import List

import dns.query
import dns.rdatatype
import dns.message
import dns.resolver
import dns.rdtypes.IN.A
import dns.rdtypes.IN.AAAA

from mitmproxy import ctx

# filename we'll save the blocklist to so we don't have to re-generate it every time
blocklist_filename = 'blocklist.json'

# additional hostnames to block
additional_doh_names: List[str] = [
    'dns.google.com'
]

# additional IPs to block
additional_doh_ips: List[str] = [

]


def get_doh_providers():
    """
    Scrape a list of DoH providers from curl's wiki page.
    :return: a generator of dicts containing information about the DoH providers
    """
    https_url_re = re.compile(r'https://'
                              r'(?P<hostname>[0-9a-zA-Z._~-]+)'
                              r'(?P<port>:[0-9]+)?'
                              r'(?P<path>[0-9a-zA-Z._~/-]+)?')

    provider_re = re.compile(r'(\[([^\]]+)\]\(([^)]+))\)|(.*)')
    # URLs that are not DoH URLs
    do_not_include = ['my.nextdns.io', 'blog.cloudflare.com']
    found_table = False
    with urllib.request.urlopen('https://raw.githubusercontent.com/wiki/curl/curl/DNS-over-HTTPS.md') as fp:
        for line in fp:
            line = line.decode()
            if line.startswith('|'):
                if not found_table:
                    found_table = True
                    continue
                cols = line.split('|')
                provider_col = cols[1].strip()
                website = None
                provider_name = None
                matches = provider_re.findall(provider_col)
                if matches[0][3] != '':
                    provider_name = matches[0][3]
                if matches[0][1] != '':
                    provider_name = matches[0][1]
                if matches[0][2] != '':
                    website = matches[0][2]
                if provider_name is not None:
                    provider_name = re.sub(r'([^[]+)\s?(.*)', r'\1', provider_name)
                    while provider_name[-1] == ' ':
                        provider_name = provider_name[:-1]
                url_col = cols[2]
                doh_url_matches = https_url_re.findall(url_col)
                if len(doh_url_matches) == 0:
                    continue
                else:
                    for doh_url in doh_url_matches:
                        if doh_url[0] in do_not_include:
                            continue
                        yield {
                            'name': provider_name,
                            'website': website,
                            'url': 'https://{}{}{}'.format(doh_url[0],
                                                           ':{}'.format(doh_url[1])
                                                           if len(doh_url[1]) != 0
                                                           else '', doh_url[2]),
                            'hostname': doh_url[0],
                            'port': doh_url[1] if len(doh_url[1]) != 0 else '443',
                            'path': doh_url[2],
                        }
            if found_table and line.startswith('#'):
                break
    return


def get_ips(hostname):
    """
    Lookup all A and AAAA records for given hostname
    :param hostname: the name to lookup
    :return: a list of IP addresses returned
    """
    default_nameserver = dns.resolver.Resolver().nameservers[0]
    ips = list()
    rdtypes = [dns.rdatatype.A, dns.rdatatype.AAAA]
    for rdtype in rdtypes:
        q = dns.message.make_query(hostname, rdtype)
        r = dns.query.udp(q, default_nameserver)
        if r.flags & dns.flags.TC:
            r = dns.query.tcp(q, default_nameserver)
        for a in r.answer:
            for i in a.items:
                if isinstance(i, dns.rdtypes.IN.A.A) or isinstance(i, dns.rdtypes.IN.AAAA.AAAA):
                    ips.append(str(i.address))
    return ips


def load_blocklist():
    """
    Load a tuple containing two lists, in the form of (hostnames, ips).
    It will attempt to load it from a file, and if that file is not found,
    it will generate the blocklist and save it to a file.

    :return: a ``tuple`` of (``list``, ``list``), the hostnames and IPs to block
    """
    if os.path.isfile(blocklist_filename):
        with open(blocklist_filename, 'r') as fp:
            j = json.load(fp)
        doh_hostnames, doh_ips = j['hostnames'], j['ips']
    else:
        doh_hostnames = list([i['hostname'] for i in get_doh_providers()])
        doh_ips = list()
        for hostname in doh_hostnames:
            ips = get_ips(hostname)
            doh_ips.extend(ips)
    doh_hostnames.extend(additional_doh_names)
    doh_ips.extend(additional_doh_ips)
    with open(blocklist_filename, 'w') as fp:
        obj = {
            'hostnames': doh_hostnames,
            'ips': doh_ips
        }
        json.dump(obj, fp=fp)
    return doh_hostnames, doh_ips


# load DoH hostnames and IP addresses to block
doh_hostnames, doh_ips = load_blocklist()
ctx.log.info('DoH blocklist loaded')

# 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:<commit_msg>replace scraping and DNS lookups with static list<commit_after>"""
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)
"""
from typing import List

from mitmproxy import ctx

# 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": ["192.168.3.11", "172.16.58.3", "fc00:e968:6179::de52:7100:ff", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:ff", "172.16.31.10", "172.16.17.32", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "8.8.4.4", "8.8.8.8", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "fc00:db20:35b:7399::5", "172.16.58.3", "192.168.3.11", "fdf8:f53e:61e4::18", "fc00:db20:35b:7399::5", "172.16.58.3", "192.168.3.11", "fc00:db20:35b:7399::5", "fdf8:f53e:61e4::18", "192.168.3.11", "192.168.3.11", "fc00:e968:6179::de52:7100:337", "fdf8:f53e:61e4::18", "172.16.17.32", "172.16.17.32", "fc00:e968:6179::de52:7100:1a80", "fdf8:f53e:61e4::18", "9.9.9.9", "149.112.112.112", "fc00:e968:6179::de52:7100", "fc00:db20:35b:7399::5", "9.9.9.9", "172.16.58.3", "fdf8:f53e:61e4::18", "fc00:e968:6179::de52:7100", "192.168.127.12", "192.168.3.11", "fc00:e968:6179::de52:7100", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "172.16.17.32", "172.16.58.3", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fc00:e968:6179::de52:7100", "172.16.58.3", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.31.10", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "172.16.17.32", "192.168.127.12", "172.16.58.3", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "172.16.31.10", "172.16.17.32", "fc00:db20:35b:7399::5", "172.16.17.32", "fdf8:f53e:61e4::18", "192.168.127.12", "2a07:a8c0::", "192.168.3.11", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "192.168.3.11", "192.168.127.12", "fc00:e968:6179::de52:7100", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.17.32", "fc00:db20:35b:7399::5", "192.168.3.11", "fdf8:f53e:61e4::18", "192.168.127.12", "fc00:db20:35b:7399::5", "172.16.31.10", "fdf8:f53e:61e4::18", "172.16.31.10", "fdf8:f53e:61e4::18", "192.168.127.12", "192.168.127.12", "fdf8:f53e:61e4::18", "fdf8:f53e:61e4::18", "192.168.3.11", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "192.168.127.12", "172.16.58.3", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.58.3", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.58.3", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.17.32", "172.16.58.3", "172.16.17.32", "192.168.127.12", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "172.16.58.3", "fc00:db20:35b:7399::5", "192.168.127.12", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.31.10", "172.16.17.32", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:4001", "192.168.127.12", "172.16.17.32", "fc00:db20:35b:7399::5", "fdf8:f53e:61e4::18", "192.168.127.12", "192.168.127.12", "fc00:db20:35b:7399::5", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "172.16.58.3", "172.16.17.32", "172.16.31.10", "192.168.3.11", "fdf8:f53e:61e4::18", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fdf8:f53e:61e4::18", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.58.3", "172.16.31.10", "fc00:e968:6179::de52:7100", "172.16.17.32", "192.168.127.12", "fdf8:f53e:61e4::18", "fc00:db20:35b:7399::5", "192.168.3.11", "172.16.17.32", "fc00:db20:35b:7399::5", "172.16.17.32", "fc00:db20:35b:7399::5", "192.168.3.11", "192.168.3.11", "fc00:db20:35b:7399::5", "fc00:db20:35b:7399::5", "192.168.127.12", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "172.16.58.3", "fc00:db20:35b:7399::5", "172.16.31.10", "192.168.3.11", "192.168.127.12", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "172.16.17.32", "192.168.3.11", "172.16.31.10", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "fc00:e968:6179::de52:7100", "172.16.31.10", "192.168.3.11", "fc00:e968:6179::de52:7100", "192.168.127.12", "fdf8:f53e:61e4::18", "192.168.3.11", "fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "192.168.3.11", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "172.16.31.10", "2a0d:5fdf8:f53e:61e4::18", "172.16.58.3", "fdf8:f53e:61e4::18", "192.168.3.11", "172.16.58.3", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b", "fc00:db20:35b:7399::5", "172.16.31.10", "192.168.127.12", "fc00:db20:35b:7399::5", "fc00:e968:6179::de52:7100", "172.16.17.32", "172.16.31.10", "fdf8:f53e:61e4::18", "fdf8:f53e:61e4::18"]}

# 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:
{'fraction_non_alphanumeric': 0.189347216659992, 'fraction_numerical': 0.15618742490989188, 'mean_word_length': 3.1731283422459895, 'pattern_counts': {'":': 2, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 92, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4726432', 'n_tokens_mistral': 6346, 'n_tokens_neox': 5350, 'n_words': 833}