blob: addceb2e52e0ff5b1ce331fcb4e321152113fb9f [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
David Brown79c4fcf2021-01-26 15:04:05 -07007
David Brownb6e0ae62017-11-21 15:13:04 -07008from cryptography.hazmat.backends import default_backend
9from cryptography.hazmat.primitives import serialization
10from cryptography.hazmat.primitives.asymmetric import ec
11from cryptography.hazmat.primitives.hashes import SHA256
12
13from .general import KeyClass
Fabio Utzig8f289ba2023-01-09 21:01:55 -030014from .privatebytes import PrivateBytesMixin
David Brownb6e0ae62017-11-21 15:13:04 -070015
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000016
David Brownb6e0ae62017-11-21 15:13:04 -070017class ECDSAUsageError(Exception):
18 pass
19
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000020
David Brownb6e0ae62017-11-21 15:13:04 -070021class ECDSA256P1Public(KeyClass):
22 def __init__(self, key):
23 self.key = key
24
25 def shortname(self):
26 return "ecdsa"
27
28 def _unsupported(self, name):
29 raise ECDSAUsageError("Operation {} requires private key".format(name))
30
31 def _get_public(self):
32 return self.key
33
34 def get_public_bytes(self):
35 # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
36 return self._get_public().public_bytes(
37 encoding=serialization.Encoding.DER,
38 format=serialization.PublicFormat.SubjectPublicKeyInfo)
39
Fabio Utzig6f286772022-09-04 20:03:11 -030040 def get_public_pem(self):
41 return self._get_public().public_bytes(
42 encoding=serialization.Encoding.PEM,
43 format=serialization.PublicFormat.SubjectPublicKeyInfo)
44
Fabio Utzig8f289ba2023-01-09 21:01:55 -030045 def get_private_bytes(self, minimal, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020046 self._unsupported('get_private_bytes')
47
David Brownb6e0ae62017-11-21 15:13:04 -070048 def export_private(self, path, passwd=None):
49 self._unsupported('export_private')
50
51 def export_public(self, path):
52 """Write the public key to the given file."""
53 pem = self._get_public().public_bytes(
54 encoding=serialization.Encoding.PEM,
55 format=serialization.PublicFormat.SubjectPublicKeyInfo)
56 with open(path, 'wb') as f:
57 f.write(pem)
58
59 def sig_type(self):
60 return "ECDSA256_SHA256"
61
62 def sig_tlv(self):
63 return "ECDSA256"
64
65 def sig_len(self):
David Brown4878c272020-03-10 16:23:56 -060066 # Early versions of MCUboot (< v1.5.0) required ECDSA
67 # signatures to be padded to 72 bytes. Because the DER
68 # encoding is done with signed integers, the size of the
69 # signature will vary depending on whether the high bit is set
70 # in each value. This padding was done in a
71 # not-easily-reversible way (by just adding zeros).
72 #
73 # The signing code no longer requires this padding, and newer
74 # versions of MCUboot don't require it. But, continue to
75 # return the total length so that the padding can be done if
76 # requested.
David Brownb6e0ae62017-11-21 15:13:04 -070077 return 72
78
Fabio Utzig4a5477a2019-05-27 15:45:08 -030079 def verify(self, signature, payload):
Anthony Liu04630ce2020-03-10 11:57:26 +080080 # strip possible paddings added during sign
81 signature = signature[:signature[1] + 2]
Fabio Utzig4a5477a2019-05-27 15:45:08 -030082 k = self.key
83 if isinstance(self.key, ec.EllipticCurvePrivateKey):
84 k = self.key.public_key()
85 return k.verify(signature=signature, data=payload,
86 signature_algorithm=ec.ECDSA(SHA256()))
87
88
Fabio Utzig8f289ba2023-01-09 21:01:55 -030089class ECDSA256P1(ECDSA256P1Public, PrivateBytesMixin):
David Brownb6e0ae62017-11-21 15:13:04 -070090 """
91 Wrapper around an ECDSA private key.
92 """
93
94 def __init__(self, key):
95 """key should be an instance of EllipticCurvePrivateKey"""
96 self.key = key
David Brown4878c272020-03-10 16:23:56 -060097 self.pad_sig = False
David Brownb6e0ae62017-11-21 15:13:04 -070098
99 @staticmethod
100 def generate():
101 pk = ec.generate_private_key(
102 ec.SECP256R1(),
103 backend=default_backend())
104 return ECDSA256P1(pk)
105
106 def _get_public(self):
107 return self.key.public_key()
108
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000109 def _build_minimal_ecdsa_privkey(self, der, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200110 '''
111 Builds a new DER that only includes the EC private key, removing the
112 public key that is added as an "optional" BITSTRING.
113 '''
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000114
115 if format == serialization.PrivateFormat.OpenSSH:
116 print(os.path.basename(__file__) +
117 ': Warning: --minimal is supported only for PKCS8 '
118 'or TraditionalOpenSSL formats')
119 return bytearray(der)
120
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200121 EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!"
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000122 if format == serialization.PrivateFormat.PKCS8:
123 offset_PUB = 68 # where the context specific TLV starts (tag 0xA1)
124 if der[offset_PUB] != 0xa1:
125 raise ECDSAUsageError(EXCEPTION_TEXT)
126 len_PUB = der[offset_PUB + 1] + 2 # + 2 for 0xA1 0x44 bytes
127 b = bytearray(der[:offset_PUB]) # remove the TLV with the PUB key
128 offset_SEQ = 29
129 if b[offset_SEQ] != 0x30:
130 raise ECDSAUsageError(EXCEPTION_TEXT)
131 b[offset_SEQ + 1] -= len_PUB
132 offset_OCT_STR = 27
133 if b[offset_OCT_STR] != 0x04:
134 raise ECDSAUsageError(EXCEPTION_TEXT)
135 b[offset_OCT_STR + 1] -= len_PUB
136 if b[0] != 0x30 or b[1] != 0x81:
137 raise ECDSAUsageError(EXCEPTION_TEXT)
138 # as b[1] has bit7 set, the length is on b[2]
139 b[2] -= len_PUB
140 if b[2] < 0x80:
141 del(b[1])
142
143 elif format == serialization.PrivateFormat.TraditionalOpenSSL:
144 offset_PUB = 51
145 if der[offset_PUB] != 0xA1:
146 raise ECDSAUsageError(EXCEPTION_TEXT)
147 len_PUB = der[offset_PUB + 1] + 2
148 b = bytearray(der[0:offset_PUB])
149 b[1] -= len_PUB
150
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200151 return b
152
Fabio Utzig8f289ba2023-01-09 21:01:55 -0300153 _VALID_FORMATS = {
154 'pkcs8': serialization.PrivateFormat.PKCS8,
155 'openssl': serialization.PrivateFormat.TraditionalOpenSSL
156 }
157 _DEFAULT_FORMAT='pkcs8'
158
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000159 def get_private_bytes(self, minimal, format):
Fabio Utzig8f289ba2023-01-09 21:01:55 -0300160 format, priv = self._get_private_bytes(minimal, format, ECDSAUsageError)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200161 if minimal:
Fabio Utzig8f289ba2023-01-09 21:01:55 -0300162 priv = self._build_minimal_ecdsa_privkey(priv,
163 self._VALID_FORMATS[format])
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200164 return priv
165
David Brownb6e0ae62017-11-21 15:13:04 -0700166 def export_private(self, path, passwd=None):
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000167 """Write the private key to the given file, protecting it with '
168 'the optional password."""
David Brownb6e0ae62017-11-21 15:13:04 -0700169 if passwd is None:
170 enc = serialization.NoEncryption()
171 else:
172 enc = serialization.BestAvailableEncryption(passwd)
173 pem = self.key.private_bytes(
174 encoding=serialization.Encoding.PEM,
175 format=serialization.PrivateFormat.PKCS8,
176 encryption_algorithm=enc)
177 with open(path, 'wb') as f:
178 f.write(pem)
179
David Brown2c9153a2017-11-21 15:18:12 -0700180 def raw_sign(self, payload):
181 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700182 return self.key.sign(
183 data=payload,
184 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700185
186 def sign(self, payload):
David Brown2c9153a2017-11-21 15:18:12 -0700187 sig = self.raw_sign(payload)
David Brown4878c272020-03-10 16:23:56 -0600188 if self.pad_sig:
189 # To make fixed length, pad with one or two zeros.
190 sig += b'\000' * (self.sig_len() - len(sig))
191 return sig
192 else:
193 return sig