blob: 85c034215c4414894af4adb458afdb0b4c720561 [file] [log] [blame]
David Brown5e7c6dd2017-11-16 14:47:16 -07001"""
2RSA Key management
3"""
4
5from cryptography.hazmat.backends import default_backend
6from cryptography.hazmat.primitives import serialization
7from cryptography.hazmat.primitives.asymmetric import rsa
8from cryptography.hazmat.primitives.asymmetric.padding import PSS, MGF1
9from cryptography.hazmat.primitives.hashes import SHA256
10
11from .general import KeyClass
12
Fabio Utzig19fd79a2019-05-08 18:20:39 -030013
14# Sizes that bootutil will recognize
15RSA_KEY_SIZES = [2048, 3072]
16
17
David Brown5e7c6dd2017-11-16 14:47:16 -070018class RSAUsageError(Exception):
19 pass
20
Fabio Utzig19fd79a2019-05-08 18:20:39 -030021
22class RSAPublic(KeyClass):
David Brown5e7c6dd2017-11-16 14:47:16 -070023 """The public key can only do a few operations"""
24 def __init__(self, key):
25 self.key = key
26
Fabio Utzig19fd79a2019-05-08 18:20:39 -030027 def key_size(self):
28 return self.key.key_size
29
David Brown5e7c6dd2017-11-16 14:47:16 -070030 def shortname(self):
31 return "rsa"
32
33 def _unsupported(self, name):
34 raise RSAUsageError("Operation {} requires private key".format(name))
35
36 def _get_public(self):
37 return self.key
38
39 def get_public_bytes(self):
40 # The key embedded into MCUboot is in PKCS1 format.
41 return self._get_public().public_bytes(
42 encoding=serialization.Encoding.DER,
43 format=serialization.PublicFormat.PKCS1)
44
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +020045 def get_private_bytes(self, minimal):
46 self._unsupported('get_private_bytes')
47
David Brown5e7c6dd2017-11-16 14:47:16 -070048 def export_private(self, path, passwd=None):
49 self._unsupported('export_private')
50
51 def export_public(self, path):
52 """Write the public key to the given file."""
53 pem = self._get_public().public_bytes(
54 encoding=serialization.Encoding.PEM,
55 format=serialization.PublicFormat.SubjectPublicKeyInfo)
56 with open(path, 'wb') as f:
57 f.write(pem)
58
59 def sig_type(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030060 return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070061
62 def sig_tlv(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030063 return"RSA{}".format(self.key_size())
David Brown5e7c6dd2017-11-16 14:47:16 -070064
David Brown1d5bea12017-11-16 15:11:10 -070065 def sig_len(self):
Fabio Utzig19fd79a2019-05-08 18:20:39 -030066 return self.key_size() / 8
David Brown1d5bea12017-11-16 15:11:10 -070067
Fabio Utzig4a5477a2019-05-27 15:45:08 -030068 def verify(self, signature, payload):
69 k = self.key
70 if isinstance(self.key, rsa.RSAPrivateKey):
71 k = self.key.public_key()
72 return k.verify(signature=signature, data=payload,
73 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
74 algorithm=SHA256())
75
Fabio Utzig19fd79a2019-05-08 18:20:39 -030076
77class RSA(RSAPublic):
David Brown5e7c6dd2017-11-16 14:47:16 -070078 """
Fabio Utzig19fd79a2019-05-08 18:20:39 -030079 Wrapper around an RSA key, with imgtool support.
David Brown5e7c6dd2017-11-16 14:47:16 -070080 """
81
82 def __init__(self, key):
83 """The key should be a private key from cryptography"""
84 self.key = key
85
86 @staticmethod
Fabio Utzig19fd79a2019-05-08 18:20:39 -030087 def generate(key_size=2048):
88 if key_size not in RSA_KEY_SIZES:
89 raise RSAUsageError("Key size {} is not supported by MCUboot"
90 .format(key_size))
David Brown5e7c6dd2017-11-16 14:47:16 -070091 pk = rsa.generate_private_key(
92 public_exponent=65537,
Fabio Utzig19fd79a2019-05-08 18:20:39 -030093 key_size=key_size,
David Brown5e7c6dd2017-11-16 14:47:16 -070094 backend=default_backend())
Fabio Utzig19fd79a2019-05-08 18:20:39 -030095 return RSA(pk)
David Brown5e7c6dd2017-11-16 14:47:16 -070096
97 def _get_public(self):
98 return self.key.public_key()
99
Ioannis Konstantelias78e57c72019-11-28 16:06:12 +0200100 def _build_minimal_rsa_privkey(self, der):
101 '''
102 Builds a new DER that only includes N/E/D/P/Q RSA parameters;
103 standard DER private bytes provided by OpenSSL also includes
104 CRT params (DP/DQ/QP) which can be removed.
105 '''
106 OFFSET_N = 7 # N is always located at this offset
107 b = bytearray(der)
108 off = OFFSET_N
109 if b[off + 1] != 0x82:
110 raise RSAUsageError("Error parsing N while minimizing")
111 len_N = (b[off + 2] << 8) + b[off + 3] + 4
112 off += len_N
113 if b[off + 1] != 0x03:
114 raise RSAUsageError("Error parsing E while minimizing")
115 len_E = b[off + 2] + 4
116 off += len_E
117 if b[off + 1] != 0x82:
118 raise RSAUsageError("Error parsing D while minimizing")
119 len_D = (b[off + 2] << 8) + b[off + 3] + 4
120 off += len_D
121 if b[off + 1] != 0x81:
122 raise RSAUsageError("Error parsing P while minimizing")
123 len_P = b[off + 2] + 3
124 off += len_P
125 if b[off + 1] != 0x81:
126 raise RSAUsageError("Error parsing Q while minimizing")
127 len_Q = b[off + 2] + 3
128 off += len_Q
129 # adjust DER size for removed elements
130 b[2] = (off - 4) >> 8
131 b[3] = (off - 4) & 0xff
132 return b[:off]
133
134 def get_private_bytes(self, minimal):
135 priv = self.key.private_bytes(
136 encoding=serialization.Encoding.DER,
137 format=serialization.PrivateFormat.TraditionalOpenSSL,
138 encryption_algorithm=serialization.NoEncryption())
139 if minimal:
140 priv = self._build_minimal_rsa_privkey(priv)
141 return priv
142
David Brown5e7c6dd2017-11-16 14:47:16 -0700143 def export_private(self, path, passwd=None):
Fabio Utzig19fd79a2019-05-08 18:20:39 -0300144 """Write the private key to the given file, protecting it with the
145 optional password."""
David Brown5e7c6dd2017-11-16 14:47:16 -0700146 if passwd is None:
147 enc = serialization.NoEncryption()
148 else:
149 enc = serialization.BestAvailableEncryption(passwd)
150 pem = self.key.private_bytes(
151 encoding=serialization.Encoding.PEM,
152 format=serialization.PrivateFormat.PKCS8,
153 encryption_algorithm=enc)
154 with open(path, 'wb') as f:
155 f.write(pem)
156
157 def sign(self, payload):
David Brown20462a72017-11-21 14:28:51 -0700158 # The verification code only allows the salt length to be the
159 # same as the hash length, 32.
David Brown5e7c6dd2017-11-16 14:47:16 -0700160 return self.key.sign(
161 data=payload,
David Brown20462a72017-11-21 14:28:51 -0700162 padding=PSS(mgf=MGF1(SHA256()), salt_length=32),
David Brown5e7c6dd2017-11-16 14:47:16 -0700163 algorithm=SHA256())