Files
buryan-infra/ops/notify/check_certs.py

236 lines
8.5 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# ============================================================
# check_certs.py — контроль сроков сертификатов (задача F6-6)
# ============================================================
# Зачем: сертификат обратного прокси действует до 24.12.2026. Если продление
# не сработает, узнать об этом лучше за две недели, а не в день истечения.
#
# Что проверяет: настоящий сертификат, который отдаётся по каждому домену —
# то есть именно то, что получает браузер. Проверка идёт по сети, а не по
# файлам, поэтому ловит и случай, когда файл обновился, а прокси его не взял.
#
# Порог: предупреждение за 14 дней, критично за 7.
#
# Запуск по расписанию: раз в сутки.
# ============================================================
import json
import os
import socket
import ssl
import subprocess
import sys
import time
from datetime import datetime, timezone
WARN_DAYS = int(os.getenv("THRESH_WARN_DAYS", "14"))
CRIT_DAYS = int(os.getenv("THRESH_CRITICAL_DAYS", "7"))
STATE_FILE = os.getenv("CERT_STATE_FILE", "/var/lib/buryan-monitor/cert-state.json")
TOKENS_FILE = os.getenv("TOKENS_FILE", "/root/bots-tokens.env")
ALERT_CHAT_ID = os.getenv("ALERT_CHAT_ID", "273442500")
TG_PROXY = os.getenv("TG_PROXY", "http://192.168.1.10:10888")
DOMAINS = os.getenv("CERT_DOMAINS", " ".join([
"buryans.ru",
"vault.buryans.ru",
"matrix.buryans.ru",
"headscale.buryans.ru",
"authentik.buryans.ru",
"n8n.buryans.ru",
"element.buryans.ru",
"status.buryans.ru",
"git.buryans.ru",
"recipes.buryans.ru",
"finance.buryans.ru",
"sync.buryans.ru",
"music.buryans.ru",
"chat.buryans.ru",
])).split()
PG_HOST = os.getenv("PG_HOST", "192.168.1.151")
PG_DB = os.getenv("PG_DB", "buryan_monitoring")
PG_USER = os.getenv("PG_USER", "buryan_monitor")
def expiry_of(host, timeout=12):
"""Срок действия сертификата, который отдаёт узел.
Сертификат запрашивается как обычная строка PEM и разбирается openssl.
Через ssl.getpeercert() не получается: при отключённой проверке
подлинности Python возвращает пустой словарь, и срок узнать неоткуда.
"""
pem = ssl.get_server_certificate((host, 443), timeout=timeout)
res = subprocess.run(
["openssl", "x509", "-noout", "-enddate", "-subject"],
input=pem, capture_output=True, text=True, timeout=15,
)
not_after_raw = ""
subject = "?"
for line in res.stdout.splitlines():
if line.startswith("notAfter="):
not_after_raw = line.split("=", 1)[1].strip()
elif line.startswith("subject="):
subject = line.split("=", 1)[1].strip()
if not not_after_raw:
return None, None
not_after = datetime.strptime(not_after_raw, "%b %d %H:%M:%S %Y %Z")
not_after = not_after.replace(tzinfo=timezone.utc)
days = (not_after - datetime.now(timezone.utc)).days
return days, subject
def status_of(days):
if days < CRIT_DAYS:
return "CRITICAL"
if days < WARN_DAYS:
return "WARNING"
return "OK"
def read_state():
try:
with open(STATE_FILE) as fh:
return json.load(fh)
except Exception:
return {}
def write_state(state):
os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
tmp = STATE_FILE + ".tmp"
with open(tmp, "w") as fh:
json.dump(state, fh)
os.replace(tmp, STATE_FILE)
def alert_token():
try:
with open(TOKENS_FILE) as fh:
for line in fh:
if line.startswith("ALERT_TOKEN="):
return line.split("=", 1)[1].strip()
except Exception:
pass
return ""
def send_alert(text):
"""Единый слой: Matrix основной, Telegram зеркало.
Возвращает True, если доставлено хотя бы одним каналом, — чтобы
вызывающая сторона не повторяла уведомление.
"""
try:
import os as _os
import sys as _sys
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
import notify
return notify.send(text)
except Exception as _exc: # noqa: BLE001
print(f"общий слой уведомлений недоступен, шлю напрямую в Telegram: {_exc}",
file=sys.stderr)
return send_alert_telegram(text)
def send_alert_telegram(text):
token = alert_token()
if not token:
print(f"нет токена бота алертов в {TOKENS_FILE}", file=sys.stderr)
return False
try:
res = subprocess.run(
["curl", "-s", "-m", "25", "-o", "/dev/null", "-w", "%{http_code}",
"-x", TG_PROXY, "-X", "POST",
"--data-urlencode", f"chat_id={ALERT_CHAT_ID}",
"--data-urlencode", f"text={text}",
"--data-urlencode", "parse_mode=HTML",
f"https://api.telegram.org/bot{token}/sendMessage"],
capture_output=True, text=True, timeout=40,
)
return res.stdout.strip() == "200"
except Exception as exc:
print(f"не удалось отправить уведомление: {exc}", file=sys.stderr)
return False
def save_metrics(rows):
import shutil
if not shutil.which("psql") or not rows:
return
values = ",".join(
f"('{h}',{d},'{s.replace(chr(39), chr(39) * 2)}')" for h, d, s in rows
)
sql = ("INSERT INTO cert_metrics (domain, days_left, subject) "
f"VALUES {values}")
try:
subprocess.run(["psql", "-h", PG_HOST, "-U", PG_USER, "-d", PG_DB, "-c", sql],
capture_output=True, text=True, timeout=30)
except Exception as exc:
print(f"не удалось записать замеры: {exc}", file=sys.stderr)
def main():
state = read_state()
now = time.time()
problems = []
rows = []
unreachable = []
for host in DOMAINS:
try:
days, subject = expiry_of(host)
except Exception as exc:
unreachable.append(f"{host} ({exc})")
continue
if days is None:
unreachable.append(host)
continue
rows.append((host, days, subject or "?"))
status = status_of(days)
prev = state.get(host, {})
prev_status = prev.get("status")
if status == "OK":
if prev_status and prev_status != "OK":
send_alert(f"✅ Сертификат <b>{host}</b> продлён, осталось {days} дней")
state[host] = {"status": "OK", "days": days, "ts": now}
continue
if status != prev_status or now - prev.get("ts", 0) > 24 * 3600:
problems.append((host, days, status, subject))
state[host] = {"status": status, "days": days, "ts": now}
if problems:
# Одно сообщение на все домены — по той же причине, что и для дисков.
problems.sort(key=lambda p: p[1])
lines = [
f"{'🔴' if status == 'CRITICAL' else '🟠'} "
f"<b>{host}</b> — осталось {days} дней"
for host, days, status, _ in problems
]
send_alert(
f"⚠️ <b>Сроки сертификатов</b>: истекают у {len(problems)} домен(ов)\n\n"
+ "\n".join(lines)
+ "\n\nПродлением занимается обратный прокси (CT 101, npm-app-1).\n"
"Проверить: <code>pct exec 101 -- docker exec npm-app-1 "
"certbot renew --dry-run</code>"
)
if unreachable:
print(f"не удалось проверить: {', '.join(unreachable)}", file=sys.stderr)
write_state(state)
save_metrics(rows)
if rows:
worst = min(d for _, d, _ in rows)
print(f"[{datetime.now().isoformat()}] проверено доменов: {len(rows)}, "
f"минимум дней: {worst}, тревог: {len(problems)}")
return 0
if __name__ == "__main__":
sys.exit(main())