Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

name.py 15KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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: typing.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. 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 f"<RelativeDistinguishedName({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(
  247. cls,
  248. data: str,
  249. attr_name_overrides: typing.Optional[_NameOidMap] = None,
  250. ) -> Name:
  251. return _RFC4514NameParser(data, attr_name_overrides or {}).parse()
  252. def rfc4514_string(
  253. self, attr_name_overrides: typing.Optional[_OidNameMap] = None
  254. ) -> str:
  255. """
  256. Format as RFC4514 Distinguished Name string.
  257. For example 'CN=foobar.com,O=Foo Corp,C=US'
  258. An X.509 name is a two-level structure: a list of sets of attributes.
  259. Each list element is separated by ',' and within each list element, set
  260. elements are separated by '+'. The latter is almost never used in
  261. real world certificates. According to RFC4514 section 2.1 the
  262. RDNSequence must be reversed when converting to string representation.
  263. """
  264. return ",".join(
  265. attr.rfc4514_string(attr_name_overrides)
  266. for attr in reversed(self._attributes)
  267. )
  268. def get_attributes_for_oid(
  269. self, oid: ObjectIdentifier
  270. ) -> typing.List[NameAttribute]:
  271. return [i for i in self if i.oid == oid]
  272. @property
  273. def rdns(self) -> typing.List[RelativeDistinguishedName]:
  274. return self._attributes
  275. def public_bytes(self, backend: typing.Any = None) -> bytes:
  276. return rust_x509.encode_name_bytes(self)
  277. def __eq__(self, other: object) -> bool:
  278. if not isinstance(other, Name):
  279. return NotImplemented
  280. return self._attributes == other._attributes
  281. def __hash__(self) -> int:
  282. # TODO: this is relatively expensive, if this looks like a bottleneck
  283. # for you, consider optimizing!
  284. return hash(tuple(self._attributes))
  285. def __iter__(self) -> typing.Iterator[NameAttribute]:
  286. for rdn in self._attributes:
  287. for ava in rdn:
  288. yield ava
  289. def __len__(self) -> int:
  290. return sum(len(rdn) for rdn in self._attributes)
  291. def __repr__(self) -> str:
  292. rdns = ",".join(attr.rfc4514_string() for attr in self._attributes)
  293. return f"<Name({rdns})>"
  294. class _RFC4514NameParser:
  295. _OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+")
  296. _DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*")
  297. _PAIR = r"\\([\\ #=\"\+,;<>]|[\da-zA-Z]{2})"
  298. _PAIR_RE = re.compile(_PAIR)
  299. _LUTF1 = r"[\x01-\x1f\x21\x24-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  300. _SUTF1 = r"[\x01-\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  301. _TUTF1 = r"[\x01-\x1F\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]"
  302. _UTFMB = rf"[\x80-{chr(sys.maxunicode)}]"
  303. _LEADCHAR = rf"{_LUTF1}|{_UTFMB}"
  304. _STRINGCHAR = rf"{_SUTF1}|{_UTFMB}"
  305. _TRAILCHAR = rf"{_TUTF1}|{_UTFMB}"
  306. _STRING_RE = re.compile(
  307. rf"""
  308. (
  309. ({_LEADCHAR}|{_PAIR})
  310. (
  311. ({_STRINGCHAR}|{_PAIR})*
  312. ({_TRAILCHAR}|{_PAIR})
  313. )?
  314. )?
  315. """,
  316. re.VERBOSE,
  317. )
  318. _HEXSTRING_RE = re.compile(r"#([\da-zA-Z]{2})+")
  319. def __init__(self, data: str, attr_name_overrides: _NameOidMap) -> None:
  320. self._data = data
  321. self._idx = 0
  322. self._attr_name_overrides = attr_name_overrides
  323. def _has_data(self) -> bool:
  324. return self._idx < len(self._data)
  325. def _peek(self) -> typing.Optional[str]:
  326. if self._has_data():
  327. return self._data[self._idx]
  328. return None
  329. def _read_char(self, ch: str) -> None:
  330. if self._peek() != ch:
  331. raise ValueError
  332. self._idx += 1
  333. def _read_re(self, pat) -> str:
  334. match = pat.match(self._data, pos=self._idx)
  335. if match is None:
  336. raise ValueError
  337. val = match.group()
  338. self._idx += len(val)
  339. return val
  340. def parse(self) -> Name:
  341. """
  342. Parses the `data` string and converts it to a Name.
  343. According to RFC4514 section 2.1 the RDNSequence must be
  344. reversed when converting to string representation. So, when
  345. we parse it, we need to reverse again to get the RDNs on the
  346. correct order.
  347. """
  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)