Remove non-reserved attributes when setting "target".
[pwmd.git] / src / pwmd-dump.c
blob8991d30d1793274c7d604c3ab10350296d4b8cf3
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 target = xml_attribute_value (n, (xmlChar *)"target");
350 if (target)
352 xmlChar lastc = 0, *p;
354 remove_non_reserved_attributes (n);
355 again:
356 for (lastc = 0, p = target; *p;)
358 if (*p == '!' && (p == target || lastc == '\t'))
360 xmlChar *c;
362 c = p;
363 while (*p)
364 *c++ = *++p;
365 *c = 0;
366 goto again;
369 lastc = *p++;
372 if (!xmlSetProp (n, (xmlChar *) "target", target))
374 xmlFree (target);
375 return GPG_ERR_INV_VALUE;
378 xmlFree (target);
380 if (n->children && !force)
382 fprintf(stderr, _("%s: aborting do to literal child elements (use --force)\n"), filename);
383 return GPG_ERR_CANCELED;
385 else if (n->children)
387 xmlNodePtr tmp = n->children;
389 xmlUnlinkNode (n->children);
390 xmlFreeNodeList (tmp);
394 rc = strip_literals (filename, n->children, force);
395 if (rc)
396 break;
399 return rc;
403 main(int argc, char **argv)
405 gpg_error_t rc;
406 int opt, optindex;
407 struct crypto_s *crypto = NULL;
408 char *outfile = NULL, *infile = NULL, *keyfile = NULL;
409 void *key = NULL;
410 enum {
411 OPT_FORCE,
412 OPT_XML
414 const char *optstring = "vhk:n";
415 int convert = 1;
416 int force = 0;
417 int xml = 0;
418 const struct option longopts[] = {
419 {"force", no_argument, 0, 0},
420 {"xml", no_argument, 0, 0},
421 {"no-convert", no_argument, 0, 'n'},
422 {"keyfile", required_argument, 0, 'k'},
423 {"version", no_argument, 0, 'v'},
424 {"help", no_argument, 0, 'h'},
425 {0, 0, 0, 0}
428 #ifndef DEBUG
429 #ifdef HAVE_SETRLIMIT
430 struct rlimit rl;
432 rl.rlim_cur = rl.rlim_max = 0;
434 if (setrlimit (RLIMIT_CORE, &rl) != 0)
435 err (EXIT_FAILURE, "setrlimit()");
436 #endif
438 #ifdef HAVE_PR_SET_DUMPABLE
439 prctl (PR_SET_DUMPABLE, 0);
440 #endif
441 #endif
443 #ifndef MEM_DEBUG
444 xmem_init ();
445 #endif
446 gpg_err_init ();
448 if (!gcry_check_version (GCRYPT_VERSION))
450 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
451 "Wanted %s, got %s.\n"), GCRYPT_VERSION,
452 gcry_check_version (NULL));
453 exit (EXIT_FAILURE);
456 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
457 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
458 xmlInitMemory ();
459 xmlInitGlobals ();
460 xmlInitParser ();
461 xmlXPathInit ();
463 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
465 switch (opt)
467 case 'n':
468 convert = 0;
469 break;
470 case 'k':
471 keyfile = optarg;
472 break;
473 case 'h':
474 usage (argv[0], EXIT_SUCCESS);
475 break;
476 case 'v':
477 printf (_("%s\n\n"
478 "Copyright (C) 2015, 2016\n"
479 "%s\n"
480 "Released under the terms of the GPL v2. Use at your own risk.\n\n"),
481 PACKAGE_STRING, PACKAGE_BUGREPORT);
482 exit (EXIT_SUCCESS);
483 case 0:
484 switch (optindex)
486 case OPT_FORCE:
487 force = 1;
488 break;
489 case OPT_XML:
490 xml = 1;
491 break;
492 default:
493 usage (argv[0], EXIT_FAILURE);
495 break;
496 default:
497 usage (argv[0], EXIT_FAILURE);
498 break;
502 if (argc - optind != 2)
503 usage (argv[0], EXIT_FAILURE);
505 infile = argv[optind++];
506 outfile = argv[optind];
507 if (strcmp (outfile, "-"))
509 if (access (outfile, R_OK|W_OK) == 0)
511 fprintf(stderr, _("Please remove the existing output file '%s'.\n"),
512 outfile);
513 exit (EXIT_FAILURE);
517 rc = init_client_crypto (&crypto);
518 if (rc)
519 goto fail;
521 if (!xml)
523 rc = decrypt_common (crypto, infile, keyfile);
524 xfree (key);
526 else
528 struct stat st;
529 int fd;
531 if (stat (infile, &st) == -1)
533 rc = gpg_error_from_syserror ();
534 goto fail;
537 fd = open (infile, O_RDONLY);
538 if (fd == -1)
540 rc = gpg_error_from_syserror ();
541 goto fail;
544 crypto->plaintext = gcry_calloc (1, sizeof (char) * st.st_size+1);
545 if (!crypto->plaintext)
547 close (fd);
548 rc = GPG_ERR_ENOMEM;
549 goto fail;
552 crypto->plaintext_len = read (fd, crypto->plaintext, st.st_size);
553 close (fd);
554 if (crypto->plaintext_len != st.st_size)
556 rc = GPG_ERR_UNKNOWN_ERRNO;
557 goto fail;
561 if (!rc)
563 xmlDocPtr doc;
565 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
566 cleanup_crypto (&crypto);
567 if (!rc)
569 xmlChar *buf;
570 int len;
572 FILE *fp = outfile[0] == '-' && outfile[1] == 0 ? stdout
573 : fopen (outfile, "w");
575 if (!fp)
577 rc = gpg_error_from_syserror ();
578 xmlFreeDoc (doc);
579 goto fail;
582 if (convert)
584 xmlNodePtr n = xmlDocGetRootElement (doc);
585 rc = strip_literals (infile, n->children, force);
586 if (rc)
588 xmlFreeDoc (doc);
589 goto fail;
593 xmlDocDumpMemory (doc, &buf, &len);
594 xmlFreeDoc (doc);
595 fprintf (fp, "%s", buf);
596 xmlFree (buf);
597 fclose (fp);
599 else
600 goto fail;
602 else
603 goto fail;
605 cleanup_crypto (&crypto);
606 exit (EXIT_SUCCESS);
608 fail:
609 cleanup_crypto (&crypto);
610 fprintf(stderr, "ERR %u: %s\n", rc, gpg_strerror (rc));
611 exit (EXIT_FAILURE);
614 static gpg_error_t
615 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
616 size_t keylen, void **result, size_t *rlen, uint64_t iterations)
618 gpg_error_t rc;
619 void *tmp;
621 /* Be sure the algorithm is available. */
622 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
623 if (rc)
624 return rc;
626 /* Always allocate enough for a 256-bit key although the algorithms
627 themselves may use less. Fixes SAVE --cipher with a different
628 keylen than the previously saved cipher when cached. */
629 *rlen = 32;
630 tmp = xmalloc (*rlen);
631 if (!tmp)
632 return GPG_ERR_ENOMEM;
634 if (!iterations)
635 iterations = DEFAULT_KDFS2K_ITERATIONS;
637 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
638 salt, salt_len, iterations, *rlen, tmp);
639 if (!rc)
640 *result = tmp;
641 else
642 xfree (tmp);
644 return rc;
648 * Useful for a large amount of data. Rather than doing all of the data in one
649 * iteration do it in chunks. This lets the command be cancelable rather than
650 * waiting for it to complete.
652 #define CRYPTO_BLOCKSIZE(c) (c * 1024)
653 static gpg_error_t
654 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
655 size_t insize, size_t blocksize)
657 gpg_error_t rc = 0;
658 off_t len = CRYPTO_BLOCKSIZE (blocksize);
659 void *p = gcry_malloc (len);
660 off_t total = 0;
662 if (!p)
663 return gpg_error (GPG_ERR_ENOMEM);
665 if (insize < CRYPTO_BLOCKSIZE (blocksize))
666 len = insize;
668 pthread_cleanup_push (gcry_free, p);
670 for (;;)
672 unsigned char *inbuf2 = inbuf + total;
673 unsigned char *tmp;
675 if (len + total > insize)
676 len = blocksize;
678 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
679 if (rc)
680 break;
682 tmp = inbuf + total;
683 memmove (tmp, p, len);
684 total += len;
685 if (total >= insize)
686 break;
688 #ifdef HAVE_PTHREAD_TESTCANCEL
689 pthread_testcancel ();
690 #endif
693 pthread_cleanup_pop (1);
694 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
695 rc = gpg_error (rc);
697 return rc;
700 static void
701 cleanup_cipher (void *arg)
703 gcry_cipher_close ((gcry_cipher_hd_t) arg);
706 /* Decrypt the XML data. For PKI data files the key is retrieved from
707 * gpg-agent and the signature verified. */
708 static gpg_error_t
709 decrypt_data (struct crypto_s *crypto, unsigned char *salted_key,
710 size_t skeylen)
712 gpg_error_t rc = 0;
713 unsigned char *key = salted_key;
714 gcry_cipher_hd_t h = NULL;
715 size_t blocksize, keysize = 0;
716 int algo = cipher_to_gcrypt (crypto->hdr.flags);
717 void *outbuf = NULL;
718 uint64_t n = crypto->hdr.s2k_count;
719 #ifdef WITH_AGENT
720 size_t keylen = skeylen;
721 gcry_sexp_t sig_sexp;
723 if (crypto->hdr.flags & PWMD_FLAG_PKI)
725 rc = agent_extract_key (crypto, &key, &keylen);
726 if (rc)
727 return rc;
729 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
730 if (!sig_sexp)
732 gcry_free (key);
733 return GPG_ERR_BAD_DATA;
736 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
737 crypto->ciphertext_len);
738 gcry_sexp_release (sig_sexp);
740 #endif
742 if (!rc)
744 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
745 if (!rc)
747 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
748 &keysize);
749 if (!rc)
751 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
752 &blocksize);
753 if (!rc)
755 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
756 if (!rc)
758 rc = gcry_cipher_setkey (h, key, keysize);
765 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
767 if (!rc)
769 outbuf = gcry_malloc (crypto->hdr.datalen+1);
770 if (!outbuf)
771 rc = GPG_ERR_ENOMEM;
772 else
773 memset (outbuf, 0, crypto->hdr.datalen+1);
776 pthread_cleanup_push (gcry_free, outbuf);
777 #ifdef WITH_AGENT
778 pthread_cleanup_push (gcry_free, key);
779 #endif
781 if (!rc)
783 if (!key)
784 rc = GPG_ERR_INV_PARAMETER;
785 else
787 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
788 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
791 if (!rc && crypto->hdr.version <= 0x03000e)
793 key[0] ^= 1;
794 rc = gcry_cipher_setkey (h, key, keysize);
798 if (!rc && crypto->hdr.version <= 0x03000e)
800 for (n = 0; !rc && n < crypto->hdr.s2k_count; n++)
802 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
803 if (rc)
804 break;
806 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
810 #ifdef WITH_AGENT
811 pthread_cleanup_pop (0);
812 if (crypto->hdr.flags & PWMD_FLAG_PKI)
813 gcry_free (key);
814 else if (key && crypto->hdr.version <= 0x03000e)
815 key[0] ^= 1;
816 #else
817 if (crypto->hdr.version <= 0x03000e)
818 key[0] ^= 1;
819 #endif
820 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
821 pthread_cleanup_pop (1); /* cipher */
822 if (!rc)
824 char buf[] = "<?xml ";
826 if (memcmp (outbuf, buf, sizeof(buf)-1))
828 gcry_free (outbuf);
829 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
832 crypto->plaintext = outbuf;
833 crypto->plaintext_len = crypto->hdr.datalen;
836 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
837 rc = gpg_error (rc);
839 return rc;
842 static gpg_error_t
843 get_passphrase (const char *filename, const char *keyfile, void **r_key,
844 size_t *r_len)
846 char buf[255] = { 0 };
847 struct termios told, tnew;
849 *r_len = 0;
851 if (keyfile)
853 ssize_t len;
854 struct stat st;
855 int fd;
857 if (stat (keyfile, &st) == -1)
858 return gpg_error_from_syserror ();
860 fd = open (keyfile, O_RDONLY);
861 if (fd == -1)
862 return gpg_error_from_syserror ();
864 len = read (fd, buf, sizeof (buf));
865 if (len != st.st_size)
867 close (fd);
868 wipememory (buf, 0, sizeof (buf));
869 return gpg_error_from_syserror ();
872 *r_len = st.st_size ? st.st_size : 1;
873 *r_key = xmalloc (*r_len);
874 memcpy (*r_key, buf, *r_len);
875 wipememory (buf, 0, sizeof (buf));
876 close (fd);
877 return 0;
880 if (!isatty (STDIN_FILENO))
881 return GPG_ERR_ENOTTY;
883 if (tcgetattr (STDIN_FILENO, &told) == -1)
884 return gpg_error_from_syserror ();
886 memcpy (&tnew, &told, sizeof (struct termios));
887 tnew.c_lflag &= ~(ECHO);
888 tnew.c_lflag |= ICANON | ECHONL;
889 if (tcsetattr (STDIN_FILENO, TCSANOW, &tnew) == -1)
891 int n = errno;
893 tcsetattr (STDIN_FILENO, TCSANOW, &told);
894 return gpg_error_from_errno (n);
897 fprintf(stderr, "Passphrase for '%s': ", filename);
898 if (!fgets (buf, sizeof (buf), stdin))
900 tcsetattr (STDIN_FILENO, TCSANOW, &told);
901 return GPG_ERR_EOF;
904 tcsetattr (STDIN_FILENO, TCSANOW, &told);
905 buf[strlen(buf)-1] = 0;
906 *r_len = buf[0] == 0 ? 1 : strlen (buf);
907 *r_key = str_dup (buf);
908 wipememory (buf, 0, sizeof (buf));
909 return 0;
912 /* Common to both PKI and non-PKI files. */
913 static gpg_error_t
914 decrypt_common (struct crypto_s *crypto, const char *filename,
915 const char *keyfile)
917 void *key = NULL;
918 size_t keylen = 0;
919 gpg_error_t rc = read_data_file (filename, crypto);
920 int algo = cipher_to_gcrypt (crypto->hdr.flags);
921 void *skey = NULL;
922 size_t skeysize = 0;
924 if (rc)
925 return rc;
927 rc = get_passphrase (filename, keyfile, &key, &keylen);
928 if (rc)
929 return rc;
931 if (key)// && !IS_PKI (crypto))
933 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
934 keylen, &skey, &skeysize,
935 crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : crypto->hdr.s2k_count);
936 if (rc)
938 xfree (key);
939 return rc;
943 xfree (key);
944 xfree (crypto->filename);
945 crypto->filename = str_dup (filename);
946 rc = decrypt_data (crypto, skey, skeysize);
947 xfree (skey);
948 return rc;
951 static gpg_error_t
952 read_header (file_header_t *hdr, int fd)
954 ssize_t len;
955 uint32_t i;
956 uint64_t n;
958 #ifdef WORDS_BIGENDIAN
959 len = read (fd, &hdr->magic, sizeof(hdr->magic));
960 if (len == -1)
961 goto done;
963 len = read (fd, &hdr->version, sizeof(hdr->version));
964 if (len == -1)
965 goto done;
967 len = read (fd, &hdr->s2k_count, sizeof(hdr->s2k_count));
968 if (len == -1)
969 goto done;
971 len = read (fd, &hdr->flags, sizeof(hdr->flags));
972 if (len == -1)
973 goto done;
975 len = read (fd, &hdr->iv, sizeof(hdr->iv));
976 if (len == -1)
977 goto done;
979 len = read (fd, &hdr->salt, sizeof(hdr->salt));
980 if (len == -1)
981 goto done;
983 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
984 if (len == -1)
985 goto done;
986 #else
987 len = read (fd, &hdr->magic, sizeof(hdr->magic));
988 if (len == -1)
989 goto done;
991 len = read (fd, &i, sizeof(hdr->version));
992 if (len == -1)
993 goto done;
994 hdr->version = ntohl (i);
996 len = read (fd, &n, sizeof(hdr->s2k_count));
997 if (len == -1)
998 goto done;
999 hdr->s2k_count = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1001 len = read (fd, &n, sizeof(hdr->flags));
1002 if (len == -1)
1003 goto done;
1004 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1006 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1007 if (len == -1)
1008 goto done;
1010 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1011 if (len == -1)
1012 goto done;
1014 len = read (fd, &i, sizeof(hdr->datalen));
1015 if (len == -1)
1016 goto done;
1017 hdr->datalen = ntohl (i);
1018 #endif
1020 done:
1021 return len == -1 ? gpg_error_from_errno (errno) : 0;
1024 /* Read the header of a data file to determine cipher and other. The
1025 * header is stored big endian in the file and is converted to little
1026 * endian when needed. */
1027 static gpg_error_t
1028 read_data_header (const char *filename, file_header_t * rhdr,
1029 struct stat *rst, int *rfd)
1031 gpg_error_t rc = 0;
1032 struct stat st;
1033 file_header_t hdr;
1034 int fd;
1036 if (lstat (filename, &st) == -1)
1037 return gpg_error_from_errno (errno);
1039 if (!S_ISREG (st.st_mode))
1040 return gpg_error (GPG_ERR_ENOANO);
1042 fd = open (filename, O_RDONLY);
1043 if (fd == -1)
1044 return gpg_error_from_errno (errno);
1046 rc = read_header (&hdr, fd);
1047 if (!rc && memcmp (hdr.magic, crypto_magic, sizeof (hdr.magic)))
1048 rc = GPG_ERR_BAD_DATA;
1049 else if (!rc && hdr.version < 0x030000)
1050 rc = GPG_ERR_UNKNOWN_VERSION;
1052 if (rc)
1053 close (fd);
1054 else
1056 if (rhdr)
1057 *rhdr = hdr;
1058 if (rst)
1059 *rst = st;
1060 if (rfd)
1061 *rfd = fd;
1062 else
1063 close (fd);
1066 return gpg_error (rc);
1069 static gpg_error_t
1070 read_data_file (const char *filename, struct crypto_s * crypto)
1072 int fd;
1073 gpg_error_t rc = 0;
1074 size_t len, rlen;
1075 char *buf = NULL;
1076 struct stat st;
1078 if (!filename)
1079 return GPG_ERR_INV_PARAMETER;
1081 cleanup_crypto_stage1 (crypto);
1082 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
1083 if (rc)
1084 return gpg_error (rc);
1086 crypto->ciphertext_len = crypto->hdr.datalen;
1087 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
1088 if (!crypto->ciphertext)
1090 rc = GPG_ERR_ENOMEM;
1091 goto done;
1094 /* The keygrips for PKI files are stored after the header. They are
1095 * stored in the file to let file(1) magic(5) show the grips. */
1096 if (crypto->hdr.flags & PWMD_FLAG_PKI)
1098 rlen = read (fd, crypto->grip, 20);
1099 if (rlen != 20)
1101 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1102 goto done;
1105 rlen = read (fd, crypto->sign_grip, 20);
1106 if (rlen != 20)
1108 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1109 goto done;
1113 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
1114 if (len != crypto->hdr.datalen)
1116 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1117 goto done;
1120 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
1121 goto done;
1123 if (!use_agent)
1125 rc = GPG_ERR_NOT_IMPLEMENTED;
1126 goto done;
1129 #ifdef WITH_AGENT
1130 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
1131 buf = xmalloc (len);
1132 if (!buf)
1134 rc = GPG_ERR_ENOMEM;
1135 goto done;
1138 /* Remaining data file bytes are the encrypted key and XML. */
1139 rlen = read (fd, buf, len);
1140 if (rlen != len)
1142 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1143 goto done;
1146 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
1147 if (rc)
1148 goto done;
1150 if (crypto->pkey_sexp)
1151 gcry_sexp_release (crypto->pkey_sexp);
1153 if (crypto->sigpkey_sexp)
1154 gcry_sexp_release (crypto->sigpkey_sexp);
1156 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
1157 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
1158 if (!rc)
1159 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
1160 #endif
1162 done:
1163 close (fd);
1164 xfree (buf);
1165 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
1166 rc = gpg_error (rc);
1168 return rc;
1171 static void
1172 cleanup_save (struct save_s *save)
1174 if (!save)
1175 return;
1177 #ifdef WITH_AGENT
1178 if (save->pkey)
1179 gcry_sexp_release (save->pkey);
1181 if (save->sigpkey)
1182 gcry_sexp_release (save->sigpkey);
1183 #endif
1185 memset (save, 0, sizeof (struct save_s));
1188 /* Keep the agent ctx to retain pinentry options which will be freed in
1189 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
1190 static void
1191 cleanup_crypto_stage1 (struct crypto_s *cr)
1193 if (!cr)
1194 return;
1196 cleanup_save (&cr->save);
1198 #ifdef WITH_AGENT
1199 if (cr->ciphertext_sexp)
1200 gcry_sexp_release (cr->ciphertext_sexp);
1202 cr->ciphertext_sexp = NULL;
1203 #endif
1205 gcry_free (cr->plaintext);
1206 xfree (cr->ciphertext);
1207 xfree (cr->filename);
1208 cr->filename = NULL;
1209 cr->ciphertext = NULL;
1210 cr->ciphertext_len = 0;
1211 cr->plaintext = NULL;
1212 cr->plaintext_len = 0;
1215 static void
1216 cleanup_crypto_stage2 (struct crypto_s *cr)
1218 if (!cr)
1219 return;
1221 cleanup_crypto_stage1 (cr);
1222 set_header_defaults (&cr->hdr);
1225 static void
1226 cleanup_crypto (struct crypto_s **c)
1228 struct crypto_s *cr = *c;
1230 if (!cr)
1231 return;
1233 cleanup_crypto_stage2 (cr);
1235 #ifdef WITH_AGENT
1236 if (cr->pkey_sexp)
1237 gcry_sexp_release (cr->pkey_sexp);
1239 if (cr->sigpkey_sexp)
1240 gcry_sexp_release (cr->sigpkey_sexp);
1242 if (cr->agent)
1243 cleanup_agent (cr->agent);
1244 #endif
1246 xfree (cr);
1247 *c = NULL;
1250 /* Sets the default cipher values for new files. */
1251 static void
1252 set_header_defaults (file_header_t * hdr)
1254 char *s = "aes256";
1255 int flags = cipher_string_to_cipher (s);
1257 memset (hdr, 0, sizeof (file_header_t));
1258 memcpy (hdr->magic, crypto_magic, sizeof (hdr->magic));
1259 if (flags == -1)
1260 fprintf(stderr, _("Invalid 'cipher' in configuration file. Using a default of aes256."));
1262 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
1263 hdr->version = VERSION_HEX;
1265 #ifdef WITH_AGENT
1266 if (use_agent)
1267 hdr->flags |= PWMD_FLAG_PKI;
1268 #endif