Debian Codegraph @

src/lib/crypto/BotanSymmetricAlgorithm.cpp

raw
1 /*
2 * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
20 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
22 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
24 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 // TODO: Store context in securely allocated memory
28
29 /*****************************************************************************
30 BotanSymmetricAlgorithm.cpp
31
32 Botan symmetric algorithm implementation
33 *****************************************************************************/
34
35 #include "config.h"
36 #include "BotanSymmetricAlgorithm.h"
37 #include "BotanUtil.h"
38 #include "salloc.h"
39 #include <iostream>
40
41 #include <botan/symkey.h>
42 #include <botan/parsing.h>
43 #include <botan/version.h>
44 #include <botan/filters.h>
45 #include <botan/aead.h>
46
47 #include "Botan_ecb.h"
48
49 #if BOTAN_VERSION_CODE <= BOTAN_VERSION_CODE_FOR(2,11,0)
50 #include <botan/cipher_filter.h>
51 #endif
52
53 std::vector<std::string> split_on_delim(const std::string& str, char delim)
54 {
55 std::vector<std::string> elems;
56 if(str.empty()) return elems;
57
58 std::string substr;
59 for (auto i = str.begin(); i != str.end(); ++i)
60 {
61 if (*i == delim)
62 {
63 if (!substr.empty())
64 elems.push_back(substr);
65 substr.clear();
66 }
67 else
68 substr += *i;
69 }
70
71 if (!substr.empty())
72 elems.push_back(substr);
73
74 return elems;
75 }
76
77
78 // Constructor
79 BotanSymmetricAlgorithm::BotanSymmetricAlgorithm()
80 {
81 cryption = NULL;
82 maximumBytes = Botan::BigInt(1);
83 maximumBytes.flip_sign();
84 counterBytes = Botan::BigInt(0);
85 }
86
87 // Destructor
88 BotanSymmetricAlgorithm::~BotanSymmetricAlgorithm()
89 {
90 delete cryption;
91 cryption = NULL;
92 }
93
94 // Encryption functions
95 bool BotanSymmetricAlgorithm::encryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode:CBC */, const ByteString& IV /* = ByteString()*/, bool padding /* = true */, size_t counterBits /* = 0 */, const ByteString& aad /* = ByteString() */, size_t tagBytes /* = 0 */)
96 {
97 // Call the superclass initialiser
98 if (!SymmetricAlgorithm::encryptInit(key, mode, IV, padding, counterBits, aad, tagBytes))
99 {
100 return false;
101 }
102
103 // Check the IV
104 if (mode != SymMode::GCM && (IV.size() > 0) && (IV.size() != getBlockSize()))
105 {
106 ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize());
107
108 ByteString dummy;
109 SymmetricAlgorithm::encryptFinal(dummy);
110
111 return false;
112 }
113
114 ByteString iv;
115
116 if (IV.size() > 0)
117 {
118 iv = IV;
119 }
120 else
121 {
122 iv.wipe(getBlockSize());
123 }
124
125 // Check the counter bits
126 if (counterBits > 0)
127 {
128 Botan::BigInt counter = BotanUtil::byteString2bigInt(iv);
129 counter.mask_bits(counterBits);
130
131 // Reverse the bits
132 while (counterBits > 0)
133 {
134 counterBits--;
135 if (counter.get_bit(counterBits))
136 {
137 counter.clear_bit(counterBits);
138 }
139 else
140 {
141 counter.set_bit(counterBits);
142 }
143 }
144
145 // Set the maximum bytes
146 maximumBytes = (counter + 1) * getBlockSize();
147 counterBytes = Botan::BigInt(0);
148 }
149 else
150 {
151 maximumBytes = Botan::BigInt(1);
152 maximumBytes.flip_sign();
153 }
154
155 // Determine the cipher
156 std::string cipherName = getCipher();
157
158 if (cipherName == "")
159 {
160 ERROR_MSG("Invalid encryption cipher");
161
162 ByteString dummy;
163 SymmetricAlgorithm::encryptFinal(dummy);
164
165 return false;
166 }
167
168 // Allocate the context
169 try
170 {
171 Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size());
172 if (mode == SymMode::ECB)
173 {
174 // ECB cipher mode was dropped in Botan 2.0
175 const std::vector<std::string> algo_parts = split_on_delim(cipherName, '/');
176 const std::string cipher_name = algo_parts[0];
177 bool with_pkcs7_padding;
178 if (algo_parts.size() == 3 && algo_parts[2] == "PKCS7")
179 {
180 with_pkcs7_padding = true;
181 }
182 else
183 {
184 with_pkcs7_padding = false;
185 }
186 std::unique_ptr<Botan::BlockCipher> bc(Botan::BlockCipher::create(cipher_name));
187 Botan::Keyed_Filter* cipher = new Botan::Cipher_Mode_Filter(new Botan::ECB_Encryption(bc.release(), with_pkcs7_padding));
188 cipher->set_key(botanKey);
189 cryption = new Botan::Pipe(cipher);
190 }
191 else if (mode == SymMode::GCM)
192 {
193 Botan::AEAD_Mode* aead = Botan::get_aead(cipherName, Botan::ENCRYPTION);
194 aead->set_key(botanKey);
195 aead->set_associated_data(aad.const_byte_str(), aad.size());
196
197 Botan::InitializationVector botanIV = Botan::InitializationVector(IV.const_byte_str(), IV.size());
198 Botan::Keyed_Filter* filter = new Botan::Cipher_Mode_Filter(aead);
199 filter->set_iv(botanIV);
200 cryption = new Botan::Pipe(filter);
201 }
202 else
203 {
204 Botan::InitializationVector botanIV = Botan::InitializationVector(IV.const_byte_str(), IV.size());
205 cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, botanIV, Botan::ENCRYPTION));
206 }
207 cryption->start_msg();
208 }
209 catch (std::exception &e)
210 {
211 ERROR_MSG("Failed to create the encryption token: %s", e.what());
212
213 ByteString dummy;
214 SymmetricAlgorithm::encryptFinal(dummy);
215
216 delete cryption;
217 cryption = NULL;
218
219 return false;
220 }
221
222 return true;
223 }
224
225 bool BotanSymmetricAlgorithm::encryptUpdate(const ByteString& data, ByteString& encryptedData)
226 {
227 if (!SymmetricAlgorithm::encryptUpdate(data, encryptedData))
228 {
229 delete cryption;
230 cryption = NULL;
231
232 return false;
233 }
234
235 // Write data
236 try
237 {
238 if (data.size() > 0)
239 cryption->write(data.const_byte_str(), data.size());
240 }
241 catch (...)
242 {
243 ERROR_MSG("Failed to write to the encryption token");
244
245 ByteString dummy;
246 SymmetricAlgorithm::encryptFinal(dummy);
247
248 delete cryption;
249 cryption = NULL;
250
251 return false;
252 }
253
254 // Count number of bytes written
255 if (maximumBytes.is_positive())
256 {
257 counterBytes += data.size();
258 }
259
260 // Read data
261 int bytesRead = 0;
262 try
263 {
264 size_t outLen = cryption->remaining();
265 encryptedData.resize(outLen);
266 if (outLen > 0)
267 bytesRead = cryption->read(&encryptedData[0], outLen);
268 }
269 catch (...)
270 {
271 ERROR_MSG("Failed to encrypt the data");
272
273 ByteString dummy;
274 SymmetricAlgorithm::encryptFinal(dummy);
275
276 delete cryption;
277 cryption = NULL;
278
279 return false;
280 }
281
282 // Resize the output block
283 encryptedData.resize(bytesRead);
284 currentBufferSize -= bytesRead;
285
286 return true;
287 }
288
289 bool BotanSymmetricAlgorithm::encryptFinal(ByteString& encryptedData)
290 {
291 if (!SymmetricAlgorithm::encryptFinal(encryptedData))
292 {
293 delete cryption;
294 cryption = NULL;
295
296 return false;
297 }
298
299 // Read data
300 int bytesRead = 0;
301 try
302 {
303 cryption->end_msg();
304 size_t outLen = cryption->remaining();
305 encryptedData.resize(outLen);
306 if (outLen > 0)
307 bytesRead = cryption->read(&encryptedData[0], outLen);
308 }
309 catch (...)
310 {
311 ERROR_MSG("Failed to encrypt the data");
312
313 delete cryption;
314 cryption = NULL;
315
316 return false;
317 }
318
319 // Clean up
320 delete cryption;
321 cryption = NULL;
322
323 // Resize the output block
324 encryptedData.resize(bytesRead);
325
326 return true;
327 }
328
329 // Decryption functions
330 bool BotanSymmetricAlgorithm::decryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode::CBC */, const ByteString& IV /* = ByteString() */, bool padding /* = true */, size_t counterBits /* = 0 */, const ByteString& aad /* = ByteString() */, size_t tagBytes /* = 0 */)
331 {
332 // Call the superclass initialiser
333 if (!SymmetricAlgorithm::decryptInit(key, mode, IV, padding, counterBits, aad, tagBytes))
334 {
335 return false;
336 }
337
338 // Check the IV
339 if (mode != SymMode::GCM && (IV.size() > 0) && (IV.size() != getBlockSize()))
340 {
341 ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize());
342
343 ByteString dummy;
344 SymmetricAlgorithm::decryptFinal(dummy);
345
346 return false;
347 }
348
349 ByteString iv;
350
351 if (IV.size() > 0)
352 {
353 iv = IV;
354 }
355 else
356 {
357 iv.wipe(getBlockSize());
358 }
359
360 // Check the counter bits
361 if (counterBits > 0)
362 {
363 Botan::BigInt counter = BotanUtil::byteString2bigInt(iv);
364 counter.mask_bits(counterBits);
365
366 // Reverse the bits
367 while (counterBits > 0)
368 {
369 counterBits--;
370 if (counter.get_bit(counterBits))
371 {
372 counter.clear_bit(counterBits);
373 }
374 else
375 {
376 counter.set_bit(counterBits);
377 }
378 }
379
380 // Set the maximum bytes
381 maximumBytes = (counter + 1) * getBlockSize();
382 counterBytes = Botan::BigInt(0);
383 }
384 else
385 {
386 maximumBytes = Botan::BigInt(1);
387 maximumBytes.flip_sign();
388 }
389
390 // Determine the cipher class
391 std::string cipherName = getCipher();
392
393 if (cipherName == "")
394 {
395 ERROR_MSG("Invalid decryption cipher");
396
397 ByteString dummy;
398 SymmetricAlgorithm::decryptFinal(dummy);
399
400 return false;
401 }
402
403 // Allocate the context
404 try
405 {
406 Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size());
407 if (mode == SymMode::ECB)
408 {
409 // ECB cipher mode was dropped in Botan 2.0
410 const std::vector<std::string> algo_parts = split_on_delim(cipherName, '/');
411 const std::string cipher_name = algo_parts[0];
412 bool with_pkcs7_padding;
413 if (algo_parts.size() == 3 && algo_parts[2] == "PKCS7")
414 {
415 with_pkcs7_padding = true;
416 }
417 else
418 {
419 with_pkcs7_padding = false;
420 }
421 std::unique_ptr<Botan::BlockCipher> bc(Botan::BlockCipher::create(cipher_name));
422 Botan::Keyed_Filter* cipher = new Botan::Cipher_Mode_Filter(new Botan::ECB_Decryption(bc.release(),with_pkcs7_padding));
423 cipher->set_key(botanKey);
424 cryption = new Botan::Pipe(cipher);
425 }
426 else if (mode == SymMode::GCM)
427 {
428 Botan::AEAD_Mode* aead = Botan::get_aead(cipherName, Botan::DECRYPTION);
429 aead->set_key(botanKey);
430 aead->set_associated_data(aad.const_byte_str(), aad.size());
431
432 Botan::InitializationVector botanIV = Botan::InitializationVector(IV.const_byte_str(), IV.size());
433 Botan::Keyed_Filter* filter = new Botan::Cipher_Mode_Filter(aead);
434 filter->set_iv(botanIV);
435 cryption = new Botan::Pipe(filter);
436 }
437 else
438 {
439 Botan::InitializationVector botanIV = Botan::InitializationVector(IV.const_byte_str(), IV.size());
440 cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, botanIV, Botan::DECRYPTION));
441 }
442 cryption->start_msg();
443 }
444 catch (...)
445 {
446 ERROR_MSG("Failed to create the decryption token");
447
448 ByteString dummy;
449 SymmetricAlgorithm::decryptFinal(dummy);
450
451 delete cryption;
452 cryption = NULL;
453
454 return false;
455 }
456
457 return true;
458 }
459
460 bool BotanSymmetricAlgorithm::decryptUpdate(const ByteString& encryptedData, ByteString& data)
461 {
462 if (!SymmetricAlgorithm::decryptUpdate(encryptedData, data))
463 {
464 delete cryption;
465 cryption = NULL;
466
467 return false;
468 }
469
470 // AEAD ciphers should not return decrypted data until final is called
471 if (currentCipherMode == SymMode::GCM)
472 {
473 data.resize(0);
474 return true;
475 }
476
477 // Write data
478 try
479 {
480 if (encryptedData.size() > 0)
481 cryption->write(encryptedData.const_byte_str(), encryptedData.size());
482 }
483 catch (...)
484 {
485 ERROR_MSG("Failed to write to the decryption token");
486
487 ByteString dummy;
488 SymmetricAlgorithm::decryptFinal(dummy);
489
490 delete cryption;
491 cryption = NULL;
492
493 return false;
494 }
495
496 // Count number of bytes written
497 if (maximumBytes.is_positive())
498 {
499 counterBytes += encryptedData.size();
500 }
501
502 // Read data
503 int bytesRead = 0;
504 try
505 {
506 size_t outLen = cryption->remaining();
507 data.resize(outLen);
508 if (outLen > 0)
509 bytesRead = cryption->read(&data[0], outLen);
510 }
511 catch (...)
512 {
513 ERROR_MSG("Failed to decrypt the data");
514
515 ByteString dummy;
516 SymmetricAlgorithm::decryptFinal(dummy);
517
518 delete cryption;
519 cryption = NULL;
520
521 return false;
522 }
523
524 // Resize the output block
525 data.resize(bytesRead);
526 currentBufferSize -= bytesRead;
527
528 return true;
529 }
530
531 bool BotanSymmetricAlgorithm::decryptFinal(ByteString& data)
532 {
533 SymMode::Type mode = currentCipherMode;
534 ByteString aeadBuffer = currentAEADBuffer;
535
536 if (!SymmetricAlgorithm::decryptFinal(data))
537 {
538 delete cryption;
539 cryption = NULL;
540
541 return false;
542 }
543
544 if (mode == SymMode::GCM)
545 {
546 // Write data
547 try
548 {
549 if (aeadBuffer.size() > 0)
550 cryption->write(aeadBuffer.const_byte_str(), aeadBuffer.size());
551 }
552 catch (...)
553 {
554 ERROR_MSG("Failed to write to the decryption token");
555
556 delete cryption;
557 cryption = NULL;
558
559 return false;
560 }
561 }
562
563 // Read data
564 int bytesRead = 0;
565 try
566 {
567 cryption->end_msg();
568 size_t outLen = cryption->remaining();
569 data.resize(outLen);
570 if (outLen > 0)
571 bytesRead = cryption->read(&data[0], outLen);
572 }
573 catch (std::exception &e)
574 {
575 ERROR_MSG("Failed to decrypt the data: %s", e.what());
576
577 delete cryption;
578 cryption = NULL;
579
580 return false;
581 }
582
583 // Clean up
584 delete cryption;
585 cryption = NULL;
586
587 // Resize the output block
588 data.resize(bytesRead);
589
590 return true;
591 }
592
593 // Check if more bytes of data can be encrypted
594 bool BotanSymmetricAlgorithm::checkMaximumBytes(unsigned long bytes)
595 {
596 if (maximumBytes.is_negative()) return true;
597
598 if (maximumBytes.cmp(counterBytes + bytes) >= 0) return true;
599
600 return false;
601 }