Ejemplo n.º 1
0
def _extract_cert_from_data(f,
                            password=None,
                            key_converter=None,
                            cert_converter=None):
    certs = []
    private_key = None

    if isinstance(f, unicode):
        f = StringIO(str(f))
    elif isinstance(f, str):
        f = StringIO(f)

    if not hasattr(f, 'seek'):
        raise TypeError(
            "PEM lib (data must be a file like object, string or bytes")

    if _is_cert_pem(f):
        certs, private_key = _read_pem_cert_from_data(f, password,
                                                      key_converter,
                                                      cert_converter)
    else:
        cf = CertificateFactory.getInstance("X.509")
        certs = list(cf.generateCertificates(ByteArrayInputStream(f.read())))

    return certs, private_key
Ejemplo n.º 2
0
 def _load_certificates(self, f):
     cf = CertificateFactory.getInstance("X.509")
     try:
         for cert in cf.generateCertificates(BufferedInputStream(f)):
             self._trust_store.setCertificateEntry(str(uuid.uuid4()), cert)
     except CertificateParsingException:
         log.debug("Failed to parse certificate", exc_info=True)
         raise
Ejemplo n.º 3
0
 def _load_certificates(self, f):
     cf = CertificateFactory.getInstance("X.509")
     try:
         for cert in cf.generateCertificates(BufferedInputStream(f)):
             self._trust_store.setCertificateEntry(str(uuid.uuid4()), cert)
     except CertificateParsingException:
         log.debug("Failed to parse certificate", exc_info=True)
         raise
Ejemplo n.º 4
0
def _get_ca_certs_trust_manager(ca_certs):
    trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
    trust_store.load(None, None)
    with open(ca_certs) as f:
        cf = CertificateFactory.getInstance("X.509")
        for cert in cf.generateCertificates(BufferedInputStream(f)):
            trust_store.setCertificateEntry(str(uuid.uuid4()), cert)

    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
    tmf.init(trust_store)
    return tmf
Ejemplo n.º 5
0
def _get_ca_certs_trust_manager(ca_certs):
    trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
    trust_store.load(None, None)
    num_certs_installed = 0
    with open(ca_certs) as f:
        cf = CertificateFactory.getInstance("X.509")
        for cert in cf.generateCertificates(BufferedInputStream(f)):
            trust_store.setCertificateEntry(str(uuid.uuid4()), cert)
            num_certs_installed += 1
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
    tmf.init(trust_store)
    log.debug("Installed %s certificates", num_certs_installed, extra={"sock": "*"})
    return tmf
Ejemplo n.º 6
0
def _get_ca_certs_trust_manager(ca_certs=None):
    trust_store = KeyStore.getInstance(KeyStore.getDefaultType())
    trust_store.load(None, None)
    num_certs_installed = 0
    if ca_certs is not None:
        with open(ca_certs) as f:
            cf = CertificateFactory.getInstance("X.509")
            for cert in cf.generateCertificates(BufferedInputStream(f)):
                trust_store.setCertificateEntry(str(uuid.uuid4()), cert)
                num_certs_installed += 1
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
    tmf.init(trust_store)
    log.debug("Installed %s certificates", num_certs_installed, extra={"sock": "*"})
    return tmf
Ejemplo n.º 7
0
 def trustSpecificCertificate(self, pemCertificateFile, pemCertificateAlias):
         from java.io import BufferedInputStream, FileInputStream
         from java.security import KeyStore
         from java.security.cert import CertificateFactory, X509Certificate
         from javax.net.ssl import SSLContext, TrustManagerFactory
         
         fis = FileInputStream(pemCertificateFile)
         bis = BufferedInputStream(fis)
         ca = CertificateFactory.getInstance("X.509").generateCertificate(bis)
         ks = KeyStore.getInstance(KeyStore.getDefaultType())
         ks.load(None, None)
         ks.setCertificateEntry(pemCertificateAlias, ca)
         tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
         tmf.init(ks)
         context = SSLContext.getInstance("SSL")
         context.init(None, tmf.getTrustManagers(), None)
         SSLContext.setDefault(context)
