Fix cancellation of gpgme without pthread_cancel.
[libpwmd.git] / src / pwmd-dump.c
blobeea49b6c18d348b7738417e5bf919f420adf0dc2
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 <sys/prctl.h>
34 #include <errno.h>
35 #include <arpa/inet.h>
36 #include <libxml/tree.h>
37 #include <libxml/parser.h>
38 #include <libxml/xpath.h>
39 #include <err.h>
40 #include <termios.h>
42 #include "pwmd-error.h"
43 #include <gcrypt.h>
45 #ifdef ENABLE_NLS
46 #ifdef HAVE_LOCALE_H
47 #include <locale.h>
48 #endif
49 #endif
51 #ifndef _
52 #include "gettext.h"
53 #define _(msgid) gettext(msgid)
54 #endif
56 #ifdef HAVE_GETOPT_LONG
57 #ifdef HAVE_GETOPT_H
58 #include <getopt.h>
59 #endif
60 #else
61 #include "getopt_long.h"
62 #endif
64 #include "util-misc.h"
65 #include "util-string.h"
66 #include "mem.h"
68 #ifdef WITH_AGENT
69 #include "agent.h"
70 #endif
72 #define PWMD_CIPHER_OFFSET (1)
73 #define PWMD_CIPHER(n) (PWMD_CIPHER_OFFSET << n)
74 #define PWMD_CIPHER_AES128 PWMD_CIPHER (0)
75 #define PWMD_CIPHER_AES192 PWMD_CIPHER (1)
76 #define PWMD_CIPHER_AES256 PWMD_CIPHER (2)
77 #define PWMD_CIPHER_SERPENT128 PWMD_CIPHER (3)
78 #define PWMD_CIPHER_SERPENT192 PWMD_CIPHER (4)
79 #define PWMD_CIPHER_SERPENT256 PWMD_CIPHER (5)
80 #define PWMD_CIPHER_CAMELLIA128 PWMD_CIPHER (6)
81 #define PWMD_CIPHER_CAMELLIA192 PWMD_CIPHER (7)
82 #define PWMD_CIPHER_CAMELLIA256 PWMD_CIPHER (8)
83 #define PWMD_CIPHER_3DES PWMD_CIPHER (9)
84 #define PWMD_CIPHER_CAST5 PWMD_CIPHER (10)
85 #define PWMD_CIPHER_BLOWFISH PWMD_CIPHER (11)
86 #define PWMD_CIPHER_TWOFISH PWMD_CIPHER (12)
87 #define PWMD_CIPHER_TWOFISH128 PWMD_CIPHER (13)
89 #define PWMD_FLAG_OFFSET (PWMD_CIPHER_OFFSET << 15)
90 #define PWMD_FLAG(n) (PWMD_FLAG_OFFSET << n)
91 #define PWMD_FLAG_PKI PWMD_FLAG (1)
92 #define PWMD_FLAG_NO_PASSPHRASE PWMD_FLAG (2)
94 #define KEYSIZE 32
96 typedef struct
98 uint8_t magic[5];
99 uint32_t version;
100 uint64_t s2k_count;
101 uint64_t flags;
102 uint8_t iv[16];
103 uint8_t salt[8];
104 uint32_t datalen; /* of the encrypted xml */
105 } __attribute__ ((packed)) file_header_t;
107 struct save_s
109 gcry_sexp_t pkey; /* SAVE --keygrip */
110 gcry_sexp_t sigpkey; /* SAVE --sign-keygrip */
111 file_header_t hdr;
114 struct crypto_s
116 //assuan_context_t client_ctx;
117 #ifdef WITH_AGENT
118 struct agent_s *agent;
119 #endif
120 struct save_s save;
121 gcry_sexp_t pkey_sexp;
122 unsigned char grip[20];
123 gcry_sexp_t sigpkey_sexp;
124 unsigned char sign_grip[20];
125 gcry_sexp_t ciphertext_sexp;
126 void *ciphertext;
127 size_t ciphertext_len;
128 void *plaintext;
129 size_t plaintext_len;
130 file_header_t hdr;
131 char *filename; /* the currently opened data file */
134 #define DEFAULT_KDFS2K_ITERATIONS 5000000
135 #define COMPAT_KDFS2K_ITERATIONS 1000
137 const char *reserved_attributes[] = {
138 "_name", "_mtime", "_ctime", "_acl", "target",
139 NULL
141 static unsigned char crypto_magic[5] = "\177PWMD";
142 static int use_agent;
144 static void set_header_defaults (file_header_t * hdr);
145 static gpg_error_t decrypt_common (struct crypto_s *crypto,
146 const char *filename, const char *keyfile);
147 static gpg_error_t read_data_file (const char *filename,
148 struct crypto_s *crypto);
149 static void cleanup_crypto_stage1 (struct crypto_s *cr);
150 static void cleanup_crypto (struct crypto_s **c);
152 static int
153 cipher_to_gcrypt (int flags)
155 if (flags < 0)
156 return flags;
158 if (flags & PWMD_CIPHER_AES128)
159 return GCRY_CIPHER_AES128;
160 else if (flags & PWMD_CIPHER_AES192)
161 return GCRY_CIPHER_AES192;
162 else if (flags & PWMD_CIPHER_AES256)
163 return GCRY_CIPHER_AES256;
164 else if (flags & PWMD_CIPHER_SERPENT128)
165 return GCRY_CIPHER_SERPENT128;
166 else if (flags & PWMD_CIPHER_SERPENT192)
167 return GCRY_CIPHER_SERPENT192;
168 else if (flags & PWMD_CIPHER_SERPENT256)
169 return GCRY_CIPHER_SERPENT256;
170 else if (flags & PWMD_CIPHER_CAMELLIA128)
171 return GCRY_CIPHER_CAMELLIA128;
172 else if (flags & PWMD_CIPHER_CAMELLIA192)
173 return GCRY_CIPHER_CAMELLIA192;
174 else if (flags & PWMD_CIPHER_CAMELLIA256)
175 return GCRY_CIPHER_CAMELLIA256;
176 else if (flags & PWMD_CIPHER_BLOWFISH)
177 return GCRY_CIPHER_BLOWFISH;
178 else if (flags & PWMD_CIPHER_3DES)
179 return GCRY_CIPHER_3DES;
180 else if (flags & PWMD_CIPHER_CAST5)
181 return GCRY_CIPHER_CAST5;
182 else if (flags & PWMD_CIPHER_TWOFISH)
183 return GCRY_CIPHER_TWOFISH;
184 else if (flags & PWMD_CIPHER_TWOFISH128)
185 return GCRY_CIPHER_TWOFISH128;
187 return -1;
190 static int
191 cipher_string_to_cipher (const char *str)
193 int flags = 0;
195 if (!strcasecmp (str, "aes128"))
196 flags = PWMD_CIPHER_AES128;
197 else if (!strcasecmp (str, "aes192"))
198 flags = PWMD_CIPHER_AES192;
199 else if (!strcasecmp (str, "aes256"))
200 flags = PWMD_CIPHER_AES256;
201 else if (!strcasecmp (str, "serpent128"))
202 flags = PWMD_CIPHER_SERPENT128;
203 else if (!strcasecmp (str, "serpent192"))
204 flags = PWMD_CIPHER_SERPENT192;
205 else if (!strcasecmp (str, "serpent256"))
206 flags = PWMD_CIPHER_SERPENT256;
207 else if (!strcasecmp (str, "camellia128"))
208 flags = PWMD_CIPHER_CAMELLIA128;
209 else if (!strcasecmp (str, "camellia192"))
210 flags = PWMD_CIPHER_CAMELLIA192;
211 else if (!strcasecmp (str, "camellia256"))
212 flags = PWMD_CIPHER_CAMELLIA256;
213 else if (!strcasecmp (str, "blowfish"))
214 flags = PWMD_CIPHER_BLOWFISH;
215 else if (!strcasecmp (str, "cast5"))
216 flags = PWMD_CIPHER_CAST5;
217 else if (!strcasecmp (str, "3des"))
218 flags = PWMD_CIPHER_3DES;
219 else if (!strcasecmp (str, "twofish256"))
220 flags = PWMD_CIPHER_TWOFISH;
221 else if (!strcasecmp (str, "twofish128"))
222 flags = PWMD_CIPHER_TWOFISH128;
223 else
224 return -1;
226 return flags;
229 static void
230 usage (const char *pn, int rc)
232 fprintf(rc == EXIT_SUCCESS ? stdout : stderr,
233 "%s [-hvn] [--force] [-k <filename>] [--xml] <infile> <outfile>\n"
234 " --no-convert, -n don't discard data for elements with targets\n"
235 " --force don't abort when converting\n"
236 " --xml read a raw pwmd XML document\n"
237 " --keyfile, -k file containing the passphrase to use for decryption\n"
238 " --help\n"
239 " --version\n\n"
240 "Use - as <outfile> to write to standard output.\n",
241 pn);
242 exit (rc);
245 static gpg_error_t
246 init_client_crypto (struct crypto_s **crypto)
248 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
249 gpg_error_t rc;
251 if (!new)
253 rc = GPG_ERR_ENOMEM;
254 return rc;
257 #ifdef WITH_AGENT
258 if (use_agent)
260 rc = agent_init (&new->agent);
261 if (!rc)
263 rc = send_agent_common_options (new->agent);
264 if (!rc)
265 rc = agent_set_pinentry_options (new->agent);
268 if (rc)
270 cleanup_agent (new->agent);
271 xfree (new);
272 return rc;
275 #endif
277 set_header_defaults (&new->hdr);
278 *crypto = new;
279 return 0;
282 static gpg_error_t
283 parse_doc (const char *xml, size_t len, xmlDocPtr *result)
285 xmlDocPtr doc;
287 xmlResetLastError ();
288 doc = xmlReadMemory (xml, len, NULL, "UTF-8", XML_PARSE_NOBLANKS);
289 if (!doc && xmlGetLastError ())
290 return GPG_ERR_BAD_DATA;
292 *result = doc;
293 return !doc ? GPG_ERR_ENOMEM : 0;
296 static xmlChar *
297 xml_attribute_value (xmlNodePtr n, xmlChar * attr)
299 xmlAttrPtr a = xmlHasProp (n, attr);
301 if (!a)
302 return NULL;
304 if (!a->children || !a->children->content)
305 return NULL;
307 return xmlGetProp (n, attr);
310 static int
311 xml_reserved_attribute (const char *name)
313 int i;
315 for (i = 0; reserved_attributes[i]; i++)
317 if (!strcmp (name, reserved_attributes[i]))
318 return 1;
321 return 0;
323 static void
324 remove_non_reserved_attributes (xmlNodePtr n)
326 xmlAttrPtr a;
328 for (a = n->properties; a; a = a->next)
330 if (xml_reserved_attribute ((char *)a->name))
331 continue;
333 xmlRemoveProp (a);
337 static gpg_error_t
338 strip_literals (const char *filename, xmlNodePtr n, int force)
340 gpg_error_t rc = 0;
342 for (; n; n = n->next)
344 xmlChar *target;
346 if (n->type != XML_ELEMENT_NODE)
347 continue;
349 if (!xmlStrEqual (n->name, (xmlChar *) "element"))
351 xmlNodePtr tmp = n->next;
353 xmlUnlinkNode (n);
354 xmlFreeNodeList (n);
355 return strip_literals (filename, tmp, force);
358 target = xml_attribute_value (n, (xmlChar *)"target");
359 if (target)
361 xmlChar lastc = 0, *p;
363 remove_non_reserved_attributes (n);
364 again:
365 for (lastc = 0, p = target; *p;)
367 if (*p == '!' && (p == target || lastc == '\t'))
369 xmlChar *c;
371 c = p;
372 while (*p)
373 *c++ = *++p;
374 *c = 0;
375 goto again;
378 lastc = *p++;
381 if (!xmlSetProp (n, (xmlChar *) "target", target))
383 xmlFree (target);
384 return GPG_ERR_INV_VALUE;
387 xmlFree (target);
389 if (n->children && !force)
391 fprintf(stderr, _("%s: aborting do to literal child elements (use --force)\n"), filename);
392 return GPG_ERR_CANCELED;
394 else if (n->children)
396 xmlNodePtr tmp = n->children;
398 xmlUnlinkNode (n->children);
399 xmlFreeNodeList (tmp);
403 rc = strip_literals (filename, n->children, force);
404 if (rc)
405 break;
408 return rc;
412 main(int argc, char **argv)
414 gpg_error_t rc;
415 int opt, optindex;
416 struct crypto_s *crypto = NULL;
417 char *outfile = NULL, *infile = NULL, *keyfile = NULL;
418 void *key = NULL;
419 enum {
420 OPT_FORCE,
421 OPT_XML
423 const char *optstring = "vhk:n";
424 int convert = 1;
425 int force = 0;
426 int xml = 0;
427 const struct option longopts[] = {
428 {"force", no_argument, 0, 0},
429 {"xml", no_argument, 0, 0},
430 {"no-convert", no_argument, 0, 'n'},
431 {"keyfile", required_argument, 0, 'k'},
432 {"version", no_argument, 0, 'v'},
433 {"help", no_argument, 0, 'h'},
434 {0, 0, 0, 0}
437 #ifndef DEBUG
438 #ifdef HAVE_SETRLIMIT
439 struct rlimit rl;
441 rl.rlim_cur = rl.rlim_max = 0;
443 if (setrlimit (RLIMIT_CORE, &rl) != 0)
444 err (EXIT_FAILURE, "setrlimit()");
445 #endif
447 #ifdef HAVE_PR_SET_DUMPABLE
448 prctl (PR_SET_DUMPABLE, 0);
449 #endif
450 #endif
452 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
454 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
455 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
456 gpgrt_check_version (NULL));
457 exit (EXIT_FAILURE);
460 gpgrt_init ();
461 //gpgrt_set_alloc_func (xrealloc_gpgrt);
463 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
465 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
466 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
467 gcry_check_version (NULL));
468 exit (EXIT_FAILURE);
471 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
472 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
473 xmlInitMemory ();
474 xmlInitGlobals ();
475 xmlInitParser ();
476 xmlXPathInit ();
478 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
480 switch (opt)
482 case 'n':
483 convert = 0;
484 break;
485 case 'k':
486 keyfile = optarg;
487 break;
488 case 'h':
489 usage (argv[0], EXIT_SUCCESS);
490 break;
491 case 'v':
492 printf (_("%s\n\n"
493 "Copyright (C) 2015, 2016\n"
494 "%s\n"
495 "Released under the terms of the GPL v2. Use at your own risk.\n\n"),
496 PACKAGE_STRING, PACKAGE_BUGREPORT);
497 exit (EXIT_SUCCESS);
498 case 0:
499 switch (optindex)
501 case OPT_FORCE:
502 force = 1;
503 break;
504 case OPT_XML:
505 xml = 1;
506 break;
507 default:
508 usage (argv[0], EXIT_FAILURE);
510 break;
511 default:
512 usage (argv[0], EXIT_FAILURE);
513 break;
517 if (argc - optind != 2)
518 usage (argv[0], EXIT_FAILURE);
520 infile = argv[optind++];
521 outfile = argv[optind];
522 if (strcmp (outfile, "-"))
524 if (access (outfile, R_OK|W_OK) == 0)
526 fprintf(stderr, _("Please remove the existing output file '%s'.\n"),
527 outfile);
528 exit (EXIT_FAILURE);
532 rc = init_client_crypto (&crypto);
533 if (rc)
534 goto fail;
536 if (!xml)
538 rc = decrypt_common (crypto, infile, keyfile);
539 xfree (key);
541 else
543 struct stat st;
544 int fd;
546 if (stat (infile, &st) == -1)
548 rc = gpg_error_from_syserror ();
549 goto fail;
552 fd = open (infile, O_RDONLY);
553 if (fd == -1)
555 rc = gpg_error_from_syserror ();
556 goto fail;
559 crypto->plaintext = gcry_calloc (1, sizeof (char) * st.st_size+1);
560 if (!crypto->plaintext)
562 close (fd);
563 rc = GPG_ERR_ENOMEM;
564 goto fail;
567 crypto->plaintext_len = read (fd, crypto->plaintext, st.st_size);
568 close (fd);
569 if (crypto->plaintext_len != st.st_size)
571 rc = GPG_ERR_UNKNOWN_ERRNO;
572 goto fail;
576 if (!rc)
578 xmlDocPtr doc;
580 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
581 cleanup_crypto (&crypto);
582 if (!rc)
584 xmlChar *buf;
585 int len;
587 FILE *fp = outfile[0] == '-' && outfile[1] == 0 ? stdout
588 : fopen (outfile, "w");
590 if (!fp)
592 rc = gpg_error_from_syserror ();
593 xmlFreeDoc (doc);
594 goto fail;
597 if (convert)
599 xmlNodePtr n = xmlDocGetRootElement (doc);
600 rc = strip_literals (infile, n->children, force);
601 if (rc)
603 xmlFreeDoc (doc);
604 goto fail;
608 xmlDocDumpMemory (doc, &buf, &len);
609 xmlFreeDoc (doc);
610 fprintf (fp, "%s", buf);
611 xmlFree (buf);
612 fclose (fp);
614 else
615 goto fail;
617 else
618 goto fail;
620 cleanup_crypto (&crypto);
621 exit (EXIT_SUCCESS);
623 fail:
624 cleanup_crypto (&crypto);
625 fprintf(stderr, "ERR %u: %s\n", rc, gpg_strerror (rc));
626 exit (EXIT_FAILURE);
629 static gpg_error_t
630 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
631 size_t keylen, void **result, size_t *rlen, uint64_t iterations)
633 gpg_error_t rc;
634 void *tmp;
636 /* Be sure the algorithm is available. */
637 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
638 if (rc)
639 return rc;
641 /* Always allocate enough for a 256-bit key although the algorithms
642 themselves may use less. Fixes SAVE --cipher with a different
643 keylen than the previously saved cipher when cached. */
644 *rlen = 32;
645 tmp = xmalloc (*rlen);
646 if (!tmp)
647 return GPG_ERR_ENOMEM;
649 if (!iterations)
650 iterations = DEFAULT_KDFS2K_ITERATIONS;
652 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
653 salt, salt_len, iterations, *rlen, tmp);
654 if (!rc)
655 *result = tmp;
656 else
657 xfree (tmp);
659 return rc;
663 * Useful for a large amount of data. Rather than doing all of the data in one
664 * iteration do it in chunks. This lets the command be cancelable rather than
665 * waiting for it to complete.
667 #define CRYPTO_BLOCKSIZE(c) (c * 1024)
668 static gpg_error_t
669 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
670 size_t insize, size_t blocksize)
672 gpg_error_t rc = 0;
673 off_t len = CRYPTO_BLOCKSIZE (blocksize);
674 void *p = gcry_malloc (len);
675 off_t total = 0;
677 if (!p)
678 return gpg_error (GPG_ERR_ENOMEM);
680 if (insize < CRYPTO_BLOCKSIZE (blocksize))
681 len = insize;
683 pthread_cleanup_push (gcry_free, p);
685 for (;;)
687 unsigned char *inbuf2 = inbuf + total;
688 unsigned char *tmp;
690 if (len + total > insize)
691 len = blocksize;
693 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
694 if (rc)
695 break;
697 tmp = inbuf + total;
698 memmove (tmp, p, len);
699 total += len;
700 if (total >= insize)
701 break;
703 #ifdef HAVE_PTHREAD_TESTCANCEL
704 pthread_testcancel ();
705 #endif
708 pthread_cleanup_pop (1);
709 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
710 rc = gpg_error (rc);
712 return rc;
715 static void
716 cleanup_cipher (void *arg)
718 gcry_cipher_close ((gcry_cipher_hd_t) arg);
721 /* Decrypt the XML data. For PKI data files the key is retrieved from
722 * gpg-agent and the signature verified. */
723 static gpg_error_t
724 decrypt_data (struct crypto_s *crypto, unsigned char *salted_key,
725 size_t skeylen)
727 gpg_error_t rc = 0;
728 unsigned char *key = salted_key;
729 gcry_cipher_hd_t h = NULL;
730 size_t blocksize, keysize = 0;
731 int algo = cipher_to_gcrypt (crypto->hdr.flags);
732 void *outbuf = NULL;
733 uint64_t n = crypto->hdr.s2k_count;
734 #ifdef WITH_AGENT
735 size_t keylen = skeylen;
736 gcry_sexp_t sig_sexp;
738 if (crypto->hdr.flags & PWMD_FLAG_PKI)
740 rc = agent_extract_key (crypto, &key, &keylen);
741 if (rc)
742 return rc;
744 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
745 if (!sig_sexp)
747 gcry_free (key);
748 return GPG_ERR_BAD_DATA;
751 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
752 crypto->ciphertext_len);
753 gcry_sexp_release (sig_sexp);
755 #endif
757 if (!rc)
759 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
760 if (!rc)
762 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
763 &keysize);
764 if (!rc)
766 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
767 &blocksize);
768 if (!rc)
770 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
771 if (!rc)
773 rc = gcry_cipher_setkey (h, key, keysize);
780 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
782 if (!rc)
784 outbuf = gcry_malloc (crypto->hdr.datalen+1);
785 if (!outbuf)
786 rc = GPG_ERR_ENOMEM;
787 else
788 memset (outbuf, 0, crypto->hdr.datalen+1);
791 pthread_cleanup_push (gcry_free, outbuf);
792 #ifdef WITH_AGENT
793 pthread_cleanup_push (gcry_free, key);
794 #endif
796 if (!rc)
798 if (!key)
799 rc = GPG_ERR_INV_PARAMETER;
800 else
802 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
803 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
806 if (!rc && crypto->hdr.version <= 0x03000e)
808 key[0] ^= 1;
809 rc = gcry_cipher_setkey (h, key, keysize);
813 if (!rc && crypto->hdr.version <= 0x03000e)
815 for (n = 0; !rc && n < crypto->hdr.s2k_count; n++)
817 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
818 if (rc)
819 break;
821 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
825 #ifdef WITH_AGENT
826 pthread_cleanup_pop (0);
827 if (crypto->hdr.flags & PWMD_FLAG_PKI)
828 gcry_free (key);
829 else if (key && crypto->hdr.version <= 0x03000e)
830 key[0] ^= 1;
831 #else
832 if (crypto->hdr.version <= 0x03000e)
833 key[0] ^= 1;
834 #endif
835 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
836 pthread_cleanup_pop (1); /* cipher */
837 if (!rc)
839 char buf[] = "<?xml ";
841 if (memcmp (outbuf, buf, sizeof(buf)-1))
843 gcry_free (outbuf);
844 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
847 crypto->plaintext = outbuf;
848 crypto->plaintext_len = crypto->hdr.datalen;
851 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
852 rc = gpg_error (rc);
854 return rc;
857 static gpg_error_t
858 get_passphrase (const char *filename, const char *keyfile, void **r_key,
859 size_t *r_len)
861 char buf[255] = { 0 };
862 struct termios told, tnew;
864 *r_len = 0;
866 if (keyfile)
868 ssize_t len;
869 struct stat st;
870 int fd;
872 if (stat (keyfile, &st) == -1)
873 return gpg_error_from_syserror ();
875 fd = open (keyfile, O_RDONLY);
876 if (fd == -1)
877 return gpg_error_from_syserror ();
879 len = read (fd, buf, sizeof (buf));
880 if (len != st.st_size)
882 close (fd);
883 wipememory (buf, 0, sizeof (buf));
884 return gpg_error_from_syserror ();
887 *r_len = st.st_size ? st.st_size : 1;
888 *r_key = xmalloc (*r_len);
889 memcpy (*r_key, buf, *r_len);
890 wipememory (buf, 0, sizeof (buf));
891 close (fd);
892 return 0;
895 if (!isatty (STDIN_FILENO))
896 return GPG_ERR_ENOTTY;
898 if (tcgetattr (STDIN_FILENO, &told) == -1)
899 return gpg_error_from_syserror ();
901 memcpy (&tnew, &told, sizeof (struct termios));
902 tnew.c_lflag &= ~(ECHO);
903 tnew.c_lflag |= ICANON | ECHONL;
904 if (tcsetattr (STDIN_FILENO, TCSANOW, &tnew) == -1)
906 int n = errno;
908 tcsetattr (STDIN_FILENO, TCSANOW, &told);
909 return gpg_error_from_errno (n);
912 fprintf(stderr, "Passphrase for '%s': ", filename);
913 if (!fgets (buf, sizeof (buf), stdin))
915 tcsetattr (STDIN_FILENO, TCSANOW, &told);
916 return GPG_ERR_EOF;
919 tcsetattr (STDIN_FILENO, TCSANOW, &told);
920 buf[strlen(buf)-1] = 0;
921 *r_len = buf[0] == 0 ? 1 : strlen (buf);
922 *r_key = str_dup (buf);
923 wipememory (buf, 0, sizeof (buf));
924 return 0;
927 /* Common to both PKI and non-PKI files. */
928 static gpg_error_t
929 decrypt_common (struct crypto_s *crypto, const char *filename,
930 const char *keyfile)
932 void *key = NULL;
933 size_t keylen = 0;
934 gpg_error_t rc = read_data_file (filename, crypto);
935 int algo = cipher_to_gcrypt (crypto->hdr.flags);
936 void *skey = NULL;
937 size_t skeysize = 0;
939 if (rc)
940 return rc;
942 rc = get_passphrase (filename, keyfile, &key, &keylen);
943 if (rc)
944 return rc;
946 if (key)// && !IS_PKI (crypto))
948 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
949 keylen, &skey, &skeysize,
950 crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : crypto->hdr.s2k_count);
951 if (rc)
953 xfree (key);
954 return rc;
958 xfree (key);
959 xfree (crypto->filename);
960 crypto->filename = str_dup (filename);
961 rc = decrypt_data (crypto, skey, skeysize);
962 xfree (skey);
963 return rc;
966 static gpg_error_t
967 read_header (file_header_t *hdr, int fd)
969 ssize_t len;
970 uint32_t i;
971 uint64_t n;
973 #ifdef WORDS_BIGENDIAN
974 len = read (fd, &hdr->magic, sizeof(hdr->magic));
975 if (len == -1)
976 goto done;
978 len = read (fd, &hdr->version, sizeof(hdr->version));
979 if (len == -1)
980 goto done;
982 len = read (fd, &hdr->s2k_count, sizeof(hdr->s2k_count));
983 if (len == -1)
984 goto done;
986 len = read (fd, &hdr->flags, sizeof(hdr->flags));
987 if (len == -1)
988 goto done;
990 len = read (fd, &hdr->iv, sizeof(hdr->iv));
991 if (len == -1)
992 goto done;
994 len = read (fd, &hdr->salt, sizeof(hdr->salt));
995 if (len == -1)
996 goto done;
998 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
999 if (len == -1)
1000 goto done;
1001 #else
1002 len = read (fd, &hdr->magic, sizeof(hdr->magic));
1003 if (len == -1)
1004 goto done;
1006 len = read (fd, &i, sizeof(hdr->version));
1007 if (len == -1)
1008 goto done;
1009 hdr->version = ntohl (i);
1011 len = read (fd, &n, sizeof(hdr->s2k_count));
1012 if (len == -1)
1013 goto done;
1014 hdr->s2k_count = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1016 len = read (fd, &n, sizeof(hdr->flags));
1017 if (len == -1)
1018 goto done;
1019 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1021 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1022 if (len == -1)
1023 goto done;
1025 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1026 if (len == -1)
1027 goto done;
1029 len = read (fd, &i, sizeof(hdr->datalen));
1030 if (len == -1)
1031 goto done;
1032 hdr->datalen = ntohl (i);
1033 #endif
1035 done:
1036 return len == -1 ? gpg_error_from_errno (errno) : 0;
1039 /* Read the header of a data file to determine cipher and other. The
1040 * header is stored big endian in the file and is converted to little
1041 * endian when needed. */
1042 static gpg_error_t
1043 read_data_header (const char *filename, file_header_t * rhdr,
1044 struct stat *rst, int *rfd)
1046 gpg_error_t rc = 0;
1047 struct stat st;
1048 file_header_t hdr;
1049 int fd;
1051 if (lstat (filename, &st) == -1)
1052 return gpg_error_from_errno (errno);
1054 if (!S_ISREG (st.st_mode))
1055 return gpg_error (GPG_ERR_ENOANO);
1057 fd = open (filename, O_RDONLY);
1058 if (fd == -1)
1059 return gpg_error_from_errno (errno);
1061 rc = read_header (&hdr, fd);
1062 if (!rc && memcmp (hdr.magic, crypto_magic, sizeof (hdr.magic)))
1063 rc = GPG_ERR_BAD_DATA;
1064 else if (!rc && hdr.version < 0x030000)
1065 rc = GPG_ERR_UNKNOWN_VERSION;
1067 if (rc)
1068 close (fd);
1069 else
1071 if (rhdr)
1072 *rhdr = hdr;
1073 if (rst)
1074 *rst = st;
1075 if (rfd)
1076 *rfd = fd;
1077 else
1078 close (fd);
1081 return gpg_error (rc);
1084 static gpg_error_t
1085 read_data_file (const char *filename, struct crypto_s * crypto)
1087 int fd;
1088 gpg_error_t rc = 0;
1089 size_t len, rlen;
1090 char *buf = NULL;
1091 struct stat st;
1093 if (!filename)
1094 return GPG_ERR_INV_PARAMETER;
1096 cleanup_crypto_stage1 (crypto);
1097 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
1098 if (rc)
1099 return gpg_error (rc);
1101 crypto->ciphertext_len = crypto->hdr.datalen;
1102 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
1103 if (!crypto->ciphertext)
1105 rc = GPG_ERR_ENOMEM;
1106 goto done;
1109 /* The keygrips for PKI files are stored after the header. They are
1110 * stored in the file to let file(1) magic(5) show the grips. */
1111 if (crypto->hdr.flags & PWMD_FLAG_PKI)
1113 rlen = read (fd, crypto->grip, 20);
1114 if (rlen != 20)
1116 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1117 goto done;
1120 rlen = read (fd, crypto->sign_grip, 20);
1121 if (rlen != 20)
1123 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1124 goto done;
1128 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
1129 if (len != crypto->hdr.datalen)
1131 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1132 goto done;
1135 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
1136 goto done;
1138 if (!use_agent)
1140 rc = GPG_ERR_NOT_IMPLEMENTED;
1141 goto done;
1144 #ifdef WITH_AGENT
1145 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
1146 buf = xmalloc (len);
1147 if (!buf)
1149 rc = GPG_ERR_ENOMEM;
1150 goto done;
1153 /* Remaining data file bytes are the encrypted key and XML. */
1154 rlen = read (fd, buf, len);
1155 if (rlen != len)
1157 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1158 goto done;
1161 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
1162 if (rc)
1163 goto done;
1165 if (crypto->pkey_sexp)
1166 gcry_sexp_release (crypto->pkey_sexp);
1168 if (crypto->sigpkey_sexp)
1169 gcry_sexp_release (crypto->sigpkey_sexp);
1171 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
1172 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
1173 if (!rc)
1174 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
1175 #endif
1177 done:
1178 close (fd);
1179 xfree (buf);
1180 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
1181 rc = gpg_error (rc);
1183 return rc;
1186 static void
1187 cleanup_save (struct save_s *save)
1189 if (!save)
1190 return;
1192 #ifdef WITH_AGENT
1193 if (save->pkey)
1194 gcry_sexp_release (save->pkey);
1196 if (save->sigpkey)
1197 gcry_sexp_release (save->sigpkey);
1198 #endif
1200 memset (save, 0, sizeof (struct save_s));
1203 /* Keep the agent ctx to retain pinentry options which will be freed in
1204 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
1205 static void
1206 cleanup_crypto_stage1 (struct crypto_s *cr)
1208 if (!cr)
1209 return;
1211 cleanup_save (&cr->save);
1213 #ifdef WITH_AGENT
1214 if (cr->ciphertext_sexp)
1215 gcry_sexp_release (cr->ciphertext_sexp);
1217 cr->ciphertext_sexp = NULL;
1218 #endif
1220 gcry_free (cr->plaintext);
1221 xfree (cr->ciphertext);
1222 xfree (cr->filename);
1223 cr->filename = NULL;
1224 cr->ciphertext = NULL;
1225 cr->ciphertext_len = 0;
1226 cr->plaintext = NULL;
1227 cr->plaintext_len = 0;
1230 static void
1231 cleanup_crypto_stage2 (struct crypto_s *cr)
1233 if (!cr)
1234 return;
1236 cleanup_crypto_stage1 (cr);
1237 set_header_defaults (&cr->hdr);
1240 static void
1241 cleanup_crypto (struct crypto_s **c)
1243 struct crypto_s *cr = *c;
1245 if (!cr)
1246 return;
1248 cleanup_crypto_stage2 (cr);
1250 #ifdef WITH_AGENT
1251 if (cr->pkey_sexp)
1252 gcry_sexp_release (cr->pkey_sexp);
1254 if (cr->sigpkey_sexp)
1255 gcry_sexp_release (cr->sigpkey_sexp);
1257 if (cr->agent)
1258 cleanup_agent (cr->agent);
1259 #endif
1261 xfree (cr);
1262 *c = NULL;
1265 /* Sets the default cipher values for new files. */
1266 static void
1267 set_header_defaults (file_header_t * hdr)
1269 char *s = "aes256";
1270 int flags = cipher_string_to_cipher (s);
1272 memset (hdr, 0, sizeof (file_header_t));
1273 memcpy (hdr->magic, crypto_magic, sizeof (hdr->magic));
1274 if (flags == -1)
1275 fprintf(stderr, _("Invalid 'cipher' in configuration file. Using a default of aes256."));
1277 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
1278 hdr->version = VERSION_HEX;
1280 #ifdef WITH_AGENT
1281 if (use_agent)
1282 hdr->flags |= PWMD_FLAG_PKI;
1283 #endif