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
|
from __future__ import annotations
import abc
from dataclasses import dataclass
from typing import AsyncIterator, Generic, List, Optional, TypeVar, Union
from asn1crypto import algos, cms, core, x509
from asn1crypto.keys import PublicKeyInfo
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import (
dsa,
ec,
ed448,
ed25519,
padding,
rsa,
)
def extract_dir_name(
names: x509.GeneralNames, err_msg_prefix: str
) -> x509.Name:
try:
name: x509.Name = next(
gname.chosen for gname in names if gname.name == 'directory_name'
)
except StopIteration:
raise NotImplementedError(
f"{err_msg_prefix}; only distinguished names are supported, "
f"and none were found."
)
return name.untag()
def extract_ac_issuer_dir_name(
attr_cert: cms.AttributeCertificateV2,
) -> x509.Name:
issuer_rec = attr_cert['ac_info']['issuer']
if issuer_rec.name == 'v1_form':
aa_names = issuer_rec.chosen
else:
issuerv2: cms.V2Form = issuer_rec.chosen
if not isinstance(issuerv2['issuer_name'], core.Void):
aa_names = issuerv2['issuer_name']
else:
aa_names = x509.GeneralNames([])
return extract_dir_name(aa_names, "Could not extract AC issuer name")
def get_issuer_dn(
cert: Union[x509.Certificate, cms.AttributeCertificateV2]
) -> x509.Name:
if isinstance(cert, x509.Certificate):
return cert.issuer
else:
return extract_ac_issuer_dir_name(cert)
def issuer_serial(
cert: Union[x509.Certificate, cms.AttributeCertificateV2]
) -> bytes:
if isinstance(cert, x509.Certificate):
return cert.issuer_serial
else:
issuer_name = extract_ac_issuer_dir_name(cert)
result_bytes = b'%s:%d' % (
issuer_name.sha256,
cert['ac_info']['serial_number'].native,
)
return result_bytes
def get_ac_extension_value(
attr_cert: cms.AttributeCertificateV2, ext_name: str
):
try:
return next(
ext['extn_value'].parsed
for ext in attr_cert['ac_info']['extensions']
if ext['extn_id'].native == ext_name
)
except StopIteration:
return None
def _get_absolute_http_crls(dps: Optional[x509.CRLDistributionPoints]):
# see x509._get_http_crl_distribution_points
if dps is None:
return
for distribution_point in dps:
distribution_point_name = distribution_point['distribution_point']
if isinstance(distribution_point_name, core.Void):
continue
# RFC 5280 indicates conforming CA should not use the relative form
if distribution_point_name.name == 'name_relative_to_crl_issuer':
continue
# This library is currently only concerned with HTTP-based CRLs
for general_name in distribution_point_name.chosen:
if general_name.name == 'uniform_resource_identifier':
yield distribution_point
def _get_ac_crl_dps(
attr_cert: cms.AttributeCertificateV2,
) -> List[x509.DistributionPoint]:
dps_ext = get_ac_extension_value(attr_cert, 'crl_distribution_points')
return list(_get_absolute_http_crls(dps_ext))
def _get_ac_delta_crl_dps(
attr_cert: cms.AttributeCertificateV2,
) -> List[x509.DistributionPoint]:
delta_dps_ext = get_ac_extension_value(attr_cert, 'freshest_crl')
return list(_get_absolute_http_crls(delta_dps_ext))
def get_relevant_crl_dps(
cert: Union[x509.Certificate, cms.AttributeCertificateV2], *, use_deltas
) -> List[x509.DistributionPoint]:
is_pkc = isinstance(cert, x509.Certificate)
if is_pkc:
# FIXME: This utility property in asn1crypto is not precise enough.
# More to the point, URLs attached to the same distribution point
# are considered interchangeable, but URLs belonging to different
# distribution points very much aren't---different distribution points
# can differ in what reason codes they record, etc.
# For the time being, we'll assume that people who care about that sort
# of nuance will run in 'require' mode, in which case the validator
# should complain if the available CRLs don't cover all reason codes.
sources = list(cert.crl_distribution_points)
else:
sources = _get_ac_crl_dps(cert)
if use_deltas:
if is_pkc:
sources.extend(cert.delta_crl_distribution_points)
else:
sources.extend(_get_ac_delta_crl_dps(cert))
return sources
def _get_http_ocsp_urls(aia_ext):
if aia_ext is None:
return
for entry in aia_ext:
# compare x509.Certificate.ocsp_urls
if entry['access_method'].native == 'ocsp':
location = entry['access_location']
if location.name != 'uniform_resource_identifier':
continue
url = location.native
if url.lower().startswith(
(
'http://',
'https://',
)
):
yield url
def get_ocsp_urls(cert: Union[x509.Certificate, cms.AttributeCertificateV2]):
if isinstance(cert, x509.Certificate):
aia = cert.authority_information_access_value
else:
aia = get_ac_extension_value(cert, 'authority_information_access')
return list(_get_http_ocsp_urls(aia))
def get_declared_revinfo(
cert: Union[x509.Certificate, cms.AttributeCertificateV2]
):
if isinstance(cert, x509.Certificate):
aia = cert.authority_information_access_value
crl_dps = cert.crl_distribution_points_value
else:
aia = get_ac_extension_value(cert, 'authority_information_access')
crl_dps = get_ac_extension_value(cert, 'crl_distribution_points')
has_crl = crl_dps is not None
# check if the AIA contains any OCSP entries (and here we include all
# entries, including those that we can't query)
if aia is not None:
has_ocsp = any(entry['access_method'].native == 'ocsp' for entry in aia)
else:
has_ocsp = False
return has_crl, has_ocsp
def validate_sig(
signature: bytes,
signed_data: bytes,
public_key_info: PublicKeyInfo,
sig_algo: str,
hash_algo: str,
parameters=None,
):
from .errors import DSAParametersUnavailable, PSSParameterMismatch
if (
sig_algo == 'dsa'
and public_key_info['algorithm']['parameters'].native is None
):
raise DSAParametersUnavailable(
"DSA public key parameters were not provided."
)
# pyca/cryptography can't load PSS-exclusive keys without some help:
if public_key_info.algorithm == 'rsassa_pss':
public_key_info = public_key_info.copy()
assert isinstance(parameters, algos.RSASSAPSSParams)
pss_key_params = public_key_info['algorithm']['parameters'].native
if pss_key_params is not None and pss_key_params != parameters.native:
raise PSSParameterMismatch(
"Public key info includes PSS parameters that do not match "
"those on the signature"
)
# set key type to generic RSA, discard parameters
public_key_info['algorithm'] = {'algorithm': 'rsa'}
pub_key = serialization.load_der_public_key(public_key_info.dump())
if sig_algo == 'rsassa_pkcs1v15':
assert isinstance(pub_key, rsa.RSAPublicKey)
h = getattr(hashes, hash_algo.upper())()
pub_key.verify(signature, signed_data, padding.PKCS1v15(), h)
elif sig_algo == 'rsassa_pss':
assert isinstance(pub_key, rsa.RSAPublicKey)
assert isinstance(parameters, algos.RSASSAPSSParams)
mga: algos.MaskGenAlgorithm = parameters['mask_gen_algorithm']
if not mga['algorithm'].native == 'mgf1':
raise NotImplementedError("Only MFG1 is supported")
mgf_md_name = mga['parameters']['algorithm'].native
salt_len: int = parameters['salt_length'].native
mgf_md = getattr(hashes, mgf_md_name.upper())()
pss_padding = padding.PSS(
mgf=padding.MGF1(algorithm=mgf_md), salt_length=salt_len
)
hash_spec = getattr(hashes, hash_algo.upper())()
pub_key.verify(signature, signed_data, pss_padding, hash_spec)
elif sig_algo == 'dsa':
assert isinstance(pub_key, dsa.DSAPublicKey)
hash_spec = getattr(hashes, hash_algo.upper())()
pub_key.verify(signature, signed_data, hash_spec)
elif sig_algo == 'ecdsa':
assert isinstance(pub_key, ec.EllipticCurvePublicKey)
hash_spec = getattr(hashes, hash_algo.upper())()
pub_key.verify(signature, signed_data, ec.ECDSA(hash_spec))
elif sig_algo == 'ed25519':
assert isinstance(pub_key, ed25519.Ed25519PublicKey)
pub_key.verify(signature, signed_data)
elif sig_algo == 'ed448':
assert isinstance(pub_key, ed448.Ed448PublicKey)
pub_key.verify(signature, signed_data)
else: # pragma: nocover
raise NotImplementedError(
f"Signature mechanism {sig_algo} is not supported."
)
ListElem = TypeVar('ListElem')
@dataclass(frozen=True)
class ConsList(Generic[ListElem]):
head: Optional[ListElem]
tail: Optional[ConsList[ListElem]] = None
@staticmethod
def empty() -> ConsList[ListElem]:
return ConsList(head=None)
@staticmethod
def sing(value: ListElem) -> ConsList[ListElem]:
return ConsList(value, ConsList.empty())
def __iter__(self):
cur = self
while cur.head is not None:
yield cur.head
cur = cur.tail
@property
def last(self) -> Optional[ListElem]:
cur = self
result = None
while cur.tail is not None:
result = cur.head
cur = cur.tail
return result
def cons(self, head: ListElem) -> ConsList[ListElem]:
return ConsList(head, self)
def __repr__(self): # pragma: nocover
return f"ConsList({list(reversed(list(self)))})"
def __bool__(self):
return self.head is not None
T = TypeVar('T')
class CancelableAsyncIterator(abc.ABC, AsyncIterator[T]):
async def cancel(self):
raise NotImplementedError
|