Пример #1
0
 def test_read_contents(self):
     with patch("builtins.open",
                mock_open(
                    read_data="-----BEGIN CERTIFICATE-----")) as mock_file:
         content = certifi.contents()
         assert "-----BEGIN CERTIFICATE-----" in content
         mock_file.assert_called_with("/etc/ssl/certs/ca-certificates.crt",
                                      'r',
                                      encoding='ascii')
Пример #2
0
def _upgrade_stream_to_ssl(raw_stream: trio.abc.Stream,
                           hostname: str) -> trio.abc.Stream:
    # The ssl context should be generated once and stored into the config
    # however this is tricky (should ssl configuration be stored per device ?)

    # Don't load default system certificates and rely on our own instead.
    # This is because system certificates are less reliable (and system
    # certificates are tried first, so they can lead to a failure even if
    # we bundle a valid certificate...)
    # Certifi provides Mozilla's carefully curated collection of Root Certificates.
    ssl_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH,
                                             cadata=certifi.contents())

    # Also provide custom certificates if any
    cafile = os.environ.get("SSL_CAFILE")
    if cafile:
        ssl_context.load_verify_locations(cafile)

    return trio.SSLStream(raw_stream, ssl_context, server_hostname=hostname)
Пример #3
0
def write_ca_bundle(cert: Certificate,
                    cert_path: str,
                    include_certifi: bool = True,
                    rename: bool = True) -> None:
    tmp_cert_path = f"{cert_path}.tmp" if rename else cert_path
    with open(tmp_cert_path, "wb") as f:
        if include_certifi:
            f.write(certifi.contents().encode())
        f.write("\n".encode())
        f.write(f"# Issuer: {cert.issuer.rfc4514_string()}\n".encode())
        f.write(f"# Subject: {cert.subject.rfc4514_string()}\n".encode())
        label = cert.issuer.get_attributes_for_oid(
            NameOID.COMMON_NAME)[0].value
        f.write(f"# Label: {label}\n".encode())
        f.write(f"# Serial: {cert.serial_number}\n".encode())
        md5 = cert_fingerprint(cert, "MD5")
        sha1 = cert_fingerprint(cert, "SHA1")
        sha256 = cert_fingerprint(cert, "SHA256")
        f.write(f"# MD5 Fingerprint: {md5}\n".encode())
        f.write(f"# SHA1 Fingerprint: {sha1}\n".encode())
        f.write(f"# SHA256 Fingerprint: {sha256}\n".encode())
        f.write(cert_to_bytes(cert))
    if rename:
        os.rename(tmp_cert_path, cert_path)
Пример #4
0
def add_statoil_root_certificate():
    """ This is a utility function for Equinor employees on Equinor machines.

    The function searches for the Statoil Root certificate in the Windows
    cert store and imports it to the cacert bundle.

    This only needs to be done once per virtual environment.
    """
    import ssl
    import certifi
    import hashlib

    STATOIL_ROOT_PEM_HASH = "ce7bb185ab908d2fea28c7d097841d9d5bbf2c76"

    print("Scanning CA certs in store ", end="")
    found = False
    for cert in ssl.enum_certificates("CA"):
        print(".", end="")
        der = cert[0]
        if hashlib.sha1(der).hexdigest() == STATOIL_ROOT_PEM_HASH:
            found = True
            print(" found it!")
            print("Converting certificate to PEM")
            pem = ssl.DER_cert_to_PEM_cert(cert[0])
            if pem in certifi.contents():
                print("Certificate already exists in certifi store. Nothing to do.")
                break
            print("Writing certificate to certifi store.")
            cafile = certifi.where()
            with open(cafile, "ab") as f:
                f.write(bytes(pem, "ascii"))
            print("Completed")
            break

    if not found:
        print("\n\nERROR: Unable to locate Statoil Root certificate.")
Пример #5
0
import argparse

from certifi import contents, where

parser = argparse.ArgumentParser()
parser.add_argument("-c", "--contents", action="store_true")
args = parser.parse_args()

if args.contents:
    print(contents())
else:
    print(where())
Пример #6
0
 def test_read_contents(self):
     content = certifi.contents()
     assert "-----BEGIN CERTIFICATE-----" in content
Пример #7
0
def add_statoil_root_certificate(noisy=True):
    """This is a utility function for Equinor employees on Equinor managed machines.

    The function searches for the Statoil Root certificate in the
    cert store and imports it to the cacert bundle. Does nothing if not
    running on Equinor host.

    This needs to be repeated after updating the cacert module.

    Returns:
        bool: True if function completes successfully
    """
    import hashlib
    import ssl

    import certifi

    STATOIL_ROOT_PEM_HASH = "ce7bb185ab908d2fea28c7d097841d9d5bbf2c76"

    found = False

    if is_linux():
        return True
    elif is_windows():
        if noisy:
            print("Scanning CA certs in Windows cert store", end="")
        for cert in ssl.enum_certificates("CA"):
            if noisy:
                print(".", end="")
            der = cert[0]
            if hashlib.sha1(der).hexdigest() == STATOIL_ROOT_PEM_HASH:
                found = True
                if noisy:
                    print(" found it!")
                break
    elif is_mac():
        import subprocess
        macos_ca_certs = subprocess.run(["security", "find-certificate", "-a", "-c", "Statoil Root CA", "-Z"],
                                        stdout=subprocess.PIPE).stdout

        if STATOIL_ROOT_PEM_HASH.upper() in str(macos_ca_certs).upper():
            c = get_macos_statoil_certificates()
            for cert in c:
                if hashlib.sha1(cert).hexdigest() == STATOIL_ROOT_PEM_HASH:
                    der = cert
                    found = True
                    break

    if found:
        pem = ssl.DER_cert_to_PEM_cert(der)
        if pem in certifi.contents():
            if noisy:
                print("Certificate already exists in certifi store. Nothing to do.")
        else:
            if noisy:
                print("Writing certificate to certifi store.")
            cafile = certifi.where()
            with open(cafile, "ab") as f:
                f.write(bytes(pem, "ascii"))
            if noisy:
                print("Completed")
    else:
        warnings.warn("Unable to locate root certificate on this host.")

    return found
Пример #8
0
def test_contents():
    contents = certifi.contents()
    assert "BEGIN CERTIFICATE" in contents