forked from ElektraInitiative/libelektra
-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypto.c
561 lines (500 loc) · 16 KB
/
crypto.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/**
* @file
*
* @brief filter plugin providing cryptographic operations
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#ifndef HAVE_KDBCONFIG
#include "kdbconfig.h"
#endif
#include "crypto.h"
#include "crypto_kdb_functions.h"
#ifdef ELEKTRA_CRYPTO_API_GCRYPT
#include "gcrypt_operations.h"
#endif
#ifdef ELEKTRA_CRYPTO_API_OPENSSL
#include "openssl_operations.h"
#endif
#ifdef ELEKTRA_CRYPTO_API_BOTAN
#include "botan_operations.h"
#endif
#include "gpg.h"
#include "helper.h"
#include <kdb.h>
#include <kdberrors.h>
#include <kdbtypes.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
static pthread_mutex_t mutex_ref_cnt = PTHREAD_MUTEX_INITIALIZER;
static unsigned int ref_cnt = 0;
// gurads against compiler warnings because the functions are only used within the specified compile variants
#if defined(ELEKTRA_CRYPTO_API_GCRYPT) || defined(ELEKTRA_CRYPTO_API_OPENSSL) || defined(ELEKTRA_CRYPTO_API_BOTAN)
/**
* @brief checks if a Key has been marked for encryption by checking the Key's metadata.
*
* If the metakey ELEKTRA_CRYPTO_META_ENCRYPT has the value "1" it is considered to be true.
* Every other value or the non-existence of the metakey is considered to be false.
*
* @param k the Key to be checked
* @retval 0 if the Key has not been marked for encryption
* @retval 1 if the Key has been marked for encryption
*/
static int isMarkedForEncryption (const Key * k)
{
const Key * metaEncrypt = keyGetMeta (k, ELEKTRA_CRYPTO_META_ENCRYPT);
if (metaEncrypt && strcmp (keyString (metaEncrypt), "1") == 0)
{
return 1;
}
return 0;
}
/**
* @brief checks if a given Key k is in the spec namespace.
* @retval 0 if the Key k is in the spec namespace.
* @retval 1 if the Key k is NOT in the spec namespace.
*/
static inline int isSpecNamespace (const Key * k)
{
return (keyGetNamespace (k) == KEY_NS_SPEC);
}
#endif
/**
* @brief verify the version of the cryptographic payload of the given key.
* @param k holds the encrypted payload.
* @param errorKey holds an error description if the version does not match or the format is wrong at all.
* @return 1 if the payload version could be verified.
* @return 0 otherwise.
*/
static int checkPayloadVersion (Key * k, Key * errorKey)
{
if (keyGetValueSize (k) < ((ssize_t) ELEKTRA_CRYPTO_MAGIC_NUMBER_LEN))
{
ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (
errorKey,
"The provided data could not be recognized as valid cryptographic payload. The data is possibly "
"corrupted. Keyname: %s",
keyName (k));
return 0; // failure
}
// check the magic number without the version
const kdb_octet_t * value = (kdb_octet_t *) keyValue (k);
if (memcmp (value, ELEKTRA_CRYPTO_MAGIC_NUMBER, ELEKTRA_CRYPTO_MAGIC_NUMBER_LEN - 2))
{
ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (
errorKey,
"The provided data could not be recognized as valid cryptographic payload. The data is possibly "
"corrupted. Keyname: %s",
keyName (k));
return 0; // failure
}
// check the version
const size_t versionOffset = ELEKTRA_CRYPTO_MAGIC_NUMBER_LEN - 2;
if (memcmp (&value[versionOffset], ELEKTRA_CRYPTO_PAYLOAD_VERSION, 2))
{
ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (
errorKey, "The version of the cryptographic payload is not compatible with the version of the plugin. Keyname: %s",
keyName (k));
return 0; // failure
}
return 1; // success
}
/**
* @brief initialize the crypto backend
* @retval 1 on success
* @retval -1 on failure
*/
static int elektraCryptoInit (Key * errorKey ELEKTRA_UNUSED)
{
#if defined(ELEKTRA_CRYPTO_API_GCRYPT)
return elektraCryptoGcryInit (errorKey);
#elif defined(ELEKTRA_CRYPTO_API_OPENSSL)
return elektraCryptoOpenSSLInit (errorKey);
#elif defined(ELEKTRA_CRYPTO_API_BOTAN)
return elektraCryptoBotanInit (errorKey);
#else
return 1;
#endif
}
/**
* @brief clean up the crypto backend
*
* Some libraries may need extra code for cleaning up the environment.
*/
static void elektraCryptoTeardown (void)
{
}
/**
* @brief read the plugin configuration for the supposed length of the master password.
* @param errorKey may hold a warning if the provided configuration is invalid
* @param conf the plugin configuration
* @return the expected length of the master password
*/
static kdb_unsigned_short_t elektraCryptoGetRandomPasswordLength (Key * errorKey, KeySet * conf)
{
Key * k = ksLookupByName (conf, ELEKTRA_CRYPTO_PARAM_MASTER_PASSWORD_LEN, 0);
if (k && keyIsString (k) > 0)
{
kdb_unsigned_short_t passwordLen = (kdb_unsigned_short_t) strtoul (keyString (k), NULL, 10);
if (passwordLen > 0)
{
return passwordLen;
}
else
{
ELEKTRA_ADD_INSTALLATION_WARNING (errorKey,
"Master password length provided at " ELEKTRA_CRYPTO_PARAM_MASTER_PASSWORD_LEN
" is invalid. Using default value instead.");
}
}
return ELEKTRA_CRYPTO_DEFAULT_MASTER_PWD_LENGTH;
}
/**
* @brief create a random master password using the crypto backend's SRNG.
* @param errorKey holds an error description in case of failure.
* @param buffer is used to store the allocated hex-encoded random string. Must be freed by the caller.
* @param length limit the length of the generated string to length characters (including the 0x00 terminator)
* @retval 1 on success
* @retval -1 on error. errorKey holds a description.
*/
static int elektraCryptoCreateRandomString (Key * errorKey ELEKTRA_UNUSED, char ** buffer ELEKTRA_UNUSED,
const kdb_unsigned_short_t length ELEKTRA_UNUSED)
{
*buffer = NULL;
#if defined(ELEKTRA_CRYPTO_API_GCRYPT)
*buffer = elektraCryptoGcryCreateRandomString (errorKey, length);
#elif defined(ELEKTRA_CRYPTO_API_OPENSSL)
*buffer = elektraCryptoOpenSSLCreateRandomString (errorKey, length);
#elif defined(ELEKTRA_CRYPTO_API_BOTAN)
*buffer = elektraCryptoBotanCreateRandomString (errorKey, length);
#endif
if (*buffer) return 1;
return -1;
}
/**
* @brief overwrites the value of the key with zeroes and then releases the Key.
* @param key to be overwritten and released
*/
static void elektraCryptoSafelyReleaseKey (Key * key)
{
if (key)
{
// overwrite key content with zeroes
ssize_t length = keyGetValueSize (key);
if (length > 0)
{
memset ((void *) keyValue (key), 0, length);
}
// release the key
keyDel (key);
}
}
/**
* @brief encrypt the (Elektra) Keys contained in data.
* @param handle for the current plugin instance
* @param data the KeySet holding the data
* @param errorKey holds an error description in case of failure
* @retval 1 on success
* @retval -1 on failure. errorKey holds an error description.
*/
static int elektraCryptoEncrypt (Plugin * handle ELEKTRA_UNUSED, KeySet * data ELEKTRA_UNUSED, Key * errorKey ELEKTRA_UNUSED)
{
Key * k;
Key * masterKey = NULL;
#if defined(ELEKTRA_CRYPTO_API_GCRYPT) || defined(ELEKTRA_CRYPTO_API_OPENSSL) || defined(ELEKTRA_CRYPTO_API_BOTAN)
KeySet * pluginConfig = elektraPluginGetConfig (handle);
masterKey = ELEKTRA_PLUGIN_FUNCTION (getMasterPassword) (errorKey, pluginConfig);
if (!masterKey)
{
goto error; // error has been set by getMasterPassword
}
#endif
#if defined(ELEKTRA_CRYPTO_API_GCRYPT) || defined(ELEKTRA_CRYPTO_API_OPENSSL)
elektraCryptoHandle * cryptoHandle = NULL;
#endif
ksRewind (data);
while ((k = ksNext (data)) != 0)
{
if (!isMarkedForEncryption (k) || isSpecNamespace (k))
{
continue;
}
#if defined(ELEKTRA_CRYPTO_API_GCRYPT)
if (elektraCryptoGcryHandleCreate (&cryptoHandle, pluginConfig, errorKey, masterKey, k, ELEKTRA_CRYPTO_ENCRYPT) != 1)
{
goto error;
}
if (elektraCryptoGcryEncrypt (cryptoHandle, k, errorKey) != 1)
{
elektraCryptoGcryHandleDestroy (cryptoHandle);
goto error;
}
elektraCryptoGcryHandleDestroy (cryptoHandle);
cryptoHandle = NULL;
#elif defined(ELEKTRA_CRYPTO_API_OPENSSL)
if (elektraCryptoOpenSSLHandleCreate (&cryptoHandle, pluginConfig, errorKey, masterKey, k, ELEKTRA_CRYPTO_ENCRYPT) != 1)
{
elektraCryptoOpenSSLHandleDestroy (cryptoHandle);
goto error;
}
if (elektraCryptoOpenSSLEncrypt (cryptoHandle, k, errorKey) != 1)
{
elektraCryptoOpenSSLHandleDestroy (cryptoHandle);
goto error;
}
elektraCryptoOpenSSLHandleDestroy (cryptoHandle);
cryptoHandle = NULL;
#elif defined(ELEKTRA_CRYPTO_API_BOTAN)
if (elektraCryptoBotanEncrypt (pluginConfig, k, errorKey, masterKey) != 1)
{
goto error; // failure, error has been set by elektraCryptoBotanEncrypt
}
#endif
}
elektraCryptoSafelyReleaseKey (masterKey);
return 1;
error:
elektraCryptoSafelyReleaseKey (masterKey);
return -1;
}
/**
* @brief decrypt the (Elektra) Keys contained in data.
* @param handle for the current plugin instance
* @param data the KeySet holding the data
* @param errorKey holds an error description in case of failure
* @retval 1 on success
* @retval -1 on failure. errorKey holds an error description.
*/
static int elektraCryptoDecrypt (Plugin * handle ELEKTRA_UNUSED, KeySet * data, Key * errorKey)
{
Key * k;
Key * masterKey = NULL;
#if defined(ELEKTRA_CRYPTO_API_GCRYPT) || defined(ELEKTRA_CRYPTO_API_OPENSSL) || defined(ELEKTRA_CRYPTO_API_BOTAN)
KeySet * pluginConfig = elektraPluginGetConfig (handle);
masterKey = ELEKTRA_PLUGIN_FUNCTION (getMasterPassword) (errorKey, pluginConfig);
if (!masterKey)
{
goto error; // error has been set by getMasterPassword
}
#endif
#if defined(ELEKTRA_CRYPTO_API_GCRYPT) || defined(ELEKTRA_CRYPTO_API_OPENSSL)
elektraCryptoHandle * cryptoHandle = NULL;
#endif
ksRewind (data);
while ((k = ksNext (data)) != 0)
{
if (!isMarkedForEncryption (k) || isSpecNamespace (k))
{
continue;
}
if (!checkPayloadVersion (k, errorKey))
{
// error has been set by checkPayloadVersion()
goto error;
}
#if defined(ELEKTRA_CRYPTO_API_GCRYPT)
if (elektraCryptoGcryHandleCreate (&cryptoHandle, pluginConfig, errorKey, masterKey, k, ELEKTRA_CRYPTO_DECRYPT) != 1)
{
goto error;
}
if (elektraCryptoGcryDecrypt (cryptoHandle, k, errorKey) != 1)
{
elektraCryptoGcryHandleDestroy (cryptoHandle);
goto error;
}
elektraCryptoGcryHandleDestroy (cryptoHandle);
cryptoHandle = NULL;
#elif defined(ELEKTRA_CRYPTO_API_OPENSSL)
if (elektraCryptoOpenSSLHandleCreate (&cryptoHandle, pluginConfig, errorKey, masterKey, k, ELEKTRA_CRYPTO_DECRYPT) != 1)
{
elektraCryptoOpenSSLHandleDestroy (cryptoHandle);
goto error;
}
if (elektraCryptoOpenSSLDecrypt (cryptoHandle, k, errorKey) != 1)
{
elektraCryptoOpenSSLHandleDestroy (cryptoHandle);
goto error;
}
elektraCryptoOpenSSLHandleDestroy (cryptoHandle);
cryptoHandle = NULL;
#elif defined(ELEKTRA_CRYPTO_API_BOTAN)
if (elektraCryptoBotanDecrypt (pluginConfig, k, errorKey, masterKey) != 1)
{
goto error; // failure, error has been set by elektraCryptoBotanDecrypt
}
#endif
}
elektraCryptoSafelyReleaseKey (masterKey);
return 1;
error:
elektraCryptoSafelyReleaseKey (masterKey);
return -1;
}
/**
* @brief initialize the crypto provider for the first instance of the plugin.
*
* @param handle holds the plugin handle
* @param errorKey holds an error description in case of failure
* @retval 1 on success
* @retval -1 on failure. Check errorKey
*/
int ELEKTRA_PLUGIN_FUNCTION (open) (Plugin * handle ELEKTRA_UNUSED, Key * errorKey)
{
pthread_mutex_lock (&mutex_ref_cnt);
if (ref_cnt == 0)
{
if (elektraCryptoInit (errorKey) != 1)
{
pthread_mutex_unlock (&mutex_ref_cnt);
return -1;
}
}
ref_cnt++;
pthread_mutex_unlock (&mutex_ref_cnt);
return 1;
}
/**
* @brief finalizes the crypto provider for the last instance of the plugin.
*
* @param handle holds the plugin handle
* @param errorKey holds an error description in case of failure. Not used at the moment.
* @retval 1 on success
* @retval -1 on failure
*/
int ELEKTRA_PLUGIN_FUNCTION (close) (Plugin * handle, Key * errorKey ELEKTRA_UNUSED)
{
/* default behaviour: no teardown except the user/system requests it */
KeySet * pluginConfig = elektraPluginGetConfig (handle);
if (!pluginConfig)
{
return -1; // failure because of missing plugin config
}
Key * shutdown = ksLookupByName (pluginConfig, ELEKTRA_CRYPTO_PARAM_SHUTDOWN, 0);
if (!shutdown)
{
return 1; // applying default behaviour -> success
}
else
{
if (strcmp (keyString (shutdown), "1") != 0)
{
return 1; // applying default behaviour -> success
}
}
pthread_mutex_lock (&mutex_ref_cnt);
if (--ref_cnt == 0)
{
elektraCryptoTeardown ();
}
pthread_mutex_unlock (&mutex_ref_cnt);
return 1; // success
}
/**
* @brief establish the Elektra plugin contract and decrypt values, if possible.
*
* The crypto configuration is expected to be contained within the KeySet ks.
* All keys having a metakey "crypto/encrypted" with a strlen() > 0 are being decrypted.
*
* @param handle holds the plugin handle
* @param ks holds the data to be operated on
* @param parentKey holds an error description in case of failure
* @retval 1 on success
* @retval -1 on failure. Check parentKey.
*/
int ELEKTRA_PLUGIN_FUNCTION (get) (Plugin * handle, KeySet * ks, Key * parentKey)
{
// Publish module configuration to Elektra (establish the contract)
if (!strcmp (keyName (parentKey), "system/elektra/modules/" ELEKTRA_PLUGIN_NAME))
{
KeySet * moduleConfig = ksNew (30,
#include "contract.h"
KS_END);
ksAppend (ks, moduleConfig);
ksDel (moduleConfig);
return 1;
}
return elektraCryptoDecrypt (handle, ks, parentKey);
}
/**
* @brief Encrypt values marked for encryption.
*
* If a key has the metakey "crypto/encrypt" with a strlen() > 0, then the value
* will be encrypted using the configuration stored in the KeySet ks.
*
* @param handle holds the plugin handle
* @param ks holds the data to be operated on
* @param parentKey holds an error description in case of failure
* @retval 1 on success
* @retval -1 on failure. Check parentKey.
*/
int ELEKTRA_PLUGIN_FUNCTION (set) (Plugin * handle, KeySet * ks, Key * parentKey)
{
return elektraCryptoEncrypt (handle, ks, parentKey);
}
/**
* @brief Checks for the existence of the master password, that is used for encryption and decryption.
*
* If the master password can not be found it will be generated randomly.
* Then it will be encrypted and stored in conf.
*
* If the master password can be found, it will be decrypted temporarily in order to verify its correctness.
* conf will not be modified in this case.
*
* An error might occur during the password generation, encryption and decryption.
* The error will be appended to errorKey.
*
* @param errorKey holds an error description in case of failure
* @param conf holds the plugin configuration
* @retval 0 no changes were made to the configuration
* @retval 1 the master password has been appended to the configuration
* @retval -1 an error occurred. Check errorKey
*/
int ELEKTRA_PLUGIN_FUNCTION (checkconf) (Key * errorKey, KeySet * conf)
{
Key * k = ksLookupByName (conf, ELEKTRA_CRYPTO_PARAM_MASTER_PASSWORD, 0);
if (k)
{
// call gpg module to verify that we own the required key
Key * msg = keyDup (k);
if (ELEKTRA_PLUGIN_FUNCTION (gpgDecryptMasterPassword) (conf, errorKey, msg) != 1)
{
keyDel (msg);
return -1; // error set by ELEKTRA_PLUGIN_FUNCTION(gpgDecryptMasterPassword)()
}
keyDel (msg);
return 0;
}
else
{
// generate random master password
const kdb_unsigned_short_t passwordLen = elektraCryptoGetRandomPasswordLength (errorKey, conf);
char * r = NULL;
if (elektraCryptoCreateRandomString (errorKey, &r, passwordLen) != 1)
{
return -1; // error set by elektraCryptoCreateRandomString()
}
// store password in configuration
k = keyNew ("user/" ELEKTRA_CRYPTO_PARAM_MASTER_PASSWORD, KEY_END);
keySetString (k, r);
elektraFree (r);
if (ELEKTRA_PLUGIN_FUNCTION (gpgEncryptMasterPassword) (conf, errorKey, k) != 1)
{
keyDel (k);
return -1; // error set by ELEKTRA_PLUGIN_FUNCTION(gpgEncryptMasterPassword)()
}
ksAppendKey (conf, k);
return 1;
}
}
Plugin * ELEKTRA_PLUGIN_EXPORT
{
// clang-format off
return elektraPluginExport(ELEKTRA_PLUGIN_NAME,
ELEKTRA_PLUGIN_OPEN, &ELEKTRA_PLUGIN_FUNCTION(open),
ELEKTRA_PLUGIN_CLOSE, &ELEKTRA_PLUGIN_FUNCTION(close),
ELEKTRA_PLUGIN_GET, &ELEKTRA_PLUGIN_FUNCTION(get),
ELEKTRA_PLUGIN_SET, &ELEKTRA_PLUGIN_FUNCTION(set),
ELEKTRA_PLUGIN_END);
}