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 |
| 14 | |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame^] | 15 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 16 | class ECDSAUsageError(Exception): |
| 17 | pass |
| 18 | |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame^] | 19 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 20 | class 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 Utzig | 6f28677 | 2022-09-04 20:03:11 -0300 | [diff] [blame] | 39 | def get_public_pem(self): |
| 40 | return self._get_public().public_bytes( |
| 41 | encoding=serialization.Encoding.PEM, |
| 42 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 43 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 44 | def get_private_bytes(self, minimal): |
| 45 | self._unsupported('get_private_bytes') |
| 46 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 47 | 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 Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 65 | # 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 Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 76 | return 72 |
| 77 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 78 | def verify(self, signature, payload): |
Anthony Liu | 04630ce | 2020-03-10 11:57:26 +0800 | [diff] [blame] | 79 | # strip possible paddings added during sign |
| 80 | signature = signature[:signature[1] + 2] |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 81 | 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 Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 88 | class 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 Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 96 | self.pad_sig = False |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 97 | |
| 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 Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 108 | def _build_minimal_ecdsa_privkey(self, der, format): |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 109 | ''' |
| 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 Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 113 | |
| 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 Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 120 | EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!" |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 121 | 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 Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 150 | return b |
| 151 | |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 152 | def get_private_bytes(self, minimal, format): |
| 153 | formats = {'pkcs8': serialization.PrivateFormat.PKCS8, |
| 154 | 'openssl': serialization.PrivateFormat.TraditionalOpenSSL |
| 155 | } |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 156 | priv = self.key.private_bytes( |
| 157 | encoding=serialization.Encoding.DER, |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 158 | format=formats[format], |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 159 | encryption_algorithm=serialization.NoEncryption()) |
| 160 | if minimal: |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame] | 161 | priv = self._build_minimal_ecdsa_privkey(priv, formats[format]) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 162 | return priv |
| 163 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 164 | def export_private(self, path, passwd=None): |
Antonio de Angelis | 7ba01c0 | 2022-11-15 15:10:41 +0000 | [diff] [blame^] | 165 | """Write the private key to the given file, protecting it with ' |
| 166 | 'the optional password.""" |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 167 | 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 Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 178 | def raw_sign(self, payload): |
| 179 | """Return the actual signature""" |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 180 | return self.key.sign( |
| 181 | data=payload, |
| 182 | signature_algorithm=ec.ECDSA(SHA256())) |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 183 | |
| 184 | def sign(self, payload): |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 185 | sig = self.raw_sign(payload) |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 186 | 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 |