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