feat(network): implement smart ddns polling via dynu and ddclient
- Introduce `monitor.py` to validate public IPv4 addresses and maintain a local history log, bypassing strict API rate limits - Configure `dynu-monitor.timer` to execute the polling script every 30 minutes under a hardened systemd sandbox. - Mount decrypted API credentials into `ddclient.service` via sops-nix `LoadCredential` directives - Documented systemd architecture and Python logic in `docs/dynu-ip-monitor.md`.
This commit is contained in:
1 parent
ebb6c48663
commit
c7acc2b0a3
5 files changed
+360
No files matched your search
@@ -0,0 +1,92 @@
|
||||
# 🌐 Dynu IP Monitor Service (dynu-ip-monitor)
|
||||
|
||||
This service manages the Dynamic DNS (DDNS) lifecycle for your host. Instead of continuously polling public APIs (which can lead to blocks or rate-limits), it implements a smart, local-first change detector that updates Dynu via `ddclient` **only when an actual WAN IP rotation is detected**.
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ Architecture and Logic Flow
|
||||
|
||||
The synchronization process runs in the background as a system service completely decoupled from the graphical user session.
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Timer triggers dynu-monitor.service] --> B[Fetch public IP via HTTP]
|
||||
B --> C{Verify public IPv4?}
|
||||
C -- No/Timeout --> D[Log warning to journald & Fallback to next provider]
|
||||
C -- Yes --> E[Read history database log]
|
||||
E --> F{Did IP change?}
|
||||
F -- No --> G[Exit cleanly]
|
||||
F -- Yes --> H[Log rotation in history log]
|
||||
H --> I[Trigger systemctl start ddclient.service]
|
||||
I --> J{ddclient success?}
|
||||
J -- Yes --> K[Record success in ip_history.jsonl]
|
||||
J -- No --> L[Record failed_update in ip_history.jsonl & exit 1]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Public IP Discovery & Validation
|
||||
|
||||
### 1. HTTP Resolvers with Fallback
|
||||
The script queries multiple independent IP reflection endpoints sequentially to handle offline states or service outages:
|
||||
1. `https://api.ipify.org`
|
||||
2. `https://ifconfig.me/ip`
|
||||
3. `https://icanhazip.com`
|
||||
4. `https://wtfismyip.com/text`
|
||||
|
||||
If a provider fails or times out, the script logs the warning to `stderr` and falls back to the next provider. If all providers fail, it exits with a non-zero code to flag a connectivity issue.
|
||||
|
||||
### 2. IP Address Validation
|
||||
Every returned IP must pass a verification check to ensure it is a valid public IPv4 address. The check rejects:
|
||||
* Loopback ranges (`127.0.0.0/8`)
|
||||
* Private networks / RFC 1918 (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`)
|
||||
* Link-local addresses (`169.254.0.0/16`)
|
||||
* Carrier-Grade NAT / CGNAT (`100.64.0.0/10`)
|
||||
|
||||
---
|
||||
|
||||
## 📊 Persistent History Registry
|
||||
|
||||
The monitor maintains a historical log of all your public IP assignments in a JSONLines format at `/var/lib/dynu/ip_history.jsonl`.
|
||||
|
||||
Each entry records the timestamp, IP address, and status:
|
||||
```json
|
||||
{"timestamp": "2026-06-24T02:00:00Z", "ip": "186.116.231.181", "status": "success"}
|
||||
{"timestamp": "2026-06-24T02:30:00Z", "ip": "186.116.231.181", "status": "success"}
|
||||
{"timestamp": "2026-06-24T03:00:00Z", "ip": "186.116.232.40", "status": "success"}
|
||||
```
|
||||
|
||||
At each check, the monitor compares the current public IP with the **last recorded successful IP** in the history file. If they match, the monitor exits cleanly without invoking the DNS provider APIs.
|
||||
|
||||
---
|
||||
|
||||
## 🔑 secrets-management & sops-nix Integration
|
||||
|
||||
### Dynamic User Credentials Access
|
||||
The `ddclient` service in NixOS runs with systemd `DynamicUser=true` for security. Because the dynamic user doesn't exist statically, standard file ownership can prevent access.
|
||||
|
||||
We resolve this by using systemd **`LoadCredential`**:
|
||||
1. `sops-nix` decrypts the credentials file owned by `root:root` into `/run/secrets/`.
|
||||
2. The systemd service for `ddclient` is injected with:
|
||||
```nix
|
||||
LoadCredential = [ "ddclient.conf:${config.sops.templates."ddclient.conf".path}" ];
|
||||
```
|
||||
3. Systemd copies the file securely, adjusts permissions, and exposes it inside the service boundaries at:
|
||||
`/run/credentials/ddclient.service/ddclient.conf`
|
||||
4. `ddclient` reads the configuration from the credentials directory.
|
||||
|
||||
---
|
||||
|
||||
## ⏱️ Systemd Timers & Services Configuration
|
||||
|
||||
The updater is divided into two systemd units defined in [dynu.nix](file:///home/kiskaadee/Config/hosts/desktop/dynu.nix):
|
||||
|
||||
### 1. `dynu-monitor.timer`
|
||||
Runs every 30 minutes. It triggers the `dynu-monitor.service` which executes the Python script.
|
||||
|
||||
### 2. `ddclient.service` (On-Demand)
|
||||
The automatic `ddclient.timer` is disabled. The service is only triggered by the Python script using:
|
||||
```bash
|
||||
systemctl start ddclient.service
|
||||
```
|
||||
This ensures your host only makes outbound API calls to Dynu when a rotation actually occurs, maintaining zero overhead.
|
||||
@@ -8,6 +8,7 @@
|
||||
./hardware-configuration.nix # Desktop-specific disk and CPU configuration
|
||||
../../modules/system/graphical.nix # System-wide graphical stack settings (DMS daemon)
|
||||
../../modules/system/base.nix # General hardware-agnostic OS settings
|
||||
./dynu.nix # Dynu DDNS update service
|
||||
];
|
||||
|
||||
# Enable experimental Nix features (required for Flakes and newer command line tools)
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# 🌐 Dynu DDNS IP Monitor & Updater Service
|
||||
# This NixOS module configures a smart, local-first IP change detector.
|
||||
# It queries public IP providers, maintains a history log of WAN IP rotations,
|
||||
# and triggers ddclient only when an actual change is detected to prevent API rate limits.
|
||||
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
# Declaratively read the external Python script into the Nix store at evaluation time
|
||||
ipMonitorScript = pkgs.writers.writePython3Bin "dynu-ip-monitor" { } (builtins.readFile ./monitor.py);
|
||||
in
|
||||
{
|
||||
# 1. Load the encrypted secrets file
|
||||
sops.defaultSopsFile = ./secrets.yaml;
|
||||
sops.defaultSopsFormat = "yaml";
|
||||
|
||||
# Define the keys to decrypt
|
||||
sops.secrets.dynu_user = { };
|
||||
sops.secrets.dynu_domain = { };
|
||||
sops.secrets.dynu_password = { };
|
||||
|
||||
# Assemble the ddclient config file securely at boot time in /run/secrets/
|
||||
# Defaults to owner root:root (which avoids dynamic user evaluation issues)
|
||||
sops.templates."ddclient.conf" = {
|
||||
content = ''
|
||||
# General configuration
|
||||
daemon=0
|
||||
syslog=yes
|
||||
pid=/run/ddclient/ddclient.pid
|
||||
|
||||
# Provider definition using credentials decrypted at runtime
|
||||
protocol=dyndns2
|
||||
server=api.dynu.com
|
||||
login=${config.sops.placeholder.dynu_user}
|
||||
password=${config.sops.placeholder.dynu_password}
|
||||
${config.sops.placeholder.dynu_domain}
|
||||
'';
|
||||
};
|
||||
|
||||
# 2. Enable ddclient and feed it the decrypted configuration template via systemd credentials
|
||||
services.ddclient = {
|
||||
enable = true;
|
||||
configFile = "/run/credentials/ddclient.service/ddclient.conf";
|
||||
};
|
||||
|
||||
systemd.services.ddclient = {
|
||||
serviceConfig = {
|
||||
# Securely load the root-owned secret file into the dynamic ddclient service
|
||||
LoadCredential = [ "ddclient.conf:${config.sops.templates."ddclient.conf".path}" ];
|
||||
};
|
||||
};
|
||||
|
||||
# 3. Disable ddclient's automatic timer.
|
||||
# This stops ddclient from polling every 10 minutes on its own.
|
||||
systemd.timers.ddclient.enable = false;
|
||||
|
||||
# 4. Define the smart IP change detector service
|
||||
systemd.services.dynu-monitor = {
|
||||
description = "Dynu DDNS Smart IP Change Monitor";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
path = with pkgs; [
|
||||
systemd # Required for systemctl
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
User = "root";
|
||||
Group = "root";
|
||||
StateDirectory = "dynu";
|
||||
Environment = "HISTORY_FILE=/var/lib/dynu/ip_history.jsonl";
|
||||
ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor";
|
||||
TimeoutSec = 30;
|
||||
|
||||
# Hardening
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
ReadWritePaths = "/var/lib/dynu";
|
||||
};
|
||||
};
|
||||
|
||||
# 5. Run the smart IP change monitor periodically (every 30 minutes)
|
||||
systemd.timers.dynu-monitor = {
|
||||
description = "Run Dynu IP monitor periodically";
|
||||
timerConfig = {
|
||||
OnBootSec = "5min";
|
||||
OnUnitActiveSec = "30min";
|
||||
AccuracySec = "1min";
|
||||
Persistent = true;
|
||||
};
|
||||
wantedBy = [ "timers.target" ];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import urllib.request
|
||||
import re
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl")
|
||||
PROVIDERS = [
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://icanhazip.com",
|
||||
"https://wtfismyip.com/text"
|
||||
]
|
||||
|
||||
|
||||
def is_valid_public_ipv4(ip):
|
||||
match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip)
|
||||
if not match:
|
||||
return False
|
||||
octets = [int(x) for x in match.groups()]
|
||||
if any(x > 255 for x in octets):
|
||||
return False
|
||||
a, b, c, d = octets
|
||||
# Exclude private/reserved IP blocks
|
||||
if a == 10:
|
||||
return False
|
||||
if a == 192 and b == 168:
|
||||
return False
|
||||
if a == 172 and 16 <= b <= 31:
|
||||
return False
|
||||
if a == 100 and 64 <= b <= 127:
|
||||
return False
|
||||
if a == 127:
|
||||
return False
|
||||
if a == 169 and b == 254:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def get_public_ip():
|
||||
errors = []
|
||||
for provider in PROVIDERS:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
provider,
|
||||
headers={
|
||||
'User-Agent': 'Mozilla/5.0'
|
||||
}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=5) as response:
|
||||
ip = response.read().decode('utf-8').strip()
|
||||
if is_valid_public_ipv4(ip):
|
||||
return ip
|
||||
else:
|
||||
errors.append(f"{provider}: invalid public IPv4 '{ip}'")
|
||||
except Exception as e:
|
||||
errors.append(f"{provider}: {str(e)}")
|
||||
print(
|
||||
f"Error: All IP discovery providers failed. Details: {errors}",
|
||||
file=sys.stderr
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def get_last_recorded_ip():
|
||||
if not os.path.exists(HISTORY_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(HISTORY_FILE, "r") as f:
|
||||
lines = f.readlines()
|
||||
if not lines:
|
||||
return None
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
if entry.get("status") == "success":
|
||||
return entry.get("ip")
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
except Exception as e:
|
||||
print(f"Warning: Failed to read history file: {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def record_ip(ip, status, details=None):
|
||||
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
||||
entry = {
|
||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
||||
"ip": ip,
|
||||
"status": status
|
||||
}
|
||||
if details:
|
||||
entry["details"] = details
|
||||
try:
|
||||
with open(HISTORY_FILE, "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
except Exception as e:
|
||||
print(f"Error: Failed to write to history file: {e}", file=sys.stderr)
|
||||
|
||||
|
||||
def trigger_ddclient():
|
||||
try:
|
||||
res = subprocess.run(
|
||||
["systemctl", "start", "ddclient.service"],
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
if res.returncode == 0:
|
||||
return True, None
|
||||
else:
|
||||
err_msg = (
|
||||
f"systemctl exited with {res.returncode}: "
|
||||
f"{res.stderr.strip()}"
|
||||
)
|
||||
return False, err_msg
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
|
||||
def main():
|
||||
current_ip = get_public_ip()
|
||||
if not current_ip:
|
||||
sys.exit(1)
|
||||
|
||||
last_ip = get_last_recorded_ip()
|
||||
if current_ip == last_ip:
|
||||
# IP matches the last recorded working IP; do nothing
|
||||
sys.exit(0)
|
||||
|
||||
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}")
|
||||
|
||||
success, error_msg = trigger_ddclient()
|
||||
if success:
|
||||
print("Dynu DDNS update via ddclient triggered successfully.")
|
||||
record_ip(current_ip, "success")
|
||||
else:
|
||||
err_msg = f"Error: Failed to trigger ddclient update: {error_msg}"
|
||||
print(err_msg, file=sys.stderr)
|
||||
record_ip(current_ip, "failed_update", details=error_msg)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,27 @@
|
||||
dynu_user: ENC[AES256_GCM,data:45Yx9kgmS2RW,iv:IJwjbSbTHw5821zQOgqLDsRfc2YRatTLbzsQ4YnU9Vg=,tag:6pH93DJL0TuR6H0pcP7x3Q==,type:str]
|
||||
dynu_domain: ENC[AES256_GCM,data:ItWPMFnpgVrC41N0hbEp7aqcQ274i0um,iv:strJsDGpG1eiixYRZqiAedLbze3CY/6cAx3cVOoq9Ro=,tag:Gc8HKVmoJ5SJV/Le/POkPQ==,type:str]
|
||||
dynu_password: ENC[AES256_GCM,data:10WqwqKusUGWsOohRrqdguNrAdFaIBTqnBbdoM8N/J4=,iv:SvrPh/U375j8RBWOE21DR0jQM4TxfzNC/+YLDBNecmI=,tag:NOf4ecQ14gcr0kIFqCSgtQ==,type:str]
|
||||
sops:
|
||||
age:
|
||||
- enc: |
|
||||
-----BEGIN AGE ENCRYPTED FILE-----
|
||||
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBoWVhDOTNiUk9iU1lKb2VI
|
||||
Q0lhU3YwV1FyYnNhNis4dVVVUXF1Tm1LbEI0CmxOaC9YYVQ5Z0xqSVlqK0JlQnZO
|
||||
RzlMSjRHOVh0QTd4YXR1N0FiSDBzVlUKLS0tIDllcHpwMWI2SzBHZGgzQ2FkaFA2
|
||||
dUpCbnpkNjh4aSt4Y1YvQ29GRjNncFkK3n635jwBAtbfUuQacdUkB6B7otfi0hbs
|
||||
jZpvTSkH0BKnK34VAShu4VgMyBemm8qTrPwe/smM5d1eS10ahBPLjA==
|
||||
-----END AGE ENCRYPTED FILE-----
|
||||
recipient: age16nr2t9jrw09kakuxy2vtvtgtwa9jvy5dmtge25rzlqelf5cjy4es46alu9
|
||||
- enc: |
|
||||
-----BEGIN AGE ENCRYPTED FILE-----
|
||||
YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBOUWpmUUd0WTFnUXpQb256
|
||||
WjhGZDlqUEZPVmVUY25xYURhbkE4dmg1bUM0CnlDNkt0cDJlTkFqZzlRKzNuWWNX
|
||||
TUtFUi9KMm9rNXZ1M0xOdmsrNkRFbFkKLS0tIEFTNUVldlJ0d0ZrWVFWRDZyN2pP
|
||||
Zys1OGRaM1ducHVvcW1mU3lKakxaek0KUxJX0bwYtoWBrcpm9rS5OpGZYNMiuSRw
|
||||
zum5VbGK6dxeW7oV29lI0dZCGmeqTDy6SFggm/TEq6JL86Nw9ZXOIw==
|
||||
-----END AGE ENCRYPTED FILE-----
|
||||
recipient: age18q3lr2z4yeg2f86my42ym4hx0dvcwgjshmchyhdkgwvf4k37dsyq3mcjse
|
||||
lastmodified: "2026-06-24T02:48:44Z"
|
||||
mac: ENC[AES256_GCM,data:lvL22HDju2AIa5Kem6egroM5b4yriVQFvSFw3Z4lpZuvVCrBhlO97qKTgzEN6vNRjKefTyeiPayoGZSJxjo4lgVE13+E6XC1VUfP+UOC0khjmXJzkG3qbYDy5j0L8HC+DqoTqIZL7cbwxhqpogvDYy2xi/SUblVse3x3Yz5VH2w=,iv:xyDKpyojtbJ5nW39YkOhk00Gan3Ys1mnzjfVAWI0H0k=,tag:f5RANfznBuCVUt9NMOMyfA==,type:str]
|
||||
unencrypted_suffix: _unencrypted
|
||||
version: 3.13.1
|
||||
Reference in new issue
Block a user