Coverage Report

Created: 2021-10-13 08:49

/src/botan/src/lib/pubkey/pbes2/pbes2.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* PKCS #5 PBES2
3
* (C) 1999-2008,2014,2021 Jack Lloyd
4
* (C) 2018 Ribose Inc
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8
9
#include <botan/internal/pbes2.h>
10
#include <botan/cipher_mode.h>
11
#include <botan/pwdhash.h>
12
#include <botan/der_enc.h>
13
#include <botan/ber_dec.h>
14
#include <botan/internal/parsing.h>
15
#include <botan/asn1_obj.h>
16
#include <botan/oids.h>
17
#include <botan/rng.h>
18
19
namespace Botan {
20
21
namespace {
22
23
bool known_pbes_cipher_mode(const std::string& mode)
24
0
   {
25
0
   return (mode == "CBC" || mode == "GCM" || mode == "SIV");
26
0
   }
27
28
secure_vector<uint8_t> derive_key(const std::string& passphrase,
29
                                  const AlgorithmIdentifier& kdf_algo,
30
                                  size_t default_key_size)
31
0
   {
32
0
   if(kdf_algo.get_oid() == OID::from_string("PKCS5.PBKDF2"))
33
0
      {
34
0
      secure_vector<uint8_t> salt;
35
0
      size_t iterations = 0, key_length = 0;
36
37
0
      AlgorithmIdentifier prf_algo;
38
0
      BER_Decoder(kdf_algo.get_parameters())
39
0
         .start_sequence()
40
0
         .decode(salt, ASN1_Type::OctetString)
41
0
         .decode(iterations)
42
0
         .decode_optional(key_length, ASN1_Type::Integer, ASN1_Class::Universal)
43
0
         .decode_optional(prf_algo, ASN1_Type::Sequence, ASN1_Class::Constructed,
44
0
                          AlgorithmIdentifier("HMAC(SHA-160)",
45
0
                                              AlgorithmIdentifier::USE_NULL_PARAM))
46
0
         .end_cons();
47
48
0
      if(salt.size() < 8)
49
0
         throw Decoding_Error("PBE-PKCS5 v2.0: Encoded salt is too small");
50
51
0
      if(key_length == 0)
52
0
         key_length = default_key_size;
53
54
0
      const std::string prf = OIDS::oid2str_or_throw(prf_algo.get_oid());
55
0
      auto pbkdf_fam = PasswordHashFamily::create_or_throw("PBKDF2(" + prf + ")");
56
0
      auto pbkdf = pbkdf_fam->from_params(iterations);
57
58
0
      secure_vector<uint8_t> derived_key(key_length);
59
0
      pbkdf->derive_key(derived_key.data(), derived_key.size(),
60
0
                        passphrase.data(), passphrase.size(),
61
0
                        salt.data(), salt.size());
62
0
      return derived_key;
63
0
      }
64
0
   else if(kdf_algo.get_oid() == OID::from_string("Scrypt"))
65
0
      {
66
0
      secure_vector<uint8_t> salt;
67
0
      size_t N = 0, r = 0, p = 0;
68
0
      size_t key_length = 0;
69
70
0
      AlgorithmIdentifier prf_algo;
71
0
      BER_Decoder(kdf_algo.get_parameters())
72
0
         .start_sequence()
73
0
         .decode(salt, ASN1_Type::OctetString)
74
0
         .decode(N)
75
0
         .decode(r)
76
0
         .decode(p)
77
0
         .decode_optional(key_length, ASN1_Type::Integer, ASN1_Class::Universal)
78
0
         .end_cons();
79
80
0
      if(key_length == 0)
81
0
         key_length = default_key_size;
82
83
0
      secure_vector<uint8_t> derived_key(key_length);
84
85
0
      auto pwdhash_fam = PasswordHashFamily::create_or_throw("Scrypt");
86
0
      auto pwdhash = pwdhash_fam->from_params(N, r, p);
87
0
      pwdhash->derive_key(derived_key.data(), derived_key.size(),
88
0
                          passphrase.data(), passphrase.size(),
89
0
                          salt.data(), salt.size());
90
91
0
      return derived_key;
92
0
      }
93
0
   else
94
0
      throw Decoding_Error("PBE-PKCS5 v2.0: Unknown KDF algorithm " +
95
0
                           kdf_algo.get_oid().to_string());
96
0
   }
97
98
secure_vector<uint8_t> derive_key(const std::string& passphrase,
99
                                  const std::string& digest,
100
                                  RandomNumberGenerator& rng,
101
                                  size_t* msec_in_iterations_out,
102
                                  size_t iterations_if_msec_null,
103
                                  size_t key_length,
104
                                  AlgorithmIdentifier& kdf_algo)
105
0
   {
106
0
   const secure_vector<uint8_t> salt = rng.random_vec(12);
107
108
0
   if(digest == "Scrypt")
109
0
      {
110
0
      auto pwhash_fam = PasswordHashFamily::create_or_throw("Scrypt");
111
112
0
      std::unique_ptr<PasswordHash> pwhash;
113
114
0
      if(msec_in_iterations_out)
115
0
         {
116
0
         const std::chrono::milliseconds msec(*msec_in_iterations_out);
117
0
         pwhash = pwhash_fam->tune(key_length, msec);
118
0
         }
119
0
      else
120
0
         {
121
0
         pwhash = pwhash_fam->from_iterations(iterations_if_msec_null);
122
0
         }
123
124
0
      secure_vector<uint8_t> key(key_length);
125
0
      pwhash->derive_key(key.data(), key.size(),
126
0
                         passphrase.c_str(), passphrase.size(),
127
0
                         salt.data(), salt.size());
128
129
0
      const size_t N = pwhash->memory_param();
130
0
      const size_t r = pwhash->iterations();
131
0
      const size_t p = pwhash->parallelism();
132
133
0
      if(msec_in_iterations_out)
134
0
         *msec_in_iterations_out = 0;
135
136
0
      std::vector<uint8_t> scrypt_params;
137
0
      DER_Encoder(scrypt_params)
138
0
         .start_sequence()
139
0
            .encode(salt, ASN1_Type::OctetString)
140
0
            .encode(N)
141
0
            .encode(r)
142
0
            .encode(p)
143
0
            .encode(key_length)
144
0
         .end_cons();
145
146
0
      kdf_algo = AlgorithmIdentifier(OID::from_string("Scrypt"), scrypt_params);
147
0
      return key;
148
0
      }
149
0
   else
150
0
      {
151
0
      const std::string prf = "HMAC(" + digest + ")";
152
0
      const std::string pbkdf_name = "PBKDF2(" + prf + ")";
153
154
0
      std::unique_ptr<PasswordHashFamily> pwhash_fam = PasswordHashFamily::create(pbkdf_name);
155
0
      if(!pwhash_fam)
156
0
         throw Invalid_Argument("Unknown password hash digest " + digest);
157
158
0
      std::unique_ptr<PasswordHash> pwhash;
159
160
0
      if(msec_in_iterations_out)
161
0
         {
162
0
         const std::chrono::milliseconds msec(*msec_in_iterations_out);
163
0
         pwhash = pwhash_fam->tune(key_length, msec);
164
0
         }
165
0
      else
166
0
         {
167
0
         pwhash = pwhash_fam->from_iterations(iterations_if_msec_null);
168
0
         }
169
170
0
      secure_vector<uint8_t> key(key_length);
171
0
      pwhash->derive_key(key.data(), key.size(),
172
0
                         passphrase.c_str(), passphrase.size(),
173
0
                         salt.data(), salt.size());
174
175
0
      std::vector<uint8_t> pbkdf2_params;
176
177
0
      const size_t iterations = pwhash->iterations();
178
179
0
      if(msec_in_iterations_out)
180
0
         *msec_in_iterations_out = iterations;
181
182
0
      DER_Encoder(pbkdf2_params)
183
0
         .start_sequence()
184
0
            .encode(salt, ASN1_Type::OctetString)
185
0
            .encode(iterations)
186
0
            .encode(key_length)
187
0
            .encode_if(prf != "HMAC(SHA-160)",
188
0
                       AlgorithmIdentifier(prf, AlgorithmIdentifier::USE_NULL_PARAM))
189
0
         .end_cons();
190
191
0
      kdf_algo = AlgorithmIdentifier("PKCS5.PBKDF2", pbkdf2_params);
192
0
      return key;
193
0
      }
194
0
   }
195
196
/*
197
* PKCS#5 v2.0 PBE Encryption
198
*/
199
std::pair<AlgorithmIdentifier, std::vector<uint8_t>>
200
pbes2_encrypt_shared(const secure_vector<uint8_t>& key_bits,
201
                     const std::string& passphrase,
202
                     size_t* msec_in_iterations_out,
203
                     size_t iterations_if_msec_null,
204
                     const std::string& cipher,
205
                     const std::string& prf,
206
                     RandomNumberGenerator& rng)
207
0
   {
208
0
   const std::vector<std::string> cipher_spec = split_on(cipher, '/');
209
0
   if(cipher_spec.size() != 2)
210
0
      throw Encoding_Error("PBE-PKCS5 v2.0: Invalid cipher spec " + cipher);
211
212
0
   if(!known_pbes_cipher_mode(cipher_spec[1]))
213
0
      throw Encoding_Error("PBE-PKCS5 v2.0: Don't know param format for " + cipher);
214
215
0
   const OID cipher_oid = OIDS::str2oid_or_empty(cipher);
216
0
   if(cipher_oid.empty())
217
0
      throw Encoding_Error("PBE-PKCS5 v2.0: No OID assigned for " + cipher);
218
219
0
   std::unique_ptr<Cipher_Mode> enc = Cipher_Mode::create(cipher, ENCRYPTION);
220
221
0
   if(!enc)
222
0
      throw Decoding_Error("PBE-PKCS5 cannot encrypt no cipher " + cipher);
223
224
0
   const size_t key_length = enc->key_spec().maximum_keylength();
225
226
0
   const secure_vector<uint8_t> iv = rng.random_vec(enc->default_nonce_length());
227
228
0
   AlgorithmIdentifier kdf_algo;
229
230
0
   const secure_vector<uint8_t> derived_key =
231
0
      derive_key(passphrase, prf, rng,
232
0
                 msec_in_iterations_out, iterations_if_msec_null,
233
0
                 key_length, kdf_algo);
234
235
0
   enc->set_key(derived_key);
236
0
   enc->start(iv);
237
0
   secure_vector<uint8_t> ctext = key_bits;
238
0
   enc->finish(ctext);
239
240
0
   std::vector<uint8_t> encoded_iv;
241
0
   DER_Encoder(encoded_iv).encode(iv, ASN1_Type::OctetString);
242
243
0
   std::vector<uint8_t> pbes2_params;
244
0
   DER_Encoder(pbes2_params)
245
0
      .start_sequence()
246
0
      .encode(kdf_algo)
247
0
      .encode(AlgorithmIdentifier(cipher, encoded_iv))
248
0
      .end_cons();
249
250
0
   AlgorithmIdentifier id(OID::from_string("PBE-PKCS5v20"), pbes2_params);
251
252
0
   return std::make_pair(id, unlock(ctext));
253
0
   }
254
255
}
256
257
std::pair<AlgorithmIdentifier, std::vector<uint8_t>>
258
pbes2_encrypt(const secure_vector<uint8_t>& key_bits,
259
              const std::string& passphrase,
260
              std::chrono::milliseconds msec,
261
              const std::string& cipher,
262
              const std::string& digest,
263
              RandomNumberGenerator& rng)
264
0
   {
265
0
   size_t msec_in_iterations_out = static_cast<size_t>(msec.count());
266
0
   return pbes2_encrypt_shared(key_bits, passphrase, &msec_in_iterations_out, 0, cipher, digest, rng);
267
   // return value msec_in_iterations_out discarded
268
0
   }
269
270
std::pair<AlgorithmIdentifier, std::vector<uint8_t>>
271
pbes2_encrypt_msec(const secure_vector<uint8_t>& key_bits,
272
                   const std::string& passphrase,
273
                   std::chrono::milliseconds msec,
274
                   size_t* out_iterations_if_nonnull,
275
                   const std::string& cipher,
276
                   const std::string& digest,
277
                   RandomNumberGenerator& rng)
278
0
   {
279
0
   size_t msec_in_iterations_out = static_cast<size_t>(msec.count());
280
281
0
   auto ret = pbes2_encrypt_shared(key_bits, passphrase, &msec_in_iterations_out, 0, cipher, digest, rng);
282
283
0
   if(out_iterations_if_nonnull)
284
0
      *out_iterations_if_nonnull = msec_in_iterations_out;
285
286
0
   return ret;
287
0
   }
288
289
std::pair<AlgorithmIdentifier, std::vector<uint8_t>>
290
pbes2_encrypt_iter(const secure_vector<uint8_t>& key_bits,
291
                   const std::string& passphrase,
292
                   size_t pbkdf_iter,
293
                   const std::string& cipher,
294
                   const std::string& digest,
295
                   RandomNumberGenerator& rng)
296
0
   {
297
0
   return pbes2_encrypt_shared(key_bits, passphrase, nullptr, pbkdf_iter, cipher, digest, rng);
298
0
   }
299
300
secure_vector<uint8_t>
301
pbes2_decrypt(const secure_vector<uint8_t>& key_bits,
302
              const std::string& passphrase,
303
              const std::vector<uint8_t>& params)
304
0
   {
305
0
   AlgorithmIdentifier kdf_algo, enc_algo;
306
307
0
   BER_Decoder(params)
308
0
      .start_sequence()
309
0
         .decode(kdf_algo)
310
0
         .decode(enc_algo)
311
0
      .end_cons();
312
313
0
   const std::string cipher = OIDS::oid2str_or_throw(enc_algo.get_oid());
314
0
   const std::vector<std::string> cipher_spec = split_on(cipher, '/');
315
0
   if(cipher_spec.size() != 2)
316
0
      throw Decoding_Error("PBE-PKCS5 v2.0: Invalid cipher spec " + cipher);
317
0
   if(!known_pbes_cipher_mode(cipher_spec[1]))
318
0
      throw Decoding_Error("PBE-PKCS5 v2.0: Don't know param format for " + cipher);
319
320
0
   secure_vector<uint8_t> iv;
321
0
   BER_Decoder(enc_algo.get_parameters()).decode(iv, ASN1_Type::OctetString).verify_end();
322
323
0
   std::unique_ptr<Cipher_Mode> dec = Cipher_Mode::create(cipher, DECRYPTION);
324
0
   if(!dec)
325
0
      throw Decoding_Error("PBE-PKCS5 cannot decrypt no cipher " + cipher);
326
327
0
   dec->set_key(derive_key(passphrase, kdf_algo, dec->key_spec().maximum_keylength()));
328
329
0
   dec->start(iv);
330
331
0
   secure_vector<uint8_t> buf = key_bits;
332
0
   dec->finish(buf);
333
334
0
   return buf;
335
0
   }
336
337
}