Debian Codegraph @

src/lib/data_mgr/SecureDataManager.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 /*****************************************************************************
28 SecureDataManager.cpp
29
30 The secure data manager main class. Every token instance has a secure data
31 manager instance member that is used to decrypt and encrypt sensitive object
32 attributes such as key material. The secure data manager maintains a key blob
33 containing a 256-bit AES key that is used in this decryption and encryption
34 process. The key blob itself is encrypted using a PBE derived key that is
35 derived from the user PIN and a PBE key that is derived from the SO PIN. It
36 is up to the token to enforce access control based on which user is logged
37 in; authentication using the SO PIN is required to be able to change the
38 user PIN. The master key that is used to decrypt/encrypt sensitive attributes
39 is stored in memory under a mask that is changed every time the key is used.
40 *****************************************************************************/
41
42 #include "config.h"
43 #include "SecureDataManager.h"
44 #include "CryptoFactory.h"
45 #include "AESKey.h"
46 #include "SymmetricAlgorithm.h"
47 #include "RFC4880.h"
48
49 // Constructors
50
51 // Initialise the object; called by all constructors
52 void SecureDataManager::initObject()
53 {
54 // Get an RNG instance
55 rng = CryptoFactory::i()->getRNG();
56
57 // Get an AES implementation
58 aes = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::AES);
59
60 // Initialise masking data
61 mask = new ByteString();
62
63 rng->generateRandom(*mask, 32);
64
65 // Set the initial login state
66 soLoggedIn = userLoggedIn = false;
67
68 // Set the magic
69 magic = ByteString("524A52"); // RJR
70
71 // Get a mutex
72 dataMgrMutex = MutexFactory::i()->getMutex();
73 }
74
75 // Constructs a new SecureDataManager for a blank token; actual
76 // initialisation is done by setting the SO PIN
77 SecureDataManager::SecureDataManager()
78 {
79 initObject();
80 }
81
82 // Constructs a SecureDataManager using the specified key blob
83 SecureDataManager::SecureDataManager(const ByteString& soPINBlob, const ByteString& userPINBlob)
84 {
85 initObject();
86
87 // De-serialise the key blob
88 soEncryptedKey = soPINBlob;
89 userEncryptedKey = userPINBlob;
90 }
91
92 // Destructor
93 SecureDataManager::~SecureDataManager()
94 {
95 // Recycle the AES instance
96 CryptoFactory::i()->recycleSymmetricAlgorithm(aes);
97
98 // Clean up the mask
99 delete mask;
100
101 MutexFactory::i()->recycleMutex(dataMgrMutex);
102 }
103
104 // Generic function for creating an encrypted version of the key from the specified passphrase
105 bool SecureDataManager::pbeEncryptKey(const ByteString& passphrase, ByteString& encryptedKey)
106 {
107 // Generate salt
108 ByteString salt;
109
110 if (!rng->generateRandom(salt, 8)) return false;
111
112 // Derive the key using RFC4880 PBE
113 AESKey* pbeKey = NULL;
114
115 if (!RFC4880::PBEDeriveKey(passphrase, salt, &pbeKey))
116 {
117 return false;
118 }
119
120 // Add the salt
121 encryptedKey.wipe();
122 encryptedKey += salt;
123
124 // Generate random IV
125 ByteString IV;
126
127 if (!rng->generateRandom(IV, aes->getBlockSize())) return false;
128
129 // Add the IV
130 encryptedKey += IV;
131
132 // Encrypt the data
133 ByteString block;
134
135 if (!aes->encryptInit(pbeKey, SymMode::CBC, IV))
136 {
137 delete pbeKey;
138
139 return false;
140 }
141
142 // First, add the magic
143 if (!aes->encryptUpdate(magic, block))
144 {
145 delete pbeKey;
146
147 return false;
148 }
149
150 encryptedKey += block;
151
152 // Then, add the key itself
153 ByteString key;
154
155 {
156 MutexLocker lock(dataMgrMutex);
157
158 unmask(key);
159
160 bool rv = aes->encryptUpdate(key, block);
161
162 remask(key);
163
164 if (!rv)
165 {
166 delete pbeKey;
167
168 return false;
169 }
170 }
171
172 encryptedKey += block;
173
174 // And finalise encryption
175 if (!aes->encryptFinal(block))
176 {
177 delete pbeKey;
178
179 return false;
180 }
181
182 encryptedKey += block;
183
184 delete pbeKey;
185
186 return true;
187 }
188
189 // Set the SO PIN (requires either a blank SecureDataManager or the
190 // SO to have logged in previously)
191 bool SecureDataManager::setSOPIN(const ByteString& soPIN)
192 {
193 // Check the new PIN
194 if (soPIN.size() == 0)
195 {
196 DEBUG_MSG("Zero length PIN specified");
197
198 return false;
199 }
200
201 // Check if the SO needs to be logged in
202 if ((soEncryptedKey.size() > 0) && !soLoggedIn)
203 {
204 DEBUG_MSG("SO must be logged in to change the SO PIN");
205
206 return false;
207 }
208
209 // If no SO PIN was set, then this is a SecureDataManager for a blank token. This
210 // means a new key has to be generated
211 if (soEncryptedKey.size() == 0)
212 {
213 ByteString key;
214
215 rng->generateRandom(key, 32);
216
217 remask(key);
218 }
219
220 return pbeEncryptKey(soPIN, soEncryptedKey);
221 }
222
223 // Set the user PIN (requires either the SO or the user to have logged
224 // in previously)
225 bool SecureDataManager::setUserPIN(const ByteString& userPIN)
226 {
227 // Check if the SO or the user is logged in
228 if (!soLoggedIn && !userLoggedIn)
229 {
230 DEBUG_MSG("Must be logged in to change the user PIN");
231
232 return false;
233 }
234
235 // Check the new PIN
236 if (userPIN.size() == 0)
237 {
238 DEBUG_MSG("Zero length PIN specified");
239
240 return false;
241 }
242
243 return pbeEncryptKey(userPIN, userEncryptedKey);
244 }
245
246 // Generic login function
247 bool SecureDataManager::login(const ByteString& passphrase, const ByteString& encryptedKey)
248 {
249 // Log out first
250 this->logout();
251
252 // First, take the salt from the encrypted key
253 ByteString salt = encryptedKey.substr(0,8);
254
255 // Then, take the IV from the encrypted key
256 ByteString IV = encryptedKey.substr(8, aes->getBlockSize());
257
258 // Now, take the encrypted data from the encrypted key
259 ByteString encryptedKeyData = encryptedKey.substr(8 + aes->getBlockSize());
260
261 // Derive the PBE key
262 AESKey* pbeKey = NULL;
263
264 if (!RFC4880::PBEDeriveKey(passphrase, salt, &pbeKey))
265 {
266 return false;
267 }
268
269 // Decrypt the key data
270 ByteString decryptedKeyData;
271 ByteString finalBlock;
272
273 // NOTE: The login will fail here if incorrect passphrase is supplied
274 if (!aes->decryptInit(pbeKey, SymMode::CBC, IV) ||
275 !aes->decryptUpdate(encryptedKeyData, decryptedKeyData) ||
276 !aes->decryptFinal(finalBlock))
277 {
278 delete pbeKey;
279
280 return false;
281 }
282
283 delete pbeKey;
284
285 decryptedKeyData += finalBlock;
286
287 // Check the magic
288 if (decryptedKeyData.substr(0, 3) != magic)
289 {
290 // The passphrase was incorrect
291 DEBUG_MSG("Incorrect passphrase supplied");
292
293 return false;
294 }
295
296 // Strip off the magic
297 ByteString key = decryptedKeyData.substr(3);
298
299 // And mask the key
300 decryptedKeyData.wipe();
301
302 MutexLocker lock(dataMgrMutex);
303 remask(key);
304
305 return true;
306 }
307
308 // Log in using the SO PIN
309 bool SecureDataManager::loginSO(const ByteString& soPIN)
310 {
311 return (soLoggedIn = login(soPIN, soEncryptedKey));
312 }
313
314 // Log in using the user PIN
315 bool SecureDataManager::loginUser(const ByteString& userPIN)
316 {
317 return (userLoggedIn = login(userPIN, userEncryptedKey));
318 }
319
320 // Generic re-authentication function
321 bool SecureDataManager::reAuthenticate(const ByteString& passphrase, const ByteString& encryptedKey)
322 {
323 // First, take the salt from the encrypted key
324 ByteString salt = encryptedKey.substr(0,8);
325
326 // Then, take the IV from the encrypted key
327 ByteString IV = encryptedKey.substr(8, aes->getBlockSize());
328
329 // Now, take the encrypted data from the encrypted key
330 ByteString encryptedKeyData = encryptedKey.substr(8 + aes->getBlockSize());
331
332 // Derive the PBE key
333 AESKey* pbeKey = NULL;
334
335 if (!RFC4880::PBEDeriveKey(passphrase, salt, &pbeKey))
336 {
337 return false;
338 }
339
340 // Decrypt the key data
341 ByteString decryptedKeyData;
342 ByteString finalBlock;
343
344 // NOTE: The login will fail here if incorrect passphrase is supplied
345 if (!aes->decryptInit(pbeKey, SymMode::CBC, IV) ||
346 !aes->decryptUpdate(encryptedKeyData, decryptedKeyData) ||
347 !aes->decryptFinal(finalBlock))
348 {
349 delete pbeKey;
350
351 return false;
352 }
353
354 delete pbeKey;
355
356 decryptedKeyData += finalBlock;
357
358 // Check the magic
359 if (decryptedKeyData.substr(0, 3) != magic)
360 {
361 // The passphrase was incorrect
362 DEBUG_MSG("Incorrect passphrase supplied");
363
364 return false;
365 }
366
367 // And mask the key
368 decryptedKeyData.wipe();
369
370 return true;
371 }
372
373 // Re-authenticate the SO
374 bool SecureDataManager::reAuthenticateSO(const ByteString& soPIN)
375 {
376 return reAuthenticate(soPIN, soEncryptedKey);
377 }
378
379 // Re-authenticate the user
380 bool SecureDataManager::reAuthenticateUser(const ByteString& userPIN)
381 {
382 return reAuthenticate(userPIN, userEncryptedKey);
383 }
384
385 // Log out
386 void SecureDataManager::logout()
387 {
388 MutexLocker lock(dataMgrMutex);
389
390 // Clear the logged in state
391 soLoggedIn = userLoggedIn = false;
392
393 // Clear the masked key
394 maskedKey.wipe();
395 }
396
397 // Decrypt the supplied data
398 bool SecureDataManager::decrypt(const ByteString& encrypted, ByteString& plaintext)
399 {
400 // Check the object logged in state
401 if ((!userLoggedIn && !soLoggedIn) || (maskedKey.size() != 32))
402 {
403 return false;
404 }
405
406 // Do not attempt decryption of empty byte strings
407 if (encrypted.size() == 0)
408 {
409 plaintext = ByteString("");
410 return true;
411 }
412
413 AESKey theKey(256);
414 ByteString unmaskedKey;
415
416 {
417 MutexLocker lock(dataMgrMutex);
418
419 unmask(unmaskedKey);
420
421 theKey.setKeyBits(unmaskedKey);
422
423 remask(unmaskedKey);
424 }
425
426 // Take the IV from the input data
427 ByteString IV = encrypted.substr(0, aes->getBlockSize());
428
429 if (IV.size() != aes->getBlockSize())
430 {
431 ERROR_MSG("Invalid IV in encrypted data");
432
433 return false;
434 }
435
436 ByteString finalBlock;
437
438 if (!aes->decryptInit(&theKey, SymMode::CBC, IV) ||
439 !aes->decryptUpdate(encrypted.substr(aes->getBlockSize()), plaintext) ||
440 !aes->decryptFinal(finalBlock))
441 {
442 return false;
443 }
444
445 plaintext += finalBlock;
446
447 return true;
448 }
449
450 // Encrypt the supplied data
451 bool SecureDataManager::encrypt(const ByteString& plaintext, ByteString& encrypted)
452 {
453 // Check the object logged in state
454 if ((!userLoggedIn && !soLoggedIn) || (maskedKey.size() != 32))
455 {
456 return false;
457 }
458
459 AESKey theKey(256);
460 ByteString unmaskedKey;
461
462 {
463 MutexLocker lock(dataMgrMutex);
464
465 unmask(unmaskedKey);
466
467 theKey.setKeyBits(unmaskedKey);
468
469 remask(unmaskedKey);
470 }
471
472 // Wipe encrypted data block
473 encrypted.wipe();
474
475 // Generate random IV
476 ByteString IV;
477
478 if (!rng->generateRandom(IV, aes->getBlockSize())) return false;
479
480 ByteString finalBlock;
481
482 if (!aes->encryptInit(&theKey, SymMode::CBC, IV) ||
483 !aes->encryptUpdate(plaintext, encrypted) ||
484 !aes->encryptFinal(finalBlock))
485 {
486 return false;
487 }
488
489 encrypted += finalBlock;
490
491 // Add IV to output data
492 encrypted = IV + encrypted;
493
494 return true;
495 }
496
497 // Returns the key blob for the SO PIN
498 ByteString SecureDataManager::getSOPINBlob()
499 {
500 return soEncryptedKey;
501 }
502
503 // Returns the key blob for the user PIN
504 ByteString SecureDataManager::getUserPINBlob()
505 {
506 return userEncryptedKey;
507 }
508
509 // Unmask the key
510 void SecureDataManager::unmask(ByteString& key)
511 {
512 key = maskedKey;
513 key ^= *mask;
514 }
515
516 // Remask the key
517 void SecureDataManager::remask(ByteString& key)
518 {
519 // Generate a new mask
520 rng->generateRandom(*mask, 32);
521
522 key ^= *mask;
523 maskedKey = key;
524 }
525
526 // Check if the SO is logged in
527 bool SecureDataManager::isSOLoggedIn()
528 {
529 return soLoggedIn;
530 }
531
532 // Check if the user is logged in
533 bool SecureDataManager::isUserLoggedIn()
534 {
535 return userLoggedIn;
536 }
537