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