Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/cryptography/hazmat/backends/openssl/ec.py: 24%

150 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-25 06:13 +0000

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 

5from __future__ import annotations 

6 

7import typing 

8 

9from cryptography.exceptions import ( 

10 InvalidSignature, 

11 UnsupportedAlgorithm, 

12 _Reasons, 

13) 

14from cryptography.hazmat.backends.openssl.utils import ( 

15 _calculate_digest_and_algorithm, 

16 _evp_pkey_derive, 

17) 

18from cryptography.hazmat.primitives import serialization 

19from cryptography.hazmat.primitives.asymmetric import ec 

20 

21if typing.TYPE_CHECKING: 

22 from cryptography.hazmat.backends.openssl.backend import Backend 

23 

24 

25def _check_signature_algorithm( 

26 signature_algorithm: ec.EllipticCurveSignatureAlgorithm, 

27) -> None: 

28 if not isinstance(signature_algorithm, ec.ECDSA): 

29 raise UnsupportedAlgorithm( 

30 "Unsupported elliptic curve signature algorithm.", 

31 _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, 

32 ) 

33 

34 

35def _ec_key_curve_sn(backend: Backend, ec_key) -> str: 

36 group = backend._lib.EC_KEY_get0_group(ec_key) 

37 backend.openssl_assert(group != backend._ffi.NULL) 

38 

39 nid = backend._lib.EC_GROUP_get_curve_name(group) 

40 # The following check is to find EC keys with unnamed curves and raise 

41 # an error for now. 

42 if nid == backend._lib.NID_undef: 

43 raise ValueError( 

44 "ECDSA keys with explicit parameters are unsupported at this time" 

45 ) 

46 

47 # This is like the above check, but it also catches the case where you 

48 # explicitly encoded a curve with the same parameters as a named curve. 

49 # Don't do that. 

50 if ( 

51 not backend._lib.CRYPTOGRAPHY_IS_LIBRESSL 

52 and backend._lib.EC_GROUP_get_asn1_flag(group) == 0 

53 ): 

54 raise ValueError( 

55 "ECDSA keys with explicit parameters are unsupported at this time" 

56 ) 

57 

58 curve_name = backend._lib.OBJ_nid2sn(nid) 

59 backend.openssl_assert(curve_name != backend._ffi.NULL) 

60 

61 sn = backend._ffi.string(curve_name).decode("ascii") 

62 return sn 

63 

64 

65def _mark_asn1_named_ec_curve(backend: Backend, ec_cdata): 

66 """ 

67 Set the named curve flag on the EC_KEY. This causes OpenSSL to 

68 serialize EC keys along with their curve OID which makes 

69 deserialization easier. 

70 """ 

71 

72 backend._lib.EC_KEY_set_asn1_flag( 

73 ec_cdata, backend._lib.OPENSSL_EC_NAMED_CURVE 

74 ) 

75 

76 

77def _check_key_infinity(backend: Backend, ec_cdata) -> None: 

78 point = backend._lib.EC_KEY_get0_public_key(ec_cdata) 

79 backend.openssl_assert(point != backend._ffi.NULL) 

80 group = backend._lib.EC_KEY_get0_group(ec_cdata) 

81 backend.openssl_assert(group != backend._ffi.NULL) 

82 if backend._lib.EC_POINT_is_at_infinity(group, point): 

83 raise ValueError( 

84 "Cannot load an EC public key where the point is at infinity" 

85 ) 

86 

87 

88def _sn_to_elliptic_curve(backend: Backend, sn: str) -> ec.EllipticCurve: 

89 try: 

90 return ec._CURVE_TYPES[sn]() 

91 except KeyError: 

92 raise UnsupportedAlgorithm( 

93 f"{sn} is not a supported elliptic curve", 

94 _Reasons.UNSUPPORTED_ELLIPTIC_CURVE, 

95 ) 

96 

97 

98def _ecdsa_sig_sign( 

99 backend: Backend, private_key: _EllipticCurvePrivateKey, data: bytes 

100) -> bytes: 

101 max_size = backend._lib.ECDSA_size(private_key._ec_key) 

102 backend.openssl_assert(max_size > 0) 

103 

104 sigbuf = backend._ffi.new("unsigned char[]", max_size) 

105 siglen_ptr = backend._ffi.new("unsigned int[]", 1) 

