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 | |
| 15 | class ECDSAUsageError(Exception): |
| 16 | pass |
| 17 | |
| 18 | class 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 Utzig | 6f28677 | 2022-09-04 20:03:11 -0300 | [diff] [blame] | 37 | def get_public_pem(self): |
| 38 | return self._get_public().public_bytes( |
| 39 | encoding=serialization.Encoding.PEM, |
| 40 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 41 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 42 | def get_private_bytes(self, minimal): |
| 43 | self._unsupported('get_private_bytes') |
| 44 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 45 | 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 Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 63 | # 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 Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 74 | return 72 |
| 75 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 76 | def verify(self, signature, payload): |
Anthony Liu | 04630ce | 2020-03-10 11:57:26 +0800 | [diff] [blame] | 77 | # strip possible paddings added during sign |
| 78 | signature = signature[:signature[1] + 2] |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 79 | 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 Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 86 | class 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 Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 94 | self.pad_sig = False |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 95 | |
| 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 Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame^] | 106 | def _build_minimal_ecdsa_privkey(self, der, format): |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 107 | ''' |
| 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 Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame^] | 111 | |
| 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 Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 118 | EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!" |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame^] | 119 | 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 Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 148 | return b |
| 149 | |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame^] | 150 | def get_private_bytes(self, minimal, format): |
| 151 | formats = {'pkcs8': serialization.PrivateFormat.PKCS8, |
| 152 | 'openssl': serialization.PrivateFormat.TraditionalOpenSSL |
| 153 | } |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 154 | priv = self.key.private_bytes( |
| 155 | encoding=serialization.Encoding.DER, |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame^] | 156 | format=formats[format], |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 157 | encryption_algorithm=serialization.NoEncryption()) |
| 158 | if minimal: |
Antonio de Angelis | c6e7e9b | 2022-11-15 15:06:40 +0000 | [diff] [blame^] | 159 | priv = self._build_minimal_ecdsa_privkey(priv, formats[format]) |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 160 | return priv |
| 161 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 162 | 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 Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 175 | def raw_sign(self, payload): |
| 176 | """Return the actual signature""" |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 177 | return self.key.sign( |
| 178 | data=payload, |
| 179 | signature_algorithm=ec.ECDSA(SHA256())) |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 180 | |
| 181 | def sign(self, payload): |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 182 | sig = self.raw_sign(payload) |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 183 | 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 |