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 |
| 6 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 7 | from cryptography.hazmat.backends import default_backend |
| 8 | from cryptography.hazmat.primitives import serialization |
| 9 | from cryptography.hazmat.primitives.asymmetric import ec |
| 10 | from cryptography.hazmat.primitives.hashes import SHA256 |
| 11 | |
| 12 | from .general import KeyClass |
| 13 | |
| 14 | class ECDSAUsageError(Exception): |
| 15 | pass |
| 16 | |
| 17 | class ECDSA256P1Public(KeyClass): |
| 18 | def __init__(self, key): |
| 19 | self.key = key |
| 20 | |
| 21 | def shortname(self): |
| 22 | return "ecdsa" |
| 23 | |
| 24 | def _unsupported(self, name): |
| 25 | raise ECDSAUsageError("Operation {} requires private key".format(name)) |
| 26 | |
| 27 | def _get_public(self): |
| 28 | return self.key |
| 29 | |
| 30 | def get_public_bytes(self): |
| 31 | # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format |
| 32 | return self._get_public().public_bytes( |
| 33 | encoding=serialization.Encoding.DER, |
| 34 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 35 | |
Fabio Utzig | 6f28677 | 2022-09-04 20:03:11 -0300 | [diff] [blame] | 36 | def get_public_pem(self): |
| 37 | return self._get_public().public_bytes( |
| 38 | encoding=serialization.Encoding.PEM, |
| 39 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 40 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 41 | def get_private_bytes(self, minimal): |
| 42 | self._unsupported('get_private_bytes') |
| 43 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 44 | def export_private(self, path, passwd=None): |
| 45 | self._unsupported('export_private') |
| 46 | |
| 47 | def export_public(self, path): |
| 48 | """Write the public key to the given file.""" |
| 49 | pem = self._get_public().public_bytes( |
| 50 | encoding=serialization.Encoding.PEM, |
| 51 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 52 | with open(path, 'wb') as f: |
| 53 | f.write(pem) |
| 54 | |
| 55 | def sig_type(self): |
| 56 | return "ECDSA256_SHA256" |
| 57 | |
| 58 | def sig_tlv(self): |
| 59 | return "ECDSA256" |
| 60 | |
| 61 | def sig_len(self): |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 62 | # Early versions of MCUboot (< v1.5.0) required ECDSA |
| 63 | # signatures to be padded to 72 bytes. Because the DER |
| 64 | # encoding is done with signed integers, the size of the |
| 65 | # signature will vary depending on whether the high bit is set |
| 66 | # in each value. This padding was done in a |
| 67 | # not-easily-reversible way (by just adding zeros). |
| 68 | # |
| 69 | # The signing code no longer requires this padding, and newer |
| 70 | # versions of MCUboot don't require it. But, continue to |
| 71 | # return the total length so that the padding can be done if |
| 72 | # requested. |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 73 | return 72 |
| 74 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 75 | def verify(self, signature, payload): |
Anthony Liu | 04630ce | 2020-03-10 11:57:26 +0800 | [diff] [blame] | 76 | # strip possible paddings added during sign |
| 77 | signature = signature[:signature[1] + 2] |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 78 | k = self.key |
| 79 | if isinstance(self.key, ec.EllipticCurvePrivateKey): |
| 80 | k = self.key.public_key() |
| 81 | return k.verify(signature=signature, data=payload, |
| 82 | signature_algorithm=ec.ECDSA(SHA256())) |
| 83 | |
| 84 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 85 | class ECDSA256P1(ECDSA256P1Public): |
| 86 | """ |
| 87 | Wrapper around an ECDSA private key. |
| 88 | """ |
| 89 | |
| 90 | def __init__(self, key): |
| 91 | """key should be an instance of EllipticCurvePrivateKey""" |
| 92 | self.key = key |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 93 | self.pad_sig = False |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 94 | |
| 95 | @staticmethod |
| 96 | def generate(): |
| 97 | pk = ec.generate_private_key( |
| 98 | ec.SECP256R1(), |
| 99 | backend=default_backend()) |
| 100 | return ECDSA256P1(pk) |
| 101 | |
| 102 | def _get_public(self): |
| 103 | return self.key.public_key() |
| 104 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame] | 105 | def _build_minimal_ecdsa_privkey(self, der): |
| 106 | ''' |
| 107 | Builds a new DER that only includes the EC private key, removing the |
| 108 | public key that is added as an "optional" BITSTRING. |
| 109 | ''' |
| 110 | offset_PUB = 68 |
| 111 | EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!" |
| 112 | if der[offset_PUB] != 0xa1: |
| 113 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 114 | len_PUB = der[offset_PUB + 1] |
| 115 | b = bytearray(der[:-offset_PUB]) |
| 116 | offset_SEQ = 29 |
| 117 | if b[offset_SEQ] != 0x30: |
| 118 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 119 | b[offset_SEQ + 1] -= len_PUB |
| 120 | offset_OCT_STR = 27 |
| 121 | if b[offset_OCT_STR] != 0x04: |
| 122 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 123 | b[offset_OCT_STR + 1] -= len_PUB |
| 124 | if b[0] != 0x30 or b[1] != 0x81: |
| 125 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 126 | b[2] -= len_PUB |
| 127 | return b |
| 128 | |
| 129 | def get_private_bytes(self, minimal): |
| 130 | priv = self.key.private_bytes( |
| 131 | encoding=serialization.Encoding.DER, |
| 132 | format=serialization.PrivateFormat.PKCS8, |
| 133 | encryption_algorithm=serialization.NoEncryption()) |
| 134 | if minimal: |
| 135 | priv = self._build_minimal_ecdsa_privkey(priv) |
| 136 | return priv |
| 137 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 138 | def export_private(self, path, passwd=None): |
| 139 | """Write the private key to the given file, protecting it with the optional password.""" |
| 140 | if passwd is None: |
| 141 | enc = serialization.NoEncryption() |
| 142 | else: |
| 143 | enc = serialization.BestAvailableEncryption(passwd) |
| 144 | pem = self.key.private_bytes( |
| 145 | encoding=serialization.Encoding.PEM, |
| 146 | format=serialization.PrivateFormat.PKCS8, |
| 147 | encryption_algorithm=enc) |
| 148 | with open(path, 'wb') as f: |
| 149 | f.write(pem) |
| 150 | |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 151 | def raw_sign(self, payload): |
| 152 | """Return the actual signature""" |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 153 | return self.key.sign( |
| 154 | data=payload, |
| 155 | signature_algorithm=ec.ECDSA(SHA256())) |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 156 | |
| 157 | def sign(self, payload): |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 158 | sig = self.raw_sign(payload) |
David Brown | 4878c27 | 2020-03-10 16:23:56 -0600 | [diff] [blame] | 159 | if self.pad_sig: |
| 160 | # To make fixed length, pad with one or two zeros. |
| 161 | sig += b'\000' * (self.sig_len() - len(sig)) |
| 162 | return sig |
| 163 | else: |
| 164 | return sig |