blob: 1f6ef90c71093f2bec6752427f4f9449e7788052 [file] [log] [blame]
Kevin Townsend0f869bb2019-08-01 21:06:48 +02001# Copyright (c) 2017,2019 Linaro Limited.
Tamas Ban861835c2019-05-13 08:59:38 +01002# Copyright (c) 2017-2019, Arm Limited.
Tamas Banf70ef8c2017-12-19 15:35:09 +00003#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""
17Cryptographic key management for imgtool.
18"""
19
Gabor Kertesz33e9b232018-09-12 15:38:41 +020020from __future__ import print_function
Kevin Townsend0f869bb2019-08-01 21:06:48 +020021from cryptography.hazmat.backends import default_backend
22from cryptography.hazmat.primitives import serialization
23from cryptography.hazmat.primitives.hashes import SHA256
24from cryptography.hazmat.primitives.asymmetric import rsa
25from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15
26from cryptography.hazmat.primitives.asymmetric.padding import MGF1
Tamas Banf70ef8c2017-12-19 15:35:09 +000027import hashlib
28from pyasn1.type import namedtype, univ
29from pyasn1.codec.der.encoder import encode
30
Tamas Ban861835c2019-05-13 08:59:38 +010031# Sizes that bootutil will recognize
32RSA_KEY_SIZES = [2048, 3072]
33
Kevin Townsend0f869bb2019-08-01 21:06:48 +020034# Public exponent
35PUBLIC_EXPONENT = 65537
36
Tamas Banf70ef8c2017-12-19 15:35:09 +000037# By default, we use RSA-PSS (PKCS 2.1). That can be overridden on
38# the command line to support the older (less secure) PKCS1.5
39sign_rsa_pss = True
40
41AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"
42
Tamas Ban861835c2019-05-13 08:59:38 +010043class RSAUsageError(Exception):
44 pass
45
Tamas Ban861835c2019-05-13 08:59:38 +010046class RSAutil():
Tamas Ban32d84642019-07-11 08:25:11 +010047 def __init__(self, key, public_key_format='hash'):
Tamas Ban861835c2019-05-13 08:59:38 +010048 """Construct an RSA key with the given key data"""
Tamas Banf70ef8c2017-12-19 15:35:09 +000049 self.key = key
Tamas Ban32d84642019-07-11 08:25:11 +010050 self.public_key_format = public_key_format
Tamas Banf70ef8c2017-12-19 15:35:09 +000051
Tamas Ban861835c2019-05-13 08:59:38 +010052 def key_size(self):
Kevin Townsend0f869bb2019-08-01 21:06:48 +020053 return self.key.key_size
Tamas Ban861835c2019-05-13 08:59:38 +010054
Tamas Ban32d84642019-07-11 08:25:11 +010055 def get_public_key_format(self):
56 return self.public_key_format
57
Tamas Banf70ef8c2017-12-19 15:35:09 +000058 @staticmethod
Tamas Ban861835c2019-05-13 08:59:38 +010059 def generate(key_size=2048):
60 if key_size not in RSA_KEY_SIZES:
61 raise RSAUsageError("Key size {} is not supported by MCUboot"
62 .format(key_size))
Kevin Townsend0f869bb2019-08-01 21:06:48 +020063 return RSAutil(rsa.generate_private_key(
64 public_exponent=PUBLIC_EXPONENT,
65 key_size=key_size,
66 backend=default_backend()))
Tamas Banf70ef8c2017-12-19 15:35:09 +000067
68 def export_private(self, path):
69 with open(path, 'wb') as f:
Kevin Townsend0f869bb2019-08-01 21:06:48 +020070 f.write(self.key.private_bytes(
71 encoding=serialization.Encoding.PEM,
72 format=serialization.PrivateFormat.TraditionalOpenSSL,
73 encryption_algorithm=serialization.NoEncryption()))
Tamas Banf70ef8c2017-12-19 15:35:09 +000074
75 def get_public_bytes(self):
Kevin Townsend0f869bb2019-08-01 21:06:48 +020076 return self.key.public_key().public_bytes(
77 encoding=serialization.Encoding.DER,
78 format=serialization.PublicFormat.PKCS1)
Tamas Banf70ef8c2017-12-19 15:35:09 +000079
80 def emit_c(self):
81 print(AUTOGEN_MESSAGE)
82 print("const unsigned char rsa_pub_key[] = {", end='')
83 encoded = self.get_public_bytes()
84 for count, b in enumerate(encoded):
85 if count % 8 == 0:
86 print("\n\t", end='')
87 else:
88 print(" ", end='')
89 print("0x{:02x},".format(b), end='')
90 print("\n};")
91 print("const unsigned int rsa_pub_key_len = {};".format(len(encoded)))
92
Tamas Banf70ef8c2017-12-19 15:35:09 +000093 def sig_type(self):
94 """Return the type of this signature (as a string)"""
95 if sign_rsa_pss:
Tamas Ban861835c2019-05-13 08:59:38 +010096 return "PKCS1_PSS_RSA{}_SHA256".format(self.key_size())
Tamas Banf70ef8c2017-12-19 15:35:09 +000097 else:
Tamas Ban861835c2019-05-13 08:59:38 +010098 return "PKCS15_RSA{}_SHA256".format(self.key_size())
Tamas Banf70ef8c2017-12-19 15:35:09 +000099
100 def sig_len(self):
Tamas Ban861835c2019-05-13 08:59:38 +0100101 return 256 if self.key_size() == 2048 else 384
Tamas Banf70ef8c2017-12-19 15:35:09 +0000102
103 def sig_tlv(self):
Tamas Ban861835c2019-05-13 08:59:38 +0100104 return "RSA2048" if self.key_size() == 2048 else "RSA3072"
Tamas Banf70ef8c2017-12-19 15:35:09 +0000105
106 def sign(self, payload):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000107 if sign_rsa_pss:
Kevin Townsend0f869bb2019-08-01 21:06:48 +0200108 signature = self.key.sign(
Kevin Townsendbf5b98c2020-06-02 12:23:57 +0200109 data=bytes(payload),
Kevin Townsend0f869bb2019-08-01 21:06:48 +0200110 padding=PSS(
111 mgf=MGF1(SHA256()),
112 salt_length=32
113 ),
114 algorithm=SHA256()
115 )
Tamas Banf70ef8c2017-12-19 15:35:09 +0000116 else:
Kevin Townsend0f869bb2019-08-01 21:06:48 +0200117 signature = self.key.sign(
Kevin Townsendbf5b98c2020-06-02 12:23:57 +0200118 data=bytes(payload),
Kevin Townsend0f869bb2019-08-01 21:06:48 +0200119 padding=PKCS1v15(),
120 algorithm=SHA256()
121 )
Tamas Banf70ef8c2017-12-19 15:35:09 +0000122 assert len(signature) == self.sig_len()
123 return signature
124
Tamas Ban32d84642019-07-11 08:25:11 +0100125def load(path, public_key_format='hash'):
Tamas Banf70ef8c2017-12-19 15:35:09 +0000126 with open(path, 'rb') as f:
127 pem = f.read()
128 try:
Kevin Townsend0f869bb2019-08-01 21:06:48 +0200129 key = serialization.load_pem_private_key(
130 pem,
131 password=None,
132 backend=default_backend()
133 )
Tamas Ban32d84642019-07-11 08:25:11 +0100134 return RSAutil(key, public_key_format)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000135 except ValueError:
Tamas Ban581034a2017-12-19 19:54:37 +0000136 raise Exception("Unsupported RSA key file")