Example #1
1
    def validatecertificatesignature(self, signed_cert, signing_cert):
        """Given a cert signed by another cert, validates the signature."""
        # First the naive way -- note this does not check expiry / use etc.

        cert_signing = x509.load_pem_x509_certificate(ssl.DER_cert_to_PEM_cert(der_encoder.encode(signing_cert)).encode(), default_backend())

        public_key = cert_signing.public_key()

        der_cert = der_encoder.encode(signed_cert)
        cert_signed = x509.load_pem_x509_certificate(ssl.DER_cert_to_PEM_cert(der_cert).encode(), default_backend())

        data = cert_signed.tbs_certificate_bytes
        signature = cert_signed.signature

        new_api = hasattr(public_key, "verify")
        if not new_api:
            verifier = public_key.verifier(signature, padding.PKCS1v15(), cert_signed.signature_hash_algorithm)
            try:
                verifier.update(data)
                verifier.verify()
            except:
                raise Asn1Error('1: Validation of cert signature failed.')
        else:
            try:
                verifier = public_key.verify(signature, data, padding.PKCS1v15(), cert_signed.signature_hash_algorithm)
                # verifier.update(data)
                # verifier.verify()
            except:
                raise Asn1Error('1: Validation of cert signature failed.')
Example #2
0
def verify_renewable_cert_sig(renewable_cert):
    """ Verifies the signature of a `.storage.RenewableCert` object.

    :param `.storage.RenewableCert` renewable_cert: cert to verify

    :raises errors.Error: If signature verification fails.
    """
    try:
        with open(renewable_cert.chain, 'rb') as chain_file:  # type: IO[bytes]
            chain = x509.load_pem_x509_certificate(chain_file.read(), default_backend())
        with open(renewable_cert.cert, 'rb') as cert_file:  # type: IO[bytes]
            cert = x509.load_pem_x509_certificate(cert_file.read(), default_backend())
        pk = chain.public_key()
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            if isinstance(pk, RSAPublicKey):
                # https://github.com/python/typeshed/blob/master/third_party/2/cryptography/hazmat/primitives/asymmetric/rsa.pyi
                verifier = pk.verifier(  # type: ignore
                    cert.signature, PKCS1v15(), cert.signature_hash_algorithm
                )
                verifier.update(cert.tbs_certificate_bytes)
                verifier.verify()
            elif isinstance(pk, EllipticCurvePublicKey):
                verifier = pk.verifier(
                    cert.signature, ECDSA(cert.signature_hash_algorithm)
                )
                verifier.update(cert.tbs_certificate_bytes)
                verifier.verify()
            else:
                raise errors.Error("Unsupported public key type")
    except (IOError, ValueError, InvalidSignature) as e:
        error_str = "verifying the signature of the cert located at {0} has failed. \
                Details: {1}".format(renewable_cert.cert, e)
        logger.exception(error_str)
        raise errors.Error(error_str)
Example #3
0
def test_tls_basic_artifacts():

    # Load end-entity certificate from keystore and root CA cert from truststore
    stdout = sdk_cmd.service_task_exec(
        config.SERVICE_NAME, "artifacts-0-node", "cat secure-tls-pod.crt"
    )[1].encode("ascii")
    end_entity_cert = x509.load_pem_x509_certificate(stdout, DEFAULT_BACKEND)

    root_ca_cert_in_truststore = _export_cert_from_task_keystore(
        "artifacts-0-node", "keystore.truststore", "dcos-root"
    )

    # Check that certificate subject maches the service name
    common_name = end_entity_cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value
    assert common_name in sdk_hosts.autoip_host(config.SERVICE_NAME, "artifacts-0-node")

    san_extension = end_entity_cert.extensions.get_extension_for_oid(
        ExtensionOID.SUBJECT_ALTERNATIVE_NAME
    )
    sans = san_extension.value._general_names._general_names
    assert len(sans) == 1

    cluster_root_ca_cert = x509.load_pem_x509_certificate(
        transport_encryption.fetch_dcos_ca_bundle_contents(), DEFAULT_BACKEND
    )

    assert root_ca_cert_in_truststore.signature == cluster_root_ca_cert.signature
