Botan 3.14.1
Crypto and TLS for C&
p11_ecdh.cpp
Go to the documentation of this file.
1/*
2* PKCS#11 ECDH
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_ecdh.h>
10
11#if defined(BOTAN_HAS_ECDH)
12
13 #include <botan/der_enc.h>
14 #include <botan/ec_apoint.h>
15 #include <botan/p11_mechanism.h>
16 #include <botan/pk_ops.h>
17 #include <botan/pk_options_readers.h>
18 #include <botan/rng.h>
19 #include <botan/internal/p11_object_guard.h>
20 #include <botan/internal/pk_options_impl.h>
21 #include <botan/internal/scoped_cleanup.h>
22
23 #if defined(BOTAN_HAS_LEGACY_EC_POINT)
24 #include <botan/ec_point.h>
25 #endif
26
27namespace Botan::PKCS11 {
28
29ECDH_PublicKey PKCS11_ECDH_PublicKey::export_key() const {
30 return ECDH_PublicKey(domain(), public_ec_point());
31}
32
33ECDH_PrivateKey PKCS11_ECDH_PrivateKey::export_key() const {
34 auto priv_key = get_attribute_value(AttributeType::Value);
35
36 Null_RNG rng;
37 return ECDH_PrivateKey(rng, domain(), BigInt::from_bytes(priv_key));
38}
39
40std::unique_ptr<Public_Key> PKCS11_ECDH_PrivateKey::public_key() const {
41 return std::make_unique<ECDH_PublicKey>(domain(), public_ec_point());
42}
43
44secure_vector<uint8_t> PKCS11_ECDH_PrivateKey::private_key_bits() const {
45 return export_key().private_key_bits();
46}
47
48namespace {
49class PKCS11_ECDH_KA_Operation final : public PK_Ops::Key_Agreement {
50 public:
51 PKCS11_ECDH_KA_Operation(const PKCS11_ECDH_PrivateKey& key, std::string_view params) :
52 PK_Ops::Key_Agreement(), m_key(key), m_mechanism(MechanismWrapper::create_ecdh_mechanism(params)) {}
53
54 size_t agreed_value_size() const override { return m_key.domain().get_p_bytes(); }
55
56 /// The encoding in V2.20 was not specified and resulted in different implementations choosing different encodings.
57 /// Applications relying only on a V2.20 encoding (e.g. the DER variant) other than the one specified now (raw) may not work with all V2.30 compliant tokens.
58 secure_vector<uint8_t> agree(size_t key_len,
59 std::span<const uint8_t> other_key,
60 std::span<const uint8_t> salt) override {
61 const auto peer_point = EC_AffinePoint::deserialize(m_key.domain(), other_key);
62 if(!peer_point) {
63 throw Decoding_Error("ECDH - Invalid elliptic curve point: not on curve");
64 }
65 if(peer_point->is_identity()) {
66 throw Decoding_Error("ECDH - Invalid elliptic curve point: identity");
67 }
68
69 /*
70 * CKM_ECDH1_DERIVE does not clear the cofactor, so a point with a small
71 * order component would reveal the private scalar modulo that order.
72 * CKM_ECDH1_COFACTOR_DERIVE is not an alternative, since it computes a
73 * different value than ECDH in software does.
74 */
75 if(m_key.domain().has_cofactor()) {
76 #if defined(BOTAN_HAS_LEGACY_EC_POINT)
77 if(!(m_key.domain().get_order() * peer_point->to_legacy_point()).is_zero()) {
78 throw Decoding_Error("ECDH - Invalid elliptic curve point: not in the prime order subgroup");
79 }
80 #else
81 throw Not_Implemented("PKCS#11 ECDH with a cofactor is not available in this build configuration");
82 #endif
83 }
84
85 std::vector<uint8_t> der_encoded_other_key;
86 if(m_key.point_encoding() == PublicPointEncoding::Der) {
87 DER_Encoder(der_encoded_other_key).encode(other_key.data(), other_key.size(), ASN1_Type::OctetString);
88 m_mechanism.set_ecdh_other_key(der_encoded_other_key.data(), der_encoded_other_key.size());
89 } else {
90 m_mechanism.set_ecdh_other_key(other_key.data(), other_key.size());
91 }
92
93 const bool raw_kdf = (m_mechanism.ecdh_kdf() == KeyDerivation::Null);
94
95 if(raw_kdf && !salt.empty()) {
96 throw Invalid_Argument("PK_Key_Agreement::derive_key requires a KDF to use a salt");
97 }
98
99 if(salt.empty()) {
100 m_mechanism.set_ecdh_salt(nullptr, 0);
101 } else {
102 m_mechanism.set_ecdh_salt(salt.data(), salt.size());
103 }
104
105 const size_t out_len = raw_kdf ? agreed_value_size() : key_len;
106
107 ObjectHandle secret_handle = 0;
108 AttributeContainer attributes;
109 attributes.add_bool(AttributeType::Sensitive, false);
110 attributes.add_bool(AttributeType::Extractable, true);
111 attributes.add_numeric(AttributeType::Class, static_cast<CK_OBJECT_CLASS>(ObjectClass::SecretKey));
112 attributes.add_numeric(AttributeType::KeyType, static_cast<CK_KEY_TYPE>(KeyType::GenericSecret));
113 attributes.add_numeric(AttributeType::ValueLen, checked_ulong_cast(out_len));
114 m_key.module()->C_DeriveKey(m_key.session().handle(),
115 m_mechanism.data(),
116 m_key.handle(),
117 attributes.data(),
118 checked_ulong_cast(attributes.count()),
119 &secret_handle);
120
121 const Object secret_object(m_key.session(), secret_handle);
122 const auto destroy_secret = scoped_cleanup([&]() noexcept {
123 try {
124 secret_object.destroy();
125 } catch(...) { // NOLINT(*-empty-catch)
126 }
127 });
128 secure_vector<uint8_t> secret = secret_object.get_attribute_value(AttributeType::Value);
129 if(secret.size() < out_len) {
130 throw PKCS11_Error("ECDH key derivation secret length is too short");
131 }
132 secret.resize(out_len);
133 return secret;
134 }
135
136 private:
137 PKCS11_ECDH_PrivateKey m_key;
138 MechanismWrapper m_mechanism;
139};
140
141} // namespace
142
143std::unique_ptr<PK_Ops::Key_Agreement> PKCS11_ECDH_PrivateKey::_create_key_agreement_op(
144 RandomNumberGenerator& /*rng*/, const PK_Key_Agreement_Options_Reader& options) const {
145 require_hardware_provider(options, algo_name(), "pkcs11");
146
147 /*
148 * The token performs the derivation, so the KDF names the PKCS #11 key
149 * derivation function (a hash name, optionally with ",Cofactor") rather
150 * than a Botan KDF; see MechanismWrapper::create_ecdh_mechanism
151 *
152 * The raw agreed value is requested via with_raw_shared_key as for any
153 * other key, so "Raw" alone is rejected here. The only exception is the
154 * cofactor variant with raw output ("Raw,Cofactor"), which the options
155 * cannot otherwise express.
156 *
157 * TODO(Botan4) remove the cofactor variant along with the rest
158 */
159 const std::string params = [&]() -> std::string {
160 if(options.using_kdf()) {
161 const std::string& kdf = options.kdf().value();
162 if(kdf == "Raw") {
163 throw Invalid_Argument("PKCS#11 ECDH does not accept Raw as a KDF; request the raw shared key instead");
164 }
165 return kdf;
166 }
167 if(options.using_raw_shared_key()) {
168 return "Raw";
169 }
170 throw Invalid_Argument(
171 "Key agreement does not produce a uniform shared key, so a KDF must be specified (or the raw shared key "
172 "explicitly requested)");
173 }();
174 return std::make_unique<PKCS11_ECDH_KA_Operation>(*this, params);
175}
176
177PKCS11_ECDH_KeyPair generate_ecdh_keypair(Session& session,
178 const EC_PublicKeyGenerationProperties& pub_props,
179 const EC_PrivateKeyGenerationProperties& priv_props) {
180 ObjectHandle pub_key_handle = 0;
181 ObjectHandle priv_key_handle = 0;
182
183 const Mechanism mechanism = {static_cast<CK_MECHANISM_TYPE>(MechanismType::EcKeyPairGen), nullptr, 0};
184
185 session.module()->C_GenerateKeyPair(session.handle(),
186 &mechanism,
187 pub_props.data(),
188 checked_ulong_cast(pub_props.count()),
189 priv_props.data(),
190 checked_ulong_cast(priv_props.count()),
191 &pub_key_handle,
192 &priv_key_handle);
193
194 Object_Creation_Guard guard(session, {pub_key_handle, priv_key_handle});
195 PKCS11_ECDH_PublicKey public_key(session, pub_key_handle); // NOLINT(*-const-correctness) clang-tidy bug
196 PKCS11_ECDH_PrivateKey private_key(session, priv_key_handle);
197 // The private key object does not include the public point. Rebind it to
198 // the private key's domain since unregistered explicit groups are decoded
199 // independently for the two token objects.
200 const EC_AffinePoint public_point(private_key.domain(), public_key.raw_public_key_bits());
201 private_key.set_public_point(public_point, private_key.point_encoding());
202 guard.release();
203 return std::make_pair(std::move(public_key), std::move(private_key));
204}
205
206} // namespace Botan::PKCS11
207
208#endif
static BigInt from_bytes(std::span< const uint8_t > bytes)
Definition bigint.cpp:84
Represents a PKCS#11 session.
Definition p11_types.h:139
Ulong checked_ulong_cast(size_t v)
Definition p11.h:1228
CK_MECHANISM Mechanism
Definition p11.h:1207
CK_OBJECT_HANDLE ObjectHandle
Definition p11.h:1214
void require_hardware_provider(const OptionsT &options, std::string_view algo_name, std::string_view provider_name)
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:128
CK_ULONG CK_OBJECT_CLASS
Definition pkcs11.h:63
CK_ULONG CK_KEY_TYPE
Definition pkcs11.h:55
CK_ULONG CK_MECHANISM_TYPE
Definition pkcs11.h:59