Ejemplo n.º 8
0
def _extract_cert_from_data(f, password=None, key_converter=None, cert_converter=None):
    certs = []
    private_key = None

    if isinstance(f, unicode):
        f = StringIO(str(f))
    elif isinstance(f, str):
        f = StringIO(f)

    if not hasattr(f, 'seek'):
        raise TypeError("PEM lib (data must be a file like object, string or bytes")

    if _is_cert_pem(f):
        certs, private_key = _read_pem_cert_from_data(f, password, key_converter, cert_converter)
    else:
        cf = CertificateFactory.getInstance("X.509")
        certs = list(cf.generateCertificates(ByteArrayInputStream(f.read())))

    return certs, private_key
Ejemplo n.º 9
0
    def trustSpecificCertificate(self, pemCertificateFile,
                                 pemCertificateAlias):
        from java.io import BufferedInputStream, FileInputStream
        from java.security import KeyStore
        from java.security.cert import CertificateFactory, X509Certificate
        from javax.net.ssl import SSLContext, TrustManagerFactory

        fis = FileInputStream(pemCertificateFile)
        bis = BufferedInputStream(fis)
        ca = CertificateFactory.getInstance("X.509").generateCertificate(bis)
        ks = KeyStore.getInstance(KeyStore.getDefaultType())
        ks.load(None, None)
        ks.setCertificateEntry(pemCertificateAlias, ca)
        tmf = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm())
        tmf.init(ks)
        context = SSLContext.getInstance("SSL")
        context.init(None, tmf.getTrustManagers(), None)
        SSLContext.setDefault(context)
Ejemplo n.º 10
0
    def __get_certificate_infos(self):
        infos = []
        es = EntityStoreAPI.wrap(self.__fed_archive.getEntityStore(),
                                 self.__passphrase_in)
        cert_entities = es.getAll(
            "/[Certificates]name=Certificate Store/[Certificate]**")
        cf = CertificateFactory.getInstance("X.509")
        for cert_entity in cert_entities:
            alias = cert_entity.getStringValue("dname")
            subject = None
            not_after = None

            content = cert_entity.getBinaryValue("content")
            if content:
                cert = cf.generateCertificate(ByteArrayInputStream(content))
                subject = cert.getSubjectDN().getName()
                not_after = cert.getNotAfter()

            infos.append(CertInfo(alias, subject, not_after))
        return infos
print 'Install certificate %s to target %s' % (deployed.name, deployed.container.name)

# Load the keystore
print 'Loading keystore %s' % (deployed.container.keystore)
ks = KeyStore.getInstance(deployed.container.keystoreType)
ksfi = FileInputStream(deployed.container.keystore)

try:
    ks.load(ksfi, deployed.container.passphrase)

     # Load certificates (base64 encoded DER/PEM-encoded certificates)
     # http://docs.oracle.com/javase/7/docs/api/java/security/cert/CertificateFactory.html#generateCertificates(java.io.InputStream)
    print 'Loading the certificate(chain)'
    inStream = ByteArrayInputStream(DatatypeConverter.parseBase64Binary(String(deployed.certificate)))
    cf = CertificateFactory.getInstance("X.509")
    chain = cf.generateCertificates(inStream).toArray(jarray.zeros(0, java.security.cert.Certificate))

    # Save the private key entry (base64 PKCS8 DER encoded)
    print 'Storing key/certificate %s (alias=%s) in keystore %s' % (deployed.name, deployed.alias, deployed.container.keystore)
    kf = KeyFactory.getInstance(deployed.keyAlgorithm)
    key = kf.generatePrivate(PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(String(deployed.key))))
    ks.setEntry(deployed.alias, KeyStore.PrivateKeyEntry(key, chain), KeyStore.PasswordProtection(deployed.keyPassword))

    ksfo = FileOutputStream(deployed.container.keystore)
    try:
        ks.store(ksfo, deployed.container.passphrase)
        print 'Stored key/certificate %s (alias=%s) in keystore %s' % (deployed.name, deployed.alias, deployed.container.keystore)
    finally:
        ksfo.close()