Example #4
0
def test_tls_basic_artifacts(hello_world_service):
    task_id = sdk_tasks.get_task_ids(config.SERVICE_NAME, 'artifacts')[0]
    assert task_id

    # Load end-entity certificate from keystore and root CA cert from truststore
    end_entity_cert = x509.load_pem_x509_certificate(
        task_exec(task_id, 'cat secure-tls-pod.crt').encode('ascii'),
        DEFAULT_BACKEND)

    root_ca_cert_in_truststore = _export_cert_from_task_keystore(
        task_id, 'keystore.truststore', 'dcos-root')

    # Check that certificate subject maches the service name
    common_name = end_entity_cert.subject.get_attributes_for_oid(
        NameOID.COMMON_NAME)[0].value
    assert common_name in sdk_hosts.autoip_host(config.SERVICE_NAME, 'artifacts-0-node')

    san_extension = end_entity_cert.extensions.get_extension_for_oid(
        ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
    sans = san_extension.value._general_names._general_names
    assert len(sans) == 1

    cluster_root_ca_cert = x509.load_pem_x509_certificate(
        sdk_cmd.request(
            'get', shakedown.dcos_url_path('/ca/dcos-ca.crt')).content,
        DEFAULT_BACKEND)

    assert root_ca_cert_in_truststore.signature == cluster_root_ca_cert.signature
Example #5
0
    def clean_pem(self):
        pem = self.cleaned_data['pem']

        try:
            backend = default_backend()
            x509.load_pem_x509_certificate(pem.encode(), backend)
        except Exception as e:
            raise forms.ValidationError('%s: %s' % (type(e).__name__, e))

        return pem
Example #6
0
def public_certificate(body):
    """
    Determines if specified string is valid public certificate.

    :param body:
    :return:
    """
    try:
        x509.load_pem_x509_certificate(bytes(body), default_backend())
    except Exception:
        raise ValidationError('Public certificate presented is not valid.')
def make_instance_config(values=None, brkt_env=None,
                         mode=INSTANCE_CREATOR_MODE):
    log.debug('Creating instance config with %s', brkt_env)

    brkt_config = {}
    if not values:
        return InstanceConfig(brkt_config, mode)

    if brkt_env:
        add_brkt_env_to_brkt_config(brkt_env, brkt_config)

    if values.token:
        brkt_config['identity_token'] = values.token

    if values.ntp_servers:
        brkt_config['ntp_servers'] = values.ntp_servers

    if mode in (INSTANCE_CREATOR_MODE, INSTANCE_UPDATER_MODE):
        brkt_config['status_port'] = (values.status_port or
                                    encryptor_service.ENCRYPTOR_STATUS_PORT)

    ic = InstanceConfig(brkt_config, mode)

    # Now handle the args that cause files to be added to brkt-files
    proxy_config = get_proxy_config(values)
    if proxy_config:
        ic.add_brkt_file('proxy.yaml', proxy_config)

    if 'ca_cert' in values and values.ca_cert:
        if mode != INSTANCE_CREATOR_MODE:
            raise ValidationError(
                'Can only specify ca-cert for instance in Creator mode'
            )
        if not values.brkt_env:
            raise ValidationError(
                'Must specify brkt-env when specifying ca-cert.'
            )
        try:
            with open(values.ca_cert, 'r') as f:
                ca_cert_data = f.read()
        except IOError as e:
            raise ValidationError(e)
        try:
            x509.load_pem_x509_certificate(ca_cert_data, default_backend())
        except Exception as e:
            raise ValidationError('Error validating CA cert: %s' % e)

        domain = get_domain_from_brkt_env(brkt_env)

        ca_cert_filename = 'ca_cert.pem.' + domain
        ic.add_brkt_file(ca_cert_filename, ca_cert_data)

    return ic
Example #8
0
def test_changing_discovery_replaces_certificate_sans(hello_world_service):
    """
    Update service configuration to change discovery prefix of a task.
    Scheduler should update task and new SANs should be generated.
    """
    original_tasks = sdk_tasks.get_task_ids(config.PACKAGE_NAME, 'discovery')
    assert len(original_tasks) == 1, 'Expecting exactly one task ID'

    task_id = original_tasks[0]
    assert task_id

    # Load end-entity certificate from PEM encoded file
    end_entity_cert = x509.load_pem_x509_certificate(
        task_exec(task_id, 'cat server.crt').encode('ascii'),
        DEFAULT_BACKEND)

    san_extension = end_entity_cert.extensions.get_extension_for_oid(
        ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
    sans = [
        san.value for san in san_extension.value._general_names._general_names]

    expected_san = (
        '{name}-0.{service_name}.autoip.dcos.thisdcos.directory'.format(
            name=DISCOVERY_TASK_PREFIX,
            service_name=config.SERVICE_NAME)
        )
    assert expected_san in sans

    # Run task update with new discovery prefix
    marathon_config = sdk_marathon.get_config(config.SERVICE_NAME)
    marathon_config['env']['DISCOVERY_TASK_PREFIX'] = DISCOVERY_TASK_PREFIX + '-new'
    sdk_marathon.update_app(config.SERVICE_NAME, marathon_config)
    sdk_tasks.check_tasks_updated(config.SERVICE_NAME, 'discovery', original_tasks)
    sdk_tasks.check_running(config.SERVICE_NAME, 4)
    new_task_id = sdk_tasks.get_task_ids(config.SERVICE_NAME, "discovery")[0]
    assert task_id != new_task_id

    new_cert = x509.load_pem_x509_certificate(
        task_exec(new_task_id, 'cat server.crt').encode('ascii'),
        DEFAULT_BACKEND)

    san_extension = new_cert.extensions.get_extension_for_oid(
        ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
    sans = [
        san.value for san in san_extension.value._general_names._general_names]

    expected_san =  (
        '{name}-0.{service_name}.autoip.dcos.thisdcos.directory'.format(
            name=DISCOVERY_TASK_PREFIX + '-new',
            service_name=config.SERVICE_NAME)
        )
    assert expected_san in sans
Example #9
0
    def __setstate__(self, state: Dict[str, Any]) -> None:
        self.__dict__.update(state)
        # Manually restore non-pickable entries
        self.__dict__['successful_trust_store'] = pickle.loads(self.__dict__['successful_trust_store'])
        self.__dict__['path_validation_result_list'] = pickle.loads(self.__dict__['path_validation_result_list'])

        certificate_chain = [load_pem_x509_certificate(cert_pem, default_backend())
                             for cert_pem in self.__dict__['certificate_chain']]
        self.__dict__['certificate_chain'] = certificate_chain

        verified_chain = [load_pem_x509_certificate(cert_pem, default_backend())
                          for cert_pem in self.__dict__['verified_certificate_chain']]
        self.__dict__['verified_certificate_chain'] = verified_chain
Example #10
0
File: views.py Project: m4c3/lemur
def pem_str(value, name):
    """
    Used to validate that the given string is a PEM formatted string

    :param value:
    :param name:
    :return: :raise ValueError:
    """
    try:
        x509.load_pem_x509_certificate(bytes(value), default_backend())
    except Exception:
        raise ValueError("The parameter '{0}' needs to be a valid PEM string".format(name))
    return value
Example #11
0
def test_changing_discovery_replaces_certificate_sans():
    """
    Update service configuration to change discovery prefix of a task.
    Scheduler should update task and new SANs should be generated.
    """

    # Load end-entity certificate from PEM encoded file
    _, stdout, _ = sdk_cmd.service_task_exec(
        config.SERVICE_NAME, "discovery-0-node", "cat server.crt"
    )
    log.info("first server.crt: {}".format(stdout))

    ascii_cert = stdout.encode("ascii")
    log.info("first server.crt ascii encoded: {}".format(ascii_cert))

    end_entity_cert = x509.load_pem_x509_certificate(ascii_cert, DEFAULT_BACKEND)

    san_extension = end_entity_cert.extensions.get_extension_for_oid(
        ExtensionOID.SUBJECT_ALTERNATIVE_NAME
    )
    sans = [san.value for san in san_extension.value._general_names._general_names]

    expected_san = "{name}-0.{service_name}.autoip.dcos.thisdcos.directory".format(
        name=DISCOVERY_TASK_PREFIX, service_name=config.SERVICE_NAME
    )
    assert expected_san in sans

    # Run task update with new discovery prefix
    marathon_config = sdk_marathon.get_config(config.SERVICE_NAME)
    marathon_config["env"]["DISCOVERY_TASK_PREFIX"] = DISCOVERY_TASK_PREFIX + "-new"
    sdk_marathon.update_app(marathon_config)
    sdk_plan.wait_for_completed_deployment(config.SERVICE_NAME)

    _, stdout, _ = sdk_cmd.service_task_exec(
        config.SERVICE_NAME, "discovery-0-node", "cat server.crt"
    )
    log.info("second server.crt: {}".format(stdout))

    ascii_cert = stdout.encode("ascii")
    log.info("second server.crt ascii encoded: {}".format(ascii_cert))
    new_cert = x509.load_pem_x509_certificate(ascii_cert, DEFAULT_BACKEND)

    san_extension = new_cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
    sans = [san.value for san in san_extension.value._general_names._general_names]

    expected_san = "{name}-0.{service_name}.autoip.dcos.thisdcos.directory".format(
        name=DISCOVERY_TASK_PREFIX + "-new", service_name=config.SERVICE_NAME
    )
    assert expected_san in sans
def add_certificate_to_elb(logger, elb_client, iam_client, elb_name, elb_port,
                           hosts, private_key, pem_certificate,
                           pem_certificate_chain):
    logger.emit("updating-elb.upload-iam-certificate", elb_name=elb_name)
    response = iam_client.upload_server_certificate(
        ServerCertificateName=generate_certificate_name(
            hosts,
            x509.load_pem_x509_certificate(pem_certificate, default_backend())
        ),
        PrivateKey=private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption(),
        ),
        CertificateBody=pem_certificate,
        CertificateChain=pem_certificate_chain,
    )
    new_cert_arn = response["ServerCertificateMetadata"]["Arn"]

    # Sleep before trying to set the certificate, it appears to sometimes fail
    # without this.
    time.sleep(15)
    logger.emit("updating-elb.set-elb-certificate", elb_name=elb_name)
    elb_client.set_load_balancer_listener_ssl_certificate(
        LoadBalancerName=elb_name,
        SSLCertificateId=new_cert_arn,
        LoadBalancerPort=elb_port,
    )
Example #13
0
    def __init__(self, signature_element, keyspec):
        source = None
        data = None
        #print "XMLSecCryptoFromXML using %s and keyspec=%s" % (signature_element, keyspec)
        fp = keyspec
        if ':' not in keyspec:
            fp,_ = _cert_fingerprint(keyspec)
        cd = _find_cert_by_fingerprint(signature_element, fp)
        if cd is not None:
            data = cd
            source = 'signature_element'
        elif '-----BEGIN' in keyspec:
            data = keyspec
            source = 'keyspec'

        if data is None:
            raise ValueError("Unable to find cert matching fingerprint: %s" % fp)

        super(XMLSecCryptoFromXML, self).__init__(source=source, do_padding=False, private=False, do_digest=False)

        self.key = load_pem_x509_certificate(data, backend=default_backend())
        if not isinstance(self.key.public_key(), rsa.RSAPublicKey):
            raise XMLSigException("We don't support non-RSA public keys at the moment.")

        # XXX now we could implement encrypted-PEM-support
        self.cert_pem = self.key.public_bytes(encoding=serialization.Encoding.PEM)

        self.keysize = self.key.public_key().key_size
        self._from_keyspec = keyspec  # for debugging
Example #14
0
def get_host_names(certificate):
    """Extract the host names from the Pem encoded X509 certificate

    :param certificate: A PEM encoded certificate
    :returns: A dictionary containing the following keys:
    ['cn', 'dns_names']
    where 'cn' is the CN from the SubjectName of the certificate, and
    'dns_names' is a list of dNSNames (possibly empty) from
    the SubjectAltNames of the certificate.
    """
    try:
        certificate = certificate.encode("ascii")

        cert = x509.load_pem_x509_certificate(certificate, backends.default_backend())
        cn = cert.subject.get_attributes_for_oid(x509.OID_COMMON_NAME)[0]
        host_names = {"cn": cn.value.lower(), "dns_names": []}
        try:
            ext = cert.extensions.get_extension_for_oid(x509.OID_SUBJECT_ALTERNATIVE_NAME)
            host_names["dns_names"] = ext.value.get_values_for_type(x509.DNSName)
        except x509.ExtensionNotFound:
            LOG.debug("%s extension not found", x509.OID_SUBJECT_ALTERNATIVE_NAME)

        return host_names
    except Exception:
        LOG.exception(_LE("Unreadable certificate."))
        raise exceptions.UnreadableCert
Example #15
0
def load_certificate(path):
    _, ext = os.path.splitext(path)
    with open(path, "rb") as f:
        if ext == ".pem":
            return x509.load_pem_x509_certificate(f.read(), default_backend())
        else:
            return x509.load_der_x509_certificate(f.read(), default_backend())
Example #16
0
    def test_generate_cert_key_pair(self):
        cn = 'testCN'
        bit_length = 512

        # Attempt to generate a cert/key pair
        cert_object = self.cert_generator.generate_cert_key_pair(
            cn=cn,
            validity=2 * 365 * 24 * 60 * 60,
            bit_length=bit_length,
            passphrase=self.ca_private_key_passphrase,
            ca_cert=self.ca_certificate,
            ca_key=self.ca_private_key,
            ca_key_pass=self.ca_private_key_passphrase
        )

        # Validate that the cert and key are loadable
        cert = x509.load_pem_x509_certificate(
            data=cert_object.certificate, backend=backends.default_backend())
        self.assertIsNotNone(cert)

        key = serialization.load_pem_private_key(
            data=cert_object.private_key,
            password=cert_object.private_key_passphrase,
            backend=backends.default_backend())
        self.assertIsNotNone(key)
Example #17
0
 def ParseFromString(self, string):
     try:
         self._value = x509.load_pem_x509_certificate(string, backend=openssl.backend)
     except (ValueError, TypeError) as e:
         raise rdfvalue.DecodeError("Invalid certificate %s: %s" % (string, e))
     # This can also raise if there isn't exactly one CN entry.
     self.GetCN()
Example #18
0
def _determine_ocsp_server(cert_path):
    # type: (str) -> Tuple[Optional[str], Optional[str]]
    """Extract the OCSP server host from a certificate.

    :param str cert_path: Path to the cert we're checking OCSP for
    :rtype tuple:
    :returns: (OCSP server URL or None, OCSP server host or None)

    """
    with open(cert_path, 'rb') as file_handler:
        cert = x509.load_pem_x509_certificate(file_handler.read(), default_backend())
    try:
        extension = cert.extensions.get_extension_for_class(x509.AuthorityInformationAccess)
        ocsp_oid = x509.AuthorityInformationAccessOID.OCSP
        descriptions = [description for description in extension.value
                        if description.access_method == ocsp_oid]

        url = descriptions[0].access_location.value
    except (x509.ExtensionNotFound, IndexError):
        logger.info("Cannot extract OCSP URI from %s", cert_path)
        return None, None

    url = url.rstrip()
    host = url.partition("://")[2].rstrip("/")

    if host:
        return url, host
    logger.info("Cannot process OCSP host from URL (%s) in cert at %s", url, cert_path)
    return None, None
Example #19
0
    def _get_and_verify_certificate_chain(
            server_info: ServerConnectivityInfo,
            trust_store: TrustStore
    ) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
        """Connects to the target server and uses the supplied trust store to validate the server's certificate.
        Returns the server's certificate and OCSP response.
        """
        ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)

        # Enable OCSP stapling
        ssl_connection.ssl_client.set_tlsext_status_ocsp()

        try:  # Perform the SSL handshake
            ssl_connection.connect()

            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        except ClientCertificateRequested:  # The server asked for a client cert
            # We can get the server cert anyway
            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        finally:
            ssl_connection.close()

        # Parse the certificates using the cryptography module
        parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
                             for x509_cert in x509_cert_chain]
        return parsed_x509_chain, verify_str, ocsp_response
