name.py 14 KB

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