blob: d8543ede29e3accfcfa81e5471ae3d27a494c18f [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
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020047 def get_private_bytes(self, minimal):
48 self._unsupported('get_private_bytes')
49
David Brown5e7c6dd2017-11-16 14:47:16 -070050 def export_private(self, path, passwd=None):
51 self._unsupported('export_private')
52
53 def export_public(self, path):
54 """Write the public key to the given file."""
55 pem = self._get_public().public_bytes(
56 encoding=serialization.Encoding.PEM,
57 format=serialization.PublicFormat.SubjectPublicKeyInfo)
58 with open(path, 'wb') as f:
59 f.write(pem)
60
61 def sig_type(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030062 return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070063
64 def sig_tlv(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030065 return"RSA{}".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070066
David Brown1d5bea12017-11-16 15:11:10 -070067 def sig_len(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030068 return self.key_size() / 8
David Brown1d5bea12017-11-16 15:11:10 -070069
Fabio Utzig4a5477a2019-05-27 15:45:08 -030070 def verify(self, signature, payload):
71 k = self.key
72 if isinstance(self.key, rsa.RSAPrivateKey):
73 k = self.key.public_key()
74 return k.verify(signature=signature, data=payload,
75 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
76 algorithm=SHA256())
77
Fabio Utzig19fd79a2019-05-08 18:20:39 -030078
79class RSA(RSAPublic):
David Brown5e7c6dd2017-11-16 14:47:16 -070080 """
Fabio Utzig19fd79a2019-05-08 18:20:39 -030081 Wrapper around an RSA key, with imgtool support.
David Brown5e7c6dd2017-11-16 14:47:16 -070082 """
83
84 def __init__(self, key):
85 """The key should be a private key from cryptography"""
86 self.key = key
87
88 @staticmethod
Fabio Utzig19fd79a2019-05-08 18:20:39 -030089 def generate(key_size=2048):
90 if key_size not in RSA_KEY_SIZES:
91 raise RSAUsageError("Key size {} is not supported by MCUboot"
92 .format(key_size))
David Brown5e7c6dd2017-11-16 14:47:16 -070093 pk = rsa.generate_private_key(
94 public_exponent=65537,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030095 key_size=key_size,
David Brown5e7c6dd2017-11-16 14:47:16 -070096 backend=default_backend())
Fabio Utzig19fd79a2019-05-08 18:20:39 -030097 return RSA(pk)
David Brown5e7c6dd2017-11-16 14:47:16 -070098
99 def _get_public(self):
100 return self.key.public_key()
101
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200102 def _build_minimal_rsa_privkey(self, der):
103 '''
104 Builds a new DER that only includes N/E/D/P/Q RSA parameters;
105 standard DER private bytes provided by OpenSSL also includes
106 CRT params (DP/DQ/QP) which can be removed.
107 '''
108 OFFSET_N = 7 # N is always located at this offset
109 b = bytearray(der)
110 off = OFFSET_N
111 if b[off + 1] != 0x82:
112 raise RSAUsageError("Error parsing N while minimizing")
113 len_N = (b[off + 2] << 8) + b[off + 3] + 4
114 off += len_N
115 if b[off + 1] != 0x03:
116 raise RSAUsageError("Error parsing E while minimizing")
117 len_E = b[off + 2] + 4
118 off += len_E
119 if b[off + 1] != 0x82:
120 raise RSAUsageError("Error parsing D while minimizing")
121 len_D = (b[off + 2] << 8) + b[off + 3] + 4
122 off += len_D
123 if b[off + 1] != 0x81:
124 raise RSAUsageError("Error parsing P while minimizing")
125 len_P = b[off + 2] + 3
126 off += len_P
127 if b[off + 1] != 0x81:
128 raise RSAUsageError("Error parsing Q while minimizing")
129 len_Q = b[off + 2] + 3
130 off += len_Q
131 # adjust DER size for removed elements
132 b[2] = (off - 4) >> 8
133 b[3] = (off - 4) & 0xff
134 return b[:off]
135
136 def get_private_bytes(self, minimal):
137 priv = self.key.private_bytes(
138 encoding=serialization.Encoding.DER,
139 format=serialization.PrivateFormat.TraditionalOpenSSL,
140 encryption_algorithm=serialization.NoEncryption())
141 if minimal:
142 priv = self._build_minimal_rsa_privkey(priv)
143 return priv
144
David Brown5e7c6dd2017-11-16 14:47:16 -0700145 def export_private(self, path, passwd=None):
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300146 """Write the private key to the given file, protecting it with the
147 optional password."""
David Brown5e7c6dd2017-11-16 14:47:16 -0700148 if passwd is None:
149 enc = serialization.NoEncryption()
150 else:
151 enc = serialization.BestAvailableEncryption(passwd)
152 pem = self.key.private_bytes(
153 encoding=serialization.Encoding.PEM,
154 format=serialization.PrivateFormat.PKCS8,
155 encryption_algorithm=enc)
156 with open(path, 'wb') as f:
157 f.write(pem)
158
159 def sign(self, payload):
David Brown20462a72017-11-21 14:28:51 -0700160 # The verification code only allows the salt length to be the
161 # same as the hash length, 32.
David Brown5e7c6dd2017-11-16 14:47:16 -0700162 return self.key.sign(
163 data=payload,
David Brown20462a72017-11-21 14:28:51 -0700164 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
David Brown5e7c6dd2017-11-16 14:47:16 -0700165 algorithm=SHA256())