blob: d4793c5386e1bbc5f355baca6defff3451d86e7d [file] [log] [blame]
David Brown5e7c6dd2017-11-16 14:47:16 -07001"""
2RSA Key management
3"""
4
David Brown79c4fcf2021-01-26 15:04:05 -07005# SPDX-License-Identifier: Apache-2.0
6
David Brown5e7c6dd2017-11-16 14:47:16 -07007from cryptography.hazmat.backends import default_backend
8from cryptography.hazmat.primitives import serialization
9from cryptography.hazmat.primitives.asymmetric import rsa
10from cryptography.hazmat.primitives.asymmetric.padding import PSS, MGF1
11from cryptography.hazmat.primitives.hashes import SHA256
12
13from .general import KeyClass
Fabio Utzig8f289ba2023-01-09 21:01:55 -030014from .privatebytes import PrivateBytesMixin
David Brown5e7c6dd2017-11-16 14:47:16 -070015
Fabio Utzig19fd79a2019-05-08 18:20:39 -030016
17# Sizes that bootutil will recognize
18RSA_KEY_SIZES = [2048, 3072]
19
20
David Brown5e7c6dd2017-11-16 14:47:16 -070021class RSAUsageError(Exception):
22 pass
23
Fabio Utzig19fd79a2019-05-08 18:20:39 -030024
25class RSAPublic(KeyClass):
David Brown5e7c6dd2017-11-16 14:47:16 -070026 """The public key can only do a few operations"""
27 def __init__(self, key):
28 self.key = key
29
Fabio Utzig19fd79a2019-05-08 18:20:39 -030030 def key_size(self):
31 return self.key.key_size
32
David Brown5e7c6dd2017-11-16 14:47:16 -070033 def shortname(self):
34 return "rsa"
35
36 def _unsupported(self, name):
37 raise RSAUsageError("Operation {} requires private key".format(name))
38
39 def _get_public(self):
40 return self.key
41
42 def get_public_bytes(self):
43 # The key embedded into MCUboot is in PKCS1 format.
44 return self._get_public().public_bytes(
45 encoding=serialization.Encoding.DER,
46 format=serialization.PublicFormat.PKCS1)
47
Fabio Utzig6f286772022-09-04 20:03:11 -030048 def get_public_pem(self):
49 return self._get_public().public_bytes(
50 encoding=serialization.Encoding.PEM,
51 format=serialization.PublicFormat.SubjectPublicKeyInfo)
52
Fabio Utzig8f289ba2023-01-09 21:01:55 -030053 def get_private_bytes(self, minimal, format):
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020054 self._unsupported('get_private_bytes')
55
David Brown5e7c6dd2017-11-16 14:47:16 -070056 def export_private(self, path, passwd=None):
57 self._unsupported('export_private')
58
59 def export_public(self, path):
60 """Write the public key to the given file."""
61 pem = self._get_public().public_bytes(
62 encoding=serialization.Encoding.PEM,
63 format=serialization.PublicFormat.SubjectPublicKeyInfo)
64 with open(path, 'wb') as f:
65 f.write(pem)
66
67 def sig_type(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030068 return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070069
70 def sig_tlv(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030071 return"RSA{}".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070072
David Brown1d5bea12017-11-16 15:11:10 -070073 def sig_len(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030074 return self.key_size() / 8
David Brown1d5bea12017-11-16 15:11:10 -070075
Fabio Utzig4a5477a2019-05-27 15:45:08 -030076 def verify(self, signature, payload):
77 k = self.key
78 if isinstance(self.key, rsa.RSAPrivateKey):
79 k = self.key.public_key()
80 return k.verify(signature=signature, data=payload,
81 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
82 algorithm=SHA256())
83
Fabio Utzig19fd79a2019-05-08 18:20:39 -030084
Fabio Utzig8f289ba2023-01-09 21:01:55 -030085class RSA(RSAPublic, PrivateBytesMixin):
David Brown5e7c6dd2017-11-16 14:47:16 -070086 """
Fabio Utzig19fd79a2019-05-08 18:20:39 -030087 Wrapper around an RSA key, with imgtool support.
David Brown5e7c6dd2017-11-16 14:47:16 -070088 """
89
90 def __init__(self, key):
91 """The key should be a private key from cryptography"""
92 self.key = key
93
94 @staticmethod
Fabio Utzig19fd79a2019-05-08 18:20:39 -030095 def generate(key_size=2048):
96 if key_size not in RSA_KEY_SIZES:
97 raise RSAUsageError("Key size {} is not supported by MCUboot"
98 .format(key_size))
David Brown5e7c6dd2017-11-16 14:47:16 -070099 pk = rsa.generate_private_key(
100 public_exponent=65537,
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300101 key_size=key_size,
David Brown5e7c6dd2017-11-16 14:47:16 -0700102 backend=default_backend())
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300103 return RSA(pk)
David Brown5e7c6dd2017-11-16 14:47:16 -0700104
105 def _get_public(self):
106 return self.key.public_key()
107
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200108 def _build_minimal_rsa_privkey(self, der):
109 '''
110 Builds a new DER that only includes N/E/D/P/Q RSA parameters;
111 standard DER private bytes provided by OpenSSL also includes
112 CRT params (DP/DQ/QP) which can be removed.
113 '''
114 OFFSET_N = 7 # N is always located at this offset
115 b = bytearray(der)
116 off = OFFSET_N
117 if b[off + 1] != 0x82:
118 raise RSAUsageError("Error parsing N while minimizing")
119 len_N = (b[off + 2] << 8) + b[off + 3] + 4
120 off += len_N
121 if b[off + 1] != 0x03:
122 raise RSAUsageError("Error parsing E while minimizing")
123 len_E = b[off + 2] + 4
124 off += len_E
125 if b[off + 1] != 0x82:
126 raise RSAUsageError("Error parsing D while minimizing")
127 len_D = (b[off + 2] << 8) + b[off + 3] + 4
128 off += len_D
129 if b[off + 1] != 0x81:
130 raise RSAUsageError("Error parsing P while minimizing")
131 len_P = b[off + 2] + 3
132 off += len_P
133 if b[off + 1] != 0x81:
134 raise RSAUsageError("Error parsing Q while minimizing")
135 len_Q = b[off + 2] + 3
136 off += len_Q
137 # adjust DER size for removed elements
138 b[2] = (off - 4) >> 8
139 b[3] = (off - 4) & 0xff
140 return b[:off]
141
Fabio Utzig8f289ba2023-01-09 21:01:55 -0300142 _VALID_FORMATS = {
143 'openssl': serialization.PrivateFormat.TraditionalOpenSSL
144 }
145 _DEFAULT_FORMAT = 'openssl'
146
147 def get_private_bytes(self, minimal, format):
148 _, priv = self._get_private_bytes(minimal, format, RSAUsageError)
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200149 if minimal:
150 priv = self._build_minimal_rsa_privkey(priv)
151 return priv
152
David Brown5e7c6dd2017-11-16 14:47:16 -0700153 def export_private(self, path, passwd=None):
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300154 """Write the private key to the given file, protecting it with the
155 optional password."""
David Brown5e7c6dd2017-11-16 14:47:16 -0700156 if passwd is None:
157 enc = serialization.NoEncryption()
158 else:
159 enc = serialization.BestAvailableEncryption(passwd)
160 pem = self.key.private_bytes(
161 encoding=serialization.Encoding.PEM,
162 format=serialization.PrivateFormat.PKCS8,
163 encryption_algorithm=enc)
164 with open(path, 'wb') as f:
165 f.write(pem)
166
167 def sign(self, payload):
David Brown20462a72017-11-21 14:28:51 -0700168 # The verification code only allows the salt length to be the
169 # same as the hash length, 32.
David Brown5e7c6dd2017-11-16 14:47:16 -0700170 return self.key.sign(
171 data=payload,
David Brown20462a72017-11-21 14:28:51 -0700172 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
David Brown5e7c6dd2017-11-16 14:47:16 -0700173 algorithm=SHA256())