blob: 0433beb5dbab5cb887409f27efd73c1dd78978a2 [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
15class ECDSAUsageError(Exception):
16 pass
17
18class ECDSA256P1Public(KeyClass):
19 def __init__(self, key):
20 self.key = key
21
22 def shortname(self):
23 return "ecdsa"
24
25 def _unsupported(self, name):
26 raise ECDSAUsageError("Operation {} requires private key".format(name))
27
28 def _get_public(self):
29 return self.key
30
31 def get_public_bytes(self):
32 # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format
33 return self._get_public().public_bytes(
34 encoding=serialization.Encoding.DER,
35 format=serialization.PublicFormat.SubjectPublicKeyInfo)
36
Fabio Utzig6f286772022-09-04 20:03:11 -030037 def get_public_pem(self):
38 return self._get_public().public_bytes(
39 encoding=serialization.Encoding.PEM,
40 format=serialization.PublicFormat.SubjectPublicKeyInfo)
41
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020042 def get_private_bytes(self, minimal):
43 self._unsupported('get_private_bytes')
44
David Brownb6e0ae62017-11-21 15:13:04 -070045 def export_private(self, path, passwd=None):
46 self._unsupported('export_private')
47
48 def export_public(self, path):
49 """Write the public key to the given file."""
50 pem = self._get_public().public_bytes(
51 encoding=serialization.Encoding.PEM,
52 format=serialization.PublicFormat.SubjectPublicKeyInfo)
53 with open(path, 'wb') as f:
54 f.write(pem)
55
56 def sig_type(self):
57 return "ECDSA256_SHA256"
58
59 def sig_tlv(self):
60 return "ECDSA256"
61
62 def sig_len(self):
David Brown4878c272020-03-10 16:23:56 -060063 # Early versions of MCUboot (< v1.5.0) required ECDSA
64 # signatures to be padded to 72 bytes. Because the DER
65 # encoding is done with signed integers, the size of the
66 # signature will vary depending on whether the high bit is set
67 # in each value. This padding was done in a
68 # not-easily-reversible way (by just adding zeros).
69 #
70 # The signing code no longer requires this padding, and newer
71 # versions of MCUboot don't require it. But, continue to
72 # return the total length so that the padding can be done if
73 # requested.
David Brownb6e0ae62017-11-21 15:13:04 -070074 return 72
75
Fabio Utzig4a5477a2019-05-27 15:45:08 -030076 def verify(self, signature, payload):
Anthony Liu04630ce2020-03-10 11:57:26 +080077 # strip possible paddings added during sign
78 signature = signature[:signature[1] + 2]
Fabio Utzig4a5477a2019-05-27 15:45:08 -030079 k = self.key
80 if isinstance(self.key, ec.EllipticCurvePrivateKey):
81 k = self.key.public_key()
82 return k.verify(signature=signature, data=payload,
83 signature_algorithm=ec.ECDSA(SHA256()))
84
85
David Brownb6e0ae62017-11-21 15:13:04 -070086class ECDSA256P1(ECDSA256P1Public):
87 """
88 Wrapper around an ECDSA private key.
89 """
90
91 def __init__(self, key):
92 """key should be an instance of EllipticCurvePrivateKey"""
93 self.key = key
David Brown4878c272020-03-10 16:23:56 -060094 self.pad_sig = False
David Brownb6e0ae62017-11-21 15:13:04 -070095
96 @staticmethod
97 def generate():
98 pk = ec.generate_private_key(
99 ec.SECP256R1(),
100 backend=default_backend())
101 return ECDSA256P1(pk)
102
103 def _get_public(self):
104 return self.key.public_key()
105
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000106 def _build_minimal_ecdsa_privkey(self, der, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200107 '''
108 Builds a new DER that only includes the EC private key, removing the
109 public key that is added as an "optional" BITSTRING.
110 '''
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000111
112 if format == serialization.PrivateFormat.OpenSSH:
113 print(os.path.basename(__file__) +
114 ': Warning: --minimal is supported only for PKCS8 '
115 'or TraditionalOpenSSL formats')
116 return bytearray(der)
117
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200118 EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!"
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000119 if format == serialization.PrivateFormat.PKCS8:
120 offset_PUB = 68 # where the context specific TLV starts (tag 0xA1)
121 if der[offset_PUB] != 0xa1:
122 raise ECDSAUsageError(EXCEPTION_TEXT)
123 len_PUB = der[offset_PUB + 1] + 2 # + 2 for 0xA1 0x44 bytes
124 b = bytearray(der[:offset_PUB]) # remove the TLV with the PUB key
125 offset_SEQ = 29
126 if b[offset_SEQ] != 0x30:
127 raise ECDSAUsageError(EXCEPTION_TEXT)
128 b[offset_SEQ + 1] -= len_PUB
129 offset_OCT_STR = 27
130 if b[offset_OCT_STR] != 0x04:
131 raise ECDSAUsageError(EXCEPTION_TEXT)
132 b[offset_OCT_STR + 1] -= len_PUB
133 if b[0] != 0x30 or b[1] != 0x81:
134 raise ECDSAUsageError(EXCEPTION_TEXT)
135 # as b[1] has bit7 set, the length is on b[2]
136 b[2] -= len_PUB
137 if b[2] < 0x80:
138 del(b[1])
139
140 elif format == serialization.PrivateFormat.TraditionalOpenSSL:
141 offset_PUB = 51
142 if der[offset_PUB] != 0xA1:
143 raise ECDSAUsageError(EXCEPTION_TEXT)
144 len_PUB = der[offset_PUB + 1] + 2
145 b = bytearray(der[0:offset_PUB])
146 b[1] -= len_PUB
147
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200148 return b
149
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000150 def get_private_bytes(self, minimal, format):
151 formats = {'pkcs8': serialization.PrivateFormat.PKCS8,
152 'openssl': serialization.PrivateFormat.TraditionalOpenSSL
153 }
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200154 priv = self.key.private_bytes(
155 encoding=serialization.Encoding.DER,
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000156 format=formats[format],
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200157 encryption_algorithm=serialization.NoEncryption())
158 if minimal:
Antonio de Angelisc6e7e9b2022-11-15 15:06:40 +0000159 priv = self._build_minimal_ecdsa_privkey(priv, formats[format])
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200160 return priv
161
David Brownb6e0ae62017-11-21 15:13:04 -0700162 def export_private(self, path, passwd=None):
163 """Write the private key to the given file, protecting it with the optional password."""
164 if passwd is None:
165 enc = serialization.NoEncryption()
166 else:
167 enc = serialization.BestAvailableEncryption(passwd)
168 pem = self.key.private_bytes(
169 encoding=serialization.Encoding.PEM,
170 format=serialization.PrivateFormat.PKCS8,
171 encryption_algorithm=enc)
172 with open(path, 'wb') as f:
173 f.write(pem)
174
David Brown2c9153a2017-11-21 15:18:12 -0700175 def raw_sign(self, payload):
176 """Return the actual signature"""
David Brownb6e0ae62017-11-21 15:13:04 -0700177 return self.key.sign(
178 data=payload,
179 signature_algorithm=ec.ECDSA(SHA256()))
David Brown2c9153a2017-11-21 15:18:12 -0700180
181 def sign(self, payload):
David Brown2c9153a2017-11-21 15:18:12 -0700182 sig = self.raw_sign(payload)
David Brown4878c272020-03-10 16:23:56 -0600183 if self.pad_sig:
184 # To make fixed length, pad with one or two zeros.
185 sig += b'\000' * (self.sig_len() - len(sig))
186 return sig
187 else:
188 return sig