name.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 typing
  5. from cryptography import utils
  6. from cryptography.hazmat.backends import _get_backend
  7. from cryptography.hazmat.backends.interfaces import Backend
  8. from cryptography.x509.oid import NameOID, ObjectIdentifier
  9. class _ASN1Type(utils.Enum):
  10. UTF8String = 12
  11. NumericString = 18
  12. PrintableString = 19
  13. T61String = 20
  14. IA5String = 22
  15. UTCTime = 23
  16. GeneralizedTime = 24
  17. VisibleString = 26
  18. UniversalString = 28
  19. BMPString = 30
  20. _ASN1_TYPE_TO_ENUM = {i.value: i for i in _ASN1Type}
  21. _SENTINEL = object()
  22. _NAMEOID_DEFAULT_TYPE = {
  23. NameOID.COUNTRY_NAME: _ASN1Type.PrintableString,
  24. NameOID.JURISDICTION_COUNTRY_NAME: _ASN1Type.PrintableString,
  25. NameOID.SERIAL_NUMBER: _ASN1Type.PrintableString,
  26. NameOID.DN_QUALIFIER: _ASN1Type.PrintableString,
  27. NameOID.EMAIL_ADDRESS: _ASN1Type.IA5String,
  28. NameOID.DOMAIN_COMPONENT: _ASN1Type.IA5String,
  29. }
  30. #: Short attribute names from RFC 4514:
  31. #: https://tools.ietf.org/html/rfc4514#page-7
  32. _NAMEOID_TO_NAME = {
  33. NameOID.COMMON_NAME: "CN",
  34. NameOID.LOCALITY_NAME: "L",
  35. NameOID.STATE_OR_PROVINCE_NAME: "ST",
  36. NameOID.ORGANIZATION_NAME: "O",
  37. NameOID.ORGANIZATIONAL_UNIT_NAME: "OU",
  38. NameOID.COUNTRY_NAME: "C",
  39. NameOID.STREET_ADDRESS: "STREET",
  40. NameOID.DOMAIN_COMPONENT: "DC",
  41. NameOID.USER_ID: "UID",
  42. NameOID.EMAIL_ADDRESS: "E",
  43. }
  44. def _escape_dn_value(val: str) -> str:
  45. """Escape special characters in RFC4514 Distinguished Name value."""
  46. if not val:
  47. return ""
  48. # See https://tools.ietf.org/html/rfc4514#section-2.4
  49. val = val.replace("\\", "\\\\")
  50. val = val.replace('"', '\\"')
  51. val = val.replace("+", "\\+")
  52. val = val.replace(",", "\\,")
  53. val = val.replace(";", "\\;")
  54. val = val.replace("<", "\\<")
  55. val = val.replace(">", "\\>")
  56. val = val.replace("\0", "\\00")
  57. if val[0] in ("#", " "):
  58. val = "\\" + val
  59. if val[-1] == " ":
  60. val = val[:-1] + "\\ "
  61. return val
  62. class NameAttribute(object):
  63. def __init__(
  64. self, oid: ObjectIdentifier, value: str, _type=_SENTINEL
  65. ) -> None:
  66. if not isinstance(oid, ObjectIdentifier):
  67. raise TypeError(
  68. "oid argument must be an ObjectIdentifier instance."
  69. )
  70. if not isinstance(value, str):
  71. raise TypeError("value argument must be a str.")
  72. if (
  73. oid == NameOID.COUNTRY_NAME
  74. or oid == NameOID.JURISDICTION_COUNTRY_NAME
  75. ):
  76. if len(value.encode("utf8")) != 2:
  77. raise ValueError(
  78. "Country name must be a 2 character country code"
  79. )
  80. # The appropriate ASN1 string type varies by OID and is defined across
  81. # multiple RFCs including 2459, 3280, and 5280. In general UTF8String
  82. # is preferred (2459), but 3280 and 5280 specify several OIDs with
  83. # alternate types. This means when we see the sentinel value we need
  84. # to look up whether the OID has a non-UTF8 type. If it does, set it
  85. # to that. Otherwise, UTF8!
  86. if _type == _SENTINEL:
  87. _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String)
  88. if not isinstance(_type, _ASN1Type):
  89. raise TypeError("_type must be from the _ASN1Type enum")
  90. self._oid = oid
  91. self._value = value
  92. self._type = _type
  93. @property
  94. def oid(self) -> ObjectIdentifier:
  95. return self._oid
  96. @property
  97. def value(self) -> str:
  98. return self._value
  99. @property
  100. def rfc4514_attribute_name(self) -> str:
  101. """
  102. The short attribute name (for example "CN") if available,
  103. otherwise the OID dotted string.
  104. """
  105. return _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string)
  106. def rfc4514_string(self) -> str:
  107. """
  108. Format as RFC4514 Distinguished Name string.
  109. Use short attribute name if available, otherwise fall back to OID
  110. dotted string.
  111. """
  112. return "%s=%s" % (
  113. self.rfc4514_attribute_name,
  114. _escape_dn_value(self.value),
  115. )
  116. def __eq__(self, other: object) -> bool:
  117. if not isinstance(other, NameAttribute):
  118. return NotImplemented
  119. return self.oid == other.oid and self.value == other.value
  120. def __ne__(self, other: object) -> bool:
  121. return not self == other
  122. def __hash__(self) -> int:
  123. return hash((self.oid, self.value))
  124. def __repr__(self) -> str:
  125. return "<NameAttribute(oid={0.oid}, value={0.value!r})>".format(self)
  126. class RelativeDistinguishedName(object):
  127. def __init__(self, attributes: typing.Iterable[NameAttribute]):
  128. attributes = list(attributes)
  129. if not attributes:
  130. raise ValueError("a relative distinguished name cannot be empty")
  131. if not all(isinstance(x, NameAttribute) for x in attributes):
  132. raise TypeError("attributes must be an iterable of NameAttribute")
  133. # Keep list and frozenset to preserve attribute order where it matters
  134. self._attributes = attributes
  135. self._attribute_set = frozenset(attributes)
  136. if len(self._attribute_set) != len(attributes):
  137. raise ValueError("duplicate attributes are not allowed")
  138. def get_attributes_for_oid(
  139. self, oid: ObjectIdentifier
  140. ) -> typing.List[NameAttribute]:
  141. return [i for i in self if i.oid == oid]
  142. def rfc4514_string(self) -> str:
  143. """
  144. Format as RFC4514 Distinguished Name string.
  145. Within each RDN, attributes are joined by '+', although that is rarely
  146. used in certificates.
  147. """
  148. return "+".join(attr.rfc4514_string() for attr in self._attributes)
  149. def __eq__(self, other: object) -> bool:
  150. if not isinstance(other, RelativeDistinguishedName):
  151. return NotImplemented
  152. return self._attribute_set == other._attribute_set
  153. def __ne__(self, other: object) -> bool:
  154. return not self == other
  155. def __hash__(self) -> int:
  156. return hash(self._attribute_set)
  157. def __iter__(self) -> typing.Iterator[NameAttribute]:
  158. return iter(self._attributes)
  159. def __len__(self) -> int:
  160. return len(self._attributes)
  161. def __repr__(self) -> str:
  162. return "<RelativeDistinguishedName({})>".format(self.rfc4514_string())
  163. class Name(object):
  164. @typing.overload
  165. def __init__(self, attributes: typing.Iterable[NameAttribute]) -> None:
  166. ...
  167. @typing.overload
  168. def __init__(
  169. self, attributes: typing.Iterable[RelativeDistinguishedName]
  170. ) -> None:
  171. ...
  172. def __init__(
  173. self,
  174. attributes: typing.Iterable[
  175. typing.Union[NameAttribute, RelativeDistinguishedName]
  176. ],
  177. ) -> None:
  178. attributes = list(attributes)
  179. if all(isinstance(x, NameAttribute) for x in attributes):
  180. self._attributes = [
  181. RelativeDistinguishedName([typing.cast(NameAttribute, x)])
  182. for x in attributes
  183. ]
  184. elif all(isinstance(x, RelativeDistinguishedName) for x in attributes):
  185. self._attributes = typing.cast(
  186. typing.List[RelativeDistinguishedName], attributes
  187. )
  188. else:
  189. raise TypeError(
  190. "attributes must be a list of NameAttribute"
  191. " or a list RelativeDistinguishedName"
  192. )
  193. def rfc4514_string(self) -> str:
  194. """
  195. Format as RFC4514 Distinguished Name string.
  196. For example 'CN=foobar.com,O=Foo Corp,C=US'
  197. An X.509 name is a two-level structure: a list of sets of attributes.
  198. Each list element is separated by ',' and within each list element, set
  199. elements are separated by '+'. The latter is almost never used in
  200. real world certificates. According to RFC4514 section 2.1 the
  201. RDNSequence must be reversed when converting to string representation.
  202. """
  203. return ",".join(
  204. attr.rfc4514_string() for attr in reversed(self._attributes)
  205. )
  206. def get_attributes_for_oid(
  207. self, oid: ObjectIdentifier
  208. ) -> typing.List[NameAttribute]:
  209. return [i for i in self if i.oid == oid]
  210. @property
  211. def rdns(self) -> typing.List[RelativeDistinguishedName]:
  212. return self._attributes
  213. def public_bytes(self, backend: typing.Optional[Backend] = None) -> bytes:
  214. backend = _get_backend(backend)
  215. return backend.x509_name_bytes(self)
  216. def __eq__(self, other: object) -> bool:
  217. if not isinstance(other, Name):
  218. return NotImplemented
  219. return self._attributes == other._attributes
  220. def __ne__(self, other: object) -> bool:
  221. return not self == other
  222. def __hash__(self) -> int:
  223. # TODO: this is relatively expensive, if this looks like a bottleneck
  224. # for you, consider optimizing!
  225. return hash(tuple(self._attributes))
  226. def __iter__(self) -> typing.Iterator[NameAttribute]:
  227. for rdn in self._attributes:
  228. for ava in rdn:
  229. yield ava
  230. def __len__(self) -> int:
  231. return sum(len(rdn) for rdn in self._attributes)
  232. def __repr__(self) -> str:
  233. rdns = ",".join(attr.rfc4514_string() for attr in self._attributes)
  234. return "<Name({})>".format(rdns)