Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

478 rindas
15 KiB

  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import annotations
  5. import binascii
  6. import re
  7. import sys
  8. import typing
  9. import warnings
  10. from collections.abc import Iterable, Iterator
  11. from cryptography import utils
  12. from cryptography.hazmat.bindings._rust import x509 as rust_x509
  13. from cryptography.x509.oid import NameOID, ObjectIdentifier
  14. class _ASN1Type(utils.Enum):
  15. BitString = 3
  16. OctetString = 4
  17. UTF8String = 12
  18. NumericString = 18
  19. PrintableString = 19
  20. T61String = 20
  21. IA5String = 22
  22. UTCTime = 23
  23. GeneralizedTime = 24
  24. VisibleString = 26
  25. UniversalString = 28
  26. BMPString = 30
  27. _ASN1_TYPE_TO_ENUM = {i.value: i for i in _ASN1Type}
  28. _NAMEOID_DEFAULT_TYPE: dict[ObjectIdentifier, _ASN1Type] = {
  29. NameOID.COUNTRY_NAME: _ASN1Type.PrintableString,
  30. NameOID.JURISDICTION_COUNTRY_NAME: _ASN1Type.PrintableString,
  31. NameOID.SERIAL_NUMBER: _ASN1Type.PrintableString,
  32. NameOID.DN_QUALIFIER: _ASN1Type.PrintableString,
  33. NameOID.EMAIL_ADDRESS: _ASN1Type.IA5String,
  34. NameOID.DOMAIN_COMPONENT: _ASN1Type.IA5String,
  35. }
  36. # Type alias
  37. _OidNameMap = typing.Mapping[ObjectIdentifier, str]
  38. _NameOidMap = typing.Mapping[str, ObjectIdentifier]
  39. #: Short attribute names from RFC 4514:
  40. #: https://tools.ietf.org/html/rfc4514#page-7
  41. _NAMEOID_TO_NAME: _OidNameMap = {
  42. NameOID.COMMON_NAME: "CN",
  43. NameOID.LOCALITY_NAME: "L",
  44. NameOID.STATE_OR_PROVINCE_NAME: "ST",
  45. NameOID.ORGANIZATION_NAME: "O",
  46. NameOID.ORGANIZATIONAL_UNIT_NAME: "OU",
  47. NameOID.COUNTRY_NAME: "C",
  48. NameOID.STREET_ADDRESS: "STREET",
  49. NameOID.DOMAIN_COMPONENT: "DC",
  50. NameOID.USER_ID: "UID",
  51. }
  52. _NAME_TO_NAMEOID = {v: k for k, v in _NAMEOID_TO_NAME.items()}
  53. _NAMEOID_LENGTH_LIMIT = {
  54. NameOID.COUNTRY_NAME: (2, 2),
  55. NameOID.JURISDICTION_COUNTRY_NAME: (2, 2),
  56. NameOID.COMMON_NAME: (1, 64),
  57. }
  58. def _escape_dn_value(val: str | bytes) -> str:
  59. """Escape special characters in RFC4514 Distinguished Name value."""
  60. if not val:
  61. return ""
  62. # RFC 4514 Section 2.4 defines the value as being the # (U+0023) character
  63. # followed by the hexadecimal encoding of the octets.
  64. if isinstance(val, bytes):
  65. return "#" + binascii.hexlify(val).decode("utf8")
  66. # See https://tools.ietf.org/html/rfc4514#section-2.4
  67. val = val.replace("\\", "\\\\")
  68. val = val.replace('"', '\\"')
  69. val = val.replace("+", "\\+")
  70. val = val.replace(",", "\\,")
  71. val = val.replace(";", "\\;")
  72. val = val.replace("<", "\\<")
  73. val = val.replace(">", "\\>")
  74. val = val.replace("\0", "\\00")
  75. if val[0] in ("#", " "):
  76. val = "\\" + val
  77. if val[-1] == " ":
  78. val = val[:-1] + "\\ "
  79. return val
  80. def _unescape_dn_value(val: str) -> str:
  81. if not val:
  82. return ""
  83. # See https://tools.ietf.org/html/rfc4514#section-3
  84. # special = escaped / SPACE / SHARP / EQUALS
  85. # escaped = DQUOTE / PLUS / COMMA / SEMI / LANGLE / RANGLE
  86. def sub(m):
  87. val = m.group(1)
  88. # Regular escape
  89. if len(val) == 1:
  90. return val
  91. # Hex-value scape
  92. return chr(int(val, 16))
  93. return _RFC4514NameParser._PAIR_RE.sub(sub, val)
  94. NameAttributeValueType = typing.TypeVar(
  95. "NameAttributeValueType",
  96. typing.Union[str, bytes],
  97. str,
  98. bytes,
  99. covariant=True,
  100. )
  101. class NameAttribute(typing.Generic[NameAttributeValueType]):
  102. def __init__(
  103. self,
  104. oid: ObjectIdentifier,
  105. value: NameAttributeValueType,
  106. _type: _ASN1Type | None = None,
  107. *,
  108. _validate: bool = True,
  109. ) -> None:
  110. if not isinstance(oid, ObjectIdentifier):
  111. raise TypeError(
  112. "oid argument must be an ObjectIdentifier instance."
  113. )
  114. if _type == _ASN1Type.BitString:
  115. if oid != NameOID.X500_UNIQUE_IDENTIFIER:
  116. raise TypeError(
  117. "oid must be X500_UNIQUE_IDENTIFIER for BitString type."
  118. )
  119. if not isinstance(value, bytes):
  120. raise TypeError("value must be bytes for BitString")
  121. else:
  122. if not isinstance(value, str):
  123. raise TypeError("value argument must be a str")
  124. length_limits = _NAMEOID_LENGTH_LIMIT.get(oid)
  125. if length_limits is not None:
  126. min_length, max_length = length_limits
  127. assert isinstance(value, str)
  128. c_len = len(value.encode("utf8"))
  129. if c_len < min_length or c_len > max_length:
  130. msg = (
  131. f"Attribute's length must be >= {min_length} and "
  132. f"<= {max_length}, but it was {c_len}"
  133. )
  134. if _validate is True:
  135. raise ValueError(msg)
  136. else:
  137. warnings.warn(msg, stacklevel=2)
  138. # The appropriate ASN1 string type varies by OID and is defined across
  139. # multiple RFCs including 2459, 3280, and 5280. In general UTF8String
  140. # is preferred (2459), but 3280 and 5280 specify several OIDs with
  141. # alternate types. This means when we see the sentinel value we need
  142. # to look up whether the OID has a non-UTF8 type. If it does, set it
  143. # to that. Otherwise, UTF8!
  144. if _type is None:
  145. _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String)
  146. if not isinstance(_type, _ASN1Type):
  147. raise TypeError("_type must be from the _ASN1Type enum")
  148. self._oid = oid
  149. self._value: NameAttributeValueType = value
  150. self._type: _ASN1Type = _type
  151. @property
  152. def oid(self) -> ObjectIdentifier:
  153. return self._oid
  154. @property
  155. def value(self) -> NameAttributeValueType:
  156. return self._value
  157. @property
  158. def rfc4514_attribute_name(self) -> str:
  159. """
  160. The short attribute name (for example "CN") if available,
  161. otherwise the OID dotted string.
  162. """
  163. return _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string)
  164. def rfc4514_string(
  165. self, attr_name_overrides: _OidNameMap | None = None
  166. ) -> str:
  167. """
  168. Format as RFC4514 Distinguished Name string.
  169. Use short attribute name if available, otherwise fall back to OID
  170. dotted string.
  171. """
  172. attr_name = (
  173. attr_name_overrides.get(self.oid) if attr_name_overrides else None
  174. )
  175. if attr_name is None:
  176. attr_name = self.rfc4514_attribute_name
  177. return f"{attr_name}={_escape_dn_value(self.value)}"
  178. def __eq__(self, other: object) -> bool:
  179. if not isinstance(other, NameAttribute):
  180. return NotImplemented
  181. return self.oid == other.oid and self.value == other.value
  182. def __hash__(self) -> int:
  183. return hash((self.oid, self.value))
  184. def __repr__(self) -> str:
  185. return f"<NameAttribute(oid={self.oid}, value={self.value!r})>"
  186. class RelativeDistinguishedName:
  187. def __init__(self, attributes: Iterable[NameAttribute]):
  188. attributes = list(attributes)
  189. if not attributes:
  190. raise ValueError("a relative distinguished name cannot be empty")
  191. if not all(isinstance(x, NameAttribute) for x in attributes):
  192. raise TypeError("attributes must be an iterable of NameAttribute")
  193. # Keep list and frozenset to preserve attribute order where it matters
  194. self._attributes = attributes
  195. self._attribute_set = frozenset(attributes)
  196. if len(self._attribute_set) != len(attributes):
  197. raise ValueError("duplicate attributes are not allowed")
  198. def get_attributes_for_oid(
  199. self,
  200. oid: ObjectIdentifier,
  201. ) -> list[NameAttribute[str | bytes]]:
  202. return [i for i in self if i.oid == oid]
  203. def rfc4514_string(
  204. self, attr_name_overrides: _OidNameMap | None = None
  205. ) -> str:
  206. """
  207. Format as RFC4514 Distinguished Name string.
  208. Within each RDN, attributes are joined by '+', although that is rarely
  209. used in certificates.
  210. """
  211. return "+".join(
  212. attr.rfc4514_string(attr_name_overrides)
  213. for attr in self._attributes
  214. )
  215. def __eq__(self, other: object) -> bool:
  216. if not isinstance(other, RelativeDistinguishedName):
  217. return NotImplemented
  218. return self._attribute_set == other._attribute_set
  219. def __hash__(self) -> int:
  220. return hash(self._attribute_set)
  221. def __iter__(self) -> Iterator[NameAttribute]:
  222. return iter(self._attributes)
  223. def __len__(self) -> int:
  224. return len(self._attributes)
  225. def __repr__(self) -> str:
  226. return f"<RelativeDistinguishedName({self.rfc4514_string()})>"
  227. class Name:
  228. @typing.overload
  229. def __init__(self, attributes: Iterable[NameAttribute]) -> None: ...
  230. @typing.overload
  231. def __init__(
  232. self, attributes: Iterable[RelativeDistinguishedName]
  233. ) -> None: ...
  234. def __init__(
  235. self,
  236. attributes: Iterable[NameAttribute | RelativeDistinguishedName],
  237. ) -> None:
  238. attributes = list(attributes)
  239. if all(isinstance(x, NameAttribute) for x in attributes):
  240. self._attributes = [
  241. RelativeDistinguishedName([typing.cast(NameAttribute, x)])
  242. for x in attributes
  243. ]
  244. elif all(isinstance(x, RelativeDistinguishedName) for x in attributes):
  245. self._attributes = typing.cast(
  246. typing.List[RelativeDistinguishedName], attributes
  247. )
  248. else:
  249. raise TypeError(
  250. "attributes must be a list of NameAttribute"
  251. " or a list RelativeDistinguishedName"
  252. )
  253. @classmethod
  254. def from_rfc4514_string(
  255. cls,
  256. data: str,
  257. attr_name_overrides: _NameOidMap | None = None,
  258. ) -> Name:
  259. return _RFC4514NameParser(data, attr_name_overrides or {}).parse()
  260. def rfc4514_string(
  261. self, attr_name_overrides: _OidNameMap | None = None
  262. ) -> str:
  263. """
  264. Format as RFC4514 Distinguished Name string.
  265. For example 'CN=foobar.com,O=Foo Corp,C=US'
  266. An X.509 name is a two-level structure: a list of sets of attributes.
  267. Each list element is separated by ',' and within each list element, set
  268. elements are separated by '+'. The latter is almost never used in
  269. real world certificates. According to RFC4514 section 2.1 the
  270. RDNSequence must be reversed when converting to string representation.
  271. """
  272. return ",".join(
  273. attr.rfc4514_string(attr_name_overrides)
  274. for attr in reversed(self._attributes)
  275. )
  276. def get_attributes_for_oid(
  277. self,
  278. oid: ObjectIdentifier,
  279. ) -> list[NameAttribute[str | bytes]]:
  280. return [i for i in self if i.oid == oid]
  281. @property
  282. def rdns(self) -> list[RelativeDistinguishedName]:
  283. return self._attributes
  284. def public_bytes(self, backend: typing.Any = None) -> bytes:
  285. return rust_x509.encode_name_bytes(self)
  286. def __eq__(self, other: object) -> bool:
  287. if not isinstance(other, Name):
  288. return NotImplemented
  289. return self._attributes == other._attributes
  290. def __hash__(self) -> int:
  291. # TODO: this is relatively expensive, if this looks like a bottleneck
  292. # for you, consider optimizing!
  293. return hash(tuple(self._attributes))
  294. def __iter__(self) -> Iterator[NameAttribute]:
  295. for rdn in self._attributes:
  296. yield from rdn
  297. def __len__(self) -> int:
  298. return sum(len(rdn) for rdn in self._attributes)
  299. def __repr__(self) -> str:
  300. rdns = ",".join(attr.rfc4514_string() for attr in self._attributes)
  301. return f"<Name({rdns})>"
  302. class _RFC4514NameParser:
  303. _OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+")
  304. _DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*")
  305. _PAIR = r"\\([\\ #=\"\+,;<>]|[\da-zA-Z]{2})"
  306. _PAIR_RE = re.compile(_PAIR)
  307. _LUTF1 = r"[\x01-\x1f\x21\x24-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  308. _SUTF1 = r"[\x01-\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  309. _TUTF1 = r"[\x01-\x1F\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  310. _UTFMB = rf"[\x80-{chr(sys.maxunicode)}]"
  311. _LEADCHAR = rf"{_LUTF1}|{_UTFMB}"
  312. _STRINGCHAR = rf"{_SUTF1}|{_UTFMB}"
  313. _TRAILCHAR = rf"{_TUTF1}|{_UTFMB}"
  314. _STRING_RE = re.compile(
  315. rf"""
  316. (
  317. ({_LEADCHAR}|{_PAIR})
  318. (
  319. ({_STRINGCHAR}|{_PAIR})*
  320. ({_TRAILCHAR}|{_PAIR})
  321. )?
  322. )?
  323. """,
  324. re.VERBOSE,
  325. )
  326. _HEXSTRING_RE = re.compile(r"#([\da-zA-Z]{2})+")
  327. def __init__(self, data: str, attr_name_overrides: _NameOidMap) -> None:
  328. self._data = data
  329. self._idx = 0
  330. self._attr_name_overrides = attr_name_overrides
  331. def _has_data(self) -> bool:
  332. return self._idx < len(self._data)
  333. def _peek(self) -> str | None:
  334. if self._has_data():
  335. return self._data[self._idx]
  336. return None
  337. def _read_char(self, ch: str) -> None:
  338. if self._peek() != ch:
  339. raise ValueError
  340. self._idx += 1
  341. def _read_re(self, pat) -> str:
  342. match = pat.match(self._data, pos=self._idx)
  343. if match is None:
  344. raise ValueError
  345. val = match.group()
  346. self._idx += len(val)
  347. return val
  348. def parse(self) -> Name:
  349. """
  350. Parses the `data` string and converts it to a Name.
  351. According to RFC4514 section 2.1 the RDNSequence must be
  352. reversed when converting to string representation. So, when
  353. we parse it, we need to reverse again to get the RDNs on the
  354. correct order.
  355. """
  356. if not self._has_data():
  357. return Name([])
  358. rdns = [self._parse_rdn()]
  359. while self._has_data():
  360. self._read_char(",")
  361. rdns.append(self._parse_rdn())
  362. return Name(reversed(rdns))
  363. def _parse_rdn(self) -> RelativeDistinguishedName:
  364. nas = [self._parse_na()]
  365. while self._peek() == "+":
  366. self._read_char("+")
  367. nas.append(self._parse_na())
  368. return RelativeDistinguishedName(nas)
  369. def _parse_na(self) -> NameAttribute:
  370. try:
  371. oid_value = self._read_re(self._OID_RE)
  372. except ValueError:
  373. name = self._read_re(self._DESCR_RE)
  374. oid = self._attr_name_overrides.get(
  375. name, _NAME_TO_NAMEOID.get(name)
  376. )
  377. if oid is None:
  378. raise ValueError
  379. else:
  380. oid = ObjectIdentifier(oid_value)
  381. self._read_char("=")
  382. if self._peek() == "#":
  383. value = self._read_re(self._HEXSTRING_RE)
  384. value = binascii.unhexlify(value[1:]).decode()
  385. else:
  386. raw_value = self._read_re(self._STRING_RE)
  387. value = _unescape_dn_value(raw_value)
  388. return NameAttribute(oid, value)