build: Update configure.ac to use recent macros.
[pwmd.git] / src / pwmd-dump.c
blob73da11e47a0e5dc5a37bb50671f77d52ce8c23fc
1 /*
2 Copyright (C) 2015-2021 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"
68 #include "version.h"
70 #if 0
71 #ifdef WITH_AGENT
72 #include "agent.h"
73 #endif
74 #endif
76 #define PWMD_CIPHER_OFFSET (1)
77 #define PWMD_CIPHER(n) (PWMD_CIPHER_OFFSET << n)
78 #define PWMD_CIPHER_AES128 PWMD_CIPHER (0)
79 #define PWMD_CIPHER_AES192 PWMD_CIPHER (1)
80 #define PWMD_CIPHER_AES256 PWMD_CIPHER (2)
81 #define PWMD_CIPHER_SERPENT128 PWMD_CIPHER (3)
82 #define PWMD_CIPHER_SERPENT192 PWMD_CIPHER (4)
83 #define PWMD_CIPHER_SERPENT256 PWMD_CIPHER (5)
84 #define PWMD_CIPHER_CAMELLIA128 PWMD_CIPHER (6)
85 #define PWMD_CIPHER_CAMELLIA192 PWMD_CIPHER (7)
86 #define PWMD_CIPHER_CAMELLIA256 PWMD_CIPHER (8)
87 #define PWMD_CIPHER_3DES PWMD_CIPHER (9)
88 #define PWMD_CIPHER_CAST5 PWMD_CIPHER (10)
89 #define PWMD_CIPHER_BLOWFISH PWMD_CIPHER (11)
90 #define PWMD_CIPHER_TWOFISH PWMD_CIPHER (12)
91 #define PWMD_CIPHER_TWOFISH128 PWMD_CIPHER (13)
93 #define PWMD_FLAG_OFFSET (PWMD_CIPHER_OFFSET << 15)
94 #define PWMD_FLAG(n) (PWMD_FLAG_OFFSET << n)
95 #define PWMD_FLAG_PKI PWMD_FLAG (1)
96 #define PWMD_FLAG_NO_PASSPHRASE PWMD_FLAG (2)
98 #define KEYSIZE 32
100 typedef struct
102 uint8_t magic[5];
103 uint32_t version;
104 uint64_t s2k_count;
105 uint64_t flags;
106 uint8_t iv[16];
107 uint8_t salt[8];
108 uint32_t datalen; /* of the encrypted xml */
109 } __attribute__ ((packed)) file_header_t;
111 struct save_s
113 gcry_sexp_t pkey; /* SAVE --keygrip */
114 gcry_sexp_t sigpkey; /* SAVE --sign-keygrip */
115 file_header_t hdr;
118 struct crypto_s
120 //assuan_context_t client_ctx;
121 #ifdef WITH_AGENT
122 struct agent_s *agent;
123 #endif
124 struct save_s save;
125 gcry_sexp_t pkey_sexp;
126 unsigned char grip[20];
127 gcry_sexp_t sigpkey_sexp;
128 unsigned char sign_grip[20];
129 gcry_sexp_t ciphertext_sexp;
130 void *ciphertext;
131 size_t ciphertext_len;
132 void *plaintext;
133 size_t plaintext_len;
134 file_header_t hdr;
135 char *filename; /* the currently opened data file */
138 #define DEFAULT_KDFS2K_ITERATIONS 5000000
139 #define COMPAT_KDFS2K_ITERATIONS 1000
141 const char *reserved_attributes[] = {
142 "_name", "_mtime", "_ctime", "_acl", "_target",
143 NULL
145 static unsigned char crypto_magic[5] = "\177PWMD";
146 static int use_agent;
148 static void set_header_defaults (file_header_t * hdr);
149 static gpg_error_t decrypt_common (struct crypto_s *crypto,
150 const char *filename, const char *keyfile);
151 static gpg_error_t read_data_file (const char *filename,
152 struct crypto_s *crypto);
153 static void cleanup_crypto_stage1 (struct crypto_s *cr);
154 static void cleanup_crypto (struct crypto_s **c);
156 static int
157 cipher_to_gcrypt (int flags)
159 if (flags < 0)
160 return flags;
162 if (flags & PWMD_CIPHER_AES128)
163 return GCRY_CIPHER_AES128;
164 else if (flags & PWMD_CIPHER_AES192)
165 return GCRY_CIPHER_AES192;
166 else if (flags & PWMD_CIPHER_AES256)
167 return GCRY_CIPHER_AES256;
168 else if (flags & PWMD_CIPHER_SERPENT128)
169 return GCRY_CIPHER_SERPENT128;
170 else if (flags & PWMD_CIPHER_SERPENT192)
171 return GCRY_CIPHER_SERPENT192;
172 else if (flags & PWMD_CIPHER_SERPENT256)
173 return GCRY_CIPHER_SERPENT256;
174 else if (flags & PWMD_CIPHER_CAMELLIA128)
175 return GCRY_CIPHER_CAMELLIA128;
176 else if (flags & PWMD_CIPHER_CAMELLIA192)
177 return GCRY_CIPHER_CAMELLIA192;
178 else if (flags & PWMD_CIPHER_CAMELLIA256)
179 return GCRY_CIPHER_CAMELLIA256;
180 else if (flags & PWMD_CIPHER_BLOWFISH)
181 return GCRY_CIPHER_BLOWFISH;
182 else if (flags & PWMD_CIPHER_3DES)
183 return GCRY_CIPHER_3DES;
184 else if (flags & PWMD_CIPHER_CAST5)
185 return GCRY_CIPHER_CAST5;
186 else if (flags & PWMD_CIPHER_TWOFISH)
187 return GCRY_CIPHER_TWOFISH;
188 else if (flags & PWMD_CIPHER_TWOFISH128)
189 return GCRY_CIPHER_TWOFISH128;
191 return -1;
194 static int
195 cipher_string_to_cipher (const char *str)
197 int flags = 0;
199 if (!strcasecmp (str, "aes128"))
200 flags = PWMD_CIPHER_AES128;
201 else if (!strcasecmp (str, "aes192"))
202 flags = PWMD_CIPHER_AES192;
203 else if (!strcasecmp (str, "aes256"))
204 flags = PWMD_CIPHER_AES256;
205 else if (!strcasecmp (str, "serpent128"))
206 flags = PWMD_CIPHER_SERPENT128;
207 else if (!strcasecmp (str, "serpent192"))
208 flags = PWMD_CIPHER_SERPENT192;
209 else if (!strcasecmp (str, "serpent256"))
210 flags = PWMD_CIPHER_SERPENT256;
211 else if (!strcasecmp (str, "camellia128"))
212 flags = PWMD_CIPHER_CAMELLIA128;
213 else if (!strcasecmp (str, "camellia192"))
214 flags = PWMD_CIPHER_CAMELLIA192;
215 else if (!strcasecmp (str, "camellia256"))
216 flags = PWMD_CIPHER_CAMELLIA256;
217 else if (!strcasecmp (str, "blowfish"))
218 flags = PWMD_CIPHER_BLOWFISH;
219 else if (!strcasecmp (str, "cast5"))
220 flags = PWMD_CIPHER_CAST5;
221 else if (!strcasecmp (str, "3des"))
222 flags = PWMD_CIPHER_3DES;
223 else if (!strcasecmp (str, "twofish256"))
224 flags = PWMD_CIPHER_TWOFISH;
225 else if (!strcasecmp (str, "twofish128"))
226 flags = PWMD_CIPHER_TWOFISH128;
227 else
228 return -1;
230 return flags;
233 static void
234 usage (const char *pn, int rc)
236 fprintf(rc == EXIT_SUCCESS ? stdout : stderr,
237 "%s [-hvn] [--force] [-k <filename>] [--xml] <infile> <outfile>\n"
238 " --no-convert, -n don't discard data for elements with targets\n"
239 " --force don't abort when converting\n"
240 " --xml read a raw pwmd XML document\n"
241 " --keyfile, -k file containing the passphrase to use for decryption\n"
242 " --help\n"
243 " --version\n\n"
244 "Use - as <outfile> to write to standard output.\n",
245 pn);
246 exit (rc);
249 static gpg_error_t
250 init_client_crypto (struct crypto_s **crypto)
252 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
253 gpg_error_t rc;
255 if (!new)
257 rc = GPG_ERR_ENOMEM;
258 return rc;
261 #ifdef WITH_AGENT
262 if (use_agent)
264 rc = agent_init (&new->agent);
265 if (!rc)
267 rc = send_agent_common_options (new->agent);
268 if (!rc)
269 rc = agent_set_pinentry_options (new->agent);
272 if (rc)
274 cleanup_agent (new->agent);
275 xfree (new);
276 return rc;
279 #endif
281 set_header_defaults (&new->hdr);
282 *crypto = new;
283 return 0;
286 static gpg_error_t
287 parse_doc (const char *xml, size_t len, xmlDocPtr *result)
289 xmlDocPtr doc;
291 xmlResetLastError ();
292 doc = xmlReadMemory (xml, len, NULL, "UTF-8", XML_PARSE_NOBLANKS);
293 if (!doc && xmlGetLastError ())
294 return GPG_ERR_BAD_DATA;
296 *result = doc;
297 return !doc ? GPG_ERR_ENOMEM : 0;
300 static xmlChar *
301 xml_attribute_value (xmlNodePtr n, xmlChar * attr)
303 xmlAttrPtr a = xmlHasProp (n, attr);
305 if (!a)
306 return NULL;
308 if (!a->children || !a->children->content)
309 return NULL;
311 return xmlGetProp (n, attr);
314 static int
315 xml_reserved_attribute (const char *name)
317 int i;
319 for (i = 0; reserved_attributes[i]; i++)
321 if (!strcmp (name, reserved_attributes[i]))
322 return 1;
325 return 0;
327 static void
328 remove_non_reserved_attributes (xmlNodePtr n)
330 xmlAttrPtr a;
332 for (a = n->properties; a; a = a->next)
334 if (xml_reserved_attribute ((char *)a->name))
335 continue;
337 xmlRemoveProp (a);
341 static gpg_error_t
342 strip_literals (const char *filename, xmlNodePtr n, int force)
344 gpg_error_t rc = 0;
346 for (; n; n = n->next)
348 xmlChar *target;
350 if (n->type != XML_ELEMENT_NODE)
351 continue;
353 if (!xmlStrEqual (n->name, (xmlChar *) "element"))
355 xmlNodePtr tmp = n->next;
357 xmlUnlinkNode (n);
358 xmlFreeNodeList (n);
359 return strip_literals (filename, tmp, force);
362 target = xml_attribute_value (n, (xmlChar *)"_target");
363 if (target)
365 xmlChar lastc = 0, *p;
367 remove_non_reserved_attributes (n);
368 again:
369 for (lastc = 0, p = target; *p;)
371 if (*p == '!' && (p == target || lastc == '\t'))
373 xmlChar *c;
375 c = p;
376 while (*p)
377 *c++ = *++p;
378 *c = 0;
379 goto again;
382 lastc = *p++;
385 if (!xmlSetProp (n, (xmlChar *) "_target", target))
387 xmlFree (target);
388 return GPG_ERR_INV_VALUE;
391 xmlFree (target);
393 if (n->children && !force)
395 fprintf(stderr, _("%s: aborting do to literal child elements (use --force)\n"), filename);
396 return GPG_ERR_CANCELED;
398 else if (n->children)
400 xmlNodePtr tmp = n->children;
402 xmlUnlinkNode (n->children);
403 xmlFreeNodeList (tmp);
407 rc = strip_literals (filename, n->children, force);
408 if (rc)
409 break;
412 return rc;
415 static gpg_error_t
416 recurse_rename_attribute (xmlNodePtr root, const char *old, const char *name)
418 xmlNodePtr n;
419 gpg_error_t rc = 0;
421 for (n = root; n; n = n->next)
423 xmlAttrPtr attr = xmlHasProp (n, (xmlChar *)old);
425 if (attr)
427 xmlChar *a = xml_attribute_value (n, (xmlChar *)old);
429 if (a && !xmlSetProp (n, (xmlChar *) name, a))
430 rc = GPG_ERR_BAD_DATA;
432 xmlFree (a);
434 if (!rc)
436 if (xmlRemoveProp (attr) == -1)
437 rc = GPG_ERR_BAD_DATA;
441 if (rc)
442 break;
444 rc = recurse_rename_attribute (n->children, old, name);
445 if (rc)
446 break;
449 return rc;
452 static gpg_error_t
453 update_to_version (xmlDocPtr doc)
455 xmlNodePtr root = xmlDocGetRootElement (doc);
456 xmlChar *v = xml_attribute_value (root, (xmlChar *)"_version");
457 gpg_error_t rc;
459 // Pwmd 3.2.0 or later. No updates needed ATM.
460 if (v)
462 xmlFree (v);
463 return 0;
466 rc = recurse_rename_attribute (root->children, "target", "_target");
467 if (!rc)
468 rc = recurse_rename_attribute (root->children, "expire", "_expire");
470 if (!rc)
471 rc = recurse_rename_attribute (root->children, "expire_increment", "_age");
473 return rc;
477 main(int argc, char **argv)
479 gpg_error_t rc;
480 int opt, optindex;
481 struct crypto_s *crypto = NULL;
482 char *outfile = NULL, *infile = NULL, *keyfile = NULL;
483 void *key = NULL;
484 enum {
485 OPT_FORCE,
486 OPT_XML
488 const char *optstring = "vhk:n";
489 int convert = 1;
490 int force = 0;
491 int xml = 0;
492 const struct option longopts[] = {
493 {"force", no_argument, 0, 0},
494 {"xml", no_argument, 0, 0},
495 {"no-convert", no_argument, 0, 'n'},
496 {"keyfile", required_argument, 0, 'k'},
497 {"version", no_argument, 0, 'v'},
498 {"help", no_argument, 0, 'h'},
499 {0, 0, 0, 0}
502 #ifndef DEBUG
503 #ifdef HAVE_SETRLIMIT
504 struct rlimit rl;
506 rl.rlim_cur = rl.rlim_max = 0;
508 if (setrlimit (RLIMIT_CORE, &rl) != 0)
509 err (EXIT_FAILURE, "setrlimit()");
510 #endif
512 #ifdef HAVE_PR_SET_DUMPABLE
513 prctl (PR_SET_DUMPABLE, 0);
514 #endif
515 #endif
517 if (!gpgrt_check_version (REQUIRE_LIBGPGERROR_VERSION))
519 fprintf (stderr, _("gpgrt_check_version(): Incompatible libgpg-error. "
520 "Wanted %s, got %s.\n"), REQUIRE_LIBGPGERROR_VERSION,
521 gpgrt_check_version (NULL));
522 exit (EXIT_FAILURE);
525 gpgrt_init ();
526 //gpgrt_set_alloc_func (xrealloc_gpgrt);
528 if (!gcry_check_version (REQUIRE_LIBGCRYPT_VERSION))
530 fprintf (stderr, _("gcry_check_version(): Incompatible libgcrypt. "
531 "Wanted %s, got %s.\n"), REQUIRE_LIBGCRYPT_VERSION,
532 gcry_check_version (NULL));
533 exit (EXIT_FAILURE);
536 gcry_set_allocation_handler (xmalloc, xmalloc, NULL, xrealloc, xfree);
537 xmlMemSetup (xfree, xmalloc, xrealloc, str_dup);
538 xmlInitMemory ();
539 xmlInitGlobals ();
540 xmlInitParser ();
541 xmlXPathInit ();
543 while ((opt = getopt_long (argc, argv, optstring, longopts, &optindex)) != -1)
545 switch (opt)
547 case 'n':
548 convert = 0;
549 break;
550 case 'k':
551 keyfile = optarg;
552 break;
553 case 'h':
554 usage (argv[0], EXIT_SUCCESS);
555 break;
556 case 'v':
557 printf (_("%s\n\n"
558 "Copyright (C) 2015-2021\n"
559 "%s\n"
560 "Released under the terms of the GPL v2. Use at your own risk.\n\n"),
561 PACKAGE_STRING PWMD_GIT_HASH, PACKAGE_BUGREPORT);
562 exit (EXIT_SUCCESS);
563 case 0:
564 switch (optindex)
566 case OPT_FORCE:
567 force = 1;
568 break;
569 case OPT_XML:
570 xml = 1;
571 break;
572 default:
573 usage (argv[0], EXIT_FAILURE);
575 break;
576 default:
577 usage (argv[0], EXIT_FAILURE);
578 break;
582 if (argc - optind != 2)
583 usage (argv[0], EXIT_FAILURE);
585 infile = argv[optind++];
586 outfile = argv[optind];
587 if (strcmp (outfile, "-"))
589 if (access (outfile, R_OK|W_OK) == 0)
591 fprintf(stderr, _("Please remove the existing output file '%s'.\n"),
592 outfile);
593 exit (EXIT_FAILURE);
597 rc = init_client_crypto (&crypto);
598 if (rc)
599 goto fail;
601 if (!xml)
603 rc = decrypt_common (crypto, infile, keyfile);
604 xfree (key);
606 else
608 struct stat st;
609 int fd;
611 fd = open (infile, O_RDONLY);
612 if (fd == -1)
614 rc = gpg_error_from_syserror ();
615 goto fail;
618 if (fstat (fd, &st) == -1)
620 rc = gpg_error_from_syserror ();
621 close (fd);
622 goto fail;
625 crypto->plaintext = gcry_calloc (1, sizeof (char) * st.st_size+1);
626 if (!crypto->plaintext)
628 close (fd);
629 rc = GPG_ERR_ENOMEM;
630 goto fail;
633 crypto->plaintext_len = read (fd, crypto->plaintext, st.st_size);
634 close (fd);
635 if (crypto->plaintext_len != st.st_size)
637 rc = GPG_ERR_UNKNOWN_ERRNO;
638 goto fail;
642 if (!rc)
644 xmlDocPtr doc;
646 rc = parse_doc ((char *) crypto->plaintext, crypto->plaintext_len, &doc);
647 cleanup_crypto (&crypto);
648 if (!rc)
650 xmlChar *buf;
651 int len;
652 xmlNodePtr n;
654 FILE *fp = outfile[0] == '-' && outfile[1] == 0 ? stdout
655 : fopen (outfile, "w");
657 if (!fp)
659 rc = gpg_error_from_syserror ();
660 xmlFreeDoc (doc);
661 goto fail;
664 if (convert)
666 n = xmlDocGetRootElement (doc);
667 rc = strip_literals (infile, n->children, force);
668 if (rc)
670 xmlFreeDoc (doc);
671 goto fail;
674 rc = update_to_version (doc);
675 if (rc)
677 xmlFreeDoc (doc);
678 goto fail;
681 n = xmlDocGetRootElement (doc);
682 if (!xmlSetProp (n, (xmlChar *) "_version",
683 (xmlChar *)PACKAGE_VERSION))
684 rc = GPG_ERR_BAD_DATA;
685 if (rc)
687 xmlFreeDoc (doc);
688 goto fail;
692 xmlDocDumpMemory (doc, &buf, &len);
693 xmlFreeDoc (doc);
694 fprintf (fp, "%s", buf);
695 xmlFree (buf);
696 fclose (fp);
698 else
699 goto fail;
701 else
702 goto fail;
704 cleanup_crypto (&crypto);
705 exit (EXIT_SUCCESS);
707 fail:
708 cleanup_crypto (&crypto);
709 fprintf(stderr, "ERR %u: %s\n", rc, gpg_strerror (rc));
710 exit (EXIT_FAILURE);
713 static gpg_error_t
714 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
715 size_t keylen, void **result, size_t *rlen, uint64_t iterations)
717 gpg_error_t rc;
718 void *tmp;
720 /* Be sure the algorithm is available. */
721 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
722 if (rc)
723 return rc;
725 /* Always allocate enough for a 256-bit key although the algorithms
726 themselves may use less. Fixes SAVE --cipher with a different
727 keylen than the previously saved cipher when cached. */
728 *rlen = 32;
729 tmp = xmalloc (*rlen);
730 if (!tmp)
731 return GPG_ERR_ENOMEM;
733 if (!iterations)
734 iterations = DEFAULT_KDFS2K_ITERATIONS;
736 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
737 salt, salt_len, iterations, *rlen, tmp);
738 if (!rc)
739 *result = tmp;
740 else
741 xfree (tmp);
743 return rc;
747 * Useful for a large amount of data. Rather than doing all of the data in one
748 * iteration do it in chunks. This lets the command be cancelable rather than
749 * waiting for it to complete.
751 #define CRYPTO_BLOCKSIZE(c) (c * 1024)
752 static gpg_error_t
753 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
754 size_t insize, size_t blocksize)
756 gpg_error_t rc = 0;
757 off_t len = CRYPTO_BLOCKSIZE (blocksize);
758 void *p = gcry_malloc (len);
759 off_t total = 0;
761 if (!p)
762 return gpg_error (GPG_ERR_ENOMEM);
764 if (insize < CRYPTO_BLOCKSIZE (blocksize))
765 len = insize;
767 pthread_cleanup_push (gcry_free, p);
769 for (;;)
771 unsigned char *inbuf2 = inbuf + total;
772 unsigned char *tmp;
774 if (len + total > insize)
775 len = blocksize;
777 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
778 if (rc)
779 break;
781 tmp = inbuf + total;
782 memmove (tmp, p, len);
783 total += len;
784 if (total >= insize)
785 break;
787 #ifdef HAVE_PTHREAD_TESTCANCEL
788 pthread_testcancel ();
789 #endif
792 pthread_cleanup_pop (1);
793 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
794 rc = gpg_error (rc);
796 return rc;
799 static void
800 cleanup_cipher (void *arg)
802 gcry_cipher_close ((gcry_cipher_hd_t) arg);
805 /* Decrypt the XML data. For PKI data files the key is retrieved from
806 * gpg-agent and the signature verified. */
807 static gpg_error_t
808 decrypt_data (struct crypto_s *crypto, unsigned char *salted_key,
809 size_t skeylen)
811 gpg_error_t rc = 0;
812 unsigned char *key = salted_key;
813 gcry_cipher_hd_t h = NULL;
814 size_t blocksize, keysize = 0;
815 int algo = cipher_to_gcrypt (crypto->hdr.flags);
816 void *outbuf = NULL;
817 uint64_t n;
818 #ifdef WITH_AGENT
819 size_t keylen = skeylen;
820 gcry_sexp_t sig_sexp;
822 if (crypto->hdr.flags & PWMD_FLAG_PKI)
824 rc = agent_extract_key (crypto, &key, &keylen);
825 if (rc)
826 return rc;
828 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
829 if (!sig_sexp)
831 gcry_free (key);
832 return GPG_ERR_BAD_DATA;
835 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
836 crypto->ciphertext_len);
837 gcry_sexp_release (sig_sexp);
839 #endif
841 (void)skeylen;
842 if (!rc)
844 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
845 if (!rc)
847 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
848 &keysize);
849 if (!rc)
851 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
852 &blocksize);
853 if (!rc)
855 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
856 if (!rc)
858 rc = gcry_cipher_setkey (h, key, keysize);
865 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
867 if (!rc)
869 outbuf = gcry_malloc (crypto->hdr.datalen+1);
870 if (!outbuf)
871 rc = GPG_ERR_ENOMEM;
872 else
873 memset (outbuf, 0, crypto->hdr.datalen+1);
876 pthread_cleanup_push (gcry_free, outbuf);
877 #ifdef WITH_AGENT
878 pthread_cleanup_push (gcry_free, key);
879 #endif
881 if (!rc)
883 if (!key)
884 rc = GPG_ERR_INV_PARAMETER;
885 else
887 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
888 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
891 if (!rc && crypto->hdr.version <= 0x03000e)
893 key[0] ^= 1;
894 rc = gcry_cipher_setkey (h, key, keysize);
898 if (!rc && crypto->hdr.version <= 0x03000e)
900 for (n = 0; !rc && n < crypto->hdr.s2k_count; n++)
902 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
903 if (rc)
904 break;
906 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize);
910 #ifdef WITH_AGENT
911 pthread_cleanup_pop (0);
912 if (crypto->hdr.flags & PWMD_FLAG_PKI)
913 gcry_free (key);
914 else if (key && crypto->hdr.version <= 0x03000e)
915 key[0] ^= 1;
916 #else
917 if (crypto->hdr.version <= 0x03000e && key)
918 key[0] ^= 1;
919 #endif
920 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
921 pthread_cleanup_pop (1); /* cipher */
922 if (!rc)
924 char buf[] = "<?xml ";
926 if (memcmp (outbuf, buf, sizeof(buf)-1))
928 gcry_free (outbuf);
929 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
932 crypto->plaintext = outbuf;
933 crypto->plaintext_len = crypto->hdr.datalen;
936 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
937 rc = gpg_error (rc);
939 return rc;
942 static gpg_error_t
943 get_passphrase (const char *filename, const char *keyfile, void **r_key,
944 size_t *r_len)
946 char buf[255] = { 0 };
947 struct termios told, tnew;
949 *r_len = 0;
951 if (keyfile)
953 ssize_t len;
954 struct stat st;
955 int fd;
957 fd = open (keyfile, O_RDONLY);
958 if (fd == -1)
959 return gpg_error_from_syserror ();
961 if (fstat (fd, &st) == -1)
963 gpg_error_t rc = gpg_error_from_syserror ();
965 close (fd);
966 return rc;
969 len = read (fd, buf, sizeof (buf));
970 if (len != st.st_size)
972 close (fd);
973 wipememory (buf, 0, sizeof (buf));
974 return gpg_error_from_syserror ();
977 *r_len = st.st_size ? st.st_size : 1;
978 *r_key = xmalloc (*r_len);
979 if (*r_key)
980 memcpy (*r_key, buf, *r_len);
981 wipememory (buf, 0, sizeof (buf));
982 close (fd);
983 return *r_key ? 0 : GPG_ERR_ENOMEM;
986 if (!isatty (STDIN_FILENO))
987 return GPG_ERR_ENOTTY;
989 if (tcgetattr (STDIN_FILENO, &told) == -1)
990 return gpg_error_from_syserror ();
992 memcpy (&tnew, &told, sizeof (struct termios));
993 tnew.c_lflag &= ~(ECHO);
994 tnew.c_lflag |= ICANON | ECHONL;
995 if (tcsetattr (STDIN_FILENO, TCSANOW, &tnew) == -1)
997 int n = errno;
999 tcsetattr (STDIN_FILENO, TCSANOW, &told);
1000 return gpg_error_from_errno (n);
1003 fprintf(stderr, "Passphrase for '%s': ", filename);
1004 if (!fgets (buf, sizeof (buf), stdin))
1006 tcsetattr (STDIN_FILENO, TCSANOW, &told);
1007 return GPG_ERR_EOF;
1010 tcsetattr (STDIN_FILENO, TCSANOW, &told);
1012 if (buf[strlen(buf)-1] == '\n')
1013 buf[strlen(buf)-1] = 0;
1014 *r_len = buf[0] == 0 ? 1 : strlen (buf);
1015 *r_key = str_dup (buf);
1016 wipememory (buf, 0, sizeof (buf));
1017 return 0;
1020 /* Common to both PKI and non-PKI files. */
1021 static gpg_error_t
1022 decrypt_common (struct crypto_s *crypto, const char *filename,
1023 const char *keyfile)
1025 void *key = NULL;
1026 size_t keylen = 0;
1027 gpg_error_t rc = read_data_file (filename, crypto);
1028 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1029 void *skey = NULL;
1030 size_t skeysize = 0;
1032 if (rc)
1033 return rc;
1035 rc = get_passphrase (filename, keyfile, &key, &keylen);
1036 if (rc)
1037 return rc;
1039 if (key)// && !IS_PKI (crypto))
1041 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1042 keylen, &skey, &skeysize,
1043 crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : crypto->hdr.s2k_count);
1044 if (rc)
1046 xfree (key);
1047 return rc;
1051 xfree (key);
1052 xfree (crypto->filename);
1053 crypto->filename = str_dup (filename);
1054 rc = decrypt_data (crypto, skey, skeysize);
1055 xfree (skey);
1056 return rc;
1059 static gpg_error_t
1060 read_header (file_header_t *hdr, int fd)
1062 ssize_t len;
1063 uint32_t i;
1064 uint64_t n;
1066 #ifdef WORDS_BIGENDIAN
1067 len = read (fd, &hdr->magic, sizeof(hdr->magic));
1068 if (len == -1)
1069 goto done;
1071 len = read (fd, &hdr->version, sizeof(hdr->version));
1072 if (len == -1)
1073 goto done;
1075 len = read (fd, &hdr->s2k_count, sizeof(hdr->s2k_count));
1076 if (len == -1)
1077 goto done;
1079 len = read (fd, &hdr->flags, sizeof(hdr->flags));
1080 if (len == -1)
1081 goto done;
1083 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1084 if (len == -1)
1085 goto done;
1087 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1088 if (len == -1)
1089 goto done;
1091 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
1092 if (len == -1)
1093 goto done;
1094 #else
1095 len = read (fd, &hdr->magic, sizeof(hdr->magic));
1096 if (len == -1)
1097 goto done;
1099 len = read (fd, &i, sizeof(hdr->version));
1100 if (len == -1)
1101 goto done;
1102 hdr->version = ntohl (i);
1104 len = read (fd, &n, sizeof(hdr->s2k_count));
1105 if (len == -1)
1106 goto done;
1107 hdr->s2k_count = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1109 len = read (fd, &n, sizeof(hdr->flags));
1110 if (len == -1)
1111 goto done;
1112 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
1114 len = read (fd, &hdr->iv, sizeof(hdr->iv));
1115 if (len == -1)
1116 goto done;
1118 len = read (fd, &hdr->salt, sizeof(hdr->salt));
1119 if (len == -1)
1120 goto done;
1122 len = read (fd, &i, sizeof(hdr->datalen));
1123 if (len == -1)
1124 goto done;
1125 hdr->datalen = ntohl (i);
1126 #endif
1128 done:
1129 return len == -1 ? gpg_error_from_errno (errno) : 0;
1132 /* Read the header of a data file to determine cipher and other. The
1133 * header is stored big endian in the file and is converted to little
1134 * endian when needed. */
1135 static gpg_error_t
1136 read_data_header (const char *filename, file_header_t * rhdr,
1137 struct stat *rst, int *rfd)
1139 gpg_error_t rc = 0;
1140 struct stat st;
1141 file_header_t hdr;
1142 int fd;
1144 *rfd = -1;
1145 fd = open (filename, O_RDONLY);
1146 if (fd == -1)
1147 return gpg_error_from_syserror ();
1149 if (fstat (fd, &st) == -1)
1151 rc = gpg_error_from_syserror ();
1152 close (fd);
1153 return rc;
1156 rc = read_header (&hdr, fd);
1157 if (!rc && memcmp (hdr.magic, crypto_magic, sizeof (hdr.magic)))
1158 rc = GPG_ERR_BAD_DATA;
1159 else if (!rc && hdr.version < 0x030000)
1160 rc = GPG_ERR_UNKNOWN_VERSION;
1162 if (rc)
1163 close (fd);
1164 else
1166 if (rhdr)
1167 *rhdr = hdr;
1168 if (rst)
1169 *rst = st;
1170 if (rfd)
1171 *rfd = fd;
1172 else
1173 close (fd);
1176 return gpg_error (rc);
1179 static gpg_error_t
1180 read_data_file (const char *filename, struct crypto_s * crypto)
1182 int fd;
1183 gpg_error_t rc = 0;
1184 size_t len, rlen;
1185 char *buf = NULL;
1186 struct stat st;
1188 if (!filename)
1189 return GPG_ERR_INV_PARAMETER;
1191 cleanup_crypto_stage1 (crypto);
1192 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
1193 if (rc)
1194 return gpg_error (rc);
1196 crypto->ciphertext_len = crypto->hdr.datalen;
1197 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
1198 if (!crypto->ciphertext)
1200 rc = GPG_ERR_ENOMEM;
1201 goto done;
1204 /* The keygrips for PKI files are stored after the header. They are
1205 * stored in the file to let file(1) magic(5) show the grips. */
1206 if (crypto->hdr.flags & PWMD_FLAG_PKI)
1208 rlen = read (fd, crypto->grip, 20);
1209 if (rlen != 20)
1211 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1212 goto done;
1215 rlen = read (fd, crypto->sign_grip, 20);
1216 if (rlen != 20)
1218 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1219 goto done;
1223 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
1224 if (len != crypto->hdr.datalen)
1226 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1227 goto done;
1230 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
1231 goto done;
1233 if (!use_agent)
1235 rc = GPG_ERR_NOT_IMPLEMENTED;
1236 goto done;
1239 #ifdef WITH_AGENT
1240 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
1241 buf = xmalloc (len);
1242 if (!buf)
1244 rc = GPG_ERR_ENOMEM;
1245 goto done;
1248 /* Remaining data file bytes are the encrypted key and XML. */
1249 rlen = read (fd, buf, len);
1250 if (rlen != len)
1252 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
1253 goto done;
1256 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
1257 if (rc)
1258 goto done;
1260 if (crypto->pkey_sexp)
1261 gcry_sexp_release (crypto->pkey_sexp);
1263 if (crypto->sigpkey_sexp)
1264 gcry_sexp_release (crypto->sigpkey_sexp);
1266 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
1267 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
1268 if (!rc)
1269 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
1270 #endif
1272 done:
1273 close (fd);
1274 xfree (buf);
1275 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
1276 rc = gpg_error (rc);
1278 return rc;
1281 static void
1282 cleanup_save (struct save_s *save)
1284 if (!save)
1285 return;
1287 #ifdef WITH_AGENT
1288 if (save->pkey)
1289 gcry_sexp_release (save->pkey);
1291 if (save->sigpkey)
1292 gcry_sexp_release (save->sigpkey);
1293 #endif
1295 memset (save, 0, sizeof (struct save_s));
1298 /* Keep the agent ctx to retain pinentry options which will be freed in
1299 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
1300 static void
1301 cleanup_crypto_stage1 (struct crypto_s *cr)
1303 if (!cr)
1304 return;
1306 cleanup_save (&cr->save);
1308 #ifdef WITH_AGENT
1309 if (cr->ciphertext_sexp)
1310 gcry_sexp_release (cr->ciphertext_sexp);
1312 cr->ciphertext_sexp = NULL;
1313 #endif
1315 gcry_free (cr->plaintext);
1316 xfree (cr->ciphertext);
1317 xfree (cr->filename);
1318 cr->filename = NULL;
1319 cr->ciphertext = NULL;
1320 cr->ciphertext_len = 0;
1321 cr->plaintext = NULL;
1322 cr->plaintext_len = 0;
1325 static void
1326 cleanup_crypto_stage2 (struct crypto_s *cr)
1328 if (!cr)
1329 return;
1331 cleanup_crypto_stage1 (cr);
1332 set_header_defaults (&cr->hdr);
1335 static void
1336 cleanup_crypto (struct crypto_s **c)
1338 struct crypto_s *cr = *c;
1340 if (!cr)
1341 return;
1343 cleanup_crypto_stage2 (cr);
1345 #ifdef WITH_AGENT
1346 if (cr->pkey_sexp)
1347 gcry_sexp_release (cr->pkey_sexp);
1349 if (cr->sigpkey_sexp)
1350 gcry_sexp_release (cr->sigpkey_sexp);
1352 if (cr->agent)
1353 cleanup_agent (cr->agent);
1354 #endif
1356 xfree (cr);
1357 *c = NULL;
1360 /* Sets the default cipher values for new files. */
1361 static void
1362 set_header_defaults (file_header_t * hdr)
1364 const char *s = "aes256";
1365 int flags = cipher_string_to_cipher (s);
1367 memset (hdr, 0, sizeof (file_header_t));
1368 memcpy (hdr->magic, crypto_magic, sizeof (hdr->magic));
1369 if (flags == -1)
1370 fprintf(stderr, _("Invalid 'cipher' in configuration file. Using a default of aes256."));
1372 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
1373 hdr->version = VERSION_HEX;
1375 #ifdef WITH_AGENT
1376 if (use_agent)
1377 hdr->flags |= PWMD_FLAG_PKI;
1378 #endif