ec.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 cryptography import utils
  6. from cryptography.exceptions import (
  7. InvalidSignature,
  8. UnsupportedAlgorithm,
  9. _Reasons,
  10. )
  11. from cryptography.hazmat.backends.openssl.utils import (
  12. _calculate_digest_and_algorithm,
  13. _check_not_prehashed,
  14. _warn_sign_verify_deprecated,
  15. )
  16. from cryptography.hazmat.primitives import hashes, serialization
  17. from cryptography.hazmat.primitives.asymmetric import (
  18. AsymmetricSignatureContext,
  19. AsymmetricVerificationContext,
  20. ec,
  21. )
  22. def _check_signature_algorithm(signature_algorithm):
  23. if not isinstance(signature_algorithm, ec.ECDSA):
  24. raise UnsupportedAlgorithm(
  25. "Unsupported elliptic curve signature algorithm.",
  26. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  27. )
  28. def _ec_key_curve_sn(backend, ec_key):
  29. group = backend._lib.EC_KEY_get0_group(ec_key)
  30. backend.openssl_assert(group != backend._ffi.NULL)
  31. nid = backend._lib.EC_GROUP_get_curve_name(group)
  32. # The following check is to find EC keys with unnamed curves and raise
  33. # an error for now.
  34. if nid == backend._lib.NID_undef:
  35. raise NotImplementedError(
  36. "ECDSA keys with unnamed curves are unsupported " "at this time"
  37. )
  38. # This is like the above check, but it also catches the case where you
  39. # explicitly encoded a curve with the same parameters as a named curve.
  40. # Don't do that.
  41. if (
  42. backend._lib.CRYPTOGRAPHY_OPENSSL_102U_OR_GREATER
  43. and backend._lib.EC_GROUP_get_asn1_flag(group) == 0
  44. ):
  45. raise NotImplementedError(
  46. "ECDSA keys with unnamed curves are unsupported " "at this time"
  47. )
  48. curve_name = backend._lib.OBJ_nid2sn(nid)
  49. backend.openssl_assert(curve_name != backend._ffi.NULL)
  50. sn = backend._ffi.string(curve_name).decode("ascii")
  51. return sn
  52. def _mark_asn1_named_ec_curve(backend, ec_cdata):
  53. """
  54. Set the named curve flag on the EC_KEY. This causes OpenSSL to
  55. serialize EC keys along with their curve OID which makes
  56. deserialization easier.
  57. """
  58. backend._lib.EC_KEY_set_asn1_flag(
  59. ec_cdata, backend._lib.OPENSSL_EC_NAMED_CURVE
  60. )
  61. def _sn_to_elliptic_curve(backend, sn):
  62. try:
  63. return ec._CURVE_TYPES[sn]()
  64. except KeyError:
  65. raise UnsupportedAlgorithm(
  66. "{} is not a supported elliptic curve".format(sn),
  67. _Reasons.UNSUPPORTED_ELLIPTIC_CURVE,
  68. )
  69. def _ecdsa_sig_sign(backend, private_key, data):
  70. max_size = backend._lib.ECDSA_size(private_key._ec_key)
  71. backend.openssl_assert(max_size > 0)
  72. sigbuf = backend._ffi.new("unsigned char[]", max_size)
  73. siglen_ptr = backend._ffi.new("unsigned int[]", 1)
  74. res = backend._lib.ECDSA_sign(
  75. 0, data, len(data), sigbuf, siglen_ptr, private_key._ec_key
  76. )
  77. backend.openssl_assert(res == 1)
  78. return backend._ffi.buffer(sigbuf)[: siglen_ptr[0]]
  79. def _ecdsa_sig_verify(backend, public_key, signature, data):
  80. res = backend._lib.ECDSA_verify(
  81. 0, data, len(data), signature, len(signature), public_key._ec_key
  82. )
  83. if res != 1:
  84. backend._consume_errors()
  85. raise InvalidSignature
  86. @utils.register_interface(AsymmetricSignatureContext)
  87. class _ECDSASignatureContext(object):
  88. def __init__(self, backend, private_key, algorithm):
  89. self._backend = backend
  90. self._private_key = private_key
  91. self._digest = hashes.Hash(algorithm, backend)
  92. def update(self, data):
  93. self._digest.update(data)
  94. def finalize(self):
  95. digest = self._digest.finalize()
  96. return _ecdsa_sig_sign(self._backend, self._private_key, digest)
  97. @utils.register_interface(AsymmetricVerificationContext)
  98. class _ECDSAVerificationContext(object):
  99. def __init__(self, backend, public_key, signature, algorithm):
  100. self._backend = backend
  101. self._public_key = public_key
  102. self._signature = signature
  103. self._digest = hashes.Hash(algorithm, backend)
  104. def update(self, data):
  105. self._digest.update(data)
  106. def verify(self):
  107. digest = self._digest.finalize()
  108. _ecdsa_sig_verify(
  109. self._backend, self._public_key, self._signature, digest
  110. )
  111. @utils.register_interface(ec.EllipticCurvePrivateKeyWithSerialization)
  112. class _EllipticCurvePrivateKey(object):
  113. def __init__(self, backend, ec_key_cdata, evp_pkey):
  114. self._backend = backend
  115. self._ec_key = ec_key_cdata
  116. self._evp_pkey = evp_pkey
  117. sn = _ec_key_curve_sn(backend, ec_key_cdata)
  118. self._curve = _sn_to_elliptic_curve(backend, sn)
  119. _mark_asn1_named_ec_curve(backend, ec_key_cdata)
  120. curve = utils.read_only_property("_curve")
  121. @property
  122. def key_size(self):
  123. return self.curve.key_size
  124. def signer(self, signature_algorithm):
  125. _warn_sign_verify_deprecated()
  126. _check_signature_algorithm(signature_algorithm)
  127. _check_not_prehashed(signature_algorithm.algorithm)
  128. return _ECDSASignatureContext(
  129. self._backend, self, signature_algorithm.algorithm
  130. )
  131. def exchange(self, algorithm, peer_public_key):
  132. if not (
  133. self._backend.elliptic_curve_exchange_algorithm_supported(
  134. algorithm, self.curve
  135. )
  136. ):
  137. raise UnsupportedAlgorithm(
  138. "This backend does not support the ECDH algorithm.",
  139. _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM,
  140. )
  141. if peer_public_key.curve.name != self.curve.name:
  142. raise ValueError(
  143. "peer_public_key and self are not on the same curve"
  144. )
  145. group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
  146. z_len = (self._backend._lib.EC_GROUP_get_degree(group) + 7) // 8
  147. self._backend.openssl_assert(z_len > 0)
  148. z_buf = self._backend._ffi.new("uint8_t[]", z_len)
  149. peer_key = self._backend._lib.EC_KEY_get0_public_key(
  150. peer_public_key._ec_key
  151. )
  152. r = self._backend._lib.ECDH_compute_key(
  153. z_buf, z_len, peer_key, self._ec_key, self._backend._ffi.NULL
  154. )
  155. self._backend.openssl_assert(r > 0)
  156. return self._backend._ffi.buffer(z_buf)[:z_len]
  157. def public_key(self):
  158. group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
  159. self._backend.openssl_assert(group != self._backend._ffi.NULL)
  160. curve_nid = self._backend._lib.EC_GROUP_get_curve_name(group)
  161. public_ec_key = self._backend._ec_key_new_by_curve_nid(curve_nid)
  162. point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
  163. self._backend.openssl_assert(point != self._backend._ffi.NULL)
  164. res = self._backend._lib.EC_KEY_set_public_key(public_ec_key, point)
  165. self._backend.openssl_assert(res == 1)
  166. evp_pkey = self._backend._ec_cdata_to_evp_pkey(public_ec_key)
  167. return _EllipticCurvePublicKey(self._backend, public_ec_key, evp_pkey)
  168. def private_numbers(self):
  169. bn = self._backend._lib.EC_KEY_get0_private_key(self._ec_key)
  170. private_value = self._backend._bn_to_int(bn)
  171. return ec.EllipticCurvePrivateNumbers(
  172. private_value=private_value,
  173. public_numbers=self.public_key().public_numbers(),
  174. )
  175. def private_bytes(self, encoding, format, encryption_algorithm):
  176. return self._backend._private_key_bytes(
  177. encoding,
  178. format,
  179. encryption_algorithm,
  180. self,
  181. self._evp_pkey,
  182. self._ec_key,
  183. )
  184. def sign(self, data, signature_algorithm):
  185. _check_signature_algorithm(signature_algorithm)
  186. data, algorithm = _calculate_digest_and_algorithm(
  187. self._backend, data, signature_algorithm._algorithm
  188. )
  189. return _ecdsa_sig_sign(self._backend, self, data)
  190. @utils.register_interface(ec.EllipticCurvePublicKeyWithSerialization)
  191. class _EllipticCurvePublicKey(object):
  192. def __init__(self, backend, ec_key_cdata, evp_pkey):
  193. self._backend = backend
  194. self._ec_key = ec_key_cdata
  195. self._evp_pkey = evp_pkey
  196. sn = _ec_key_curve_sn(backend, ec_key_cdata)
  197. self._curve = _sn_to_elliptic_curve(backend, sn)
  198. _mark_asn1_named_ec_curve(backend, ec_key_cdata)
  199. curve = utils.read_only_property("_curve")
  200. @property
  201. def key_size(self):
  202. return self.curve.key_size
  203. def verifier(self, signature, signature_algorithm):
  204. _warn_sign_verify_deprecated()
  205. utils._check_bytes("signature", signature)
  206. _check_signature_algorithm(signature_algorithm)
  207. _check_not_prehashed(signature_algorithm.algorithm)
  208. return _ECDSAVerificationContext(
  209. self._backend, self, signature, signature_algorithm.algorithm
  210. )
  211. def public_numbers(self):
  212. get_func, group = self._backend._ec_key_determine_group_get_func(
  213. self._ec_key
  214. )
  215. point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
  216. self._backend.openssl_assert(point != self._backend._ffi.NULL)
  217. with self._backend._tmp_bn_ctx() as bn_ctx:
  218. bn_x = self._backend._lib.BN_CTX_get(bn_ctx)
  219. bn_y = self._backend._lib.BN_CTX_get(bn_ctx)
  220. res = get_func(group, point, bn_x, bn_y, bn_ctx)
  221. self._backend.openssl_assert(res == 1)
  222. x = self._backend._bn_to_int(bn_x)
  223. y = self._backend._bn_to_int(bn_y)
  224. return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=self._curve)
  225. def _encode_point(self, format):
  226. if format is serialization.PublicFormat.CompressedPoint:
  227. conversion = self._backend._lib.POINT_CONVERSION_COMPRESSED
  228. else:
  229. assert format is serialization.PublicFormat.UncompressedPoint
  230. conversion = self._backend._lib.POINT_CONVERSION_UNCOMPRESSED
  231. group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
  232. self._backend.openssl_assert(group != self._backend._ffi.NULL)
  233. point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
  234. self._backend.openssl_assert(point != self._backend._ffi.NULL)
  235. with self._backend._tmp_bn_ctx() as bn_ctx:
  236. buflen = self._backend._lib.EC_POINT_point2oct(
  237. group, point, conversion, self._backend._ffi.NULL, 0, bn_ctx
  238. )
  239. self._backend.openssl_assert(buflen > 0)
  240. buf = self._backend._ffi.new("char[]", buflen)
  241. res = self._backend._lib.EC_POINT_point2oct(
  242. group, point, conversion, buf, buflen, bn_ctx
  243. )
  244. self._backend.openssl_assert(buflen == res)
  245. return self._backend._ffi.buffer(buf)[:]
  246. def public_bytes(self, encoding, format):
  247. if (
  248. encoding is serialization.Encoding.X962
  249. or format is serialization.PublicFormat.CompressedPoint
  250. or format is serialization.PublicFormat.UncompressedPoint
  251. ):
  252. if encoding is not serialization.Encoding.X962 or format not in (
  253. serialization.PublicFormat.CompressedPoint,
  254. serialization.PublicFormat.UncompressedPoint,
  255. ):
  256. raise ValueError(
  257. "X962 encoding must be used with CompressedPoint or "
  258. "UncompressedPoint format"
  259. )
  260. return self._encode_point(format)
  261. else:
  262. return self._backend._public_key_bytes(
  263. encoding, format, self, self._evp_pkey, None
  264. )
  265. def verify(self, signature, data, signature_algorithm):
  266. _check_signature_algorithm(signature_algorithm)
  267. data, algorithm = _calculate_digest_and_algorithm(
  268. self._backend, data, signature_algorithm._algorithm
  269. )
  270. _ecdsa_sig_verify(self._backend, self, signature, data)