def regenerate_certificate_revocation_list(self, certification_authority):
    logger.info("Updating CRL for CA %s" % certification_authority.common_name)
    one_day = datetime.timedelta(1, 0, 0)
    ca_cert =  x509.load_pem_x509_certificate(str(certification_authority.certificate), default_backend())
    ca_key =  serialization.load_pem_private_key(str(certification_authority.private_key), None, default_backend())

    builder = x509.CertificateRevocationListBuilder()
    builder = builder.issuer_name(ca_cert.subject)
    builder = builder.last_update(datetime.datetime.today())
    builder = builder.next_update(datetime.datetime.today() + one_day)

    for certificate in SSLRevokedCertificate.objects.filter(certification_authority=certification_authority):
        logger.info("Adding certificate 0x%X" % certificate.serial_number)
        revoked_cert = x509.RevokedCertificateBuilder().serial_number(
            certificate.serial_number
        ).revocation_date(
            certificate.revocation_date.replace(tzinfo=None)
        ).build(default_backend())

        builder = builder.add_revoked_certificate(revoked_cert)
    crl = builder.sign(
        private_key=ca_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )

    logger.info('Saving models')
    certification_authority.revocation_list = crl.public_bytes(serialization.Encoding.PEM)
    print certification_authority.revocation_list
    certification_authority.save()
Example #21
0
File: oauth.py Project: pudo/aleph
def handle_azure_oauth(sender, provider=None, oauth=None):
    from aleph.model import Role
    if 'login.microsoftonline.com' not in provider.base_url:
        return

    # Get incoming token, extract header for use with certificate verification
    id_token = oauth.get('id_token')
    headerbit = id_token.split('.')[0]
    headerbit = base64.b64decode(headerbit).decode('utf8')
    headerbit = json.loads(headerbit)

    # Load cert from MS - can be cached for upwards of 24hrs, not done now
    cert_loc = 'https://login.microsoftonline.com/common/discovery/keys'
    cert_data = json.loads(urlopen(cert_loc).read())
    pemstart = "-----BEGIN CERTIFICATE-----\n"
    pemend = "\n-----END CERTIFICATE-----\n"
    # Find correct cert based on header
    for key in cert_data['keys']:
        if headerbit['kid'] == key['kid'] and headerbit['x5t'] == key['x5t']:
            mspubkey = key['x5c'][0]
            break
    cert_str = pemstart + mspubkey + pemend
    cert_obj = load_pem_x509_certificate(cert_str.encode('ascii'),
                                         default_backend())
    public_key = cert_obj.public_key()

    # Decode incoming token and verify against the MS cert
    token_data = jwt.decode(id_token, public_key, verify=True,
                            audience=settings.OAUTH_KEY)

    # All Ok, move on
    user_id = 'azure:%s' % token_data['upn']
    return Role.load_or_create(user_id, Role.USER, token_data['name'],
                               email=token_data['upn'])
Example #22
0
def test_sct_embedding():
    if not os.environ.get('BOULDER_CONFIG_DIR', '').startswith("test/config-next"):
        return
    order = chisel2.auth_and_issue([random_domain()])
    cert = x509.load_pem_x509_certificate(str(order.fullchain_pem), default_backend())

    # make sure there is no poison extension
    try:
        cert.extensions.get_extension_for_oid(x509.ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3"))
        raise Exception("certificate contains CT poison extension")
    except x509.ExtensionNotFound:
        # do nothing
        pass

    # make sure there is a SCT list extension
    try:
        sctList = cert.extensions.get_extension_for_oid(x509.ObjectIdentifier("1.3.6.1.4.1.11129.2.4.2"))
    except x509.ExtensionNotFound:
        raise Exception("certificate doesn't contain SCT list extension")
    if len(sctList.value) != 2:
        raise Exception("SCT list contains wrong number of SCTs")
    for sct in sctList.value:
        if sct.version != x509.certificate_transparency.Version.v1:
            raise Exception("SCT contains wrong version")
        if sct.entry_type != x509.certificate_transparency.LogEntryType.PRE_CERTIFICATE:
            raise Exception("SCT contains wrong entry type")
Example #23
0
def _match_certificate(matcher):
    return MatchesAny(
        Not(IsInstance(Certificate)),
        AfterPreprocessing(
            lambda c: x509.load_pem_x509_certificate(
                c.as_bytes(), default_backend()),
            matcher))
Example #24
0
    def _get_rsa_parameters(
            server_info: ServerConnectivityInfo,
            openssl_cipher_string: str
    ) -> Optional[Tuple[int, int]]:
        ssl_connection = server_info.get_preconfigured_ssl_connection()
        ssl_connection.ssl_client.set_cipher_list(openssl_cipher_string)
        parsed_cert = None
        try:
            # Perform the SSL handshake
            ssl_connection.connect()
            certificate = ssl_connection.ssl_client.get_peer_certificate()
            parsed_cert = load_pem_x509_certificate(certificate.as_pem().encode('ascii'), backend=default_backend())
        except SslHandshakeRejected:
            # Server does not support RSA cipher suites?
            pass
        except ClientCertificateRequested:
            # AD: The server asked for a client cert. We could still retrieve the server certificate, but it is unclear
            # to me if the ROBOT check is supposed to work even if we do not provide a client cert. My guess is that
            # it should not work since it requires completing a full handshake, which we can't without a client cert.
            # Hence, propagate the error to make the check fail.
            raise
        finally:
            ssl_connection.close()

        if parsed_cert:
            return parsed_cert.public_key().public_numbers().n, parsed_cert.public_key().public_numbers().e
        else:
            return None
Example #25
0
def print_block(pemData):
    substrate = pem.readPemFromFile(io.StringIO(pemData.decode("utf-8")))
    cert, rest = decoder.decode(substrate, asn1Spec=rfc5280.Certificate())
    der_subject = encoder.encode(cert['tbsCertificate']['subject'])
    octets = hex_string_for_struct(der_subject)

    cert = x509.load_pem_x509_certificate(pemData, default_backend())
    common_name = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0]
    block_name = "CA{}DN".format(re.sub(r'[-:=_. ]', '', common_name.value))

    fingerprint = hex_string_human_readable(cert.fingerprint(hashes.SHA256()))

    dn_parts = ["/{id}={value}".format(id=nameOIDtoString(part.oid),
                                       value=part.value) for part in cert.subject]
    distinguished_name = "".join(dn_parts)

    print("// {dn}".format(dn=distinguished_name))
    print("// SHA256 Fingerprint: " + ":".join(fingerprint[:16]))
    print("//                     " + ":".join(fingerprint[16:]))
    print("// https://crt.sh/?id={crtsh} (crt.sh ID={crtsh})"
          .format(crtsh=crtshId))
    print("static const uint8_t {}[{}] = ".format(block_name, len(octets)) + "{")

    while len(octets) > 0:
        print("  " + ", ".join(octets[:13]) + ",")
        octets = octets[13:]

    print("};")
    print()

    return block_name
Example #26
0
def _export_cert_from_task_keystore(task_name, keystore_path, alias, password=KEYSTORE_PASS):
    """
    Retrieves certificate from the keystore with given alias by executing
    a keytool in context of running container and loads the certificate to
    memory.

    Args:
        task (str): Task id of container that contains the keystore
        keystore_path (str): Path inside container to keystore containing
            the certificate
        alias (str): Alias of the certificate in the keystore

    Returns:
        x509.Certificate object
    """
    args = ["-rfc"]
    if password:
        args.append('-storepass "{password}"'.format(password=password))

    args_str = " ".join(args)

    cert_bytes = sdk_cmd.service_task_exec(
        config.SERVICE_NAME, task_name, _keystore_export_command(keystore_path, alias, args_str)
    )[1].encode("ascii")

    return x509.load_pem_x509_certificate(cert_bytes, DEFAULT_BACKEND)
Example #27
0
def cert2user(buf):
    if not buf: return # No certificate supplied
    crt = x509.load_pem_x509_certificate(buf, backend=default_backend())
    for name in crt.subject:
        if name.oid == NameOID.GIVEN_NAME:
            gn = name.value
        elif name.oid == NameOID.SURNAME:
            sn = name.value
        elif name.oid == NameOID.SERIAL_NUMBER:
            serial = name.value
    try:
        return User.objects.get(username=serial)
    except User.DoesNotExist:
        for extension in crt.extensions:
            if extension.oid == ExtensionOID.SUBJECT_ALTERNATIVE_NAME:
                for name in extension.value:
                    if isinstance(name, RFC822Name):
                        email = name.value
        user = User.objects.create(
            email = email,
            first_name = gn,
            last_name = sn,
            username = serial)
        if user.id == 1:
            user.is_superuser = True
            user.save()
        return user
Example #28
0
 def get_cert_serial(self):
     if self.cert is not None:
         x509cert = x509.load_pem_x509_certificate(self.get_cert(),
                                                   backends.default_backend())
         return x509cert.serial
     else:
         return None
Example #29
0
    def _load_pems(self, keypairs, encryption_password):
        private_key = serialization.load_pem_private_key(
            keypairs["private_key"], password=encryption_password, backend=default_backend()
        )
        certificate = c_x509.load_pem_x509_certificate(keypairs["certificate"], default_backend())

        return certificate, private_key
Example #30
0
def _deserialize_certificate(cert_str):
    from cryptography import x509
    from cryptography.hazmat.backends import default_backend

    return x509.load_pem_x509_certificate(
        cert_str, backend=default_backend()
    )
