blob: d51d36de10ed177d6b3ae8979284495718d7f2c7 [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
14
Fabio Utzig19fd79a2019-05-08 18:20:39 -030015
16# Sizes that bootutil will recognize
17RSA_KEY_SIZES = [2048, 3072]
18
19
David Brown5e7c6dd2017-11-16 14:47:16 -070020class RSAUsageError(Exception):
21 pass
22
Fabio Utzig19fd79a2019-05-08 18:20:39 -030023
24class RSAPublic(KeyClass):
David Brown5e7c6dd2017-11-16 14:47:16 -070025 """The public key can only do a few operations"""
26 def __init__(self, key):
27 self.key = key
28
Fabio Utzig19fd79a2019-05-08 18:20:39 -030029 def key_size(self):
30 return self.key.key_size
31
David Brown5e7c6dd2017-11-16 14:47:16 -070032 def shortname(self):
33 return "rsa"
34
35 def _unsupported(self, name):
36 raise RSAUsageError("Operation {} requires private key".format(name))
37
38 def _get_public(self):
39 return self.key
40
41 def get_public_bytes(self):
42 # The key embedded into MCUboot is in PKCS1 format.
43 return self._get_public().public_bytes(
44 encoding=serialization.Encoding.DER,
45 format=serialization.PublicFormat.PKCS1)
46
Fabio Utzig6f286772022-09-04 20:03:11 -030047 def get_public_pem(self):
48 return self._get_public().public_bytes(
49 encoding=serialization.Encoding.PEM,
50 format=serialization.PublicFormat.SubjectPublicKeyInfo)
51
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020052 def get_private_bytes(self, minimal):
53 self._unsupported('get_private_bytes')
54
David Brown5e7c6dd2017-11-16 14:47:16 -070055 def export_private(self, path, passwd=None):
56 self._unsupported('export_private')
57
58 def export_public(self, path):
59 """Write the public key to the given file."""
60 pem = self._get_public().public_bytes(
61 encoding=serialization.Encoding.PEM,
62 format=serialization.PublicFormat.SubjectPublicKeyInfo)
63 with open(path, 'wb') as f:
64 f.write(pem)
65
66 def sig_type(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030067 return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070068
69 def sig_tlv(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030070 return"RSA{}".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070071
David Brown1d5bea12017-11-16 15:11:10 -070072 def sig_len(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030073 return self.key_size() / 8
David Brown1d5bea12017-11-16 15:11:10 -070074
Fabio Utzig4a5477a2019-05-27 15:45:08 -030075 def verify(self, signature, payload):
76 k = self.key
77 if isinstance(self.key, rsa.RSAPrivateKey):
78 k = self.key.public_key()
79 return k.verify(signature=signature, data=payload,
80 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
81 algorithm=SHA256())
82
Fabio Utzig19fd79a2019-05-08 18:20:39 -030083
84class RSA(RSAPublic):
David Brown5e7c6dd2017-11-16 14:47:16 -070085 """
Fabio Utzig19fd79a2019-05-08 18:20:39 -030086 Wrapper around an RSA key, with imgtool support.
David Brown5e7c6dd2017-11-16 14:47:16 -070087 """
88
89 def __init__(self, key):
90 """The key should be a private key from cryptography"""
91 self.key = key
92
93 @staticmethod
Fabio Utzig19fd79a2019-05-08 18:20:39 -030094 def generate(key_size=2048):
95 if key_size not in RSA_KEY_SIZES:
96 raise RSAUsageError("Key size {} is not supported by MCUboot"
97 .format(key_size))
David Brown5e7c6dd2017-11-16 14:47:16 -070098 pk = rsa.generate_private_key(
99 public_exponent=65537,
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300100 key_size=key_size,
David Brown5e7c6dd2017-11-16 14:47:16 -0700101 backend=default_backend())
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300102 return RSA(pk)
David Brown5e7c6dd2017-11-16 14:47:16 -0700103
104 def _get_public(self):
105 return self.key.public_key()
106
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200107 def _build_minimal_rsa_privkey(self, der):
108 '''
109 Builds a new DER that only includes N/E/D/P/Q RSA parameters;
110 standard DER private bytes provided by OpenSSL also includes
111 CRT params (DP/DQ/QP) which can be removed.
112 '''
113 OFFSET_N = 7 # N is always located at this offset
114 b = bytearray(der)
115 off = OFFSET_N
116 if b[off + 1] != 0x82:
117 raise RSAUsageError("Error parsing N while minimizing")
118 len_N = (b[off + 2] << 8) + b[off + 3] + 4
119 off += len_N
120 if b[off + 1] != 0x03:
121 raise RSAUsageError("Error parsing E while minimizing")
122 len_E = b[off + 2] + 4
123 off += len_E
124 if b[off + 1] != 0x82:
125 raise RSAUsageError("Error parsing D while minimizing")
126 len_D = (b[off + 2] << 8) + b[off + 3] + 4
127 off += len_D
128 if b[off + 1] != 0x81:
129 raise RSAUsageError("Error parsing P while minimizing")
130 len_P = b[off + 2] + 3
131 off += len_P
132 if b[off + 1] != 0x81:
133 raise RSAUsageError("Error parsing Q while minimizing")
134 len_Q = b[off + 2] + 3
135 off += len_Q
136 # adjust DER size for removed elements
137 b[2] = (off - 4) >> 8
138 b[3] = (off - 4) & 0xff
139 return b[:off]
140
141 def get_private_bytes(self, minimal):
142 priv = self.key.private_bytes(
143 encoding=serialization.Encoding.DER,
144 format=serialization.PrivateFormat.TraditionalOpenSSL,
145 encryption_algorithm=serialization.NoEncryption())
146 if minimal:
147 priv = self._build_minimal_rsa_privkey(priv)
148 return priv
149
David Brown5e7c6dd2017-11-16 14:47:16 -0700150 def export_private(self, path, passwd=None):
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300151 """Write the private key to the given file, protecting it with the
152 optional password."""
David Brown5e7c6dd2017-11-16 14:47:16 -0700153 if passwd is None:
154 enc = serialization.NoEncryption()
155 else:
156 enc = serialization.BestAvailableEncryption(passwd)
157 pem = self.key.private_bytes(
158 encoding=serialization.Encoding.PEM,
159 format=serialization.PrivateFormat.PKCS8,
160 encryption_algorithm=enc)
161 with open(path, 'wb') as f:
162 f.write(pem)
163
164 def sign(self, payload):
David Brown20462a72017-11-21 14:28:51 -0700165 # The verification code only allows the salt length to be the
166 # same as the hash length, 32.
David Brown5e7c6dd2017-11-16 14:47:16 -0700167 return self.key.sign(
168 data=payload,
David Brown20462a72017-11-21 14:28:51 -0700169 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
David Brown5e7c6dd2017-11-16 14:47:16 -0700170 algorithm=SHA256())