blob: 79e4bb8edd7148957121d57bd0004a0606d09319 [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
14
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000015
David Brownb6e0ae62017-11-21 15:13:04 -070016class ECDSAUsageError(Exception):
17 pass
18
Antonio de Angelis7ba01c02022-11-15 15:10:41 +000019
David Brownb6e0ae62017-11-21 15:13:04 -070020class ECDSA256P1Public(KeyClass):
21 def __init__(self, key):
22 self.key = key
23
24 def shortname(self):
25 return "ecdsa"
26
27 def _unsupported(self, name):
28 raise ECDSAUsageError("Operation {} requires private key".format(name))
29
30 def _get_public(self):
31 return self.key
32
33 def get_public_bytes(self):
34 # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
35 return self._get_public().public_bytes(
36 encoding=serialization.Encoding.DER,
37 format=serialization.PublicFormat.SubjectPublicKeyInfo)
38
Fabio Utzig6f286772022-09-04 20:03:11 -030039 def get_public_pem(self):
40 return self._get_public().public_bytes(
41 encoding=serialization.Encoding.PEM,
42 format=serialization.PublicFormat.SubjectPublicKeyInfo)
43
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020044 def get_private_bytes(self, minimal):
45 self._unsupported('get_private_bytes')
46
David Brownb6e0ae62017-11-21 15:13:04 -070047 def export_private(self, path, passwd=None):
48 self._unsupported('export_private')
49
50 def export_public(self, path):
51 """Write the public key to the given file."""
52 pem = self._get_public().public_bytes(
53 encoding=serialization.Encoding.PEM,
54 format=serialization.PublicFormat.SubjectPublicKeyInfo)
55 with open(path, 'wb') as f:
56 f.write(pem)
57
58 def sig_type(self):
59 return "ECDSA256_SHA256"
60
61 def sig_tlv(self):
62 return "ECDSA256"
63
64 def sig_len(self):
David Brown4878c272020-03-10 16:23:56 -060065 # Early versions of MCUboot (< v1.5.0) required ECDSA
66 # signatures to be padded to 72 bytes. Because the DER
67 # encoding is done with signed integers, the size of the
68 # signature will vary depending on whether the high bit is set
69 # in each value. This padding was done in a
70 # not-easily-reversible way (by just adding zeros).
71 #
72 # The signing code no longer requires this padding, and newer
73 # versions of MCUboot don't require it. But, continue to
74 # return the total length so that the padding can be done if
75 # requested.
David Brownb6e0ae62017-11-21 15:13:04 -070076 return 72
77
Fabio Utzig4a5477a2019-05-27 15:45:08 -030078 def verify(self, signature, payload):
Anthony Liu04630ce2020-03-10 11:57:26 +080079 # strip possible paddings added during sign
80 signature = signature[:signature[1] + 2]
Fabio Utzig4a5477a2019-05-27 15:45:08 -030081 k = self.key
82 if isinstance(self.key, ec.EllipticCurvePrivateKey):
83 k = self.key.public_key()
84 return k.verify(signature=signature, data=payload,
85 signature_algorithm=ec.ECDSA(SHA256()))
86
87
David Brownb6e0ae62017-11-21 15:13:04 -070088class ECDSA256P1(ECDSA256P1Public):
89 """
90 Wrapper around an ECDSA private key.
91 """
92
93 def __init__(self, key):
94 """key should be an instance of EllipticCurvePrivateKey"""
95 self.key = key
David Brown4878c272020-03-10 16:23:56 -060096 self.pad_sig = False
David Brownb6e0ae62017-11-21 15:13:04 -070097
98 @staticmethod
99 def generate():
100 pk = ec.generate_private_key(
101 ec.SECP256R1(),
102 backend=default_backend())
103 return ECDSA256P1(pk)
104
105 def _get_public(self):
106 return self.key.public_key()
107
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000108 def _build_minimal_ecdsa_privkey(self, der, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200109 '''
110 Builds a new DER that only includes the EC private key, removing the
111 public key that is added as an "optional" BITSTRING.
112 '''
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000113
114 if format == serialization.PrivateFormat.OpenSSH:
115 print(os.path.basename(__file__) +
116 ': Warning: --minimal is supported only for PKCS8 '
117 'or TraditionalOpenSSL formats')
118 return bytearray(der)
119
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200120 EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!"
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000121 if format == serialization.PrivateFormat.PKCS8:
122 offset_PUB = 68 # where the context specific TLV starts (tag 0xA1)
123 if der[offset_PUB] != 0xa1:
124 raise ECDSAUsageError(EXCEPTION_TEXT)
125 len_PUB = der[offset_PUB + 1] + 2 # + 2 for 0xA1 0x44 bytes
126 b = bytearray(der[:offset_PUB]) # remove the TLV with the PUB key
127 offset_SEQ = 29
128 if b[offset_SEQ] != 0x30:
129 raise ECDSAUsageError(EXCEPTION_TEXT)
130 b[offset_SEQ + 1] -= len_PUB
131 offset_OCT_STR = 27
132 if b[offset_OCT_STR] != 0x04:
133 raise ECDSAUsageError(EXCEPTION_TEXT)
134 b[offset_OCT_STR + 1] -= len_PUB
135 if b[0] != 0x30 or b[1] != 0x81:
136 raise ECDSAUsageError(EXCEPTION_TEXT)
137 # as b[1] has bit7 set, the length is on b[2]
138 b[2] -= len_PUB
139 if b[2] < 0x80:
140 del(b[1])
141
142 elif format == serialization.PrivateFormat.TraditionalOpenSSL:
143 offset_PUB = 51
144 if der[offset_PUB] != 0xA1:
145 raise ECDSAUsageError(EXCEPTION_TEXT)
146 len_PUB = der[offset_PUB + 1] + 2
147 b = bytearray(der[0:offset_PUB])
148 b[1] -= len_PUB
149
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200150 return b
151
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000152 def get_private_bytes(self, minimal, format):
153 formats = {'pkcs8': serialization.PrivateFormat.PKCS8,
154 'openssl': serialization.PrivateFormat.TraditionalOpenSSL
155 }
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200156 priv = self.key.private_bytes(
157 encoding=serialization.Encoding.DER,
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000158 format=formats[format],
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200159 encryption_algorithm=serialization.NoEncryption())
160 if minimal:
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000161 priv = self._build_minimal_ecdsa_privkey(priv, formats[format])
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200162 return priv
163
David Brownb6e0ae62017-11-21 15:13:04 -0700164 def export_private(self, path, passwd=None):
Antonio de Angelis7ba01c02022-11-15 15:10:41 +0000165 """Write the private key to the given file, protecting it with '
166 'the optional password."""
David Brownb6e0ae62017-11-21 15:13:04 -0700167 if passwd is None:
168 enc = serialization.NoEncryption()
169 else:
170 enc = serialization.BestAvailableEncryption(passwd)
171 pem = self.key.private_bytes(
172 encoding=serialization.Encoding.PEM,
173 format=serialization.PrivateFormat.PKCS8,
174 encryption_algorithm=enc)
175 with open(path, 'wb') as f:
176 f.write(pem)
177
David Brown2c9153a2017-11-21 15:18:12 -0700178 def raw_sign(self, payload):
179 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700180 return self.key.sign(
181 data=payload,
182 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700183
184 def sign(self, payload):
David Brown2c9153a2017-11-21 15:18:12 -0700185 sig = self.raw_sign(payload)
David Brown4878c272020-03-10 16:23:56 -0600186 if self.pad_sig:
187 # To make fixed length, pad with one or two zeros.
188 sig += b'\000' * (self.sig_len() - len(sig))
189 return sig
190 else:
191 return sig