106 res = backend._lib.ECDSA_sign( 

107 0, data, len(data), sigbuf, siglen_ptr, private_key._ec_key 

108 ) 

109 backend.openssl_assert(res == 1) 

110 return backend._ffi.buffer(sigbuf)[: siglen_ptr[0]] 

111 

112 

113def _ecdsa_sig_verify( 

114 backend: Backend, 

115 public_key: _EllipticCurvePublicKey, 

116 signature: bytes, 

117 data: bytes, 

118) -> None: 

119 res = backend._lib.ECDSA_verify( 

120 0, data, len(data), signature, len(signature), public_key._ec_key 

121 ) 

122 if res != 1: 

123 backend._consume_errors() 

124 raise InvalidSignature 

125 

126 

127class _EllipticCurvePrivateKey(ec.EllipticCurvePrivateKey): 

128 def __init__(self, backend: Backend, ec_key_cdata, evp_pkey): 

129 self._backend = backend 

130 self._ec_key = ec_key_cdata 

131 self._evp_pkey = evp_pkey 

132 

133 sn = _ec_key_curve_sn(backend, ec_key_cdata) 

134 self._curve = _sn_to_elliptic_curve(backend, sn) 

135 _mark_asn1_named_ec_curve(backend, ec_key_cdata) 

136 _check_key_infinity(backend, ec_key_cdata) 

137 

138 @property 

139 def curve(self) -> ec.EllipticCurve: 

140 return self._curve 

141 

142 @property 

143 def key_size(self) -> int: 

144 return self.curve.key_size 

145 

146 def exchange( 

147 self, algorithm: ec.ECDH, peer_public_key: ec.EllipticCurvePublicKey 

148 ) -> bytes: 

149 if not ( 

150 self._backend.elliptic_curve_exchange_algorithm_supported( 

151 algorithm, self.curve 

152 ) 

153 ): 

154 raise UnsupportedAlgorithm( 

155 "This backend does not support the ECDH algorithm.", 

156 _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, 

157 ) 

158 

159 if peer_public_key.curve.name != self.curve.name: 

160 raise ValueError( 

161 "peer_public_key and self are not on the same curve" 

162 ) 

163 

164 return _evp_pkey_derive(self._backend, self._evp_pkey, peer_public_key) 

165 

166 def public_key(self) -> ec.EllipticCurvePublicKey: 

167 group = self._backend._lib.EC_KEY_get0_group(self._ec_key) 

168 self._backend.openssl_assert(group != self._backend._ffi.NULL) 

169 

170 curve_nid = self._backend._lib.EC_GROUP_get_curve_name(group) 

171 public_ec_key = self._backend._ec_key_new_by_curve_nid(curve_nid) 

172 

173 point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) 

174 self._backend.openssl_assert(point != self._backend._ffi.NULL) 

175 

176 res = self._backend._lib.EC_KEY_set_public_key(public_ec_key, point) 

177 self._backend.openssl_assert(res == 1) 

178 

179 evp_pkey = self._backend._ec_cdata_to_evp_pkey(public_ec_key) 

180 

181 return _EllipticCurvePublicKey(self._backend, public_ec_key, evp_pkey) 

182 

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 

191 def private_bytes( 

192 self, 

193 encoding: serialization.Encoding, 

194 format: serialization.PrivateFormat, 

195 encryption_algorithm: serialization.KeySerializationEncryption, 

196 ) -> bytes: 

197 return self._backend._private_key_bytes( 

198 encoding, 

199 format, 

200 encryption_algorithm, 

201 self, 

202 self._evp_pkey, 

203 self._ec_key, 

204 ) 

205 

206 def sign( 

207 self, 

208 data: bytes, 

209 signature_algorithm: ec.EllipticCurveSignatureAlgorithm, 

210 ) -> bytes: 

211 _check_signature_algorithm(signature_algorithm) 

212 data, _ = _calculate_digest_and_algorithm( 

213 data, 

214 signature_algorithm.algorithm, 

215 ) 

216 return _ecdsa_sig_sign(self._backend, self, data) 

217 

218 

219class _EllipticCurvePublicKey(ec.EllipticCurvePublicKey): 

220 def __init__(self, backend: Backend, ec_key_cdata, evp_pkey): 

221 self._backend = backend 

222 self._ec_key = ec_key_cdata 

223 self._evp_pkey = evp_pkey 

224 

225 sn = _ec_key_curve_sn(backend, ec_key_cdata) 

