10 Commits
15 changed files with 1484 additions and 326 deletions

No files matched your search

+5 -4
View File
@@ -1,4 +1,5 @@
debug.log __pycache__/
update.log config.toml
users.db state.json
config.cfg state.json.tmp
.env
-15
View File
@@ -1,15 +0,0 @@
# Only allow web access to update.php and index.html
<Files *>
Order Deny,Allow
Deny from all
</Files>
<FilesMatch ^$>
Order Allow,Deny
Allow from all
</FilesMatch>
<FilesMatch "^(update\.php|index\.html)$">
Order Allow,Deny
Allow from all
</FilesMatch>
+126 -44
View File
@@ -1,71 +1,153 @@
# Snap DynDNS Server using INWX domains # Snap DynDNS Server using INWX domains
**Snap DynDNS Server** enables you to set up your own simple Dynamic DNS service. It requires you to use domains managed by the registrar InterNetworX (inwx.de) and their API. This server may be simply customised to be able to work with other domain sellers and their specific APIs. **Snap DynDNS Server** is a tiny Dynamic DNS service for domains managed by the registrar InterNetworX (inwx.de). It is a single Python file without dependencies beyond the standard library, made to run as a small service on shared hosting such as Uberspace.
It can set the IP of any existing domain entry, may it be IPv4 or IPv6 (and theoretically all kinds INWX supports). All domains of the clients have to be part of the same INWX account. The server is a credential broker: your INWX API login only exists on the server, while each device gets its own random token that can update exactly one hostname. A device that gets lost or compromised can be cut off by deleting one section from the config.
The idea of the service is to enable compatibility with as many client devices as possible. So clients only would need to send a GET or POST request to your service which contains their individual user data (which you can create freely) and their desired IP address for their domain. It speaks the common dyndns2 protocol (HTTP Basic Auth, `myip`/`myipv6`, `good`/`nochg` answers) on `/nic/update`, so routers like the AVM FritzBox, ddclient, and plain `curl` work. The matching client is [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client), a small shell script for cron.
This server has a client application as counterpart, named [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client). Using the latter, you will be able to retrieve the IP of your computer and send it to this service which in return updates the domain for you. ## How it works
1. A device sends `GET /nic/update` with its hostname and token as Basic Auth. Without `myip`/`myipv6`, the server uses the IP the request came from.
2. The server compares the SHA-256 of the token with the config.
3. If the IP equals the last one it stored, it answers `nochg` right away. INWX is not contacted, so polling every minute is cheap.
4. Otherwise it logs in to INWX, looks up the record by name and type, updates it, and only then stores the new IP. If INWX fails, the device gets `911` and retries on its next run.
The record (A and/or AAAA) has to exist at INWX; the helper script below creates it for new hosts. The server picks A or AAAA depending on the IP family, and keeps the TTL of the record. The connection to INWX uses IPv4 only, so an IP-restricted INWX API account only needs the server's IPv4 address on its allow-list.
## Requirements ## Requirements
The installation requires the possibility to execute PHP and Bash files. It also requires curl to be installed. There's no need for a database to be installed as everything is handled by flat text files. - Python 3.11 or newer, no packages needed
- A way to run a service behind HTTPS, e.g. supervisord plus a reverse proxy (Uberspace has both)
- An INWX account or API sub-account. If 2FA is enabled, the TOTP shared secret is needed as well. IP-restricted API accounts work if the server's IPv4 address is allowed.
The code has been tested with PHP 5.5, CentOS 7, and Apache 2.2.15. Please be aware to migrate the `.htaccess` file if you use other webservers so the sensitive files like `config.cfg` and `users.db` are safe. The server speaks plain HTTP and expects a reverse proxy in front that terminates TLS. Never expose it without HTTPS, as the token is sent with every request.
## Installation ## Installation on Uberspace
Clone the git repository to your server and move them to a public web-accessible folder of your choice. Now rename/copy the files `config.cfg.sample` and `users.db.sample` to `config.cfg` and `users.db` respectively. Open them in an editor and modify the settings so they match your data. Clone the repository anywhere outside the web root:
### config.cfg ```
git clone https://src.mehl.mx/mxmehl/snap-dyndns-server ~/snap-dyndns-server
```
In this file you have to put your inwx.de username and password. It is needed to login to the API and update the IP of your domain entry. Create the config and make it private:
### users.db ```
mkdir -p ~/etc/snap-dyndns
cp ~/snap-dyndns-server/config.toml.sample ~/etc/snap-dyndns/config.toml
chmod 600 ~/etc/snap-dyndns/config.toml
```
In this file you can create users which can use your service. Unauthorized requests which do not match any of the content here will not work. Each line matches one existing single domain entry in your INWX account. It is not necessary the DynDNS domain names to be part of the same domain (`example.com`), they can also be different ones – they just have to be part of the same INWX account (please tell me if you need this to be improved, it shouldn't be a big deal). Create the service, using a free port between 1024 and 65535 (here 8080), in `~/etc/services.d/snap-dyndns.ini`:
#### Gather INWX domain ID ```ini
[program:snap-dyndns]
command=/usr/bin/python3.14 %(ENV_HOME)s/snap-dyndns-server/snap_dyndns.py --config %(ENV_HOME)s/etc/snap-dyndns/config.toml --port 8080
autostart=yes
autorestart=yes
```
Given you own the domain example.com which you can administrate in your INWX account. For each client, you can create a subdomain, in this example `user1.example.com` and `user2.example.com`. For INWX, each domain has a unique ID. To find out this ID, you will have to use a tool like Firebug or the in-built web inspector tools by Firefox or Chromium. Use the *inspect element* feature, hover over the subdomain line in your nameserver/DNS settings (where you can define the IPs, currently on `https://www.inwx.de/de/nameserver2`), and in the id attribute of the `<div>`-element you should find a string with around 9 numbers. This number is the domain entry's ID. Please see the screenshot for how it should look like. If your Python is not at `/usr/bin/python3.14`, adjust the path. Start the service and register it as a web backend for the `/nic` path of your domain:
![That's how you get the ID of your single domain](screen-inwx-id.png) ```
supervisorctl reread
supervisorctl update
uberspace web backend set yourdyndnsservice.net/nic --http --port 8080
```
Back in `users.db`, type in the domain name (`user1.example.com`) and its INWX ID. For username and password, you can freely create one and give to your users. Each request to your service requires the correct domain name, a username and a password. Only if all three match, the IP change request will be executed. Check with `supervisorctl status` and `uberspace web backend list`. Errors and requests are logged to `~/logs/` (or `supervisorctl tail snap-dyndns stderr`).
The service also answers `/` with a short start page, but with the backend registered for `/nic` only `/nic` and `/nic/` reach it. To show the page on the domain's root as well, register the whole domain instead: `uberspace web backend set yourdyndnsservice.net --http --port 8080`.
### Client IP address
Behind the reverse proxy the TCP peer is the proxy, not the device. On Uberspace the proxy puts the device's address into `X-Forwarded-For`, which is already set in `config.toml.sample`:
```toml
client_ip_header = "X-Forwarded-For"
```
The server uses the last entry of that header, the one added by your own proxy. Entries before it are controlled by the client and ignored. If the header is missing, or the address is not a global one, the answer is `badip` and a log line instead of a wrong DNS record. Check once that the `good <ip>` answer shows your real public IP.
With another proxy, stop the service (`supervisorctl stop snap-dyndns`), run `nc -l 8080` and open the URL once from outside. `nc` prints the raw request including all headers, so you can see in which one your public IP appears.
### Adding a device
The helper creates a random token, stores only its SHA-256 in the config, prints the token once, and makes sure the DNS record exists at INWX:
```
python3 ~/snap-dyndns-server/snap_dyndns_host.py user1.example.com
```
If the A record does not exist at INWX yet, it is created with the TTL 300 and a placeholder address, which the first update of the device replaces. An existing record is left alone. Use `-t A,AAAA` to handle both types, `--ttl` for another TTL of new records, and `--no-dns` to skip INWX completely. If INWX cannot be reached, nothing is changed in the config. The helper needs the INWX login from the config and is therefore best run on the server itself, as an IP-restricted INWX account refuses logins from elsewhere.
Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. For an existing host it asks before replacing the token (`-y` skips the question), and the old token stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed.
The hostname is the Basic Auth user name, the token the password. Without the helper, generate a token and hash yourself with `python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'` and add a section `[hosts."user1.example.com"]` with `token_sha256 = "<hash>"`.
## Usage ## Usage
Please feel free to use [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client) which is the perfect combination for this server application. With curl (the `-u` option keeps the credentials out of the URL):
Please note: You cannot define whether it shall be an A, AAAA or whatever record. You would have to do that in the INWX webpanel once, the ID should stay the same.
### curl
You can use curl with a POST request:
curl -X POST -d "domain=user1.example.com&user=myuser&pass=mypassword&ip=1.2.3.4" "https://yourdyndnsservice.net/update.php"
You can also use GET requests which is **not** recommended. The advantage of POST requests is that the request is encrypted via SSL if you use a HTTPS domain. GET requests can be intercepted quite easily which is bad because you send sensitive data. A GET request would look like this
curl -d "domain=user1.example.com&user=myuser&pass=mypassword&ip=1.2.3.4" "https://yourdyndnsservice.net/update.php"
This will send following data to your **Snap DynDNS server** which is running under the domain `https://yourdyndnsservice.net` in this example:
* `domain=user1.example.com`: This is the client's personal DynDNS domain
* `user=myuser`: This is the client's username which you can define freely
* `pass=mypassword`: This is the client's personal password which you can define freely.
* `ip=1.2.3.4`: This is the IP which shall be set to this single domain
## AVM FritzBox
In the AVM Fritz!Boxes you can choose a custom DynDNS provider. In order to connect it with your Snap DynDNS server, use following data:
``` ```
Update-URL: yourdyndnsservice.net/update.php?domain=<domain>&user=<username>&pass=<pass>&ip=<ipaddr> curl -fsS -u user1.example.com:TOKEN "https://yourdyndnsservice.net/nic/update"
curl -fsS -u user1.example.com:TOKEN "https://yourdyndnsservice.net/nic/update?myip=1.2.3.4"
```
Parameters, all optional:
- `hostname`: must equal the Basic Auth user name
- `myip`: IPv4 or IPv6 address to set, defaults to the address of the request
- `myipv6`: IPv6 address, to update A and AAAA in one request
Answers (HTTP status in brackets):
- `good <ip>` (200): the record was updated
- `nochg <ip>` (200): the IP is what the server stored last, INWX was not contacted
- `badauth` (401): unknown hostname or wrong token
- `nohost` (404): hostname mismatch, or the record does not exist at INWX
- `badip` (400): the IP could not be parsed, or the address of the request is not a global one
- `911` (502 or 500): INWX or the server config failed, see the log
### AVM FritzBox
Choose a custom DynDNS provider:
```
Update-URL: https://yourdyndnsservice.net/nic/update?hostname=<domain>&myip=<ipaddr>&myipv6=<ip6addr>
Domain name: user1.example.com Domain name: user1.example.com
Username: myuser User name: user1.example.com
Password: mypassword Password: TOKEN
``` ```
Be sure to not add an URI scheme like `https://`, the device will throw an error. The IP address is set automatically by the device. Note that you can also set your IPv6 address by using `<ip6addr>` in the URL. ### ddclient
```
protocol=dyndns2
server=yourdyndnsservice.net
ssl=yes
login=user1.example.com
password=TOKEN
user1.example.com
```
## Known limits
- Explicit `myip`/`myipv6` values are only checked for syntax, private and reserved addresses are accepted there.
- The server itself never creates records, only the helper script does when adding a host.
- If you change a record at INWX by hand, the server does not notice. Delete `state.json` or change the IP to resync.
- Only one request updates at a time (a lock is held during the INWX call), which is plenty for a personal setup.
- The built-in HTTP server is meant to sit behind a reverse proxy. Do not expose its port directly.
## Development
```
uv run --python 3.14 python -m unittest -v
```
The tests use a fake INWX server. An additional smoke test runs against the INWX OT&E test system and is skipped unless `INWX_OTE_USER`, `INWX_OTE_PASS` and `INWX_OTE_HOST` (an existing A record in that account) are set in the environment. It restores the record afterwards and removes the record it creates for the helper test.
## License
AGPL-3.0-or-later, see `LICENSE`.
-11
View File
@@ -1,11 +0,0 @@
# INWX USERNAME
USERNAME=myusername
# INWX PASSWORD
PASSWORD=mypassword
# API-Host
APIHOST=https://api.domrobot.com/xmlrpc/
# Activate debugging? Use true or false
DEBUG=false
+30
View File
@@ -0,0 +1,30 @@
# Copy to ~/etc/snap-dyndns/config.toml (outside the web root) and chmod 600.
# Where the last known IPs are cached (default shown)
state_file = "~/etc/snap-dyndns/state.json"
# Header in which the reverse proxy puts the address of the device. The last entry is used.
# X-Forwarded-For is what Uberspace's proxy sets. Without this line the TCP peer's address is used,
# which is the proxy behind a web backend.
# Addresses that are not global (e.g. the proxy's) are rejected unless the device sends myip.
client_ip_header = "X-Forwarded-For"
[inwx]
user = "api-user"
pass = "api-password"
# Only needed if the INWX account has 2FA enabled (base32 secret of the authenticator)
# totp_secret = "JBSWY3DPEHPK3PXP"
# Default is the live API. Use the OT&E test system for experiments:
# api = "https://api.ote.domrobot.com/jsonrpc/"
# One section per hostname. The hostname is the Basic Auth user, the token the password.
# The record (A and/or AAAA) must already exist at INWX.
# Generate a token and its hash with:
# python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'
[hosts."user1.example.com"]
token_sha256 = "replace-with-sha256-hex-of-the-token"
# INWX zone, defaults to the last two labels of the hostname
# zone = "example.co.uk"
[hosts."user2.example.com"]
token_sha256 = "replace-with-another-hash"
-12
View File
@@ -1,12 +0,0 @@
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<title>Snap DynDNS Server</title>
</head>
<body>
<h1>Snap DynDNS Server</h1>
<p>This is a Dynamic DNS service. It is running with the <a href="https://src.mehl.mx/mxmehl/snap-dyndns-server">Snap DynDNS Server</a> software.</p>
<p>Please contact the site owner for more information on this specific service.</p>
</body>
</html>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

+382
View File
@@ -0,0 +1,382 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Snap DynDNS Server: dyndns2-style HTTP service that updates INWX records.
Clients authenticate with HTTP Basic Auth (user = hostname, password = token).
The INWX credentials never leave this server, and INWX is only contacted when
the IP of a hostname actually changed.
"""
import argparse
import base64
import contextlib
import hashlib
import hmac
import http
import http.client
import http.cookiejar
import http.server
import ipaddress
import json
import os
import ssl
import struct
import sys
import threading
import time
import tomllib
import urllib.parse
import urllib.request
from typing import cast
API_LIVE = "https://api.domrobot.com/jsonrpc/"
DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml"
DEFAULT_STATE = "~/etc/snap-dyndns/state.json"
class InwxError(Exception):
"""INWX API call failed. Messages must never contain credentials."""
class NoHost(InwxError):
"""The record to update does not exist at INWX."""
# --- INWX JSON-RPC client ---------------------------------------------------
def totp(secret, now=None):
"""RFC 6238 code (HMAC-SHA1, 30 s step, 6 digits) for a base32 secret."""
key = base64.b32decode(secret.replace(" ", "").upper())
counter = int((time.time() if now is None else now) // 30)
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = digest[-1] & 15
code = (struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF) % 10**6
return f"{code:06d}"
class _IPv4Https(urllib.request.HTTPSHandler):
"""HTTPS that only connects via IPv4.
The INWX API account is restricted to the server's IPv4 address, but the
process may prefer IPv6 for dual-stack hosts. Binding to 0.0.0.0 makes
socket.create_connection() skip every IPv6 address.
"""
def https_open(self, req):
return self.do_open(
http.client.HTTPSConnection,
req,
context=ssl.create_default_context(),
source_address=("0.0.0.0", 0),
)
@contextlib.contextmanager
def inwx_session(cfg):
"""Yield call(method, params) -> resData for a logged-in INWX session."""
inwx = cfg["inwx"]
url = inwx.get("api", API_LIVE)
opener = urllib.request.build_opener(
_IPv4Https, urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())
)
def call(method, params):
request = urllib.request.Request(
url,
json.dumps({"method": method, "params": params}).encode(),
{"Content-Type": "application/json"},
)
with opener.open(request, timeout=20) as response:
result = json.load(response)
if result.get("code") != 1000:
raise InwxError(f"{method}: {result.get('code')} {result.get('msg')}")
return result.get("resData") or {}
login = call(
"account.login", {"user": inwx["user"], "pass": inwx["pass"], "lang": "en"}
)
try:
if str(login.get("tfa", "0")) != "0":
if not inwx.get("totp_secret"):
raise InwxError("account requires 2FA but no totp_secret is configured")
call("account.unlock", {"tan": totp(inwx["totp_secret"])})
yield call
finally:
with contextlib.suppress(Exception):
call("account.logout", {})
def find_record(call, zone, name, rtype):
"""Return the single INWX record with this name and type, else raise NoHost."""
info = call("nameserver.info", {"domain": zone, "name": name, "type": rtype})
matches = [
r
for r in info.get("record", [])
if r.get("type") == rtype and r.get("name", "").rstrip(".").lower() == name
]
if not matches:
raise NoHost(f"no {rtype} record {name} in zone {zone}")
if len(matches) > 1:
raise InwxError(f"{len(matches)} {rtype} records named {name}, expected one")
return matches[0]
def inwx_update(cfg, zone, name, rtype, ip):
"""Set the record content to ip. Return True if INWX was changed."""
with inwx_session(cfg) as call:
record = find_record(call, zone, name, rtype)
if record.get("content") == ip:
return False
call("nameserver.updateRecord", {"id": record["id"], "content": ip})
return True
PLACEHOLDER = {"A": "192.0.2.1", "AAAA": "2001:db8::1"} # documentation addresses
def zone_of(host, entry):
"""INWX zone of a hostname: the host's `zone` setting, else its last two labels."""
return entry.get("zone") or ".".join(host.split(".")[-2:])
def ensure_record(cfg, zone, name, rtype, ttl=300):
"""Create the record with a placeholder address if missing. Return (created, record)."""
with inwx_session(cfg) as call:
try:
return False, find_record(call, zone, name, rtype)
except NoHost:
content = PLACEHOLDER[rtype]
call(
"nameserver.createRecord",
{
"domain": zone,
"type": rtype,
"name": name,
"content": content,
"ttl": ttl,
},
)
return True, {"content": content, "ttl": ttl}
# --- Request handling -------------------------------------------------------
def _check_auth(env, cfg, note):
"""Return the authenticated hostname or None. note() gets the reason for a refusal."""
header = env.get("HTTP_AUTHORIZATION", "")
if not header.lower().startswith("basic "):
note("badauth: missing or malformed Authorization header")
return None
try:
user, _, token = base64.b64decode(header[6:]).decode().partition(":")
except ValueError:
note("badauth: undecodable Authorization header")
return None
host = cfg.get("hosts", {}).get(user.lower())
expected = (host or {}).get("token_sha256", "").lower()
given = hashlib.sha256(token.encode()).hexdigest()
# Always compare, so unknown users and wrong tokens take the same path.
ok = hmac.compare_digest(given, expected)
if host is None:
note(f"badauth: unknown host {user[:64]!r}")
elif not ok:
note(f"{user.lower()}: badauth: wrong token")
else:
return user.lower()
return None
_STATE_LOCK = threading.Lock()
def _load_state(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return {}
def _save_state(path, state):
tmp = f"{path}.tmp"
with open(tmp, "w") as f:
json.dump(state, f)
os.replace(tmp, path)
def handle(env, cfg, update=inwx_update, note=None):
"""Process one request. Return (http_status, body).
note(text) receives one human-readable line per outcome for the log.
"""
note = note or (lambda text: None)
query = urllib.parse.parse_qs(env.get("QUERY_STRING", ""))
host = _check_auth(env, cfg, note)
if host is None:
return 401, "badauth"
requested = query.get("hostname", [host])[0].lower()
if requested != host:
note(
f"{host}: nohost: hostname parameter {requested[:64]!r} does not match the login"
)
return 404, "nohost"
# One IP per record type; without myip/myipv6 the connection's address is used.
given = [query[k][0] for k in ("myip", "myipv6") if query.get(k, [""])[0]]
ips = {}
for raw in given or [env.get("REMOTE_ADDR", "")]:
try:
ip = ipaddress.ip_address(raw)
except ValueError:
note(f"{host}: badip: invalid address {raw[:64]!r}")
return 400, "badip"
# Guards against publishing the proxy's address if client_ip_header is wrong
if not given and not ip.is_global:
note(
f"{host}: badip: connection address {ip} is not global, check client_ip_header"
)
return 400, "badip"
# shortcut: explicit myip/myipv6 are only syntax-checked (private ranges accepted), tighten if clients misbehave
ips["A" if ip.version == 4 else "AAAA"] = str(ip)
zone = zone_of(host, cfg["hosts"][host])
state_path = os.path.expanduser(cfg.get("state_file", DEFAULT_STATE))
os.makedirs(os.path.dirname(state_path), exist_ok=True)
lines = []
# shortcut: one lock held during the INWX call, fine at this load, split per host if updates get slow
with _STATE_LOCK:
state = _load_state(state_path)
for rtype, ip in ips.items():
old_ip = state.get(host, {}).get(rtype)
if old_ip == ip:
lines.append(f"nochg {ip}")
continue
try:
update(cfg, zone, host, rtype, ip)
except NoHost as e:
# shortcut: missing records are not created, add nameserver.createRecord if wanted
note(f"{host}: nohost: {e}, create it at INWX first")
return 404, "nohost"
except (InwxError, OSError, ValueError) as e:
note(f"{host}: 911: {rtype} update to {ip} failed: {e}")
return 502, "911"
# shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
note(f"{host}: good {rtype} {old_ip or 'unknown'} -> {ip}")
state.setdefault(host, {})[rtype] = ip
_save_state(state_path, state)
lines.append(f"good {ip}")
return 200, "\n".join(lines)
INDEX_HTML = """<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<title>Snap DynDNS Server</title>
</head>
<body>
<h1>Snap DynDNS Server</h1>
<p>This is a Dynamic DNS service. It is running with the <a href="https://src.mehl.mx/mxmehl/snap-dyndns-server">Snap DynDNS Server</a> software.</p>
<p>Please contact the site owner for more information on this specific service.</p>
</body>
</html>
"""
class Server(http.server.ThreadingHTTPServer):
config_path: str
class RequestHandler(http.server.BaseHTTPRequestHandler):
timeout = 30 # do not let stalled connections hold a thread forever
def do_GET(self):
url = urllib.parse.urlsplit(self.path)
if url.path in ("/", "/nic", "/nic/"):
return self._reply(200, INDEX_HTML, "text/html")
notes = []
ip = self.client_address[0]
if url.path != "/nic/update":
status, body = 404, "not found"
notes.append(f"not found: {url.path[:100]!r}")
else:
try:
# Read per request, so devices can be added without restarting
with open(cast(Server, self.server).config_path, "rb") as f:
cfg = tomllib.load(f)
ip = self._client_ip(cfg) or "-"
env = {
"QUERY_STRING": url.query,
"HTTP_AUTHORIZATION": self.headers.get("Authorization", ""),
"REMOTE_ADDR": ip,
}
status, body = handle(env, cfg, note=notes.append)
except Exception as e: # noqa: BLE001 - always answer the client
notes.append(f"500: {type(e).__name__}: {e}")
status, body = 500, "911"
# One line per noteworthy request: time, device address, HTTP status, what happened.
# A plain nochg is not noteworthy, devices poll every minute.
if notes:
print(
f"{time.strftime('[%Y-%m-%d %H:%M:%S]')} {ip}: {status} - {'; '.join(notes)}",
file=sys.stderr,
)
self._reply(status, body)
def log_request(self, code="-", size="-"):
"""Silence the default access log, do_GET writes a more useful line."""
def _client_ip(self, cfg):
"""Address of the device: last entry of client_ip_header (added by our proxy), else the peer."""
name = cfg.get("client_ip_header")
if name:
return self.headers.get(name, "").split(",")[-1].strip()
return self.client_address[0]
def _reply(self, status, body, content_type="text/plain"):
data = (body if body.endswith("\n") else body + "\n").encode()
self.send_response(status)
self.send_header("Content-Type", f"{content_type}; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
if status == 401:
self.send_header("WWW-Authenticate", 'Basic realm="Snap DynDNS"')
self.end_headers()
self.wfile.write(data)
def make_server(config_path, port, host="0.0.0.0"):
server = Server((host, port), RequestHandler)
server.config_path = config_path
return server
def main(argv=None):
parser = argparse.ArgumentParser(
description="Snap DynDNS Server (serves /nic/update)"
)
parser.add_argument(
"-c",
"--config",
default=DEFAULT_CONFIG,
help=f"config file (default: {DEFAULT_CONFIG})",
)
parser.add_argument(
"-p", "--port", type=int, default=8080, help="port to listen on (default: 8080)"
)
args = parser.parse_args(argv)
path = os.path.expanduser(args.config)
try: # fail fast on a broken config; it is re-read on every request later
with open(path, "rb") as f:
tomllib.load(f)
except (OSError, tomllib.TOMLDecodeError) as e:
sys.exit(f"snap-dyndns: cannot use config {path}: {e}")
make_server(path, args.port).serve_forever()
if __name__ == "__main__":
main()
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Add a host to the Snap DynDNS config, or replace its token.
Generates a random token, stores only its SHA-256 in the config and prints the
token once. The token is what the client needs; the server never sees it again.
Also makes sure the DNS record exists at INWX, which needs the server's IP.
"""
import argparse
import hashlib
import os
import re
import secrets
import sys
import tempfile
import tomllib
from snap_dyndns import DEFAULT_CONFIG, InwxError, ensure_record, zone_of
NAME = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$")
def set_host(text, host, digest, zone=None):
"""Return (new_text, created) with host's token_sha256 set to digest.
Works on the text, so comments and formatting stay. Raises ValueError if
an existing section is not in the usual `[hosts."name"]` form.
"""
exists = host in tomllib.loads(text).get("hosts", {})
if not exists:
section = f'\n[hosts."{host}"]\ntoken_sha256 = "{digest}"\n'
if zone:
section += f'zone = "{zone}"\n'
return text.rstrip("\n") + "\n" + section, True
if zone:
raise ValueError(f"{host} already exists, change its zone by hand")
lines = text.split("\n")
header = f'[hosts."{host}"]'
start = next((i for i, line in enumerate(lines) if line.strip() == header), None)
if start is None:
raise ValueError(
f"cannot find the line {header} in the config, edit {host} by hand"
)
for i in range(start + 1, len(lines)):
if lines[i].lstrip().startswith("["):
break
if re.match(r"\s*token_sha256\s*=", lines[i]):
lines[i] = f'token_sha256 = "{digest}"'
return "\n".join(lines), False
raise ValueError(f"no token_sha256 line in the section of {host}, edit it by hand")
def write_config(path, text):
"""Replace the file atomically, keeping its permissions (the config holds secrets)."""
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(path)))
try:
with os.fdopen(fd, "w") as f:
f.write(text)
os.chmod(tmp, os.stat(path).st_mode & 0o777)
os.replace(tmp, path)
except BaseException:
os.unlink(tmp)
raise
def confirm(question):
"""Ask on the terminal; anything but yes, including no input, means no."""
try:
return input(question).strip().lower() in ("y", "yes")
except EOFError:
return False
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument(
"hostname", help="e.g. home.example.com; an existing host gets a new token"
)
parser.add_argument(
"-c",
"--config",
default=DEFAULT_CONFIG,
help=f"config file (default: {DEFAULT_CONFIG})",
)
parser.add_argument(
"-y",
"--yes",
action="store_true",
help="replace the token of an existing host without asking",
)
parser.add_argument(
"-t",
"--types",
default="A",
help="record types to check and create, A or AAAA or A,AAAA (default: A)",
)
parser.add_argument(
"--ttl",
type=int,
default=300,
help="TTL of records created at INWX (default: 300)",
)
parser.add_argument(
"--no-dns",
action="store_true",
help="do not touch INWX, e.g. when not running on the server",
)
parser.add_argument(
"-z",
"--zone",
help="INWX zone for a new host, if not the last two labels of the hostname",
)
args = parser.parse_args(argv)
host = args.hostname.lower()
for value in (host, args.zone):
if value and not NAME.match(value):
sys.exit(f"invalid name: {value}")
types = [t.strip().upper() for t in args.types.split(",")]
if not set(types) <= {"A", "AAAA"}:
sys.exit(f"invalid record types: {args.types}")
path = os.path.expanduser(args.config)
token = secrets.token_urlsafe(32)
digest = hashlib.sha256(token.encode()).hexdigest()
try:
with open(path) as f:
text = f.read()
exists = host in tomllib.loads(text).get("hosts", {})
if (
exists
and not args.yes
and not confirm(f"{host} already exists. Replace its token? [y/N] ")
):
sys.exit("Aborted, config unchanged")
new_text, created = set_host(text, host, digest, args.zone)
cfg = tomllib.loads(new_text) # never write a config that does not parse
except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError
sys.exit(f"{path}: {e}")
# DNS first: if INWX is not reachable, nothing has been changed yet
if not args.no_dns:
zone = zone_of(host, cfg["hosts"][host])
try:
for rtype in types:
was_created, record = ensure_record(cfg, zone, host, rtype, args.ttl)
if was_created:
print(
f"DNS: created {rtype} record {host} ({record['content']} is a placeholder, "
f"TTL {record['ttl']}), the first update sets the real address"
)
else:
print(
f"DNS: {rtype} record {host} exists "
f"({record['content']}, TTL {record.get('ttl')})"
)
except (InwxError, OSError, KeyError, ValueError) as e:
sys.exit(
f"INWX: {type(e).__name__}: {e}\nNothing was changed in the config. The INWX "
"account is usually restricted to the server's IP, so run this there, "
"or use --no-dns."
)
try:
write_config(path, new_text)
except OSError as e:
sys.exit(f"{path}: {e}")
print(f"{'Added' if created else 'Replaced the token of'} {host} in {path}")
print("The server reads the config on every request, no restart needed.")
print(f"Token (shown only once): {token}")
print(f"Client entry for HOSTS: {host}:{token}")
if __name__ == "__main__":
main()
+564
View File
@@ -0,0 +1,564 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Run with: uv run --python 3.14 python -m unittest -v
The OT&E smoke test is skipped unless INWX_OTE_USER, INWX_OTE_PASS and
INWX_OTE_HOST (an existing A record there) are set in the environment.
"""
import base64
import contextlib
import hashlib
import http.client
import io
import json
import os
import secrets
import socket
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import cast
from unittest import mock
import snap_dyndns as sd
TOKEN = "s3cret"
HOST = "home.example.com"
def basic(user, token):
return "Basic " + base64.b64encode(f"{user}:{token}".encode()).decode()
def make_cfg(tmp, **inwx):
return {
"state_file": os.path.join(tmp, "state.json"),
"inwx": {"user": "u", "pass": "p", **inwx},
"hosts": {HOST: {"token_sha256": hashlib.sha256(TOKEN.encode()).hexdigest()}},
}
def make_env(query=f"hostname={HOST}", remote="1.2.3.4", auth=None):
return {
"QUERY_STRING": query,
"REMOTE_ADDR": remote,
"HTTP_AUTHORIZATION": auth or basic(HOST, TOKEN),
}
class TotpTest(unittest.TestCase):
def test_rfc6238_vector(self):
secret = base64.b32encode(b"12345678901234567890").decode()
self.assertEqual(sd.totp(secret, now=59), "287082")
class HandleTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.cfg = make_cfg(tmp.name)
self.calls = []
self.error = None
def update(self, cfg, zone, name, rtype, ip):
self.calls.append((zone, name, rtype, ip))
if self.error:
raise self.error
return True
def run_handle(self, **kw):
return sd.handle(make_env(**kw), self.cfg, self.update)
def test_first_update_then_nochg(self):
self.assertEqual(self.run_handle(), (200, "good 1.2.3.4"))
self.assertEqual(self.run_handle(), (200, "nochg 1.2.3.4"))
self.assertEqual(self.calls, [("example.com", HOST, "A", "1.2.3.4")])
def test_ip_change_updates_again(self):
self.run_handle()
self.assertEqual(self.run_handle(remote="5.6.7.8"), (200, "good 5.6.7.8"))
self.assertEqual(len(self.calls), 2)
def test_ipv6_connection_updates_aaaa(self):
self.assertEqual(
self.run_handle(remote="2606:4700:4700::1111"),
(200, "good 2606:4700:4700::1111"),
)
self.assertEqual(self.calls[0][2], "AAAA")
def test_myip_overrides_remote_addr(self):
self.run_handle(query=f"hostname={HOST}&myip=9.9.9.9")
self.assertEqual(self.calls[0][3], "9.9.9.9")
def test_dual_stack(self):
status, body = self.run_handle(
query=f"hostname={HOST}&myip=9.9.9.9&myipv6=2001:db8::2"
)
self.assertEqual((status, body), (200, "good 9.9.9.9\ngood 2001:db8::2"))
self.assertEqual([c[2] for c in self.calls], ["A", "AAAA"])
def test_hostname_param_optional(self):
self.assertEqual(self.run_handle(query="")[0], 200)
def test_zone_override(self):
self.cfg["hosts"][HOST]["zone"] = "example.co.uk"
self.run_handle()
self.assertEqual(self.calls[0][0], "example.co.uk")
def test_bad_credentials(self):
for auth in (
basic(HOST, "wrong"),
basic("other.example.com", TOKEN),
"Basic !!!",
"Bearer x",
):
self.assertEqual(self.run_handle(auth=auth), (401, "badauth"), auth)
self.assertEqual(self.calls, [])
def test_missing_auth(self):
env = make_env()
del env["HTTP_AUTHORIZATION"]
self.assertEqual(sd.handle(env, self.cfg, self.update), (401, "badauth"))
def test_hostname_mismatch(self):
self.assertEqual(
self.run_handle(query="hostname=other.example.com"), (404, "nohost")
)
def test_non_global_connection_address_is_rejected(self):
for remote in ("127.0.0.1", "10.0.0.5", "::1", ""):
self.assertEqual(self.run_handle(remote=remote), (400, "badip"), remote)
self.assertEqual(self.calls, [])
def test_explicit_ip_may_be_private(self):
self.assertEqual(
self.run_handle(
query=f"hostname={HOST}&myip=192.168.1.5", remote="127.0.0.1"
)[0],
200,
)
def test_invalid_ip(self):
self.assertEqual(
self.run_handle(query=f"hostname={HOST}&myip=1.2.3.4;rm"), (400, "badip")
)
self.assertEqual(self.calls, [])
def test_missing_record(self):
self.error = sd.NoHost("gone")
self.assertEqual(self.run_handle(), (404, "nohost"))
def test_inwx_failure_keeps_state_and_retries(self):
self.error = sd.InwxError("boom")
self.assertEqual(self.run_handle(), (502, "911"))
self.error = None
self.assertEqual(self.run_handle(), (200, "good 1.2.3.4"))
self.assertEqual(len(self.calls), 2)
class Ipv4BindTest(unittest.TestCase):
"""Checks the premise of _IPv4Https: binding to 0.0.0.0 skips IPv6 addresses."""
def test_source_address_skips_ipv6(self):
try:
server = socket.create_server(("::1", 0), family=socket.AF_INET6)
except OSError:
self.skipTest("no IPv6 loopback")
self.addCleanup(server.close)
port = server.getsockname()[1]
try:
socket.create_connection(("localhost", port), timeout=2).close()
except OSError:
self.skipTest("localhost does not resolve to ::1")
with self.assertRaises(OSError):
socket.create_connection(
("localhost", port), timeout=2, source_address=("0.0.0.0", 0)
)
class FakeInwx(ThreadingHTTPServer):
"""Minimal INWX JSON-RPC stand-in with cookie session and optional 2FA."""
def __init__(self, tfa_secret=None):
super().__init__(("127.0.0.1", 0), FakeInwxHandler)
self.tfa_secret = tfa_secret
self.wrong_login = False
self.unlocked = False
self.calls = []
self.records = [
{"id": 1, "name": HOST, "type": "A", "content": "10.0.0.1"},
{"id": 2, "name": "other.example.com", "type": "A", "content": "10.0.0.2"},
]
self.url = f"http://127.0.0.1:{self.server_port}/jsonrpc/"
threading.Thread(target=self.serve_forever, daemon=True).start()
class FakeInwxHandler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args: object) -> None:
pass
def do_POST(self):
srv = cast(FakeInwx, self.server)
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
method, p = req["method"], req["params"]
srv.calls.append(method)
cookie, code, res = None, 1000, {}
if method == "account.login":
if srv.wrong_login or (p["user"], p["pass"]) != ("u", "p"):
code = 2200
cookie = "sid=abc; Path=/"
srv.unlocked = srv.tfa_secret is None
res = {"tfa": "GOOGLE-AUTH" if srv.tfa_secret else "0"}
elif "sid=abc" not in self.headers.get("Cookie", ""):
code = 2002
elif method == "account.unlock":
valid = {
sd.totp(srv.tfa_secret, now=__import__("time").time() + d)
for d in (-30, 0, 30)
}
srv.unlocked = p["tan"] in valid
code = 1000 if srv.unlocked else 2200
elif not srv.unlocked:
code = 2200
elif method == "nameserver.info":
res = {
"record": [
r
for r in srv.records
if r["name"] == p["name"] and r["type"] == p["type"]
]
}
elif method == "nameserver.createRecord":
srv.records.append(
{
"id": 100 + len(srv.records),
**{k: p[k] for k in ("name", "type", "content", "ttl")},
}
)
elif method == "nameserver.updateRecord":
for r in srv.records:
if r["id"] == p["id"]:
r["content"] = p["content"]
body = json.dumps({"code": code, "msg": "x", "resData": res}).encode()
self.send_response(200)
if cookie:
self.send_header("Set-Cookie", cookie)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
class InwxClientTest(unittest.TestCase):
def start(self, **kw):
srv = FakeInwx(**kw)
self.addCleanup(srv.server_close)
self.addCleanup(srv.shutdown)
return srv
def cfg(self, srv, **inwx):
return {"inwx": {"user": "u", "pass": "p", "api": srv.url, **inwx}}
def test_update_changes_record(self):
srv = self.start()
self.assertTrue(
sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4")
)
self.assertEqual(srv.records[0]["content"], "1.2.3.4")
self.assertEqual(srv.calls[-1], "account.logout")
def test_same_content_skips_update(self):
srv = self.start()
self.assertFalse(
sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "10.0.0.1")
)
self.assertNotIn("nameserver.updateRecord", srv.calls)
def test_two_factor(self):
secret = base64.b32encode(b"12345678901234567890").decode()
srv = self.start(tfa_secret=secret)
self.assertTrue(
sd.inwx_update(
self.cfg(srv, totp_secret=secret), "example.com", HOST, "A", "1.2.3.4"
)
)
self.assertIn("account.unlock", srv.calls)
def test_two_factor_without_secret(self):
srv = self.start(tfa_secret="GEZDGNBVGY3TQOJQ")
with self.assertRaises(sd.InwxError):
sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4")
self.assertEqual(srv.calls[-1], "account.logout")
def test_ensure_record_creates_missing_record_once(self):
srv = self.start()
created, record = sd.ensure_record(self.cfg(srv), "example.com", HOST, "AAAA")
self.assertEqual(
(created, record), (True, {"content": sd.PLACEHOLDER["AAAA"], "ttl": 300})
)
self.assertEqual(srv.records[-1]["ttl"], 300)
self.assertEqual(
sd.ensure_record(self.cfg(srv), "example.com", HOST, "AAAA")[0], False
)
self.assertEqual(srv.calls.count("nameserver.createRecord"), 1)
def test_ensure_record_keeps_existing_record(self):
srv = self.start()
created, record = sd.ensure_record(
self.cfg(srv), "example.com", HOST, "A", ttl=60
)
self.assertFalse(created)
self.assertEqual(record["content"], "10.0.0.1")
self.assertNotIn("nameserver.createRecord", srv.calls)
def test_missing_record(self):
srv = self.start()
with self.assertRaises(sd.NoHost):
sd.inwx_update(self.cfg(srv), "example.com", HOST, "AAAA", "2001:db8::1")
def test_api_error_hides_password(self):
srv = self.start()
cfg = self.cfg(srv)
cfg["inwx"]["pass"] = "wrong-password"
with self.assertRaises(sd.InwxError) as ctx:
sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4")
self.assertNotIn("wrong-password", str(ctx.exception))
def test_https_connection_is_ipv4_only(self):
seen = {}
class FakeConnection(http.client.HTTPSConnection):
def __init__(self, *args, **kwargs):
seen.update(kwargs)
raise OSError("stop here")
cfg = {"inwx": {"user": "u", "pass": "p", "api": "https://inwx.invalid/"}}
with (
mock.patch("http.client.HTTPSConnection", FakeConnection),
self.assertRaises(OSError),
):
sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4")
self.assertEqual(seen["source_address"], ("0.0.0.0", 0))
def test_end_to_end_only_changes_reach_inwx(self):
srv = self.start()
with tempfile.TemporaryDirectory() as tmp:
cfg = make_cfg(tmp, api=srv.url)
for _ in range(3):
sd.handle(make_env(), cfg)
self.assertEqual(srv.calls.count("nameserver.updateRecord"), 1)
self.assertEqual(srv.calls.count("account.login"), 1)
class ServerTest(unittest.TestCase):
"""Real HTTP requests against make_server() with a fake INWX behind it."""
def start(self, **config):
inwx = FakeInwx()
tmp = tempfile.TemporaryDirectory()
path = os.path.join(tmp.name, "config.toml")
with open(path, "w") as f:
f.write(
f'''state_file = "{tmp.name}/state.json"
{"".join(f'{k} = "{v}"' + chr(10) for k, v in config.items())}
[inwx]
user = "u"
pass = "p"
api = "{inwx.url}"
[hosts."{HOST}"]
token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
'''
)
server = sd.make_server(path, 0, "127.0.0.1")
threading.Thread(target=server.serve_forever, daemon=True).start()
for cleanup in (
tmp.cleanup,
inwx.server_close,
inwx.shutdown,
server.server_close,
server.shutdown,
):
self.addCleanup(cleanup)
self.inwx = inwx
return server
def get(self, server, path="/nic/update?hostname=" + HOST, **headers):
headers.setdefault("Authorization", basic(HOST, TOKEN))
conn = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5)
conn.request("GET", path, headers=headers)
response = conn.getresponse()
return (
response.status,
response.getheader("WWW-Authenticate"),
response.read().decode(),
)
def test_update_via_forwarded_header_then_nochg(self):
server = self.start(client_ip_header="X-Forwarded-For")
# Only the last entry (added by our proxy) counts, earlier ones are client-controlled
headers = {"X-Forwarded-For": "6.6.6.6, 1.2.3.4"}
self.assertEqual(self.get(server, **headers), (200, None, "good 1.2.3.4\n"))
self.assertEqual(self.get(server, **headers), (200, None, "nochg 1.2.3.4\n"))
self.assertEqual(self.inwx.calls.count("nameserver.updateRecord"), 1)
def test_loopback_peer_without_header_is_rejected(self):
server = self.start()
self.assertEqual(self.get(server), (400, None, "badip\n"))
def test_missing_configured_header_is_rejected(self):
server = self.start(client_ip_header="X-Forwarded-For")
self.assertEqual(self.get(server), (400, None, "badip\n"))
def test_unauthorized_has_challenge(self):
server = self.start()
status, challenge, body = self.get(server, Authorization=basic(HOST, "bad"))
self.assertEqual(
(status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n")
)
def test_start_page_without_credentials(self):
server = self.start()
for path in ("/", "/nic", "/nic/"):
status, challenge, body = self.get(server, path, Authorization="")
self.assertEqual((status, challenge), (200, None), path)
self.assertIn("<h1>Snap DynDNS Server</h1>", body)
def logged(self, server, *args, **kw):
"""Run get() and return (response, text written to stderr)."""
err = io.StringIO()
with contextlib.redirect_stderr(err):
response = self.get(server, *args, **kw)
return response, err.getvalue()
def test_log_names_the_reason(self):
server = self.start(client_ip_header="X-Forwarded-For")
xff = {"X-Forwarded-For": "1.2.3.4"}
_, log = self.logged(server, Authorization=basic(HOST, "bad"), **xff)
self.assertRegex(
log,
rf"^\[\d{{4}}-\d\d-\d\d \d\d:\d\d:\d\d\] 1\.2\.3\.4: 401 - {HOST}: badauth: wrong token\n$",
)
_, log = self.logged(server, Authorization=basic("who.example.com", "x"), **xff)
self.assertIn("1.2.3.4: 401 - badauth: unknown host 'who.example.com'", log)
_, log = self.logged(server, "/nic/update?hostname=other.example.com", **xff)
self.assertIn(
"1.2.3.4: 404 - home.example.com: nohost: hostname parameter 'other.example.com'",
log,
)
_, log = self.logged(server, **xff)
self.assertIn("1.2.3.4: 200 - home.example.com: good A unknown -> 1.2.3.4", log)
def test_log_names_the_missing_record(self):
server = self.start(client_ip_header="X-Forwarded-For")
# Only an A record exists, the device also reports IPv6
response, log = self.logged(
server, **{"X-Forwarded-For": "2606:4700:4700::1111"}
)
self.assertEqual(response[0], 404)
self.assertIn(
"2606:4700:4700::1111: 404 - home.example.com: nohost: "
"no AAAA record home.example.com in zone example.com, create it at INWX first",
log,
)
def test_log_reports_both_results_of_a_combined_request(self):
server = self.start()
query = f"/nic/update?hostname={HOST}&myip=1.2.3.4&myipv6=2606:4700:4700::1111"
_, log = self.logged(server, query)
self.assertIn("good A unknown -> 1.2.3.4; ", log)
self.assertIn("nohost: no AAAA record", log)
def test_nochg_is_not_logged(self):
server = self.start(client_ip_header="X-Forwarded-For")
xff = {"X-Forwarded-For": "1.2.3.4"}
self.get(server, **xff)
response, log = self.logged(server, **xff)
self.assertEqual(response[2], "nochg 1.2.3.4\n")
self.assertEqual(log, "")
def test_log_names_the_inwx_failure(self):
server = self.start(client_ip_header="X-Forwarded-For")
self.inwx.wrong_login = True
_, log = self.logged(server, **{"X-Forwarded-For": "1.2.3.4"})
self.assertIn(
"1.2.3.4: 502 - home.example.com: 911: A update to 1.2.3.4 failed: account.login: 2200",
log,
)
def test_other_paths_are_not_found(self):
server = self.start()
self.assertEqual(self.get(server, "/elsewhere")[0], 404)
def test_unreachable_inwx_is_911(self):
server = self.start(client_ip_header="X-Forwarded-For")
self.inwx.shutdown()
self.inwx.server_close()
status, _, body = self.get(server, **{"X-Forwarded-For": "1.2.3.4"})
self.assertEqual((status, body), (502, "911\n"))
def test_broken_config_is_500(self):
server = self.start()
with open(server.config_path, "w") as f:
f.write("not = [valid")
self.assertEqual(self.get(server), (500, None, "911\n"))
def test_main_refuses_unreadable_config(self):
with self.assertRaises(SystemExit):
sd.main(["--config", "/nonexistent/config.toml"])
@unittest.skipUnless(
all(os.environ.get(k) for k in ("INWX_OTE_USER", "INWX_OTE_PASS", "INWX_OTE_HOST")),
"set INWX_OTE_USER, INWX_OTE_PASS, INWX_OTE_HOST to run against the INWX OT&E system",
)
class OteSmokeTest(unittest.TestCase):
def setUp(self):
self.host = os.environ["INWX_OTE_HOST"].lower()
self.zone = os.environ.get("INWX_OTE_ZONE") or ".".join(
self.host.split(".")[-2:]
)
self.cfg = {
"inwx": {
"user": os.environ["INWX_OTE_USER"],
"pass": os.environ["INWX_OTE_PASS"],
"api": "https://api.ote.domrobot.com/jsonrpc/",
}
}
def test_lookup_by_name_and_update(self):
cfg, zone, host = self.cfg, self.zone, self.host
with sd.inwx_session(cfg) as call:
original = sd.find_record(call, zone, host, "A")["content"]
test_ip = "192.0.2.1" if original != "192.0.2.1" else "192.0.2.2"
try:
self.assertTrue(sd.inwx_update(cfg, zone, host, "A", test_ip))
with sd.inwx_session(cfg) as call:
self.assertEqual(
sd.find_record(call, zone, host, "A")["content"], test_ip
)
finally:
sd.inwx_update(cfg, zone, host, "A", original)
def test_ensure_record_creates_once_and_is_cleaned_up(self):
cfg, zone = self.cfg, self.zone
name = f"snap-test-{secrets.token_hex(3)}.{zone}"
try:
self.assertTrue(sd.ensure_record(cfg, zone, name, "A")[0])
with sd.inwx_session(cfg) as call:
record = sd.find_record(call, zone, name, "A")
self.assertEqual(
(record["content"], int(record["ttl"])), (sd.PLACEHOLDER["A"], 300)
)
self.assertFalse(sd.ensure_record(cfg, zone, name, "A")[0])
finally:
with (
sd.inwx_session(cfg) as call,
contextlib.suppress(sd.NoHost),
):
record = sd.find_record(call, zone, name, "A")
call("nameserver.deleteRecord", {"id": record["id"]})
if __name__ == "__main__":
unittest.main()
+198
View File
@@ -0,0 +1,198 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
import contextlib
import hashlib
import io
import os
import stat
import tempfile
import tomllib
import unittest
from unittest import mock
import snap_dyndns_host as sh
CONFIG = """\
# my comment
state_file = "/tmp/state.json"
[inwx]
user = "u"
pass = "p"
[hosts."a.example.com"]
token_sha256 = "aaaa"
# keep this comment
[hosts."b.example.com"]
zone = "example.com"
token_sha256 = "bbbb" # trailing
"""
class SetHostTest(unittest.TestCase):
def test_new_host_is_appended(self):
text, created = sh.set_host(
CONFIG, "c.example.co.uk", "cccc", zone="example.co.uk"
)
self.assertTrue(created)
hosts = tomllib.loads(text)["hosts"]
self.assertEqual(
hosts["c.example.co.uk"], {"token_sha256": "cccc", "zone": "example.co.uk"}
)
self.assertEqual(hosts["a.example.com"], {"token_sha256": "aaaa"})
self.assertTrue(text.startswith(CONFIG.rstrip("\n")))
def test_existing_host_gets_new_hash_only(self):
text, created = sh.set_host(CONFIG, "b.example.com", "new", None)
self.assertFalse(created)
parsed = tomllib.loads(text)["hosts"]
self.assertEqual(
parsed["b.example.com"], {"zone": "example.com", "token_sha256": "new"}
)
self.assertEqual(parsed["a.example.com"]["token_sha256"], "aaaa")
self.assertIn("# keep this comment", text)
def test_existing_host_with_unusual_header_is_refused(self):
odd = CONFIG.replace('[hosts."a.example.com"]', "[hosts.'a.example.com']")
with self.assertRaises(ValueError):
sh.set_host(odd, "a.example.com", "new")
def test_zone_for_existing_host_is_refused(self):
with self.assertRaises(ValueError):
sh.set_host(CONFIG, "a.example.com", "new", zone="example.com")
def test_config_without_hosts(self):
text, created = sh.set_host(
'[inwx]\nuser = "u"\npass = "p"', "a.example.com", "aaaa"
)
self.assertTrue(created)
self.assertEqual(
tomllib.loads(text)["hosts"]["a.example.com"]["token_sha256"], "aaaa"
)
class MainTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.path = os.path.join(tmp.name, "config.toml")
with open(self.path, "w") as f:
f.write(CONFIG)
os.chmod(self.path, 0o600)
# Never talk to the real INWX from tests
patcher = mock.patch.object(
sh,
"ensure_record",
return_value=(True, {"content": "192.0.2.1", "ttl": 300}),
)
self.ensure = patcher.start()
self.addCleanup(patcher.stop)
def run_main(self, *args):
out = io.StringIO()
with contextlib.redirect_stdout(out):
sh.main(["-c", self.path, *args])
return out.getvalue()
def test_printed_token_matches_stored_hash(self):
output = self.run_main("New.Example.com")
token = output.split("Token (shown only once): ")[1].split("\n")[0]
self.assertIn(f"Client entry for HOSTS: new.example.com:{token}", output)
with open(self.path, "rb") as f:
stored = tomllib.load(f)["hosts"]["new.example.com"]["token_sha256"]
self.assertEqual(stored, hashlib.sha256(token.encode()).hexdigest())
def test_rotation_changes_the_hash_and_keeps_permissions(self):
self.run_main("a.example.com", "--yes")
with open(self.path, "rb") as f:
self.assertNotEqual(
tomllib.load(f)["hosts"]["a.example.com"]["token_sha256"], "aaaa"
)
self.assertEqual(stat.S_IMODE(os.stat(self.path).st_mode), 0o600)
def test_existing_host_asks_and_replaces_on_yes(self):
with mock.patch("builtins.input", return_value="y") as ask:
self.run_main("a.example.com")
self.assertIn("already exists", ask.call_args.args[0])
self.assertNotEqual(self.stored_hash("a.example.com"), "aaaa")
def test_existing_host_is_kept_on_no_or_without_input(self):
for answer in ("", "n", EOFError()):
with (
mock.patch("builtins.input", side_effect=[answer]),
self.assertRaises(SystemExit),
):
self.run_main("a.example.com")
self.assertEqual(self.stored_hash("a.example.com"), "aaaa")
def test_new_host_does_not_ask(self):
with mock.patch("builtins.input", side_effect=AssertionError("asked")):
self.run_main("fresh.example.com")
def stored_hash(self, host):
with open(self.path, "rb") as f:
return tomllib.load(f)["hosts"][host]["token_sha256"]
def test_creates_missing_record_with_default_ttl(self):
output = self.run_main("fresh.example.com")
args = self.ensure.call_args.args
self.assertEqual(args[1:], ("example.com", "fresh.example.com", "A", 300))
self.assertIn("DNS: created A record fresh.example.com", output)
def test_types_ttl_and_zone_are_passed_on(self):
self.run_main(
"fresh.example.co.uk", "-z", "example.co.uk", "-t", "a,aaaa", "--ttl", "60"
)
calls = [c.args[1:] for c in self.ensure.call_args_list]
self.assertEqual(
calls,
[
("example.co.uk", "fresh.example.co.uk", "A", 60),
("example.co.uk", "fresh.example.co.uk", "AAAA", 60),
],
)
def test_existing_record_is_reported_not_changed(self):
self.ensure.return_value = (False, {"content": "1.2.3.4", "ttl": 3600})
output = self.run_main("fresh.example.com")
self.assertIn("A record fresh.example.com exists (1.2.3.4, TTL 3600)", output)
def test_zone_of_existing_host_comes_from_config(self):
self.run_main("b.example.com", "--yes")
self.assertEqual(self.ensure.call_args.args[1], "example.com")
def test_no_dns_skips_inwx(self):
self.run_main("fresh.example.com", "--no-dns")
self.ensure.assert_not_called()
def test_inwx_failure_changes_nothing(self):
self.ensure.side_effect = sh.InwxError(
"account.login: 2200 Authentication error"
)
with self.assertRaises(SystemExit) as ctx:
self.run_main("fresh.example.com")
self.assertIn("Nothing was changed", str(ctx.exception))
with open(self.path) as f:
self.assertEqual(f.read(), CONFIG)
def test_invalid_record_type(self):
with self.assertRaises(SystemExit):
self.run_main("fresh.example.com", "-t", "MX")
self.ensure.assert_not_called()
def test_invalid_hostname_leaves_config_untouched(self):
for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"):
with self.assertRaises(SystemExit):
self.run_main(bad)
with open(self.path) as f:
self.assertEqual(f.read(), CONFIG)
def test_missing_config(self):
os.unlink(self.path)
with self.assertRaises(SystemExit):
self.run_main("a.example.com")
if __name__ == "__main__":
unittest.main()
-49
View File
@@ -1,49 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
<methodName>nameserver.updateRecord</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>user</name>
<value>
<string>%USER%</string>
</value>
</member>
<member>
<name>lang</name>
<value>
<string>en</string>
</value>
</member>
<member>
<name>pass</name>
<value>
<string>%PASSWD%</string>
</value>
</member>
<member>
<name>id</name>
<value>
<int>%DNSID%</int>
</value>
</member>
<member>
<name>content</name>
<value>
<string>%NEWIP%</string>
</value>
</member>
<member>
<name>ttl</name>
<value>
<int>3600</int>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>
-108
View File
@@ -1,108 +0,0 @@
<?php
/***********************************************************************
* Copyright (C) 2016 Max Mehl <mail [at] mehl [dot] mx>
************************************************************************
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
************************************************************************
*
* This file receives the requests, sanitises them, forwards the input
* to update.sh and prints the results. It is also responsible for
* debug logs.
*
***********************************************************************/
?>
<?php
// check whether debuggging is activated (very unprofessional here, improvements welcome)
$config = file_get_contents('config.cfg');
$debug = preg_match("/DEBUG=true/", $config);
if($debug === 1) {
$debug = true;
}
else {
$debug = false;
}
// if GET request is empty, use POST automatically
if(empty($_GET)) {
$method = "post";
}
// if a parameter is empty, set variable to false
if($method === "post") {
$domain = isset($_POST['domain']) ? $_POST['domain'] : false;
$ip = isset($_POST['ip']) ? $_POST['ip'] : false;
$user = isset($_POST['user']) ? $_POST['user'] : false;
$pass = isset($_POST['pass']) ? $_POST['pass'] : false;
}
else {
$domain = isset($_GET['domain']) ? $_GET['domain'] : false;
$ip = isset($_GET['ip']) ? $_GET['ip'] : false;
$user = isset($_GET['user']) ? $_GET['user'] : false;
$pass = isset($_GET['pass']) ? $_GET['pass'] : false;
}
// if any variable is empty, throw an error, else proceed
if(empty($domain) || empty($ip) || empty($user) || empty($pass)) {
echo 'At least one variable is empty. You have to define domain, IP address, username and password';
}
else {
// sanitise variables so we can protect our shell script
$domain = escapeshellarg($domain);
$ip = escapeshellarg($ip);
$user = escapeshellarg($user);
$pass = escapeshellarg($pass);
// pass variables to update.sh and show output
$command = '/bin/bash update.sh ' . $domain . ' ' . $ip . ' ' . $user . ' ' . $pass;
$output = shell_exec($command);
echo "<pre>$output</pre>";
}
// DEBUGGING
if($debug === true) {
$date = date("Y-m-d H:i:s");
$browser = $_SERVER['HTTP_USER_AGENT'];
$postdata = print_r($_POST, TRUE);
$getdata = print_r($_GET, TRUE);
$debug =
// basic info
'$date: ' . $date . '<br />' .
'$browser: ' . $browser . '<br />' .
'$debug: ' . $debug . '<br />' .
'$method: ' . $method . '<br />' .
// Specific set variables
'$domain: ' . $domain . '<br />' .
'$ip: ' . $ip . '<br />' .
'$user: ' . $user . '<br />' .
'$pass: ' . $pass . '<br />' .
// all POST and GET
'$postdata: ' . $postdata . '<br />' .
'$getdata: ' . $getdata . '<br />'
;
echo "<h2>Debug information:</h2>";
print_r($debug); // Show debug in browser
$debug_log = str_replace('<br />', "\r\n", $debug); //
file_put_contents('debug.log', $debug_log, FILE_APPEND | LOCK_EX);
}
?>
-80
View File
@@ -1,80 +0,0 @@
#!/bin/bash
########################################################################
# Copyright (C) 2016 Max Mehl <mail [at] mehl [dot] mx>
########################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
#
# This file uses the data forwarded by update.php, validates the given
# login data in the user database, and does the API call to the INWX
# API.
#
########################################################################
cd "$(dirname "$(readlink -f "$0")")"
# Test if config.cfg exists and set needed variables
if [ ! -e config.cfg ]; then echo "Missing config.cfg file. Edit and rename config.cfg.sample"; exit 1; fi
source config.cfg
# Check dependencies
deperrors=''
for depend in curl; do
if ! command -v "$depend" >/dev/null 2>&1; then
deperrors="$depend $deperrors"
fi
done
if [ -n "$deperrors" ]; then
cat <<-EOF
This program depends on some other programs to function.
Not all of those programs could be located on your system.
Please use your package manager to install the following programs:
EOF
echo "$deperrors"
exit 1
fi
USERDB=users.db
DOMAIN="$1"
NEWIP="$2"
U_USER="$3"
U_PASS="$4"
E=$(grep "^$DOMAIN;" $USERDB)
if [ "$E" != "" ]; then
DNSID=$(echo $E | cut -d";" -f2)
E_USER=$(echo $E | cut -d";" -f3)
E_PASS=$(echo $E | cut -d";" -f4)
# Check if user as given correct user and password
if [ "$U_USER" == "$E_USER" ] && [ "$U_PASS" == "$E_PASS" ]; then
DATA=$(cat update.api | sed "s/%PASSWD%/$PASSWORD/g;s/%USER%/$USERNAME/g;s/%DNSID%/$DNSID/g;s/%NEWIP%/$NEWIP/g")
curl -X POST -d "$DATA" "$APIHOST" --header "Content-Type:text/xml" --insecure > update.log
echo "" >> update.log
echo "Updated IP address for $DNSID ($DOMAIN) to $NEWIP." >> update.log
echo "Success: Updated $DOMAIN to $NEWIP."
else
echo "Wrong user or password."
fi
else
echo "Domain does not exist in database"
fi
-3
View File
@@ -1,3 +0,0 @@
# DOMAIN; DOMAIN-ID; USER; PASSWORD
user1.example.com;123456789;myuser;mypassword
user2.example.com;987654321;otheruser;otherpassword