#!/usr/bin/env python3 """Проверка TLS-сертификата и цепочки удалённого хоста.""" from __future__ import annotations import argparse import json import re import shutil import socket import ssl import subprocess from datetime import datetime, timezone from cryptography import x509 from cryptography.hazmat.primitives.asymmetric import ec, ed25519, ed448, rsa CERT_RE = re.compile(rb"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", re.S) def key_info(cert: x509.Certificate) -> str: key = cert.public_key() if isinstance(key, rsa.RSAPublicKey): return f"RSA {key.key_size}" if isinstance(key, ec.EllipticCurvePublicKey): return f"EC {key.curve.name}" if isinstance(key, ed25519.Ed25519PublicKey): return "Ed25519" if isinstance(key, ed448.Ed448PublicKey): return "Ed448" return type(key).__name__ def expiry(cert: x509.Certificate) -> datetime: value = getattr(cert, "not_valid_after_utc", None) if value is None: value = cert.not_valid_after.replace(tzinfo=timezone.utc) return value def short(name: x509.Name) -> str: text = name.rfc4514_string() return text if len(text) <= 120 else text[:117] + " [обрезано]" def fetch(host: str, port: int, timeout: float) -> tuple[bytes, str, str, bool, str]: context = ssl.create_default_context() verified = True error_text = "" try: with socket.create_connection((host, port), timeout=timeout) as raw: with context.wrap_socket(raw, server_hostname=host) as tls: return tls.getpeercert(binary_form=True), tls.version() or "?", tls.cipher()[0], True, "" except ssl.SSLCertVerificationError as error: verified = False error_text = str(error) context = ssl._create_unverified_context() with socket.create_connection((host, port), timeout=timeout) as raw: with context.wrap_socket(raw, server_hostname=host) as tls: return tls.getpeercert(binary_form=True), tls.version() or "?", tls.cipher()[0], verified, error_text def fetch_chain(host: str, port: int, timeout: float) -> tuple[list[x509.Certificate], str]: if not shutil.which("openssl"): return [], "openssl не найден" try: result = subprocess.run( ["openssl", "s_client", "-connect", f"{host}:{port}", "-servername", host, "-showcerts"], input="", capture_output=True, text=True, timeout=timeout + 10, check=False, ) except (OSError, subprocess.TimeoutExpired) as error: return [], str(error) certificates = [] for block in CERT_RE.findall(result.stdout.encode()): try: certificates.append(x509.load_pem_x509_certificate(block)) except ValueError: continue return certificates, "" def main() -> int: parser = argparse.ArgumentParser(description="Проверка TLS-сертификата") parser.add_argument("--host", required=True, help="Имя хоста или IP") parser.add_argument("--port", type=int, default=443, help="Порт TLS") parser.add_argument("--days", type=int, default=30, help="Порог предупреждения об истечении") parser.add_argument("--timeout", type=float, default=10.0, help="Таймаут соединения") parser.add_argument("--no-chain", action="store_true", help="Не загружать цепочку через openssl") parser.add_argument("--json", type=argparse.FileType("w", encoding="utf-8"), help="Сохранить отчёт в JSON") args = parser.parse_args() try: der, protocol, cipher, verified, verify_error = fetch(args.host, args.port, args.timeout) except (OSError, ssl.SSLError) as error: print(f"Не удалось подключиться к {args.host}:{args.port}: {error}") return 2 if not der: print(f"Сервер {args.host}:{args.port} не вернул сертификат.") return 2 cert = x509.load_der_x509_certificate(der) expires = expiry(cert) now = datetime.now(timezone.utc) days_left = (expires - now).days self_signed = cert.subject == cert.issuer chain: list[x509.Certificate] = [] chain_error = "" if not args.no_chain: chain, chain_error = fetch_chain(args.host, args.port, args.timeout) print(f"Хост: {args.host}:{args.port}") print(f"Проверка сертификата: {'OK' if verified else 'ОШИБКА'}") if verify_error: print(f"Причина: {verify_error}") print(f"Протокол: {protocol}") print(f"Шифр: {cipher}") print(f"Субъект: {short(cert.subject)}") print(f"Издатель: {short(cert.issuer)}") print(f"Действует до: {expires.date().isoformat()} (осталось дней: {days_left})") print(f"Ключ: {key_info(cert)}") if self_signed: print("Сертификат самоподписанный.") if chain: count = len(chain) word = "сертификат" if count == 1 else ("сертификата" if 2 <= count <= 4 else "сертификатов") print(f"Цепочка: {count} {word}") for index, item in enumerate(chain, start=1): item_days = (expiry(item) - now).days print(f" {index}. {short(item.subject)}") print(f" издатель: {short(item.issuer)}, до: {expiry(item).date().isoformat()} ({item_days} дн.)") elif chain_error: print(f"Цепочка не загружена: {chain_error}") print() warnings = [] if not verified: warnings.append("сертификат не прошёл штатную проверку") if days_left < 0: warnings.append("сертификат истёк") elif days_left <= args.days: warnings.append(f"сертификат истекает через {days_left} дн.") if warnings: print("ВНИМАНИЕ: " + "; ".join(warnings)) else: print("Сертификат действителен, срок в норме.") if args.json: payload = { "host": args.host, "port": args.port, "verified": verified, "verify_error": verify_error, "protocol": protocol, "cipher": cipher, "subject": short(cert.subject), "issuer": short(cert.issuer), "expires": expires.date().isoformat(), "days_left": days_left, "self_signed": self_signed, "chain": [ { "subject": short(item.subject), "issuer": short(item.issuer), "expires": expiry(item).date().isoformat(), } for item in chain ], } json.dump(payload, args.json, ensure_ascii=False, indent=2) args.json.write("\n") print(f"JSON сохранён: {args.json.name}") if not verified or days_left < 0: return 2 if days_left <= args.days: return 1 return 0 if __name__ == "__main__": raise SystemExit(main())