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