Debian Codegraph @

src/lib/crypto/OSSLEVPSymmetricAlgorithm.cpp

raw
1 /*
2 * Copyright (c) 2010 SURFnet bv
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 EVP context in securely allocated memory
28
29 /*****************************************************************************
30 OSSLEVPSymmetricAlgorithm.cpp
31
32 OpenSSL symmetric algorithm implementation
33 *****************************************************************************/
34
35 #include "config.h"
36 #include "OSSLEVPSymmetricAlgorithm.h"
37 #include "OSSLUtil.h"
38 #include "salloc.h"
39 #include <openssl/err.h>
40
41 // Constructor
42 OSSLEVPSymmetricAlgorithm::OSSLEVPSymmetricAlgorithm()
43 {
44 pCurCTX = NULL;
45 maximumBytes = NULL;
46 counterBytes = NULL;
47 }
48
49 // Destructor
50 OSSLEVPSymmetricAlgorithm::~OSSLEVPSymmetricAlgorithm()
51 {
52 /* In case of custom allocator from BIND, even NULL pointer might crash
53 * the library if freed after deinitialization. Do not rely on null handling
54 * as a workaround. */
55 if (pCurCTX)
56 EVP_CIPHER_CTX_free(pCurCTX);
57 if (maximumBytes)
58 BN_free(maximumBytes);
59 if (counterBytes)
60 BN_free(counterBytes);
61 }
62
63 void OSSLEVPSymmetricAlgorithm::counterBitsInit(const ByteString& iv, size_t counterBits)
64 {
65 BN_free(maximumBytes);
66 maximumBytes = NULL;
67 BN_free(counterBytes);
68 counterBytes = NULL;
69
70 // Check the counter bits
71 if (counterBits > 0)
72 {
73 BIGNUM* counter = OSSL::byteString2bn(iv);
74 BN_mask_bits(counter, counterBits);
75
76 // Reverse the bits
77 while (counterBits > 0)
78 {
79 counterBits--;
80 if (BN_is_bit_set(counter, counterBits))
81 {
82 BN_clear_bit(counter, counterBits);
83 }
84 else
85 {
86 BN_set_bit(counter, counterBits);
87 }
88 }
89
90 // Set the maximum bytes
91 BN_add_word(counter, 1);
92 BN_mul_word(counter, getBlockSize());
93 maximumBytes = counter;
94 counterBytes = BN_new();
95 BN_zero(counterBytes);
96 }
97 }
98
99 void OSSLEVPSymmetricAlgorithm::clean()
100 {
101 EVP_CIPHER_CTX_free(pCurCTX);
102 pCurCTX = NULL;
103 BN_free(maximumBytes);
104 maximumBytes = NULL;
105 BN_free(counterBytes);
106 counterBytes = NULL;
107 }
108
109 // Encryption functions
110 bool OSSLEVPSymmetricAlgorithm::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 */)
111 {
112 // Call the superclass initialiser
113 if (!SymmetricAlgorithm::encryptInit(key, mode, IV, padding, counterBits, aad, tagBytes))
114 {
115 return false;
116 }
117
118 // Check the IV
119 if (mode != SymMode::GCM && (IV.size() > 0) && (IV.size() != getBlockSize()))
120 {
121 ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize());
122
123 ByteString dummy;
124 SymmetricAlgorithm::encryptFinal(dummy);
125
126 return false;
127 }
128
129 ByteString iv;
130
131 if (IV.size() > 0)
132 {
133 iv = IV;
134 }
135 else
136 {
137 iv.wipe(getBlockSize());
138 }
139
140 counterBitsInit(iv, counterBits);
141
142 // Determine the cipher class
143 const EVP_CIPHER* cipher = getCipher();
144
145 if (cipher == NULL)
146 {
147 ERROR_MSG("Failed to initialise EVP encrypt operation");
148
149 ByteString dummy;
150 SymmetricAlgorithm::encryptFinal(dummy);
151
152 return false;
153 }
154
155 // Allocate the EVP context
156 pCurCTX = EVP_CIPHER_CTX_new();
157
158 if (pCurCTX == NULL)
159 {
160 ERROR_MSG("Failed to allocate space for EVP_CIPHER_CTX");
161
162 ByteString dummy;
163 SymmetricAlgorithm::encryptFinal(dummy);
164
165 return false;
166 }
167
168 int rv;
169 if (mode == SymMode::GCM)
170 {
171 rv = EVP_EncryptInit_ex(pCurCTX, cipher, NULL, NULL, NULL);
172
173 if (rv)
174 {
175 EVP_CIPHER_CTX_ctrl(pCurCTX, EVP_CTRL_GCM_SET_IVLEN, iv.size(), NULL);
176 rv = EVP_EncryptInit_ex(pCurCTX, NULL, NULL, (unsigned char*) currentKey->getKeyBits().const_byte_str(), iv.byte_str());
177 }
178 }
179 else
180 {
181 rv = EVP_EncryptInit(pCurCTX, cipher, (unsigned char*) currentKey->getKeyBits().const_byte_str(), iv.byte_str());
182 }
183
184 if (!rv)
185 {
186 ERROR_MSG("Failed to initialise EVP encrypt operation: %s", ERR_error_string(ERR_get_error(), NULL));
187
188 clean();
189
190 ByteString dummy;
191 SymmetricAlgorithm::encryptFinal(dummy);
192
193 return false;
194 }
195
196 EVP_CIPHER_CTX_set_padding(pCurCTX, padding ? 1 : 0);
197
198 if (mode == SymMode::GCM)
199 {
200 int outLen = 0;
201 if (aad.size() && !EVP_EncryptUpdate(pCurCTX, NULL, &outLen, (unsigned char*) aad.const_byte_str(), aad.size()))
202 {
203 ERROR_MSG("Failed to update with AAD: %s", ERR_error_string(ERR_get_error(), NULL));
204
205 clean();
206
207 ByteString dummy;
208 SymmetricAlgorithm::encryptFinal(dummy);
209
210 return false;
211 }
212 }
213
214 return true;
215 }
216
217 bool OSSLEVPSymmetricAlgorithm::encryptUpdate(const ByteString& data, ByteString& encryptedData)
218 {
219 if (!SymmetricAlgorithm::encryptUpdate(data, encryptedData))
220 {
221 clean();
222 return false;
223 }
224
225 if (data.size() == 0)
226 {
227 encryptedData.resize(0);
228
229 return true;
230 }
231
232 // Count number of bytes written
233 if (maximumBytes)
234 {
235 BN_add_word(counterBytes, data.size());
236 }
237
238 // Prepare the output block
239 encryptedData.resize(data.size() + getBlockSize() - 1);
240
241 int outLen = encryptedData.size();
242 if (!EVP_EncryptUpdate(pCurCTX, &encryptedData[0], &outLen, (unsigned char*) data.const_byte_str(), data.size()))
243 {
244 ERROR_MSG("EVP_EncryptUpdate failed: %s", ERR_error_string(ERR_get_error(), NULL));
245
246 clean();
247
248 ByteString dummy;
249 SymmetricAlgorithm::encryptFinal(dummy);
250
251 return false;
252 }
253
254 // Resize the output block
255 encryptedData.resize(outLen);
256 currentBufferSize -= outLen;
257
258 return true;
259 }
260
261 bool OSSLEVPSymmetricAlgorithm::encryptFinal(ByteString& encryptedData)
262 {
263 SymMode::Type mode = currentCipherMode;
264 size_t tagBytes = currentTagBytes;
265
266 if (!SymmetricAlgorithm::encryptFinal(encryptedData))
267 {
268 clean();
269 return false;
270 }
271
272 // Prepare the output block
273 encryptedData.resize(getBlockSize());
274
275 int outLen = encryptedData.size();
276
277 if (!EVP_EncryptFinal(pCurCTX, &encryptedData[0], &outLen))
278 {
279 ERROR_MSG("EVP_EncryptFinal failed: %s", ERR_error_string(ERR_get_error(), NULL));
280
281 clean();
282
283 return false;
284 }
285
286 // Resize the output block
287 encryptedData.resize(outLen);
288
289 if (mode == SymMode::GCM)
290 {
291 ByteString tag;
292 tag.resize(tagBytes);
293 EVP_CIPHER_CTX_ctrl(pCurCTX, EVP_CTRL_GCM_GET_TAG, tagBytes, &tag[0]);
294 encryptedData += tag;
295 }
296
297 clean();
298
299 return true;
300 }
301
302 // Decryption functions
303 bool OSSLEVPSymmetricAlgorithm::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 */)
304 {
305 // Call the superclass initialiser
306 if (!SymmetricAlgorithm::decryptInit(key, mode, IV, padding, counterBits, aad, tagBytes))
307 {
308 return false;
309 }
310
311 // Check the IV
312 if (mode != SymMode::GCM && (IV.size() > 0) && (IV.size() != getBlockSize()))
313 {
314 ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize());
315
316 ByteString dummy;
317 SymmetricAlgorithm::decryptFinal(dummy);
318
319 return false;
320 }
321
322 ByteString iv;
323
324 if (IV.size() > 0)
325 {
326 iv = IV;
327 }
328 else
329 {
330 iv.wipe(getBlockSize());
331 }
332
333 counterBitsInit(iv, counterBits);
334
335 // Determine the cipher class
336 const EVP_CIPHER* cipher = getCipher();
337
338 if (cipher == NULL)
339 {
340 ERROR_MSG("Failed to initialise EVP decrypt operation");
341
342 ByteString dummy;
343 SymmetricAlgorithm::decryptFinal(dummy);
344
345 return false;
346 }
347
348 // Allocate the EVP context
349 pCurCTX = EVP_CIPHER_CTX_new();
350
351 if (pCurCTX == NULL)
352 {
353 ERROR_MSG("Failed to allocate space for EVP_CIPHER_CTX");
354
355 ByteString dummy;
356 SymmetricAlgorithm::decryptFinal(dummy);
357
358 return false;
359 }
360
361 int rv;
362 if (mode == SymMode::GCM)
363 {
364 rv = EVP_DecryptInit_ex(pCurCTX, cipher, NULL, NULL, NULL);
365
366 if (rv)
367 {
368 EVP_CIPHER_CTX_ctrl(pCurCTX, EVP_CTRL_GCM_SET_IVLEN, iv.size(), NULL);
369 rv = EVP_DecryptInit_ex(pCurCTX, NULL, NULL, (unsigned char*) currentKey->getKeyBits().const_byte_str(), iv.byte_str());
370 }
371 }
372 else
373 {
374 rv = EVP_DecryptInit(pCurCTX, cipher, (unsigned char*) currentKey->getKeyBits().const_byte_str(), iv.byte_str());
375 }
376
377 if (!rv)
378 {
379 ERROR_MSG("Failed to initialise EVP decrypt operation: %s", ERR_error_string(ERR_get_error(), NULL));
380
381 clean();
382
383 ByteString dummy;
384 SymmetricAlgorithm::decryptFinal(dummy);
385
386 return false;
387 }
388
389 EVP_CIPHER_CTX_set_padding(pCurCTX, padding ? 1 : 0);
390
391 if (mode == SymMode::GCM)
392 {
393 int outLen = 0;
394 if (aad.size() && !EVP_DecryptUpdate(pCurCTX, NULL, &outLen, (unsigned char*) aad.const_byte_str(), aad.size()))
395 {
396 ERROR_MSG("Failed to update with AAD: %s", ERR_error_string(ERR_get_error(), NULL));
397
398 clean();
399
400 ByteString dummy;
401 SymmetricAlgorithm::decryptFinal(dummy);
402
403 return false;
404 }
405 }
406
407 return true;
408 }
409
410 bool OSSLEVPSymmetricAlgorithm::decryptUpdate(const ByteString& encryptedData, ByteString& data)
411 {
412 if (!SymmetricAlgorithm::decryptUpdate(encryptedData, data))
413 {
414 clean();
415 return false;
416 }
417
418 // AEAD ciphers should not return decrypted data until final is called
419 if (currentCipherMode == SymMode::GCM)
420 {
421 data.resize(0);
422 return true;
423 }
424
425 // Count number of bytes written
426 if (maximumBytes)
427 {
428 BN_add_word(counterBytes, encryptedData.size());
429 }
430
431 // Prepare the output block
432 data.resize(encryptedData.size() + getBlockSize());
433
434 int outLen = data.size();
435
436 DEBUG_MSG("Decrypting %d bytes into buffer of %d bytes", encryptedData.size(), data.size());
437
438 if (!EVP_DecryptUpdate(pCurCTX, &data[0], &outLen, (unsigned char*) encryptedData.const_byte_str(), encryptedData.size()))
439 {
440 ERROR_MSG("EVP_DecryptUpdate failed: %s", ERR_error_string(ERR_get_error(), NULL));
441
442 clean();
443
444 ByteString dummy;
445 SymmetricAlgorithm::decryptFinal(dummy);
446
447 return false;
448 }
449
450 DEBUG_MSG("Decrypt returned %d bytes of data", outLen);
451
452 // Resize the output block
453 data.resize(outLen);
454 currentBufferSize -= outLen;
455
456 return true;
457 }
458
459 bool OSSLEVPSymmetricAlgorithm::decryptFinal(ByteString& data)
460 {
461 SymMode::Type mode = currentCipherMode;
462 size_t tagBytes = currentTagBytes;
463 ByteString aeadBuffer = currentAEADBuffer;
464
465 if (!SymmetricAlgorithm::decryptFinal(data))
466 {
467 clean();
468 return false;
469 }
470
471 data.resize(0);
472 if (mode == SymMode::GCM)
473 {
474 // Check buffer size
475 if (aeadBuffer.size() < tagBytes)
476 {
477 ERROR_MSG("Tag bytes (%d) does not fit in AEAD buffer (%d)", tagBytes, aeadBuffer.size());
478
479 clean();
480
481 return false;
482 }
483
484 // Set the tag
485 EVP_CIPHER_CTX_ctrl(pCurCTX, EVP_CTRL_GCM_SET_TAG, tagBytes, &aeadBuffer[aeadBuffer.size()-tagBytes]);
486
487 // Prepare the output block
488 data.resize(aeadBuffer.size() - tagBytes + getBlockSize());
489 int outLen = data.size();
490
491 if (!EVP_DecryptUpdate(pCurCTX, &data[0], &outLen, (unsigned char*) aeadBuffer.const_byte_str(), aeadBuffer.size() - tagBytes))
492 {
493 ERROR_MSG("EVP_DecryptUpdate failed: %s", ERR_error_string(ERR_get_error(), NULL));
494
495 clean();
496
497 return false;
498 }
499
500 data.resize(outLen);
501 }
502
503 // Prepare the output block
504 int initialSize = data.size();
505 data.resize(initialSize + getBlockSize());
506
507 int outLen = data.size() - initialSize;
508 int rv;
509
510 if (!(rv = EVP_DecryptFinal(pCurCTX, &data[initialSize], &outLen)))
511 {
512 ERROR_MSG("EVP_DecryptFinal failed (0x%08X): %s", rv, ERR_error_string(ERR_get_error(), NULL));
513
514 clean();
515
516 return false;
517 }
518
519 // Resize the output block
520 data.resize(initialSize + outLen);
521
522 clean();
523
524 return true;
525 }
526
527 // Check if more bytes of data can be encrypted
528 bool OSSLEVPSymmetricAlgorithm::checkMaximumBytes(unsigned long bytes)
529 {
530 if (maximumBytes == NULL) return true;
531
532 BIGNUM* bigNum = BN_new();
533 BN_copy(bigNum, counterBytes);
534 BN_add_word(bigNum, bytes);
535
536 bool rv = false;
537 if (BN_cmp(maximumBytes, bigNum) >= 0) rv = true;
538
539 BN_free(bigNum);
540
541 return rv;
542 }