def read_cryptoapi(self): certData = {} self._log("Retrieving certificate data from CryptoAPI") for storename in ("CA", "ROOT", "MY"): self._log("Gathering information from store: %s" % storename) with wincertstore.CertSystemStore(storename) as store: storecerts = {} for cert in store.itercerts(usage=None): certName = cert.get_name() self._log("Processing certificate: %s" % certName) keyName = re.sub(r"[\W]+", '', cert.get_name()) pem = cert.get_pem().decode("ascii") encodedDer = ''.join(pem.split("\n")[1:-2]) der = base64.b64decode(encodedDer) h = sha1() h.update(der) thumbprint = h.hexdigest() certificateInfo = { "Name": certName, "Thumbprint": thumbprint, "PEM": pem } self._log("Processing DER data for certificate: %s" % certName) derInfo = self._parse_der(der) for key in derInfo: certificateInfo[key] = derInfo[key] storecerts[keyName] = certificateInfo self._log("Finished processing certificate: %s" % certName) certData[storename] = storecerts return certData
def check_pem_file(): """ Convenience USGS only function that checks if the DOI PEM file is stored in the wincertstore and export a local copy for use in the application. Returns ------- None """ try: import wincertstore pem_fname = get_pem_fname() if not os.path.exists(pem_fname): for storename in ("CA", "ROOT"): with wincertstore.CertSystemStore(storename) as store: for cert in store.itercerts(usage=wincertstore.SERVER_AUTH): if 'DOIRootCA2' in cert.get_name(): text_file = open(pem_fname, "w", encoding='ascii') contents = cert.get_pem().encode().decode("ascii") text_file.write(contents) text_file.close() os.environ['PIP_CERT'] = pem_fname os.environ['SSL_CERT_FILE'] = pem_fname os.environ['GIT_SSL_CAINFO'] = pem_fname return pem_fname except: # this is an optional convenience function that will only work # on the Windows platform, for USGS users. # if anything goes wrong pass silently pass
def fetch_ssl_certificate(): """ function to add system CAs for cert checking """ if platform == 'linux': print('OS: Linux; changing certs environment variable...') os.environ['REQUESTS_CA_BUNDLE'] = os.path.join( '/etc/ssl/certs', 'ca-certificates.crt') print('Certs env variable changed: REQUESTS_CA_BUNDLE={0}'.format( os.getenv('REQUESTS_CA_BUNDLE'))) # if you're on WINDOWS, it probably should work for you. Extracting if platform == 'win32': print('OS: Windows; extracting SSL certificates') file = open('./certs_extracted', 'w') for storename in ['CA', 'ROOT']: with wincertstore.CertSystemStore(storename) as store: for cert in store.itercerts(usage=wincertstore.SERVER_AUTH): pem = cert.get_pem() file.write(pem + '\n') file.close() os.environ['REQUESTS_CA_BUNDLE'] = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'certs_extracted') print( 'Certificates extracted. Certs env variable changed: REQUESTS_CA_BUNDLE={0}' .format(os.getenv('REQUESTS_CA_BUNDLE')))
def create_certfile(self): certfile = wincertstore.CertFile() store = wincertstore.CertSystemStore("ROOT") try: certfile.addstore(store) finally: store.close() certfile.addstore("CA") return certfile
def test_wincertstore(self): store = wincertstore.CertSystemStore("ROOT") try: for cert in store.itercerts(): pem = cert.get_pem() enc = cert.get_encoded() name = cert.get_name() trust = cert.enhanced_keyusage_names() self.assertEqual(ssl.DER_cert_to_PEM_cert(enc), pem) self.assertEqual(ssl.PEM_cert_to_DER_cert(pem), enc) for crl in store.itercrls(): pem = cert.get_pem() finally: store.close()
def get_pems_wincertstore(store_names=None): import wincertstore store_names = store_names or ("CA", "ROOT") for store_name in store_names: with wincertstore.CertSystemStore(store_name) as store: for cert in store.itercerts(usage=wincertstore.SERVER_AUTH): try: pem = cert.get_pem() pem_entry = '# Label: "{name}"\n{pem}'.format( name=cert.get_name(), pem=pem.decode('ascii') if isinstance(pem, bytes) else pem) except UnicodeEncodeError: pem_entry = '' yield pem_entry
def get_pems_win(store_names=['CA']): certs = [] import wincertstore for store_name in store_names: with wincertstore.CertSystemStore(store_name) as store: for cert in store.itercerts(usage=wincertstore.SERVER_AUTH): try: pem = cert.get_pem() pem_entry = '# Label: \'{name}\'\n{pem}'.format( name=cert.get_name(), pem=pem.decode('ascii') if isinstance(pem, bytes) else pem) except UnicodeEncodeError as e: g_log.exception(e) pem_entry = '' certs.append(pem_entry) return certs
def hex_string_readable(bytes): return ["{:02X}".format(x) for x in bytes] def slugify(text, separator="_"): """Slugify a given text.""" if text == "" or text is None: return "" slug = unicode_slug.slugify(text, separator=separator) return "unknown" if slug == "" else slug if os.name == "nt": cnt = 0 for storename in ("ROOT", "CA", "MY"): with wincertstore.CertSystemStore(storename) as store: for cert in store.itercerts(usage=wincertstore.SERVER_AUTH): pem = cert.get_pem() encoded_der = "".join(pem.split("\n")[1:-2]) cert_bytes = base64.b64decode(encoded_der) cert_pem = ssl.DER_cert_to_PEM_cert(cert_bytes) cert_details = x509.load_pem_x509_certificate( cert_pem.encode("utf-8"), default_backend()) fingerprint = hex_string_readable( cert_details.fingerprint(hashes.SHA1())) fingerprint_string = "".join(fingerprint) print(cert.get_name())
def run(plugin): """Import intermediate certs and return True on success""" if QgsApplication.authManager().isDisabled(): plugin.log(QgsApplication.authManager().disabledMessage()) return False ca_pems = dict() with wincertstore.CertSystemStore("CA") as store: for cert in store.itercerts(usage=None): # plugin.log(cert.get_name()) # plugin.log(cert.enhanced_keyusage_names()) ca_pems[cert.get_name()] = cert.get_pem() plugin.log( plugin.tr("Number of possible CAs found: {0}").format(len(ca_pems))) if not ca_pems: return False ca_certs = [] trusted_cas = QgsApplication.authManager().trustedCaCertsCache() for ca_cn, ca_pem in ca_pems.items(): try: ca_bytes = ca_pem.encode('ASCII') except UnicodeEncodeError: continue pem_ba = QByteArray(ca_bytes) cas = QSslCertificate.fromData(pem_ba) # plugin.log("Converted PEM to QSslCertificate {0}: ".format(ca_cn)) if not cas: plugin.log( plugin.tr("Could not convert PEM to QSslCertificate: {0}"). format(ca_cn)) continue ca = cas[0] # noinspection PyArgumentList if not QgsAuthCertUtils.certIsViable(cert=ca): plugin.log(plugin.tr(" cert not viable: {0}").format(ca_cn)) continue # noinspection PyArgumentList if not QgsAuthCertUtils.certificateIsAuthority(cert=ca): plugin.log(plugin.tr(" cert not a CA: {0}").format(ca_cn)) continue if ca in trusted_cas: plugin.log( plugin.tr(" cert already in trusted CA cache: {0}").format( ca_cn)) continue plugin.log(plugin.tr(" found CA to add: {0}").format(ca_cn)) ca_certs.append(ca) if ca_certs: plugin.log(plugin.tr("Storing CAs in auth system db")) if not QgsApplication.authManager().storeCertAuthorities(ca_certs): plugin.log(plugin.tr(" FAILED")) return False plugin.log(plugin.tr(" SUCCESS")) plugin.log(plugin.tr("Reinitializing auth system SSL caches")) QgsApplication.authManager().initSslCaches() return True else: plugin.log(plugin.tr("No CAs found to store in auth system db")) return True