finally:
Ejemplo n.º 12
0
    def __configure_certificates(self):
        if self.__cert_config is not None:
            # determine existing certificates
            logging.info("Determine existing certificates")
            cert_infos = self.__get_certificate_infos()
            self.__cert_config.set_cert_infos(cert_infos)
            self.__cert_config.update_config_file()

            # apply configured certificates
            logging.info("Configure certificates")
            certs = self.__cert_config.get_certificates()
            es = EntityStoreAPI.wrap(self.__fed_archive.getEntityStore(),
                                     self.__passphrase_in)

            cert_infos = []
            cert = None

            for cert_ref in certs:
                file = self.__resolve_file_path(cert_ref.get_file())
                logging.info("Process alias '%s' (%s): %s" %
                             (cert_ref.get_alias(), cert_ref.get_type(), file))
                if cert_ref.get_type() == "crt":
                    cf = CertificateFactory.getInstance("X.509")
                    if os.path.isfile(file):
                        fis = FileInputStream(file)
                        cert = cf.generateCertificate(fis)
                        self.__add_or_replace_certificate(
                            es, cert_ref.get_alias(), cert)
                    else:
                        if self.__simulation_mode:
                            logging.warning(
                                "[SIMULATION_MODE] Certificate file not found, certificate (CRT) ignored: alias=%s"
                                % (cert_ref.get_alias()))
                            continue
                        else:
                            raise ValueError(
                                "Certificate file not found for alias '%s': %s"
                                % (cert_ref.get_alias(), file))
                elif cert_ref.get_type() == "p12":
                    if os.path.isfile(file):
                        key = self.__get_key_from_p12(file,
                                                      cert_ref.get_password())
                        cert = self.__get_cert_from_p12(
                            file, cert_ref.get_password())
                        self.__add_or_replace_certificate(
                            es, cert_ref.get_alias(), cert, key)
                    else:
                        if self.__simulation_mode:
                            logging.warning(
                                "[SIMULATION_MODE] Certificate file not found, certificate (P12) ignored: alias=%s"
                                % (cert_ref.get_alias()))
                            continue
                        else:
                            raise ValueError(
                                "Certificate file not found for alias '%s': %s"
                                % (cert_ref.get_alias(), file))
                elif cert_ref.get_type() == "empty":
                    self.__remove_certificate(es, cert_ref.get_alias())
                    logging.info("Certificate removed: %s" %
                                 (cert_ref.get_alias()))
                    continue
                else:
                    raise ValueError("Unsupported certificate type: %s" %
                                     (cert_ref.get_type()))

                subject = cert.getSubjectDN().getName()
                not_after = cert.getNotAfter()

                cert_info = CertInfo(cert_ref.get_alias(), subject, not_after)
                logging.info(
                    "Certificate (%s) added/replaced: %s [%s] - %s" %
                    (cert_ref.get_type(), cert_info.get_alias(),
                     cert_info.format_not_after(), cert_info.get_subject()))

                cert_infos.append(cert_info)

            if self.__update_cert_config:
                self.__cert_config.set_update_cert_infos(cert_infos)
                self.__cert_config.update_config_file()

            if self.__expiration_days >= 0:
                logging.info(
                    "Checking for certificate expiration within %i days." %
                    (self.__expiration_days))
                has_expired = False
                for cert_info in cert_infos:
                    expiration_days = cert_info.expiration_in_days()
                    if self.__expiration_days > expiration_days:
                        logging.error("Certificate '%s' expires in %i days!" %
                                      (cert_info.get_alias(), expiration_days))
                        has_expired = True

                if has_expired:
                    raise ValueError(
                        "At least one certificate expires in less than %i days; check log file!"
                        % (self.__expiration_days))

            if not self.__simulation_mode:
                DeploymentArchive.updateConfiguration(self.__fed_archive,
                                                      es.es)
                logging.info("Certificates updated.")
            else:
                logging.info(
                    "[SIMULATION_MODE] Certificates simulation succeeded.")
        return True
Ejemplo n.º 13
0
from etld import get_eTLD_service
from base64 import b64decode

from java.security.cert import X509Certificate, CertificateFactory
from java.io import StringBufferInputStream
from javax.naming.ldap import LdapName

cert_factory = CertificateFactory.getInstance('X.509')
svc = get_eTLD_service()


class CertChainFilter:
    def redact_ee(self, ee):
        cert_data = b64decode(ee)
        x509_cert = cert_factory.generateCertificate(
            StringBufferInputStream(cert_data))
        dn = x509_cert.getSubjectDN().getName()
        LDAP_dn = LdapName(dn)
        redacted_ee = {}
        cn = ''
        for rdn in LDAP_dn.getRdns():
            if rdn.getType() == 'CN':
                cn = rdn.getValue()
        redacted_ee['redactedCN'] = svc.get_base_domain(cn)
        return redacted_ee

    def filter_document(self, document):
        failedCertChain = document['failedCertChain']
        try:
            if failedCertChain:
                document['failedCertChain'] = None