Compare commits
3
Commits
47d059ee8d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e341ea6d8 | ||
|
|
49cded6122 | ||
|
|
90f3ca930c |
No files matched your search
+7
-2
@@ -44,7 +44,7 @@ services:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
environment:
|
||||
- DYNU_API_KEY=${DYNU_API_KEY}
|
||||
- CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN}
|
||||
- DOCKER_API_VERSION=${DOCKER_API_VERSION:-1.40}
|
||||
command:
|
||||
- "--log.level=INFO"
|
||||
@@ -61,7 +61,7 @@ services:
|
||||
- "--entrypoints.websecure.http.tls.domains[0].sans=*.${DOMAIN}"
|
||||
# SSL Setup
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge=true"
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=dynu"
|
||||
- "--certificatesresolvers.myresolver.acme.dnschallenge.provider=cloudflare"
|
||||
- "--certificatesresolvers.myresolver.acme.email=${ACME_EMAIL}"
|
||||
- "--certificatesresolvers.myresolver.acme.storage=/letsencrypt/acme.json"
|
||||
volumes:
|
||||
@@ -81,6 +81,11 @@ services:
|
||||
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
|
||||
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
|
||||
|
||||
# Middleware: Public Rate Limit (mitigates scraper/crawler bursts on public routes)
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.average=20"
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.burst=40"
|
||||
- "traefik.http.middlewares.public-ratelimit.ratelimit.period=1s"
|
||||
|
||||
# Dashboard - Public (HTTPS)
|
||||
- "traefik.http.routers.traefik-dash.rule=Host(`traefik.${DOMAIN}`)"
|
||||
- "traefik.http.routers.traefik-dash.entrypoints=websecure"
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
./hardware-configuration.nix # Server-specific disk and CPU configuration
|
||||
./modules/homeserver.nix # Core services: systemd units, Authelia, SOPS secrets
|
||||
./modules/traefik-deployments.nix # Traefik deployment secrets and env templates
|
||||
./modules/dynu.nix # Dynu DDNS smart IP monitor service
|
||||
./modules/shell.nix # Declarative bash environment for the server
|
||||
] ++ lib.optional (builtins.pathExists /etc/nixos/homelab-instance.nix) /etc/nixos/homelab-instance.nix
|
||||
++ lib.optional (!(builtins.pathExists /etc/nixos/homelab-instance.nix) && builtins.pathExists ./instance.nix) ./instance.nix;
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
# 🌐 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" {
|
||||
flakeIgnore = [ "E501" ];
|
||||
} (builtins.readFile ../scripts/monitor.py);
|
||||
in
|
||||
{
|
||||
# Define the keys to decrypt
|
||||
sops.secrets."dynu/user" = { };
|
||||
sops.secrets."dynu/domain" = { };
|
||||
sops.secrets."dynu/password" = { };
|
||||
sops.secrets."system/pdf_decrypt_password" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
};
|
||||
|
||||
# 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 = builtins.replaceStrings
|
||||
[ "@dynu_user@" "@dynu_password@" "@dynu_domain@" ]
|
||||
[
|
||||
config.sops.placeholder."dynu/user"
|
||||
config.sops.placeholder."dynu/password"
|
||||
config.sops.placeholder."dynu/domain"
|
||||
]
|
||||
(builtins.readFile ../scripts/ddclient.conf);
|
||||
};
|
||||
|
||||
# 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}" ];
|
||||
};
|
||||
};
|
||||
|
||||
# Disable ddclient's automatic timer.
|
||||
# This stops ddclient from polling every 10 minutes on its own.
|
||||
systemd.timers.ddclient.enable = false;
|
||||
|
||||
# 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";
|
||||
};
|
||||
};
|
||||
|
||||
# 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" ];
|
||||
};
|
||||
}
|
||||
@@ -110,7 +110,7 @@
|
||||
'';
|
||||
# Define the keys to decrypt from secrets.yaml
|
||||
sops.secrets = (lib.genAttrs [
|
||||
"dynu/api_key"
|
||||
"cloudflare/dns_api_token"
|
||||
"traefik/acme_email"
|
||||
"authelia/session_secret"
|
||||
"authelia/storage_encryption_key"
|
||||
@@ -145,7 +145,7 @@
|
||||
DOMAIN = config.homelab.domain;
|
||||
LLDAP_LDAP_BASE_DN = ldapBaseDn;
|
||||
DOCKER_API_VERSION = "1.40";
|
||||
DYNU_API_KEY = config.sops.placeholder."dynu/api_key";
|
||||
CF_DNS_API_TOKEN = config.sops.placeholder."cloudflare/dns_api_token";
|
||||
ACME_EMAIL = config.sops.placeholder."traefik/acme_email";
|
||||
AUTHELIA_SESSION_SECRET = config.sops.placeholder."authelia/session_secret";
|
||||
AUTHELIA_STORAGE_ENCRYPTION_KEY = config.sops.placeholder."authelia/storage_encryption_key";
|
||||
@@ -326,6 +326,8 @@
|
||||
"d ${config.homelab.coreDir}/config/stalwart/data 0777 ${config.homelab.operatorUser} users -"
|
||||
"d ${config.homelab.coreDir}/config/stalwart/etc 0777 ${config.homelab.operatorUser} users -"
|
||||
"d ${config.homelab.sitesDir} 0755 ${config.homelab.operatorUser} users -"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia - - - - d:u:1000:rwX,u:1000:rwx,m::rwx"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia/db.sqlite3 - - - - u:1000:rw,m::rw"
|
||||
"a+ ${config.homelab.coreDir}/config/authelia/emails.txt - - - - u:1000:rw,m::rw"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/gitops 0755 ${config.homelab.operatorUser} users -"
|
||||
"d /home/${config.homelab.operatorUser}/.local/state/homelab/docker 0755 ${config.homelab.operatorUser} users -"
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
# This replaces the laptop-inherited ~/.bashrc with a clean, server-appropriate profile.
|
||||
# Delivered via /etc/bashrc — no Home Manager required.
|
||||
|
||||
{ pkgs, ... }:
|
||||
{ config, pkgs, ... }:
|
||||
|
||||
{
|
||||
sops.secrets."system/pdf_decrypt_password" = {
|
||||
owner = config.homelab.operatorUser;
|
||||
};
|
||||
# ── Shell-integrated programs ─────────────────────────────────────────────────
|
||||
# These handle both installation and bash hook injection automatically
|
||||
programs.zoxide.enable = true; # smart cd with bash init wired into /etc/bashrc
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
# General configuration
|
||||
syslog=no
|
||||
pid=/run/ddclient/ddclient.pid
|
||||
cache=/var/lib/ddclient/ddclient.cache
|
||||
usev4=webv4
|
||||
|
||||
# Provider definition using credentials decrypted at runtime
|
||||
protocol=dyndns2
|
||||
server=api.dynu.com
|
||||
login=@dynu_user@
|
||||
password=@dynu_password@
|
||||
@dynu_domain@
|
||||
@@ -1,201 +0,0 @@
|
||||
"""
|
||||
Dynu DDNS Smart IP Change Monitor and Updater.
|
||||
|
||||
This script determines the current public IPv4 address by querying multiple
|
||||
external resolvers sequentially. It compares the discovered IP against the last
|
||||
recorded successful IP in a local history log. If a change is detected, it
|
||||
triggers the `ddclient.service` on-demand to perform the DNS record update.
|
||||
|
||||
This local-first state verification prevents making redundant API requests to
|
||||
the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
|
||||
# History file location storing the transition log of public IP states.
|
||||
# Defaults to a state directory managed securely by the systemd service unit.
|
||||
HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl")
|
||||
|
||||
# Fallback sequence of external services to discover the public WAN IP.
|
||||
PROVIDERS = [
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://icanhazip.com",
|
||||
"https://wtfismyip.com/text",
|
||||
]
|
||||
|
||||
|
||||
def is_valid_public_ipv4(ip):
|
||||
"""
|
||||
Validates that a string is a properly formatted public IPv4 address.
|
||||
|
||||
This function excludes standard private, loopback, link-local, and CGNAT
|
||||
blocks to avoid recording temporary, local, or invalid network states.
|
||||
"""
|
||||
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
|
||||
|
||||
# RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12
|
||||
if a == 10:
|
||||
return False
|
||||
if a == 192 and b == 168:
|
||||
return False
|
||||
if a == 172 and 16 <= b <= 31:
|
||||
return False
|
||||
|
||||
# Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10
|
||||
if a == 100 and 64 <= b <= 127:
|
||||
return False
|
||||
|
||||
# Loopback address range: 127.0.0.0/8
|
||||
if a == 127:
|
||||
return False
|
||||
|
||||
# Link-local addresses: 169.254.0.0/16
|
||||
return not (a == 169 and b == 254)
|
||||
|
||||
|
||||
def get_public_ip():
|
||||
"""
|
||||
Queries public IP providers until a valid public IPv4 is returned.
|
||||
|
||||
Returns:
|
||||
str: The validated public IP string, or None if all providers fail.
|
||||
"""
|
||||
errors = []
|
||||
for provider in PROVIDERS:
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
provider,
|
||||
headers={"User-Agent": "Mozilla/5.0 (NixOS WAN Monitor)"},
|
||||
)
|
||||
# Fetch with 5s timeout to avoid hanging the systemd service
|
||||
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 (urllib.error.URLError, OSError, ValueError) as e:
|
||||
errors.append(f"{provider}: {e!s}")
|
||||
|
||||
print(
|
||||
f"Error: All IP discovery providers failed. Details: {errors}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def get_last_recorded_ip():
|
||||
"""
|
||||
Reads the history log to locate the last successful IP address.
|
||||
|
||||
Returns:
|
||||
str: The last successfully updated IP, or None if no log exists yet.
|
||||
"""
|
||||
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
|
||||
# Search backwards to find the most recent successful transition
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
if entry.get("status") == "success":
|
||||
return entry.get("ip")
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
except OSError as e:
|
||||
print(f"Warning: Failed to read history file: {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def record_ip(ip, status, details=None):
|
||||
"""
|
||||
Appends a new event entry into the JSONLines history registry.
|
||||
"""
|
||||
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
|
||||
entry = {
|
||||
"timestamp": datetime.now(tz=UTC).isoformat(),
|
||||
"ip": ip,
|
||||
"status": status,
|
||||
}
|
||||
if details:
|
||||
entry["details"] = details
|
||||
try:
|
||||
with open(HISTORY_FILE, "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
except OSError as e:
|
||||
print(f"Error: Failed to write to history file: {e}", file=sys.stderr)
|
||||
|
||||
|
||||
def trigger_ddclient():
|
||||
"""
|
||||
Invokes the systemd service unit for `ddclient` on-demand.
|
||||
|
||||
Returns:
|
||||
tuple: (bool, str) representing (success_boolean, error_details_string)
|
||||
"""
|
||||
try:
|
||||
# Run ddclient as a one-shot activation via systemd to perform API call
|
||||
res = subprocess.run(
|
||||
["systemctl", "start", "ddclient.service"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if res.returncode == 0:
|
||||
return True, None
|
||||
else:
|
||||
err_msg = (
|
||||
f"systemctl exited with {res.returncode}: {res.stderr.strip()}"
|
||||
)
|
||||
return False, err_msg
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
return False, str(e)
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
Orchestrator logic for DDNS state management.
|
||||
"""
|
||||
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 last recorded working IP; do nothing to conserve quota
|
||||
sys.exit(0)
|
||||
|
||||
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}")
|
||||
|
||||
# Trigger ddclient to perform the DNS record update
|
||||
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()
|
||||
+7
-2
@@ -38,6 +38,11 @@ lldap:
|
||||
brevo:
|
||||
smtp_login: ENC[AES256_GCM,data:zfqKsAtoAOWCrSqx38sknwcJZT2m8W2J,iv:tMwTNDf+2CE3/8rKqWTWLl5Zp4LUVNSFV90QN94VXxo=,tag:XYXz9w3oIa0qkcfjCcgcYg==,type:str]
|
||||
smtp_key: ENC[AES256_GCM,data:YulXyaVF/sLWE9x12yxdBAj9KMbfP/CK/7FS3XkYO8sCj3GWgPbNoSaUT/9quLWHPtCsBxxdLeLoDNa1jE2WRyHP1W+Ioyyx5sAzdzevzHIBmfP+fdw0rKhe,iv:QT0HfzNPsTqXlN3IC/+bBzJfUzN9YkXYiv/3uqkXHBw=,tag:vBetkZPDYoh0Yy3BpMT9BQ==,type:str]
|
||||
cloudflare:
|
||||
account_name: ENC[AES256_GCM,data:fIuzvJbLoz/w,iv:tT3rCldA9hqHzKjJa4gENTk/XprzS5X6Wm/rqkb6jow=,tag:p0aEezfUFlJn25PdW/DAOA==,type:str]
|
||||
global_api_key: ENC[AES256_GCM,data:IDFHetxM2LE1/cytHo2Jn16piLeIvM27ui3Qld4Z5hwWauDRaY05nZH6+V6ic9dYFfagvA==,iv:9q3cosnJ+eC1BLmQ1Hx1y3Dksyc5k4UMQPZ6Or9vWFE=,tag:k/RilX02EJzMWZcfzBtu4A==,type:str]
|
||||
account_id: ENC[AES256_GCM,data:/IyUXySFGQSGs16Kv6yZajMiGTxwOuxILvcFZ/6YROo=,iv:TdMwtzs/LMnbhpsEbqunj4n+P+JxcscYGKaM42fYQ20=,tag:HHmIq03Jc4g8fBvuaWevAA==,type:str]
|
||||
dns_api_token: ENC[AES256_GCM,data:lTByYg0BM+mloaHDb2WkN7LY9twnVzKn6NO8W1rTH5FXyWaNlEovLxCPT2sG+JuRfqGJ52w=,iv:nBX3rUSdf1wFSTz0sY/ApNKVaYkCPJAJPhmMu+abzhE=,tag:LK8qyYap/T1HZb+jWnHyuA==,type:str]
|
||||
appctl:
|
||||
tokens_json: ENC[AES256_GCM,data:O2vsiMMcZjsduFSRen1MnnckdRYK45aPH40EhX42h1WUwf62Nm58PV5BQJOgJ97AH3hOH97mzg1tjL0C1oV/epXMaypRWY9AGLS00CfzD2sgdM5Wx7VKbfGggFnGqgd7veaCA+pxUC0uTk/Dq2Cz/uhXhLX1wVjafX0OAqS6fxO+L9Oza3+RBtKgx2xX0AKW+KSZQUM1nvNW8R/Eyvnqvw2OSb2FdKN1CKhlVWhCZiaxTe8617BqGhJDL9pu4lfn0m+tdIwvluI3h8cmKuT6dzd01Jxr0EHBY/+mZZ/WQoNhIy4QulFpKiMudiT+WGzUm+UT4mYBoGwzQCVV8MD7W1r84mkbCkLc/HpWG08TqK4tpAdtLgYK3Zslr1+lmboWyJ6WcinmxkhUexhj+gTyfXYmVSB3fF8PIeyQINGB3rLvmpZ7DDMzYa1ICgFbJ6zmYa54TXRDLGzLD09koeDp9FhXNKPvuwz2x4uwWDDUfU8wwTkGbw==,iv:FJpB+WZiE4PKUhIuwBWIB/TLtifwCzGRMtbMx7x6ly8=,tag:NZQXYFnVBqbOONl+Yh3tuA==,type:str]
|
||||
sops:
|
||||
@@ -60,7 +65,7 @@ sops:
|
||||
yvBksdjSVYITIR6E6sZJx4ujk8Gmu64UsHwxtASMZRQ60sUjLCo8+A==
|
||||
-----END AGE ENCRYPTED FILE-----
|
||||
recipient: age1pln9sxy5j93lklqklfwp3qepx7x4cs4y2w63n9y3ykt68qgra5ysqleesg
|
||||
lastmodified: "2026-10-19T20:40:13Z"
|
||||
mac: ENC[AES256_GCM,data:rui8qF/l3ucq8vrZniHtGjlLGPq7ihteKK7rcaz2prRvmo7nHd97Axt7oElo050HFuoaJB1/coVPzYcAUozjZNsNx3TQYABGFWvxF5Y0SxjdLc1rqAjGR/j2Cf5wmvF9H457KBHfij2gQHY/ZZ2Nyd9aEpAKSFtKkn3aYkmTvW4=,iv:RdQWUpkahFEYEhd9kTpPG0GMJaHr7b+wbhf5MBhk6mo=,tag:1E3mcFk/EMnJNNxuZ6AXAw==,type:str]
|
||||
lastmodified: "2026-11-23T20:45:18Z"
|
||||
mac: ENC[AES256_GCM,data:3Rm8olJtCErH+KGisvQENqwFhMF3Y9acXjrBHC7ot3ThRzT8Yo3X1RyxKXzyYzB6Yy2G3ua9yUtgQjydXgjQR1b6KY6ERmyu6H2S1IF/Ps4grYVZ6xEhJMDtjNKDvhtjhRM61eFByeYzJeHWD6K8dsxDcWUI2GKRRH7U8iG95Fo=,iv:/IY6iKamEEoi5vVLRGOmmPpyJte3amLfjVhYIDbMdBE=,tag:gT3RSrnwl0TH14LJvbiPlg==,type:str]
|
||||
unencrypted_suffix: _unencrypted
|
||||
version: 3.13.3
|
||||
Reference in new issue
Block a user