Botan 3.14.1
Crypto and TLS for C&
p11_rsa.cpp
Go to the documentation of this file.
1/*
2* PKCS#11 RSA
3* (C) 2016 Daniel Neus, Sirrix AG
4* (C) 2016 Philipp Weber, Sirrix AG
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/p11_rsa.h>
10
11#include <botan/pk_keys.h>
12
13#if defined(BOTAN_HAS_RSA)
14
15 #include <botan/assert.h>
16 #include <botan/mem_ops.h>
17 #include <botan/numthry.h>
18 #include <botan/p11_mechanism.h>
19 #include <botan/pk_options_readers.h>
20 #include <botan/pss_params.h>
21 #include <botan/pubkey.h>
22 #include <botan/rng.h>
23 #include <botan/internal/blinding.h>
24 #include <botan/internal/mod_inv.h>
25 #include <botan/internal/monty.h>
26 #include <botan/internal/monty_exp.h>
27 #include <botan/internal/p11_object_guard.h>
28 #include <botan/internal/p11_sig_stream.h>
29 #include <botan/internal/pk_ops_impl.h>
30 #include <botan/internal/pk_options_impl.h>
31
32namespace Botan::PKCS11 {
33
34RSA_PublicKeyImportProperties::RSA_PublicKeyImportProperties(const BigInt& modulus, const BigInt& pub_exponent) :
35 PublicKeyProperties(KeyType::Rsa), m_modulus(modulus), m_pub_exponent(pub_exponent) {
36 add_binary(AttributeType::Modulus, m_modulus.serialize());
37 add_binary(AttributeType::PublicExponent, m_pub_exponent.serialize());
38}
39
40RSA_PublicKeyGenerationProperties::RSA_PublicKeyGenerationProperties(Ulong bits) : PublicKeyProperties(KeyType::Rsa) {
41 add_numeric(AttributeType::ModulusBits, bits);
42}
43
44PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, ObjectHandle handle) :
45 Object(session, handle),
46 RSA_PublicKey(BigInt::from_bytes(get_attribute_value(AttributeType::Modulus)),
47 BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent))) {}
48
49namespace {
50
51// Validate before creating the token object, so invalid input leaves nothing behind
52const RSA_PublicKeyImportProperties& check_rsa_public_key(const RSA_PublicKeyImportProperties& props) {
53 const RSA_PublicKey key(props.modulus(), props.pub_exponent());
54 BOTAN_UNUSED(key);
55 return props; // NOLINT(*-return-const-ref-from-parameter)
56}
57
58} // namespace
59
60PKCS11_RSA_PublicKey::PKCS11_RSA_PublicKey(Session& session, const RSA_PublicKeyImportProperties& pubkey_props) :
61 Object(session, check_rsa_public_key(pubkey_props)),
62 RSA_PublicKey(pubkey_props.modulus(), pubkey_props.pub_exponent()) {}
63
64RSA_PrivateKeyImportProperties::RSA_PrivateKeyImportProperties(const BigInt& modulus, const BigInt& priv_exponent) :
65 PrivateKeyProperties(KeyType::Rsa), m_modulus(modulus), m_priv_exponent(priv_exponent) {
66 add_binary(AttributeType::Modulus, m_modulus.serialize());
67 add_binary(AttributeType::PrivateExponent, m_priv_exponent.serialize());
68}
69
70PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, ObjectHandle handle) :
71 Object(session, handle),
72 RSA_PublicKey(BigInt::from_bytes(get_attribute_value(AttributeType::Modulus)),
73 BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent))) {}
74
75PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session, const RSA_PrivateKeyImportProperties& priv_key_props) :
76 Object(session, priv_key_props) {
77 Object_Creation_Guard guard(session, {handle()});
78 BigInt n = priv_key_props.modulus();
79 BigInt e = BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent));
80 RSA_PublicKey::init(std::move(n), std::move(e));
81 guard.release();
82}
83
84PKCS11_RSA_PrivateKey::PKCS11_RSA_PrivateKey(Session& session,
85 uint32_t bits,
86 const RSA_PrivateKeyGenerationProperties& priv_key_props) :
87 Object(session) {
88 RSA_PublicKeyGenerationProperties pub_key_props(bits);
89 pub_key_props.set_encrypt(true);
90 pub_key_props.set_verify(true);
91 pub_key_props.set_token(false); // don't create a persistent public key object
92
93 ObjectHandle pub_key_handle = CK_INVALID_HANDLE;
94 ObjectHandle priv_key_handle = CK_INVALID_HANDLE;
95 const Mechanism mechanism = {static_cast<CK_MECHANISM_TYPE>(MechanismType::RsaPkcsKeyPairGen), nullptr, 0};
96 session.module()->C_GenerateKeyPair(session.handle(),
97 &mechanism,
98 pub_key_props.data(),
99 checked_ulong_cast(pub_key_props.count()),
100 priv_key_props.data(),
101 checked_ulong_cast(priv_key_props.count()),
102 &pub_key_handle,
103 &priv_key_handle);
104
105 // The public key object is only needed temporarily
106 const Object_Creation_Guard destroy_public(session, {pub_key_handle});
107 Object_Creation_Guard guard(session, {priv_key_handle});
108
109 this->reset_handle(priv_key_handle);
110
111 BigInt n = BigInt::from_bytes(get_attribute_value(AttributeType::Modulus));
112 BigInt e = BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent));
113 RSA_PublicKey::init(std::move(n), std::move(e));
114 guard.release();
115}
116
117RSA_PrivateKey PKCS11_RSA_PrivateKey::export_key() const {
118 auto p = get_attribute_value(AttributeType::Prime1);
119 auto q = get_attribute_value(AttributeType::Prime2);
120 auto e = get_attribute_value(AttributeType::PublicExponent);
121 auto d = get_attribute_value(AttributeType::PrivateExponent);
122 auto n = get_attribute_value(AttributeType::Modulus);
123
124 return RSA_PrivateKey(BigInt::from_bytes(p),
125 BigInt::from_bytes(q),
126 BigInt::from_bytes(e),
127 BigInt::from_bytes(d),
128 BigInt::from_bytes(n));
129}
130
131std::unique_ptr<Public_Key> PKCS11_RSA_PrivateKey::public_key() const {
132 return std::make_unique<RSA_PublicKey>(BigInt::from_bytes(get_attribute_value(AttributeType::Modulus)),
133 BigInt::from_bytes(get_attribute_value(AttributeType::PublicExponent)));
134}
135
136secure_vector<uint8_t> PKCS11_RSA_PrivateKey::private_key_bits() const {
137 return export_key().private_key_bits();
138}
139
140namespace {
141// note: multiple-part decryption operations (with C_DecryptUpdate/C_DecryptFinal)
142// are not supported (PK_Ops::Decryption does not provide an `update` method)
143class PKCS11_RSA_Decryption_Operation final : public PK_Ops::Decryption {
144 public:
145 PKCS11_RSA_Decryption_Operation(const PKCS11_RSA_PrivateKey& key,
146 const PK_Encryption_Options_Reader& options,
147 RandomNumberGenerator& rng) :
148 m_key(key),
149 m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(options)),
150 m_mod_n(Barrett_Reduction::for_public_modulus(m_key.get_n())),
151 m_monty_n(m_key.get_n(), m_mod_n),
152 m_bits(m_key.get_n().bits() - 1),
153 m_blinder(
154 m_mod_n,
155 rng,
156 [this](const BigInt& k) {
157 const size_t powm_window = 1;
158 const auto powm_m_n = monty_precompute(m_monty_n, k, powm_window);
159 return monty_execute_vartime(*powm_m_n, m_key.get_e()).value();
160 },
161 [this](const BigInt& k) { return inverse_mod_rsa_public_modulus(k, m_key.get_n()); }) {}
162
163 size_t plaintext_length(size_t /*ctext_len*/) const override { return m_key.get_n().bytes(); }
164
165 size_t ciphertext_length(size_t /*ptext_len*/) const override { return m_key.get_n().bytes(); }
166
167 size_t decrypt(uint8_t& valid_mask, std::span<uint8_t> ptext, std::span<const uint8_t> ctext) override {
168 valid_mask = 0;
169
170 const size_t modulus_bytes = (m_key.get_n().bits() + 7) / 8;
171
172 // blind for RSA/RAW decryption
173 const bool use_blinding = m_mechanism.padding_size() == 0;
174
175 std::vector<uint8_t> encrypted_data(ctext.begin(), ctext.end());
176
177 if(use_blinding) {
178 // RFC 8017 5.1.2: ciphertext representative must be in [0, n-1];
179 // check before blinding (which reduces mod n).
180 if(encrypted_data.size() != modulus_bytes) {
181 return 0;
182 }
183 const BigInt input_bn = BigInt::from_bytes(encrypted_data);
184 if(input_bn.is_zero() || input_bn >= m_key.get_n()) {
185 return 0;
186 }
187 const BigInt blinded = m_blinder.blind(input_bn);
188 // SoftHSM at least requires raw RSA inputs be == the modulus size
189 encrypted_data = blinded.serialize(modulus_bytes);
190 }
191
192 m_key.module()->C_DecryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
193
194 secure_vector<uint8_t> decrypted_data;
195 try {
196 m_key.module()->C_Decrypt(m_key.session().handle(), encrypted_data, decrypted_data);
197 valid_mask = 0xFF;
198 } catch(PKCS11_Error&) {
199 decrypted_data.clear();
200 }
201
202 // Unblind for RSA/RAW decryption
203 if(use_blinding) {
204 const BigInt unblinded = m_blinder.unblind(BigInt::from_bytes(decrypted_data));
205 decrypted_data.resize(modulus_bytes);
206 unblinded.serialize_to(decrypted_data);
207 }
208
209 BOTAN_ARG_CHECK(ptext.size() >= decrypted_data.size(), "Output buffer too small for decryption");
210 copy_mem(ptext.first(decrypted_data.size()), decrypted_data);
211 return decrypted_data.size();
212 }
213
214 private:
215 PKCS11_RSA_PrivateKey m_key;
216 MechanismWrapper m_mechanism;
217 Barrett_Reduction m_mod_n;
218 const Montgomery_Params m_monty_n;
219 size_t m_bits;
220 Blinder m_blinder;
221};
222
223// note: multiple-part decryption operations (with C_DecryptUpdate/C_DecryptFinal)
224// are not supported (PK_Ops::Decryption does not provide an `update` method)
225class PKCS11_RSA_Decryption_Operation_Software_EME final : public PK_Ops::Decryption_with_Padding {
226 public:
227 PKCS11_RSA_Decryption_Operation_Software_EME(const PKCS11_RSA_PrivateKey& key,
228 const PK_Encryption_Options_Reader& options,
229 RandomNumberGenerator& rng) :
230 PK_Ops::Decryption_with_Padding(options),
231 m_raw_op(key, PK_Options_Reader_Access::read(PK_Encryption_Options().with_padding("Raw")), rng) {}
232
233 size_t plaintext_length(size_t ctext_len) const override { return m_raw_op.plaintext_length(ctext_len); }
234
235 size_t ciphertext_length(size_t ptext_len) const override { return m_raw_op.ciphertext_length(ptext_len); }
236
237 secure_vector<uint8_t> raw_decrypt(std::span<const uint8_t> input) override {
238 /*
239 * RFC 8017 7.1.2 and 7.2.2
240 *
241 * If the length of the ciphertext C is not k octets, output
242 * "decryption error" and stop.
243 */
244 if(input.size() != m_raw_op.ciphertext_length(0)) {
245 throw Decoding_Error("RSA ciphertext is an incorrect size for this public key");
246 }
247
248 // Returns the fixed-width RSA encoded message (I2OSP(m, k)); the outer
249 // PKCS#1 / OAEP unpadder relies on the leading 0x00 byte being preserved.
250 uint8_t valid_mask = 0;
251 secure_vector<uint8_t> raw(m_raw_op.plaintext_length(input.size()));
252 raw.resize(m_raw_op.decrypt(valid_mask, raw, input));
253 return raw;
254 }
255
256 private:
257 PKCS11_RSA_Decryption_Operation m_raw_op;
258};
259
260// note: multiple-part encryption operations (with C_EncryptUpdate/C_EncryptFinal)
261// are not supported (PK_Ops::Encryption does not provide an `update` method)
262class PKCS11_RSA_Encryption_Operation final : public PK_Ops::Encryption {
263 public:
264 PKCS11_RSA_Encryption_Operation(const PKCS11_RSA_PublicKey& key, const PK_Encryption_Options_Reader& options) :
265 m_key(key), m_mechanism(MechanismWrapper::create_rsa_crypt_mechanism(options)) {
266 const size_t k = key.get_n().bytes();
267 const size_t pad = m_mechanism.padding_size();
268 if(pad == 0) {
269 m_bits = 8 * k - 1;
270 } else if(k > pad) {
271 m_bits = 8 * (k - pad);
272 } else {
273 m_bits = 0;
274 }
275 }
276
277 size_t ciphertext_length(size_t /*ptext_len*/) const override { return m_key.get_n().bytes(); }
278
279 size_t max_input_bits() const override { return m_bits; }
280
281 std::vector<uint8_t> encrypt(std::span<const uint8_t> input, RandomNumberGenerator& /*rng*/) override {
282 m_key.module()->C_EncryptInit(m_key.session().handle(), m_mechanism.data(), m_key.handle());
283
284 std::vector<uint8_t> encrypted_data;
285 m_key.module()->C_Encrypt(
286 m_key.session().handle(), secure_vector<uint8_t>(input.begin(), input.end()), encrypted_data);
287 return encrypted_data;
288 }
289
290 private:
291 PKCS11_RSA_PublicKey m_key;
292 MechanismWrapper m_mechanism;
293 size_t m_bits = 0;
294};
295
296class PKCS11_RSA_Signature_Operation final : public PK_Ops::Signature {
297 public:
298 PKCS11_RSA_Signature_Operation(const PKCS11_RSA_PrivateKey& key, const PK_Signature_Options_Reader& options) :
299 m_key(key),
300 m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(options)),
301 m_stream(Signature_Stream::Direction::Sign, m_key, m_mechanism) {}
302
303 size_t signature_length() const override { return m_key.get_n().bytes(); }
304
305 void update(std::span<const uint8_t> input) override { m_stream.update(input); }
306
307 std::vector<uint8_t> sign(RandomNumberGenerator& /*rng*/) override {
308 auto signature = m_stream.sign();
309 if(signature.size() != signature_length()) {
310 throw PKCS11_Error("PKCS #11 module returned an RSA signature of unexpected length");
311 }
312 return signature;
313 }
314
315 std::string hash_function() const override;
316
317 AlgorithmIdentifier algorithm_identifier() const override;
318
319 private:
320 PKCS11_RSA_PrivateKey m_key;
321 MechanismWrapper m_mechanism;
322 Signature_Stream m_stream;
323};
324
325namespace {
326
327std::string hash_function_name_from_pkcs11_rsa_mechanism_type(MechanismType type) {
328 switch(type) {
329 case MechanismType::Sha1RsaPkcs:
330 case MechanismType::Sha1RsaPkcsPss:
331 case MechanismType::Sha1RsaX931:
332 return "SHA-1";
333
334 case MechanismType::Sha224RsaPkcs:
335 case MechanismType::Sha224RsaPkcsPss:
336 return "SHA-224";
337
338 case MechanismType::Sha256RsaPkcs:
339 case MechanismType::Sha256RsaPkcsPss:
340 return "SHA-256";
341
342 case MechanismType::Sha384RsaPkcs:
343 case MechanismType::Sha384RsaPkcsPss:
344 return "SHA-384";
345
346 case MechanismType::Sha512RsaPkcs:
347 case MechanismType::Sha512RsaPkcsPss:
348 return "SHA-512";
349
350 case MechanismType::RsaX509:
351 case MechanismType::RsaX931:
352 case MechanismType::RsaPkcs:
353 case MechanismType::RsaPkcsPss:
354 return "Raw";
355
356 default:
357 throw Internal_Error("Unable to determine associated hash function of PKCS11 RSA signature operation");
358 }
359}
360
361} // namespace
362
363std::string PKCS11_RSA_Signature_Operation::hash_function() const {
364 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
365}
366
367AlgorithmIdentifier PKCS11_RSA_Signature_Operation::algorithm_identifier() const {
368 const std::string hash = this->hash_function();
369
370 switch(m_mechanism.mechanism_type()) {
371 case MechanismType::Sha1RsaPkcs:
372 case MechanismType::Sha224RsaPkcs:
373 case MechanismType::Sha256RsaPkcs:
374 case MechanismType::Sha384RsaPkcs:
375 case MechanismType::Sha512RsaPkcs: {
376 const OID oid = OID::from_string("RSA/EMSA3(" + hash + ")");
377 return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_NULL_PARAM);
378 }
379
380 case MechanismType::Sha1RsaPkcsPss:
381 case MechanismType::Sha224RsaPkcsPss:
382 case MechanismType::Sha256RsaPkcsPss:
383 case MechanismType::Sha384RsaPkcsPss:
384 case MechanismType::Sha512RsaPkcsPss: {
385 // The hashed PSS mechanisms always use MGF1 with the message hash
386 const auto* pss = static_cast<const RsaPkcsPssParams*>(m_mechanism.data()->pParameter);
388 return AlgorithmIdentifier("RSA/PSS", PSS_Params(hash, pss->sLen).serialize());
389 }
390
391 default:
392 throw Not_Implemented("No algorithm identifier defined for RSA with this PKCS11 mechanism");
393 }
394}
395
396class PKCS11_RSA_Verification_Operation final : public PK_Ops::Verification {
397 public:
398 PKCS11_RSA_Verification_Operation(const PKCS11_RSA_PublicKey& key, const PK_Signature_Options_Reader& options) :
399 m_key(key),
400 m_mechanism(MechanismWrapper::create_rsa_sign_mechanism(options)),
401 m_stream(Signature_Stream::Direction::Verify, m_key, m_mechanism) {}
402
403 void update(std::span<const uint8_t> input) override { m_stream.update(input); }
404
405 bool is_valid_signature(std::span<const uint8_t> sig) override { return m_stream.verify(sig); }
406
407 std::string hash_function() const override;
408
409 private:
410 const PKCS11_RSA_PublicKey m_key;
411 MechanismWrapper m_mechanism;
412 Signature_Stream m_stream;
413};
414
415std::string PKCS11_RSA_Verification_Operation::hash_function() const {
416 return hash_function_name_from_pkcs11_rsa_mechanism_type(m_mechanism.mechanism_type());
417}
418
419} // namespace
420
421std::unique_ptr<PK_Ops::Encryption> PKCS11_RSA_PublicKey::_create_encryption_op(
422 RandomNumberGenerator& rng, const PK_Encryption_Options_Reader& options) const {
423 BOTAN_UNUSED(rng);
424 require_hardware_provider(options, algo_name(), "pkcs11");
425 return std::make_unique<PKCS11_RSA_Encryption_Operation>(*this, options);
426}
427
428std::unique_ptr<PK_Ops::Verification> PKCS11_RSA_PublicKey::_create_verification_op(
429 const PK_Signature_Options_Reader& options) const {
430 require_hardware_provider(options, algo_name(), "pkcs11");
431 return std::make_unique<PKCS11_RSA_Verification_Operation>(*this, options);
432}
433
434std::unique_ptr<PK_Ops::Decryption> PKCS11_RSA_PrivateKey::_create_decryption_op(
435 RandomNumberGenerator& rng, const PK_Encryption_Options_Reader& options) const {
436 require_hardware_provider(options, algo_name(), "pkcs11");
437 if(m_use_software_padding && options.padding().value_or("Raw") != "Raw") {
438 return std::make_unique<PKCS11_RSA_Decryption_Operation_Software_EME>(*this, options, rng);
439 } else {
440 return std::make_unique<PKCS11_RSA_Decryption_Operation>(*this, options, rng);
441 }
442}
443
444std::unique_ptr<PK_Ops::Signature> PKCS11_RSA_PrivateKey::_create_signature_op(
445 RandomNumberGenerator& rng, const PK_Signature_Options_Reader& options) const {
446 BOTAN_UNUSED(rng);
447 require_hardware_provider(options, algo_name(), "pkcs11");
448 return std::make_unique<PKCS11_RSA_Signature_Operation>(*this, options);
449}
450
451PKCS11_RSA_KeyPair generate_rsa_keypair(Session& session,
452 const RSA_PublicKeyGenerationProperties& pub_props,
453 const RSA_PrivateKeyGenerationProperties& priv_props) {
454 ObjectHandle pub_key_handle = 0;
455 ObjectHandle priv_key_handle = 0;
456
457 const Mechanism mechanism = {static_cast<CK_MECHANISM_TYPE>(MechanismType::RsaPkcsKeyPairGen), nullptr, 0};
458
459 session.module()->C_GenerateKeyPair(session.handle(),
460 &mechanism,
461 pub_props.data(),
462 checked_ulong_cast(pub_props.count()),
463 priv_props.data(),
464 checked_ulong_cast(priv_props.count()),
465 &pub_key_handle,
466 &priv_key_handle);
467
468 Object_Creation_Guard guard(session, {pub_key_handle, priv_key_handle});
469 auto keypair =
470 std::make_pair(PKCS11_RSA_PublicKey(session, pub_key_handle), PKCS11_RSA_PrivateKey(session, priv_key_handle));
471 guard.release();
472 return keypair;
473}
474
475} // namespace Botan::PKCS11
476
477#endif
#define BOTAN_UNUSED
Definition assert.h:151
#define BOTAN_ASSERT_NONNULL(ptr)
Definition assert.h:121
#define BOTAN_ARG_CHECK(expr, msg)
Definition assert.h:33
BigInt value() const
Definition monty.cpp:279
Common attributes of all public key objects.
Definition p11_object.h:305
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< uint64_t > read()
Definition hwrng.cpp:15
Ulong checked_ulong_cast(size_t v)
Definition p11.h:1228
AttributeType
Definition p11.h:50
CK_MECHANISM Mechanism
Definition p11.h:1207
CK_OBJECT_HANDLE ObjectHandle
Definition p11.h:1214
CK_RSA_PKCS_PSS_PARAMS RsaPkcsPssParams
Definition p11.h:1217
void require_hardware_provider(const OptionsT &options, std::string_view algo_name, std::string_view provider_name)
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
std::shared_ptr< const Montgomery_Exponentiation_State > monty_precompute(const Montgomery_Int &g, size_t window_bits)
Montgomery_Int monty_execute_vartime(const Montgomery_Exponentiation_State &precomputed_state, const BigInt &k)
BigInt inverse_mod_rsa_public_modulus(const BigInt &x, const BigInt &n)
Definition mod_inv.cpp:302
#define CK_INVALID_HANDLE
Definition pkcs11.h:35
CK_ULONG CK_MECHANISM_TYPE
Definition pkcs11.h:59