forked from facebookarchive/doh-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
161 lines (141 loc) · 4.91 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python3
#
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import binascii
import base64
import logging
import urllib.parse
from typing import Dict, List, Tuple
from dohproxy import constants, protocol
def extract_path_params(url: str) -> Tuple[str, Dict[str, List[str]]]:
""" Given a URI, extract the path and the parameters
"""
p = urllib.parse.urlparse(url)
params = urllib.parse.parse_qs(p.query, keep_blank_values=True)
return p.path, params
def extract_ct_body(params: Dict[str, List[str]]) -> Tuple[str, bytes]:
""" Extract the content type and body from a list of get parameters.
:param params: A dictionary of key/value of parameters as provided by
urllib.parse.parse_qs
:return: a tuple that contains a string and bytes, respectively ct and
body.
:raises: a DOHParamsException with an explanatory message.
"""
if constants.DOH_CONTENT_TYPE_PARAM in params and \
len(params[constants.DOH_CONTENT_TYPE_PARAM]):
ct = params[constants.DOH_CONTENT_TYPE_PARAM][0]
if not ct:
# An empty value indicates the default
# application/dns-udpwireformat type
ct = constants.DOH_MEDIA_TYPE
else:
raise protocol.DOHParamsException(b'Missing Content Type Parameter')
if constants.DOH_BODY_PARAM in params and \
len(params[constants.DOH_BODY_PARAM]):
try:
body = doh_b64_decode(
params[constants.DOH_BODY_PARAM][0])
except binascii.Error:
raise protocol.DOHParamsException(b'Invalid Body Parameter')
if not body:
raise protocol.DOHParamsException(b'Missing Body')
else:
raise protocol.DOHParamsException(b'Missing Body Parameter')
return ct, body
def doh_b64_encode(s: bytes) -> str:
"""Base 64 urlsafe encode and remove padding.
:param s: input bytes-like object to be encoded.
:return: urlsafe base 64 encoded string.
"""
return base64.urlsafe_b64encode(s).decode('utf-8').rstrip('=')
def doh_b64_decode(s: str) -> bytes:
"""Base 64 urlsafe decode, add padding as needed.
:param s: input base64 encoded string with potentially missing padding.
:return: decodes bytes
"""
padding = '=' * (-len(s) % 4)
return base64.urlsafe_b64decode(s + padding)
def build_query_params(dns_query):
"""Given a wire-format DNS query, build the query parameters.
"""
return {
constants.DOH_BODY_PARAM: doh_b64_encode(dns_query),
constants.DOH_CONTENT_TYPE_PARAM: constants.DOH_MEDIA_TYPE,
}
def make_url(domain, uri):
"""Utility function to return a URL ready to use from a browser or cURL....
"""
p = urllib.parse.ParseResult(
scheme='https',
netloc=domain,
path=uri,
params='', query='', fragment='',
)
return urllib.parse.urlunparse(p)
def client_parser_base():
"""Build a ArgumentParser object with all the default arguments that are
useful to both client and stub.
:return: a ArgumentParser object with the common client side arguments set.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--domain',
default='localhost',
help='Domain to make DOH request against. Default: [%(default)s]'
)
parser.add_argument(
'--uri',
default=constants.DOH_URI,
help='DNS API URI. Default [%(default)s]',
)
parser.add_argument(
'--remote-address',
help='Remote address where the DOH proxy is running. If None, '
'--domain will be resolved to lookup and IP. Default: [%(default)s]',
)
parser.add_argument(
'--port',
default=443,
help='Port to connect to. Default: [%(default)s]'
)
parser.add_argument(
'--post',
action='store_true',
help='Use HTTP POST instead of GET.'
)
parser.add_argument(
'--debug',
action='store_true',
help='Prints some debugging output',
)
parser.add_argument(
'--level',
default='DEBUG',
help='log level [%(default)s]',
)
parser.add_argument(
'--insecure',
action='store_true',
help=argparse.SUPPRESS,
)
return parser
def configure_logger(name='', level='DEBUG'):
"""
:param name: (optional) name of the logger, default: ''.
:param level: (optional) level of logging, default: DEBUG.
:return: a logger instance.
"""
logging.basicConfig(format='%(asctime)s: %(levelname)8s: %(message)s')
logger = logging.getLogger(name)
level_name = level.upper()
level = getattr(logging, level_name, None)
if not isinstance(level, int):
raise Exception("Invalid log level name : %s" % level_name)
logger.setLevel(level)
return logger