okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
4.4 KiB88 linesraw
1"""How Strata's own programs check the certificate of a server they download from (#3722).
2
3Python's OpenSSL checks a server against a list of root certificates it carries (certifi) and does not fetch a missing intermediate
4certificate. Chrome and curl.exe use the operating system's certificate store and its chain building (Windows schannel, macOS Security,
5the system bundle on Linux): they also trust the roots that antivirus HTTPS scanning, a company proxy or a Windows Insider build adds
6there, and they fetch a missing intermediate from the address inside the certificate. So a PC where the browser works could still
7fail with CERTIFICATE_VERIFY_FAILED ("unable to get local issuer certificate") in Strata.
8
9`install()` makes every later HTTPS connection of this process use the operating system's store, through the `truststore` package
10(pure Python, Python 3.10 and newer, pinned in requirements.txt and the runtime locks). Where it is not installed (an older Python, a
11checkout that has not installed the pins yet) the certifi list is used; where that is missing too, Python's own default stays.
12Verification is never turned off: a connection that still fails is explained by `explain()`, and nothing here offers to skip the check.
13"""
14
15from __future__ import annotations
16
17import ssl
18import sys
19
20#: "truststore", "certifi" or "default": what the process uses after install()
21mode: str | None = None
22
23
24def install() -> str:
25    """Use the OS certificate store for every HTTPS connection of this process. Safe to call again and from any thread's start."""
26    global mode
27    if mode is not None:
28        return mode
29    try:
30        import truststore                                  # Python >= 3.10
31        truststore.inject_into_ssl()
32        mode = "truststore"
33        return mode
34    except Exception:                                      # ImportError, or a Python/OS truststore cannot work on
35        pass
36    try:
37        import certifi
38        bundle = certifi.where()
39        ssl._create_default_https_context = lambda *a, **k: ssl.create_default_context(cafile=bundle)   # type: ignore[assignment]
40        mode = "certifi"
41    except Exception:
42        mode = "default"
43    return mode
44
45
46def is_certificate_error(exc: BaseException | None) -> bool:
47    """True for a failed certificate check, however urllib, http.client or requests wrapped it."""
48    seen = 0
49    while exc is not None and seen < 6:
50        if isinstance(exc, ssl.SSLCertVerificationError) or "CERTIFICATE_VERIFY_FAILED" in str(exc):
51            return True
52        exc = getattr(exc, "reason", None) if isinstance(getattr(exc, "reason", None), BaseException) else (exc.__cause__ or exc.__context__)
53        seen += 1
54    return False
55
56
57TRY = ("Things to try, in this order: 1) check that the date and time of this PC are right; 2) in your antivirus or security suite, switch off "
58       "'HTTPS scanning' / 'web shield' for Strata, or add Strata and its Python to its exceptions, then try again; 3) if you use a company "
59       "or school network or proxy, ask the person who runs it to trust the download addresses, or try another network (a phone hotspot "
60       "is enough to tell); 4) run Windows Update, which refreshes the certificates the PC trusts. Strata will not skip the check: "
61       "an unchecked download could be a different file.")
62
63
64def explain(host: str | None = None) -> str:
65    """The plain sentence for a certificate failure: no urlopen text, the likely causes, no offer to turn the check off."""
66    where = f"the server {host}" if host else "the download server"
67    return (f"Strata could not confirm that it is really talking to {where}: its security certificate was not accepted. "
68            "Something between this PC and the internet is probably intercepting secure (HTTPS) connections, most often antivirus "
69            "web scanning or a company or school proxy. " + TRY)
70
71
72class CertificateProblem(OSError):
73    """A download stopped because the server's certificate was not accepted. str() is the plain explanation."""
74
75    def __init__(self, host: str | None = None):
76        super().__init__(explain(host))
77        self.host = host
78
79
80def host_of(url: str) -> str | None:
81    try:
82        return url.split("/")[2]
83    except IndexError:
84        return None
85
86
87if __name__ == "__main__":                                 # python -m strata_control.tls: what this process would use
88    print(install(), sys.version.split()[0])