feat!: complete refactoring of server #1
No files matched your search
+6
-4
@@ -1,4 +1,6 @@
|
||||
debug.log
|
||||
update.log
|
||||
users.db
|
||||
config.cfg
|
||||
__pycache__/
|
||||
config.toml
|
||||
state.json
|
||||
state.json.lock
|
||||
state.json.tmp
|
||||
.env
|
||||
@@ -1,15 +1,15 @@
|
||||
# Only allow web access to update.php and index.html
|
||||
<Files *>
|
||||
Order Deny,Allow
|
||||
Deny from all
|
||||
</Files>
|
||||
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
<FilesMatch ^$>
|
||||
Order Allow,Deny
|
||||
Allow from all
|
||||
</FilesMatch>
|
||||
# Run update.cgi as CGI and hand the Authorization header to it
|
||||
Options +ExecCGI
|
||||
AddHandler cgi-script .cgi
|
||||
CGIPassAuth On
|
||||
|
||||
<FilesMatch "^(update\.php|index\.html)$">
|
||||
Order Allow,Deny
|
||||
Allow from all
|
||||
# Optional: config location if it is not ~/etc/snap-dyndns/config.toml
|
||||
# SetEnv SNAP_DYNDNS_CONFIG /home/USER/etc/snap-dyndns/config.toml
|
||||
|
||||
# Only update.cgi may be requested, nothing else of this repository
|
||||
<FilesMatch "^(?!update\.cgi$)">
|
||||
Require all denied
|
||||
</FilesMatch>
|
||||
@@ -1,71 +1,125 @@
|
||||
# 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 CGI script without dependencies beyond the standard library, made for 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), 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 /update.cgi` 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 already. The server picks A or AAAA depending on the IP family, and keeps the TTL you set there.
|
||||
|
||||
## 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.
|
||||
- Apache with CGI and `.htaccess` support (Uberspace 7 has both)
|
||||
- Python 3.11 or newer, no packages needed
|
||||
- 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 IP 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.
|
||||
## Installation on Uberspace
|
||||
|
||||
## Installation
|
||||
Clone the repository into a web-accessible directory, e.g. the document root of a dedicated (sub)domain:
|
||||
|
||||
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.
|
||||
```
|
||||
git clone https://src.mehl.mx/mxmehl/snap-dyndns-server /var/www/virtual/myuser/dyndns.mydomain.net
|
||||
```
|
||||
|
||||
### config.cfg
|
||||
The `.htaccess` in the repository enables CGI, passes the `Authorization` header to the script, and denies access to every file except `update.cgi`. If your Python is not at `/usr/bin/python3.14`, adjust the shebang of `update.cgi`.
|
||||
|
||||
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 **outside** the web root and make it private:
|
||||
|
||||
### users.db
|
||||
```
|
||||
mkdir -p ~/etc/snap-dyndns
|
||||
cp /var/www/virtual/myuser/dyndns.mydomain.net/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).
|
||||
If you prefer another location, uncomment `SetEnv SNAP_DYNDNS_CONFIG` in `.htaccess`. The state file with the last known IPs is written next to the config (`state_file` in the config).
|
||||
|
||||
#### Gather INWX domain ID
|
||||
### Adding a device
|
||||
|
||||
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.
|
||||
Generate a token and its hash:
|
||||
|
||||

|
||||
```
|
||||
python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'
|
||||
```
|
||||
|
||||
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.
|
||||
Put the hash into a new section of `config.toml` and give the token to the device:
|
||||
|
||||
```toml
|
||||
[hosts."user1.example.com"]
|
||||
token_sha256 = "<hash>"
|
||||
```
|
||||
|
||||
The hostname is the Basic Auth user name, the token the password. The INWX zone is guessed as the last two labels of the hostname. For zones such as `example.co.uk` set `zone = "example.co.uk"` in that section.
|
||||
|
||||
## 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.
|
||||
|
||||
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:
|
||||
With curl (the `-u` option keeps the credentials out of the URL):
|
||||
|
||||
```
|
||||
Update-URL: yourdyndnsservice.net/update.php?domain=<domain>&user=<username>&pass=<pass>&ip=<ipaddr>
|
||||
curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi"
|
||||
curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi?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
|
||||
- `911` (502 or 500): INWX or the server config failed, see the Apache error log
|
||||
|
||||
### AVM FritzBox
|
||||
|
||||
Choose a custom DynDNS provider:
|
||||
|
||||
```
|
||||
Update-URL: https://dyndns.mydomain.net/update.cgi?hostname=<domain>&myip=<ipaddr>&myipv6=<ip6addr>
|
||||
Domain name: user1.example.com
|
||||
Username: myuser
|
||||
Password: mypassword
|
||||
User name: user1.example.com
|
||||
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=dyndns.mydomain.net
|
||||
script=/dyn/update.cgi
|
||||
ssl=yes
|
||||
login=user1.example.com
|
||||
password=TOKEN
|
||||
user1.example.com
|
||||
```
|
||||
|
||||
## Known limits
|
||||
|
||||
- The IP is only checked for syntax, private and reserved addresses are accepted.
|
||||
- Missing records are not created, add them at INWX first.
|
||||
- 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 file lock is held during the INWX call), which is plenty for a personal setup.
|
||||
|
||||
## 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.
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0-or-later, see `LICENSE`.
|
||||
@@ -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
|
||||
@@ -0,0 +1,24 @@
|
||||
# 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"
|
||||
|
||||
[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
@@ -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 |
+217
@@ -0,0 +1,217 @@
|
||||
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""Snap DynDNS Server: dyndns2-style CGI broker 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 base64
|
||||
import contextlib
|
||||
import fcntl
|
||||
import hashlib
|
||||
import hmac
|
||||
import http
|
||||
import http.cookiejar
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import tomllib
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
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}"
|
||||
|
||||
|
||||
@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(
|
||||
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
|
||||
|
||||
|
||||
# --- Request handling -------------------------------------------------------
|
||||
|
||||
|
||||
def _check_auth(env, cfg):
|
||||
"""Return the authenticated hostname or None."""
|
||||
header = env.get("HTTP_AUTHORIZATION", "")
|
||||
if not header.lower().startswith("basic "):
|
||||
return None
|
||||
try:
|
||||
user, _, token = base64.b64decode(header[6:]).decode().partition(":")
|
||||
except ValueError:
|
||||
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.
|
||||
if hmac.compare_digest(given, expected) and host is not None:
|
||||
return user.lower()
|
||||
return None
|
||||
|
||||
|
||||
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):
|
||||
"""Process one request. Return (http_status, body)."""
|
||||
query = urllib.parse.parse_qs(env.get("QUERY_STRING", ""))
|
||||
host = _check_auth(env, cfg)
|
||||
if host is None:
|
||||
return 401, "badauth"
|
||||
|
||||
requested = query.get("hostname", [host])[0].lower()
|
||||
if requested != host:
|
||||
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:
|
||||
return 400, "badip"
|
||||
# shortcut: syntax-only check (private/reserved IPs are accepted), reject them if clients misbehave
|
||||
ips["A" if ip.version == 4 else "AAAA"] = str(ip)
|
||||
|
||||
zone = cfg["hosts"][host].get("zone") or ".".join(host.split(".")[-2:])
|
||||
state_path = os.path.expanduser(cfg.get("state_file", DEFAULT_STATE))
|
||||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||||
|
||||
lines = []
|
||||
# shortcut: lock is held during the INWX call, fine at this load, split if updates ever get slow
|
||||
with open(f"{state_path}.lock", "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
state = _load_state(state_path)
|
||||
for rtype, ip in ips.items():
|
||||
if state.get(host, {}).get(rtype) == 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
|
||||
print(f"snap-dyndns: {host}: {e}", file=sys.stderr)
|
||||
return 404, "nohost"
|
||||
except (InwxError, OSError, ValueError) as e:
|
||||
print(f"snap-dyndns: {host}: {e}", file=sys.stderr)
|
||||
return 502, "911"
|
||||
# shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
|
||||
state.setdefault(host, {})[rtype] = ip
|
||||
_save_state(state_path, state)
|
||||
lines.append(f"good {ip}")
|
||||
return 200, "\n".join(lines)
|
||||
|
||||
|
||||
def main(env=os.environ, out=sys.stdout):
|
||||
"""CGI entry point."""
|
||||
try:
|
||||
path = os.path.expanduser(env.get("SNAP_DYNDNS_CONFIG", DEFAULT_CONFIG))
|
||||
with open(path, "rb") as f:
|
||||
cfg = tomllib.load(f)
|
||||
status, body = handle(env, cfg)
|
||||
except Exception as e: # noqa: BLE001 - a CGI must always answer
|
||||
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr)
|
||||
status, body = 500, "911"
|
||||
headers = [
|
||||
f"Status: {status} {http.HTTPStatus(status).phrase}",
|
||||
"Content-Type: text/plain; charset=utf-8",
|
||||
"Cache-Control: no-store",
|
||||
]
|
||||
if status == 401:
|
||||
headers.append('WWW-Authenticate: Basic realm="Snap DynDNS"')
|
||||
out.write("\n".join(headers) + "\n\n" + body + "\n")
|
||||
@@ -0,0 +1,305 @@
|
||||
# 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 hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
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.fail = None
|
||||
|
||||
def update(self, cfg, zone, name, rtype, ip):
|
||||
self.calls.append((zone, name, rtype, ip))
|
||||
if self.fail:
|
||||
raise self.fail
|
||||
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="2001:db8::1"), (200, "good 2001:db8::1"))
|
||||
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_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.fail = sd.NoHost("gone")
|
||||
self.assertEqual(self.run_handle(), (404, "nohost"))
|
||||
|
||||
def test_inwx_failure_keeps_state_and_retries(self):
|
||||
self.fail = sd.InwxError("boom")
|
||||
self.assertEqual(self.run_handle(), (502, "911"))
|
||||
self.fail = None
|
||||
self.assertEqual(self.run_handle(), (200, "good 1.2.3.4"))
|
||||
self.assertEqual(len(self.calls), 2)
|
||||
|
||||
|
||||
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.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, *args):
|
||||
pass
|
||||
|
||||
def do_POST(self):
|
||||
srv = 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 (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.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_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_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 MainTest(unittest.TestCase):
|
||||
def run_main(self, env, cfg_text):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, "config.toml")
|
||||
with open(path, "w") as f:
|
||||
f.write(cfg_text.replace("STATE", os.path.join(tmp, "state.json")))
|
||||
out = io.StringIO()
|
||||
sd.main({**env, "SNAP_DYNDNS_CONFIG": path}, out)
|
||||
return out.getvalue()
|
||||
|
||||
CFG = f"""
|
||||
state_file = "STATE"
|
||||
[inwx]
|
||||
user = "u"
|
||||
pass = "p"
|
||||
api = "http://127.0.0.1:1/"
|
||||
[hosts."{HOST}"]
|
||||
token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}"
|
||||
"""
|
||||
|
||||
def test_unauthorized_has_challenge(self):
|
||||
out = self.run_main(make_env(auth=basic(HOST, "bad")), self.CFG)
|
||||
head, _, body = out.partition("\n\n")
|
||||
self.assertTrue(head.startswith("Status: 401 Unauthorized"))
|
||||
self.assertIn('WWW-Authenticate: Basic realm="Snap DynDNS"', head)
|
||||
self.assertEqual(body, "badauth\n")
|
||||
|
||||
def test_unreachable_inwx_is_911(self):
|
||||
out = self.run_main(make_env(), self.CFG)
|
||||
self.assertTrue(out.startswith("Status: 502 Bad Gateway\n"))
|
||||
self.assertTrue(out.endswith("\n\n911\n"))
|
||||
|
||||
def test_broken_config_is_500(self):
|
||||
out = self.run_main(make_env(), "not = [valid")
|
||||
self.assertTrue(out.startswith("Status: 500 Internal Server Error\n"))
|
||||
|
||||
|
||||
@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 test_lookup_by_name_and_update(self):
|
||||
host = os.environ["INWX_OTE_HOST"].lower()
|
||||
zone = os.environ.get("INWX_OTE_ZONE") or ".".join(host.split(".")[-2:])
|
||||
cfg = {
|
||||
"inwx": {
|
||||
"user": os.environ["INWX_OTE_USER"],
|
||||
"pass": os.environ["INWX_OTE_PASS"],
|
||||
"api": "https://api.ote.domrobot.com/jsonrpc/",
|
||||
}
|
||||
}
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
-49
@@ -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>
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/python3.14
|
||||
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
||||
from snap_dyndns import main
|
||||
|
||||
main()
|
||||
-108
@@ -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);
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# DOMAIN; DOMAIN-ID; USER; PASSWORD
|
||||
user1.example.com;123456789;myuser;mypassword
|
||||
user2.example.com;987654321;otheruser;otherpassword
|
||||
Reference in new issue
Block a user