Example #31
0
    def handshake_pkt_recv(self, pkt):
        if pkt.status == 2:
            print("ERROR PACKET")
            #self.transport.close()

        elif self.status == "LISTEN":  # server get the first packet
            if pkt.cert and pkt.pk and pkt.signature:
                if pkt.status == 0:
                    print(self.root_public_key)
                    print("recvive client's first handshake packet")
                    self.peer_verikey = x509.load_pem_x509_certificate(
                        pkt.cert, default_backend()).public_key()
                    self.peer_public_key = load_pem_public_key(
                        pkt.pk, backend=default_backend())
                    if self.verify_signature(pkt) and self.verify_chain(
                            pkt.certChain) and self.verify_cert(pkt.cert):
                        #verify
                        # verify the signiature  fail: send error else:pass
                        # generate its own ECDH public key

                        nonce_sig = self.generate_signature(
                            self.signing_key, pkt.nonce)

                        #self.shared_key = self.private_key.exchange(ec.ECDH(), load_pem_public_key(pkt.pk, backend=default_backend()))
                        #self.derived_key = self.get_derived_key(self.shared_key)
                        #self.generate_communicatekey(self.shared_key)
                        #self.higherProtocol().connection_made(self.higher_transport)

                        pktstatus = 1
                        sendpkt = HandshakePacket(
                            status=pktstatus,
                            nonceSignature=nonce_sig,
                            pk=self.public_bytes(self.public_key, "pk"),
                            signature=self.signature,
                            cert=self.public_bytes(self.certificate, "cert"),
                            nonce=self.nonce,
                            certChain=[self.team2_certification_bytes])
                        self.transport.write(sendpkt.__serialize__())
                        print("send server first packet")
                        self.status = "HS_SENT"
                        return
                    else:
                        self.send_error_handshake_pkt()
                        #self.higherProtocol().connection_lost(None)
                        #self.transport.close()
                        return
                elif pkt.status == 1:
                    print(
                        "handshake packet status shouldn't be 1 when the server status is LISTEN"
                    )
                    self.send_error_handshake_pkt()
                    return
            else:
                print("miss handshake field")
                self.send_error_handshake_pkt()
                return
        elif self.status == "HS_SENT":  #client and server already sent the first packet
            print("HS_SENT")
            if pkt.status == 1:
                if self.mode == "client":
                    print("client handshake made")
                    self.peer_verikey = x509.load_pem_x509_certificate(
                        pkt.cert, default_backend()).public_key()
                    self.peer_public_key = load_pem_public_key(
                        pkt.pk, backend=default_backend())
                    if self.verify_signature(pkt) and self.verify_nonce(
                            pkt) and self.verify_chain(
                                pkt.certChain) and self.verify_cert(pkt.cert):
                        print("verify nonce and signature")
                        self.shared_key = self.private_key.exchange(
                            ec.ECDH(), self.peer_public_key)
                        self.derived_key = self.get_derived_key(
                            self.shared_key)

                        nonce_sig = self.generate_signature(
                            self.signing_key, pkt.nonce)

                        sendpkt = HandshakePacket(status=1,
                                                  nonceSignature=nonce_sig)
                        self.transport.write(pkt.__serialize__())
                        self.status = "ESTABILISHED"
                        self.generate_communicatekey(self.shared_key)
                        self.higherProtocol().connection_made(
                            self.higher_transport)
                        print("sent 2 packet")
                    else:
                        self.send_error_handshake_pkt()
                        return
                else:
                    if self.verify_nonce(pkt):
                        self.shared_key = self.private_key.exchange(
                            ec.ECDH(), self.peer_public_key)
                        self.derived_key = self.get_derived_key(
                            self.shared_key)
                        print("server handshake made")
                        self.status = "ESTABILISHED"
                        self.generate_communicatekey(self.shared_key)
                        self.higherProtocol().connection_made(
                            self.higher_transport)
                    else:
                        self.send_error_handshake_pkt()
                        return

        else:
            self.send_error_handshake_pkt()
            return
Example #32
0
 def _parse_certificate(self, certificate):
     certificate_object = x509.load_pem_x509_certificate(
         certificate, default_backend()
     )
     return certificate_object
def get_remote_cert_fingerprint(host: str, port: int):
    pem_data = ssl.get_server_certificate((host, port))
    cert = x509.load_pem_x509_certificate(pem_data.encode(), default_backend())
    return cert.fingerprint(hashes.SHA256())
    def renew_cert(self, request, reuse_key=False):
        if not request.id and not request.thumbprint:
            log.debug("Request id or thumbprint must be specified for TPP")
            raise CertificateRenewError
        if not request.id and request.thumbprint:
            request.id = self.search_by_thumbprint(request.thumbprint)

        if reuse_key:
            log.debug(f"Trying to renew certificate {request.id}")
            # TODO: Change _post() with post(args)
            status, data = self._post(URLS.CERTIFICATE_RENEW,
                                      data={'CertificateDN': request.id})
            if not data['Success']:
                raise CertificateRenewError
            return

        cert = self.retrieve_cert(request)
        cert = x509.load_pem_x509_certificate(cert.cert.encode(),
                                              default_backend())
        for a in cert.subject:
            if a.oid == x509.NameOID.COMMON_NAME:
                request.common_name = a.value
            elif a.oid == x509.NameOID.COUNTRY_NAME:
                request.country = a.value
            elif a.oid == x509.NameOID.LOCALITY_NAME:
                request.locality = a.value
            elif a.oid == x509.NameOID.STATE_OR_PROVINCE_NAME:
                request.province = a.value
            elif a.oid == x509.NameOID.ORGANIZATION_NAME:
                request.organization = a.value
            elif a.oid == x509.NameOID.ORGANIZATIONAL_UNIT_NAME:
                request.organizational_unit = a.value
        for e in cert.extensions:
            dns = []
            emails = []
            ips = []
            upns = []
            uris = []
            if e.oid == x509.OID_SUBJECT_ALTERNATIVE_NAME:
                for x in e.value:
                    if isinstance(x, x509.DNSName):
                        dns.append(x.value)
                    elif isinstance(x, x509.RFC822Name):
                        emails.append(x.value)
                    elif isinstance(x, x509.IPAddress):
                        ips.append(x.value)
                    elif isinstance(x, x509.OtherName):
                        # remove header bytes from ASN1 encoded UPN field before setting it in the request object
                        upns.append(x.value[2::])
                    elif isinstance(x, x509.UniformResourceIdentifier):
                        uris.append(x.value)
                # request.san_dns = list([x.value for x in e.value if isinstance(x, x509.DNSName)])
                # request.email_addresses = list([x.value for x in e.value if isinstance(x, x509.RFC822Name)])
                # request.ip_addresses = list([x.value.exploded for x in e.value if isinstance(x, x509.IPAddress)])
                # remove header bytes from ASN1 encoded UPN field before setting it in the request object
                # upns = []
                # for x in e.value:
                #     if isinstance(x, x509.OtherName):
                #         upns.append(x.value[2::])
                # request.user_principal_names = upns
                # request.uniform_resource_identifiers = \
                #     list([x.value for x in e.value if isinstance(x, x509.UniformResourceIdentifier)])
            request.san_dns = dns
            request.email_addresses = emails
            request.ip_addresses = ips
            request.user_principal_names = upns
            request.uniform_resource_identifiers = uris

        if request.csr_origin == CSR_ORIGIN_LOCAL:
            if cert.signature_algorithm_oid in (AlgOID.ECDSA_WITH_SHA1,
                                                AlgOID.ECDSA_WITH_SHA224,
                                                AlgOID.ECDSA_WITH_SHA256,
                                                AlgOID.ECDSA_WITH_SHA384,
                                                AlgOID.ECDSA_WITH_SHA512):
                request.key_type = (KeyType.ECDSA, KeyType.ALLOWED_CURVES[0])
            else:
                request.key_type = KeyType(KeyType.RSA,
                                           2048)  # todo: make parsing key size
            request.build_csr()

        request_data = {'CertificateDN': request.id}
        if request.csr_origin in [CSR_ORIGIN_PROVIDED, CSR_ORIGIN_LOCAL]:
            request_data['PKCS10'] = request.csr
        elif request.csr_origin == CSR_ORIGIN_SERVICE:
            request_data['Subject'] = request.common_name
            request_data['SubjectAltNames'] = self.wrap_alt_names(request)

        # TODO: Change _post() with post(args)
        status, data = self._post(URLS.CERTIFICATE_RENEW, data=request_data)
        if status == HTTPStatus.OK:
            if 'CertificateDN' in data:
                request.id = data['CertificateDN']
            log.debug(
                f"Certificate successfully requested with request id {request.id}"
            )
            return True

        log.error(f"Request status is not {HTTPStatus.OK}. {status}")
        raise CertificateRequestError
Example #35
0
 def set_state(self, state):
     self._cert = x509.load_pem_x509_certificate(state)
Example #36
0
def create_rtclient(cn, rtclient_file, rtclient_key_file, signer_file,
                    signer_key_file):
    # Make sure files exist
    if not (os.path.isfile(signer_file) and os.path.isfile(signer_key_file)):
        raise FileNotFoundError('Failed to find {}, {}, or {}'.format(
            signer_file, signer_key_file))

    # Setup cryptography
    be = cryptography.hazmat.backends.default_backend()

    # Create client cert key pair
    #print('\nrtclient Cert key')
    rtclient_priv_key = load_or_create_key(rtclient_key_file, backend=be)

    #print('\nLoad Signer')
    # Load the Signing key from the file
    #print('    Loading key from %s' % signer_key_file)
    with open(signer_key_file, 'rb') as f:
        signer_ca_priv_key = serialization.load_pem_private_key(data=f.read(),
                                                                password=None,
                                                                backend=be)

    # Load the Signing Certificate from the file
    #print('    Loading certificate from %s' % signer_file)
    with open(signer_file, 'rb') as f:
        signer_ca_cert = x509.load_pem_x509_certificate(f.read(), be)

    # Build certificate
    #print('\nCreate rtclient Certificate')
    builder = x509.CertificateBuilder()

    builder = builder.issuer_name(signer_ca_cert.subject)

    # Device cert must have minutes and seconds set to 0
    builder = builder.not_valid_before(
        datetime.datetime.now(tz=pytz.utc).replace(minute=0, second=0))

    # Should be year 9999, but this doesn't work on windows
    builder = builder.not_valid_after(
        datetime.datetime(3000, 12, 31, 23, 59, 59))

    builder = builder.subject_name(
        x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, cn)]))

    builder = builder.public_key(rtclient_priv_key.public_key())

    # Device certificate is generated from certificate dates and public key
    builder = builder.serial_number(cert_sn(16, builder))

    # specific for client cert
    builder = builder.add_extension(x509.BasicConstraints(ca=False,
                                                          path_length=None),
                                    critical=False)

    builder = builder.add_extension(x509.KeyUsage(digital_signature=True,
                                                  content_commitment=True,
                                                  key_encipherment=True,
                                                  data_encipherment=False,
                                                  key_agreement=False,
                                                  key_cert_sign=False,
                                                  crl_sign=False,
                                                  encipher_only=False,
                                                  decipher_only=False),
                                    critical=False)

    builder = builder.add_extension(x509.ExtendedKeyUsage(
        [x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH]),
                                    critical=False)

    # Sign certificate
    rtclient_cert = builder.sign(private_key=signer_ca_priv_key,
                                 algorithm=hashes.SHA256(),
                                 backend=be)

    # Save certificate for reference
    #print('    Save rtclient Certificate to %s' % rtclient_file)
    with open(rtclient_file, 'wb') as f:
        f.write(
            rtclient_cert.public_bytes(encoding=serialization.Encoding.PEM))
        print('rtclientcert create success')
