Botan 3.14.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/mem_ops.h>
12#include <botan/pk_options_readers.h>
13#include <botan/pss_params.h>
14#include <botan/rsa.h>
15#include <botan/internal/pk_options_impl.h>
16
17#include <botan/internal/ct_utils.h>
18#include <botan/internal/fmt.h>
19#include <botan/internal/sig_padding.h>
20#include <botan/internal/stl_util.h>
21#include <botan/internal/tpm2_algo_mappings.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 const 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 const 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(const PK_Signature_Options_Reader& options) {
146 if(!options.using_padding()) {
147 throw Not_Implemented("TPM2 RSA signing without padding is not supported");
148 }
149
150 if(!options.using_hash()) {
151 throw Invalid_Argument("RSA signing padding scheme must at least specify a hash function");
152 }
153
154 // The TPM chooses the PSS salt length itself, and PKCS#1 v1.5 has no salt
155 if(options.using_salt_size()) {
156 throw Not_Implemented("TPM2 RSA signing does not support specifying the salt size");
157 }
158
159 const std::string& hash_name = options.hash_function_name();
160 const std::string padding = fmt("{}({})", options.padding().value(), hash_name);
161
162 // PKCS#1 v1.5 is deterministic, while the TPM generates the PSS salt itself
163 if(options.using_deterministic_signature() && options.padding().value() != "PKCS1v15") {
164 throw Invalid_Argument(fmt("TPM2 RSA signing with {} cannot produce deterministic signatures", padding));
165 }
166
167 auto sig_scheme = rsa_signature_scheme_botan_to_tss2(padding);
168 if(!sig_scheme) {
169 throw Not_Implemented(Botan::fmt("RSA signing with padding scheme {}", padding));
170 }
171
172 return {
173 .signature_scheme = sig_scheme.value(),
174 .hash_name = hash_name,
175 .padding = padding,
176 };
177}
178
179size_t signature_length_for_rsa_key_handle(const SessionBundle& sessions, const Object& key_handle) {
180 return key_handle._public_info(sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits / 8;
181}
182
183class RSA_Signature_Operation final : public Signature_Operation {
184 public:
185 RSA_Signature_Operation(const Object& object,
186 const SessionBundle& sessions,
187 const PK_Signature_Options_Reader& options) :
188 Signature_Operation(object, sessions, select_signature_algorithms(options)),
189 // This EMSA object actually isn't required, we just need it to
190 // conveniently figure out the padding name for the algorithm identifier
191 m_padding_name(SignaturePaddingScheme::create_or_throw(options)->name()) {}
192
193 size_t signature_length() const override { return signature_length_for_rsa_key_handle(sessions(), key_handle()); }
194
195 AlgorithmIdentifier algorithm_identifier() const override {
196 // TODO: This is essentially a copy of the ::algorithm_identifier()
197 // in `rsa.h`. We should probably refactor this into a common
198 // function.
199
200 // TODO: This is a hack, and we should clean this up.
201
202 try {
203 const std::string full_name = "RSA/" + m_padding_name;
204 const OID oid = OID::from_string(full_name);
205 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_NULL_PARAM);
206 } catch(Lookup_Error&) {}
207
208 if(m_padding_name.starts_with("PSS(")) {
209 const auto parameters = PSS_Params::from_padding_name(m_padding_name).serialize();
210 return AlgorithmIdentifier("RSA/PSS", parameters);
211 }
212
213 throw Invalid_Argument(fmt("Signatures using RSA/{} are not supported", m_padding_name));
214 }
215
216 private:
217 std::vector<uint8_t> marshal_signature(const TPMT_SIGNATURE& signature) const override {
218 const auto& sig = [&] {
219 if(signature.sigAlg == TPM2_ALG_RSASSA) {
220 return signature.signature.rsassa;
221 } else if(signature.sigAlg == TPM2_ALG_RSAPSS) {
222 return signature.signature.rsapss;
223 }
224 throw Invalid_State(fmt("TPM2 returned an unexpected signature scheme {}", signature.sigAlg));
225 }();
226
227 BOTAN_ASSERT_NOMSG(sig.sig.size == signature_length());
228 return copy_into<std::vector<uint8_t>>(sig.sig);
229 }
230
231 std::string m_padding_name;
232};
233
234class RSA_Verification_Operation final : public Verification_Operation {
235 public:
236 RSA_Verification_Operation(const Object& object,
237 const SessionBundle& sessions,
238 const PK_Signature_Options_Reader& options) :
239 Verification_Operation(object, sessions, select_signature_algorithms(options)) {}
240
241 private:
242 TPMT_SIGNATURE unmarshal_signature(std::span<const uint8_t> signature) const override {
243 BOTAN_ARG_CHECK(signature.size() == signature_length_for_rsa_key_handle(sessions(), key_handle()),
244 "Unexpected signature byte length");
245
246 TPMT_SIGNATURE sig;
247 sig.sigAlg = scheme().scheme;
248
249 auto& sig_data = [&]() -> TPMS_SIGNATURE_RSA& {
250 if(sig.sigAlg == TPM2_ALG_RSASSA) {
251 return sig.signature.rsassa;
252 } else if(sig.sigAlg == TPM2_ALG_RSAPSS) {
253 return sig.signature.rsapss;
254 }
255 throw Invalid_State(fmt("Requested an unexpected signature scheme {}", sig.sigAlg));
256 }();
257
258 sig_data.hash = scheme().details.any.hashAlg;
259 copy_into(sig_data.sig, signature);
260 return sig;
261 }
262};
263
264TPMT_RSA_DECRYPT select_encryption_algorithms(const PK_Encryption_Options_Reader& options) {
265 if(!options.using_padding()) {
266 throw Lookup_Error("TPM2 RSA encryption requires specifying a padding scheme");
267 }
268
269 std::string padding = options.padding().value();
270
271 if(padding == "OAEP") {
272 if(!options.using_hash()) {
273 throw Lookup_Error("TPM2 RSA OAEP requires specifying a hash function");
274 }
275 const std::string& hash_name = options.hash_function_name();
276
277 // The TPM always uses the OAEP hash for MGF1 as well
278 if(options.using_mgf1_hash() && options.mgf1_hash_function().value() != hash_name) {
279 throw Not_Implemented("TPM2 RSA OAEP does not support a distinct MGF1 hash function");
280 }
281
282 // TODO: support the OAEP label; note that the TPM includes a terminating
283 // null byte in the label it hashes, so this is not directly compatible
284 // with an RFC 8017 label of the same bytes
285
286 padding = fmt("OAEP({})", hash_name);
287 }
288
289 auto scheme = rsa_encryption_scheme_botan_to_tss2(padding);
290 if(!scheme) {
291 throw Not_Implemented(Botan::fmt("RSA encryption with padding scheme {}", padding));
292 }
293 return scheme.value();
294}
295
296class RSA_Encryption_Operation final : public PK_Ops::Encryption {
297 public:
298 RSA_Encryption_Operation(const Object& object,
299 const SessionBundle& sessions,
300 const PK_Encryption_Options_Reader& options) :
301 m_key_handle(object), m_sessions(sessions), m_scheme(select_encryption_algorithms(options)) {}
302
303 std::vector<uint8_t> encrypt(std::span<const uint8_t> msg, Botan::RandomNumberGenerator& /* rng */) override {
304 const auto plaintext = copy_into<TPM2B_PUBLIC_KEY_RSA>(msg);
305
306 // The OAEP label; see the TODO in select_encryption_algorithms
307 const auto label = init_empty<TPM2B_DATA>();
308
310 check_rc("Esys_RSA_Encrypt",
311 Esys_RSA_Encrypt(m_key_handle.context()->esys_context(),
312 m_key_handle.transient_handle(),
313 m_sessions[0],
314 m_sessions[1],
315 m_sessions[2],
316 &plaintext,
317 &m_scheme,
318 &label,
319 out_ptr(ciphertext)));
320 BOTAN_ASSERT_NONNULL(ciphertext);
321 return copy_into<std::vector<uint8_t>>(*ciphertext);
322 }
323
324 // This duplicates quite a bit of domain knowledge about those RSA
325 // EMEs. And I'm quite certain that I screwed up somewhere.
326 //
327 // TODO: See if we can somehow share the logic with the software
328 // RSA implementation and also PKCS#11 (which I believe is plain wrong).
329 size_t max_input_bits() const override {
330 const auto max_ptext_bytes =
331 (m_key_handle._public_info(m_sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits - 1) / 8;
332 auto hash_output_bytes = [](TPM2_ALG_ID hash) -> size_t {
333 switch(hash) {
334 case TPM2_ALG_SHA1:
335 return 160 / 8;
336 case TPM2_ALG_SHA256:
337 case TPM2_ALG_SHA3_256:
338 return 256 / 8;
339 case TPM2_ALG_SHA384:
340 case TPM2_ALG_SHA3_384:
341 return 384 / 8;
342 case TPM2_ALG_SHA512:
343 case TPM2_ALG_SHA3_512:
344 return 512 / 8;
345 default:
346 throw Invalid_State("Unexpected hash algorithm");
347 }
348 };
349
350 const auto max_input_bytes = [&]() -> size_t {
351 switch(m_scheme.scheme) {
352 case TPM2_ALG_RSAES:
353 return max_ptext_bytes - 10;
354 case TPM2_ALG_OAEP:
355 return max_ptext_bytes - 2 * hash_output_bytes(m_scheme.details.oaep.hashAlg) - 1;
356 case TPM2_ALG_NULL:
357 return max_ptext_bytes;
358 default:
359 throw Invalid_State("Unexpected RSA encryption scheme");
360 }
361 }();
362
363 return max_input_bytes * 8;
364 }
365
366 size_t ciphertext_length(size_t /* ptext_len */) const override {
367 return m_key_handle._public_info(m_sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits - 1;
368 }
369
370 private:
371 const Object& m_key_handle;
372 const SessionBundle& m_sessions;
373 TPMT_RSA_DECRYPT m_scheme;
374};
375
376class RSA_Decryption_Operation final : public PK_Ops::Decryption {
377 public:
378 RSA_Decryption_Operation(const Object& object,
379 const SessionBundle& sessions,
380 const PK_Encryption_Options_Reader& options) :
381 m_key_handle(object), m_sessions(sessions), m_scheme(select_encryption_algorithms(options)) {}
382
383 size_t decrypt(uint8_t& valid_mask, std::span<uint8_t> ptext, std::span<const uint8_t> input) override {
384 const auto ciphertext = copy_into<TPM2B_PUBLIC_KEY_RSA>(input);
385 const auto label = init_empty<TPM2B_DATA>(); // see the TODO in select_encryption_algorithms
387
388 // TODO: I'm not sure that TPM2_RC_FAILURE is the right error code for
389 // all cases here. It passed the test (with a faulty ciphertext),
390 // but I didn't find this to be clearly documented. :-(
391 //
392 // It seems the TPM2 simulator in Ubuntu 26.04 returns some other (otherwise
393 // undocumented?) value. Since this situation is clearly a bit ambiguous we now
394 // just accept any error as "decryption failed", somewhat unfortunate in that
395 // logical errors may become hidden but no clear resolution otherwise.
396 const auto rc = Esys_RSA_Decrypt(m_key_handle.context()->esys_context(),
397 m_key_handle.transient_handle(),
398 m_sessions[0],
399 m_sessions[1],
400 m_sessions[2],
401 &ciphertext,
402 &m_scheme,
403 &label,
404 out_ptr(plaintext));
405
406 const auto success = CT::Mask<TSS2_RC>::is_equal(rc, TPM2_RC_SUCCESS).as_choice();
407 valid_mask = CT::Mask<uint8_t>::from_choice(success).value();
408
409 // A "typical" payload size for RSA encryption, assuming that we usually
410 // encrypt some symmetric key of a hybrid encryption scheme.
411 constexpr size_t default_plaintext_length = 32;
412
413 // When Esys_RSA_Decrypt fails to decrypt the ciphertext (e.g. because
414 // of a PKCS#1.5 padding failure), the `plaintext` pointer will be nullptr.
415 // This behaviour in itself is likely exposing a timing side channel already.
416 // Nevertheless, we do our best to mitigate any oracles by always copying a
417 // dummy plaintext value in this case.
418 auto dummy_plaintext = init_with_size<TPM2B_PUBLIC_KEY_RSA>(default_plaintext_length);
419 auto* out = &dummy_plaintext;
420 auto* maybe_plaintext = plaintext.get();
421 CT::conditional_swap_ptr(success.as_bool(), out, maybe_plaintext);
422
424 const auto decrypted = as_span(*out);
425 BOTAN_ARG_CHECK(ptext.size() >= decrypted.size(), "Output buffer too small for decryption");
426 copy_mem(ptext.first(decrypted.size()), decrypted);
427 return decrypted.size();
428 }
429
430 size_t plaintext_length(size_t /* ciphertext_length */) const override {
431 return m_key_handle._public_info(m_sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits / 8;
432 }
433
434 size_t ciphertext_length(size_t /* ptext_len */) const override {
435 return m_key_handle._public_info(m_sessions, TPM2_ALG_RSA).pub->publicArea.parameters.rsaDetail.keyBits / 8;
436 }
437
438 private:
439 const Object& m_key_handle;
440 const SessionBundle& m_sessions;
441 TPMT_RSA_DECRYPT m_scheme;
442};
443
444} // namespace
445
446std::unique_ptr<PK_Ops::Verification> RSA_PublicKey::_create_verification_op(
447 const PK_Signature_Options_Reader& options) const {
448 require_hardware_provider(options, algo_name(), "tpm2");
449 return std::make_unique<RSA_Verification_Operation>(handles(), sessions(), options);
450}
451
452std::unique_ptr<PK_Ops::Signature> RSA_PrivateKey::_create_signature_op(
454 BOTAN_UNUSED(rng);
455 require_hardware_provider(options, algo_name(), "tpm2");
456 return std::make_unique<RSA_Signature_Operation>(handles(), sessions(), options);
457}
458
459std::unique_ptr<PK_Ops::Encryption> RSA_PublicKey::_create_encryption_op(
461 BOTAN_UNUSED(rng);
462 require_hardware_provider(options, algo_name(), "tpm2");
463 return std::make_unique<RSA_Encryption_Operation>(handles(), sessions(), options);
464}
465
466std::unique_ptr<PK_Ops::Decryption> RSA_PrivateKey::_create_decryption_op(
468 BOTAN_UNUSED(rng);
469 require_hardware_provider(options, algo_name(), "tpm2");
470 return std::make_unique<RSA_Decryption_Operation>(handles(), sessions(), options);
471}
472
473} // namespace Botan::TPM2
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:82
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
static constexpr Mask< T > from_choice(Choice c)
Definition ct_utils.h:407
static constexpr Mask< T > is_equal(T x, T y)
Definition ct_utils.h:447
static OID from_string(std::string_view str)
Definition asn1_oid.cpp:80
const std::optional< std::string > & padding() const
const std::string & hash_function_name() const
static PSS_Params from_padding_name(std::string_view padding_name)
std::vector< uint8_t > serialize() const
std::string algo_name() const override
Definition rsa.h:41
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:224
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
std::unique_ptr< PK_Ops::Signature > _create_signature_op(Botan::RandomNumberGenerator &rng, const PK_Signature_Options_Reader &options) const override
Definition tpm2_rsa.cpp:452
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, const PK_Encryption_Options_Reader &options) const override
Definition tpm2_rsa.cpp:466
std::unique_ptr< PK_Ops::Encryption > _create_encryption_op(Botan::RandomNumberGenerator &rng, const PK_Encryption_Options_Reader &options) const override
Definition tpm2_rsa.cpp:459
std::unique_ptr< PK_Ops::Verification > _create_verification_op(const PK_Signature_Options_Reader &options) const override
Definition tpm2_rsa.cpp:446
RSA_PublicKey(Object handle, SessionBundle sessions, const TPM2B_PUBLIC *public_blob)
Definition tpm2_rsa.cpp:29
const char * name
Definition ffi_tls.h:59
constexpr void conditional_swap_ptr(bool cnd, T &x, T &y)
Definition ct_utils.h:779
std::string decrypt(std::span< const uint8_t > input, std::string_view passphrase)
std::string encrypt(const uint8_t input[], size_t input_len, std::string_view passphrase, RandomNumberGenerator &rng)
Definition cryptobox.cpp:44
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:151
constexpr void check_rc(std::string_view location, TSS2_RC rc)
Definition tpm2_util.h:53
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:161
constexpr T init_with_size(size_t length)
Create a TPM2 buffer of a given type and length.
Definition tpm2_util.h:141
constexpr void copy_into(T &dest, std::span< const uint8_t > data)
Definition tpm2_util.h:116
constexpr auto as_span(tpm2_buffer auto &data)
Construct a std::span as a view into a TPM2 buffer.
Definition tpm2_util.h:101
void require_hardware_provider(const OptionsT &options, std::string_view algo_name, std::string_view provider_name)
constexpr auto out_ptr(T &outptr) noexcept
Definition stl_util.h:164
std::string fmt(std::string_view format, const T &... args)
Definition fmt.h:53
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
static TPMA_OBJECT render(ObjectAttributes attributes)