1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
|
import asyncio
import warnings
from typing import Iterable, Optional
from asn1crypto import x509
from ._types import type_name
from .context import ValidationContext
from .errors import InvalidCertificateError, PathBuildingError, ValidationError
from .path import ValidationPath
from .policy_decl import PKIXValidationParams
from .util import CancelableAsyncIterator
from .validate import async_validate_path, validate_tls_hostname, validate_usage
from .version import __version__, __version_info__
__all__ = [
'__version__',
'__version_info__',
'CertificateValidator',
'ValidationContext',
'PKIXValidationParams',
'find_valid_path',
]
async def find_valid_path(
certificate: x509.Certificate,
paths: CancelableAsyncIterator[ValidationPath],
validation_context: ValidationContext,
pkix_validation_params: Optional[PKIXValidationParams] = None,
):
exceptions = []
try:
async for candidate_path in paths:
try:
await async_validate_path(
validation_context, candidate_path, pkix_validation_params
)
return candidate_path
except ValidationError as e:
exceptions.append(e)
except PathBuildingError:
if certificate.self_signed in {'yes', 'maybe'}:
raise InvalidCertificateError(
f'The X.509 certificate provided is self-signed - '
f'"{certificate.subject.human_friendly}"'
)
raise
finally:
await paths.cancel()
if len(exceptions) == 1:
raise exceptions[0]
non_signature_exception = None
for exception in exceptions:
if 'signature' not in str(exception):
non_signature_exception = exception
if non_signature_exception:
raise non_signature_exception
raise exceptions[0]
class CertificateValidator:
# A pyhanko_certvalidator.path.ValidationPath object - only set once validated
_path = None
def __init__(
self,
end_entity_cert: x509.Certificate,
intermediate_certs: Optional[Iterable[x509.Certificate]] = None,
validation_context: Optional[ValidationContext] = None,
pkix_params: Optional[PKIXValidationParams] = None,
):
"""
:param end_entity_cert:
An asn1crypto.x509.Certificate object X.509 end-entity
certificate to validate
:param intermediate_certs:
None or a list of asn1crypto.x509.Certificate
Used in constructing certificate paths for validation.
:param validation_context:
A pyhanko_certvalidator.context.ValidationContext() object that
controls generic validation options and tracks revocation data.
The same validation context will also be used in the validation
of relevant certificates found in OCSP responses and/or CRLs.
:param pkix_params:
A pyhanko_certvalidator.context.PKIXValidationParams() object that
controls advanced PKIX validation parameters used to validate
the end-entity certificate. These can be used to constrain
policy processing and names.
Ancillary validation of CRLs and OCSP responses ignore these
settings.
"""
if validation_context is None:
validation_context = ValidationContext()
if intermediate_certs is not None:
certificate_registry = validation_context.certificate_registry
for intermediate_cert in intermediate_certs:
certificate_registry.register(intermediate_cert)
self._context: ValidationContext = validation_context
self._certificate: x509.Certificate = end_entity_cert
self._params: Optional[PKIXValidationParams] = pkix_params
@property
def certificate(self):
return self._certificate
async def async_validate_path(self) -> ValidationPath:
"""
Builds possible certificate paths and validates them until a valid one
is found, or all fail.
:raises:
pyhanko_certvalidator.errors.PathBuildingError - when an error occurs building the path
pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path
pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
"""
if self._path is not None:
return self._path
certificate = self._certificate
paths = self._context.path_builder.async_build_paths_lazy(certificate)
self._path = candidate_path = await find_valid_path(
certificate,
paths,
validation_context=self._context,
pkix_validation_params=self._params,
)
return candidate_path
def validate_usage(
self, key_usage, extended_key_usage=None, extended_optional=False
):
"""
Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
.. deprecated:: 0.17.0
Use :meth:`async_validate_usage` instead.
:param key_usage:
A set of unicode strings of the required key usage purposes. Valid
values include:
- "digital_signature"
- "non_repudiation"
- "key_encipherment"
- "data_encipherment"
- "key_agreement"
- "key_cert_sign"
- "crl_sign"
- "encipher_only"
- "decipher_only"
:param extended_key_usage:
A set of unicode strings of the required extended key usage
purposes. These must be either dotted number OIDs, or one of the
following extended key usage purposes:
- "server_auth"
- "client_auth"
- "code_signing"
- "email_protection"
- "ipsec_end_system"
- "ipsec_tunnel"
- "ipsec_user"
- "time_stamping"
- "ocsp_signing"
- "wireless_access_points"
An example of a dotted number OID:
- "1.3.6.1.5.5.7.3.1"
:param extended_optional:
A bool - if the extended_key_usage extension may be ommited and still
considered valid
:raises:
pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path
pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified
:return:
A pyhanko_certvalidator.path.ValidationPath object of the validated
certificate validation path
"""
warnings.warn(
"'validate_usage' is deprecated, use "
"'async_validate_usage' instead",
DeprecationWarning,
)
return asyncio.run(
self.async_validate_usage(
key_usage, extended_key_usage, extended_optional
)
)
async def async_validate_usage(
self, key_usage, extended_key_usage=None, extended_optional=False
):
"""
Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required key usage purposes. Valid
values include:
- "digital_signature"
- "non_repudiation"
- "key_encipherment"
- "data_encipherment"
- "key_agreement"
- "key_cert_sign"
- "crl_sign"
- "encipher_only"
- "decipher_only"
:param extended_key_usage:
A set of unicode strings of the required extended key usage
purposes. These must be either dotted number OIDs, or one of the
following extended key usage purposes:
- "server_auth"
- "client_auth"
- "code_signing"
- "email_protection"
- "ipsec_end_system"
- "ipsec_tunnel"
- "ipsec_user"
- "time_stamping"
- "ocsp_signing"
- "wireless_access_points"
An example of a dotted number OID:
- "1.3.6.1.5.5.7.3.1"
:param extended_optional:
A bool - if the extended_key_usage extension may be ommited and still
considered valid
:raises:
pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path
pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified
:return:
A pyhanko_certvalidator.path.ValidationPath object of the validated
certificate validation path
"""
validated_path = await self.async_validate_path()
validate_usage(
self._context,
self._certificate,
key_usage,
extended_key_usage,
extended_optional,
)
return validated_path
def validate_tls(self, hostname):
"""
Validates the certificate path, that the certificate is valid for
the hostname provided and that the certificate is valid for the purpose
of a TLS connection.
.. deprecated:: 0.17.0
Use :meth:`async_validate_tls` instead.
:param hostname:
A unicode string of the TLS server hostname
:raises:
pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path
pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname
:return:
A pyhanko_certvalidator.path.ValidationPath object of the validated
certificate validation path
"""
warnings.warn(
"'validate_tls' is deprecated, use 'async_validate_tls' instead",
DeprecationWarning,
)
return asyncio.run(self.async_validate_tls(hostname))
async def async_validate_tls(self, hostname):
"""
Validates the certificate path, that the certificate is valid for
the hostname provided and that the certificate is valid for the purpose
of a TLS connection.
:param hostname:
A unicode string of the TLS server hostname
:raises:
pyhanko_certvalidator.errors.PathValidationError - when an error occurs validating the path
pyhanko_certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
pyhanko_certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname
:return:
A pyhanko_certvalidator.path.ValidationPath object of the validated
certificate validation path
"""
await self.async_validate_path()
validate_tls_hostname(self._context, self._certificate, hostname)
return self._path
|