Example #37
0
def pem_to_cert(pem: str):
    return x509.load_pem_x509_certificate(pem.encode(), default_backend())
Example #38
0
    def __init__(self, server_address, RequestHandlerClass, agent_uuid,
                 contact_ip, ima_log_file, tpm_log_file_data):
        """Constructor overridden to provide ability to pass configuration arguments to the server"""
        # Find the locations for the U/V transport and mTLS key and certificate.
        # They are either relative to secdir (/var/lib/keylime/secure) or absolute paths.
        secdir = secure_mount.mount()
        keyname = config.get('cloud_agent', 'rsa_keyname')
        if not os.path.isabs(keyname):
            keyname = os.path.join(secdir, keyname)

        # read or generate the key depending on configuration
        if os.path.isfile(keyname):
            # read in private key
            logger.info("Using existing key in %s", keyname)
            with open(keyname, "rb") as f:
                rsa_key = crypto.rsa_import_privkey(f.read())
        else:
            logger.info(
                "Key for U/V transport and mTLS certificate not found, generating a new one"
            )
            rsa_key = crypto.rsa_generate(2048)
            with open(keyname, "wb") as f:
                f.write(crypto.rsa_export_privkey(rsa_key))

        self.rsakey_path = keyname
        self.rsaprivatekey = rsa_key
        self.rsapublickey_exportable = crypto.rsa_export_pubkey(
            self.rsaprivatekey)

        self.mtls_cert_enabled = config.getboolean('cloud_agent',
                                                   'mtls_cert_enabled',
                                                   fallback=False)
        if self.mtls_cert_enabled:
            certname = config.get('cloud_agent', 'mtls_cert')

            if not os.path.isabs(certname):
                certname = os.path.join(secdir, certname)

            if os.path.isfile(certname):
                logger.info("Using existing mTLS cert in %s", certname)
                with open(certname, "rb") as f:
                    mtls_cert = x509.load_pem_x509_certificate(
                        f.read(), backend=default_backend())
            else:
                logger.info("No mTLS certificate found, generating a new one")
                agent_ips = [server_address[0]]
                if contact_ip is not None:
                    agent_ips.append(contact_ip)
                with open(certname, "wb") as f:
                    # By default generate a TLS certificate valid for 5 years
                    valid_util = datetime.datetime.utcnow(
                    ) + datetime.timedelta(days=(360 * 5))
                    mtls_cert = crypto.generate_selfsigned_cert(
                        agent_uuid, rsa_key, valid_util, agent_ips)
                    f.write(mtls_cert.public_bytes(serialization.Encoding.PEM))

            self.mtls_cert_path = certname
            self.mtls_cert = mtls_cert
        else:
            self.mtls_cert_path = None
            self.mtls_cert = None
            logger.info(
                "WARNING: mTLS disabled, Tenant and Verifier will reach out to agent via HTTP"
            )

        # attempt to get a U value from the TPM NVRAM
        nvram_u = tpm_instance.read_key_nvram()
        if nvram_u is not None:
            logger.info("Existing U loaded from TPM NVRAM")
            self.add_U(nvram_u)
        http.server.HTTPServer.__init__(self, server_address,
                                        RequestHandlerClass)
        self.enc_keyname = config.get('cloud_agent', 'enc_keyname')
        self.agent_uuid = agent_uuid
        self.ima_log_file = ima_log_file
        self.tpm_log_file_data = tpm_log_file_data
def get_cert_fingerprint(cert_path):
    with open(cert_path) as pem_data:
        cert = x509.load_pem_x509_certificate(pem_data.read().encode(),
                                              default_backend())
        return cert.fingerprint(hashes.SHA256())
Example #40
0
 def parse_vmc_cert(self, pem_data):
     return x509.load_pem_x509_certificate(pem_data, default_backend())
Example #41
0
def convert_bytes_to_cert(bytes_cert: bytes) -> dict:
    cert = None
    try:
        cert = x509.load_der_x509_certificate(bytes_cert, default_backend())
    except BaseException:
        try:
            cert = x509.load_pem_x509_certificate(bytes_cert, default_backend())
        except BaseException:
            pass

    if cert:
        result = {}
        serial_number = cert.serial_number
        issuer = cert.issuer
        try:
            result['validity'] = {}
            result['validity']['end_datetime'] = cert.not_valid_after
            result['validity']['start_datetime'] = cert.not_valid_before
            result['validity']['end'] = result['validity']['end_datetime'].strftime('%Y-%m-%dT%H:%M:%SZ')
            result['validity']['start'] = result['validity']['start_datetime'].strftime('%Y-%m-%dT%H:%M:%SZ')
        except Exception:
            pass
        result['issuer'] = {}
        dict_replace = {
            'countryName': 'country',
            'organizationName': 'organization',
            'commonName': 'common_name'
        }
        try:
            for n in issuer.rdns:
                z = n._attributes[0]
                name_k = z.oid._name
                value = z.value
                if name_k in dict_replace:
                    result['issuer'][dict_replace[name_k]] = [value]
        except Exception:
            pass
        try:
            if 'v' in cert.version.name:
                result['version'] = cert.version.name.split('v')[1].strip()
        except BaseException:
            result['version'] = str(cert.version.value)
        dnss = get_certificate_domains(cert)
        atr = cert.subject._attributes
        result['subject'] = {}
        for i in atr:
            for q in i._attributes:
                result['subject'][q.oid._name] = [q.value]
        if 'serialNumber' in list(result.keys()):
            if len(result['serialNumber']) == 16:
                result['serialNumber'] = '00' + result['serialNumber']
        try:
            result['serialNumber_int'] = int('0x' + result['serialNumber'], 16)
            result['serial_number'] = str(result['serialNumber_int'])
        except BaseException:
            result['serialNumber_int'] = 0
        result['names'] = dnss
        if result['serialNumber_int'] == 0:
            result['serial_number'] = str(serial_number)
            result['serial_number_hex'] = str(hex(serial_number))
        result['raw_serial'] = str(serial_number)
        hashs = {
            'fingerprint_sha256': sha256,
            'fingerprint_sha1': sha1,
            'fingerprint_md5': md5
        }
        for namehash, func in hashs.items():
            hm = func()
            hm.update(bytes_cert)
            result[namehash] = hm.hexdigest()
        remove_keys = ['serialNumber_int']
        for key in remove_keys:
            result.pop(key)
        return result
