| 1 |
""" |
| 2 |
Copyright (c) 2023 Proton AG |
| 3 |
|
| 4 |
This file is part of Proton. |
| 5 |
|
| 6 |
Proton is free software: you can redistribute it and/or modify |
| 7 |
it under the terms of the GNU General Public License as published by |
| 8 |
the Free Software Foundation, either version 3 of the License, or |
| 9 |
(at your option) any later version. |
| 10 |
|
| 11 |
Proton is distributed in the hope that it will be useful, |
| 12 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
GNU General Public License for more details. |
| 15 |
|
| 16 |
You should have received a copy of the GNU General Public License |
| 17 |
along with ProtonVPN. If not, see <https://www.gnu.org/licenses/>. |
| 18 |
""" |
| 19 |
import ipaddress |
| 20 |
import logging |
| 21 |
import re |
| 22 |
import struct |
| 23 |
import typing |
| 24 |
import random |
| 25 |
|
| 26 |
|
| 27 |
class DNSResponseError(Exception): |
| 28 |
pass |
| 29 |
|
| 30 |
|
| 31 |
class DNSParsingException(DNSResponseError): |
| 32 |
pass |
| 33 |
|
| 34 |
|
| 35 |
class DNSParser: |
| 36 |
"""Parse response from any DNS resolvers""" |
| 37 |
|
| 38 |
STRUCT_REPLY_COUNTS = struct.Struct('>HHHH') |
| 39 |
STRUCT_REC_FORMAT = struct.Struct('>HHIH') |
| 40 |
|
| 41 |
_MINIMUM_RECORD_LENGTH = 12 # => Transaction ID/Flags/#Questions/#Answers/#AuthorRRs/#AdditRRs |
| 42 |
|
| 43 |
# Regular expression used in _is_valid_hostname. |
| 44 |
# Each hostname segment (the strings in between the period characters) is only valid if: |
| 45 |
# - it has a minimum of 1 character and maximum of 63, |
| 46 |
# - it only contains alphanumeric characters or the hyphen but |
| 47 |
# - it does not start or end with a hyphen. |
| 48 |
_VALID_HOSTNAME_SEGMENT = re.compile(r"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE) |
| 49 |
|
| 50 |
# type definitions |
| 51 |
IPvxAddress = typing.Union[ipaddress.IPv4Address, ipaddress.IPv6Address] |
| 52 |
ParsedData = typing.Union[str, IPvxAddress] |
| 53 |
|
| 54 |
@classmethod |
| 55 |
def parse(cls, reply_data) -> typing.Optional[typing.List[typing.Tuple[int, ParsedData]]]: |
| 56 |
""" parse DNS reply and returns list of : TTL, address(IP or CNAME)""" |
| 57 |
|
| 58 |
if len(reply_data) < cls._MINIMUM_RECORD_LENGTH: |
| 59 |
raise DNSParsingException(f"(truncated reply)") |
| 60 |
|
| 61 |
# Match reply code (0x0 = OK) |
| 62 |
dns_rcode = reply_data[3] & 0xf |
| 63 |
|
| 64 |
# ensure we have something to parse |
| 65 |
if dns_rcode == 0x3: |
| 66 |
#NXDOMAIN, this is fatal |
| 67 |
raise DNSResponseError("No alternative routing exists for this environment (NXDOMAIN)") |
| 68 |
elif dns_rcode != 0x0: |
| 69 |
raise DNSResponseError(f"DNS response error code: {dns_rcode}") |
| 70 |
|
| 71 |
# Get counts |
| 72 |
offset = 4 |
| 73 |
dns_qdcount, dns_ancount, dns_nscount, dns_arcount = cls.STRUCT_REPLY_COUNTS.unpack_from(reply_data[offset:]) |
| 74 |
offset += cls.STRUCT_REPLY_COUNTS.size |
| 75 |
# skip questions |
| 76 |
for dns_qd_idx in range(dns_qdcount): |
| 77 |
length, data = cls._get_name(reply_data, offset) |
| 78 |
# We ignore QTYPE/QCLASS |
| 79 |
offset += length + 4 |
| 80 |
|
| 81 |
# tuples (TTL, data) |
| 82 |
answers = [] |
| 83 |
# answers |
| 84 |
for dns_an_idx in range(dns_ancount): |
| 85 |
length, data = cls._get_name(reply_data, offset) |
| 86 |
|
| 87 |
offset += length |
| 88 |
try: |
| 89 |
rec_type, rec_class, rec_ttl, rec_dlen = cls.STRUCT_REC_FORMAT.unpack_from(reply_data[offset:]) |
| 90 |
except struct.error: |
| 91 |
raise DNSParsingException(f"(truncated record headers)") |
| 92 |
offset += cls.STRUCT_REC_FORMAT.size |
| 93 |
|
| 94 |
record = reply_data[offset:offset + rec_dlen] |
| 95 |
if offset + rec_dlen > len(reply_data): |
| 96 |
raise DNSParsingException(f"(truncated reply while parsing record)") |
| 97 |
offset += rec_dlen |
| 98 |
|
| 99 |
if rec_type == 0x10 and rec_class == 0x01: # IN TXT |
| 100 |
if record[0] != rec_dlen - 1: |
| 101 |
raise DNSParsingException(f"(length of TXT record doesn't match REC_DLEN)") |
| 102 |
if record[0] != len(record) - 1: |
| 103 |
raise DNSParsingException(f"(length of TXT record doesn't actual record data)") |
| 104 |
try: |
| 105 |
hostname = record[1:].decode('ascii') |
| 106 |
|
| 107 |
# Only hostnames with a valid format are accepted in TXT records. |
| 108 |
# This is to avoid possible security exploits where the TXT record contains |
| 109 |
# a full URL (hostname + path), which e.g. could trigger SSO redirects. |
| 110 |
if not cls._is_valid_hostname(hostname): |
| 111 |
raise DNSParsingException(f"Invalid hostname in TXT record: {hostname}") |
| 112 |
|
| 113 |
answers.append((int(rec_ttl), hostname)) |
| 114 |
except UnicodeDecodeError: |
| 115 |
raise DNSParsingException(f"(UnicodeDecodeError in TXT record)") |
| 116 |
elif rec_type == 0x01 and rec_class == 0x01: # IN A |
| 117 |
if len(record) != 4: |
| 118 |
raise DNSParsingException(f"(length of A record doesn't match)") |
| 119 |
|
| 120 |
try: |
| 121 |
ipv4_address = ipaddress.IPv4Address(record) |
| 122 |
except ValueError as exc: |
| 123 |
raise DNSParsingException(f"Invalid IP address in A record: {record}") from exc |
| 124 |
|
| 125 |
answers.append((int(rec_ttl), ipv4_address)) |
| 126 |
else: |
| 127 |
logging.debug(f"record type currently not supported: {rec_type}... skip") |
| 128 |
|
| 129 |
return answers |
| 130 |
|
| 131 |
@staticmethod |
| 132 |
def _get_name(buffer: bytes, offset=0): |
| 133 |
# Length that we've parsed (for that specific record) |
| 134 |
parsed_length = 0 |
| 135 |
# Have we jumped to somewhere else? |
| 136 |
has_jumped = False |
| 137 |
# Parts we've seen until now |
| 138 |
parts = [] |
| 139 |
# While we're in the buffer, and we are not on a null byte (terminator) |
| 140 |
while offset < len(buffer) and buffer[offset] != 0: |
| 141 |
# Read the length of the part, in one byte |
| 142 |
length = buffer[offset] |
| 143 |
# If the length starts with two one bytes, then it's a pointer |
| 144 |
if length & 0b1100_0000 == 0b1100_0000: |
| 145 |
offset = ((buffer[offset] & 0b0011_1111) << 8) + buffer[offset + 1] |
| 146 |
# Pointers have length 2 |
| 147 |
if not has_jumped: |
| 148 |
parsed_length += 2 |
| 149 |
# We're not any more in the current record, stop counting |
| 150 |
has_jumped = True |
| 151 |
else: |
| 152 |
# Real entry |
| 153 |
# Add the part |
| 154 |
if offset + 1 + length > len(buffer): |
| 155 |
raise DNSParsingException(f"DNS resolution failed (non-parsable value)") |
| 156 |
parts.append(buffer[offset + 1:offset + 1 + length]) |
| 157 |
# Add length, and the length byte |
| 158 |
if not has_jumped: |
| 159 |
parsed_length += length + 1 |
| 160 |
offset += length + 1 |
| 161 |
|
| 162 |
# This is for the 0-byte that terminates a name |
| 163 |
if not has_jumped: |
| 164 |
parsed_length += 1 |
| 165 |
|
| 166 |
return parsed_length, parts |
| 167 |
|
| 168 |
@classmethod |
| 169 |
def _build_simple_query(cls, domain: bytes, qtype: int, qclass: int): |
| 170 |
"""internal utility to build the simplest DNS request we need""" |
| 171 |
id: bytes = struct.pack('!H', random.randint(0, 65535)) # nosemgrep: gitlab.bandit.B311 # nosec B311 # noqa: E501 # pylint: disable=line-too-long |
| 172 |
qtype: bytes = struct.pack('!H', qtype) |
| 173 |
qclass: bytes = struct.pack('!H', qclass) |
| 174 |
|
| 175 |
# it's a query with a single question, no AN, no RR, no AR |
| 176 |
return id + b"\x01\x20\x00\x01\x00\x00\x00\x00\x00\x00" + domain + qtype + qclass |
| 177 |
|
| 178 |
@classmethod |
| 179 |
def build_query(cls, fqdn: typing.Union[str, bytes], qtype, qclass): |
| 180 |
"""Build a very simple dns request that is just a query with no AN, no RR, no AR, and a single question""" |
| 181 |
|
| 182 |
if type(fqdn) == str: |
| 183 |
domain = b''.join([bytes([len(el)]) + el.encode('ascii') for el in fqdn.split('.')]) + b'\x00' |
| 184 |
elif type(fqdn) == bytes: |
| 185 |
domain = b''.join([bytes([len(el)]) + el for el in fqdn.split(b'.')]) + b'\x00' |
| 186 |
else: |
| 187 |
raise TypeError("fqdn can only be str or bytes") |
| 188 |
|
| 189 |
query = cls._build_simple_query(domain, qtype, qclass) |
| 190 |
return query |
| 191 |
|
| 192 |
@classmethod |
| 193 |
def _is_valid_hostname(cls, hostname): |
| 194 |
if len(hostname) > 255: |
| 195 |
return False |
| 196 |
|
| 197 |
# Strip exactly one dot from the right, if present. |
| 198 |
if hostname[-1] == ".": |
| 199 |
hostname = hostname[:-1] |
| 200 |
|
| 201 |
# The hostname is valid if all its segments are valid. |
| 202 |
return all(cls._VALID_HOSTNAME_SEGMENT.match(segment) for segment in hostname.split(".")) |