David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 1 | """ |
| 2 | ECDSA key management |
| 3 | """ |
| 4 | |
David Brown | 79c4fcf | 2021-01-26 15:04:05 -0700 | [diff] [blame] | 5 | # SPDX-License-Identifier: Apache-2.0 |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 6 | import os.path |
David Brown | 79c4fcf | 2021-01-26 15:04:05 -0700 | [diff] [blame] | 7 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 8 | from cryptography.hazmat.backends import default_backend |
| 9 | from cryptography.hazmat.primitives import serialization |
| 10 | from cryptography.hazmat.primitives.asymmetric import ec |
| 11 | from cryptography.hazmat.primitives.hashes import SHA256 |
| 12 | |
| 13 | from .general import KeyClass |
Fabio Utzig | 8f289ba | 2023-01-09 21:01:55 -0300 | [diff] [blame] | 14 | from .privatebytes import PrivateBytesMixin |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 15 | |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 16 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 17 | class ECDSAUsageError(Exception): |
| 18 | pass |
| 19 | |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 20 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 21 | class 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 Utzig | 6f28677 | 2022-09-04 20:03:11 -0300 | [diff] [blame] | 40 | def get_public_pem(self): |
| 41 | return self._get_public().public_bytes( |
| 42 | encoding=serialization.Encoding.PEM, |
| 43 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 44 | |
Fabio Utzig | 8f289ba | 2023-01-09 21:01:55 -0300 | [diff] [blame] | 45 | def get_private_bytes(self, minimal, format): |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 46 | self._unsupported('get_private_bytes') |
| 47 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 48 | 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 Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 66 | # 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 Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 77 | return 72 |
| 78 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 79 | def verify(self, signature, payload): |
Anthony Liu | 04630ce | 2020-03-10 11:57:26 +0800 | [diff] [blame] | 80 | # strip possible paddings added during sign |
| 81 | signature = signature[:signature[1] + 2] |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 82 | 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 Utzig | 8f289ba | 2023-01-09 21:01:55 -0300 | [diff] [blame] | 89 | class ECDSA256P1(ECDSA256P1Public, PrivateBytesMixin): |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 90 | """ |
| 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 Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 97 | self.pad_sig = False |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 98 | |
| 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 Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 109 | def _build_minimal_ecdsa_privkey(self, der, format): |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 110 | ''' |
| 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 Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 114 | |
| 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 Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 121 | EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!" |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 122 | 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 Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 151 | return b |
| 152 | |
Fabio Utzig | 8f289ba | 2023-01-09 21:01:55 -0300 | [diff] [blame] | 153 | _VALID_FORMATS = { |
| 154 | 'pkcs8': serialization.PrivateFormat.PKCS8, |
| 155 | 'openssl': serialization.PrivateFormat.TraditionalOpenSSL |
| 156 | } |
| 157 | _DEFAULT_FORMAT='pkcs8' |
| 158 | |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 159 | def get_private_bytes(self, minimal, format): |
Fabio Utzig | 8f289ba | 2023-01-09 21:01:55 -0300 | [diff] [blame] | 160 | format, priv = self._get_private_bytes(minimal, format, ECDSAUsageError) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 161 | if minimal: |
Fabio Utzig | 8f289ba | 2023-01-09 21:01:55 -0300 | [diff] [blame] | 162 | priv = self._build_minimal_ecdsa_privkey(priv, |
| 163 | self._VALID_FORMATS[format]) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 164 | return priv |
| 165 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 166 | def export_private(self, path, passwd=None): |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame] | 167 | """Write the private key to the given file, protecting it with ' |
| 168 | 'the optional password.""" |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 169 | 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 Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 180 | def raw_sign(self, payload): |
| 181 | """Return the actual signature""" |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 182 | return self.key.sign( |
| 183 | data=payload, |
| 184 | signature_algorithm=ec.ECDSA(SHA256())) |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 185 | |
| 186 | def sign(self, payload): |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 187 | sig = self.raw_sign(payload) |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 188 | 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 |