name.py 14 KB

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