Update copyright.
[pwmd.git] / src / pwmd-dump.c
blobfc387aeaeb7e844d98452420937988ad0cdbb963
1 /*
2 Copyright (C) 2015-2018 Ben Kibbey <bjk@luxsci.net>
4 This file is part of pwmd.
6 Pwmd is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 2 of the License, or
9 (at your option) any later version.
11 Pwmd 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
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <stdint.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <sys/resource.h>
32 #include <errno.h>
33 #include <arpa/inet.h>
34 #include <libxml/tree.h>
35 #include <libxml/parser.h>
36 #include <libxml/xpath.h>
37 #include <err.h>
38 #include <termios.h>
40 #include "pwmd-error.h"
41 #include <gcrypt.h>
43 #ifdef HAVE_SYS_PRCTL_H
44 #include <sys/prctl.h>
45 #endif
47 #ifdef ENABLE_NLS
48 #ifdef HAVE_LOCALE_H
49 #include <locale.h>
50 #endif
51 #endif
53 #ifndef _
54 #include "gettext.h"
55 #define _(msgid) gettext(msgid)
56 #endif
58 #ifdef HAVE_GETOPT_LONG
59 #ifdef HAVE_GETOPT_H
60 #include <getopt.h>
61 #endif
62 #else
63 #include "getopt_long.h"
64 #endif
66 #include "util-string.h"
67 #include "mem.h"
69 #if 0
70 #ifdef WITH_AGENT
71 #include "agent.h"
72 #endif
73 #endif
75 #define PWMD_CIPHER_OFFSET (1)
76 #define PWMD_CIPHER(n) (PWMD_CIPHER_OFFSET << n)
77 #define PWMD_CIPHER_AES128 PWMD_CIPHER (0)
78 #define PWMD_CIPHER_AES192 PWMD_CIPHER (1)
79 #define PWMD_CIPHER_AES256 PWMD_CIPHER (2)
80 #define PWMD_CIPHER_SERPENT128 PWMD_CIPHER (3)
81 #define PWMD_CIPHER_SERPENT192 PWMD_CIPHER (4)
82 #define PWMD_CIPHER_SERPENT256 PWMD_CIPHER (5)
83 #define PWMD_CIPHER_CAMELLIA128 PWMD_CIPHER (6)
84 #define PWMD_CIPHER_CAMELLIA192 PWMD_CIPHER (7)
85 #define PWMD_CIPHER_CAMELLIA256 PWMD_CIPHER (8)
86 #define PWMD_CIPHER_3DES PWMD_CIPHER (9)
87 #define PWMD_CIPHER_CAST5 PWMD_CIPHER (10)
88 #define PWMD_CIPHER_BLOWFISH PWMD_CIPHER (11)
89 #define PWMD_CIPHER_TWOFISH PWMD_CIPHER (12)
90 #define PWMD_CIPHER_TWOFISH128 PWMD_CIPHER (13)
92 #define PWMD_FLAG_OFFSET (PWMD_CIPHER_OFFSET << 15)
93 #define PWMD_FLAG(n) (PWMD_FLAG_OFFSET << n)
94 #define PWMD_FLAG_PKI PWMD_FLAG (1)
95 #define PWMD_FLAG_NO_PASSPHRASE PWMD_FLAG (2)
97 #define KEYSIZE 32
99 typedef struct
101 uint8_t magic[5];
102 uint32_t version;
103 uint64_t s2k_count;
104 uint64_t flags;
105 uint8_t iv[16];
106 uint8_t salt[8];
107 uint32_t datalen; /* of the encrypted xml */
108 } __attribute__ ((packed)) file_header_t;
110 struct save_s
112 gcry_sexp_t pkey; /* SAVE --keygrip */
113 gcry_sexp_t sigpkey; /* SAVE --sign-keygrip */
114 file_header_t hdr;
117 struct crypto_s
119 //assuan_context_t client_ctx;
120 #ifdef WITH_AGENT
121 struct agent_s *agent;
122 #endif
123 struct save_s save;
124 gcry_sexp_t pkey_sexp;
125 unsigned char grip[20];
126 gcry_sexp_t sigpkey_sexp;
127 unsigned char sign_grip[20];
128 gcry_sexp_t ciphertext_sexp;
129 void *ciphertext;
130 size_t ciphertext_len;
131 void *plaintext;
132 size_t plaintext_len;
133 file_header_t hdr;
134 char *filename; /* the currently opened data file */
137 #define DEFAULT_KDFS2K_ITERATIONS 5000000
138 #define COMPAT_KDFS2K_ITERATIONS 1000
140 const char *reserved_attributes[] = {
141 "_name", "_mtime", "_ctime", "_acl", "target",
142 NULL
144 static unsigned char crypto_magic[5] = "\177PWMD";
145 static int use_agent;
147 static void set_header_defaults (file_header_t * hdr);
148 static gpg_error_t decrypt_common (struct crypto_s *crypto,
149 const char *filename, const char *keyfile);
150 static gpg_error_t read_data_file (const char *filename,
151 struct crypto_s *crypto);
152 static void cleanup_crypto_stage1 (struct crypto_s *cr);
153 static void cleanup_crypto (struct crypto_s **c);
155 static int
156 cipher_to_gcrypt (int flags)
158 if (flags < 0)
159 return flags;
161 if (flags & PWMD_CIPHER_AES128)
162 return GCRY_CIPHER_AES128;
163 else if (flags & PWMD_CIPHER_AES192)
164 return GCRY_CIPHER_AES192;
165 else if (flags & PWMD_CIPHER_AES256)
166 return GCRY_CIPHER_AES256;
167 else if (flags & PWMD_CIPHER_SERPENT128)
168 return GCRY_CIPHER_SERPENT128;
169 else if (flags & PWMD_CIPHER_SERPENT192)
170 return GCRY_CIPHER_SERPENT192;
171 else if (flags & PWMD_CIPHER_SERPENT256)
172 return GCRY_CIPHER_SERPENT256;
173 else if (flags & PWMD_CIPHER_CAMELLIA128)
174 return GCRY_CIPHER_CAMELLIA128;
175 else if (flags & PWMD_CIPHER_CAMELLIA192)
176 return GCRY_CIPHER_CAMELLIA192;
177 else if (flags & PWMD_CIPHER_CAMELLIA256)
178 return GCRY_CIPHER_CAMELLIA256;
179 else if (flags & PWMD_CIPHER_BLOWFISH)
180 return GCRY_CIPHER_BLOWFISH;
181 else if (flags & PWMD_CIPHER_3DES)
182 return GCRY_CIPHER_3DES;
183 else if (flags & PWMD_CIPHER_CAST5)
184 return GCRY_CIPHER_CAST5;
185 else if (flags & PWMD_CIPHER_TWOFISH)
186 return GCRY_CIPHER_TWOFISH;
187 else if (flags & PWMD_CIPHER_TWOFISH128)
188 return GCRY_CIPHER_TWOFISH128;
190 return -1;
193 static int
194 cipher_string_to_cipher (const char *str)
196 int flags = 0;
198 if (!strcasecmp (str, "aes128"))
199 flags = PWMD_CIPHER_AES128;
200 else if (!strcasecmp (str, "aes192"))
201 flags = PWMD_CIPHER_AES192;
202 else if (!strcasecmp (str, "aes256"))
203 flags = PWMD_CIPHER_AES256;
204 else if (!strcasecmp (str, "serpent128"))
205 flags = PWMD_CIPHER_SERPENT128;
206 else if (!strcasecmp (str, "serpent192"))
207 flags = PWMD_CIPHER_SERPENT192;
208 else if (!strcasecmp (str, "serpent256"))
209 flags = PWMD_CIPHER_SERPENT256;
210 else if (!strcasecmp (str, "camellia128"))
211 flags = PWMD_CIPHER_CAMELLIA128;
212 else if (!strcasecmp (str, "camellia192"))
213 flags = PWMD_CIPHER_CAMELLIA192;
214 else if (!strcasecmp (str, "camellia256"))
215 flags = PWMD_CIPHER_CAMELLIA256;
216 else if (!strcasecmp (str, "blowfish"))
217 flags = PWMD_CIPHER_BLOWFISH;
218 else if (!strcasecmp (str, "cast5"))
219 flags = PWMD_CIPHER_CAST5;
220 else if (!strcasecmp (str, "3des"))
221 flags = PWMD_CIPHER_3DES;
222 else if (!strcasecmp (str, "twofish256"))
223 flags = PWMD_CIPHER_TWOFISH;
224 else if (!strcasecmp (str, "twofish128"))
225 flags = PWMD_CIPHER_TWOFISH128;
226 else
227 return -1;
229 return flags;
232 static void
233 usage (const char *pn, int rc)
235 fprintf(rc == EXIT_SUCCESS ? stdout : stderr,
236 "%s [-hvn] [--force] [-k <filename>] [--xml] <infile> <outfile>\n"
237 " --no-convert, -n don't discard data for elements with targets\n"
238 " --force don't abort when converting\n"
239 " --xml read a raw pwmd XML document\n"
240 " --keyfile, -k file containing the passphrase to use for decryption\n"
241 " --help\n"
242 " --version\n\n"
243 "Use - as <outfile> to write to standard output.\n",
244 pn);
245 exit (rc);
248 static gpg_error_t
249 init_client_crypto (struct crypto_s **crypto)
251 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
252 gpg_error_t rc;
254 if (!new)
256 rc = GPG_ERR_ENOMEM;
257 return rc;
260 #ifdef WITH_AGENT
261 if (use_agent)
263 rc = agent_init (&new->agent);
264 if (!rc)
266 rc = send_agent_common_options (new->agent);
267 if (!rc)
268 rc = agent_set_pinentry_options (new->agent);
271 if (rc)
273 cleanup_agent (new->agent);
274 xfree (new);
275 return rc;
278 #endif
280 set_header_defaults (&new->hdr);
281 *crypto = new;
282 return 0;
285 static gpg_error_t
286 parse_doc (const char *xml, size_t len, xmlDocPtr *result)
288 xmlDocPtr doc;
290 xmlResetLastError ();
291 doc = xmlReadMemory (xml, len, NULL, "UTF-8", XML_PARSE_NOBLANKS);
292 if (!doc && xmlGetLastError ())
293 return GPG_ERR_BAD_DATA;
295 *result = doc;
296 return !doc ? GPG_ERR_ENOMEM : 0;
299 static xmlChar *
300 xml_attribute_value (xmlNodePtr n, xmlChar * attr)
302 xmlAttrPtr a = xmlHasProp (n, attr);
304 if (!a)
305 return NULL;
307 if (!a->children || !a->children->content)
308 return NULL;
310 return xmlGetProp (n, attr);
313 static int
314 xml_reserved_attribute (const char *name)
316 int i;
318 for (i = 0; reserved_attributes[i]; i++)
320 if (!strcmp (name, reserved_attributes[i]))
321 return 1;
324 return 0;
326 static void
327 remove_non_reserved_attributes (xmlNodePtr n)
329 xmlAttrPtr a;
331 for (a = n->properties; a; a = a->next)
333 if (xml_reserved_attribute ((char *)a->name))
334 continue;
336 xmlRemoveProp (a);
340 static gpg_error_t
341 strip_literals (const char *filename, xmlNodePtr n, int force)
343 gpg_error_t rc = 0;
345 for (; n; n = n->next)
347 xmlChar *target;
349 if (n->type != XML_ELEMENT_NODE)
350 continue;
352 if (!xmlStrEqual (n->name, (xmlChar *) "element"))
354 xmlNodePtr tmp = n->next;
356 xmlUnlinkNode (n);
357 xmlFreeNodeList (n);
358 return strip_literals (filename, tmp, force);
361 target = xml_attribute_value (n, (xmlChar *)"target");
362 if (target)
364 xmlChar lastc = 0, *p;
366 remove_non_reserved_attributes (n);
367 again:
368 for (lastc = 0, p = target; *p;)
370 if (*p == '!' && (p == target || lastc == '\t'))
372 xmlChar *c;
374 c = p;
375 while (*p)
376 *c++ = *++p;
377 *c = 0;
378 goto again;
381 lastc = *p++;
384 if (!xmlSetProp (n, (xmlChar *) "target", target))
386 xmlFree (target);
387 return GPG_ERR_INV_VALUE;
390 xmlFree (target);
392 if (n->children && !force)
394 fprintf(stderr, _("%s: aborting do to literal child elements (use --force)\n"), filename);
395 return GPG_ERR_CANCELED;
397 else if (n->children)
399 xmlNodePtr tmp = n->children;
401 xmlUnlinkNode (n->children);
402 xmlFreeNodeList (tmp);
406 rc = strip_literals (filename, n->children, force);
407 if (rc)
408 break;
411 return rc;
415 main(int argc, char **argv)
417 gpg_error_t rc;
418 int opt, optindex;
419 struct crypto_s *crypto = NULL;
420 char *outfile = NULL, *infile = NULL, *keyfile = NULL;
421 void *key = NULL;
422 enum {
423 OPT_FORCE,
424 OPT_XML
426 const char *optstring = "vhk:n";
427 int convert = 1;
428 int force = 0;
429 int xml = 0;
430 const struct option longopts[] = {
431 {"force", no_argument, 0, 0},
432 {"xml", no_argument, 0, 0},
433 {"no-convert", no_argument, 0, 'n'},
434 {"keyfile", required_argument, 0, 'k'},
435 {"version", no_argument, 0, 'v'},
436 {"help", no_argument, 0, 'h'},
437 {0, 0, 0, 0}
440 #ifndef DEBUG
441 #ifdef HAVE_SETRLIMIT
442 struct rlimit rl;
444 rl.rlim_cur = rl.rlim_max = 0;
446 if (setrlimit (RLIMIT_CORE, &rl) != 0)
447 err (EXIT_FAILURE, "setrlimit()");
448 #endif
450 #ifdef HAVE_PR_SET_DUMPABLE
451 prctl (PR_SET_DUMPABLE, 0);
452 #endif
453 #endif
455 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
457 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
458 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
459 gpgrt_check_version (NULL));
460 exit (EXIT_FAILURE);
463 gpgrt_init ();
464 //gpgrt_set_alloc_func (xrealloc_gpgrt);
466 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
468 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
469 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
470 gcry_check_version (NULL));
471 exit (EXIT_FAILURE);
474 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
475 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
476 xmlInitMemory ();
477 xmlInitGlobals ();
478 xmlInitParser ();
479 xmlXPathInit ();
481 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
483 switch (opt)
485 case 'n':
486 convert = 0;
487 break;
488 case 'k':
489 keyfile = optarg;
490 break;
491 case 'h':
492 usage (argv[0], EXIT_SUCCESS);
493 break;
494 case 'v':
495 printf (_("%s\n\n"
496 "Copyright (C) 2015-2018\n"
497 "%s\n"
498 "Released under the terms of the GPL v2. Use at your own risk.\n\n"),
499 PACKAGE_STRING, PACKAGE_BUGREPORT);
500 exit (EXIT_SUCCESS);
501 case 0:
502 switch (optindex)
504 case OPT_FORCE:
505 force = 1;
506 break;
507 case OPT_XML:
508 xml = 1;
509 break;
510 default:
511 usage (argv[0], EXIT_FAILURE);
513 break;
514 default:
515 usage (argv[0], EXIT_FAILURE);
516 break;
520 if (argc - optind != 2)
521 usage (argv[0], EXIT_FAILURE);
523 infile = argv[optind++];
524 outfile = argv[optind];
525 if (strcmp (outfile, "-"))
527 if (access (outfile, R_OK|W_OK) == 0)
529 fprintf(stderr, _("Please remove the existing output file '%s'.\n"),
530 outfile);
531 exit (EXIT_FAILURE);
535 rc = init_client_crypto (&crypto);
536 if (rc)
537 goto fail;
539 if (!xml)
541 rc = decrypt_common (crypto, infile, keyfile);
542 xfree (key);
544 else
546 struct stat st;
547 int fd;
549 fd = open (infile, O_RDONLY);
550 if (fd == -1)
552 rc = gpg_error_from_syserror ();
553 goto fail;
556 if (fstat (fd, &st) == -1)
558 rc = gpg_error_from_syserror ();
559 close (fd);
560 goto fail;
563 crypto->plaintext = gcry_calloc (1, sizeof (char) * st.st_size+1);
564 if (!crypto->plaintext)
566 close (fd);
567 rc = GPG_ERR_ENOMEM;
568 goto fail;
571 crypto->plaintext_len = read (fd, crypto->plaintext, st.st_size);
572 close (fd);
573 if (crypto->plaintext_len != st.st_size)
575 rc = GPG_ERR_UNKNOWN_ERRNO;
576 goto fail;
580 if (!rc)
582 xmlDocPtr doc;
584 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
585 cleanup_crypto (&crypto);
586 if (!rc)
588 xmlChar *buf;
589 int len;
591 FILE *fp = outfile[0] == '-' && outfile[1] == 0 ? stdout
592 : fopen (outfile, "w");
594 if (!fp)
596 rc = gpg_error_from_syserror ();
597 xmlFreeDoc (doc);
598 goto fail;
601 if (convert)
603 xmlNodePtr n = xmlDocGetRootElement (doc);
604 rc = strip_literals (infile, n->children, force);
605 if (rc)
607 xmlFreeDoc (doc);
608 goto fail;
612 xmlDocDumpMemory (doc, &buf, &len);
613 xmlFreeDoc (doc);
614 fprintf (fp, "%s", buf);
615 xmlFree (buf);
616 fclose (fp);
618 else
619 goto fail;
621 else
622 goto fail;
624 cleanup_crypto (&crypto);
625 exit (EXIT_SUCCESS);
627 fail:
628 cleanup_crypto (&crypto);
629 fprintf(stderr, "ERR %u: %s\n", rc, gpg_strerror (rc));
630 exit (EXIT_FAILURE);
633 static gpg_error_t
634 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
635 size_t keylen, void **result, size_t *rlen, uint64_t iterations)
637 gpg_error_t rc;
638 void *tmp;
640 /* Be sure the algorithm is available. */
641 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
642 if (rc)
643 return rc;
645 /* Always allocate enough for a 256-bit key although the algorithms
646 themselves may use less. Fixes SAVE --cipher with a different
647 keylen than the previously saved cipher when cached. */
648 *rlen = 32;
649 tmp = xmalloc (*rlen);
650 if (!tmp)
651 return GPG_ERR_ENOMEM;
653 if (!iterations)
654 iterations = DEFAULT_KDFS2K_ITERATIONS;
656 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
657 salt, salt_len, iterations, *rlen, tmp);
658 if (!rc)
659 *result = tmp;
660 else
661 xfree (tmp);
663 return rc;
667 * Useful for a large amount of data. Rather than doing all of the data in one
668 * iteration do it in chunks. This lets the command be cancelable rather than
669 * waiting for it to complete.
671 #define CRYPTO_BLOCKSIZE(c) (c * 1024)
672 static gpg_error_t
673 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
674 size_t insize, size_t blocksize)
676 gpg_error_t rc = 0;
677 off_t len = CRYPTO_BLOCKSIZE (blocksize);
678 void *p = gcry_malloc (len);
679 off_t total = 0;
681 if (!p)
682 return gpg_error (GPG_ERR_ENOMEM);
684 if (insize < CRYPTO_BLOCKSIZE (blocksize))
685 len = insize;
687 pthread_cleanup_push (gcry_free, p);
689 for (;;)
691 unsigned char *inbuf2 = inbuf + total;
692 unsigned char *tmp;
694 if (len + total > insize)
695 len = blocksize;
697 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
698 if (rc)
699 break;
701 tmp = inbuf + total;
702 memmove (tmp, p, len);
703 total += len;
704 if (total >= insize)
705 break;
707 #ifdef HAVE_PTHREAD_TESTCANCEL
708 pthread_testcancel ();
709 #endif
712 pthread_cleanup_pop (1);
713 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
714 rc = gpg_error (rc);
716 return rc;
719 static void
720 cleanup_cipher (void *arg)
722 gcry_cipher_close ((gcry_cipher_hd_t) arg);
725 /* Decrypt the XML data. For PKI data files the key is retrieved from
726 * gpg-agent and the signature verified. */
727 static gpg_error_t
728 decrypt_data (struct crypto_s *crypto, unsigned char *salted_key,
729 size_t skeylen)
731 gpg_error_t rc = 0;
732 unsigned char *key = salted_key;
733 gcry_cipher_hd_t h = NULL;
734 size_t blocksize, keysize = 0;
735 int algo = cipher_to_gcrypt (crypto->hdr.flags);
736 void *outbuf = NULL;
737 uint64_t n;
738 #ifdef WITH_AGENT
739 size_t keylen = skeylen;
740 gcry_sexp_t sig_sexp;
742 if (crypto->hdr.flags & PWMD_FLAG_PKI)
744 rc = agent_extract_key (crypto, &key, &keylen);
745 if (rc)
746 return rc;
748 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
749 if (!sig_sexp)
751 gcry_free (key);
752 return GPG_ERR_BAD_DATA;
755 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
756 crypto->ciphertext_len);
757 gcry_sexp_release (sig_sexp);
759 #endif
761 (void)skeylen;
762 if (!rc)
764 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
765 if (!rc)
767 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
768 &keysize);
769 if (!rc)
771 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
772 &blocksize);
773 if (!rc)
775 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
776 if (!rc)
778 rc = gcry_cipher_setkey (h, key, keysize);
785 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
787 if (!rc)
789 outbuf = gcry_malloc (crypto->hdr.datalen+1);
790 if (!outbuf)
791 rc = GPG_ERR_ENOMEM;
792 else
793 memset (outbuf, 0, crypto->hdr.datalen+1);
796 pthread_cleanup_push (gcry_free, outbuf);
797 #ifdef WITH_AGENT
798 pthread_cleanup_push (gcry_free, key);
799 #endif
801 if (!rc)
803 if (!key)
804 rc = GPG_ERR_INV_PARAMETER;
805 else
807 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
808 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
811 if (!rc && crypto->hdr.version <= 0x03000e)
813 key[0] ^= 1;
814 rc = gcry_cipher_setkey (h, key, keysize);
818 if (!rc && crypto->hdr.version <= 0x03000e)
820 for (n = 0; !rc && n < crypto->hdr.s2k_count; n++)
822 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
823 if (rc)
824 break;
826 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
830 #ifdef WITH_AGENT
831 pthread_cleanup_pop (0);
832 if (crypto->hdr.flags & PWMD_FLAG_PKI)
833 gcry_free (key);
834 else if (key && crypto->hdr.version <= 0x03000e)
835 key[0] ^= 1;
836 #else
837 if (crypto->hdr.version <= 0x03000e && key)
838 key[0] ^= 1;
839 #endif
840 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
841 pthread_cleanup_pop (1); /* cipher */
842 if (!rc)
844 char buf[] = "<?xml ";
846 if (memcmp (outbuf, buf, sizeof(buf)-1))
848 gcry_free (outbuf);
849 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
852 crypto->plaintext = outbuf;
853 crypto->plaintext_len = crypto->hdr.datalen;
856 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
857 rc = gpg_error (rc);
859 return rc;
862 static gpg_error_t
863 get_passphrase (const char *filename, const char *keyfile, void **r_key,
864 size_t *r_len)
866 char buf[255] = { 0 };
867 struct termios told, tnew;
869 *r_len = 0;
871 if (keyfile)
873 ssize_t len;
874 struct stat st;
875 int fd;
877 fd = open (keyfile, O_RDONLY);
878 if (fd == -1)
879 return gpg_error_from_syserror ();
881 if (fstat (fd, &st) == -1)
883 gpg_error_t rc = gpg_error_from_syserror ();
885 close (fd);
886 return rc;
889 len = read (fd, buf, sizeof (buf));
890 if (len != st.st_size)
892 close (fd);
893 wipememory (buf, 0, sizeof (buf));
894 return gpg_error_from_syserror ();
897 *r_len = st.st_size ? st.st_size : 1;
898 *r_key = xmalloc (*r_len);
899 if (*r_key)
900 memcpy (*r_key, buf, *r_len);
901 wipememory (buf, 0, sizeof (buf));
902 close (fd);
903 return *r_key ? 0 : GPG_ERR_ENOMEM;
906 if (!isatty (STDIN_FILENO))
907 return GPG_ERR_ENOTTY;
909 if (tcgetattr (STDIN_FILENO, &told) == -1)
910 return gpg_error_from_syserror ();
912 memcpy (&tnew, &told, sizeof (struct termios));
913 tnew.c_lflag &= ~(ECHO);
914 tnew.c_lflag |= ICANON | ECHONL;
915 if (tcsetattr (STDIN_FILENO, TCSANOW, &tnew) == -1)
917 int n = errno;
919 tcsetattr (STDIN_FILENO, TCSANOW, &told);
920 return gpg_error_from_errno (n);
923 fprintf(stderr, "Passphrase for '%s': ", filename);
924 if (!fgets (buf, sizeof (buf), stdin))
926 tcsetattr (STDIN_FILENO, TCSANOW, &told);
927 return GPG_ERR_EOF;
930 tcsetattr (STDIN_FILENO, TCSANOW, &told);
932 if (buf[strlen(buf)-1] == '\n')
933 buf[strlen(buf)-1] = 0;
934 *r_len = buf[0] == 0 ? 1 : strlen (buf);
935 *r_key = str_dup (buf);
936 wipememory (buf, 0, sizeof (buf));
937 return 0;
940 /* Common to both PKI and non-PKI files. */
941 static gpg_error_t
942 decrypt_common (struct crypto_s *crypto, const char *filename,
943 const char *keyfile)
945 void *key = NULL;
946 size_t keylen = 0;
947 gpg_error_t rc = read_data_file (filename, crypto);
948 int algo = cipher_to_gcrypt (crypto->hdr.flags);
949 void *skey = NULL;
950 size_t skeysize = 0;
952 if (rc)
953 return rc;
955 rc = get_passphrase (filename, keyfile, &key, &keylen);
956 if (rc)
957 return rc;
959 if (key)// && !IS_PKI (crypto))
961 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
962 keylen, &skey, &skeysize,
963 crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : crypto->hdr.s2k_count);
964 if (rc)
966 xfree (key);
967 return rc;
971 xfree (key);
972 xfree (crypto->filename);
973 crypto->filename = str_dup (filename);
974 rc = decrypt_data (crypto, skey, skeysize);
975 xfree (skey);
976 return rc;
979 static gpg_error_t
980 read_header (file_header_t *hdr, int fd)
982 ssize_t len;
983 uint32_t i;
984 uint64_t n;
986 #ifdef WORDS_BIGENDIAN
987 len = read (fd, &hdr->magic, sizeof(hdr->magic));
988 if (len == -1)
989 goto done;
991 len = read (fd, &hdr->version, sizeof(hdr->version));
992 if (len == -1)
993 goto done;
995 len = read (fd, &hdr->s2k_count, sizeof(hdr->s2k_count));
996 if (len == -1)
997 goto done;
999 len = read (fd, &hdr->flags, sizeof(hdr->flags));
1000 if (len == -1)
1001 goto done;
1003 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1004 if (len == -1)
1005 goto done;
1007 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1008 if (len == -1)
1009 goto done;
1011 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
1012 if (len == -1)
1013 goto done;
1014 #else
1015 len = read (fd, &hdr->magic, sizeof(hdr->magic));
1016 if (len == -1)
1017 goto done;
1019 len = read (fd, &i, sizeof(hdr->version));
1020 if (len == -1)
1021 goto done;
1022 hdr->version = ntohl (i);
1024 len = read (fd, &n, sizeof(hdr->s2k_count));
1025 if (len == -1)
1026 goto done;
1027 hdr->s2k_count = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1029 len = read (fd, &n, sizeof(hdr->flags));
1030 if (len == -1)
1031 goto done;
1032 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1034 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1035 if (len == -1)
1036 goto done;
1038 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1039 if (len == -1)
1040 goto done;
1042 len = read (fd, &i, sizeof(hdr->datalen));
1043 if (len == -1)
1044 goto done;
1045 hdr->datalen = ntohl (i);
1046 #endif
1048 done:
1049 return len == -1 ? gpg_error_from_errno (errno) : 0;
1052 /* Read the header of a data file to determine cipher and other. The
1053 * header is stored big endian in the file and is converted to little
1054 * endian when needed. */
1055 static gpg_error_t
1056 read_data_header (const char *filename, file_header_t * rhdr,
1057 struct stat *rst, int *rfd)
1059 gpg_error_t rc = 0;
1060 struct stat st;
1061 file_header_t hdr;
1062 int fd;
1064 fd = open (filename, O_RDONLY);
1065 if (fd == -1)
1066 return gpg_error_from_syserror ();
1068 if (fstat (fd, &st) == -1)
1070 rc = gpg_error_from_syserror ();
1071 close (fd);
1072 return rc;
1075 rc = read_header (&hdr, fd);
1076 if (!rc && memcmp (hdr.magic, crypto_magic, sizeof (hdr.magic)))
1077 rc = GPG_ERR_BAD_DATA;
1078 else if (!rc && hdr.version < 0x030000)
1079 rc = GPG_ERR_UNKNOWN_VERSION;
1081 if (rc)
1082 close (fd);
1083 else
1085 if (rhdr)
1086 *rhdr = hdr;
1087 if (rst)
1088 *rst = st;
1089 if (rfd)
1090 *rfd = fd;
1091 else
1092 close (fd);
1095 return gpg_error (rc);
1098 static gpg_error_t
1099 read_data_file (const char *filename, struct crypto_s * crypto)
1101 int fd;
1102 gpg_error_t rc = 0;
1103 size_t len, rlen;
1104 char *buf = NULL;
1105 struct stat st;
1107 if (!filename)
1108 return GPG_ERR_INV_PARAMETER;
1110 cleanup_crypto_stage1 (crypto);
1111 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
1112 if (rc)
1113 return gpg_error (rc);
1115 crypto->ciphertext_len = crypto->hdr.datalen;
1116 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
1117 if (!crypto->ciphertext)
1119 rc = GPG_ERR_ENOMEM;
1120 goto done;
1123 /* The keygrips for PKI files are stored after the header. They are
1124 * stored in the file to let file(1) magic(5) show the grips. */
1125 if (crypto->hdr.flags & PWMD_FLAG_PKI)
1127 rlen = read (fd, crypto->grip, 20);
1128 if (rlen != 20)
1130 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1131 goto done;
1134 rlen = read (fd, crypto->sign_grip, 20);
1135 if (rlen != 20)
1137 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1138 goto done;
1142 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
1143 if (len != crypto->hdr.datalen)
1145 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1146 goto done;
1149 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
1150 goto done;
1152 if (!use_agent)
1154 rc = GPG_ERR_NOT_IMPLEMENTED;
1155 goto done;
1158 #ifdef WITH_AGENT
1159 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
1160 buf = xmalloc (len);
1161 if (!buf)
1163 rc = GPG_ERR_ENOMEM;
1164 goto done;
1167 /* Remaining data file bytes are the encrypted key and XML. */
1168 rlen = read (fd, buf, len);
1169 if (rlen != len)
1171 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1172 goto done;
1175 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
1176 if (rc)
1177 goto done;
1179 if (crypto->pkey_sexp)
1180 gcry_sexp_release (crypto->pkey_sexp);
1182 if (crypto->sigpkey_sexp)
1183 gcry_sexp_release (crypto->sigpkey_sexp);
1185 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
1186 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
1187 if (!rc)
1188 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
1189 #endif
1191 done:
1192 close (fd);
1193 xfree (buf);
1194 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
1195 rc = gpg_error (rc);
1197 return rc;
1200 static void
1201 cleanup_save (struct save_s *save)
1203 if (!save)
1204 return;
1206 #ifdef WITH_AGENT
1207 if (save->pkey)
1208 gcry_sexp_release (save->pkey);
1210 if (save->sigpkey)
1211 gcry_sexp_release (save->sigpkey);
1212 #endif
1214 memset (save, 0, sizeof (struct save_s));
1217 /* Keep the agent ctx to retain pinentry options which will be freed in
1218 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
1219 static void
1220 cleanup_crypto_stage1 (struct crypto_s *cr)
1222 if (!cr)
1223 return;
1225 cleanup_save (&cr->save);
1227 #ifdef WITH_AGENT
1228 if (cr->ciphertext_sexp)
1229 gcry_sexp_release (cr->ciphertext_sexp);
1231 cr->ciphertext_sexp = NULL;
1232 #endif
1234 gcry_free (cr->plaintext);
1235 xfree (cr->ciphertext);
1236 xfree (cr->filename);
1237 cr->filename = NULL;
1238 cr->ciphertext = NULL;
1239 cr->ciphertext_len = 0;
1240 cr->plaintext = NULL;
1241 cr->plaintext_len = 0;
1244 static void
1245 cleanup_crypto_stage2 (struct crypto_s *cr)
1247 if (!cr)
1248 return;
1250 cleanup_crypto_stage1 (cr);
1251 set_header_defaults (&cr->hdr);
1254 static void
1255 cleanup_crypto (struct crypto_s **c)
1257 struct crypto_s *cr = *c;
1259 if (!cr)
1260 return;
1262 cleanup_crypto_stage2 (cr);
1264 #ifdef WITH_AGENT
1265 if (cr->pkey_sexp)
1266 gcry_sexp_release (cr->pkey_sexp);
1268 if (cr->sigpkey_sexp)
1269 gcry_sexp_release (cr->sigpkey_sexp);
1271 if (cr->agent)
1272 cleanup_agent (cr->agent);
1273 #endif
1275 xfree (cr);
1276 *c = NULL;
1279 /* Sets the default cipher values for new files. */
1280 static void
1281 set_header_defaults (file_header_t * hdr)
1283 const char *s = "aes256";
1284 int flags = cipher_string_to_cipher (s);
1286 memset (hdr, 0, sizeof (file_header_t));
1287 memcpy (hdr->magic, crypto_magic, sizeof (hdr->magic));
1288 if (flags == -1)
1289 fprintf(stderr, _("Invalid 'cipher' in configuration file. Using a default of aes256."));
1291 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
1292 hdr->version = VERSION_HEX;
1294 #ifdef WITH_AGENT
1295 if (use_agent)
1296 hdr->flags |= PWMD_FLAG_PKI;
1297 #endif