226 self._curve = _sn_to_elliptic_curve(backend, sn) 

227 _mark_asn1_named_ec_curve(backend, ec_key_cdata) 

228 _check_key_infinity(backend, ec_key_cdata) 

229 

230 @property 

231 def curve(self) -> ec.EllipticCurve: 

232 return self._curve 

233 

234 @property 

235 def key_size(self) -> int: 

236 return self.curve.key_size 

237 

238 def __eq__(self, other: object) -> bool: 

239 if not isinstance(other, _EllipticCurvePublicKey): 

240 return NotImplemented 

241 

242 return ( 

243 self._backend._lib.EVP_PKEY_cmp(self._evp_pkey, other._evp_pkey) 

244 == 1 

245 ) 

246 

247 def public_numbers(self) -> ec.EllipticCurvePublicNumbers: 

248 group = self._backend._lib.EC_KEY_get0_group(self._ec_key) 

249 self._backend.openssl_assert(group != self._backend._ffi.NULL) 

250 

251 point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) 

252 self._backend.openssl_assert(point != self._backend._ffi.NULL) 

253 

254 with self._backend._tmp_bn_ctx() as bn_ctx: 

255 bn_x = self._backend._lib.BN_CTX_get(bn_ctx) 

256 bn_y = self._backend._lib.BN_CTX_get(bn_ctx) 

257 

258 res = self._backend._lib.EC_POINT_get_affine_coordinates( 

259 group, point, bn_x, bn_y, bn_ctx 

260 ) 

261 self._backend.openssl_assert(res == 1) 

262 

263 x = self._backend._bn_to_int(bn_x) 

264 y = self._backend._bn_to_int(bn_y) 

265 

266 return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=self._curve) 

267 

268 def _encode_point(self, format: serialization.PublicFormat) -> bytes: 

269 if format is serialization.PublicFormat.CompressedPoint: 

270 conversion = self._backend._lib.POINT_CONVERSION_COMPRESSED 

271 else: 

272 assert format is serialization.PublicFormat.UncompressedPoint 

273 conversion = self._backend._lib.POINT_CONVERSION_UNCOMPRESSED 

274 

275 group = self._backend._lib.EC_KEY_get0_group(self._ec_key) 

276 self._backend.openssl_assert(group != self._backend._ffi.NULL) 

277 point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) 

278 self._backend.openssl_assert(point != self._backend._ffi.NULL) 

279 with self._backend._tmp_bn_ctx() as bn_ctx: 

280 buflen = self._backend._lib.EC_POINT_point2oct( 

281 group, point, conversion, self._backend._ffi.NULL, 0, bn_ctx 

282 ) 

283 self._backend.openssl_assert(buflen > 0) 

284 buf = self._backend._ffi.new("char[]", buflen) 

285 res = self._backend._lib.EC_POINT_point2oct( 

286 group, point, conversion, buf, buflen, bn_ctx 

287 ) 

288 self._backend.openssl_assert(buflen == res) 

289 

290 return self._backend._ffi.buffer(buf)[:] 

291 

292 def public_bytes( 

293 self, 

294 encoding: serialization.Encoding, 

295 format: serialization.PublicFormat, 

296 ) -> bytes: 

297 if ( 

298 encoding is serialization.Encoding.X962 

299 or format is serialization.PublicFormat.CompressedPoint 

300 or format is serialization.PublicFormat.UncompressedPoint 

301 ): 

302 if encoding is not serialization.Encoding.X962 or format not in ( 

303 serialization.PublicFormat.CompressedPoint, 

304 serialization.PublicFormat.UncompressedPoint, 

305 ): 

306 raise ValueError( 

307 "X962 encoding must be used with CompressedPoint or " 

308 "UncompressedPoint format" 

309 ) 

310 

311 return self._encode_point(format) 

312 else: 

313 return self._backend._public_key_bytes( 

314 encoding, format, self, self._evp_pkey, None 

315 ) 

316 

317 def verify( 

318 self, 

319 signature: bytes, 

320 data: bytes, 

321 signature_algorithm: ec.EllipticCurveSignatureAlgorithm, 

322 ) -> None: 

323 _check_signature_algorithm(signature_algorithm) 

324 data, _ = _calculate_digest_and_algorithm( 

325 data, 

326 signature_algorithm.algorithm, 

327 ) 

328 _ecdsa_sig_verify(self._backend, self, signature, data)