Botan 3.8.1
Crypto and TLS for C&
tpm2_rsa.cpp
Go to the documentation of this file.
1/*
2* TPM 2.0 RSA Key Wrappres
3* (C) 2024 Jack Lloyd
4* (C) 2024 René Meusel, Amos Treiber - Rohde & Schwarz Cybersecurity GmbH, financed by LANCOM Systems GmbH
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/tpm2_rsa.h>
10
11#include <botan/hash.h>
12#include <botan/pss_params.h>
13#include <botan/rsa.h>
14
15#include <botan/internal/ct_utils.h>
16#include <botan/internal/emsa.h>
17#include <botan/internal/fmt.h>
18#include <botan/internal/scan_name.h>
19#include <botan/internal/stl_util.h>
20#include <botan/internal/tpm2_algo_mappings.h>
21#include <botan/internal/tpm2_hash.h>
22#include <botan/internal/tpm2_pkops.h>
23#include <botan/internal/tpm2_util.h>
24
25#include <tss2/tss2_esys.h>
26
27namespace Botan::TPM2 {
28
29RSA_PublicKey::RSA_PublicKey(Object handle, SessionBundle session_bundle, const TPM2B_PUBLIC* public_blob) :
31 std::move(handle), std::move(session_bundle), rsa_pubkey_components_from_tss2_public(public_blob)) {}
32
33RSA_PublicKey::RSA_PublicKey(Object handle, SessionBundle session_bundle, const std::pair<BigInt, BigInt>& pubkey) :
34 Botan::TPM2::PublicKey(std::move(handle), std::move(session_bundle)),
35
36 // TODO: move those BigInts as soon as the RSA c'tor allows it
37 Botan::RSA_PublicKey(pubkey.first, pubkey.second) {}
38
40 SessionBundle session_bundle,
41 const TPM2B_PUBLIC* public_blob,
42 std::span<const uint8_t> private_blob) :
43 Botan::TPM2::RSA_PrivateKey(std::move(handle),
44 std::move(session_bundle),
45 rsa_pubkey_components_from_tss2_public(public_blob),
46 private_blob) {}
47
49 SessionBundle session_bundle,
50 const std::pair<BigInt, BigInt>& pubkey,
51 std::span<const uint8_t> private_blob) :
52 Botan::TPM2::PrivateKey(std::move(handle), std::move(session_bundle), private_blob),
53
54 // TODO: move those BigInts as soon as the RSA c'tor allows it
55 Botan::RSA_PublicKey(pubkey.first, pubkey.second) {}
56
57std::unique_ptr<TPM2::PrivateKey> RSA_PrivateKey::create_unrestricted_transient(const std::shared_ptr<Context>& ctx,
59 std::span<const uint8_t> auth_value,
60 const TPM2::PrivateKey& parent,
61 uint16_t keylength,
62 std::optional<uint32_t> exponent) {
63 BOTAN_ARG_CHECK(parent.is_parent(), "The passed key cannot be used as a parent key");
64
65 TPM2B_SENSITIVE_CREATE sensitive_data = {
66 .size = 0, // ignored
67 .sensitive =
68 {
69 .userAuth = copy_into<TPM2B_AUTH>(auth_value),
70
71 // Architecture Document, Section 25.2.3
72 // When an asymmetric key is created, the caller is not allowed to
73 // provide the sensitive data of the key.
75 },
76 };
77
78 TPMT_PUBLIC key_template = {
79 .type = TPM2_ALG_RSA,
80
81 // This is the algorithm for fingerprinting the newly created public key.
82 // For best compatibility we always use SHA-256.
83 .nameAlg = TPM2_ALG_SHA256,
84
85 // This sets up the key to be both a decryption and a signing key, forbids
86 // its duplication (fixed_tpm, fixed_parent) and ensures that the key's
87 // private portion can be used only by a user with an HMAC or password
88 // session.
89 .objectAttributes = ObjectAttributes::render({
90 .fixed_tpm = true,
91 .fixed_parent = true,
92 .sensitive_data_origin = true,
93 .user_with_auth = true,
94 .decrypt = true,
95 .sign_encrypt = true,
96 }),
97
98 // We currently do not support policy-based authorization
99 .authPolicy = init_empty<TPM2B_DIGEST>(),
100 .parameters =
101 {
102 .rsaDetail =
103 {
104 // Structures Document (Part 2), Section 12.2.3.5
105 // If the key is not a restricted decryption key, this field
106 // shall be set to TPM_ALG_NULL.
107 //
108 // TODO: Once we stop supporting TSS < 4.0, we could use
109 // `.keyBits = {.null = {}}, .mode = {.null = {}}`
110 // which better reflects our intention here.
111 .symmetric =
112 {
113 .algorithm = TPM2_ALG_NULL,
114 .keyBits = {.sym = 0},
115 .mode = {.sym = TPM2_ALG_NULL},
116 },
117
118 // Structures Document (Part 2), Section 12.2.3.5
119 // When both sign and decrypt are SET, restricted shall be
120 // CLEAR and scheme shall be TPM_ALG_NULL
121 //
122 // TODO: Once we stop supporting TSS < 4.0, we could use
123 // `.details = {.null = {}}`
124 // which better reflects our intention here.
125 .scheme =
126 {
127 .scheme = TPM2_ALG_NULL,
128 .details = {.anySig = {.hashAlg = TPM2_ALG_NULL}},
129 },
130 .keyBits = keylength,
131 .exponent = exponent.value_or(0 /* default value - 2^16 + 1*/),
132 },
133 },
134
135 // For creating an asymmetric key this value is not used.
136 .unique = {.rsa = init_empty<TPM2B_PUBLIC_KEY_RSA>()},
137 };
138
140 ctx, sessions, parent.handles().transient_handle(), key_template, sensitive_data);
141}
142
143namespace {
144
145SignatureAlgorithmSelection select_signature_algorithms(std::string_view padding) {
146 const SCAN_Name req(padding);
147 if(req.arg_count() == 0) {
148 throw Invalid_Argument("RSA signing padding scheme must at least specify a hash function");
149 }
150
151 auto sig_scheme = rsa_signature_scheme_botan_to_tss2(padding);
152 if(!sig_scheme) {
153 throw Not_Implemented(Botan::fmt("RSA signing with padding scheme {}", padding));
154 }
155
156 return {
157 .signature_scheme = sig_scheme.value(),
158 .hash_name = req.arg(0),
159 .padding = std::string(padding),
160 };
161}
162
163size_t signature_length_for_key_handle(const SessionBundle& sessions, const Object& key_handle) {
164 return key_handle._public_info(sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits / 8;
165}
166
167class RSA_Signature_Operation final : public Signature_Operation {
168 public:
169 RSA_Signature_Operation(const Object& object, const SessionBundle& sessions, std::string_view padding) :
170 Signature_Operation(object, sessions, select_signature_algorithms(padding)) {}
171
172 size_t signature_length() const override { return signature_length_for_key_handle(sessions(), key_handle()); }
173
174 AlgorithmIdentifier algorithm_identifier() const override {
175 // TODO: This is essentially a copy of the ::algorithm_identifier()
176 // in `rsa.h`. We should probably refactor this into a common
177 // function.
178
179 // This EMSA object actually isn't required, we just need it to
180 // conveniently figure out the algorithm identifier.
181 //
182 // TODO: This is a hack, and we should clean this up.
183 BOTAN_STATE_CHECK(padding().has_value());
184 const auto emsa = EMSA::create_or_throw(padding().value());
185 const std::string emsa_name = emsa->name();
186
187 try {
188 const std::string full_name = "RSA/" + emsa_name;
189 const OID oid = OID::from_string(full_name);
190 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM);
191 } catch(Lookup_Error&) {}
192
193 if(emsa_name.starts_with("PSS(")) {
194 auto parameters = PSS_Params::from_emsa_name(emsa_name).serialize();
195 return AlgorithmIdentifier("RSA/PSS", parameters);
196 }
197
198 throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", emsa_name));
199 }
200
201 private:
202 std::vector<uint8_t> marshal_signature(const TPMT_SIGNATURE& signature) const override {
203 const auto& sig = [&] {
204 if(signature.sigAlg == TPM2_ALG_RSASSA) {
205 return signature.signature.rsassa;
206 } else if(signature.sigAlg == TPM2_ALG_RSAPSS) {
207 return signature.signature.rsapss;
208 }
209 throw Invalid_State(fmt("TPM2 returned an unexpected signature scheme {}", signature.sigAlg));
210 }();
211
212 BOTAN_ASSERT_NOMSG(sig.sig.size == signature_length());
213 return copy_into<std::vector<uint8_t>>(sig.sig);
214 }
215};
216
217class RSA_Verification_Operation final : public Verification_Operation {
218 public:
219 RSA_Verification_Operation(const Object& object, const SessionBundle& sessions, std::string_view padding) :
220 Verification_Operation(object, sessions, select_signature_algorithms(padding)) {}
221
222 private:
223 TPMT_SIGNATURE unmarshal_signature(std::span<const uint8_t> signature) const override {
224 BOTAN_ARG_CHECK(signature.size() == signature_length_for_key_handle(sessions(), key_handle()),
225 "Unexpected signature byte length");
226
227 TPMT_SIGNATURE sig;
228 sig.sigAlg = scheme().scheme;
229
230 auto& sig_data = [&]() -> TPMS_SIGNATURE_RSA& {
231 if(sig.sigAlg == TPM2_ALG_RSASSA) {
232 return sig.signature.rsassa;
233 } else if(sig.sigAlg == TPM2_ALG_RSAPSS) {
234 return sig.signature.rsapss;
235 }
236 throw Invalid_State(fmt("Requested an unexpected signature scheme {}", sig.sigAlg));
237 }();
238
239 sig_data.hash = scheme().details.any.hashAlg;
240 copy_into(sig_data.sig, signature);
241 return sig;
242 }
243};
244
245TPMT_RSA_DECRYPT select_encryption_algorithms(std::string_view padding) {
246 auto scheme = rsa_encryption_scheme_botan_to_tss2(padding);
247 if(!scheme) {
248 throw Not_Implemented(Botan::fmt("RSA encryption with padding scheme {}", padding));
249 }
250 return scheme.value();
251}
252
253class RSA_Encryption_Operation final : public PK_Ops::Encryption {
254 public:
255 RSA_Encryption_Operation(const Object& object, const SessionBundle& sessions, std::string_view padding) :
256 m_key_handle(object), m_sessions(sessions), m_scheme(select_encryption_algorithms(padding)) {}
257
258 std::vector<uint8_t> encrypt(std::span<const uint8_t> msg, Botan::RandomNumberGenerator& /* rng */) override {
259 const auto plaintext = copy_into<TPM2B_PUBLIC_KEY_RSA>(msg);
260
261 // TODO: Figure out what this is for. Given that I didn't see any other
262 // way to pass an EME-OAEP label, I'm guessing that this is what
263 // it is for. But I'm not sure.
264 //
265 // Again, a follow-up of https://github.com/randombit/botan/pull/4318
266 // that targets async encryption will probably be quite helpful here.
267 const auto label = init_empty<TPM2B_DATA>();
268
270 check_rc("Esys_RSA_Encrypt",
271 Esys_RSA_Encrypt(*m_key_handle.context(),
272 m_key_handle.transient_handle(),
273 m_sessions[0],
274 m_sessions[1],
275 m_sessions[2],
276 &plaintext,
277 &m_scheme,
278 &label,
279 out_ptr(ciphertext)));
280 BOTAN_ASSERT_NONNULL(ciphertext);
281 return copy_into<std::vector<uint8_t>>(*ciphertext);
282 }
283
284 // This duplicates quite a bit of domain knowledge about those RSA
285 // EMEs. And I'm quite certain that I screwed up somewhere.
286 //
287 // TODO: See if we can somehow share the logic with the software
288 // RSA implementation and also PKCS#11 (which I believe is plain wrong).
289 size_t max_input_bits() const override {
290 const auto max_ptext_bytes =
291 (m_key_handle._public_info(m_sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits - 1) / 8;
292 auto hash_output_bytes = [](TPM2_ALG_ID hash) -> size_t {
293 switch(hash) {
294 case TPM2_ALG_SHA1:
295 return 160 / 8;
296 case TPM2_ALG_SHA256:
297 case TPM2_ALG_SHA3_256:
298 return 256 / 8;
299 case TPM2_ALG_SHA384:
300 case TPM2_ALG_SHA3_384:
301 return 384 / 8;
302 case TPM2_ALG_SHA512:
303 case TPM2_ALG_SHA3_512:
304 return 512 / 8;
305 default:
306 throw Invalid_State("Unexpected hash algorithm");
307 }
308 };
309
310 const auto max_input_bytes = [&]() -> size_t {
311 switch(m_scheme.scheme) {
312 case TPM2_ALG_RSAES:
313 return max_ptext_bytes - 10;
314 case TPM2_ALG_OAEP:
315 return max_ptext_bytes - 2 * hash_output_bytes(m_scheme.details.oaep.hashAlg) - 1;
316 case TPM2_ALG_NULL:
317 return max_ptext_bytes;
318 default:
319 throw Invalid_State("Unexpected RSA encryption scheme");
320 }
321 }();
322
323 return max_input_bytes * 8;
324 }
325
326 size_t ciphertext_length(size_t /* ptext_len */) const override {
327 return m_key_handle._public_info(m_sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits - 1;
328 }
329
330 private:
331 const Object& m_key_handle;
332 const SessionBundle& m_sessions;
333 TPMT_RSA_DECRYPT m_scheme;
334};
335
336class RSA_Decryption_Operation final : public PK_Ops::Decryption {
337 public:
338 RSA_Decryption_Operation(const Object& object, const SessionBundle& sessions, std::string_view padding) :
339 m_key_handle(object), m_sessions(sessions), m_scheme(select_encryption_algorithms(padding)) {}
340
341 secure_vector<uint8_t> decrypt(uint8_t& valid_mask, std::span<const uint8_t> input) override {
342 const auto ciphertext = copy_into<TPM2B_PUBLIC_KEY_RSA>(input);
343 const auto label = init_empty<TPM2B_DATA>(); // TODO: implement? see encrypt operation
345
346 // TODO: I'm not sure that TPM2_RC_FAILURE is the right error code for
347 // all cases here. It passed the test (with a faulty ciphertext),
348 // but I didn't find this to be clearly documented. :-(
349 auto rc = check_rc_expecting<TPM2_RC_FAILURE>("Esys_RSA_Decrypt",
350 Esys_RSA_Decrypt(*m_key_handle.context(),
351 m_key_handle.transient_handle(),
352 m_sessions[0],
353 m_sessions[1],
354 m_sessions[2],
355 &ciphertext,
356 &m_scheme,
357 &label,
358 out_ptr(plaintext)));
359
360 const auto success = CT::Mask<decltype(rc)>::is_equal(rc, TPM2_RC_SUCCESS).as_choice();
361 valid_mask = CT::Mask<uint8_t>::from_choice(success).value();
362
363 // A "typical" payload size for RSA encryption, assuming that we usually
364 // encrypt some symmetric key of a hybrid encryption scheme.
365 constexpr size_t default_plaintext_length = 32;
366
367 // When Esys_RSA_Decrypt fails to decrypt the ciphertext (e.g. because
368 // of a PKCS#1.5 padding failure), the `plaintext` pointer will be nullptr.
369 // This behaviour in itself is likely exposing a timing side channel already.
370 // Nevertheless, we do our best to mitigate any oracles by always copying a
371 // dummy plaintext value in this case.
372 auto dummy_plaintext = init_with_size<TPM2B_PUBLIC_KEY_RSA>(default_plaintext_length);
373 auto* out = &dummy_plaintext;
374 auto* maybe_plaintext = plaintext.get();
375 CT::conditional_swap_ptr(success.as_bool(), out, maybe_plaintext);
376
379 }
380
381 size_t plaintext_length(size_t /* ciphertext_length */) const override {
382 return m_key_handle._public_info(m_sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits / 8;
383 }
384
385 private:
386 const Object& m_key_handle;
387 const SessionBundle& m_sessions;
388 TPMT_RSA_DECRYPT m_scheme;
389};
390
391} // namespace
392
393std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::create_verification_op(std::string_view params,
394 std::string_view provider) const {
395 BOTAN_UNUSED(provider);
396 return std::make_unique<RSA_Verification_Operation>(handles(), sessions(), params);
397}
398
400 std::string_view params,
401 std::string_view provider) const {
402 BOTAN_UNUSED(rng, provider);
403 return std::make_unique<RSA_Signature_Operation>(handles(), sessions(), params);
404}
405
407 std::string_view params,
408 std::string_view provider) const {
409 BOTAN_UNUSED(rng, provider);
410 return std::make_unique<RSA_Encryption_Operation>(handles(), sessions(), params);
411}
412
414 std::string_view params,
415 std::string_view provider) const {
416 BOTAN_UNUSED(rng, provider);
417 return std::make_unique<RSA_Decryption_Operation>(handles(), sessions(), params);
418}
419
420} // namespace Botan::TPM2
#define BOTAN_UNUSED
Definition assert.h:120
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:61
#define BOTAN_STATE_CHECK(expr)
Definition assert.h:43
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:88
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:31
static constexpr Mask< T > from_choice(Choice c)
Definition ct_utils.h:414
static std::unique_ptr< EMSA > create_or_throw(std::string_view algo_spec)
Definition emsa.cpp:135
static OID from_string(std::string_view str)
Definition asn1_oid.cpp:86
std::vector< uint8_t > serialize() const
static PSS_Params from_emsa_name(std::string_view emsa_name)
ESYS_TR transient_handle() const noexcept
static std::unique_ptr< PrivateKey > create_transient_from_template(const std::shared_ptr< Context > &ctx, const SessionBundle &sessions, ESYS_TR parent, const TPMT_PUBLIC &key_template, const TPM2B_SENSITIVE_CREATE &sensitive_data)
Definition tpm2_key.cpp:217
const SessionBundle & sessions() const
Definition tpm2_key.h:224
const Object & handles() const
Definition tpm2_key.h:99
const SessionBundle & sessions() const
Definition tpm2_key.h:101
RSA_PrivateKey(Object handle, SessionBundle sessions, const TPM2B_PUBLIC *public_blob, std::span< const uint8_t > private_blob={})
Definition tpm2_rsa.cpp:39
static std::unique_ptr< TPM2::PrivateKey > create_unrestricted_transient(const std::shared_ptr< Context > &ctx, const SessionBundle &sessions, std::span< const uint8_t > auth_value, const TPM2::PrivateKey &parent, uint16_t keylength, std::optional< uint32_t > exponent={})
Definition tpm2_rsa.cpp:57
std::unique_ptr< PK_Ops::Decryption > create_decryption_op(Botan::RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition tpm2_rsa.cpp:413
std::unique_ptr< PK_Ops::Signature > create_signature_op(Botan::RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition tpm2_rsa.cpp:399
std::unique_ptr< PK_Ops::Encryption > create_encryption_op(Botan::RandomNumberGenerator &rng, std::string_view params, std::string_view provider) const override
Definition tpm2_rsa.cpp:406
std::unique_ptr< PK_Ops::Verification > create_verification_op(std::string_view params, std::string_view provider) const override
Definition tpm2_rsa.cpp:393
RSA_PublicKey(Object handle, SessionBundle sessions, const TPM2B_PUBLIC *public_blob)
Definition tpm2_rsa.cpp:29
constexpr void conditional_swap_ptr(bool cnd, T &x, T &y)
Definition ct_utils.h:765
std::string encrypt(const uint8_t input[], size_t input_len, std::string_view passphrase, RandomNumberGenerator &rng)
Definition cryptobox.cpp:42
std::string decrypt(const uint8_t input[], size_t input_len, std::string_view passphrase)
std::optional< TPMT_SIG_SCHEME > rsa_signature_scheme_botan_to_tss2(std::string_view name)
constexpr T init_empty()
Create an empty TPM2 buffer of the given type.
Definition tpm2_util.h:153
constexpr void check_rc(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:55
std::optional< TPMT_RSA_DECRYPT > rsa_encryption_scheme_botan_to_tss2(std::string_view padding)
std::unique_ptr< T, esys_liberator > unique_esys_ptr
A unique pointer type for ESYS handles that automatically frees the handle.
Definition tpm2_util.h:163
constexpr T init_with_size(size_t length)
Create a TPM2 buffer of a given type and length.
Definition tpm2_util.h:143
constexpr void copy_into(T &dest, std::span< const uint8_t > data)
Definition tpm2_util.h:118
constexpr TSS2_RC check_rc_expecting(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:73
constexpr auto out_ptr(T &outptr) noexcept
Definition stl_util.h:421
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:65
static TPMA_OBJECT render(ObjectAttributes attributes)