name.py 8.1 KB

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