def config_ca_certs(): OS = platform.system() print "platform system:", OS if OS == 'Windows': CA_CERTS = ssl.enum_certificates("ROOT") elif OS == 'Linux': CA_CERTS = "/etc/ssl/certs/ca-bundle.crt"
def _load_wincerts(self, store): """Attempt to load CA certs from Windows trust store.""" cert_store = self._ctx.get_cert_store() oid = _stdlibssl.Purpose.SERVER_AUTH.oid for cert, encoding, trust in _stdlibssl.enum_certificates(store): if encoding == "x509_asn": if trust is True or oid in trust: cert_store.add_cert( _crypto.X509.from_cryptography( _load_der_x509_certificate(cert)))
def get_root_ca_certs(linux_certs_dir_path='/etc/ssl/certs'): system = platform.system().lower() #https://stackoverflow.com/a/64445061/4260911 if system == 'windows': items = ssl.enum_certificates("root") for cert_bytes, encoding, is_trusted in items: if encoding == "x509_asn": cert = x509.load_der_x509_certificate(cert_bytes) yield cert elif system == 'linux': certs_file_names = os.listdir(linux_certs_dir_path) for cert_file_name in certs_file_names: cert_file_path = os.path.join(linux_certs_dir_path, cert_file_name) if not os.path.isfile(cert_file_path): continue with open(cert_file_path, 'rb') as f: cert_pem = f.read() cert = x509.load_pem_x509_certificate(cert_pem) yield cert elif system == 'darwin': keychains = [ '/Library/Keychains/System.keychain', '/System/Library/Keychains/SystemRootCertificates.keychain' ] proc = subprocess.Popen(['security', 'find-certificate', '-a', '-p'] + keychains, stdout=subprocess.PIPE) res = proc.stdout.read() root_certs = list( filter( lambda a: a != b'\n' and a != b'', re.split( b'(-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)', res, flags=re.MULTILINE | re.DOTALL))) for cert_pem in root_certs: cert = x509.load_pem_x509_certificate(cert_pem) yield cert else: raise NotImplemented( f'missing implementation for this operating system="{system}"')
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.")
def create_default_context(cafile=None, capath=None, cadata=None): """Return a backports.ssl.SSLContext object configured with sensible default settings. The optional *cafile* argument is path to a file of concatenated CA certificates in PEM format. The optional *capath* argument is a path to a directory containing several CA certificates in PEM format, following an OpenSSL specific layout. The optional *cadata* argument is either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates. If *cafile*, *capath* and *cadata* are all None then system-installed CA certificates will be loaded (if available). """ # adapted from Python 3.4's ssl.create_default_context context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # require certificate that matches the host name. context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True # SSLv2 considered harmful. context.options |= _ossl.OP_NO_SSLv2 # SSLv3 has problematic security and is only required for really old # clients such as IE6 on Windows XP context.options |= _ossl.OP_NO_SSLv3 # disable compression to prevent CRIME attacks (OpenSSL 1.0+) context.options |= getattr(_ossl, "OP_NO_COMPRESSION", 0) # Prefer the server's ciphers by default so that we get stronger # encryption context.options |= getattr(_ossl, "OP_CIPHER_SERVER_PREFERENCE", 0) # Use single use keys in order to improve forward secrecy context.options |= getattr(_ossl, "OP_SINGLE_DH_USE", 0) context.options |= getattr(_ossl, "OP_SINGLE_ECDH_USE", 0) # disallow ciphers with known vulnerabilities # TODO: backports.ssl.SSLContext is missing set_ciphers context._ctx.set_cipher_list(_RESTRICTED_SERVER_CIPHERS) if cafile or capath or cadata: context.load_verify_locations(cafile, capath, cadata) elif context.verify_mode != ssl.CERT_NONE: # no explicit cafile, capath or cadata but the verify mode is # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system # root CA certificates for the given purpose. This may fail silently. if sys.platform == "win32": certs = bytearray() for storename in ("CA", "ROOT"): for cert, encoding, trust in enum_certificates(storename): # CA certs are never PKCS#7 encoded if encoding == "x509_asn": if trust is True or Purpose.SERVER_AUTH in trust: certs.extend(cert) if certs: context.load_verify_locations(cadata=certs) else: context.set_default_verify_paths() return context
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
def update_event(self, inp=-1): self.set_output_val(0, ssl.enum_certificates(self.input(0)))
import ssl print(ssl.enum_certificates("MY"))