name.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. elif not isinstance(value, str):
  122. raise TypeError("value argument must be a str")
  123. length_limits = _NAMEOID_LENGTH_LIMIT.get(oid)
  124. if length_limits is not None:
  125. min_length, max_length = length_limits
  126. assert isinstance(value, str)
  127. c_len = len(value.encode("utf8"))
  128. if c_len < min_length or c_len > max_length:
  129. msg = (
  130. f"Attribute's length must be >= {min_length} and "
  131. f"<= {max_length}, but it was {c_len}"
  132. )
  133. if _validate is True:
  134. raise ValueError(msg)
  135. else:
  136. warnings.warn(msg, stacklevel=2)
  137. # The appropriate ASN1 string type varies by OID and is defined across
  138. # multiple RFCs including 2459, 3280, and 5280. In general UTF8String
  139. # is preferred (2459), but 3280 and 5280 specify several OIDs with
  140. # alternate types. This means when we see the sentinel value we need
  141. # to look up whether the OID has a non-UTF8 type. If it does, set it
  142. # to that. Otherwise, UTF8!
  143. if _type is None:
  144. _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String)
  145. if not isinstance(_type, _ASN1Type):
  146. raise TypeError("_type must be from the _ASN1Type enum")
  147. self._oid = oid
  148. self._value: NameAttributeValueType = value
  149. self._type: _ASN1Type = _type
  150. @property
  151. def oid(self) -> ObjectIdentifier:
  152. return self._oid
  153. @property
  154. def value(self) -> NameAttributeValueType:
  155. return self._value
  156. @property
  157. def rfc4514_attribute_name(self) -> str:
  158. """
  159. The short attribute name (for example "CN") if available,
  160. otherwise the OID dotted string.
  161. """
  162. return _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string)
  163. def rfc4514_string(
  164. self, attr_name_overrides: _OidNameMap | None = None
  165. ) -> str:
  166. """
  167. Format as RFC4514 Distinguished Name string.
  168. Use short attribute name if available, otherwise fall back to OID
  169. dotted string.
  170. """
  171. attr_name = (
  172. attr_name_overrides.get(self.oid) if attr_name_overrides else None
  173. )
  174. if attr_name is None:
  175. attr_name = self.rfc4514_attribute_name
  176. return f"{attr_name}={_escape_dn_value(self.value)}"
  177. def __eq__(self, other: object) -> bool:
  178. if not isinstance(other, NameAttribute):
  179. return NotImplemented
  180. return self.oid == other.oid and self.value == other.value
  181. def __hash__(self) -> int:
  182. return hash((self.oid, self.value))
  183. def __repr__(self) -> str:
  184. return f"<NameAttribute(oid={self.oid}, value={self.value!r})>"
  185. class RelativeDistinguishedName:
  186. def __init__(self, attributes: Iterable[NameAttribute]):
  187. attributes = list(attributes)
  188. if not attributes:
  189. raise ValueError("a relative distinguished name cannot be empty")
  190. if not all(isinstance(x, NameAttribute) for x in attributes):
  191. raise TypeError("attributes must be an iterable of NameAttribute")
  192. # Keep list and frozenset to preserve attribute order where it matters
  193. self._attributes = attributes
  194. self._attribute_set = frozenset(attributes)
  195. if len(self._attribute_set) != len(attributes):
  196. raise ValueError("duplicate attributes are not allowed")
  197. def get_attributes_for_oid(
  198. self,
  199. oid: ObjectIdentifier,
  200. ) -> list[NameAttribute[str | bytes]]:
  201. return [i for i in self if i.oid == oid]
  202. def rfc4514_string(
  203. self, attr_name_overrides: _OidNameMap | None = None
  204. ) -> str:
  205. """
  206. Format as RFC4514 Distinguished Name string.
  207. Within each RDN, attributes are joined by '+', although that is rarely
  208. used in certificates.
  209. """
  210. return "+".join(
  211. attr.rfc4514_string(attr_name_overrides)
  212. for attr in self._attributes
  213. )
  214. def __eq__(self, other: object) -> bool:
  215. if not isinstance(other, RelativeDistinguishedName):
  216. return NotImplemented
  217. return self._attribute_set == other._attribute_set
  218. def __hash__(self) -> int:
  219. return hash(self._attribute_set)
  220. def __iter__(self) -> Iterator[NameAttribute]:
  221. return iter(self._attributes)
  222. def __len__(self) -> int:
  223. return len(self._attributes)
  224. def __repr__(self) -> str:
  225. return f"<RelativeDistinguishedName({self.rfc4514_string()})>"
  226. class Name:
  227. @typing.overload
  228. def __init__(self, attributes: Iterable[NameAttribute]) -> None: ...
  229. @typing.overload
  230. def __init__(
  231. self, attributes: Iterable[RelativeDistinguishedName]
  232. ) -> None: ...
  233. def __init__(
  234. self,
  235. attributes: Iterable[NameAttribute | RelativeDistinguishedName],
  236. ) -> None:
  237. attributes = list(attributes)
  238. if all(isinstance(x, NameAttribute) for x in attributes):
  239. self._attributes = [
  240. RelativeDistinguishedName([typing.cast(NameAttribute, x)])
  241. for x in attributes
  242. ]
  243. elif all(isinstance(x, RelativeDistinguishedName) for x in attributes):
  244. self._attributes = typing.cast(
  245. typing.List[RelativeDistinguishedName], attributes
  246. )
  247. else:
  248. raise TypeError(
  249. "attributes must be a list of NameAttribute"
  250. " or a list RelativeDistinguishedName"
  251. )
  252. @classmethod
  253. def from_rfc4514_string(
  254. cls,
  255. data: str,
  256. attr_name_overrides: _NameOidMap | None = None,
  257. ) -> Name:
  258. return _RFC4514NameParser(data, attr_name_overrides or {}).parse()
  259. def rfc4514_string(
  260. self, attr_name_overrides: _OidNameMap | None = None
  261. ) -> str:
  262. """
  263. Format as RFC4514 Distinguished Name string.
  264. For example 'CN=foobar.com,O=Foo Corp,C=US'
  265. An X.509 name is a two-level structure: a list of sets of attributes.
  266. Each list element is separated by ',' and within each list element, set
  267. elements are separated by '+'. The latter is almost never used in
  268. real world certificates. According to RFC4514 section 2.1 the
  269. RDNSequence must be reversed when converting to string representation.
  270. """
  271. return ",".join(
  272. attr.rfc4514_string(attr_name_overrides)
  273. for attr in reversed(self._attributes)
  274. )
  275. def get_attributes_for_oid(
  276. self,
  277. oid: ObjectIdentifier,
  278. ) -> list[NameAttribute[str | bytes]]:
  279. return [i for i in self if i.oid == oid]
  280. @property
  281. def rdns(self) -> list[RelativeDistinguishedName]:
  282. return self._attributes
  283. def public_bytes(self, backend: typing.Any = None) -> bytes:
  284. return rust_x509.encode_name_bytes(self)
  285. def __eq__(self, other: object) -> bool:
  286. if not isinstance(other, Name):
  287. return NotImplemented
  288. return self._attributes == other._attributes
  289. def __hash__(self) -> int:
  290. # TODO: this is relatively expensive, if this looks like a bottleneck
  291. # for you, consider optimizing!
  292. return hash(tuple(self._attributes))
  293. def __iter__(self) -> Iterator[NameAttribute]:
  294. for rdn in self._attributes:
  295. yield from rdn
  296. def __len__(self) -> int:
  297. return sum(len(rdn) for rdn in self._attributes)
  298. def __repr__(self) -> str:
  299. rdns = ",".join(attr.rfc4514_string() for attr in self._attributes)
  300. return f"<Name({rdns})>"
  301. class _RFC4514NameParser:
  302. _OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+")
  303. _DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*")
  304. _PAIR = r"\\([\\ #=\"\+,;<>]|[\da-zA-Z]{2})"
  305. _PAIR_RE = re.compile(_PAIR)
  306. _LUTF1 = r"[\x01-\x1f\x21\x24-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  307. _SUTF1 = r"[\x01-\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  308. _TUTF1 = r"[\x01-\x1F\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  309. _UTFMB = rf"[\x80-{chr(sys.maxunicode)}]"
  310. _LEADCHAR = rf"{_LUTF1}|{_UTFMB}"
  311. _STRINGCHAR = rf"{_SUTF1}|{_UTFMB}"
  312. _TRAILCHAR = rf"{_TUTF1}|{_UTFMB}"
  313. _STRING_RE = re.compile(
  314. rf"""
  315. (
  316. ({_LEADCHAR}|{_PAIR})
  317. (
  318. ({_STRINGCHAR}|{_PAIR})*
  319. ({_TRAILCHAR}|{_PAIR})
  320. )?
  321. )?
  322. """,
  323. re.VERBOSE,
  324. )
  325. _HEXSTRING_RE = re.compile(r"#([\da-zA-Z]{2})+")
  326. def __init__(self, data: str, attr_name_overrides: _NameOidMap) -> None:
  327. self._data = data
  328. self._idx = 0
  329. self._attr_name_overrides = attr_name_overrides
  330. def _has_data(self) -> bool:
  331. return self._idx < len(self._data)
  332. def _peek(self) -> str | None:
  333. if self._has_data():
  334. return self._data[self._idx]
  335. return None
  336. def _read_char(self, ch: str) -> None:
  337. if self._peek() != ch:
  338. raise ValueError
  339. self._idx += 1
  340. def _read_re(self, pat) -> str:
  341. match = pat.match(self._data, pos=self._idx)
  342. if match is None:
  343. raise ValueError
  344. val = match.group()
  345. self._idx += len(val)
  346. return val
  347. def parse(self) -> Name:
  348. """
  349. Parses the `data` string and converts it to a Name.
  350. According to RFC4514 section 2.1 the RDNSequence must be
  351. reversed when converting to string representation. So, when
  352. we parse it, we need to reverse again to get the RDNs on the
  353. correct order.
  354. """
  355. if not self._has_data():
  356. return Name([])
  357. rdns = [self._parse_rdn()]
  358. while self._has_data():
  359. self._read_char(",")
  360. rdns.append(self._parse_rdn())
  361. return Name(reversed(rdns))
  362. def _parse_rdn(self) -> RelativeDistinguishedName:
  363. nas = [self._parse_na()]
  364. while self._peek() == "+":
  365. self._read_char("+")
  366. nas.append(self._parse_na())
  367. return RelativeDistinguishedName(nas)
  368. def _parse_na(self) -> NameAttribute:
  369. try:
  370. oid_value = self._read_re(self._OID_RE)
  371. except ValueError:
  372. name = self._read_re(self._DESCR_RE)
  373. oid = self._attr_name_overrides.get(
  374. name, _NAME_TO_NAMEOID.get(name)
  375. )
  376. if oid is None:
  377. raise ValueError
  378. else:
  379. oid = ObjectIdentifier(oid_value)
  380. self._read_char("=")
  381. if self._peek() == "#":
  382. value = self._read_re(self._HEXSTRING_RE)
  383. value = binascii.unhexlify(value[1:]).decode()
  384. else:
  385. raw_value = self._read_re(self._STRING_RE)
  386. value = _unescape_dn_value(raw_value)
  387. return NameAttribute(oid, value)