Files
Strato-MCP/strato_client.py
T

729 lines
29 KiB
Python

#!/usr/bin/env python3
"""Small HTTP client for STRATO's customer portal.
STRATO does not publish a DNS-zone API for ordinary hosted domains. This
client implements the minimum path proven by the public certbot-dns-strato
project: authenticate, resolve the package that owns one configured DNS zone,
read its combined TXT/CNAME form, and replace that form after a narrowly scoped
change. Every write re-sends all other form controls unchanged, runs under a
process-wide lock and is followed by a fresh read for verification.
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import os
import re
import struct
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from html.parser import HTMLParser
from http.cookiejar import CookieJar
from typing import Callable, Iterable
STRATO_URL = "https://www.strato.de/apps/CustomerService"
MAX_RESPONSE_BYTES = 5 * 1024 * 1024
USER_AGENT = "Mozilla/5.0 (compatible; strato-dns-mcp/0.3)"
SESSION_TTL_SECONDS = 600
RECORD_TYPES = ("CNAME", "TXT")
_RECORD_FIELDS = {"prefix", "type", "value", "action_change_txt_records"}
_REQUEST_FIELDS = {"sessionID", "cID", "node", "vhost"}
_WRITE_LOCK = threading.Lock()
class StratoError(RuntimeError):
"""Short credential-free error suitable for an MCP response."""
class StratoAuthenticationError(StratoError):
pass
class StratoParseError(StratoError):
pass
class StratoWriteDisabledError(StratoError):
pass
@dataclass(frozen=True)
class StratoConfig:
username: str
password: str
domain: str
package_id: str | None = None
totp_secret: str | None = None
totp_device: str | None = None
timeout_seconds: float = 20.0
write_enabled: bool = False
@classmethod
def from_env(cls) -> "StratoConfig":
values = {
"username": os.environ.get("STRATO_USERNAME", "").strip(),
"password": os.environ.get("STRATO_PASSWORD", ""),
"domain": os.environ.get("STRATO_DOMAIN", "").strip().rstrip("."),
}
missing = [name.upper() for name, value in values.items() if not value]
if missing:
raise StratoError(
"Missing configuration: " + ", ".join(f"STRATO_{name}" for name in missing)
)
domain = values["domain"].encode("idna").decode("ascii").lower()
if not re.fullmatch(r"(?=.{1,253}$)[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?", domain):
raise StratoError("STRATO_DOMAIN is not a valid DNS zone name")
return cls(
username=values["username"],
password=values["password"],
domain=domain,
package_id=os.environ.get("STRATO_PACKAGE_ID", "").strip() or None,
totp_secret=os.environ.get("STRATO_TOTP_SECRET", "").strip() or None,
totp_device=os.environ.get("STRATO_TOTP_DEVICE", "").strip() or None,
timeout_seconds=float(os.environ.get("STRATO_TIMEOUT_SECONDS", "20")),
write_enabled=os.environ.get("STRATO_WRITE_ENABLED", "false").strip().lower()
in {"1", "true", "yes", "on"},
)
@dataclass(frozen=True)
class DnsRecord:
type: str
prefix: str
value: str
def as_dict(self) -> dict[str, str]:
result = {"type": self.type, "prefix": self.prefix, "value": self.value}
readable = _unicode_name(self.prefix)
if readable != self.prefix:
result["prefix_unicode"] = readable
return result
@dataclass(frozen=True)
class DnsForm:
records: tuple[DnsRecord, ...]
submit_value: str
# Every other control of the DNS form (hidden fields, checked radios, selects),
# re-sent unchanged so a record change never resets unrelated settings.
extra_fields: tuple[tuple[str, str], ...] = ()
def _unicode_name(name: str) -> str:
try:
return ".".join(
label.encode("ascii").decode("idna") if label.startswith("xn--") else label
for label in name.split(".")
)
except UnicodeError:
return name
class _FormParser(HTMLParser):
"""Extract parallel type/prefix/value fields and all other controls of the form
that contains STRATO's DNS submit button."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.prefixes: list[str] = []
self.types: list[str] = []
self.values: list[str] = []
self._in_type_select = False
self._in_value_textarea = False
self._textarea_parts: list[str] = []
self.submit_value: str | None = None
# extra controls per <form>; index 0 collects controls outside any form
self._forms: list[list[tuple[str, str]]] = [[]]
self._form_stack: list[int] = []
self._target_form: int | None = None
self._extra_select: str | None = None
self._extra_select_value: str | None = None
self._extra_select_first: str | None = None
self._extra_textarea: str | None = None
def _current(self) -> list[tuple[str, str]]:
return self._forms[self._form_stack[-1]] if self._form_stack else self._forms[0]
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
data = dict(attrs)
name = data.get("name") or ""
if tag == "form":
self._forms.append([])
self._form_stack.append(len(self._forms) - 1)
elif tag == "input" and name == "prefix":
self.prefixes.append(data.get("value") or "")
elif tag == "input" and name == "action_change_txt_records":
self.submit_value = data.get("value") or ""
self._target_form = self._form_stack[-1] if self._form_stack else 0
elif tag == "select" and name == "type":
self._in_type_select = True
elif tag == "option" and self._in_type_select:
if "selected" in data:
self.types.append(data.get("value") or "")
elif tag == "textarea" and name == "value":
self._in_value_textarea = True
self._textarea_parts = []
elif name and name not in _RECORD_FIELDS:
self._extra_start(tag, name, data)
elif tag == "option" and self._extra_select is not None:
value = data.get("value") or ""
if self._extra_select_first is None:
self._extra_select_first = value
if "selected" in data:
self._extra_select_value = value
def _extra_start(self, tag: str, name: str, data: dict[str, str | None]) -> None:
if tag == "input":
kind = (data.get("type") or "text").lower()
if kind in ("submit", "button", "image", "reset", "file"):
return
if kind in ("radio", "checkbox") and "checked" not in data:
return
self._current().append((name, data.get("value") or ("on" if kind == "checkbox" else "")))
elif tag == "select":
self._extra_select = name
self._extra_select_value = None
self._extra_select_first = None
elif tag == "textarea":
self._extra_textarea = name
self._textarea_parts = []
def handle_endtag(self, tag: str) -> None:
if tag == "form" and self._form_stack:
self._form_stack.pop()
elif tag == "select":
if self._in_type_select:
self._in_type_select = False
elif self._extra_select is not None:
value = self._extra_select_value if self._extra_select_value is not None else self._extra_select_first
if value is not None:
self._current().append((self._extra_select, value))
self._extra_select = None
elif tag == "textarea":
if self._in_value_textarea:
self.values.append("".join(self._textarea_parts))
self._in_value_textarea = False
elif self._extra_textarea is not None:
self._current().append((self._extra_textarea, "".join(self._textarea_parts)))
self._extra_textarea = None
def handle_data(self, data: str) -> None:
if self._in_value_textarea or self._extra_textarea is not None:
self._textarea_parts.append(data)
def extra_fields(self) -> tuple[tuple[str, str], ...]:
if self._target_form is None:
return ()
return tuple(
(name, value) for name, value in self._forms[self._target_form]
if name not in _REQUEST_FIELDS
)
class _PackageParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.rows: list[tuple[str, list[str]]] = []
self._depth = 0
self._text: list[str] = []
self._links: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "tr":
if self._depth == 0:
self._text, self._links = [], []
self._depth += 1
if self._depth and tag == "a":
href = dict(attrs).get("href")
if href:
self._links.append(href)
def handle_endtag(self, tag: str) -> None:
if tag == "tr" and self._depth:
self._depth -= 1
if self._depth == 0:
self.rows.append((" ".join(self._text), list(self._links)))
def handle_data(self, data: str) -> None:
if self._depth and data.strip():
self._text.append(data.strip())
def _totp(secret: str, at_time: int | None = None) -> str:
"""Generate a standard six-digit SHA-1 TOTP without third-party modules."""
normalized = re.sub(r"\s+", "", secret).upper()
try:
key = base64.b32decode(normalized + "=" * ((8 - len(normalized) % 8) % 8))
except Exception as exc:
raise StratoAuthenticationError("STRATO_TOTP_SECRET is not valid base32") from exc
counter = int((at_time if at_time is not None else time.time()) // 30)
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = digest[-1] & 0x0F
number = struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF
return f"{number % 1_000_000:06d}"
def parse_dns_form(html: str) -> DnsForm:
parser = _FormParser()
parser.feed(html)
counts = (len(parser.types), len(parser.prefixes), len(parser.values))
if len(set(counts)) != 1:
raise StratoParseError(
"STRATO DNS form changed: type/prefix/value field counts do not match"
)
if not parser.submit_value:
raise StratoParseError("STRATO DNS form changed: submit action is missing")
records = tuple(DnsRecord(t.upper(), p.strip(), v.strip()) for t, p, v in zip(
parser.types, parser.prefixes, parser.values, strict=True
))
return DnsForm(
records=records,
submit_value=parser.submit_value,
extra_fields=parser.extra_fields(),
)
def parse_records(html: str) -> list[DnsRecord]:
"""Compatibility helper for callers that only need the record list."""
return list(parse_dns_form(html).records)
def normalize_cname_prefix(prefix: str, zone: str) -> str:
value = prefix.strip().rstrip(".").lower()
zone = zone.lower().rstrip(".")
if value.endswith("." + zone):
value = value[: -(len(zone) + 1)]
if not value or value == "@":
raise StratoError("CNAME prefix must name a subdomain, not the zone apex")
labels = value.split(".")
for index, label in enumerate(labels):
if label == "*":
if index != 0:
raise StratoError("A wildcard is allowed only in the first DNS label")
continue
ascii_label = label.encode("idna").decode("ascii")
if not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", ascii_label):
raise StratoError("CNAME prefix is not a valid relative DNS name")
return ".".join(label.encode("idna").decode("ascii") for label in labels)
def normalize_cname_target(target: str) -> str:
value = target.strip().rstrip(".").lower()
if not value or "://" in value or "/" in value:
raise StratoError("CNAME target must be a DNS name without scheme or path")
try:
ascii_value = value.encode("idna").decode("ascii")
except UnicodeError as exc:
raise StratoError("CNAME target is not a valid DNS name") from exc
if not re.fullmatch(
r"(?=.{1,253}$)[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?", ascii_value
) or any(not label or len(label) > 63 for label in ascii_value.split(".")):
raise StratoError("CNAME target is not a valid DNS name")
return ascii_value
def normalize_txt_prefix(prefix: str, zone: str) -> str:
"""TXT names may contain underscores (_acme-challenge, _dmarc, selector._domainkey)."""
value = prefix.strip().rstrip(".").lower()
zone = zone.lower().rstrip(".")
if value.endswith("." + zone):
value = value[: -(len(zone) + 1)]
if not value or value == "@" or value == zone:
raise StratoError(
"TXT records at the zone apex (e.g. SPF) are managed in the STRATO web UI, not here"
)
labels = value.split(".")
for label in labels:
ascii_label = label.encode("idna").decode("ascii") if not label.startswith("_") else label
if not re.fullmatch(r"_?[a-z0-9](?:[a-z0-9_-]{0,61}[a-z0-9])?|_[a-z0-9]", ascii_label):
raise StratoError("TXT prefix is not a valid relative DNS name")
return ".".join(
label if label.startswith("_") else label.encode("idna").decode("ascii") for label in labels
)
def normalize_txt_value(value: str) -> str:
cleaned = value.strip()
if not cleaned:
raise StratoError("TXT value must not be empty")
if "\n" in cleaned or "\r" in cleaned:
raise StratoError("TXT value must be a single line")
if len(cleaned) > 4000:
raise StratoError("TXT value is too long (max 4000 characters)")
return cleaned
def normalize_prefix(record_type: str, prefix: str, zone: str) -> str:
if record_type == "CNAME":
return normalize_cname_prefix(prefix, zone)
if record_type == "TXT":
return normalize_txt_prefix(prefix, zone)
raise StratoError(f"record_type must be one of {', '.join(RECORD_TYPES)}")
def normalize_value(record_type: str, value: str) -> str:
return normalize_cname_target(value) if record_type == "CNAME" else normalize_txt_value(value)
def _same_value(record_type: str, a: str, b: str) -> bool:
if record_type == "CNAME":
try:
return normalize_cname_target(a) == normalize_cname_target(b)
except StratoError:
return False
return a.strip() == b.strip()
@dataclass(frozen=True)
class ChangePlan:
"""A fully resolved record change against one exact zone state."""
action: str
record_type: str
before: DnsRecord | None
after: DnsRecord | None
records: tuple[DnsRecord, ...]
zone_state: str
preserved_fields: tuple[str, ...] = ()
def fingerprint(self) -> str:
return "|".join([
self.action,
self.zone_state,
repr(self.before.as_dict() if self.before else None),
repr(self.after.as_dict() if self.after else None),
])
def _zone_state(form: DnsForm) -> str:
material = "\n".join(f"{r.type}\t{r.prefix}\t{r.value}" for r in form.records)
return hashlib.sha256(material.encode()).hexdigest()[:16]
def parse_package_id(html: str, domain: str) -> str:
parser = _PackageParser()
parser.feed(html)
for text, links in parser.rows:
if domain.lower() not in text.lower():
continue
for link in links:
package = urllib.parse.parse_qs(urllib.parse.urlparse(link).query).get("cID")
if package and package[0].isdigit():
return package[0]
raise StratoParseError(f"Configured domain {domain} was not found in STRATO packages")
class StratoClient:
def __init__(
self,
config: StratoConfig,
*,
opener: object | None = None,
sleep: Callable[[float], None] = time.sleep,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.config = config
self.opener = opener or urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(CookieJar())
)
self.sleep = sleep
self.clock = clock
self.session_id: str | None = None
self.session_started: float | None = None
self.package_id: str | None = config.package_id
# one client is shared by concurrent tool calls: serialize login + reads
self._session_lock = threading.RLock()
def _request(
self,
method: str,
*,
params: dict[str, object] | None = None,
form: dict[str, object] | list[tuple[str, object]] | None = None,
) -> tuple[str, str]:
url = STRATO_URL
if params:
url += "?" + urllib.parse.urlencode(params, doseq=True)
body = urllib.parse.urlencode(form, doseq=True).encode() if form is not None else None
request = urllib.request.Request(
url,
data=body,
method=method,
headers={"User-Agent": USER_AGENT, "Accept": "text/html,application/xhtml+xml"},
)
try:
response = self.opener.open(request, timeout=self.config.timeout_seconds)
raw = response.read(MAX_RESPONSE_BYTES + 1)
except urllib.error.HTTPError as exc:
raise StratoError(f"STRATO returned HTTP {exc.code}") from None
except (urllib.error.URLError, TimeoutError, OSError):
raise StratoError("STRATO could not be reached") from None
if len(raw) > MAX_RESPONSE_BYTES:
raise StratoError("STRATO response exceeded the size limit")
return response.geturl(), raw.decode("utf-8", errors="replace")
def login(self) -> None:
self.session_id = None
self._request("GET")
self.sleep(1.0)
url, html = self._request(
"POST",
form={
"identifier": self.config.username,
"passwd": self.config.password,
"action_customer_login.x": "Login",
},
)
if re.search(r"Zwei.Faktor.Authentifizierung", html, flags=re.IGNORECASE):
if not self.config.totp_secret or not self.config.totp_device:
raise StratoAuthenticationError(
"STRATO requested 2FA; configure STRATO_TOTP_SECRET and STRATO_TOTP_DEVICE"
)
token = re.search(r'name=["\']totp_token["\'][^>]*value=["\']([^"\']+)', html)
device = re.search(
rf'<option\s+value=["\'](S\.{re.escape(self.config.username)}\.\w+)["\'][^>]*>'
rf'\s*{re.escape(self.config.totp_device)}\s*</option>',
html,
flags=re.IGNORECASE,
)
if not token or not device:
raise StratoParseError("STRATO 2FA form could not be understood")
self.sleep(1.0)
url, html = self._request(
"POST",
form={
"identifier": self.config.username,
"totp_token": token.group(1),
"pw_id": device.group(1),
"totp": _totp(self.config.totp_secret),
"action_customer_login.x": 1,
},
)
session = urllib.parse.parse_qs(urllib.parse.urlparse(url).query).get("sessionID")
if not session:
raise StratoAuthenticationError("STRATO login was not accepted")
self.session_id = session[0]
self.session_started = self.clock()
def _session_fresh(self) -> bool:
if not self.session_id:
return False
if self.session_started is None: # injected by tests / callers
return True
return self.clock() - self.session_started < SESSION_TTL_SECONDS
def resolve_package(self) -> str:
if self.package_id:
return self.package_id
if not self.session_id:
raise StratoAuthenticationError("STRATO session is not initialized")
_, html = self._request(
"GET",
params={"sessionID": self.session_id, "cID": 0, "node": "kds_CustomerEntryPage"},
)
self.package_id = parse_package_id(html, self.config.domain)
return self.package_id
def list_txt_and_cname_records(self) -> list[DnsRecord]:
return list(self._get_dns_form().records)
def _fetch_dns_form(self) -> DnsForm:
package_id = self.resolve_package()
_, html = self._request(
"GET",
params={
"sessionID": self.session_id or "",
"cID": package_id,
"node": "ManageDomains",
"action_show_txt_records": "",
"vhost": self.config.domain,
},
)
return parse_dns_form(html)
def _get_dns_form(self) -> DnsForm:
"""Read the DNS form, reusing a recent session and re-logging in once if it expired."""
with self._session_lock:
reused = self._session_fresh()
if not reused:
self.login()
try:
return self._fetch_dns_form()
except (StratoParseError, StratoAuthenticationError):
if not reused:
raise
self.login()
return self._fetch_dns_form()
def list_cnames(self) -> list[DnsRecord]:
return [record for record in self.list_txt_and_cname_records() if record.type == "CNAME"]
def _require_writes(self) -> None:
if not self.config.write_enabled:
raise StratoWriteDisabledError(
"DNS writes are disabled; set STRATO_WRITE_ENABLED=true to enable them"
)
def _push_records(self, form: DnsForm, records: list[DnsRecord]) -> None:
self._require_writes()
package_id = self.resolve_package()
fields: list[tuple[str, object]] = [
("sessionID", self.session_id or ""),
("cID", package_id),
("node", "ManageDomains"),
("vhost", self.config.domain),
*form.extra_fields,
]
for record in records:
fields += [("prefix", record.prefix), ("type", record.type), ("value", record.value)]
fields.append(("action_change_txt_records", form.submit_value))
self._request("POST", form=fields)
@staticmethod
def _at(records: Iterable[DnsRecord], record_type: str, prefix: str) -> list[DnsRecord]:
return [
record for record in records
if record.type == record_type and record.prefix.lower() == prefix.lower()
]
@staticmethod
def _cname_at(records: Iterable[DnsRecord], prefix: str) -> list[DnsRecord]:
return StratoClient._at(records, "CNAME", prefix)
# ------------------------------------------------------------------ planning
def plan(
self,
action: str,
record_type: str,
prefix: str,
value: str | None = None,
*,
new_prefix: str | None = None,
old_value: str | None = None,
form: DnsForm | None = None,
) -> ChangePlan:
"""Resolve a create/update/delete against the current zone without writing."""
record_type = record_type.strip().upper()
if record_type not in RECORD_TYPES:
raise StratoError(f"record_type must be one of {', '.join(RECORD_TYPES)}")
if action not in ("create", "update", "delete"):
raise StratoError("action must be create, update or delete")
name = normalize_prefix(record_type, prefix, self.config.domain)
form = form or self._get_dns_form()
records = list(form.records)
state = _zone_state(form)
extras = tuple(dict.fromkeys(name for name, _ in form.extra_fields))
def find_one() -> DnsRecord:
matches = self._at(records, record_type, name)
if record_type == "TXT" and old_value is not None:
matches = [r for r in matches if _same_value("TXT", r.value, old_value)]
if len(matches) != 1:
hint = " (pass old_value to pick one TXT record)" if record_type == "TXT" and len(matches) > 1 else ""
raise StratoError(f"Exactly one existing {record_type} with this prefix is required{hint}")
return matches[0]
if action == "create":
if value is None:
raise StratoError("value is required to create a record")
new_value = normalize_value(record_type, value)
same_name = [r for r in records if r.prefix.lower() == name.lower()]
if record_type == "CNAME" and same_name:
raise StratoError("A DNS record with this prefix already exists")
if record_type == "TXT":
if any(r.type == "CNAME" for r in same_name):
raise StratoError("A CNAME already exists at this prefix; DNS forbids other records there")
if any(r.type == "TXT" and _same_value("TXT", r.value, new_value) for r in same_name):
raise StratoError("This exact TXT record already exists")
created = DnsRecord(record_type, name, new_value)
return ChangePlan("create", record_type, None, created, tuple([*records, created]), state, extras)
current = find_one()
if action == "delete":
remaining = tuple(r for r in records if r is not current)
return ChangePlan("delete", record_type, current, None, remaining, state, extras)
destination = normalize_prefix(record_type, new_prefix, self.config.domain) if new_prefix else name
new_value = normalize_value(record_type, value) if value is not None else current.value
if destination.lower() != name.lower():
others = [r for r in records if r.prefix.lower() == destination.lower()]
if record_type == "CNAME" and others:
raise StratoError("A DNS record with the new prefix already exists")
if record_type == "TXT" and any(r.type == "CNAME" for r in others):
raise StratoError("A CNAME already exists at the new prefix")
replacement = DnsRecord(record_type, destination, new_value)
if replacement == current:
raise StratoError("The update would not change anything")
updated = tuple(replacement if r is current else r for r in records)
return ChangePlan("update", record_type, current, replacement, updated, state, extras)
def apply(self, plan: ChangePlan) -> ChangePlan:
"""Write a previewed plan if the zone still matches it, then verify."""
def unchanged(form: DnsForm) -> ChangePlan:
if _zone_state(form) != plan.zone_state:
raise StratoError(
"The DNS zone changed since the preview; preview again before applying"
)
return plan
return self._execute(unchanged)
def _execute(self, build: Callable[[DnsForm], ChangePlan]) -> ChangePlan:
"""Read, plan, write and verify as one locked read-modify-write cycle."""
self._require_writes()
with _WRITE_LOCK:
form = self._get_dns_form()
plan = build(form)
self._push_records(form, list(plan.records))
verified = self._get_dns_form().records
return self._verify(plan, verified)
def _verify(self, plan: ChangePlan, verified: Iterable[DnsRecord]) -> ChangePlan:
verified = list(verified)
def present(record: DnsRecord) -> list[DnsRecord]:
return [
r for r in self._at(verified, record.type, record.prefix)
if _same_value(record.type, r.value, record.value)
]
if plan.after is not None:
found = present(plan.after)
if len(found) != 1:
raise StratoError(f"STRATO did not persist the {plan.record_type} {plan.action}")
plan = ChangePlan(plan.action, plan.record_type, plan.before, found[0], plan.records, plan.zone_state, plan.preserved_fields)
# update and delete always change the old record, so it must be gone now
if plan.before is not None and present(plan.before):
raise StratoError(f"STRATO did not remove the old {plan.record_type} record")
return plan
# ------------------------------------------------------------- convenience
def create_cname(self, prefix: str, target: str) -> DnsRecord:
result = self._execute(lambda form: self.plan("create", "CNAME", prefix, target, form=form))
assert result.after is not None
return result.after
def update_cname(
self, prefix: str, target: str, *, new_prefix: str | None = None
) -> tuple[DnsRecord, DnsRecord]:
result = self._execute(
lambda form: self.plan("update", "CNAME", prefix, target, new_prefix=new_prefix, form=form)
)
assert result.before is not None and result.after is not None
return result.before, result.after
def delete_cname(self, prefix: str) -> DnsRecord:
result = self._execute(lambda form: self.plan("delete", "CNAME", prefix, form=form))
assert result.before is not None
return result.before