Example #42
0
    def config_params(self, params={}):
        ec = VppEnum.vl_api_ipsec_crypto_alg_t
        ei = VppEnum.vl_api_ipsec_integ_alg_t
        self.vpp_enums = {
            'AES-CBC-128': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_128,
            'AES-CBC-192': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_192,
            'AES-CBC-256': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_256,
            'AES-GCM-16ICV-128': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_128,
            'AES-GCM-16ICV-192': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_192,
            'AES-GCM-16ICV-256': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_256,
            'HMAC-SHA1-96': ei.IPSEC_API_INTEG_ALG_SHA1_96,
            'SHA2-256-128': ei.IPSEC_API_INTEG_ALG_SHA_256_128,
            'SHA2-384-192': ei.IPSEC_API_INTEG_ALG_SHA_384_192,
            'SHA2-512-256': ei.IPSEC_API_INTEG_ALG_SHA_512_256
        }

        is_natt = 'natt' in params and params['natt'] or False
        self.p = Profile(self, 'pr1')

        if 'auth' in params and params['auth'] == 'rsa-sig':
            auth_method = 'rsa-sig'
            work_dir = os.getenv('BR') + '/../src/plugins/ikev2/test/certs/'
            self.vapi.ikev2_set_local_key(key_file=work_dir +
                                          params['server-key'])

            client_file = work_dir + params['client-cert']
            server_pem = open(work_dir + params['server-cert']).read()
            client_priv = open(work_dir + params['client-key']).read()
            client_priv = load_pem_private_key(str.encode(client_priv), None,
                                               default_backend())
            self.peer_cert = x509.load_pem_x509_certificate(
                str.encode(server_pem), default_backend())
            self.p.add_auth(method='rsa-sig', data=str.encode(client_file))
            auth_data = None
        else:
            auth_data = b'$3cr3tpa$$w0rd'
            self.p.add_auth(method='shared-key', data=auth_data)
            auth_method = 'shared-key'
            client_priv = None

        self.p.add_local_id(id_type='fqdn', data=b'vpp.home')
        self.p.add_remote_id(id_type='fqdn', data=b'roadwarrior.example.com')
        self.p.add_local_ts(start_addr='10.10.10.0', end_addr='10.10.10.255')
        self.p.add_remote_ts(start_addr='10.0.0.0', end_addr='10.0.0.255')

        self.sa = IKEv2SA(self,
                          i_id=self.p.remote_id['data'],
                          r_id=self.p.local_id['data'],
                          id_type=self.p.local_id['id_type'],
                          natt=is_natt,
                          priv_key=client_priv,
                          auth_method=auth_method,
                          auth_data=auth_data,
                          local_ts=self.p.remote_ts,
                          remote_ts=self.p.local_ts)

        ike_crypto = ('AES-CBC', 32) if 'ike-crypto' not in params else\
            params['ike-crypto']
        ike_integ = 'HMAC-SHA1-96' if 'ike-integ' not in params else\
            params['ike-integ']
        ike_dh = '2048MODPgr' if 'ike-dh' not in params else params['ike-dh']

        esp_crypto = ('AES-CBC', 32) if 'esp-crypto' not in params else\
            params['esp-crypto']
        esp_integ = 'HMAC-SHA1-96' if 'esp-integ' not in params else\
            params['esp-integ']

        self.sa.set_ike_props(crypto=ike_crypto[0],
                              crypto_key_len=ike_crypto[1],
                              integ=ike_integ,
                              prf='PRF_HMAC_SHA2_256',
                              dh=ike_dh)
        self.sa.set_esp_props(crypto=esp_crypto[0],
                              crypto_key_len=esp_crypto[1],
                              integ=esp_integ)
    def add_remove_policy_management_certificate(self):
        """
        Add and then remove a  policy management certificates for an Isolated
        mode attestation instance.

        """
        write_banner("add_remove_policy_management_certificate")
        print(
            "Get and set the policy management certificates for a isolated instance."
        )
        endpoint = os.environ.get("ATTESTATION_ISOLATED_URL")
        with AttestationAdministrationClient(
                endpoint, DefaultAzureCredential()) as admin_client:
            # [BEGIN add_policy_management_certificate]
            new_key = create_rsa_key()
            new_certificate = create_x509_certificate(new_key,
                                                      u"NewCertificateName")

            # Add the new certificate to the list. Specify a validation slack of
            # 1.0 to test passing in validation parameters to this method.
            add_result, _ = admin_client.add_policy_management_certificate(
                new_certificate,
                signing_key=self.isolated_key,
                signing_certificate=self.isolated_certificate,
                validation_slack=1.0,
            )
            if add_result.certificate_resolution != CertificateModification.IS_PRESENT:
                raise Exception("Certificate was not added!")

            # [END add_policy_management_certificate]

            certificates, _ = admin_client.get_policy_management_certificates()
            print("Isolated instance now has", len(certificates),
                  "certificates")

            for cert_pem in certificates:
                cert = load_pem_x509_certificate(cert_pem[0].encode("ascii"),
                                                 default_backend())
                print("certificate subject: ", cert.subject)

            # The signing certificate for the isolated instance should be
            # the configured isolated_signing_certificate.
            #
            # Note that the certificate list returned is an array of certificate chains.
            actual_cert0 = certificates[0][0]
            isolated_cert = self.isolated_certificate
            print("Actual Cert 0:   ", actual_cert0)
            print("Isolated Cert: ", isolated_cert)
            if actual_cert0 != isolated_cert:
                raise Exception("Unexpected certificate mismatch.")

            found_cert = False
            expected_cert = new_certificate
            for cert_pem in certificates:
                actual_cert1 = cert_pem[0]
                if actual_cert1 == expected_cert:
                    found_cert = True
            if not found_cert:
                raise Exception("Could not find new certificate!")

        # [BEGIN remove_policy_management_certificate]
        with AttestationAdministrationClient(
                endpoint, DefaultAzureCredential()) as admin_client:
            # Now remove the certificate we just added.
            print("Remove the newly added certificate.")
            remove_result, _ = admin_client.remove_policy_management_certificate(
                new_certificate,
                signing_key=self.isolated_key,
                signing_certificate=self.isolated_certificate,
            )

            if (remove_result.certificate_resolution !=
                    CertificateModification.IS_ABSENT):
                raise Exception("Certificate was not removed!")
Example #44
0
                config["SGX_CONSTANTS"]["ias_report_signing_certificate_oid"]):
            ias_report_signing_certificate = b64decode(ext.value.value)

    return (ias_report, ias_report_signature, ias_report_signing_certificate)


if __name__ == "__main__":

    CONFIGS_FILE = "configs.conf"
    config = ConfigParser()
    config.read(CONFIGS_FILE)

    try:
        cert_str = ssl.get_server_certificate(
            (config["SERVER"]["host"], int(config["SERVER"]["port"])))
        cert = x509.load_pem_x509_certificate(str.encode(cert_str),
                                              default_backend())
    except:
        print("Unable to load server certificate! Aborting...")
        exit(-1)

    ias_report, ias_report_signature, ias_report_signing_certificate = get_certificate_extensions(
        cert)

    if ias_report is None or ias_report_signature is None or ias_report_signing_certificate is None:
        print(
            "The certificate obtained from the server doesn't contain all expected extensions! Aborting..."
        )
        exit(-2)

    if not verify_report_signature(ias_report, ias_report_signature,
                                   ias_report_signing_certificate):
Example #45
0
def convert_certificate_to_pem(public_key):
    cert_obj = load_pem_x509_certificate(str.encode(public_key),
                                         default_backend())
    pub_key = cert_obj.public_key()
    return pub_key
Example #46
0
    print 'not_valid_before: {0}\n'.format(cert.not_valid_before)
    print 'not_valid_after: {0}\n'.format(cert.not_valid_after)
    for name in cert.issuer:
        print name
    #print 'issuer: {0}\n'.format(cert.issuer)
    #print 'subject: {0}\n'.format(cert.subject)
    for name in cert.subject:
        print name
    print 'signature_hash_algorithm: {0}\n'.format(
        cert.signature_hash_algorithm)
    print 'signature_algorithm_oid): {0}\n'.format(
        cert.signature_algorithm_oid)

    for ext in cert.extensions:

        print(ext)


with open(cert_path + cert_name, 'r') as f:

    raw = f.read()

    cert = x509.load_pem_x509_certificate(raw, openssl.backend)

    X509_print(cert)
    #print cert
    pub = cert.public_key()

    print pub.public_bytes(ser_encoding,
                           serialization.PublicFormat.SubjectPublicKeyInfo)
Example #47
0
 def __init__(self, public_cert, private_key):
     self.public_cert = public_cert
     self.private_key = private_key
     self.cert_obj = load_pem_x509_certificate(
         force_bytes(self.public_cert), default_backend())
     self.public_key = self.cert_obj.public_key()
Example #48
0
    answer = input(
        "Digita SI se hai ricevuto la conferma di infezione dal laboratorio di analisi "
        "e vuoi aiutare a contenere l'infezione condividendo questa informazione: "
    )

    if answer == "si" or answer == "SI" or answer == "Si":
        '''
        Il cittadino è risultato positivo e vuole comunicare le informazioni al server
        '''

        # Caricamento chiave pubblica del server del Governo
        # a partire dal suo certificato
        gov_public_key_file = open(
            "certGov.pem", "rb")  # Apertura del file contenente il certificato
        gov_cert = x509.load_pem_x509_certificate(
            gov_public_key_file.read(),
            default_backend())  # Caricamento del certificato dal file
        gov_public_key = gov_cert.public_key(
        )  # estrapolazione public key dal certificato

        # Calcolo dei dummy data illustrati nella relazione, in particolare in questa implementazione
        # questi dati altro non sono che una ripetizione della skt del cittadino
        dummy = str(skt_hex)

        # Composizione del messaggio da inviare al Governo tramite il Proxy
        stringa = dummy + "," + sigma + "," + str(skt_hex) + "," + str(
            salt_hex) + "," + str(14)
        m = bytes(stringa, 'utf-8')

        # Invocazione della funzione definita nel file 'utilities.py'
        simm_key, c = simm_enc(m)
 def cert_load(self, fname):
     with open(fname, "rb") as f:
         return x509.load_pem_x509_certificate(f.read(), default_backend())
Example #50
0
    def test_sign(self, name):

        csr_pem = """-----BEGIN CERTIFICATE REQUEST-----
MIIFbDCCA1QCAQAwgbQxCzAJBgNVBAYTAlVTMQ0wCwYDVQQIDARVdGFoMRIwEAYD
VQQHDAlTYWx0IExha2UxFDASBgNVBAoMC1ZlbmFmaSBJbmMuMRQwEgYDVQQLDAtJ
bnRlZ3JhdGlvbjEnMCUGCSqGSIb3DQEJARYYZW1haWxAdmVuYWZpLmV4YW1wbGUu
Y29tMS0wKwYDVQQDDCR0ZXN0LWNzci0zMjMxMzEzMS52ZW5hZmkuZXhhbXBsZS5j
b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC4T0bdjq+mF+DABhF+
XWCwOXXUWbPNWa72VVhxoelbyTS0iIeZEe64AvNGykytFdOuT/F9pdkZa+Io07R1
ZMp6Ak8dp2Wjt4c5rayVZus6ZK+0ZwBRJO7if/cqhEpxy8Wz1RMfVLf2AE1u/xZS
QSYY0BTRWGmPqrFJrIGbnyQfvmGVPk3cA0RfdrwYJZXtZ2/4QNrbNCoSoSmqTHzt
NAtZhvT2dPU9U48Prx4b2460x+ck3xA1OdJNXV7n5u53QbxOIcjdGT0lJ62ml70G
5gvEHmdPcg+t5cw/Sm5cfDSUEDtNEXvD4oJXfP98ty6f1cYsZpcrgxRwk9RfGain
hvoweXhZP3NWnU5nRdn2nOfExv+xMeQOyB/rYv98zqzK6LvwKhwI5UB1l/n9KTpg
jgaNCP4x/KAsrPecbHK91oiqGSbPn4wtTYOmPkDxSzATN317u7fE20iqvVAUy/O+
7SCNNKEDPX2NP9LLz0IPK0roQxLiwd2CVyN6kEXuzs/3psptkNRMSlhyeAZdfrOE
CNOp46Pam9f9HGBqzXxxoIlfzLqHHL584kgFlBm7qmivVrgp6zdLPDa+UayXEl2N
O17SnGS8nkOTmfg3cez7lzX/LPLO9X/Y1xKYqx5hoGZhh754K8mzDWCVCYThWgou
yBOYY8uNXiX6ldqzQUHpbxxQgwIDAQABoHIwcAYJKoZIhvcNAQkOMWMwYTBfBgNV
HREEWDBWgilhbHQxLXRlc3QtY3NyLTMyMzEzMTMxLnZlbmFmaS5leGFtcGxlLmNv
bYIpYWx0Mi10ZXN0LWNzci0zMjMxMzEzMS52ZW5hZmkuZXhhbXBsZS5jb20wDQYJ
KoZIhvcNAQELBQADggIBAJd87BIdeh0WWoyQ4IX+ENpNqmm/sLmdfmUB/hj9NpBL
qbr2UTWaSr1jadoZ+mrDxtm1Z0YJDTTIrEWxkBOW5wQ039lYZNe2tfDXSJZwJn7u
2keaXtWQ2SdduK1wOPDO9Hra6WnH7aEq5D1AyoghvPsZwTqZkNynt/A1BZW5C/ha
J9/mwgWfL4qXBGBOhLwKN5GUo3erUkJIdH0TlMqI906D/c/YAuJ86SRdQtBYci6X
bJ7C+OnoiV6USn1HtQE6dfOMeS8voJuixpSIvHZ/Aim6kSAN1Za1f6FQAkyqbF+o
oKTJHDS1CPWikCeLdpPUcOCDIbsiISTsMZkEvIkzZ7dKBIlIugauxw3vaEpk47jN
Wq09r639RbSv/Qs8D6uY66m1IpL4zHm4lTAknrjM/BqihPxc8YiN76ssajvQ4SFT
DHPrDweEVe4KL1ENw8nv4wdkIFKwJTDarV5ZygbETzIhfa2JSBZFTdN+Wmd2Mh5h
OTu+vuHrJF2TO8g1G48EB/KWGt+yvVUpWAanRMwldnFX80NcUlM7GzNn6IXTeE+j
BttIbvAAVJPG8rVCP8u3DdOf+vgm5macj9oLoVP8RBYo/z0E3e+H50nXv3uS6JhN
xlAKgaU6i03jOm5+sww5L2YVMi1eeBN+kx7o94ogpRemC/EUidvl1PUJ6+e7an9V
-----END CERTIFICATE REQUEST-----
        """

        with tempfile.NamedTemporaryFile("w+") as f:
            f.write(csr_pem)
            f.flush()
            csr_path = f.name
            cn = "test-csr-32313131.venafi.example.com"

            # Provide python27 compatibility
            if not isinstance(cn, text_type):
                cn = cn.decode()

            ret = self.run_run_plus(fun="venafi.request",
                                    minion_id=cn,
                                    csr_path=csr_path,
                                    zone="fake")
            cert_output = ret["return"][0]
            assert (
                cert_output
                is not None), "venafi_certificate not found in `output_value`"

            cert = x509.load_pem_x509_certificate(cert_output.encode(),
                                                  default_backend())
            assert isinstance(cert, x509.Certificate)
            assert cert.subject.get_attributes_for_oid(
                NameOID.COMMON_NAME) == [
                    x509.NameAttribute(NameOID.COMMON_NAME, cn)
                ]
