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"
41 * -----BEGIN RSA PRIVATE KEY-----
42 * Proc-Type: 4,ENCRYPTED
43 * DEK-Info: DES-EDE3-CBC,704CFFD62FBA03E9
45 * 4AV/g0BiTeb07hzo4/Ct47HGhHEshMhBPGJ843QzuAinpZBbg3OxwPsQsLgoPhJL
46 * Bg6Oxyz9M4UN1Xlx6Lyo2lRT908mBP6dl/OItLsVArqAzM+e29KHQVNjV1h7xN9F
47 * u84tOgZftKun+ZkQUOoRvMLLu4yV4CUraks9tgyXquugGba/tbeyj2MYsC8wwSJX
49 * -----END RSA PRIVATE KEY-----
52 #define PEM_SUFF "-----"
54 #define PEM_PREF_BEGIN "-----BEGIN "
55 #define PEM_PREF_BEGIN_L 11
56 #define PEM_PREF_END "-----END "
57 #define PEM_PREF_END_L 9
60 parse_header_lines (const gchar *hbeg, const gchar *hend, GHashTable **result)
63 gchar *line, *name, *value;
66 copy = g_strndup (hbeg, hend - hbeg);
67 lines = g_strsplit (copy, "\n", 0);
70 for (l = lines; l && *l; ++l) {
74 /* Look for the break between name: value */
75 value = strchr (line, ':');
80 value = g_strdup (value + 1);
83 name = g_strdup (line);
87 *result = egg_openssl_headers_new ();
88 g_hash_table_replace (*result, name, value);
95 pem_find_begin (const gchar *data,
100 const gchar *pref, *suff;
103 /* Look for a prefix */
104 pref = g_strstr_len ((gchar*)data, n_data, PEM_PREF_BEGIN);
108 n_data -= (pref - data) + PEM_PREF_BEGIN_L;
109 data = pref + PEM_PREF_BEGIN_L;
111 /* Look for the end of that begin */
112 suff = g_strstr_len ((gchar*)data, n_data, PEM_SUFF);
116 /* Make sure on the same line */
117 if (memchr (pref, '\n', suff - pref))
125 pref += PEM_PREF_BEGIN_L;
126 g_assert (suff > pref);
127 stype = g_alloca (suff - pref + 1);
128 memcpy (stype, pref, suff - pref);
129 stype[suff - pref] = 0;
130 *type = g_quark_from_string (stype);
133 /* The byte after this ---BEGIN--- */
134 return suff + PEM_SUFF_L;
138 pem_find_end (const gchar *data,
147 /* Look for a prefix */
148 pref = g_strstr_len (data, n_data, PEM_PREF_END);
152 n_data -= (pref - data) + PEM_PREF_END_L;
153 data = pref + PEM_PREF_END_L;
155 /* Next comes the type string */
156 stype = g_quark_to_string (type);
157 n_type = strlen (stype);
158 if (strncmp ((gchar*)data, stype, n_type) != 0)
164 /* Next comes the suffix */
165 if (strncmp ((gchar*)data, PEM_SUFF, PEM_SUFF_L) != 0)
170 if (isspace (data[0]))
175 /* The beginning of this ---END--- */
180 pem_parse_block (const gchar *data, gsize n_data, guchar **decoded, gsize *n_decoded,
181 GHashTable **headers)
183 const gchar *x, *hbeg, *hend;
184 const gchar *p, *end;
192 g_assert (n_decoded);
199 /* Try and find a pair of blank lines with only white space between */
200 while (hend == NULL) {
201 x = memchr (p, '\n', end - p);
205 while (isspace (*x)) {
206 /* Found a second line, with only spaces between */
211 /* Found a space between two lines */
227 *n_decoded = (n_data * 3) / 4 + 1;
228 if (egg_secure_check (data))
229 *decoded = egg_secure_alloc (*n_decoded);
231 *decoded = g_malloc0 (*n_decoded);
232 g_return_val_if_fail (*decoded, FALSE);
234 *n_decoded = g_base64_decode_step (data, n_data, *decoded, &state, &save);
236 egg_secure_free (*decoded);
240 if (headers && hbeg && hend)
241 parse_header_lines (hbeg, hend, headers);
247 egg_openssl_headers_new (void)
249 return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
253 egg_openssl_pem_parse (gconstpointer data, gsize n_data,
254 EggOpensslPemCallback callback, gpointer user_data)
256 const gchar *beg, *end;
257 const gchar *outer_beg, *outer_end;
259 guchar *decoded = NULL;
261 GHashTable *headers = NULL;
264 g_return_val_if_fail (data, 0);
265 g_return_val_if_fail (n_data, 0);
266 g_return_val_if_fail (callback, 0);
270 /* This returns the first character after the PEM BEGIN header */
271 beg = pem_find_begin ((const gchar*)data, n_data, &type, &outer_beg);
277 /* This returns the character position before the PEM END header */
278 end = pem_find_end ((const gchar*)beg, n_data - ((const gchar*)beg - (const gchar *)data),
284 if (pem_parse_block (beg, end - beg, &decoded, &n_decoded, &headers)) {
285 g_assert (outer_end > outer_beg);
288 outer_beg, outer_end - outer_beg,
291 egg_secure_free (decoded);
293 g_hash_table_remove_all (headers);
297 /* Try for another block */
299 n_data -= (const gchar*)end - (const gchar*)data;
304 g_hash_table_destroy (headers);
310 append_each_header (gpointer key, gpointer value, gpointer user_data)
312 GString *string = (GString*)user_data;
314 g_string_append (string, (gchar*)key);
315 g_string_append (string, ": ");
316 g_string_append (string, (gchar*)value);
317 g_string_append_c (string, '\n');
321 egg_openssl_pem_write (const guchar *data, gsize n_data, GQuark type,
322 GHashTable *headers, gsize *n_result)
327 gsize n_prefix, estimate;
329 g_return_val_if_fail (data || !n_data, NULL);
330 g_return_val_if_fail (type, NULL);
331 g_return_val_if_fail (n_result, NULL);
333 string = g_string_sized_new (4096);
336 g_string_append_len (string, PEM_PREF_BEGIN, PEM_PREF_BEGIN_L);
337 g_string_append (string, g_quark_to_string (type));
338 g_string_append_len (string, PEM_SUFF, PEM_SUFF_L);
339 g_string_append_c (string, '\n');
342 if (headers && g_hash_table_size (headers) > 0) {
343 g_hash_table_foreach (headers, append_each_header, string);
344 g_string_append_c (string, '\n');
347 /* Resize string to fit the base64 data. Algorithm from Glib reference */
348 estimate = n_data * 4 / 3 + n_data * 4 / (3 * 65) + 7;
349 n_prefix = string->len;
350 g_string_set_size (string, n_prefix + estimate);
352 /* The actual base64 data, without line breaks */
354 length = g_base64_encode_step (data, n_data, FALSE,
355 string->str + n_prefix, &state, &save);
356 length += g_base64_encode_close (TRUE, string->str + n_prefix + length,
359 g_assert (length <= estimate);
360 g_string_set_size (string, n_prefix + length);
363 * OpenSSL is absolutely certain that it wants its PEM base64
364 * lines to be 64 characters in length. So go through and break
368 for (i = 64; i < length; i += 64) {
369 g_string_insert_c (string, n_prefix + i, '\n');
375 g_string_append_len (string, PEM_PREF_END, PEM_PREF_END_L);
376 g_string_append (string, g_quark_to_string (type));
377 g_string_append_len (string, PEM_SUFF, PEM_SUFF_L);
378 g_string_append_c (string, '\n');
380 *n_result = string->len;
381 return (guchar*)g_string_free (string, FALSE);
384 /* ----------------------------------------------------------------------------
388 static const struct {
392 } openssl_algos[] = {
393 { "DES-ECB", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB },
394 { "DES-CFB64", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CFB },
395 { "DES-CFB", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CFB },
402 /* DES-EDE-CFB64 DES-EDE-CFB */
407 { "DES-EDE3-ECB", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_ECB },
408 { "DES-EDE3-CFB64", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CFB },
409 { "DES-EDE3-CFB", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CFB },
412 { "DES-OFB", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_OFB },
413 { "DES-EDE3-OFB", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_OFB },
414 { "DES-CBC", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CBC },
415 { "DES-EDE3-CBC", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CBC },
420 /* RC2-CFB64 RC2-CFB */
422 { "RC4", GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM },
423 { "RC4-40", GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM },
424 { "IDEA-ECB", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_ECB },
425 { "IDEA-CFB64", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_CFB },
426 { "IDEA-OFB", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_OFB },
427 { "IDEA-CBC", GCRY_CIPHER_IDEA, GCRY_CIPHER_MODE_CBC },
428 { "BF-ECB", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_ECB },
429 { "BF-CBC", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC },
430 { "BF-CFB64", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CFB },
431 { "BF-CFB", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CFB },
432 { "BF-OFB", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_OFB },
433 { "CAST5-ECB", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_ECB },
434 { "CAST5-CBC", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CBC },
435 { "CAST5-CFB64", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CFB },
436 { "CAST5-CFB", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CFB },
437 { "CAST5-OFB", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_OFB },
438 /* RC5-32-12-16-CBC */
439 /* RC5-32-12-16-ECB */
440 /* RC5-32-12-16-CFB64 RC5-32-12-16-CFB */
441 /* RC5-32-12-16-OFB */
442 { "AES-128-ECB", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB },
443 { "AES-128-CBC", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC },
446 { "AES-128-CFB128", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CFB },
447 { "AES-128-CFB", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CFB },
448 { "AES-128-OFB", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_OFB },
449 { "AES-128-CTR", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CTR },
450 { "AES-192-ECB", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_ECB },
451 { "AES-192-CBC", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC },
454 { "AES-192-CFB128", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB },
455 { "AES-192-CFB", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB },
456 { "AES-192-OFB", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_OFB },
457 { "AES-192-CTR", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CTR },
458 { "AES-256-ECB", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB },
459 { "AES-256-CBC", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC },
462 { "AES-256-CFB128", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB },
463 { "AES-256-CFB", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB },
464 { "AES-256-OFB", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB },
465 { "AES-256-CTR", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CTR },
466 /* CAMELLIA-128-ECB */
467 /* CAMELLIA-128-CBC */
468 /* CAMELLIA-128-CFB1 */
469 /* CAMELLIA-128-CFB8 */
470 /* CAMELLIA-128-CFB128 CAMELLIA-128-CFB */
471 /* CAMELLIA-128-OFB */
472 /* CAMELLIA-192-ECB */
473 /* CAMELLIA-192-CBC */
474 /* CAMELLIA-192-CFB1 */
475 /* CAMELLIA-192-CFB8 */
476 /* CAMELLIA-192-CFB128 CAMELLIA-192-CFB */
477 /* CAMELLIA-192_OFB */
478 /* CAMELLIA-256-ECB */
479 /* CAMELLIA-256-CBC */
480 /* CAMELLIA-256-CFB1 */
481 /* CAMELLIA-256-CFB8 */
482 /* CAMELLIA-256-CFB128 CAMELLIA-256-CFB */
483 /* CAMELLIA-256-OFB */
486 /* ------------------------------------------------------------------------- */
489 egg_openssl_parse_algo (const char *name, int *mode)
491 static GQuark openssl_quarks[G_N_ELEMENTS(openssl_algos)] = { 0, };
492 static gsize openssl_quarks_inited = 0;
496 if (g_once_init_enter (&openssl_quarks_inited)) {
497 for (i = 0; i < G_N_ELEMENTS(openssl_algos); ++i)
498 openssl_quarks[i] = g_quark_from_static_string (openssl_algos[i].desc);
499 g_once_init_leave (&openssl_quarks_inited, 1);
502 q = g_quark_try_string (name);
504 for (i = 0; i < G_N_ELEMENTS(openssl_algos); ++i) {
505 if (q == openssl_quarks[i]) {
506 *mode = openssl_algos[i].mode;
507 return openssl_algos[i].algo;
516 parse_dekinfo (const gchar *dek, int *algo, int *mode, guchar **iv)
518 gboolean success = FALSE;
519 gchar **parts = NULL;
523 parts = g_strsplit (dek, ",", 2);
524 if (!parts || !parts[0] || !parts[1])
527 /* Parse the algorithm name */
528 *algo = egg_openssl_parse_algo (parts[0], mode);
532 /* Make sure this is usable */
533 gcry = gcry_cipher_test_algo (*algo);
538 ivlen = gcry_cipher_get_algo_blklen (*algo);
540 *iv = egg_hex_decode (parts[1], strlen(parts[1]), &len);
541 if (!*iv || ivlen != len) {
554 egg_openssl_decrypt_block (const gchar *dekinfo, const gchar *password,
555 gssize n_password, const guchar *data, gsize n_data,
556 guchar **decrypted, gsize *n_decrypted)
565 if (!parse_dekinfo (dekinfo, &algo, &mode, &iv))
568 ivlen = gcry_cipher_get_algo_blklen (algo);
570 /* We assume the iv is at least as long as at 8 byte salt */
571 g_return_val_if_fail (ivlen >= 8, FALSE);
573 /* IV is already set from the DEK info */
574 if (!egg_symkey_generate_simple (algo, GCRY_MD_MD5, password,
575 n_password, iv, 8, 1, &key, NULL)) {
580 /* TODO: Use secure memory */
581 gcry = gcry_cipher_open (&ch, algo, mode, 0);
582 g_return_val_if_fail (!gcry, FALSE);
584 gcry = gcry_cipher_setkey (ch, key, gcry_cipher_get_algo_keylen (algo));
585 g_return_val_if_fail (!gcry, FALSE);
586 egg_secure_free (key);
589 gcry = gcry_cipher_setiv (ch, iv, ivlen);
590 g_return_val_if_fail (!gcry, FALSE);
593 /* Allocate output area */
594 *n_decrypted = n_data;
595 *decrypted = egg_secure_alloc (n_data);
597 gcry = gcry_cipher_decrypt (ch, *decrypted, *n_decrypted, (void*)data, n_data);
599 egg_secure_free (*decrypted);
600 g_return_val_if_reached (FALSE);
603 gcry_cipher_close (ch);
609 egg_openssl_encrypt_block (const gchar *dekinfo, const gchar *password,
610 gssize n_password, const guchar *data, gsize n_data,
611 guchar **encrypted, gsize *n_encrypted)
613 gsize n_overflow, n_batch, n_padding;
617 guchar *padded = NULL;
622 if (!parse_dekinfo (dekinfo, &algo, &mode, &iv))
623 g_return_val_if_reached (FALSE);
625 ivlen = gcry_cipher_get_algo_blklen (algo);
627 /* We assume the iv is at least as long as at 8 byte salt */
628 g_return_val_if_fail (ivlen >= 8, FALSE);
630 /* IV is already set from the DEK info */
631 if (!egg_symkey_generate_simple (algo, GCRY_MD_MD5, password,
632 n_password, iv, 8, 1, &key, NULL))
633 g_return_val_if_reached (FALSE);
635 gcry = gcry_cipher_open (&ch, algo, mode, 0);
636 g_return_val_if_fail (!gcry, FALSE);
638 gcry = gcry_cipher_setkey (ch, key, gcry_cipher_get_algo_keylen (algo));
639 g_return_val_if_fail (!gcry, FALSE);
640 egg_secure_free (key);
643 gcry = gcry_cipher_setiv (ch, iv, ivlen);
644 g_return_val_if_fail (!gcry, FALSE);
647 /* Allocate output area */
648 n_overflow = (n_data % ivlen);
649 n_padding = n_overflow ? (ivlen - n_overflow) : 0;
650 n_batch = n_data - n_overflow;
651 *n_encrypted = n_data + n_padding;
652 *encrypted = g_malloc0 (*n_encrypted);
654 g_assert (*n_encrypted % ivlen == 0);
655 g_assert (*n_encrypted >= n_data);
656 g_assert (*n_encrypted == n_batch + n_overflow + n_padding);
658 /* Encrypt everything but the last bit */
659 gcry = gcry_cipher_encrypt (ch, *encrypted, n_batch, (void*)data, n_batch);
662 g_return_val_if_reached (FALSE);
665 /* Encrypt the padded block */
667 padded = egg_secure_alloc (ivlen);
668 memset (padded, 0, ivlen);
669 memcpy (padded, data + n_batch, n_overflow);
670 gcry = gcry_cipher_encrypt (ch, *encrypted + n_batch, ivlen, padded, ivlen);
671 egg_secure_free (padded);
674 g_return_val_if_reached (FALSE);
678 gcry_cipher_close (ch);
683 egg_openssl_get_dekinfo (GHashTable *headers)
688 val = g_hash_table_lookup (headers, "Proc-Type");
689 if (!val || strcmp (val, "4,ENCRYPTED") != 0)
691 val = g_hash_table_lookup (headers, "DEK-Info");
692 g_return_val_if_fail (val, NULL);
697 egg_openssl_prep_dekinfo (GHashTable *headers)
699 gchar *dekinfo, *hex;
704 ivlen = gcry_cipher_get_algo_blklen (GCRY_CIPHER_3DES);
705 g_return_val_if_fail (ivlen, NULL);
706 iv = g_malloc (ivlen);
707 gcry_create_nonce (iv, ivlen);
709 /* And encode it into the string */
710 hex = egg_hex_encode (iv, ivlen);
711 g_return_val_if_fail (hex, NULL);
712 dekinfo = g_strdup_printf ("DES-EDE3-CBC,%s", hex);
715 g_hash_table_insert (headers, g_strdup ("DEK-Info"), (void*)dekinfo);
716 g_hash_table_insert (headers, g_strdup ("Proc-Type"), g_strdup ("4,ENCRYPTED"));