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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
|
#!/usr/bin/env python3
import argparse
import base64
import configparser
import contextlib
import fcntl
import http.client
import ipaddress
import json
import logging
import os
import socket
import ssl
import sys
import tempfile
import urllib.parse
HE_DNS_API_HOST = "dyn.dns.he.net"
DEFAULT_CHECK_URL = "https://ip.mfamily.org/"
DEFAULT_STATE_FILE = "/var/lib/he-dyndns/state.json"
def parse_ip(value, version=None):
try:
address = ipaddress.ip_address(value.strip())
except ValueError as exc:
raise ValueError("invalid IP address: {}".format(value)) from exc
if version is not None and address.version != version:
raise ValueError("expected an IPv{} address, got {}".format(version, address))
return address
def get_key(keyfile, record):
if not os.path.exists(keyfile):
raise RuntimeError("missing keyfile {}".format(keyfile))
config = configparser.ConfigParser()
config.read(keyfile)
if "keys" not in config:
raise RuntimeError("keyfile lacks [keys] section")
if record not in config["keys"]:
raise RuntimeError("keyfile has no entry for {}".format(record))
return config["keys"][record]
def http_get(host, port, target, family, headers=None, timeout=10, use_tls=False):
"""Make an HTTP request using only addresses from the requested family."""
request_headers = {
"Host": host if port == 80 else "{}:{}".format(host, port),
"Connection": "close",
"User-Agent": "he-dyndns/1",
}
request_headers.update(headers or {})
request = "GET {} HTTP/1.1\r\n{}\r\n\r\n".format(
target,
"\r\n".join("{}: {}".format(name, value) for name, value in request_headers.items()),
).encode("ascii")
errors = []
addresses = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
for af, socktype, proto, _canonname, sockaddr in addresses:
connection = socket.socket(af, socktype, proto)
connection.settimeout(timeout)
try:
connection.connect(sockaddr)
if use_tls:
context = ssl.create_default_context()
connection = context.wrap_socket(connection, server_hostname=host)
connection.sendall(request)
response = http.client.HTTPResponse(connection)
response.begin()
body = response.read(4097)
if len(body) > 4096:
raise RuntimeError("HTTP response was too large")
return response.status, body
except (OSError, http.client.HTTPException, RuntimeError) as exc:
errors.append(str(exc))
finally:
connection.close()
detail = "; ".join(errors) if errors else "no addresses returned"
raise RuntimeError(
"could not connect to {} over IPv{}: {}".format(
host, 4 if family == socket.AF_INET else 6, detail
)
)
def discover_address(check_url, version, timeout=10):
parsed = urllib.parse.urlsplit(check_url)
if parsed.scheme not in ("http", "https") or not parsed.hostname:
raise ValueError("check URL must be an http:// or https:// URL with a hostname")
if parsed.username or parsed.password or parsed.fragment:
raise ValueError("check URL must not contain credentials or a fragment")
family = socket.AF_INET if version == 4 else socket.AF_INET6
target = parsed.path or "/"
if parsed.query:
target += "?" + parsed.query
use_tls = parsed.scheme == "https"
port = parsed.port or (443 if use_tls else 80)
status, body = http_get(
parsed.hostname, port, target, family, timeout=timeout, use_tls=use_tls
)
if status != 200:
raise RuntimeError("address check returned HTTP {}".format(status))
try:
value = body.decode("ascii").strip()
except UnicodeDecodeError as exc:
raise RuntimeError("address check returned non-ASCII data") from exc
return parse_ip(value, version)
def update_he(record, key, address, timeout=10):
family = socket.AF_INET if address.version == 4 else socket.AF_INET6
query = urllib.parse.urlencode({"hostname": record, "myip": str(address)})
credentials = base64.b64encode(
"{}:{}".format(record, key).encode("ascii")
).decode("ascii")
status, body = http_get(
HE_DNS_API_HOST,
443,
"/nic/update?" + query,
family,
headers={"Authorization": "Basic " + credentials},
timeout=timeout,
use_tls=True,
)
if status != 200:
raise RuntimeError("HE returned HTTP {}".format(status))
response = body.decode("ascii", errors="replace").strip()
result = response.split()[0] if response else ""
log.debug("HE response: %s", response)
if result in ("good", "nochg"):
return
if result == "badauth":
raise RuntimeError(
"HE badauth: wrong key or record not configured for dynamic updates"
)
raise RuntimeError("HE returned {!r}: unknown response code".format(result))
def read_state(path):
try:
with open(path, "r", encoding="utf-8") as state_file:
state = json.load(state_file)
except FileNotFoundError:
return {}
except (OSError, json.JSONDecodeError) as exc:
raise RuntimeError("could not read state file {}: {}".format(path, exc)) from exc
if not isinstance(state, dict):
raise RuntimeError("state file {} does not contain an object".format(path))
return state
def write_state(path, state):
directory = os.path.dirname(os.path.abspath(path))
os.makedirs(directory, mode=0o755, exist_ok=True)
fd, temporary_path = tempfile.mkstemp(prefix=".state-", dir=directory, text=True)
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as state_file:
json.dump(state, state_file, indent=2, sort_keys=True)
state_file.write("\n")
state_file.flush()
os.fsync(state_file.fileno())
os.replace(temporary_path, path)
except Exception:
with contextlib.suppress(FileNotFoundError):
os.unlink(temporary_path)
raise
@contextlib.contextmanager
def state_lock(path):
directory = os.path.dirname(os.path.abspath(path))
os.makedirs(directory, mode=0o755, exist_ok=True)
lock_file = open(path + ".lock", "a", encoding="ascii")
try:
fcntl.flock(lock_file, fcntl.LOCK_EX)
yield
finally:
fcntl.flock(lock_file, fcntl.LOCK_UN)
lock_file.close()
def selected_version(args, parser):
if args.v4 and args.addr6:
parser.error("--v4 cannot be combined with --addr6")
if args.v6 and args.addr4:
parser.error("--v6 cannot be combined with --addr4")
return 6 if args.v6 or args.addr6 else 4
def make_parser():
parser = argparse.ArgumentParser(
description="Update a Hurricane Electric DNS dynamic record"
)
versions = parser.add_mutually_exclusive_group()
versions.add_argument("--v4", action="store_true", help="update IPv4 A record (default)")
versions.add_argument("--v6", action="store_true", help="update IPv6 AAAA record")
addresses = parser.add_mutually_exclusive_group()
addresses.add_argument(
"--addr4", help="use this IPv4 address; bypass discovery/state comparison"
)
addresses.add_argument(
"--addr6", help="use this IPv6 address; bypass discovery/state comparison"
)
parser.add_argument("record", help="DNS record to update")
parser.add_argument(
"--check-url", default=DEFAULT_CHECK_URL,
help="public address service (default: %(default)s)",
)
parser.add_argument(
"--state-file", default=DEFAULT_STATE_FILE,
help="local comparison state (default: %(default)s)",
)
parser.add_argument(
"--keyfile", default="/etc/he-dyndns.conf",
help="key config file (default: %(default)s)",
)
parser.add_argument("--key", help="HE DDNS key; overrides --keyfile")
parser.add_argument("--timeout", type=float, default=10, help="network timeout in seconds")
parser.add_argument("--debug", action="store_true", help="enable debug logging")
return parser
def run(args, parser):
version = selected_version(args, parser)
explicit_value = args.addr4 if version == 4 else args.addr6
key = args.key if args.key is not None else get_key(args.keyfile, args.record)
if explicit_value is not None:
address = parse_ip(explicit_value, version)
update_he(args.record, key, address, timeout=args.timeout)
return
with state_lock(args.state_file):
address = discover_address(args.check_url, version, timeout=args.timeout)
log.debug("discovered IPv%s address %s", version, address)
state = read_state(args.state_file)
record_state = state.get(args.record)
if not isinstance(record_state, dict):
record_state = {}
previous = record_state.get(str(version))
if previous == str(address):
log.debug("address is unchanged; skipping HE update")
return
update_he(args.record, key, address, timeout=args.timeout)
state[args.record] = record_state
record_state[str(version)] = str(address)
write_state(args.state_file, state)
def main(argv=None):
parser = make_parser()
args = parser.parse_args(argv)
log.setLevel(logging.DEBUG if args.debug else logging.ERROR)
try:
run(args, parser)
except (OSError, RuntimeError, ValueError, configparser.Error) as exc:
log.error("%s", exc)
return 1
return 0
log = logging.getLogger("he-dyndns")
if not log.handlers:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(name)s: %(levelname)s: %(message)s"))
log.addHandler(handler)
if __name__ == "__main__":
sys.exit(main())
|