Example #51
0
def mock_certificate(mock_certificate_binary) -> Tuple[Certificate, List[str]]:
    binary, cert_dict = mock_certificate_binary
    return load_pem_x509_certificate(binary, default_backend()), cert_dict['names']
    def sign_certificate_request_dns(self,
                                     service,
                                     service_dns,
                                     password,
                                     custom_ca,
                                     java_services=None,
                                     kube_ns="default"):
        """Sign Certificate Request based on root Certificate Authority (CA)."""
        with open(self._config_path / f"csr/{service}.csr.pem", "rb") as f:
            csr = x509.load_pem_x509_csr(data=f.read(),
                                         backend=default_backend())

        if custom_ca and len(custom_ca) == 2:
            custom_crt, custom_key = custom_ca
            with custom_crt.open(mode="rb") as root_cert:
                root_ca_cert = x509.load_pem_x509_certificate(
                    root_cert.read(), default_backend())

            with custom_key.open(mode="rb") as root_key:
                root_ca_pkey = serialization.load_pem_private_key(
                    root_key.read(),
                    password=password.encode("utf-8"),
                    backend=default_backend())
        else:
            with open(self._config_path / "certs/root.ca.crt",
                      "rb") as root_cert:
                root_ca_cert = x509.load_pem_x509_certificate(
                    root_cert.read(), default_backend())

            with open(self._config_path / "certs/root.ca.key",
                      "rb") as root_key:
                root_ca_pkey = serialization.load_pem_private_key(
                    root_key.read(),
                    password=password.encode("utf-8"),
                    backend=default_backend())

        cert = (x509.CertificateBuilder().subject_name(
            csr.subject).issuer_name(root_ca_cert.subject).public_key(
                csr.public_key()).serial_number(
                    x509.random_serial_number()).not_valid_before(
                        datetime.datetime.utcnow()).not_valid_after(
                            datetime.datetime.utcnow() +
                            datetime.timedelta(days=365 * 10)).add_extension(
                                extval=x509.KeyUsage(
                                    digital_signature=True,
                                    key_encipherment=True,
                                    content_commitment=True,
                                    data_encipherment=False,
                                    key_agreement=False,
                                    encipher_only=False,
                                    decipher_only=False,
                                    key_cert_sign=False,
                                    crl_sign=False,
                                ),
                                critical=True,
                            ).add_extension(extval=x509.BasicConstraints(
                                ca=False, path_length=None),
                                            critical=True).
                add_extension(
                    extval=x509.AuthorityKeyIdentifier.from_issuer_public_key(
                        root_ca_pkey.public_key()),
                    critical=False).add_extension(
                        extval=x509.SubjectAlternativeName([
                            x509.DNSName(service_dns),
                            x509.DNSName(service_dns +
                                         f".{kube_ns}.svc.cluster.local"),
                            x509.DNSName(service_dns + f".{kube_ns}"),
                        ]),
                        critical=False,
                    ).sign(private_key=root_ca_pkey,
                           algorithm=hashes.SHA256(),
                           backend=default_backend()))

        with open(self._config_path / f"certs/{service}.ca.crt", "wb") as f:
            f.write(cert.public_bytes(encoding=serialization.Encoding.PEM))

        if java_services and service in java_services:

            with open(self._config_path / f"certs/{service}.ca.crt.der",
                      "wb") as ca_crt:
                ca_crt.write(
                    cert.public_bytes(encoding=serialization.Encoding.DER))
Example #53
0
 def from_pem(cls, data: bytes) -> "Cert":
     cert = x509.load_pem_x509_certificate(data)  # type: ignore
     return cls(cert)
Example #54
0
# Bitly link API integration
BITLY_LOGIN = credstash.getSecret('BITLY_LOGIN', table='staging')
BITLY_API_KEY = credstash.getSecret('BITLY_API_KEY', table='staging')
BITLY_ACCESS_TOKEN = credstash.getSecret('BITLY_ACCESS_TOKEN', table='staging')
BITLY_TIMEOUT = 5

# Twilio API integration
TWILIO_ACCOUNT_SID = credstash.getSecret('TWILIO_ACCOUNT_SID', table='staging')
TWILIO_AUTH_TOKEN = credstash.getSecret('TWILIO_AUTH_TOKEN', table='staging')

CDN_DOMAIN = credstash.getSecret('CDN_DOMAIN', table='staging')

# Auth0 Config

certificate_text = credstash.getSecret('AUTH_CERT', table='staging').encode()
certificate = load_pem_x509_certificate(certificate_text, default_backend())
default_publickey = certificate.public_key()

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':
    ('rest_framework_auth0.authentication.Auth0JSONWebTokenAuthentication', ),
}

AUTH0 = {
    'CLIENTS': {
        'default': {
            'AUTH0_CLIENT_ID': credstash.getSecret('AUTH_ID', table='staging'),
            'AUTH0_ALGORITHM': 'RS256',
            'PUBLIC_KEY': default_publickey
        }
    },
 def _process_cert(self, key):
     key = load_pem_x509_certificate(key, self.cryptography_backend())
     self.prepared_key = key.public_key()
Example #56
0
def mk_signed_cert(cacert, ca_pk, name, serialnum):
    del serialnum
    csr = {"request": {
        "CN": name,
        "hosts": [
            name,
        ],
        "key": {
            "algo": "rsa",
            "size": config.getint('ca', 'cert_bits')
        },
        "names": [
            {
                "C": config.get('ca', 'cert_country'),
                "L": config.get('ca', 'cert_locality'),
                "O": config.get('ca', 'cert_organization'),
                "OU": config.get('ca', 'cert_org_unit'),
                "ST": config.get('ca', 'cert_state')
            }
        ]
    }
    }

    # check CRL distribution point
    disturl = config.get('ca', 'cert_crl_dist')
    if disturl == 'default':
        disturl = f"http://{socket.getfqdn()}:{config.CRL_PORT}/crl.der"

    # set up config for cfssl server
    cfsslconfig = {
        "signing": {
            "default": {
                "usages": ["client auth", "server auth", "key agreement", "key encipherment", "signing", "digital signature", "data encipherment"],
                "expiry": "8760h",
                "crl_url": disturl,
            }
        }
    }
    secdir = secure_mount.mount()
    try:
        # need to temporarily write out the private key with no password
        # to tmpfs.
        with os.fdopen(os.open(f"{secdir}/ca-key.pem", os.O_WRONLY | os.O_CREAT, 0o600), 'wb') as f:
            f.write(ca_pk.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption(),
                )
            )

        with open(os.path.join(secdir, 'cfsslconfig.yml'), 'w', encoding="utf-8") as f:
            json.dump(cfsslconfig, f)

        with open(f"{secdir}/cacert.crt", 'wb') as f:
            f.write(cacert.public_bytes(serialization.Encoding.PEM))

        cmdline = f"-config={secdir}/cfsslconfig.yml"

        privkey_path = os.path.abspath(f"{secdir}/ca-key.pem")
        cacert_path = os.path.abspath(f"{secdir}/cacert.crt")

        cmdline += f" -ca-key {privkey_path} -ca {cacert_path}"

        start_cfssl(cmdline)
        body = post_cfssl('api/v1/cfssl/newcert', csr)
    finally:
        stop_cfssl()
        os.remove(os.path.join(secdir, "ca-key.pem"))
        os.remove(os.path.join(secdir, "cfsslconfig.yml"))
        os.remove(os.path.join(secdir, "cacert.crt"))

    if body['success']:
        pk = serialization.load_pem_private_key(
            body['result']['private_key'].encode('utf-8'),
            password=None,
            backend=default_backend(),
        )
        cert = x509.load_pem_x509_certificate(
            data=body['result']['certificate'].encode('utf-8'),
            backend=default_backend(),
        )
        return cert, pk

    raise Exception(f"Unable to create cert for {name}")
