Fix crash on bad passphrase.
[pwmd.git] / src / crypto.c
blobca84fd3e0a566727e8cbd1d91d543448e0655470
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
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 <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
32 #include "pwmd-error.h"
33 #include "util-misc.h"
34 #include "common.h"
35 #include "rcfile.h"
36 #include "pinentry.h"
37 #include "crypto.h"
38 #include "cache.h"
39 #include "mem.h"
40 #include "util-string.h"
42 static uint8_t pwmd_magic[5] = { '\177', 'P', 'W', 'M', 'D' };
44 /* Sets the default cipher values for new files. */
45 void
46 set_header_defaults (file_header_t * hdr)
48 char *s = config_get_string (NULL, "cipher");
49 int flags = cipher_string_to_cipher (s);
51 xfree (s);
52 memset (hdr, 0, sizeof (file_header_t));
53 memcpy (hdr->magic, pwmd_magic, sizeof (hdr->magic));
54 if (flags == -1)
55 log_write (_
56 ("Invalid 'cipher' in configuration file. Using a default of aes256."));
57 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
58 hdr->version = VERSION_HEX;
60 #ifdef WITH_AGENT
61 if (use_agent)
62 hdr->flags |= PWMD_FLAG_PKI;
63 #endif
66 static gpg_error_t
67 read_header (file_header_t *hdr, int fd)
69 ssize_t len;
70 uint32_t i;
71 uint64_t n;
73 #ifdef WORDS_BIGENDIAN
74 len = read (fd, &hdr->magic, sizeof(hdr->magic));
75 if (len == -1)
76 goto done;
78 len = read (fd, &hdr->version, sizeof(hdr->version));
79 if (len == -1)
80 goto done;
82 len = read (fd, &hdr->iterations, sizeof(hdr->iterations));
83 if (len == -1)
84 goto done;
86 len = read (fd, &hdr->flags, sizeof(hdr->flags));
87 if (len == -1)
88 goto done;
90 len = read (fd, &hdr->iv, sizeof(hdr->iv));
91 if (len == -1)
92 goto done;
94 len = read (fd, &hdr->salt, sizeof(hdr->salt));
95 if (len == -1)
96 goto done;
98 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
99 if (len == -1)
100 goto done;
101 #else
102 len = read (fd, &hdr->magic, sizeof(hdr->magic));
103 if (len == -1)
104 goto done;
106 len = read (fd, &i, sizeof(hdr->version));
107 if (len == -1)
108 goto done;
109 hdr->version = ntohl (i);
111 len = read (fd, &n, sizeof(hdr->iterations));
112 if (len == -1)
113 goto done;
114 hdr->iterations = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
116 len = read (fd, &n, sizeof(hdr->flags));
117 if (len == -1)
118 goto done;
119 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
121 len = read (fd, &hdr->iv, sizeof(hdr->iv));
122 if (len == -1)
123 goto done;
125 len = read (fd, &hdr->salt, sizeof(hdr->salt));
126 if (len == -1)
127 goto done;
129 len = read (fd, &i, sizeof(hdr->datalen));
130 if (len == -1)
131 goto done;
132 hdr->datalen = ntohl (i);
133 #endif
135 done:
136 return len == -1 ? gpg_error_from_errno (errno) : 0;
139 /* Read the header of a data file to determine cipher and other. The
140 * header is stored big endian in the file and is converted to little
141 * endian when needed. */
142 gpg_error_t
143 read_data_header (const char *filename, file_header_t * rhdr,
144 struct stat *rst, int *rfd)
146 gpg_error_t rc = 0;
147 struct stat st;
148 file_header_t hdr;
149 int fd;
151 if (lstat (filename, &st) == -1)
152 return gpg_error_from_errno (errno);
154 if (!S_ISREG (st.st_mode))
155 return gpg_error (GPG_ERR_ENOANO);
157 fd = open (filename, O_RDONLY);
158 if (fd == -1)
159 return gpg_error_from_errno (errno);
161 rc = read_header (&hdr, fd);
162 if (!rc && memcmp (hdr.magic, pwmd_magic, sizeof (hdr.magic)))
163 rc = GPG_ERR_BAD_DATA;
164 else if (!rc && hdr.version < 0x030000)
165 rc = GPG_ERR_UNKNOWN_VERSION;
167 if (rc)
168 close (fd);
169 else
171 if (rhdr)
172 *rhdr = hdr;
173 if (rst)
174 *rst = st;
175 if (rfd)
176 *rfd = fd;
177 else
178 close (fd);
181 return gpg_error (rc);
184 gpg_error_t
185 read_data_file (const char *filename, struct crypto_s * crypto)
187 int fd;
188 gpg_error_t rc = 0;
189 size_t len, rlen;
190 char *buf = NULL;
191 struct stat st;
193 if (!filename)
194 return GPG_ERR_INV_PARAMETER;
196 cleanup_crypto_stage1 (crypto);
197 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
198 if (rc)
199 return gpg_error (rc);
201 crypto->ciphertext_len = crypto->hdr.datalen;
202 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
203 if (!crypto->ciphertext)
205 rc = GPG_ERR_ENOMEM;
206 goto done;
209 /* The keygrips for PKI files are stored after the header. They are
210 * stored in the file to let file(1) magic(5) show the grips. */
211 if (crypto->hdr.flags & PWMD_FLAG_PKI)
213 rlen = read (fd, crypto->grip, 20);
214 if (rlen != 20)
216 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
217 goto done;
220 rlen = read (fd, crypto->sign_grip, 20);
221 if (rlen != 20)
223 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
224 goto done;
228 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
229 if (len != crypto->hdr.datalen)
231 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
232 goto done;
235 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
236 goto done;
238 if (!use_agent)
240 rc = GPG_ERR_NOT_IMPLEMENTED;
241 goto done;
244 #ifdef WITH_AGENT
245 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
246 buf = xmalloc (len);
247 if (!buf)
249 rc = GPG_ERR_ENOMEM;
250 goto done;
253 /* Remaining data file bytes are the encrypted key and XML. */
254 rlen = read (fd, buf, len);
255 if (rlen != len)
257 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
258 goto done;
261 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
262 if (rc)
263 goto done;
265 if (crypto->pkey_sexp)
266 gcry_sexp_release (crypto->pkey_sexp);
268 if (crypto->sigpkey_sexp)
269 gcry_sexp_release (crypto->sigpkey_sexp);
271 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
272 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
273 if (!rc)
274 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
275 #endif
277 done:
278 close (fd);
279 xfree (buf);
280 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
281 rc = gpg_error (rc);
283 return rc;
286 #define CRYPTO_BLOCKSIZE(c) (blocksize * 1024)
289 * Useful for a large amount of data. Rather than doing all of the data in one
290 * iteration do it in chunks. This lets the command be cancelable rather than
291 * waiting for it to complete.
293 static gpg_error_t
294 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
295 size_t insize, size_t blocksize, status_msg_t which)
297 gpg_error_t rc = 0;
298 off_t len = CRYPTO_BLOCKSIZE (blocksize);
299 void *p = gcry_malloc (len);
300 off_t total = 0;
302 if (!p)
303 return gpg_error (GPG_ERR_ENOMEM);
305 if (insize < CRYPTO_BLOCKSIZE (blocksize))
306 len = insize;
308 pthread_cleanup_push (gcry_free, p);
310 for (;;)
312 unsigned char *inbuf2 = inbuf + total;
313 unsigned char *tmp;
315 if (len + total > insize)
316 len = blocksize;
318 if (which == STATUS_ENCRYPT)
319 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
320 else
321 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
323 if (rc)
324 break;
326 tmp = inbuf + total;
327 memmove (tmp, p, len);
328 total += len;
329 if (total >= insize)
330 break;
332 #ifdef HAVE_PTHREAD_TESTCANCEL
333 pthread_testcancel ();
334 #endif
337 pthread_cleanup_pop (1);
338 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
339 rc = gpg_error (rc);
341 return rc;
344 static void
345 cleanup_cipher (void *arg)
347 gcry_cipher_close ((gcry_cipher_hd_t) arg);
350 /* Decrypt the XML data. For PKI data files the key is retrieved from
351 * gpg-agent and the signature verified. */
352 gpg_error_t
353 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
354 unsigned char *salted_key, size_t skeylen)
356 gpg_error_t rc = 0;
357 unsigned char *key = salted_key;
358 gcry_cipher_hd_t h = NULL;
359 size_t blocksize, keysize = 0;
360 int algo = cipher_to_gcrypt (crypto->hdr.flags);
361 void *outbuf = NULL;
362 uint64_t n = crypto->hdr.iterations;
363 long progress = 0;
364 #ifdef WITH_AGENT
365 size_t keylen = skeylen;
366 gcry_sexp_t sig_sexp;
368 if (crypto->hdr.flags & PWMD_FLAG_PKI)
370 rc = agent_extract_key (crypto, &key, &keylen);
371 if (rc)
372 return rc;
374 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
375 if (!sig_sexp)
377 gcry_free (key);
378 return GPG_ERR_BAD_DATA;
381 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
382 crypto->ciphertext_len);
383 gcry_sexp_release (sig_sexp);
385 #endif
387 if (!rc)
389 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
390 if (!rc)
392 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
393 &keysize);
394 if (!rc)
396 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
397 &blocksize);
398 if (!rc)
400 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
401 if (!rc)
403 rc = gcry_cipher_setkey (h, key, keysize);
410 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
412 if (!rc)
414 outbuf = gcry_malloc (crypto->hdr.datalen);
415 if (!outbuf)
416 rc = GPG_ERR_ENOMEM;
419 pthread_cleanup_push (gcry_free, outbuf);
420 #ifdef WITH_AGENT
421 pthread_cleanup_push (gcry_free, key);
422 #endif
424 if (!rc)
426 if (!key)
427 rc = GPG_ERR_INV_PARAMETER;
428 else
430 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
431 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
432 STATUS_DECRYPT);
435 if (!rc)
437 key[0] ^= 1;
438 rc = gcry_cipher_setkey (h, key, keysize);
442 if (!rc)
444 progress = config_get_long (NULL, "cipher_progress");
445 if (progress == -1)
446 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
449 if (!rc && ctx && crypto->hdr.iterations)
450 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", 0,
451 crypto->hdr.iterations);
453 for (n = 0; !rc && n < crypto->hdr.iterations; n++)
455 if (ctx && progress && !(n % progress))
457 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
458 crypto->hdr.iterations);
459 if (rc)
460 break;
463 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
464 if (rc)
465 break;
467 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
468 STATUS_DECRYPT);
471 if (!rc && ctx && crypto->hdr.iterations)
472 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
473 crypto->hdr.iterations);
475 #ifdef WITH_AGENT
476 pthread_cleanup_pop (0);
477 if (crypto->hdr.flags & PWMD_FLAG_PKI)
478 gcry_free (key);
479 else if (key)
480 key[0] ^= 1;
481 #else
482 key[0] ^= 1;
483 #endif
484 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
485 pthread_cleanup_pop (1); /* cipher */
486 if (!rc)
488 char buf[] = "<?xml ";
490 if (memcmp (outbuf, buf, sizeof(buf)-1))
492 gcry_free (outbuf);
493 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
496 crypto->plaintext = outbuf;
497 crypto->plaintext_len = crypto->hdr.datalen;
500 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
501 rc = gpg_error (rc);
503 return rc;
506 /* The cached document is encrypted with encrypt_xml(). This decrypts
507 * it from the OPEN command. */
508 gpg_error_t
509 decrypt_cache (struct crypto_s * crypto, const void *data, size_t len)
511 gcry_cipher_hd_t h = NULL;
512 gpg_error_t rc;
514 rc = gcry_cipher_open (&h, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
515 if (rc)
516 return rc;
518 gcry_free (crypto->plaintext);
519 crypto->plaintext = gcry_malloc (len);
520 if (!crypto->plaintext)
522 rc = GPG_ERR_ENOMEM;
523 goto done;
526 rc = gcry_cipher_setiv (h, cache_iv, cache_blocksize);
527 if (rc)
528 goto done;
530 rc = gcry_cipher_setkey (h, cache_key, cache_keysize);
531 if (rc)
532 goto done;
534 rc = gcry_cipher_decrypt (h, crypto->plaintext, len, data, len);
535 if (rc || strncmp (crypto->plaintext, "<?xml ", 6))
537 if (!rc)
538 rc = GPG_ERR_BAD_DATA;
540 gcry_free (crypto->plaintext);
541 crypto->plaintext = NULL;
544 crypto->plaintext_len = len;
546 done:
547 if (h)
548 gcry_cipher_close (h);
550 return rc;
553 /* Encrypt the XML data and set 'result'. At least one encryption
554 * iteration is done. */
555 gpg_error_t
556 encrypt_xml (assuan_context_t ctx, void *key, size_t keylen,
557 int algo, const void *xml, size_t len, void * *result,
558 size_t *result_len, unsigned char **iv, size_t * iv_len,
559 uint64_t iter)
561 gpg_error_t rc;
562 gcry_cipher_hd_t h;
563 size_t blocksize, keysize;
564 void *inbuf = NULL;
565 size_t olen = len;
566 uint64_t n = 0;
567 unsigned char *tmpkey = NULL;
568 int init_iv = *(iv_len) == 0;
570 if (!key)
571 return GPG_ERR_INV_PARAMETER;
573 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
574 if (rc)
575 return rc;
577 pthread_cleanup_push (cleanup_cipher, h);
578 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
579 if (!rc)
580 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL, &blocksize);
582 if (!rc && init_iv)
584 *(iv) = xmalloc (blocksize);
585 if (!*(iv))
586 rc = GPG_ERR_ENOMEM;
588 gcry_create_nonce (*(iv), blocksize);
591 if (!rc)
593 if (init_iv)
594 *iv_len = blocksize;
596 tmpkey = gcry_malloc (keysize);
597 if (!tmpkey)
598 rc = GPG_ERR_ENOMEM;
601 pthread_cleanup_push (gcry_free, tmpkey);
603 if (!rc)
605 memcpy (tmpkey, key, keysize);
606 tmpkey[0] ^= 1;
607 rc = gcry_cipher_setkey (h, tmpkey, keysize);
608 if (!rc)
610 if (len % blocksize)
611 len += blocksize - (len % blocksize);
615 if (!rc)
617 inbuf = gcry_malloc (len);
618 if (!inbuf)
619 rc = GPG_ERR_ENOMEM;
622 pthread_cleanup_push (gcry_free, inbuf);
624 if (!rc)
626 long progress = config_get_long (NULL, "cipher_progress");
628 memset (inbuf, 0, len);
629 memcpy (inbuf, xml, olen);
631 if (progress == -1)
632 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
634 if (!rc && ctx && iter)
635 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", 0, iter);
637 for (n = 0; !rc && n < iter; n++)
639 if (ctx && progress && !(n % progress))
641 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
642 if (rc)
643 break;
646 rc = gcry_cipher_setiv (h, *(iv), blocksize);
647 if (rc)
648 break;
650 rc = iterate_crypto_once (h, inbuf, len, blocksize, STATUS_ENCRYPT);
654 if (!rc && ctx && iter)
655 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
657 if (!rc)
659 /* Do at least one iteration. */
660 rc = gcry_cipher_setiv (h, *(iv), blocksize);
661 if (!rc)
663 rc = gcry_cipher_setkey (h, key, keysize);
664 if (!rc)
665 rc = iterate_crypto_once (h, inbuf, len, blocksize,
666 STATUS_ENCRYPT);
670 pthread_cleanup_pop (rc ? 1 : 0); /* inbuf */
671 pthread_cleanup_pop (1); /* tmpkey */
672 pthread_cleanup_pop (1); /* cipher */
674 if (rc && init_iv)
676 xfree (*(iv));
677 *iv = NULL;
680 *result = rc ? NULL : inbuf;
681 *result_len = len;
682 return rc;
685 void
686 cleanup_save (struct save_s *save)
688 if (!save)
689 return;
691 #ifdef WITH_AGENT
692 if (save->pkey)
693 gcry_sexp_release (save->pkey);
695 if (save->sigpkey)
696 gcry_sexp_release (save->sigpkey);
697 #endif
699 memset (save, 0, sizeof (struct save_s));
702 /* Keep the agent ctx to retain pinentry options which will be freed in
703 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
704 void
705 cleanup_crypto_stage1 (struct crypto_s *cr)
707 if (!cr)
708 return;
710 cleanup_save (&cr->save);
712 #ifdef WITH_AGENT
713 if (cr->ciphertext_sexp)
714 gcry_sexp_release (cr->ciphertext_sexp);
716 cr->ciphertext_sexp = NULL;
717 #endif
719 gcry_free (cr->plaintext);
720 xfree (cr->ciphertext);
721 xfree (cr->filename);
722 cr->filename = NULL;
723 cr->ciphertext = NULL;
724 cr->ciphertext_len = 0;
725 cr->plaintext = NULL;
726 cr->plaintext_len = 0;
729 void
730 cleanup_crypto_stage2 (struct crypto_s *cr)
732 if (!cr)
733 return;
735 cleanup_crypto_stage1 (cr);
736 set_header_defaults (&cr->hdr);
739 void
740 cleanup_crypto (struct crypto_s **c)
742 struct crypto_s *cr = *c;
744 if (!cr)
745 return;
747 cleanup_crypto_stage2 (cr);
749 #ifdef WITH_AGENT
750 if (cr->pkey_sexp)
751 gcry_sexp_release (cr->pkey_sexp);
753 if (cr->sigpkey_sexp)
754 gcry_sexp_release (cr->sigpkey_sexp);
756 if (cr->agent)
757 cleanup_agent (cr->agent);
758 #endif
760 xfree (cr);
761 *c = NULL;
764 gpg_error_t
765 init_client_crypto (struct crypto_s **crypto)
767 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
768 gpg_error_t rc;
770 if (!new)
772 rc = GPG_ERR_ENOMEM;
773 return rc;
776 #ifdef WITH_AGENT
777 if (use_agent)
779 rc = agent_init (&new->agent);
780 if (!rc)
782 rc = send_agent_common_options (new->agent);
783 if (!rc)
784 rc = agent_set_pinentry_options (new->agent);
787 if (rc)
789 cleanup_agent (new->agent);
790 xfree (new);
791 return rc;
794 #endif
796 set_header_defaults (&new->hdr);
797 *crypto = new;
798 return 0;
801 static gpg_error_t
802 try_decrypt (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
803 const char *filename, unsigned char **key, size_t *keysize)
805 gpg_error_t rc;
806 int pin_try = 1;
807 int pin_tries = 3;
808 char *pin_title = NULL;
809 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
813 rc = decrypt_common (ctx, inquire, crypto, filename, NULL, NULL, key,
814 keysize);
815 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE && ctx)
817 if (pin_try == 1)
818 pin_title = client->pinentry_opts.title;
820 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try+1, pin_tries);
823 while (!inquire && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
824 && ++pin_try <= pin_tries);
826 if (ctx && pin_title != client->pinentry_opts.title)
828 xfree (client->pinentry_opts.title);
829 client->pinentry_opts.title = pin_title;
832 return rc;
835 /* Common to both PKI and non-PKI files when saving a data
836 * file. Defers to gpg-agent when needed and handles keyfiles. */
837 gpg_error_t
838 export_common (assuan_context_t ctx, int inquire, struct crypto_s * crypto,
839 const void *data, size_t datalen, const char *outfile,
840 const char *keyfile, void **rkey, size_t *rkeylen,
841 int use_cache, int force, int no_passphrase)
843 gpg_error_t rc = 0;
844 void *enc_xml = NULL;
845 size_t enc_xml_len = 0;
846 unsigned char *iv = NULL;
847 size_t iv_len = 0;
848 int algo = cipher_to_gcrypt (crypto->save.hdr.flags);
849 unsigned char *key = NULL;
850 void *salted_key = NULL;
851 size_t keysize, keylen = 0;
852 int cached = 0;
854 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
855 if (rc)
856 return rc;
858 if (keyfile)
860 int fd;
861 unsigned char *buf;
862 struct stat st;
864 if (stat (keyfile, &st) == -1)
865 return gpg_error_from_errno (errno);
867 buf = gcry_malloc (st.st_size);
868 if (!buf)
869 return GPG_ERR_ENOMEM;
871 fd = open (keyfile, O_RDONLY);
872 if (fd == -1)
873 rc = gpg_error_from_errno (errno);
874 else
876 size_t len = read (fd, buf, st.st_size);
878 if (len != st.st_size)
879 rc = GPG_ERR_TOO_SHORT;
882 if (fd != -1)
883 close (fd);
885 key = buf;
886 keylen = st.st_size;
887 log_write (_("Using passphrase obtained from file '%s'"), keyfile);
889 if (!keylen)
891 unsigned char *tmp;
893 gcry_free (key);
894 tmp = gcry_malloc (sizeof (unsigned char));
895 *tmp = 0;
896 key = tmp;
897 keylen++;
900 else
902 if (use_cache)
904 int defer = -1;
906 cache_lock ();
907 rc = cache_iscached (outfile, &defer);
908 if (!rc)
909 cached = 1;
910 else if (gpg_err_code (rc) == GPG_ERR_ENOENT
911 || gpg_err_code (rc) == GPG_ERR_NO_DATA)
912 rc = 0;
914 if (cached)
916 struct cache_data_s *cdata = cache_get_data_filename (outfile);
918 salted_key = gcry_malloc (cdata->keylen);
919 if (salted_key)
921 memcpy (salted_key, cdata->key, cdata->keylen);
922 keysize = cdata->keylen;
924 else
925 rc = GPG_ERR_ENOMEM;
928 cache_unlock ();
931 if (!rc && !cached)
933 if (force) // SAVE
935 struct crypto_s *tmp = NULL;
936 gpg_error_t rc = init_client_crypto (&tmp);
938 if (!rc)
940 rc = read_data_file (outfile, tmp);
941 if (!rc)
943 rc = try_decrypt (ctx, inquire, tmp, outfile,
944 &key, &keylen);
948 cleanup_crypto (&tmp);
949 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
950 use_cache = 0;
951 else if (rc)
952 return rc;
955 if (!use_cache && !no_passphrase) // PASSWD or new file
957 gcry_free (key);
958 if (inquire)
960 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
961 (unsigned char **)&key, &keylen);
963 else
965 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
966 (char **)&key, &keylen);
969 if (rc)
970 return rc;
972 else
974 if (no_passphrase)
976 keylen = 1;
977 key = gcry_malloc (keylen);
978 memset (key, 0, keylen);
984 if (!rc && !cached)
986 gcry_create_nonce (crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
987 rc = hash_key (algo, crypto->save.hdr.salt,
988 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
989 &keysize);
990 gcry_free (key);
993 if (!rc)
994 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
995 &enc_xml, &enc_xml_len, &iv, &iv_len,
996 crypto->save.hdr.iterations);
998 if (!rc)
1000 if (no_passphrase && !(crypto->save.hdr.flags & PWMD_FLAG_PKI))
1001 crypto->save.hdr.flags |= PWMD_FLAG_NO_PASSPHRASE;
1003 memcpy (crypto->save.hdr.iv, iv, iv_len);
1004 xfree (iv);
1005 crypto->save.hdr.datalen = enc_xml_len;
1006 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
1007 NULL);
1008 gcry_free (enc_xml);
1009 if (!rc)
1011 *rkey = salted_key;
1012 *rkeylen = keysize;
1013 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
1017 if (rc)
1018 gcry_free (salted_key);
1020 return rc;
1023 static gpg_error_t
1024 write_header (struct crypto_s *crypto, int fd)
1026 ssize_t len;
1027 uint64_t n, x;
1028 uint32_t i;
1030 #ifdef WORDS_BIGENDIAN
1031 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1032 if (len == -1)
1033 goto done;
1035 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
1036 if (len == -1)
1037 goto done;
1039 len = write (fd, &crypto->save.hdr.iterations,
1040 sizeof(crypto->save.hdr.iterations));
1041 if (len == -1)
1042 goto done;
1044 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1045 if (len == -1)
1046 goto done;
1048 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1049 if (len == -1)
1050 goto done;
1052 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1053 if (len == -1)
1054 goto done;
1056 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1057 if (len == -1)
1058 goto done;
1059 #else
1060 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1061 if (len == -1)
1062 goto done;
1064 i = htonl (crypto->save.hdr.version);
1065 len = write (fd, &i, sizeof(i));
1066 if (len == -1)
1067 goto done;
1069 n = crypto->save.hdr.iterations;
1070 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1071 len = write (fd, &x, sizeof(x));
1072 if (len == -1)
1073 goto done;
1075 n = crypto->save.hdr.flags;
1076 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1077 len = write (fd, &x, sizeof(x));
1078 if (len == -1)
1079 goto done;
1081 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1082 if (len == -1)
1083 goto done;
1085 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1086 if (len == -1)
1087 goto done;
1089 i = htonl (crypto->save.hdr.datalen);
1090 len = write (fd, &i, sizeof(i));
1091 if (len == -1)
1092 goto done;
1093 #endif
1095 done:
1096 return len == -1 ? gpg_error_from_errno (errno) : 0;
1099 /* Write the data structures to disk. */
1100 gpg_error_t
1101 write_file (struct crypto_s *crypto, const char *filename,
1102 void *data, size_t data_len, void *sexp, size_t sexp_len,
1103 void *pubkey, void *sigpkey)
1105 char tmp[FILENAME_MAX] = { 0 };
1106 mode_t mode = 0;
1107 struct stat st;
1108 int fd;
1109 gpg_error_t rc = 0;
1111 if (filename)
1113 mode_t mask;
1115 if (lstat (filename, &st) == 0)
1117 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1119 if (!(mode & S_IWUSR))
1120 return GPG_ERR_EACCES;
1122 else if (errno != ENOENT)
1123 return gpg_error_from_errno (errno);
1125 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1126 mask = umask (600);
1127 fd = mkstemp (tmp);
1128 if (fd == -1)
1130 rc = gpg_error_from_errno (errno);
1131 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1132 umask (mask);
1133 return rc;
1136 umask (mask);
1138 else
1140 // xml_import() or convert_file() from command line.
1141 fd = STDOUT_FILENO;
1144 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1145 crypto->save.hdr.version = VERSION_HEX;
1146 rc = write_header (crypto, fd);
1147 if (!rc)
1149 size_t len;
1151 if (crypto->save.hdr.flags & PWMD_FLAG_PKI)
1153 unsigned char grip[20];
1155 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1156 len = write (fd, grip, sizeof (grip));
1157 if (len == sizeof (grip))
1159 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1160 len = write (fd, grip, sizeof (grip));
1161 if (len == sizeof (grip))
1163 len = write (fd, data, data_len);
1164 if (len == data_len)
1166 len = write (fd, sexp, sexp_len);
1167 if (len != sexp_len)
1168 rc = gpg_error_from_errno (errno);
1170 else
1171 rc = gpg_error_from_errno (errno);
1174 else
1175 rc = gpg_error_from_errno (errno);
1177 else
1179 len = write (fd, data, data_len);
1180 if (len != data_len)
1181 rc = gpg_error_from_errno (errno);
1185 if (!rc)
1187 if (fsync (fd) != -1)
1189 if (filename && close (fd) != -1)
1192 if (mode && config_get_boolean (filename, "backup"))
1194 char tmp2[FILENAME_MAX];
1196 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1197 if (rename (filename, tmp2) == -1)
1198 rc = gpg_error_from_errno (errno);
1201 else if (filename)
1202 rc = gpg_error_from_errno (errno);
1204 else
1205 rc = gpg_error_from_errno (errno);
1208 if (!rc)
1210 if (filename && rename (tmp, filename) != -1)
1212 if (filename && mode)
1213 chmod (filename, mode);
1216 else
1217 rc = gpg_error_from_errno (errno);
1220 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1221 return rc;
1224 gpg_error_t
1225 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1226 size_t keylen, void **result, size_t *rlen)
1228 gpg_error_t rc;
1229 void *tmp;
1231 /* Be sure the algorithm is available. */
1232 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1233 if (rc)
1234 return rc;
1236 /* Always allocate enough for a 256-bit key although the algorithms
1237 themselves may use less. Fixes SAVE --cipher with a different
1238 keylen than the previously saved cipher when cached. */
1239 *rlen = 32;
1240 tmp = xmalloc (*rlen);
1241 if (!tmp)
1242 return GPG_ERR_ENOMEM;
1244 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1245 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1246 if (!rc)
1247 *result = tmp;
1248 else
1249 xfree (tmp);
1251 return rc;
1254 /* The PASSWD command when not using gpg-agent. */
1255 gpg_error_t
1256 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1257 struct crypto_s **rcrypto, int no_passphrase)
1259 unsigned char *key = NULL;
1260 size_t keylen = 0;
1261 struct crypto_s *crypto = NULL;
1262 gpg_error_t rc = init_client_crypto (&crypto);
1263 int cached;
1265 if (rc)
1266 return rc;
1268 crypto->client_ctx = ctx;
1269 rc = read_data_file (filename, crypto);
1270 if (rc)
1272 cleanup_crypto (&crypto);
1273 return rc;
1276 rc = try_decrypt (ctx, inquire, crypto, filename, &key, &keylen);
1277 if (rc)
1279 cleanup_crypto (&crypto);
1280 return rc;
1283 gcry_free (key);
1284 key = NULL;
1286 if (!rc)
1288 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1290 if (!no_passphrase)
1291 crypto->save.hdr.flags &= ~PWMD_FLAG_NO_PASSPHRASE;
1293 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1294 crypto->plaintext_len, crypto->filename, NULL,
1295 (void **)&key, &keylen, 0, 0, no_passphrase);
1298 if (!rc)
1300 rc = save_common (filename, crypto, crypto->plaintext,
1301 crypto->plaintext_len, key, keylen, &cached, 1);
1302 if (!rc)
1303 *rcrypto = crypto;
1306 if (rc)
1308 gcry_free (key);
1309 cleanup_crypto (&crypto);
1311 else if (!cached)
1312 send_status_all (STATUS_CACHE, NULL);
1314 return rc;
1317 gpg_error_t
1318 save_common (const char *filename, struct crypto_s *crypto,
1319 const unsigned char *data, size_t datalen,
1320 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1322 struct cache_data_s *cdata;
1323 gpg_error_t rc = 0;
1324 gcry_sexp_t pubkey = NULL;
1325 gcry_sexp_t sigkey = NULL;
1327 /* This is safe since it is a (somewhat) fast operation. */
1328 cache_lock ();
1329 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1330 cdata = cache_get_data_filename (filename);
1331 *cached = cdata != NULL;
1333 if (!cdata)
1334 cdata = xcalloc (1, sizeof (struct cache_data_s));
1336 #ifdef WITH_AGENT
1337 if (use_agent && !no_agent)
1339 rc = gcry_sexp_build (&pubkey, NULL, "%S", crypto->pkey_sexp);
1340 if (!rc)
1341 rc = gcry_sexp_build (&sigkey, NULL, "%S", crypto->sigpkey_sexp);
1343 #endif
1345 if (!rc)
1347 gcry_free (cdata->doc);
1348 cdata->doc = NULL;
1349 gcry_free (cdata->key);
1350 cdata->key = (unsigned char *)key;
1351 cdata->keylen = keylen;
1352 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1353 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1354 &cache_blocksize, 0);
1357 if (!rc)
1359 unsigned char md5file[16];
1361 /* Update in case of any --keygrip argument */
1362 if (cdata->pubkey)
1363 gcry_sexp_release (cdata->pubkey);
1365 if (cdata->sigkey)
1366 gcry_sexp_release (cdata->sigkey);
1368 cdata->pubkey = pubkey;
1369 cdata->sigkey = sigkey;
1370 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1371 rc = cache_set_data (md5file, cdata, crypto->grip);
1373 else
1375 if (pubkey)
1376 gcry_sexp_release (pubkey);
1378 if (sigkey)
1379 gcry_sexp_release (sigkey);
1382 pthread_cleanup_pop (1); // mutex unlock
1383 return rc;
1386 gpg_error_t
1387 getpin_common (assuan_context_t ctx, const char *filename, int which,
1388 char **rkey, size_t *rkeylen)
1390 gpg_error_t rc;
1391 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1392 struct pinentry_s *pin = pinentry_init (filename);
1394 if (!pin)
1395 return GPG_ERR_ENOMEM;
1397 if (client)
1398 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1400 rc = pinentry_lock (ctx, pin);
1401 if (!rc)
1402 rc = pinentry_getpin (pin, rkey, which);
1404 pinentry_deinit (pin);
1405 if (rc)
1406 return rc;
1408 *rkeylen = strlen (*rkey);
1409 if (!(*rkeylen))
1410 (*rkeylen)++;
1412 return rc;
1415 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1416 * both call xfree(). */
1417 gpg_error_t
1418 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1419 unsigned char **result, size_t *rlen)
1421 gpg_error_t rc;
1423 assuan_begin_confidential (ctx);
1424 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1425 assuan_end_confidential (ctx);
1426 return rc;
1429 /* Common to both PKI and non-PKI files. */
1430 gpg_error_t
1431 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1432 const char *filename, void **salted_key, size_t *salted_keysize,
1433 unsigned char **rkey, size_t *rkeylen)
1435 unsigned char *key = NULL;
1436 size_t keylen = 0;
1437 gpg_error_t rc = read_data_file (filename, crypto);
1438 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1439 void *skey = NULL;
1440 size_t skeysize = 0;
1442 if (salted_key)
1443 *salted_key = NULL;
1444 if (salted_keysize)
1445 *salted_keysize = 0;
1447 if (rkey)
1448 *rkey = NULL;
1449 if (rkeylen)
1450 *rkeylen = 0;
1452 if (rc)
1454 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1455 return rc;
1458 key = (unsigned char *)config_get_string (filename, "passphrase");
1459 if (key)
1461 log_write (_("Trying the passphrase specified in config ..."));
1462 keylen = strlen ((char *)key);
1465 if (!key)
1467 key = (unsigned char *)config_get_string (filename, "passphrase_file");
1468 if (key)
1470 char *tmp = expand_homedir ((char *)key);
1471 int fd;
1472 struct stat st;
1474 xfree (key);
1475 key = (unsigned char *)tmp;
1476 log_write (_("Trying the passphrase using file '%s' ..."), key);
1477 fd = open ((char *)key, O_RDONLY);
1478 if (fd == -1)
1480 rc = gpg_error_from_errno (errno);
1481 log_write ("%s: %s", key, pwmd_strerror (rc));
1482 xfree (key);
1483 return rc;
1486 if (stat ((char *)key, &st) == -1)
1488 rc = gpg_error_from_errno (errno);
1489 log_write ("%s: %s", key, pwmd_strerror (rc));
1490 xfree (key);
1491 close(fd);
1492 return rc;
1495 xfree (key);
1496 key = xmalloc (st.st_size);
1497 if (key)
1499 if (read (fd, key, st.st_size) != st.st_size)
1501 log_write ("short read() count");
1502 rc = GPG_ERR_TOO_SHORT;
1505 else
1506 rc = GPG_ERR_ENOMEM;
1508 close (fd);
1510 if (rc)
1512 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1513 xfree (key);
1514 return rc;
1517 keylen = st.st_size;
1518 if (!keylen)
1520 tmp = xmalloc (sizeof (unsigned char));
1521 *tmp = 0;
1522 xfree (key);
1523 key = (unsigned char *)tmp;
1524 keylen++;
1529 if (!key && !IS_PKI (crypto) && inquire
1530 && !(crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
1532 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1533 &keylen);
1534 if (!rc)
1535 if (!keylen)
1536 keylen++;
1538 else if (!key && !IS_PKI (crypto))
1540 if (crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
1542 keylen = 1;
1543 key = gcry_malloc (keylen);
1544 memset (key, 0, keylen);
1546 else
1547 rc = getpin_common (ctx, filename, PINENTRY_OPEN, (char **)&key,
1548 &keylen);
1550 else if (key && IS_PKI (crypto))
1552 #ifdef WITH_AGENT
1553 rc = set_agent_passphrase (crypto, (char *)key, keylen);
1554 #else
1555 rc = GPG_ERR_NOT_IMPLEMENTED;
1556 #endif
1558 else if (!key && IS_PKI (crypto))
1560 #ifdef WITH_AGENT
1561 /* The cache entry has been cleared in save_command(). Will prompt. */
1562 rc = set_pinentry_mode (crypto->agent, inquire ? "loopback" : "ask");
1563 #else
1564 rc = GPG_ERR_NOT_IMPLEMENTED;
1565 #endif
1568 if (rc)
1570 xfree (key);
1571 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1572 return rc;
1575 if (key && !IS_PKI (crypto))
1577 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1578 keylen, &skey, &skeysize);
1579 if (rc)
1581 xfree (key);
1582 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1583 return rc;
1586 if (rkey)
1587 *rkey = key;
1588 if (rkeylen)
1589 *rkeylen = keylen;
1592 xfree (crypto->filename);
1593 crypto->filename = str_dup (filename);
1594 rc = decrypt_data (ctx, crypto, skey, skeysize);
1595 if (rc)
1597 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1598 xfree (key);
1599 xfree (skey);
1601 else
1603 if (salted_key)
1604 *salted_key = skey;
1605 else
1606 xfree (skey);
1608 if (salted_keysize)
1609 *salted_keysize = skeysize;
1612 return rc;