Fix sys/prctl.h conditional.
[pwmd.git] / src / pwmd-dump.c
blob9d5df7470e8c791ed762742a582222cc53cd4804
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-misc.h"
68 #include "util-string.h"
69 #include "mem.h"
71 #ifdef WITH_AGENT
72 #include "agent.h"
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, 2016\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 if (stat (infile, &st) == -1)
551 rc = gpg_error_from_syserror ();
552 goto fail;
555 fd = open (infile, O_RDONLY);
556 if (fd == -1)
558 rc = gpg_error_from_syserror ();
559 goto fail;
562 crypto->plaintext = gcry_calloc (1, sizeof (char) * st.st_size+1);
563 if (!crypto->plaintext)
565 close (fd);
566 rc = GPG_ERR_ENOMEM;
567 goto fail;
570 crypto->plaintext_len = read (fd, crypto->plaintext, st.st_size);
571 close (fd);
572 if (crypto->plaintext_len != st.st_size)
574 rc = GPG_ERR_UNKNOWN_ERRNO;
575 goto fail;
579 if (!rc)
581 xmlDocPtr doc;
583 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
584 cleanup_crypto (&crypto);
585 if (!rc)
587 xmlChar *buf;
588 int len;
590 FILE *fp = outfile[0] == '-' && outfile[1] == 0 ? stdout
591 : fopen (outfile, "w");
593 if (!fp)
595 rc = gpg_error_from_syserror ();
596 xmlFreeDoc (doc);
597 goto fail;
600 if (convert)
602 xmlNodePtr n = xmlDocGetRootElement (doc);
603 rc = strip_literals (infile, n->children, force);
604 if (rc)
606 xmlFreeDoc (doc);
607 goto fail;
611 xmlDocDumpMemory (doc, &buf, &len);
612 xmlFreeDoc (doc);
613 fprintf (fp, "%s", buf);
614 xmlFree (buf);
615 fclose (fp);
617 else
618 goto fail;
620 else
621 goto fail;
623 cleanup_crypto (&crypto);
624 exit (EXIT_SUCCESS);
626 fail:
627 cleanup_crypto (&crypto);
628 fprintf(stderr, "ERR %u: %s\n", rc, gpg_strerror (rc));
629 exit (EXIT_FAILURE);
632 static gpg_error_t
633 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
634 size_t keylen, void **result, size_t *rlen, uint64_t iterations)
636 gpg_error_t rc;
637 void *tmp;
639 /* Be sure the algorithm is available. */
640 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
641 if (rc)
642 return rc;
644 /* Always allocate enough for a 256-bit key although the algorithms
645 themselves may use less. Fixes SAVE --cipher with a different
646 keylen than the previously saved cipher when cached. */
647 *rlen = 32;
648 tmp = xmalloc (*rlen);
649 if (!tmp)
650 return GPG_ERR_ENOMEM;
652 if (!iterations)
653 iterations = DEFAULT_KDFS2K_ITERATIONS;
655 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
656 salt, salt_len, iterations, *rlen, tmp);
657 if (!rc)
658 *result = tmp;
659 else
660 xfree (tmp);
662 return rc;
666 * Useful for a large amount of data. Rather than doing all of the data in one
667 * iteration do it in chunks. This lets the command be cancelable rather than
668 * waiting for it to complete.
670 #define CRYPTO_BLOCKSIZE(c) (c * 1024)
671 static gpg_error_t
672 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
673 size_t insize, size_t blocksize)
675 gpg_error_t rc = 0;
676 off_t len = CRYPTO_BLOCKSIZE (blocksize);
677 void *p = gcry_malloc (len);
678 off_t total = 0;
680 if (!p)
681 return gpg_error (GPG_ERR_ENOMEM);
683 if (insize < CRYPTO_BLOCKSIZE (blocksize))
684 len = insize;
686 pthread_cleanup_push (gcry_free, p);
688 for (;;)
690 unsigned char *inbuf2 = inbuf + total;
691 unsigned char *tmp;
693 if (len + total > insize)
694 len = blocksize;
696 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
697 if (rc)
698 break;
700 tmp = inbuf + total;
701 memmove (tmp, p, len);
702 total += len;
703 if (total >= insize)
704 break;
706 #ifdef HAVE_PTHREAD_TESTCANCEL
707 pthread_testcancel ();
708 #endif
711 pthread_cleanup_pop (1);
712 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
713 rc = gpg_error (rc);
715 return rc;
718 static void
719 cleanup_cipher (void *arg)
721 gcry_cipher_close ((gcry_cipher_hd_t) arg);
724 /* Decrypt the XML data. For PKI data files the key is retrieved from
725 * gpg-agent and the signature verified. */
726 static gpg_error_t
727 decrypt_data (struct crypto_s *crypto, unsigned char *salted_key,
728 size_t skeylen)
730 gpg_error_t rc = 0;
731 unsigned char *key = salted_key;
732 gcry_cipher_hd_t h = NULL;
733 size_t blocksize, keysize = 0;
734 int algo = cipher_to_gcrypt (crypto->hdr.flags);
735 void *outbuf = NULL;
736 uint64_t n = crypto->hdr.s2k_count;
737 #ifdef WITH_AGENT
738 size_t keylen = skeylen;
739 gcry_sexp_t sig_sexp;
741 if (crypto->hdr.flags & PWMD_FLAG_PKI)
743 rc = agent_extract_key (crypto, &key, &keylen);
744 if (rc)
745 return rc;
747 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
748 if (!sig_sexp)
750 gcry_free (key);
751 return GPG_ERR_BAD_DATA;
754 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
755 crypto->ciphertext_len);
756 gcry_sexp_release (sig_sexp);
758 #endif
760 if (!rc)
762 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
763 if (!rc)
765 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
766 &keysize);
767 if (!rc)
769 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
770 &blocksize);
771 if (!rc)
773 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
774 if (!rc)
776 rc = gcry_cipher_setkey (h, key, keysize);
783 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
785 if (!rc)
787 outbuf = gcry_malloc (crypto->hdr.datalen+1);
788 if (!outbuf)
789 rc = GPG_ERR_ENOMEM;
790 else
791 memset (outbuf, 0, crypto->hdr.datalen+1);
794 pthread_cleanup_push (gcry_free, outbuf);
795 #ifdef WITH_AGENT
796 pthread_cleanup_push (gcry_free, key);
797 #endif
799 if (!rc)
801 if (!key)
802 rc = GPG_ERR_INV_PARAMETER;
803 else
805 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
806 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
809 if (!rc && crypto->hdr.version <= 0x03000e)
811 key[0] ^= 1;
812 rc = gcry_cipher_setkey (h, key, keysize);
816 if (!rc && crypto->hdr.version <= 0x03000e)
818 for (n = 0; !rc && n < crypto->hdr.s2k_count; n++)
820 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
821 if (rc)
822 break;
824 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
828 #ifdef WITH_AGENT
829 pthread_cleanup_pop (0);
830 if (crypto->hdr.flags & PWMD_FLAG_PKI)
831 gcry_free (key);
832 else if (key && crypto->hdr.version <= 0x03000e)
833 key[0] ^= 1;
834 #else
835 if (crypto->hdr.version <= 0x03000e)
836 key[0] ^= 1;
837 #endif
838 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
839 pthread_cleanup_pop (1); /* cipher */
840 if (!rc)
842 char buf[] = "<?xml ";
844 if (memcmp (outbuf, buf, sizeof(buf)-1))
846 gcry_free (outbuf);
847 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
850 crypto->plaintext = outbuf;
851 crypto->plaintext_len = crypto->hdr.datalen;
854 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
855 rc = gpg_error (rc);
857 return rc;
860 static gpg_error_t
861 get_passphrase (const char *filename, const char *keyfile, void **r_key,
862 size_t *r_len)
864 char buf[255] = { 0 };
865 struct termios told, tnew;
867 *r_len = 0;
869 if (keyfile)
871 ssize_t len;
872 struct stat st;
873 int fd;
875 if (stat (keyfile, &st) == -1)
876 return gpg_error_from_syserror ();
878 fd = open (keyfile, O_RDONLY);
879 if (fd == -1)
880 return gpg_error_from_syserror ();
882 len = read (fd, buf, sizeof (buf));
883 if (len != st.st_size)
885 close (fd);
886 wipememory (buf, 0, sizeof (buf));
887 return gpg_error_from_syserror ();
890 *r_len = st.st_size ? st.st_size : 1;
891 *r_key = xmalloc (*r_len);
892 memcpy (*r_key, buf, *r_len);
893 wipememory (buf, 0, sizeof (buf));
894 close (fd);
895 return 0;
898 if (!isatty (STDIN_FILENO))
899 return GPG_ERR_ENOTTY;
901 if (tcgetattr (STDIN_FILENO, &told) == -1)
902 return gpg_error_from_syserror ();
904 memcpy (&tnew, &told, sizeof (struct termios));
905 tnew.c_lflag &= ~(ECHO);
906 tnew.c_lflag |= ICANON | ECHONL;
907 if (tcsetattr (STDIN_FILENO, TCSANOW, &tnew) == -1)
909 int n = errno;
911 tcsetattr (STDIN_FILENO, TCSANOW, &told);
912 return gpg_error_from_errno (n);
915 fprintf(stderr, "Passphrase for '%s': ", filename);
916 if (!fgets (buf, sizeof (buf), stdin))
918 tcsetattr (STDIN_FILENO, TCSANOW, &told);
919 return GPG_ERR_EOF;
922 tcsetattr (STDIN_FILENO, TCSANOW, &told);
923 buf[strlen(buf)-1] = 0;
924 *r_len = buf[0] == 0 ? 1 : strlen (buf);
925 *r_key = str_dup (buf);
926 wipememory (buf, 0, sizeof (buf));
927 return 0;
930 /* Common to both PKI and non-PKI files. */
931 static gpg_error_t
932 decrypt_common (struct crypto_s *crypto, const char *filename,
933 const char *keyfile)
935 void *key = NULL;
936 size_t keylen = 0;
937 gpg_error_t rc = read_data_file (filename, crypto);
938 int algo = cipher_to_gcrypt (crypto->hdr.flags);
939 void *skey = NULL;
940 size_t skeysize = 0;
942 if (rc)
943 return rc;
945 rc = get_passphrase (filename, keyfile, &key, &keylen);
946 if (rc)
947 return rc;
949 if (key)// && !IS_PKI (crypto))
951 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
952 keylen, &skey, &skeysize,
953 crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : crypto->hdr.s2k_count);
954 if (rc)
956 xfree (key);
957 return rc;
961 xfree (key);
962 xfree (crypto->filename);
963 crypto->filename = str_dup (filename);
964 rc = decrypt_data (crypto, skey, skeysize);
965 xfree (skey);
966 return rc;
969 static gpg_error_t
970 read_header (file_header_t *hdr, int fd)
972 ssize_t len;
973 uint32_t i;
974 uint64_t n;
976 #ifdef WORDS_BIGENDIAN
977 len = read (fd, &hdr->magic, sizeof(hdr->magic));
978 if (len == -1)
979 goto done;
981 len = read (fd, &hdr->version, sizeof(hdr->version));
982 if (len == -1)
983 goto done;
985 len = read (fd, &hdr->s2k_count, sizeof(hdr->s2k_count));
986 if (len == -1)
987 goto done;
989 len = read (fd, &hdr->flags, sizeof(hdr->flags));
990 if (len == -1)
991 goto done;
993 len = read (fd, &hdr->iv, sizeof(hdr->iv));
994 if (len == -1)
995 goto done;
997 len = read (fd, &hdr->salt, sizeof(hdr->salt));
998 if (len == -1)
999 goto done;
1001 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
1002 if (len == -1)
1003 goto done;
1004 #else
1005 len = read (fd, &hdr->magic, sizeof(hdr->magic));
1006 if (len == -1)
1007 goto done;
1009 len = read (fd, &i, sizeof(hdr->version));
1010 if (len == -1)
1011 goto done;
1012 hdr->version = ntohl (i);
1014 len = read (fd, &n, sizeof(hdr->s2k_count));
1015 if (len == -1)
1016 goto done;
1017 hdr->s2k_count = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1019 len = read (fd, &n, sizeof(hdr->flags));
1020 if (len == -1)
1021 goto done;
1022 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1024 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1025 if (len == -1)
1026 goto done;
1028 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1029 if (len == -1)
1030 goto done;
1032 len = read (fd, &i, sizeof(hdr->datalen));
1033 if (len == -1)
1034 goto done;
1035 hdr->datalen = ntohl (i);
1036 #endif
1038 done:
1039 return len == -1 ? gpg_error_from_errno (errno) : 0;
1042 /* Read the header of a data file to determine cipher and other. The
1043 * header is stored big endian in the file and is converted to little
1044 * endian when needed. */
1045 static gpg_error_t
1046 read_data_header (const char *filename, file_header_t * rhdr,
1047 struct stat *rst, int *rfd)
1049 gpg_error_t rc = 0;
1050 struct stat st;
1051 file_header_t hdr;
1052 int fd;
1054 if (lstat (filename, &st) == -1)
1055 return gpg_error_from_errno (errno);
1057 if (!S_ISREG (st.st_mode))
1058 return gpg_error (GPG_ERR_ENOANO);
1060 fd = open (filename, O_RDONLY);
1061 if (fd == -1)
1062 return gpg_error_from_errno (errno);
1064 rc = read_header (&hdr, fd);
1065 if (!rc && memcmp (hdr.magic, crypto_magic, sizeof (hdr.magic)))
1066 rc = GPG_ERR_BAD_DATA;
1067 else if (!rc && hdr.version < 0x030000)
1068 rc = GPG_ERR_UNKNOWN_VERSION;
1070 if (rc)
1071 close (fd);
1072 else
1074 if (rhdr)
1075 *rhdr = hdr;
1076 if (rst)
1077 *rst = st;
1078 if (rfd)
1079 *rfd = fd;
1080 else
1081 close (fd);
1084 return gpg_error (rc);
1087 static gpg_error_t
1088 read_data_file (const char *filename, struct crypto_s * crypto)
1090 int fd;
1091 gpg_error_t rc = 0;
1092 size_t len, rlen;
1093 char *buf = NULL;
1094 struct stat st;
1096 if (!filename)
1097 return GPG_ERR_INV_PARAMETER;
1099 cleanup_crypto_stage1 (crypto);
1100 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
1101 if (rc)
1102 return gpg_error (rc);
1104 crypto->ciphertext_len = crypto->hdr.datalen;
1105 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
1106 if (!crypto->ciphertext)
1108 rc = GPG_ERR_ENOMEM;
1109 goto done;
1112 /* The keygrips for PKI files are stored after the header. They are
1113 * stored in the file to let file(1) magic(5) show the grips. */
1114 if (crypto->hdr.flags & PWMD_FLAG_PKI)
1116 rlen = read (fd, crypto->grip, 20);
1117 if (rlen != 20)
1119 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1120 goto done;
1123 rlen = read (fd, crypto->sign_grip, 20);
1124 if (rlen != 20)
1126 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1127 goto done;
1131 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
1132 if (len != crypto->hdr.datalen)
1134 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1135 goto done;
1138 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
1139 goto done;
1141 if (!use_agent)
1143 rc = GPG_ERR_NOT_IMPLEMENTED;
1144 goto done;
1147 #ifdef WITH_AGENT
1148 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
1149 buf = xmalloc (len);
1150 if (!buf)
1152 rc = GPG_ERR_ENOMEM;
1153 goto done;
1156 /* Remaining data file bytes are the encrypted key and XML. */
1157 rlen = read (fd, buf, len);
1158 if (rlen != len)
1160 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1161 goto done;
1164 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
1165 if (rc)
1166 goto done;
1168 if (crypto->pkey_sexp)
1169 gcry_sexp_release (crypto->pkey_sexp);
1171 if (crypto->sigpkey_sexp)
1172 gcry_sexp_release (crypto->sigpkey_sexp);
1174 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
1175 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
1176 if (!rc)
1177 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
1178 #endif
1180 done:
1181 close (fd);
1182 xfree (buf);
1183 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
1184 rc = gpg_error (rc);
1186 return rc;
1189 static void
1190 cleanup_save (struct save_s *save)
1192 if (!save)
1193 return;
1195 #ifdef WITH_AGENT
1196 if (save->pkey)
1197 gcry_sexp_release (save->pkey);
1199 if (save->sigpkey)
1200 gcry_sexp_release (save->sigpkey);
1201 #endif
1203 memset (save, 0, sizeof (struct save_s));
1206 /* Keep the agent ctx to retain pinentry options which will be freed in
1207 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
1208 static void
1209 cleanup_crypto_stage1 (struct crypto_s *cr)
1211 if (!cr)
1212 return;
1214 cleanup_save (&cr->save);
1216 #ifdef WITH_AGENT
1217 if (cr->ciphertext_sexp)
1218 gcry_sexp_release (cr->ciphertext_sexp);
1220 cr->ciphertext_sexp = NULL;
1221 #endif
1223 gcry_free (cr->plaintext);
1224 xfree (cr->ciphertext);
1225 xfree (cr->filename);
1226 cr->filename = NULL;
1227 cr->ciphertext = NULL;
1228 cr->ciphertext_len = 0;
1229 cr->plaintext = NULL;
1230 cr->plaintext_len = 0;
1233 static void
1234 cleanup_crypto_stage2 (struct crypto_s *cr)
1236 if (!cr)
1237 return;
1239 cleanup_crypto_stage1 (cr);
1240 set_header_defaults (&cr->hdr);
1243 static void
1244 cleanup_crypto (struct crypto_s **c)
1246 struct crypto_s *cr = *c;
1248 if (!cr)
1249 return;
1251 cleanup_crypto_stage2 (cr);
1253 #ifdef WITH_AGENT
1254 if (cr->pkey_sexp)
1255 gcry_sexp_release (cr->pkey_sexp);
1257 if (cr->sigpkey_sexp)
1258 gcry_sexp_release (cr->sigpkey_sexp);
1260 if (cr->agent)
1261 cleanup_agent (cr->agent);
1262 #endif
1264 xfree (cr);
1265 *c = NULL;
1268 /* Sets the default cipher values for new files. */
1269 static void
1270 set_header_defaults (file_header_t * hdr)
1272 char *s = "aes256";
1273 int flags = cipher_string_to_cipher (s);
1275 memset (hdr, 0, sizeof (file_header_t));
1276 memcpy (hdr->magic, crypto_magic, sizeof (hdr->magic));
1277 if (flags == -1)
1278 fprintf(stderr, _("Invalid 'cipher' in configuration file. Using a default of aes256."));
1280 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
1281 hdr->version = VERSION_HEX;
1283 #ifdef WITH_AGENT
1284 if (use_agent)
1285 hdr->flags |= PWMD_FLAG_PKI;
1286 #endif