1 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
2 /* egg-openssl.c - OpenSSL compatibility functionality
4 Copyright (C) 2007 Stefan Walter
6 The Gnome Keyring Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 License, or (at your option) any later version.
11 The Gnome Keyring Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the Gnome Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
21 Author: Stef Walter <stef@memberwebs.com>
27 #include "egg-openssl.h"
28 #include "egg-secure-memory.h"
29 #include "egg-symkey.h"
42 * -----BEGIN RSA PRIVATE KEY-----
43 * Proc-Type: 4,ENCRYPTED
44 * DEK-Info: DES-EDE3-CBC,704CFFD62FBA03E9
46 * 4AV/g0BiTeb07hzo4/Ct47HGhHEshMhBPGJ843QzuAinpZBbg3OxwPsQsLgoPhJL
47 * Bg6Oxyz9M4UN1Xlx6Lyo2lRT908mBP6dl/OItLsVArqAzM+e29KHQVNjV1h7xN9F
48 * u84tOgZftKun+ZkQUOoRvMLLu4yV4CUraks9tgyXquugGba/tbeyj2MYsC8wwSJX
50 * -----END RSA PRIVATE KEY-----
53 #define PEM_SUFF "-----"
55 #define PEM_PREF_BEGIN "-----BEGIN "
56 #define PEM_PREF_BEGIN_L 11
57 #define PEM_PREF_END "-----END "
58 #define PEM_PREF_END_L 9
61 parse_header_lines (const gchar *hbeg, const gchar *hend, GHashTable **result)
64 gchar *line, *name, *value;
67 copy = g_strndup (hbeg, hend - hbeg);
68 lines = g_strsplit (copy, "\n", 0);
71 for (l = lines; l && *l; ++l) {
75 /* Look for the break between name: value */
76 value = strchr (line, ':');
81 value = g_strdup (value + 1);
84 name = g_strdup (line);
88 *result = egg_openssl_headers_new ();
89 g_hash_table_replace (*result, name, value);
96 pem_find_begin (const gchar *data, gsize n_data, GQuark *type)
98 const gchar *pref, *suff;
101 /* Look for a prefix */
102 pref = g_strstr_len ((gchar*)data, n_data, PEM_PREF_BEGIN);
106 n_data -= (pref - data) + PEM_PREF_BEGIN_L;
107 data = pref + PEM_PREF_BEGIN_L;
109 /* Look for the end of that begin */
110 suff = g_strstr_len ((gchar*)data, n_data, PEM_SUFF);
114 /* Make sure on the same line */
115 if (memchr (pref, '\n', suff - pref))
120 pref += PEM_PREF_BEGIN_L;
121 g_assert (suff > pref);
122 stype = g_alloca (suff - pref + 1);
123 memcpy (stype, pref, suff - pref);
124 stype[suff - pref] = 0;
125 *type = g_quark_from_string (stype);
128 /* The byte after this ---BEGIN--- */
129 return suff + PEM_SUFF_L;
133 pem_find_end (const gchar *data, gsize n_data, GQuark type)
139 /* Look for a prefix */
140 pref = g_strstr_len (data, n_data, PEM_PREF_END);
144 n_data -= (pref - data) + PEM_PREF_END_L;
145 data = pref + PEM_PREF_END_L;
147 /* Next comes the type string */
148 stype = g_quark_to_string (type);
149 n_type = strlen (stype);
150 if (strncmp ((gchar*)data, stype, n_type) != 0)
156 /* Next comes the suffix */
157 if (strncmp ((gchar*)data, PEM_SUFF, PEM_SUFF_L) != 0)
160 /* The beginning of this ---END--- */
165 pem_parse_block (const gchar *data, gsize n_data, guchar **decoded, gsize *n_decoded,
166 GHashTable **headers)
168 const gchar *x, *hbeg, *hend;
169 const gchar *p, *end;
177 g_assert (n_decoded);
184 /* Try and find a pair of blank lines with only white space between */
185 while (hend == NULL) {
186 x = memchr (p, '\n', end - p);
190 while (isspace (*x)) {
191 /* Found a second line, with only spaces between */
196 /* Found a space between two lines */
212 *n_decoded = (n_data * 3) / 4 + 1;
213 if (egg_secure_check (data))
214 *decoded = egg_secure_alloc (*n_decoded);
216 *decoded = g_malloc0 (*n_decoded);
217 g_return_val_if_fail (*decoded, FALSE);
219 *n_decoded = g_base64_decode_step (data, n_data, *decoded, &state, &save);
221 egg_secure_free (*decoded);
225 if (headers && hbeg && hend)
226 parse_header_lines (hbeg, hend, headers);
232 egg_openssl_headers_new (void)
234 return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
238 egg_openssl_pem_parse (const guchar *data, gsize n_data,
239 EggOpensslPemCallback callback, gpointer user_data)
241 const gchar *beg, *end;
243 guchar *decoded = NULL;
245 GHashTable *headers = NULL;
248 g_return_val_if_fail (data, 0);
249 g_return_val_if_fail (n_data, 0);
250 g_return_val_if_fail (callback, 0);
254 /* This returns the first character after the PEM BEGIN header */
255 beg = pem_find_begin ((const gchar*)data, n_data, &type);
261 /* This returns the character position before the PEM END header */
262 end = pem_find_end ((const gchar*)beg, n_data - ((const guchar*)beg - data), type);
267 if (pem_parse_block (beg, end - beg, &decoded, &n_decoded, &headers)) {
268 (callback) (type, decoded, n_decoded, headers, user_data);
270 egg_secure_free (decoded);
272 g_hash_table_remove_all (headers);
276 /* Try for another block */
278 n_data -= (const guchar*)end - data;
279 data = (const guchar*)end;
283 g_hash_table_destroy (headers);
291 append_each_header (gpointer key, gpointer value, gpointer user_data)
293 GString *string = (GString*)user_data;
295 g_string_append (string, (gchar*)key);
296 g_string_append (string, ": ");
297 g_string_append (string, (gchar*)value);
298 g_string_append_c (string, '\n');
302 egg_openssl_pem_write (const guchar *data, gsize n_data, GQuark type,
303 GHashTable *headers, gsize *n_result)
307 gsize length, n_prefix;
309 g_return_val_if_fail (data || !n_data, NULL);
310 g_return_val_if_fail (type, NULL);
311 g_return_val_if_fail (n_result, NULL);
313 string = g_string_sized_new (4096);
316 g_string_append_len (string, PEM_PREF_BEGIN, PEM_PREF_BEGIN_L);
317 g_string_append (string, g_quark_to_string (type));
318 g_string_append_len (string, PEM_SUFF, PEM_SUFF_L);
319 g_string_append_c (string, '\n');
322 if (headers && g_hash_table_size (headers) > 0) {
323 g_hash_table_foreach (headers, append_each_header, string);
324 g_string_append_c (string, '\n');
327 /* Resize string to fit the base64 data. Algorithm from Glib reference */
328 length = n_data * 4 / 3 + n_data * 4 / (3 * 72) + 7;
329 n_prefix = string->len;
330 g_string_set_size (string, n_prefix + length);
332 /* The actual base64 data */
334 length = g_base64_encode_step (data, n_data, TRUE,
335 string->str + string->len, &state, &save);
336 g_string_set_size (string, n_prefix + length);
339 g_string_append_c (string, '\n');
340 g_string_append_len (string, PEM_PREF_END, PEM_PREF_END_L);
341 g_string_append (string, g_quark_to_string (type));
342 g_string_append_len (string, PEM_SUFF, PEM_SUFF_L);
343 g_string_append_c (string, '\n');
345 *n_result = string->len;
346 return (guchar*)g_string_free (string, FALSE);
349 #endif /* UNTESTED_CODE */
351 /* ----------------------------------------------------------------------------
355 const static struct {
359 } openssl_algos[] = {
360 { "DES-ECB", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB },
361 { "DES-CFB64", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CFB },
362 { "DES-CFB", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CFB },
369 /* DES-EDE-CFB64 DES-EDE-CFB */
374 { "DES-EDE3-ECB", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_ECB },
375 { "DES-EDE3-CFB64", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CFB },
376 { "DES-EDE3-CFB", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CFB },
379 { "DES-OFB", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_OFB },
380 { "DES-EDE3-OFB", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_OFB },
381 { "DES-CBC", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CBC },
382 { "DES-EDE3-CBC", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CBC },
387 /* RC2-CFB64 RC2-CFB */
389 { "RC4", GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM },
390 { "RC4-40", GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM },
391 { "IDEA-ECB", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_ECB },
392 { "IDEA-CFB64", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_CFB },
393 { "IDEA-OFB", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_OFB },
394 { "IDEA-CBC", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_CBC },
395 { "BF-ECB", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_ECB },
396 { "BF-CBC", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC },
397 { "BF-CFB64", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CFB },
398 { "BF-CFB", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CFB },
399 { "BF-OFB", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_OFB },
400 { "CAST5-ECB", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_ECB },
401 { "CAST5-CBC", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CBC },
402 { "CAST5-CFB64", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CFB },
403 { "CAST5-CFB", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CFB },
404 { "CAST5-OFB", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_OFB },
405 /* RC5-32-12-16-CBC */
406 /* RC5-32-12-16-ECB */
407 /* RC5-32-12-16-CFB64 RC5-32-12-16-CFB */
408 /* RC5-32-12-16-OFB */
409 { "AES-128-ECB", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB },
410 { "AES-128-CBC", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC },
413 { "AES-128-CFB128", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CFB },
414 { "AES-128-CFB", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CFB },
415 { "AES-128-OFB", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_OFB },
416 { "AES-128-CTR", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CTR },
417 { "AES-192-ECB", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_ECB },
418 { "AES-192-CBC", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC },
421 { "AES-192-CFB128", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB },
422 { "AES-192-CFB", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB },
423 { "AES-192-OFB", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_OFB },
424 { "AES-192-CTR", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CTR },
425 { "AES-256-ECB", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB },
426 { "AES-256-CBC", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC },
429 { "AES-256-CFB128", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB },
430 { "AES-256-CFB", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB },
431 { "AES-256-OFB", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB },
432 { "AES-256-CTR", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CTR },
433 /* CAMELLIA-128-ECB */
434 /* CAMELLIA-128-CBC */
435 /* CAMELLIA-128-CFB1 */
436 /* CAMELLIA-128-CFB8 */
437 /* CAMELLIA-128-CFB128 CAMELLIA-128-CFB */
438 /* CAMELLIA-128-OFB */
439 /* CAMELLIA-192-ECB */
440 /* CAMELLIA-192-CBC */
441 /* CAMELLIA-192-CFB1 */
442 /* CAMELLIA-192-CFB8 */
443 /* CAMELLIA-192-CFB128 CAMELLIA-192-CFB */
444 /* CAMELLIA-192_OFB */
445 /* CAMELLIA-256-ECB */
446 /* CAMELLIA-256-CBC */
447 /* CAMELLIA-256-CFB1 */
448 /* CAMELLIA-256-CFB8 */
449 /* CAMELLIA-256-CFB128 CAMELLIA-256-CFB */
450 /* CAMELLIA-256-OFB */
453 /* ------------------------------------------------------------------------- */
456 egg_openssl_parse_algo (const char *name, int *mode)
458 static GQuark openssl_quarks[G_N_ELEMENTS(openssl_algos)] = { 0, };
459 static gsize openssl_quarks_inited = 0;
463 if (g_once_init_enter (&openssl_quarks_inited)) {
464 for (i = 0; i < G_N_ELEMENTS(openssl_algos); ++i)
465 openssl_quarks[i] = g_quark_from_static_string (openssl_algos[i].desc);
466 g_once_init_leave (&openssl_quarks_inited, 1);
469 q = g_quark_try_string (name);
471 for (i = 0; i < G_N_ELEMENTS(openssl_algos); ++i) {
472 if (q == openssl_quarks[i]) {
473 *mode = openssl_algos[i].mode;
474 return openssl_algos[i].algo;
483 parse_dekinfo (const gchar *dek, int *algo, int *mode, guchar **iv)
485 gboolean success = FALSE;
486 gchar **parts = NULL;
490 parts = g_strsplit (dek, ",", 2);
491 if (!parts || !parts[0] || !parts[1])
494 /* Parse the algorithm name */
495 *algo = egg_openssl_parse_algo (parts[0], mode);
499 /* Make sure this is usable */
500 gcry = gcry_cipher_test_algo (*algo);
505 ivlen = gcry_cipher_get_algo_blklen (*algo);
507 *iv = egg_hex_decode (parts[1], strlen(parts[1]), &len);
508 if (!*iv || ivlen != len) {
521 egg_openssl_decrypt_block (const gchar *dekinfo, const gchar *password,
522 gssize n_password, const guchar *data, gsize n_data,
523 guchar **decrypted, gsize *n_decrypted)
532 if (!parse_dekinfo (dekinfo, &algo, &mode, &iv))
535 ivlen = gcry_cipher_get_algo_blklen (algo);
537 /* We assume the iv is at least as long as at 8 byte salt */
538 g_return_val_if_fail (ivlen >= 8, FALSE);
540 /* IV is already set from the DEK info */
541 if (!egg_symkey_generate_simple (algo, GCRY_MD_MD5, password,
542 n_password, iv, 8, 1, &key, NULL)) {
547 /* TODO: Use secure memory */
548 gcry = gcry_cipher_open (&ch, algo, mode, 0);
549 g_return_val_if_fail (!gcry, FALSE);
551 gcry = gcry_cipher_setkey (ch, key, gcry_cipher_get_algo_keylen (algo));
552 g_return_val_if_fail (!gcry, FALSE);
553 egg_secure_free (key);
556 gcry = gcry_cipher_setiv (ch, iv, ivlen);
557 g_return_val_if_fail (!gcry, FALSE);
560 /* Allocate output area */
561 *n_decrypted = n_data;
562 *decrypted = egg_secure_alloc (n_data);
564 gcry = gcry_cipher_decrypt (ch, *decrypted, *n_decrypted, (void*)data, n_data);
566 egg_secure_free (*decrypted);
567 g_return_val_if_reached (FALSE);
570 gcry_cipher_close (ch);
576 egg_openssl_encrypt_block (const gchar *dekinfo, const gchar *password,
577 gssize n_password, const guchar *data, gsize n_data,
578 guchar **encrypted, gsize *n_encrypted)
580 gsize n_overflow, n_batch, n_padding;
584 guchar *padded = NULL;
589 if (!parse_dekinfo (dekinfo, &algo, &mode, &iv))
590 g_return_val_if_reached (FALSE);
592 ivlen = gcry_cipher_get_algo_blklen (algo);
594 /* We assume the iv is at least as long as at 8 byte salt */
595 g_return_val_if_fail (ivlen >= 8, FALSE);
597 /* IV is already set from the DEK info */
598 if (!egg_symkey_generate_simple (algo, GCRY_MD_MD5, password,
599 n_password, iv, 8, 1, &key, NULL))
600 g_return_val_if_reached (FALSE);
602 gcry = gcry_cipher_open (&ch, algo, mode, 0);
603 g_return_val_if_fail (!gcry, FALSE);
605 gcry = gcry_cipher_setkey (ch, key, gcry_cipher_get_algo_keylen (algo));
606 g_return_val_if_fail (!gcry, FALSE);
607 egg_secure_free (key);
610 gcry = gcry_cipher_setiv (ch, iv, ivlen);
611 g_return_val_if_fail (!gcry, FALSE);
614 /* Allocate output area */
615 n_overflow = (n_data % ivlen);
616 n_padding = n_overflow ? (ivlen - n_overflow) : 0;
617 n_batch = n_data - n_overflow;
618 *n_encrypted = n_data + n_padding;
619 *encrypted = g_malloc0 (*n_encrypted);
621 g_assert (*n_encrypted % ivlen == 0);
622 g_assert (*n_encrypted >= n_data);
623 g_assert (*n_encrypted == n_batch + n_overflow + n_padding);
625 /* Encrypt everything but the last bit */
626 gcry = gcry_cipher_encrypt (ch, *encrypted, n_batch, (void*)data, n_batch);
629 g_return_val_if_reached (FALSE);
632 /* Encrypt the padded block */
634 padded = egg_secure_alloc (ivlen);
635 memset (padded, 0, ivlen);
636 memcpy (padded, data + n_batch, n_overflow);
637 gcry = gcry_cipher_encrypt (ch, *encrypted + n_batch, ivlen, padded, ivlen);
638 egg_secure_free (padded);
641 g_return_val_if_reached (FALSE);
645 gcry_cipher_close (ch);
650 egg_openssl_get_dekinfo (GHashTable *headers)
655 val = g_hash_table_lookup (headers, "Proc-Type");
656 if (!val || strcmp (val, "4,ENCRYPTED") != 0)
658 val = g_hash_table_lookup (headers, "DEK-Info");
659 g_return_val_if_fail (val, NULL);
664 egg_openssl_prep_dekinfo (GHashTable *headers)
666 gchar *dekinfo, *hex;
671 ivlen = gcry_cipher_get_algo_blklen (GCRY_CIPHER_3DES);
672 g_return_val_if_fail (ivlen, NULL);
673 iv = g_malloc (ivlen);
674 gcry_create_nonce (iv, ivlen);
676 /* And encode it into the string */
677 hex = egg_hex_encode (iv, ivlen);
678 g_return_val_if_fail (hex, NULL);
679 dekinfo = g_strdup_printf ("DES-EDE3-CBC,%s", hex);
682 g_hash_table_insert (headers, g_strdup ("DEK-Info"), (void*)dekinfo);
683 g_hash_table_insert (headers, g_strdup ("Proc-Type"), g_strdup ("4,ENCRYPTED"));