Rename inquire keywords for keyid's.
[pwmd.git] / src / pwmd-dump.c
blob296852e5149afb1ee543f8a701d9818c1e4dc55e
1 /*
2 Copyright (C) 2015, 2016
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <stdint.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #include <errno.h>
34 #include <arpa/inet.h>
35 #include <libxml/tree.h>
36 #include <libxml/parser.h>
37 #include <libxml/xpath.h>
38 #include <err.h>
39 #include <termios.h>
41 #include "pwmd-error.h"
42 #include <gcrypt.h>
44 #ifdef HAVE_SYS_PRCTL_H
45 #include <sys/prctl.h>
46 #endif
48 #ifdef ENABLE_NLS
49 #ifdef HAVE_LOCALE_H
50 #include <locale.h>
51 #endif
52 #endif
54 #ifndef _
55 #include "gettext.h"
56 #define _(msgid) gettext(msgid)
57 #endif
59 #ifdef HAVE_GETOPT_LONG
60 #ifdef HAVE_GETOPT_H
61 #include <getopt.h>
62 #endif
63 #else
64 #include "getopt_long.h"
65 #endif
67 #include "util-string.h"
68 #include "mem.h"
70 #if 0
71 #ifdef WITH_AGENT
72 #include "agent.h"
73 #endif
74 #endif
76 #define PWMD_CIPHER_OFFSET (1)
77 #define PWMD_CIPHER(n) (PWMD_CIPHER_OFFSET << n)
78 #define PWMD_CIPHER_AES128 PWMD_CIPHER (0)
79 #define PWMD_CIPHER_AES192 PWMD_CIPHER (1)
80 #define PWMD_CIPHER_AES256 PWMD_CIPHER (2)
81 #define PWMD_CIPHER_SERPENT128 PWMD_CIPHER (3)
82 #define PWMD_CIPHER_SERPENT192 PWMD_CIPHER (4)
83 #define PWMD_CIPHER_SERPENT256 PWMD_CIPHER (5)
84 #define PWMD_CIPHER_CAMELLIA128 PWMD_CIPHER (6)
85 #define PWMD_CIPHER_CAMELLIA192 PWMD_CIPHER (7)
86 #define PWMD_CIPHER_CAMELLIA256 PWMD_CIPHER (8)
87 #define PWMD_CIPHER_3DES PWMD_CIPHER (9)
88 #define PWMD_CIPHER_CAST5 PWMD_CIPHER (10)
89 #define PWMD_CIPHER_BLOWFISH PWMD_CIPHER (11)
90 #define PWMD_CIPHER_TWOFISH PWMD_CIPHER (12)
91 #define PWMD_CIPHER_TWOFISH128 PWMD_CIPHER (13)
93 #define PWMD_FLAG_OFFSET (PWMD_CIPHER_OFFSET << 15)
94 #define PWMD_FLAG(n) (PWMD_FLAG_OFFSET << n)
95 #define PWMD_FLAG_PKI PWMD_FLAG (1)
96 #define PWMD_FLAG_NO_PASSPHRASE PWMD_FLAG (2)
98 #define KEYSIZE 32
100 typedef struct
102 uint8_t magic[5];
103 uint32_t version;
104 uint64_t s2k_count;
105 uint64_t flags;
106 uint8_t iv[16];
107 uint8_t salt[8];
108 uint32_t datalen; /* of the encrypted xml */
109 } __attribute__ ((packed)) file_header_t;
111 struct save_s
113 gcry_sexp_t pkey; /* SAVE --keygrip */
114 gcry_sexp_t sigpkey; /* SAVE --sign-keygrip */
115 file_header_t hdr;
118 struct crypto_s
120 //assuan_context_t client_ctx;
121 #ifdef WITH_AGENT
122 struct agent_s *agent;
123 #endif
124 struct save_s save;
125 gcry_sexp_t pkey_sexp;
126 unsigned char grip[20];
127 gcry_sexp_t sigpkey_sexp;
128 unsigned char sign_grip[20];
129 gcry_sexp_t ciphertext_sexp;
130 void *ciphertext;
131 size_t ciphertext_len;
132 void *plaintext;
133 size_t plaintext_len;
134 file_header_t hdr;
135 char *filename; /* the currently opened data file */
138 #define DEFAULT_KDFS2K_ITERATIONS 5000000
139 #define COMPAT_KDFS2K_ITERATIONS 1000
141 const char *reserved_attributes[] = {
142 "_name", "_mtime", "_ctime", "_acl", "target",
143 NULL
145 static unsigned char crypto_magic[5] = "\177PWMD";
146 static int use_agent;
148 static void set_header_defaults (file_header_t * hdr);
149 static gpg_error_t decrypt_common (struct crypto_s *crypto,
150 const char *filename, const char *keyfile);
151 static gpg_error_t read_data_file (const char *filename,
152 struct crypto_s *crypto);
153 static void cleanup_crypto_stage1 (struct crypto_s *cr);
154 static void cleanup_crypto (struct crypto_s **c);
156 static int
157 cipher_to_gcrypt (int flags)
159 if (flags < 0)
160 return flags;
162 if (flags & PWMD_CIPHER_AES128)
163 return GCRY_CIPHER_AES128;
164 else if (flags & PWMD_CIPHER_AES192)
165 return GCRY_CIPHER_AES192;
166 else if (flags & PWMD_CIPHER_AES256)
167 return GCRY_CIPHER_AES256;
168 else if (flags & PWMD_CIPHER_SERPENT128)
169 return GCRY_CIPHER_SERPENT128;
170 else if (flags & PWMD_CIPHER_SERPENT192)
171 return GCRY_CIPHER_SERPENT192;
172 else if (flags & PWMD_CIPHER_SERPENT256)
173 return GCRY_CIPHER_SERPENT256;
174 else if (flags & PWMD_CIPHER_CAMELLIA128)
175 return GCRY_CIPHER_CAMELLIA128;
176 else if (flags & PWMD_CIPHER_CAMELLIA192)
177 return GCRY_CIPHER_CAMELLIA192;
178 else if (flags & PWMD_CIPHER_CAMELLIA256)
179 return GCRY_CIPHER_CAMELLIA256;
180 else if (flags & PWMD_CIPHER_BLOWFISH)
181 return GCRY_CIPHER_BLOWFISH;
182 else if (flags & PWMD_CIPHER_3DES)
183 return GCRY_CIPHER_3DES;
184 else if (flags & PWMD_CIPHER_CAST5)
185 return GCRY_CIPHER_CAST5;
186 else if (flags & PWMD_CIPHER_TWOFISH)
187 return GCRY_CIPHER_TWOFISH;
188 else if (flags & PWMD_CIPHER_TWOFISH128)
189 return GCRY_CIPHER_TWOFISH128;
191 return -1;
194 static int
195 cipher_string_to_cipher (const char *str)
197 int flags = 0;
199 if (!strcasecmp (str, "aes128"))
200 flags = PWMD_CIPHER_AES128;
201 else if (!strcasecmp (str, "aes192"))
202 flags = PWMD_CIPHER_AES192;
203 else if (!strcasecmp (str, "aes256"))
204 flags = PWMD_CIPHER_AES256;
205 else if (!strcasecmp (str, "serpent128"))
206 flags = PWMD_CIPHER_SERPENT128;
207 else if (!strcasecmp (str, "serpent192"))
208 flags = PWMD_CIPHER_SERPENT192;
209 else if (!strcasecmp (str, "serpent256"))
210 flags = PWMD_CIPHER_SERPENT256;
211 else if (!strcasecmp (str, "camellia128"))
212 flags = PWMD_CIPHER_CAMELLIA128;
213 else if (!strcasecmp (str, "camellia192"))
214 flags = PWMD_CIPHER_CAMELLIA192;
215 else if (!strcasecmp (str, "camellia256"))
216 flags = PWMD_CIPHER_CAMELLIA256;
217 else if (!strcasecmp (str, "blowfish"))
218 flags = PWMD_CIPHER_BLOWFISH;
219 else if (!strcasecmp (str, "cast5"))
220 flags = PWMD_CIPHER_CAST5;
221 else if (!strcasecmp (str, "3des"))
222 flags = PWMD_CIPHER_3DES;
223 else if (!strcasecmp (str, "twofish256"))
224 flags = PWMD_CIPHER_TWOFISH;
225 else if (!strcasecmp (str, "twofish128"))
226 flags = PWMD_CIPHER_TWOFISH128;
227 else
228 return -1;
230 return flags;
233 static void
234 usage (const char *pn, int rc)
236 fprintf(rc == EXIT_SUCCESS ? stdout : stderr,
237 "%s [-hvn] [--force] [-k <filename>] [--xml] <infile> <outfile>\n"
238 " --no-convert, -n don't discard data for elements with targets\n"
239 " --force don't abort when converting\n"
240 " --xml read a raw pwmd XML document\n"
241 " --keyfile, -k file containing the passphrase to use for decryption\n"
242 " --help\n"
243 " --version\n\n"
244 "Use - as <outfile> to write to standard output.\n",
245 pn);
246 exit (rc);
249 static gpg_error_t
250 init_client_crypto (struct crypto_s **crypto)
252 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
253 gpg_error_t rc;
255 if (!new)
257 rc = GPG_ERR_ENOMEM;
258 return rc;
261 #ifdef WITH_AGENT
262 if (use_agent)
264 rc = agent_init (&new->agent);
265 if (!rc)
267 rc = send_agent_common_options (new->agent);
268 if (!rc)
269 rc = agent_set_pinentry_options (new->agent);
272 if (rc)
274 cleanup_agent (new->agent);
275 xfree (new);
276 return rc;
279 #endif
281 set_header_defaults (&new->hdr);
282 *crypto = new;
283 return 0;
286 static gpg_error_t
287 parse_doc (const char *xml, size_t len, xmlDocPtr *result)
289 xmlDocPtr doc;
291 xmlResetLastError ();
292 doc = xmlReadMemory (xml, len, NULL, "UTF-8", XML_PARSE_NOBLANKS);
293 if (!doc && xmlGetLastError ())
294 return GPG_ERR_BAD_DATA;
296 *result = doc;
297 return !doc ? GPG_ERR_ENOMEM : 0;
300 static xmlChar *
301 xml_attribute_value (xmlNodePtr n, xmlChar * attr)
303 xmlAttrPtr a = xmlHasProp (n, attr);
305 if (!a)
306 return NULL;
308 if (!a->children || !a->children->content)
309 return NULL;
311 return xmlGetProp (n, attr);
314 static int
315 xml_reserved_attribute (const char *name)
317 int i;
319 for (i = 0; reserved_attributes[i]; i++)
321 if (!strcmp (name, reserved_attributes[i]))
322 return 1;
325 return 0;
327 static void
328 remove_non_reserved_attributes (xmlNodePtr n)
330 xmlAttrPtr a;
332 for (a = n->properties; a; a = a->next)
334 if (xml_reserved_attribute ((char *)a->name))
335 continue;
337 xmlRemoveProp (a);
341 static gpg_error_t
342 strip_literals (const char *filename, xmlNodePtr n, int force)
344 gpg_error_t rc = 0;
346 for (; n; n = n->next)
348 xmlChar *target;
350 if (n->type != XML_ELEMENT_NODE)
351 continue;
353 if (!xmlStrEqual (n->name, (xmlChar *) "element"))
355 xmlNodePtr tmp = n->next;
357 xmlUnlinkNode (n);
358 xmlFreeNodeList (n);
359 return strip_literals (filename, tmp, force);
362 target = xml_attribute_value (n, (xmlChar *)"target");
363 if (target)
365 xmlChar lastc = 0, *p;
367 remove_non_reserved_attributes (n);
368 again:
369 for (lastc = 0, p = target; *p;)
371 if (*p == '!' && (p == target || lastc == '\t'))
373 xmlChar *c;
375 c = p;
376 while (*p)
377 *c++ = *++p;
378 *c = 0;
379 goto again;
382 lastc = *p++;
385 if (!xmlSetProp (n, (xmlChar *) "target", target))
387 xmlFree (target);
388 return GPG_ERR_INV_VALUE;
391 xmlFree (target);
393 if (n->children && !force)
395 fprintf(stderr, _("%s: aborting do to literal child elements (use --force)\n"), filename);
396 return GPG_ERR_CANCELED;
398 else if (n->children)
400 xmlNodePtr tmp = n->children;
402 xmlUnlinkNode (n->children);
403 xmlFreeNodeList (tmp);
407 rc = strip_literals (filename, n->children, force);
408 if (rc)
409 break;
412 return rc;
416 main(int argc, char **argv)
418 gpg_error_t rc;
419 int opt, optindex;
420 struct crypto_s *crypto = NULL;
421 char *outfile = NULL, *infile = NULL, *keyfile = NULL;
422 void *key = NULL;
423 enum {
424 OPT_FORCE,
425 OPT_XML
427 const char *optstring = "vhk:n";
428 int convert = 1;
429 int force = 0;
430 int xml = 0;
431 const struct option longopts[] = {
432 {"force", no_argument, 0, 0},
433 {"xml", no_argument, 0, 0},
434 {"no-convert", no_argument, 0, 'n'},
435 {"keyfile", required_argument, 0, 'k'},
436 {"version", no_argument, 0, 'v'},
437 {"help", no_argument, 0, 'h'},
438 {0, 0, 0, 0}
441 #ifndef DEBUG
442 #ifdef HAVE_SETRLIMIT
443 struct rlimit rl;
445 rl.rlim_cur = rl.rlim_max = 0;
447 if (setrlimit (RLIMIT_CORE, &rl) != 0)
448 err (EXIT_FAILURE, "setrlimit()");
449 #endif
451 #ifdef HAVE_PR_SET_DUMPABLE
452 prctl (PR_SET_DUMPABLE, 0);
453 #endif
454 #endif
456 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
458 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
459 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
460 gpgrt_check_version (NULL));
461 exit (EXIT_FAILURE);
464 gpgrt_init ();
465 //gpgrt_set_alloc_func (xrealloc_gpgrt);
467 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
469 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
470 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
471 gcry_check_version (NULL));
472 exit (EXIT_FAILURE);
475 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
476 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
477 xmlInitMemory ();
478 xmlInitGlobals ();
479 xmlInitParser ();
480 xmlXPathInit ();
482 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
484 switch (opt)
486 case 'n':
487 convert = 0;
488 break;
489 case 'k':
490 keyfile = optarg;
491 break;
492 case 'h':
493 usage (argv[0], EXIT_SUCCESS);
494 break;
495 case 'v':
496 printf (_("%s\n\n"
497 "Copyright (C) 2015, 2016\n"
498 "%s\n"
499 "Released under the terms of the GPL v2. Use at your own risk.\n\n"),
500 PACKAGE_STRING, PACKAGE_BUGREPORT);
501 exit (EXIT_SUCCESS);
502 case 0:
503 switch (optindex)
505 case OPT_FORCE:
506 force = 1;
507 break;
508 case OPT_XML:
509 xml = 1;
510 break;
511 default:
512 usage (argv[0], EXIT_FAILURE);
514 break;
515 default:
516 usage (argv[0], EXIT_FAILURE);
517 break;
521 if (argc - optind != 2)
522 usage (argv[0], EXIT_FAILURE);
524 infile = argv[optind++];
525 outfile = argv[optind];
526 if (strcmp (outfile, "-"))
528 if (access (outfile, R_OK|W_OK) == 0)
530 fprintf(stderr, _("Please remove the existing output file '%s'.\n"),
531 outfile);
532 exit (EXIT_FAILURE);
536 rc = init_client_crypto (&crypto);
537 if (rc)
538 goto fail;
540 if (!xml)
542 rc = decrypt_common (crypto, infile, keyfile);
543 xfree (key);
545 else
547 struct stat st;
548 int fd;
550 fd = open (infile, O_RDONLY);
551 if (fd == -1)
553 rc = gpg_error_from_syserror ();
554 goto fail;
557 if (fstat (fd, &st) == -1)
559 rc = gpg_error_from_syserror ();
560 close (fd);
561 goto fail;
564 crypto->plaintext = gcry_calloc (1, sizeof (char) * st.st_size+1);
565 if (!crypto->plaintext)
567 close (fd);
568 rc = GPG_ERR_ENOMEM;
569 goto fail;
572 crypto->plaintext_len = read (fd, crypto->plaintext, st.st_size);
573 close (fd);
574 if (crypto->plaintext_len != st.st_size)
576 rc = GPG_ERR_UNKNOWN_ERRNO;
577 goto fail;
581 if (!rc)
583 xmlDocPtr doc;
585 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
586 cleanup_crypto (&crypto);
587 if (!rc)
589 xmlChar *buf;
590 int len;
592 FILE *fp = outfile[0] == '-' && outfile[1] == 0 ? stdout
593 : fopen (outfile, "w");
595 if (!fp)
597 rc = gpg_error_from_syserror ();
598 xmlFreeDoc (doc);
599 goto fail;
602 if (convert)
604 xmlNodePtr n = xmlDocGetRootElement (doc);
605 rc = strip_literals (infile, n->children, force);
606 if (rc)
608 xmlFreeDoc (doc);
609 goto fail;
613 xmlDocDumpMemory (doc, &buf, &len);
614 xmlFreeDoc (doc);
615 fprintf (fp, "%s", buf);
616 xmlFree (buf);
617 fclose (fp);
619 else
620 goto fail;
622 else
623 goto fail;
625 cleanup_crypto (&crypto);
626 exit (EXIT_SUCCESS);
628 fail:
629 cleanup_crypto (&crypto);
630 fprintf(stderr, "ERR %u: %s\n", rc, gpg_strerror (rc));
631 exit (EXIT_FAILURE);
634 static gpg_error_t
635 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
636 size_t keylen, void **result, size_t *rlen, uint64_t iterations)
638 gpg_error_t rc;
639 void *tmp;
641 /* Be sure the algorithm is available. */
642 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
643 if (rc)
644 return rc;
646 /* Always allocate enough for a 256-bit key although the algorithms
647 themselves may use less. Fixes SAVE --cipher with a different
648 keylen than the previously saved cipher when cached. */
649 *rlen = 32;
650 tmp = xmalloc (*rlen);
651 if (!tmp)
652 return GPG_ERR_ENOMEM;
654 if (!iterations)
655 iterations = DEFAULT_KDFS2K_ITERATIONS;
657 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
658 salt, salt_len, iterations, *rlen, tmp);
659 if (!rc)
660 *result = tmp;
661 else
662 xfree (tmp);
664 return rc;
668 * Useful for a large amount of data. Rather than doing all of the data in one
669 * iteration do it in chunks. This lets the command be cancelable rather than
670 * waiting for it to complete.
672 #define CRYPTO_BLOCKSIZE(c) (c * 1024)
673 static gpg_error_t
674 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
675 size_t insize, size_t blocksize)
677 gpg_error_t rc = 0;
678 off_t len = CRYPTO_BLOCKSIZE (blocksize);
679 void *p = gcry_malloc (len);
680 off_t total = 0;
682 if (!p)
683 return gpg_error (GPG_ERR_ENOMEM);
685 if (insize < CRYPTO_BLOCKSIZE (blocksize))
686 len = insize;
688 pthread_cleanup_push (gcry_free, p);
690 for (;;)
692 unsigned char *inbuf2 = inbuf + total;
693 unsigned char *tmp;
695 if (len + total > insize)
696 len = blocksize;
698 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
699 if (rc)
700 break;
702 tmp = inbuf + total;
703 memmove (tmp, p, len);
704 total += len;
705 if (total >= insize)
706 break;
708 #ifdef HAVE_PTHREAD_TESTCANCEL
709 pthread_testcancel ();
710 #endif
713 pthread_cleanup_pop (1);
714 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
715 rc = gpg_error (rc);
717 return rc;
720 static void
721 cleanup_cipher (void *arg)
723 gcry_cipher_close ((gcry_cipher_hd_t) arg);
726 /* Decrypt the XML data. For PKI data files the key is retrieved from
727 * gpg-agent and the signature verified. */
728 static gpg_error_t
729 decrypt_data (struct crypto_s *crypto, unsigned char *salted_key,
730 size_t skeylen)
732 gpg_error_t rc = 0;
733 unsigned char *key = salted_key;
734 gcry_cipher_hd_t h = NULL;
735 size_t blocksize, keysize = 0;
736 int algo = cipher_to_gcrypt (crypto->hdr.flags);
737 void *outbuf = NULL;
738 uint64_t n = crypto->hdr.s2k_count;
739 #ifdef WITH_AGENT
740 size_t keylen = skeylen;
741 gcry_sexp_t sig_sexp;
743 if (crypto->hdr.flags & PWMD_FLAG_PKI)
745 rc = agent_extract_key (crypto, &key, &keylen);
746 if (rc)
747 return rc;
749 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
750 if (!sig_sexp)
752 gcry_free (key);
753 return GPG_ERR_BAD_DATA;
756 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
757 crypto->ciphertext_len);
758 gcry_sexp_release (sig_sexp);
760 #endif
762 (void)skeylen;
763 if (!rc)
765 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
766 if (!rc)
768 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
769 &keysize);
770 if (!rc)
772 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
773 &blocksize);
774 if (!rc)
776 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
777 if (!rc)
779 rc = gcry_cipher_setkey (h, key, keysize);
786 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
788 if (!rc)
790 outbuf = gcry_malloc (crypto->hdr.datalen+1);
791 if (!outbuf)
792 rc = GPG_ERR_ENOMEM;
793 else
794 memset (outbuf, 0, crypto->hdr.datalen+1);
797 pthread_cleanup_push (gcry_free, outbuf);
798 #ifdef WITH_AGENT
799 pthread_cleanup_push (gcry_free, key);
800 #endif
802 if (!rc)
804 if (!key)
805 rc = GPG_ERR_INV_PARAMETER;
806 else
808 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
809 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
812 if (!rc && crypto->hdr.version <= 0x03000e)
814 key[0] ^= 1;
815 rc = gcry_cipher_setkey (h, key, keysize);
819 if (!rc && crypto->hdr.version <= 0x03000e)
821 for (n = 0; !rc && n < crypto->hdr.s2k_count; n++)
823 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
824 if (rc)
825 break;
827 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
831 #ifdef WITH_AGENT
832 pthread_cleanup_pop (0);
833 if (crypto->hdr.flags & PWMD_FLAG_PKI)
834 gcry_free (key);
835 else if (key && crypto->hdr.version <= 0x03000e)
836 key[0] ^= 1;
837 #else
838 if (crypto->hdr.version <= 0x03000e)
839 key[0] ^= 1;
840 #endif
841 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
842 pthread_cleanup_pop (1); /* cipher */
843 if (!rc)
845 char buf[] = "<?xml ";
847 if (memcmp (outbuf, buf, sizeof(buf)-1))
849 gcry_free (outbuf);
850 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
853 crypto->plaintext = outbuf;
854 crypto->plaintext_len = crypto->hdr.datalen;
857 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
858 rc = gpg_error (rc);
860 return rc;
863 static gpg_error_t
864 get_passphrase (const char *filename, const char *keyfile, void **r_key,
865 size_t *r_len)
867 char buf[255] = { 0 };
868 struct termios told, tnew;
870 *r_len = 0;
872 if (keyfile)
874 ssize_t len;
875 struct stat st;
876 int fd;
878 fd = open (keyfile, O_RDONLY);
879 if (fd == -1)
880 return gpg_error_from_syserror ();
882 if (fstat (fd, &st) == -1)
884 gpg_error_t rc = gpg_error_from_syserror ();
886 close (fd);
887 return rc;
890 len = read (fd, buf, sizeof (buf));
891 if (len != st.st_size)
893 close (fd);
894 wipememory (buf, 0, sizeof (buf));
895 return gpg_error_from_syserror ();
898 *r_len = st.st_size ? st.st_size : 1;
899 *r_key = xmalloc (*r_len);
900 if (*r_key)
901 memcpy (*r_key, buf, *r_len);
902 wipememory (buf, 0, sizeof (buf));
903 close (fd);
904 return *r_key ? 0 : GPG_ERR_ENOMEM;
907 if (!isatty (STDIN_FILENO))
908 return GPG_ERR_ENOTTY;
910 if (tcgetattr (STDIN_FILENO, &told) == -1)
911 return gpg_error_from_syserror ();
913 memcpy (&tnew, &told, sizeof (struct termios));
914 tnew.c_lflag &= ~(ECHO);
915 tnew.c_lflag |= ICANON | ECHONL;
916 if (tcsetattr (STDIN_FILENO, TCSANOW, &tnew) == -1)
918 int n = errno;
920 tcsetattr (STDIN_FILENO, TCSANOW, &told);
921 return gpg_error_from_errno (n);
924 fprintf(stderr, "Passphrase for '%s': ", filename);
925 if (!fgets (buf, sizeof (buf), stdin))
927 tcsetattr (STDIN_FILENO, TCSANOW, &told);
928 return GPG_ERR_EOF;
931 tcsetattr (STDIN_FILENO, TCSANOW, &told);
933 if (buf[strlen(buf)-1] == '\n')
934 buf[strlen(buf)-1] = 0;
935 *r_len = buf[0] == 0 ? 1 : strlen (buf);
936 *r_key = str_dup (buf);
937 wipememory (buf, 0, sizeof (buf));
938 return 0;
941 /* Common to both PKI and non-PKI files. */
942 static gpg_error_t
943 decrypt_common (struct crypto_s *crypto, const char *filename,
944 const char *keyfile)
946 void *key = NULL;
947 size_t keylen = 0;
948 gpg_error_t rc = read_data_file (filename, crypto);
949 int algo = cipher_to_gcrypt (crypto->hdr.flags);
950 void *skey = NULL;
951 size_t skeysize = 0;
953 if (rc)
954 return rc;
956 rc = get_passphrase (filename, keyfile, &key, &keylen);
957 if (rc)
958 return rc;
960 if (key)// && !IS_PKI (crypto))
962 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
963 keylen, &skey, &skeysize,
964 crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : crypto->hdr.s2k_count);
965 if (rc)
967 xfree (key);
968 return rc;
972 xfree (key);
973 xfree (crypto->filename);
974 crypto->filename = str_dup (filename);
975 rc = decrypt_data (crypto, skey, skeysize);
976 xfree (skey);
977 return rc;
980 static gpg_error_t
981 read_header (file_header_t *hdr, int fd)
983 ssize_t len;
984 uint32_t i;
985 uint64_t n;
987 #ifdef WORDS_BIGENDIAN
988 len = read (fd, &hdr->magic, sizeof(hdr->magic));
989 if (len == -1)
990 goto done;
992 len = read (fd, &hdr->version, sizeof(hdr->version));
993 if (len == -1)
994 goto done;
996 len = read (fd, &hdr->s2k_count, sizeof(hdr->s2k_count));
997 if (len == -1)
998 goto done;
1000 len = read (fd, &hdr->flags, sizeof(hdr->flags));
1001 if (len == -1)
1002 goto done;
1004 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1005 if (len == -1)
1006 goto done;
1008 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1009 if (len == -1)
1010 goto done;
1012 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
1013 if (len == -1)
1014 goto done;
1015 #else
1016 len = read (fd, &hdr->magic, sizeof(hdr->magic));
1017 if (len == -1)
1018 goto done;
1020 len = read (fd, &i, sizeof(hdr->version));
1021 if (len == -1)
1022 goto done;
1023 hdr->version = ntohl (i);
1025 len = read (fd, &n, sizeof(hdr->s2k_count));
1026 if (len == -1)
1027 goto done;
1028 hdr->s2k_count = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1030 len = read (fd, &n, sizeof(hdr->flags));
1031 if (len == -1)
1032 goto done;
1033 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1035 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1036 if (len == -1)
1037 goto done;
1039 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1040 if (len == -1)
1041 goto done;
1043 len = read (fd, &i, sizeof(hdr->datalen));
1044 if (len == -1)
1045 goto done;
1046 hdr->datalen = ntohl (i);
1047 #endif
1049 done:
1050 return len == -1 ? gpg_error_from_errno (errno) : 0;
1053 /* Read the header of a data file to determine cipher and other. The
1054 * header is stored big endian in the file and is converted to little
1055 * endian when needed. */
1056 static gpg_error_t
1057 read_data_header (const char *filename, file_header_t * rhdr,
1058 struct stat *rst, int *rfd)
1060 gpg_error_t rc = 0;
1061 struct stat st;
1062 file_header_t hdr;
1063 int fd;
1065 fd = open (filename, O_RDONLY);
1066 if (fd == -1)
1067 return gpg_error_from_syserror ();
1069 if (fstat (fd, &st) == -1)
1071 rc = gpg_error_from_syserror ();
1072 close (fd);
1073 return rc;
1076 rc = read_header (&hdr, fd);
1077 if (!rc && memcmp (hdr.magic, crypto_magic, sizeof (hdr.magic)))
1078 rc = GPG_ERR_BAD_DATA;
1079 else if (!rc && hdr.version < 0x030000)
1080 rc = GPG_ERR_UNKNOWN_VERSION;
1082 if (rc)
1083 close (fd);
1084 else
1086 if (rhdr)
1087 *rhdr = hdr;
1088 if (rst)
1089 *rst = st;
1090 if (rfd)
1091 *rfd = fd;
1092 else
1093 close (fd);
1096 return gpg_error (rc);
1099 static gpg_error_t
1100 read_data_file (const char *filename, struct crypto_s * crypto)
1102 int fd;
1103 gpg_error_t rc = 0;
1104 size_t len, rlen;
1105 char *buf = NULL;
1106 struct stat st;
1108 if (!filename)
1109 return GPG_ERR_INV_PARAMETER;
1111 cleanup_crypto_stage1 (crypto);
1112 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
1113 if (rc)
1114 return gpg_error (rc);
1116 crypto->ciphertext_len = crypto->hdr.datalen;
1117 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
1118 if (!crypto->ciphertext)
1120 rc = GPG_ERR_ENOMEM;
1121 goto done;
1124 /* The keygrips for PKI files are stored after the header. They are
1125 * stored in the file to let file(1) magic(5) show the grips. */
1126 if (crypto->hdr.flags & PWMD_FLAG_PKI)
1128 rlen = read (fd, crypto->grip, 20);
1129 if (rlen != 20)
1131 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1132 goto done;
1135 rlen = read (fd, crypto->sign_grip, 20);
1136 if (rlen != 20)
1138 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1139 goto done;
1143 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
1144 if (len != crypto->hdr.datalen)
1146 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1147 goto done;
1150 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
1151 goto done;
1153 if (!use_agent)
1155 rc = GPG_ERR_NOT_IMPLEMENTED;
1156 goto done;
1159 #ifdef WITH_AGENT
1160 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
1161 buf = xmalloc (len);
1162 if (!buf)
1164 rc = GPG_ERR_ENOMEM;
1165 goto done;
1168 /* Remaining data file bytes are the encrypted key and XML. */
1169 rlen = read (fd, buf, len);
1170 if (rlen != len)
1172 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1173 goto done;
1176 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
1177 if (rc)
1178 goto done;
1180 if (crypto->pkey_sexp)
1181 gcry_sexp_release (crypto->pkey_sexp);
1183 if (crypto->sigpkey_sexp)
1184 gcry_sexp_release (crypto->sigpkey_sexp);
1186 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
1187 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
1188 if (!rc)
1189 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
1190 #endif
1192 done:
1193 close (fd);
1194 xfree (buf);
1195 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
1196 rc = gpg_error (rc);
1198 return rc;
1201 static void
1202 cleanup_save (struct save_s *save)
1204 if (!save)
1205 return;
1207 #ifdef WITH_AGENT
1208 if (save->pkey)
1209 gcry_sexp_release (save->pkey);
1211 if (save->sigpkey)
1212 gcry_sexp_release (save->sigpkey);
1213 #endif
1215 memset (save, 0, sizeof (struct save_s));
1218 /* Keep the agent ctx to retain pinentry options which will be freed in
1219 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
1220 static void
1221 cleanup_crypto_stage1 (struct crypto_s *cr)
1223 if (!cr)
1224 return;
1226 cleanup_save (&cr->save);
1228 #ifdef WITH_AGENT
1229 if (cr->ciphertext_sexp)
1230 gcry_sexp_release (cr->ciphertext_sexp);
1232 cr->ciphertext_sexp = NULL;
1233 #endif
1235 gcry_free (cr->plaintext);
1236 xfree (cr->ciphertext);
1237 xfree (cr->filename);
1238 cr->filename = NULL;
1239 cr->ciphertext = NULL;
1240 cr->ciphertext_len = 0;
1241 cr->plaintext = NULL;
1242 cr->plaintext_len = 0;
1245 static void
1246 cleanup_crypto_stage2 (struct crypto_s *cr)
1248 if (!cr)
1249 return;
1251 cleanup_crypto_stage1 (cr);
1252 set_header_defaults (&cr->hdr);
1255 static void
1256 cleanup_crypto (struct crypto_s **c)
1258 struct crypto_s *cr = *c;
1260 if (!cr)
1261 return;
1263 cleanup_crypto_stage2 (cr);
1265 #ifdef WITH_AGENT
1266 if (cr->pkey_sexp)
1267 gcry_sexp_release (cr->pkey_sexp);
1269 if (cr->sigpkey_sexp)
1270 gcry_sexp_release (cr->sigpkey_sexp);
1272 if (cr->agent)
1273 cleanup_agent (cr->agent);
1274 #endif
1276 xfree (cr);
1277 *c = NULL;
1280 /* Sets the default cipher values for new files. */
1281 static void
1282 set_header_defaults (file_header_t * hdr)
1284 const char *s = "aes256";
1285 int flags = cipher_string_to_cipher (s);
1287 memset (hdr, 0, sizeof (file_header_t));
1288 memcpy (hdr->magic, crypto_magic, sizeof (hdr->magic));
1289 if (flags == -1)
1290 fprintf(stderr, _("Invalid 'cipher' in configuration file. Using a default of aes256."));
1292 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
1293 hdr->version = VERSION_HEX;
1295 #ifdef WITH_AGENT
1296 if (use_agent)
1297 hdr->flags |= PWMD_FLAG_PKI;
1298 #endif