def register_azure_signer():
    print("\nRegistering Signer started....")
    signer_cer_path = SIGNER_CA_FILENAME_BASE + '.cer'
    with open(signer_cer_path, 'wb') as cer:
        with open(signer_cert_path, 'rb') as crt:
            cer.write(crt.read())

    if not os.path.isfile(signer_cer_path):
        print(
            "No signer certificate found...TrustFLEX resource_generation notebook has to be run with Customer Cert option before running this notebook\r\n"
        )
        return 'danger'

    #Checking if the signer certificate is already uploaded to the Azure iot hub
    print("Check if the Signer is already registered...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "list", "--hub-name", hub_name,
        "--query", "value[].properties[].thumbprint"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Getting signer list from azure failed")
        return 'danger'
    cert_check = subProcessOut.stdout
    signer_cert_finger = re.findall(r'"(.*?)"', cert_check)
    with open(signer_cer_path, 'rb') as f:
        cert = x509.load_pem_x509_certificate(f.read(), crypto_be)
        fingerprint = binascii.hexlify(cert.fingerprint(
            hashes.SHA1())).decode().upper()
    for x in signer_cert_finger:
        if (x == fingerprint):
            print(
                "Signer already registered....Proceed to Register device step\r\n"
            )
            return 'success'
    print('Proceed to Signer registration')

    ## Getting signer org name from the signer certificate
    signer_org_name = get_org_name(cert.subject).strip().replace(" ", "_")
    print("Signer ca uploading to the hub started...", end='')
    signer_name = SIGNER_CA_FILENAME_BASE + '_' + signer_org_name + '_' + datetime.now(
    ).strftime("%Y-%m-%d-%H-%M-%S")

    ## Signer Certificate Upload to the azure iot hub  ##
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "create", "--hub-name", hub_name,
        "--name", signer_name, "--path", signer_cer_path
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)

    if subProcessOut.returncode != 0:
        print("signer certificate upload to azure iot hub failed\r\n")
        return 'danger'
    print('OK')

    # Get the etag for the signer certificate ##
    print("Getting the verification code from the iot hub...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "show", "--hub-name", hub_name,
        "--name", signer_name, "--query", "etag"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print(
            "Getting etag for signer certificate from azure iot hub failed\r\n"
        )
        return 'danger'
    etag_id = subProcessOut.stdout
    print('OK')

    ##Generate the verification code for the signer cerificate ##
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "generate-verification-code",
        "--hub-name", hub_name, "--name", signer_name, "--etag", etag_id
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("Getting verificateion code from azure iot hub failed\r\n")
        return 'danger'
    data = subProcessOut.stdout
    json_data = json.loads(data)
    registration_code = json_data['properties']['verificationCode']

    ##Generate the verification certificate with the verification code##
    print("Generating the verification certificate with verification code...",
          end='')
    generate_verification_cert(registration_code, SIGNER_CA_KEY_FILENAME,
                               SIGNER_CA_CERT_FILENAME,
                               SIGNER_CA_VER_CERT_FILENAME)
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "show", "--hub-name", hub_name,
        "--name", signer_name, "--query", "etag"
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print(
            "Getting etag for signer certificate from azure iot hub failed\r\n"
        )
        return 'danger'
    etag_id = subProcessOut.stdout
    print('OK')

    ## Upload the Verification certificate to azure iot hub ##
    print("Uploading the verification certificate to iot hub...", end='')
    subProcessOut = sys_helper.run_subprocess_cmd(cmd=[
        "az", "iot", "hub", "certificate", "verify", "--hub-name", hub_name,
        "--name", signer_name, "--path", verification_cert_path, "--etag",
        etag_id
    ],
                                                  sys_newlines=True,
                                                  sys_shell=True)
    if subProcessOut.returncode != 0:
        print("uploading verification certificate to azure iot hub failed\r\n")
        return 'danger'
    print('OK')
    print("Signer ca {} uploaded and verified in azure hub\r\n".format(
        signer_name))
    return 'success'
HQYDVQQDDBZBcHBsZSBXZWJBdXRobiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJ
bmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMB4XDTIwMDMxODE4MjEzMloXDTQ1MDMx
NTAwMDAwMFowSzEfMB0GA1UEAwwWQXBwbGUgV2ViQXV0aG4gUm9vdCBDQTETMBEG
A1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTB2MBAGByqGSM49
AgEGBSuBBAAiA2IABCJCQ2pTVhzjl4Wo6IhHtMSAzO2cv+H9DQKev3//fG59G11k
xu9eI0/7o6V5uShBpe1u6l6mS19S1FEh6yGljnZAJ+2GNP1mi/YK2kSXIuTHjxA/
pcoRf7XkOtO4o1qlcaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUJtdk
2cV4wlpn0afeaxLQG2PxxtcwDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA
MGQCMFrZ+9DsJ1PW9hfNdBywZDsWDbWFp28it1d/5w2RPkRX3Bbn/UbDTNLx7Jr3
jAGGiQIwHFj+dJZYUJR786osByBelJYsVZd2GbHQu209b5RCmGQ21gpSAk9QZW4B
1bWeT0vT
-----END CERTIFICATE-----
    '''.encode('ascii')

# Decode the root so we can use it later
kAPPLE_WEBAUTHN_AUTHORITY_ROOT = x509.load_pem_x509_certificate(
    kAPPLE_WEBAUTHN_AUTHORITY_ROOT_PEM, default_backend())

# Apple OID for the nonce hash
kAPPLE_AAA_NONCE_OID = x509.ObjectIdentifier('1.2.840.113635.100.8.2')


def _generate_attest_nonce(auth_data_raw, client_data_raw):
    """
    Given the raw client data and auth data structures, calculate the
    nonce that is included as the subject in the attestation end
    entity cert.
    """

    # Hash the client data string
    client_digest = hashes.Hash(hashes.SHA256())
    client_digest.update(client_data_raw)
Example #59
0
]

# Auth0
AUTH0_CLIENT_ID = get_env_variable("AUTH0_CLIENT_ID")
AUTH0_CLIENT_SECRET = get_env_variable("AUTH0_CLIENT_SECRET")
AUTH0_DOMAIN = get_env_variable("AUTH0_DOMAIN")

AUTH0_API_ID = get_env_variable("AUTH0_API_ID")
AUTH0_API_SECRET = get_env_variable("AUTH0_API_SECRET")
AUTH0_AUDIENCE = get_env_variable("AUTH0_AUDIENCE")

AUTH0_PUBLIC_KEY = get_env_variable("AUTH0_PUBLIC_KEY")

# JWT Settings
pem_data = AUTH0_PUBLIC_KEY.encode()
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
jwt_public_key = cert.public_key()


def jwt_get_username_from_payload_handler(payload):
    return payload.get('email')


JWT_AUTH = {
    'JWT_AUDIENCE': AUTH0_CLIENT_ID,
    'JWT_PAYLOAD_GET_USERNAME_HANDLER': jwt_get_username_from_payload_handler,
    'JWT_AUTH_HEADER_PREFIX': 'Bearer',
    'JWT_PUBLIC_KEY': jwt_public_key,
    'JWT_ALGORITHM': 'RS256',
}
Example #60
0
    def _generate_certificate(self,
                              common_name: str,
                              pem_path: str,
                              p12path: str,
                              expiry_time_days: int = 3650) -> None:
        """
        Create a certificate and p12 file
        :param common_name: Common Name for certificate
        :param pem_path: String filepath for the pem file created
        :param p12path: String filepath for the p12 file created
        :param expiry_time_days: length of time in seconds that the certificate is valid for, defaults to 10 years
        """
        ca_key = serialization.load_pem_private_key(
            open(self.ca_key_path, 'rb').read(), None, default_backend())
        one_day = datetime.timedelta(1, 0, 0)
        public_key = self.key.public_key()
        cert = x509.CertificateBuilder()
        cert = cert.subject_name(
            x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]))
        cert = cert.serial_number(x509.random_serial_number())
        cert = cert.not_valid_before(datetime.datetime.today() - one_day)
        cert = cert.not_valid_after(datetime.datetime.today() +
                                    (one_day * expiry_time_days))
        ca_subject = x509.load_pem_x509_certificate(
            open(self.ca_pem_path, 'rb').read()).subject
        cert = cert.issuer_name(
            x509.Name([
                x509.NameAttribute(
                    NameOID.COMMON_NAME,
                    str(ca_subject.rfc4514_string().split("=")[1]))
            ]))
        cert = cert.public_key(public_key)
        cert = cert.add_extension(x509.SubjectKeyIdentifier.from_public_key(
            ca_key.public_key()),
                                  critical=False)
        # SAN is checked for https:// links
        if common_name[:2].isnumeric():
            cert = cert.add_extension(x509.SubjectAlternativeName(
                [x509.IPAddress(ipaddress.IPv4Address(common_name))]),
                                      critical=False)
        else:
            cert = cert.add_extension(x509.SubjectAlternativeName(
                [x509.DNSName(common_name)]),
                                      critical=False)
        cert = cert.sign(private_key=ca_key, algorithm=hashes.SHA256())

        p12 = pkcs12.serialize_key_and_certificates(
            key=self.key,
            cert=cert,
            cas=[
                x509.load_pem_x509_certificate(
                    open(self.ca_pem_path, 'rb').read())
            ],
            name=b'certbundle',
            encryption_algorithm=serialization.BestAvailableEncryption(
                bytes(self.cert_pwd, encoding='UTF-8')))

        with open(p12path, 'wb') as p12file:
            p12file.write(p12)
            print("P12 Stored Here: " + p12path)

        if os.path.exists(pem_path):
            print("Certificate File Exists, aborting.")
            print(pem_path)
        else:
            f = open(pem_path, "wb")
            f.write(cert.public_bytes(serialization.Encoding.PEM))
            f.close()
            print(f"PEM Stored Here: {pem_path}")