ec.py 13 KB

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