def test_basic_certificate_validator_tls_invalid_key_usage(self):
        cert = self._load_cert_object('mozilla.org.crt')
        other_certs = [
            self._load_cert_object('digicert-sha2-secure-server-ca.crt')
        ]

        moment = datetime(2019, 1, 1, 0, 0, 0, tzinfo=timezone.utc)

        context = ValidationContext(moment=moment)
        validator = CertificateValidator(cert, other_certs, context)

        with self.assertRaisesRegex(PathValidationError, 'for the purpose'):
            validator.validate_usage(set(['crl_sign']))
    def test_certvalidator_with_params(self):

        cert = self._load_nist_cert('ValidPolicyMappingTest12EE.crt')
        ca_certs = [self._load_nist_cert('TrustAnchorRootCertificate.crt')]
        other_certs = [self._load_nist_cert('P12Mapping1to3CACert.crt')]

        context = ValidationContext(trust_roots=ca_certs,
                                    other_certs=other_certs,
                                    revocation_mode="soft-fail",
                                    weak_hash_algos={'md2', 'md5'})

        validator = CertificateValidator(
            cert,
            validation_context=context,
            pkix_params=PKIXValidationParams(user_initial_policy_set=frozenset(
                ['2.16.840.1.101.3.2.1.48.1'])))
        path = validator.validate_usage(key_usage={'digital_signature'})

        # check if we got the right policy processing
        # (i.e. if our params got through)
        qps = path.qualified_policies()

        qp, = qps
        self.assertEqual(1, len(qp.qualifiers))
        qual_obj, = qp.qualifiers
        self.assertEqual(qual_obj['policy_qualifier_id'].native, 'user_notice')
        self.assertEqual(
            qual_obj['qualifier']['explicit_text'].native,
            'q7:  This is the user notice from qualifier 7 associated with '
            'NIST-test-policy-3.  This user notice should be displayed '
            'when  NIST-test-policy-1 is in the user-constrained-policy-set')
Exemple #3
0
    def validate_cert_usage(cls,
                            validator: CertificateValidator,
                            key_usage_settings: KeyUsageConstraints = None):
        key_usage_settings = key_usage_settings or KeyUsageConstraints()
        key_usage_settings = KeyUsageConstraints(
            key_usage=(cls.key_usage if key_usage_settings.key_usage is None
                       else key_usage_settings.key_usage),
            extd_key_usage=(cls.extd_key_usage
                            if key_usage_settings.extd_key_usage is None else
                            key_usage_settings.extd_key_usage))
        cert: x509.Certificate = validator._certificate

        revoked = trusted = False
        path = None

        try:
            # validate usage without going through pyhanko_certvalidator
            key_usage_settings.validate(cert)
            path = validator.validate_usage(key_usage=set())
            trusted = True
        except InvalidCertificateError as e:
            # TODO accumulate these somewhere
            logger.warning(e)
        except RevokedError:
            revoked = True
        except (PathValidationError, PathBuildingError) as e:
            logger.warning(e)
        if not trusted:
            subj = cert.subject.human_friendly
            logger.warning(f"Chain of trust validation for {subj} failed.")
        return trusted, revoked, path
def test_validate(requests_mock, setup):
    setup.illusionist.register(requests_mock)
    signer_cert = setup.arch.get_cert(CertLabel('signer1'))
    root = setup.arch.get_cert(CertLabel('root'))
    interm = setup.arch.get_cert(CertLabel('interm'))
    vc = ValidationContext(trust_roots=[root],
                           allow_fetching=True,
                           revocation_mode='hard-fail',
                           other_certs=[interm])

    validator = CertificateValidator(signer_cert,
                                     intermediate_certs=[],
                                     validation_context=vc)
    validator.validate_usage({'digital_signature'})

    assert len(vc.ocsps)
    assert len(vc.crls)
    def test_basic_certificate_validator_tls_whitelist(self):
        cert = self._load_cert_object('mozilla.org.crt')
        other_certs = [
            self._load_cert_object('digicert-sha2-secure-server-ca.crt')
        ]

        moment = datetime(2020, 1, 1, 0, 0, 0, tzinfo=timezone.utc)

        context = ValidationContext(whitelisted_certs=[cert.sha1_fingerprint],
                                    moment=moment)
        validator = CertificateValidator(cert, other_certs, context)

        # If whitelist does not work, this will raise exception for expiration
        validator.validate_tls('www.mozilla.org')

        # If whitelist does not work, this will raise exception for hostname
        validator.validate_tls('google.com')

        # If whitelist does not work, this will raise exception for key usage
        validator.validate_usage(set(['crl_sign']))
 def test_self_signed_with_policy(self):
     # tests whether a corner case in the policy validation logic when the
     # path length is zero is handled gracefully
     cert = self._load_cert_object('self-signed-with-policy.crt')
     context = ValidationContext(trust_roots=[cert], allow_fetching=False)
     validator = CertificateValidator(cert, validation_context=context)
     path = validator.validate_usage({'digital_signature'})
     qp, = path.qualified_policies()
     # Note: the cert declares a concrete policy, but for the purposes
     # of PKIX validation, any policy is valid, since we're validating
     # a self-signed certificate (so everything breaks down anyway)
     self.assertEqual(qp.user_domain_policy_id, 'any_policy')
     self.assertEqual(qp.issuer_domain_policy_id, 'any_policy')
Exemple #7
0
    def validation_paths(self, validation_context):
        """
        Produce validation paths for the certificates gathered by this
        :class:`.TimeStamper`.

        This is internal API.

        :param validation_context:
            The validation context to apply.
        :return:
            A generator producing validation paths.
        """
        for cert in self._certs.values():
            validator = CertificateValidator(
                cert,
                intermediate_certs=self.cert_registry,
                validation_context=validation_context)
            yield validator.validate_usage(set(), {"time_stamping"})