149 lines
4.8 KiB
Python
149 lines
4.8 KiB
Python
"""Arvan DNS helpers for a Certbot DNS-01 check.
|
|
|
|
Certbot sets CERTBOT_DOMAIN and CERTBOT_VALIDATION. The API key is one line
|
|
in /etc/letsencrypt/arvan-api-key and is never printed.
|
|
|
|
nudentic.ir is its own zone, so the TXT name is _acme-challenge.
|
|
A name under wixur.ir uses that zone: gitea.wixur.ir becomes
|
|
_acme-challenge.gitea in zone wixur.ir.
|
|
"""
|
|
import json
|
|
import os
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
KEY_PATH = "/etc/letsencrypt/arvan-api-key"
|
|
API = "https://napi.arvancloud.ir/cdn/4.0/domains"
|
|
|
|
|
|
def auth_header():
|
|
raw = open(KEY_PATH, encoding="utf-8").read().strip()
|
|
if raw.lower().startswith("apikey "):
|
|
return "Apikey " + raw.split(None, 1)[1]
|
|
return "Apikey " + raw
|
|
|
|
|
|
def request(method, url, body=None):
|
|
data = None if body is None else json.dumps(body).encode()
|
|
headers = {"Authorization": auth_header(), "Accept": "application/json"}
|
|
if body is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
req = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
return resp.status, resp.read().decode()
|
|
except urllib.error.HTTPError as err:
|
|
return err.code, err.read().decode()
|
|
|
|
|
|
def zone_and_record(domain):
|
|
domain = domain.strip().rstrip(".")
|
|
override = os.environ.get("ARVAN_ZONE", "").strip().rstrip(".")
|
|
labels = domain.split(".")
|
|
if override:
|
|
zone = override
|
|
elif len(labels) > 2:
|
|
zone = ".".join(labels[-2:])
|
|
else:
|
|
zone = domain
|
|
if domain == zone:
|
|
name = "_acme-challenge"
|
|
elif domain.endswith("." + zone):
|
|
prefix = domain[: -(len(zone) + 1)]
|
|
name = "_acme-challenge." + prefix
|
|
else:
|
|
raise SystemExit("CERTBOT_DOMAIN is not in the Arvan zone")
|
|
fqdn = name + "." + zone
|
|
return zone, name, fqdn
|
|
|
|
|
|
def record_names_match(got, name, fqdn):
|
|
if not isinstance(got, str):
|
|
return False
|
|
got = got.strip().rstrip(".").lower()
|
|
return got in (name.lower(), fqdn.lower())
|
|
|
|
|
|
def walk(node):
|
|
if isinstance(node, list):
|
|
for item in node:
|
|
yield from walk(item)
|
|
elif isinstance(node, dict):
|
|
if "id" in node and "type" in node:
|
|
yield node
|
|
for value in node.values():
|
|
yield from walk(value)
|
|
|
|
|
|
def txt_text(record):
|
|
raw_value = record.get("value")
|
|
if isinstance(raw_value, dict):
|
|
return str(raw_value.get("text", ""))
|
|
if isinstance(raw_value, str):
|
|
return raw_value
|
|
return ""
|
|
|
|
|
|
def list_txt(zone):
|
|
status, body = request(
|
|
"GET", "{}/{}/dns-records?per_page=100&type=txt".format(API, zone)
|
|
)
|
|
if status < 200 or status >= 300:
|
|
raise SystemExit("Arvan DNS list failed: HTTP {}".format(status))
|
|
return list(walk(json.loads(body)))
|
|
|
|
|
|
def delete_record(zone, record_id):
|
|
status, _body = request(
|
|
"DELETE", "{}/{}/dns-records/{}".format(API, zone, record_id)
|
|
)
|
|
if status not in (200, 204, 404):
|
|
raise SystemExit("Arvan DNS delete failed: HTTP {}".format(status))
|
|
|
|
|
|
def upsert_txt(zone, name, value):
|
|
status, body = request(
|
|
"POST",
|
|
"{}/{}/dns-records".format(API, zone),
|
|
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
|
)
|
|
if 200 <= status < 300:
|
|
return
|
|
if status == 422 and "duplicate" in body.lower():
|
|
for record in list_txt(zone):
|
|
if str(record.get("type", "")).lower() != "txt":
|
|
continue
|
|
if not record_names_match(record.get("name"), name, name + "." + zone):
|
|
continue
|
|
if value and value in txt_text(record):
|
|
return
|
|
delete_record(zone, record["id"])
|
|
status, _body = request(
|
|
"POST",
|
|
"{}/{}/dns-records".format(API, zone),
|
|
{"type": "txt", "name": name, "value": {"text": value}, "ttl": 120},
|
|
)
|
|
if 200 <= status < 300 or (status == 422 and "duplicate" in _body.lower()):
|
|
return
|
|
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
|
raise SystemExit("Arvan DNS create failed: HTTP {}".format(status))
|
|
|
|
|
|
def txt_visible(fqdn, value):
|
|
urls = (
|
|
"https://dns.google/resolve?name={}&type=TXT".format(fqdn),
|
|
"https://cloudflare-dns.com/dns-query?name={}&type=TXT".format(fqdn),
|
|
)
|
|
for url in urls:
|
|
req = urllib.request.Request(url, headers={"Accept": "application/dns-json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
payload = json.loads(resp.read().decode())
|
|
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
|
continue
|
|
for answer in payload.get("Answer") or []:
|
|
data = answer.get("data", "").strip('"')
|
|
if value in data:
|
|
return True
|
|
return False
|