name.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 enum import Enum
  6. from cryptography import utils
  7. from cryptography.hazmat.backends import _get_backend
  8. from cryptography.x509.oid import NameOID, ObjectIdentifier
  9. class _ASN1Type(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. }
  43. def _escape_dn_value(val):
  44. """Escape special characters in RFC4514 Distinguished Name value."""
  45. if not val:
  46. return ""
  47. # See https://tools.ietf.org/html/rfc4514#section-2.4
  48. val = val.replace("\\", "\\\\")
  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("\0", "\\00")
  56. if val[0] in ("#", " "):
  57. val = "\\" + val
  58. if val[-1] == " ":
  59. val = val[:-1] + "\\ "
  60. return val
  61. class NameAttribute(object):
  62. def __init__(self, oid: ObjectIdentifier, value: str, _type=_SENTINEL):
  63. if not isinstance(oid, ObjectIdentifier):
  64. raise TypeError(
  65. "oid argument must be an ObjectIdentifier instance."
  66. )
  67. if not isinstance(value, str):
  68. raise TypeError("value argument must be a text type.")
  69. if (
  70. oid == NameOID.COUNTRY_NAME
  71. or oid == NameOID.JURISDICTION_COUNTRY_NAME
  72. ):
  73. if len(value.encode("utf8")) != 2:
  74. raise ValueError(
  75. "Country name must be a 2 character country code"
  76. )
  77. # The appropriate ASN1 string type varies by OID and is defined across
  78. # multiple RFCs including 2459, 3280, and 5280. In general UTF8String
  79. # is preferred (2459), but 3280 and 5280 specify several OIDs with
  80. # alternate types. This means when we see the sentinel value we need
  81. # to look up whether the OID has a non-UTF8 type. If it does, set it
  82. # to that. Otherwise, UTF8!
  83. if _type == _SENTINEL:
  84. _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String)
  85. if not isinstance(_type, _ASN1Type):
  86. raise TypeError("_type must be from the _ASN1Type enum")
  87. self._oid = oid
  88. self._value = value
  89. self._type = _type
  90. oid = utils.read_only_property("_oid")
  91. value = utils.read_only_property("_value")
  92. def rfc4514_string(self) -> str:
  93. """
  94. Format as RFC4514 Distinguished Name string.
  95. Use short attribute name if available, otherwise fall back to OID
  96. dotted string.
  97. """
  98. key = _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string)
  99. return "%s=%s" % (key, _escape_dn_value(self.value))
  100. def __eq__(self, other: object) -> bool:
  101. if not isinstance(other, NameAttribute):
  102. return NotImplemented
  103. return self.oid == other.oid and self.value == other.value
  104. def __ne__(self, other: object) -> bool:
  105. return not self == other
  106. def __hash__(self) -> int:
  107. return hash((self.oid, self.value))
  108. def __repr__(self) -> str:
  109. return "<NameAttribute(oid={0.oid}, value={0.value!r})>".format(self)
  110. class RelativeDistinguishedName(object):
  111. def __init__(self, attributes: typing.Iterable[NameAttribute]):
  112. attributes = list(attributes)
  113. if not attributes:
  114. raise ValueError("a relative distinguished name cannot be empty")
  115. if not all(isinstance(x, NameAttribute) for x in attributes):
  116. raise TypeError("attributes must be an iterable of NameAttribute")
  117. # Keep list and frozenset to preserve attribute order where it matters
  118. self._attributes = attributes
  119. self._attribute_set = frozenset(attributes)
  120. if len(self._attribute_set) != len(attributes):
  121. raise ValueError("duplicate attributes are not allowed")
  122. def get_attributes_for_oid(self, oid) -> typing.List[NameAttribute]:
  123. return [i for i in self if i.oid == oid]
  124. def rfc4514_string(self) -> str:
  125. """
  126. Format as RFC4514 Distinguished Name string.
  127. Within each RDN, attributes are joined by '+', although that is rarely
  128. used in certificates.
  129. """
  130. return "+".join(attr.rfc4514_string() for attr in self._attributes)
  131. def __eq__(self, other: object) -> bool:
  132. if not isinstance(other, RelativeDistinguishedName):
  133. return NotImplemented
  134. return self._attribute_set == other._attribute_set
  135. def __ne__(self, other: object) -> bool:
  136. return not self == other
  137. def __hash__(self) -> int:
  138. return hash(self._attribute_set)
  139. def __iter__(self) -> typing.Iterator[NameAttribute]:
  140. return iter(self._attributes)
  141. def __len__(self) -> int:
  142. return len(self._attributes)
  143. def __repr__(self) -> str:
  144. return "<RelativeDistinguishedName({})>".format(self.rfc4514_string())
  145. class Name(object):
  146. def __init__(self, attributes):
  147. attributes = list(attributes)
  148. if all(isinstance(x, NameAttribute) for x in attributes):
  149. self._attributes = [
  150. RelativeDistinguishedName([x]) for x in attributes
  151. ]
  152. elif all(isinstance(x, RelativeDistinguishedName) for x in attributes):
  153. self._attributes = attributes
  154. else:
  155. raise TypeError(
  156. "attributes must be a list of NameAttribute"
  157. " or a list RelativeDistinguishedName"
  158. )
  159. def rfc4514_string(self) -> str:
  160. """
  161. Format as RFC4514 Distinguished Name string.
  162. For example 'CN=foobar.com,O=Foo Corp,C=US'
  163. An X.509 name is a two-level structure: a list of sets of attributes.
  164. Each list element is separated by ',' and within each list element, set
  165. elements are separated by '+'. The latter is almost never used in
  166. real world certificates. According to RFC4514 section 2.1 the
  167. RDNSequence must be reversed when converting to string representation.
  168. """
  169. return ",".join(
  170. attr.rfc4514_string() for attr in reversed(self._attributes)
  171. )
  172. def get_attributes_for_oid(self, oid) -> typing.List[NameAttribute]:
  173. return [i for i in self if i.oid == oid]
  174. @property
  175. def rdns(self) -> typing.Iterable[RelativeDistinguishedName]:
  176. return self._attributes
  177. def public_bytes(self, backend=None) -> bytes:
  178. backend = _get_backend(backend)
  179. return backend.x509_name_bytes(self)
  180. def __eq__(self, other: object) -> bool:
  181. if not isinstance(other, Name):
  182. return NotImplemented
  183. return self._attributes == other._attributes
  184. def __ne__(self, other: object) -> bool:
  185. return not self == other
  186. def __hash__(self) -> int:
  187. # TODO: this is relatively expensive, if this looks like a bottleneck
  188. # for you, consider optimizing!
  189. return hash(tuple(self._attributes))
  190. def __iter__(self) -> typing.Iterator[NameAttribute]:
  191. for rdn in self._attributes:
  192. for ava in rdn:
  193. yield ava
  194. def __len__(self) -> int:
  195. return sum(len(rdn) for rdn in self._attributes)
  196. def __repr__(self) -> str:
  197. rdns = ",".join(attr.rfc4514_string() for attr in self._attributes)
  198. return "<Name({})>".format(rdns)