blob: 52357b1d0f17e1965d37bec93d67c63f958454bd [file] [log] [blame]
David Brownb6e0ae62017-11-21 15:13:04 -07001"""
2ECDSA key management
3"""
4
David Brown79c4fcf2021-01-26 15:04:05 -07005# SPDX-License-Identifier: Apache-2.0
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +00006import os.path
Roland Mikhel57041742023-02-03 14:43:13 +01007import hashlib
David Brown79c4fcf2021-01-26 15:04:05 -07008
David Brownb6e0ae62017-11-21 15:13:04 -07009from cryptography.hazmat.backends import default_backend
10from cryptography.hazmat.primitives import serialization
11from cryptography.hazmat.primitives.asymmetric import ec
Roland Mikhel57041742023-02-03 14:43:13 +010012from cryptography.hazmat.primitives.hashes import SHA256, SHA384
David Brownb6e0ae62017-11-21 15:13:04 -070013
14from .general import KeyClass
Fabio Utzig8f289ba2023-01-09 21:01:55 -030015from .privatebytes import PrivateBytesMixin
David Brownb6e0ae62017-11-21 15:13:04 -070016
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000017
David Brownb6e0ae62017-11-21 15:13:04 -070018class ECDSAUsageError(Exception):
19 pass
20
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000021
Roland Mikhel57041742023-02-03 14:43:13 +010022class ECDSAPublicKey(KeyClass):
23 """
24 Wrapper around an ECDSA public key.
25 """
David Brownb6e0ae62017-11-21 15:13:04 -070026 def __init__(self, key):
27 self.key = key
28
David Brownb6e0ae62017-11-21 15:13:04 -070029 def _unsupported(self, name):
30 raise ECDSAUsageError("Operation {} requires private key".format(name))
31
32 def _get_public(self):
Roland Mikhel018b7702023-07-17 15:12:18 +020033 return self.key
David Brownb6e0ae62017-11-21 15:13:04 -070034
35 def get_public_bytes(self):
36 # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
37 return self._get_public().public_bytes(
38 encoding=serialization.Encoding.DER,
39 format=serialization.PublicFormat.SubjectPublicKeyInfo)
40
Fabio Utzig6f286772022-09-04 20:03:11 -030041 def get_public_pem(self):
42 return self._get_public().public_bytes(
43 encoding=serialization.Encoding.PEM,
44 format=serialization.PublicFormat.SubjectPublicKeyInfo)
45
Fabio Utzig8f289ba2023-01-09 21:01:55 -030046 def get_private_bytes(self, minimal, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020047 self._unsupported('get_private_bytes')
48
David Brownb6e0ae62017-11-21 15:13:04 -070049 def export_private(self, path, passwd=None):
50 self._unsupported('export_private')
51
52 def export_public(self, path):
53 """Write the public key to the given file."""
54 pem = self._get_public().public_bytes(
55 encoding=serialization.Encoding.PEM,
56 format=serialization.PublicFormat.SubjectPublicKeyInfo)
57 with open(path, 'wb') as f:
58 f.write(pem)
59
David Brownb6e0ae62017-11-21 15:13:04 -070060
Roland Mikhel57041742023-02-03 14:43:13 +010061class ECDSAPrivateKey(PrivateBytesMixin):
David Brownb6e0ae62017-11-21 15:13:04 -070062 """
63 Wrapper around an ECDSA private key.
64 """
David Brownb6e0ae62017-11-21 15:13:04 -070065 def __init__(self, key):
David Brownb6e0ae62017-11-21 15:13:04 -070066 self.key = key
David Brownb6e0ae62017-11-21 15:13:04 -070067
Roland Mikhel018b7702023-07-17 15:12:18 +020068 def _get_public(self):
69 return self.key.public_key()
70
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +000071 def _build_minimal_ecdsa_privkey(self, der, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020072 '''
73 Builds a new DER that only includes the EC private key, removing the
74 public key that is added as an "optional" BITSTRING.
75 '''
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +000076
77 if format == serialization.PrivateFormat.OpenSSH:
78 print(os.path.basename(__file__) +
79 ': Warning: --minimal is supported only for PKCS8 '
80 'or TraditionalOpenSSL formats')
81 return bytearray(der)
82
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020083 EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!"
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +000084 if format == serialization.PrivateFormat.PKCS8:
85 offset_PUB = 68 # where the context specific TLV starts (tag 0xA1)
86 if der[offset_PUB] != 0xa1:
87 raise ECDSAUsageError(EXCEPTION_TEXT)
88 len_PUB = der[offset_PUB + 1] + 2 # + 2 for 0xA1 0x44 bytes
89 b = bytearray(der[:offset_PUB]) # remove the TLV with the PUB key
90 offset_SEQ = 29
91 if b[offset_SEQ] != 0x30:
92 raise ECDSAUsageError(EXCEPTION_TEXT)
93 b[offset_SEQ + 1] -= len_PUB
94 offset_OCT_STR = 27
95 if b[offset_OCT_STR] != 0x04:
96 raise ECDSAUsageError(EXCEPTION_TEXT)
97 b[offset_OCT_STR + 1] -= len_PUB
98 if b[0] != 0x30 or b[1] != 0x81:
99 raise ECDSAUsageError(EXCEPTION_TEXT)
100 # as b[1] has bit7 set, the length is on b[2]
101 b[2] -= len_PUB
102 if b[2] < 0x80:
103 del(b[1])
104
105 elif format == serialization.PrivateFormat.TraditionalOpenSSL:
106 offset_PUB = 51
107 if der[offset_PUB] != 0xA1:
108 raise ECDSAUsageError(EXCEPTION_TEXT)
109 len_PUB = der[offset_PUB + 1] + 2
110 b = bytearray(der[0:offset_PUB])
111 b[1] -= len_PUB
112
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200113 return b
114
Fabio Utzig8f289ba2023-01-09 21:01:55 -0300115 _VALID_FORMATS = {
116 'pkcs8': serialization.PrivateFormat.PKCS8,
117 'openssl': serialization.PrivateFormat.TraditionalOpenSSL
118 }
Roland Mikhel57041742023-02-03 14:43:13 +0100119 _DEFAULT_FORMAT = 'pkcs8'
Fabio Utzig8f289ba2023-01-09 21:01:55 -0300120
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000121 def get_private_bytes(self, minimal, format):
Roland Mikhel57041742023-02-03 14:43:13 +0100122 format, priv = self._get_private_bytes(minimal,
123 format, ECDSAUsageError)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200124 if minimal:
Roland Mikhel57041742023-02-03 14:43:13 +0100125 priv = self._build_minimal_ecdsa_privkey(
126 priv, self._VALID_FORMATS[format])
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200127 return priv
128
David Brownb6e0ae62017-11-21 15:13:04 -0700129 def export_private(self, path, passwd=None):
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000130 """Write the private key to the given file, protecting it with '
131 'the optional password."""
David Brownb6e0ae62017-11-21 15:13:04 -0700132 if passwd is None:
133 enc = serialization.NoEncryption()
134 else:
135 enc = serialization.BestAvailableEncryption(passwd)
136 pem = self.key.private_bytes(
137 encoding=serialization.Encoding.PEM,
138 format=serialization.PrivateFormat.PKCS8,
139 encryption_algorithm=enc)
140 with open(path, 'wb') as f:
141 f.write(pem)
142
Roland Mikhel57041742023-02-03 14:43:13 +0100143
144class ECDSA256P1Public(ECDSAPublicKey):
145 """
146 Wrapper around an ECDSA (p256) public key.
147 """
148 def __init__(self, key):
149 super().__init__(key)
150 self.key = key
151
152 def shortname(self):
153 return "ecdsa"
154
155 def sig_type(self):
156 return "ECDSA256_SHA256"
157
158 def sig_tlv(self):
159 return "ECDSASIG"
160
161 def sig_len(self):
162 # Early versions of MCUboot (< v1.5.0) required ECDSA
163 # signatures to be padded to 72 bytes. Because the DER
164 # encoding is done with signed integers, the size of the
165 # signature will vary depending on whether the high bit is set
166 # in each value. This padding was done in a
167 # not-easily-reversible way (by just adding zeros).
168 #
169 # The signing code no longer requires this padding, and newer
170 # versions of MCUboot don't require it. But, continue to
171 # return the total length so that the padding can be done if
172 # requested.
173 return 72
174
175 def verify(self, signature, payload):
176 # strip possible paddings added during sign
177 signature = signature[:signature[1] + 2]
178 k = self.key
179 if isinstance(self.key, ec.EllipticCurvePrivateKey):
180 k = self.key.public_key()
181 return k.verify(signature=signature, data=payload,
182 signature_algorithm=ec.ECDSA(SHA256()))
183
184
Roland Mikhel018b7702023-07-17 15:12:18 +0200185class ECDSA256P1(ECDSAPrivateKey, ECDSA256P1Public):
Roland Mikhel57041742023-02-03 14:43:13 +0100186 """
187 Wrapper around an ECDSA (p256) private key.
188 """
189 def __init__(self, key):
190 super().__init__(key)
191 self.key = key
192 self.pad_sig = False
193
194 @staticmethod
195 def generate():
196 pk = ec.generate_private_key(
197 ec.SECP256R1(),
198 backend=default_backend())
199 return ECDSA256P1(pk)
200
David Brown2c9153a2017-11-21 15:18:12 -0700201 def raw_sign(self, payload):
202 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700203 return self.key.sign(
204 data=payload,
205 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700206
207 def sign(self, payload):
David Brown2c9153a2017-11-21 15:18:12 -0700208 sig = self.raw_sign(payload)
David Brown4878c272020-03-10 16:23:56 -0600209 if self.pad_sig:
210 # To make fixed length, pad with one or two zeros.
211 sig += b'\000' * (self.sig_len() - len(sig))
212 return sig
213 else:
214 return sig
Roland Mikhel57041742023-02-03 14:43:13 +0100215
216
217class ECDSA384P1Public(ECDSAPublicKey):
218 """
219 Wrapper around an ECDSA (p384) public key.
220 """
221 def __init__(self, key):
222 super().__init__(key)
223 self.key = key
224
225 def shortname(self):
226 return "ecdsap384"
227
228 def sig_type(self):
229 return "ECDSA384_SHA384"
230
231 def sig_tlv(self):
232 return "ECDSASIG"
233
234 def sig_len(self):
235 # Early versions of MCUboot (< v1.5.0) required ECDSA
236 # signatures to be padded to a fixed length. Because the DER
237 # encoding is done with signed integers, the size of the
238 # signature will vary depending on whether the high bit is set
239 # in each value. This padding was done in a
240 # not-easily-reversible way (by just adding zeros).
241 #
242 # The signing code no longer requires this padding, and newer
243 # versions of MCUboot don't require it. But, continue to
244 # return the total length so that the padding can be done if
245 # requested.
246 return 103
247
248 def verify(self, signature, payload):
249 # strip possible paddings added during sign
250 signature = signature[:signature[1] + 2]
251 k = self.key
252 if isinstance(self.key, ec.EllipticCurvePrivateKey):
253 k = self.key.public_key()
254 return k.verify(signature=signature, data=payload,
255 signature_algorithm=ec.ECDSA(SHA384()))
256
257
Roland Mikhel018b7702023-07-17 15:12:18 +0200258class ECDSA384P1(ECDSAPrivateKey, ECDSA384P1Public):
Roland Mikhel57041742023-02-03 14:43:13 +0100259 """
260 Wrapper around an ECDSA (p384) private key.
261 """
262
263 def __init__(self, key):
264 """key should be an instance of EllipticCurvePrivateKey"""
265 super().__init__(key)
266 self.key = key
267 self.pad_sig = False
268
269 @staticmethod
270 def generate():
271 pk = ec.generate_private_key(
272 ec.SECP384R1(),
273 backend=default_backend())
274 return ECDSA384P1(pk)
275
276 def raw_sign(self, payload):
277 """Return the actual signature"""
278 return self.key.sign(
279 data=payload,
280 signature_algorithm=ec.ECDSA(SHA384()))
281
282 def sign(self, payload):
283 sig = self.raw_sign(payload)
284 if self.pad_sig:
285 # To make fixed length, pad with one or two zeros.
286 sig += b'\000' * (self.sig_len() - len(sig))
287 return sig
288 else:
289 return sig