Send STATUS_CACHE after PASSWD.
[pwmd.git] / src / crypto.c
blob3637ca3e62ef2125bc8a5958df356956cdd033ec
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
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 #ifdef WITH_LIBACL
33 #include <sys/acl.h>
34 #endif
36 #include "pwmd-error.h"
37 #include "util-misc.h"
38 #include "common.h"
39 #include "rcfile.h"
40 #include "pinentry.h"
41 #include "crypto.h"
42 #include "cache.h"
43 #include "mem.h"
44 #include "util-string.h"
46 static uint8_t pwmd_magic[5] = { '\177', 'P', 'W', 'M', 'D' };
48 /* Sets the default cipher values for new files. */
49 void
50 set_header_defaults (file_header_t * hdr)
52 char *s = config_get_string (NULL, "cipher");
53 int flags = cipher_string_to_cipher (s);
55 xfree (s);
56 memset (hdr, 0, sizeof (file_header_t));
57 memcpy (hdr->magic, pwmd_magic, sizeof (hdr->magic));
58 if (flags == -1)
59 log_write (_
60 ("Invalid 'cipher' in configuration file. Using a default of aes256."));
61 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
62 hdr->version = VERSION_HEX;
64 #ifdef WITH_AGENT
65 if (use_agent)
66 hdr->flags |= PWMD_FLAG_PKI;
67 #endif
70 static gpg_error_t
71 read_header (file_header_t *hdr, int fd)
73 ssize_t len;
74 uint32_t i;
75 uint64_t n;
77 #ifdef WORDS_BIGENDIAN
78 len = read (fd, &hdr->magic, sizeof(hdr->magic));
79 if (len == -1)
80 goto done;
82 len = read (fd, &hdr->version, sizeof(hdr->version));
83 if (len == -1)
84 goto done;
86 len = read (fd, &hdr->iterations, sizeof(hdr->iterations));
87 if (len == -1)
88 goto done;
90 len = read (fd, &hdr->flags, sizeof(hdr->flags));
91 if (len == -1)
92 goto done;
94 len = read (fd, &hdr->iv, sizeof(hdr->iv));
95 if (len == -1)
96 goto done;
98 len = read (fd, &hdr->salt, sizeof(hdr->salt));
99 if (len == -1)
100 goto done;
102 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
103 if (len == -1)
104 goto done;
105 #else
106 len = read (fd, &hdr->magic, sizeof(hdr->magic));
107 if (len == -1)
108 goto done;
110 len = read (fd, &i, sizeof(hdr->version));
111 if (len == -1)
112 goto done;
113 hdr->version = ntohl (i);
115 len = read (fd, &n, sizeof(hdr->iterations));
116 if (len == -1)
117 goto done;
118 hdr->iterations = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
120 len = read (fd, &n, sizeof(hdr->flags));
121 if (len == -1)
122 goto done;
123 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
125 len = read (fd, &hdr->iv, sizeof(hdr->iv));
126 if (len == -1)
127 goto done;
129 len = read (fd, &hdr->salt, sizeof(hdr->salt));
130 if (len == -1)
131 goto done;
133 len = read (fd, &i, sizeof(hdr->datalen));
134 if (len == -1)
135 goto done;
136 hdr->datalen = ntohl (i);
137 #endif
139 done:
140 return len == -1 ? gpg_error_from_errno (errno) : 0;
143 /* Read the header of a data file to determine cipher and other. The
144 * header is stored big endian in the file and is converted to little
145 * endian when needed. */
146 gpg_error_t
147 read_data_header (const char *filename, file_header_t * rhdr,
148 struct stat *rst, int *rfd)
150 gpg_error_t rc = 0;
151 struct stat st;
152 file_header_t hdr;
153 int fd;
155 if (lstat (filename, &st) == -1)
156 return gpg_error_from_errno (errno);
158 if (!S_ISREG (st.st_mode))
159 return gpg_error (GPG_ERR_ENOANO);
161 fd = open (filename, O_RDONLY);
162 if (fd == -1)
163 return gpg_error_from_errno (errno);
165 rc = read_header (&hdr, fd);
166 if (!rc && memcmp (hdr.magic, pwmd_magic, sizeof (hdr.magic)))
167 rc = GPG_ERR_BAD_DATA;
168 else if (!rc && hdr.version < 0x030000)
169 rc = GPG_ERR_UNKNOWN_VERSION;
171 if (rc)
172 close (fd);
173 else
175 if (rhdr)
176 *rhdr = hdr;
177 if (rst)
178 *rst = st;
179 if (rfd)
180 *rfd = fd;
181 else
182 close (fd);
185 return gpg_error (rc);
188 gpg_error_t
189 read_data_file (const char *filename, struct crypto_s * crypto)
191 int fd;
192 gpg_error_t rc = 0;
193 size_t len, rlen;
194 char *buf = NULL;
195 struct stat st;
197 cleanup_crypto_stage1 (crypto);
198 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
199 if (rc)
200 return gpg_error (rc);
202 crypto->ciphertext_len = crypto->hdr.datalen;
203 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
204 if (!crypto->ciphertext)
206 rc = GPG_ERR_ENOMEM;
207 goto done;
210 /* The keygrips for PKI files are stored after the header. They are
211 * stored in the file to let file(1) magic(5) show the grips. */
212 if (crypto->hdr.flags & PWMD_FLAG_PKI)
214 rlen = read (fd, crypto->grip, 20);
215 if (rlen != 20)
217 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
218 goto done;
221 rlen = read (fd, crypto->sign_grip, 20);
222 if (rlen != 20)
224 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
225 goto done;
229 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
230 if (len != crypto->hdr.datalen)
232 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
233 goto done;
236 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
237 goto done;
239 if (!use_agent)
241 rc = GPG_ERR_NOT_IMPLEMENTED;
242 goto done;
245 #ifdef WITH_AGENT
246 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
247 buf = xmalloc (len);
248 if (!buf)
250 rc = GPG_ERR_ENOMEM;
251 goto done;
254 /* Remaining data file bytes are the encrypted key and XML. */
255 rlen = read (fd, buf, len);
256 if (rlen != len)
258 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
259 goto done;
262 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
263 if (rc)
264 goto done;
266 if (crypto->pkey_sexp)
267 gcry_sexp_release (crypto->pkey_sexp);
269 if (crypto->sigpkey_sexp)
270 gcry_sexp_release (crypto->sigpkey_sexp);
272 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
273 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
274 if (!rc)
275 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
276 #endif
278 done:
279 close (fd);
280 xfree (buf);
281 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
282 rc = gpg_error (rc);
284 return rc;
287 #define CRYPTO_BLOCKSIZE(c) (blocksize * 1024)
290 * Useful for a large amount of data. Rather than doing all of the data in one
291 * iteration do it in chunks. This lets the command be cancelable rather than
292 * waiting for it to complete.
294 static gpg_error_t
295 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
296 size_t insize, size_t blocksize, status_msg_t which)
298 gpg_error_t rc = 0;
299 off_t len = CRYPTO_BLOCKSIZE (blocksize);
300 void *p = gcry_malloc (len);
301 off_t total = 0;
302 unsigned char *inbuf2;
304 if (!p)
305 return gpg_error (GPG_ERR_ENOMEM);
307 if (insize < CRYPTO_BLOCKSIZE (blocksize))
308 len = insize;
310 pthread_cleanup_push (gcry_free, p);
312 for (;;)
314 inbuf2 = inbuf + total;
315 unsigned char *tmp;
317 if (len + total > insize)
318 len = blocksize;
320 if (which == STATUS_ENCRYPT)
321 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
322 else
323 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
325 if (rc)
326 break;
328 tmp = inbuf + total;
329 memmove (tmp, p, len);
330 total += len;
331 if (total >= insize)
332 break;
334 #ifdef HAVE_PTHREAD_TESTCANCEL
335 pthread_testcancel ();
336 #endif
339 pthread_cleanup_pop (1);
340 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
341 rc = gpg_error (rc);
343 return rc;
346 static void
347 cleanup_cipher (void *arg)
349 gcry_cipher_close ((gcry_cipher_hd_t) arg);
352 /* Decrypt the XML data. For PKI data files the key is retrieved from
353 * gpg-agent and the signature verified. */
354 gpg_error_t
355 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
356 unsigned char *salted_key, size_t skeylen)
358 gpg_error_t rc = 0;
359 unsigned char *key = salted_key;
360 gcry_cipher_hd_t h = NULL;
361 size_t blocksize, keysize = 0;
362 int algo = cipher_to_gcrypt (crypto->hdr.flags);
363 void *outbuf = NULL;
364 uint64_t n = crypto->hdr.iterations;
365 long progress = 0;
366 #ifdef WITH_AGENT
367 size_t keylen = skeylen;
368 gcry_sexp_t sig_sexp;
370 if (crypto->hdr.flags & PWMD_FLAG_PKI)
372 rc = agent_extract_key (crypto, &key, &keylen);
373 if (rc)
374 return rc;
376 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
377 if (!sig_sexp)
379 gcry_free (key);
380 return GPG_ERR_BAD_DATA;
383 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
384 crypto->ciphertext_len);
385 gcry_sexp_release (sig_sexp);
387 #endif
389 if (!rc)
391 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
392 if (!rc)
394 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
395 &keysize);
396 if (!rc)
398 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
399 &blocksize);
400 if (!rc)
402 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
403 if (!rc)
405 rc = gcry_cipher_setkey (h, key, keysize);
412 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
414 if (!rc)
416 outbuf = gcry_malloc (crypto->hdr.datalen);
417 if (!outbuf)
418 rc = GPG_ERR_ENOMEM;
421 pthread_cleanup_push (gcry_free, outbuf);
422 #ifdef WITH_AGENT
423 pthread_cleanup_push (gcry_free, key);
424 #endif
426 if (!rc)
428 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
429 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
430 STATUS_DECRYPT);
431 if (!rc)
433 key[0] ^= 1;
434 rc = gcry_cipher_setkey (h, key, keysize);
438 if (!rc)
440 progress = config_get_long (NULL, "cipher_progress");
441 if (progress == -1)
442 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
445 if (!rc && ctx && crypto->hdr.iterations)
446 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", 0,
447 crypto->hdr.iterations);
449 for (n = 0; !rc && n < crypto->hdr.iterations; n++)
451 if (ctx && !(n % progress))
453 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
454 crypto->hdr.iterations);
455 if (rc)
456 break;
459 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
460 if (rc)
461 break;
463 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
464 STATUS_DECRYPT);
467 if (!rc && ctx && crypto->hdr.iterations)
468 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
469 crypto->hdr.iterations);
471 #ifdef WITH_AGENT
472 pthread_cleanup_pop (0);
473 if (crypto->hdr.flags & PWMD_FLAG_PKI)
474 gcry_free (key);
475 else if (key)
476 key[0] ^= 1;
477 #else
478 key[0] ^= 1;
479 #endif
480 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
481 pthread_cleanup_pop (1); /* cipher */
482 if (!rc)
484 char buf[] = "<?xml ";
486 if (memcmp (outbuf, buf, sizeof(buf)-1))
488 gcry_free (outbuf);
489 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
492 crypto->plaintext = outbuf;
493 crypto->plaintext_len = crypto->hdr.datalen;
496 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
497 rc = gpg_error (rc);
499 return rc;
502 /* The cached document is encrypted with encrypt_xml(). This decrypts
503 * it from the OPEN command. */
504 gpg_error_t
505 decrypt_cache (struct crypto_s * crypto, const void *data, size_t len)
507 gcry_cipher_hd_t h = NULL;
508 gpg_error_t rc;
510 rc = gcry_cipher_open (&h, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
511 if (rc)
512 return rc;
514 gcry_free (crypto->plaintext);
515 crypto->plaintext = gcry_malloc (len);
516 if (!crypto->plaintext)
518 rc = GPG_ERR_ENOMEM;
519 goto done;
522 rc = gcry_cipher_setiv (h, cache_iv, cache_blocksize);
523 if (rc)
524 goto done;
526 rc = gcry_cipher_setkey (h, cache_key, cache_keysize);
527 if (rc)
528 goto done;
530 rc = gcry_cipher_decrypt (h, crypto->plaintext, len, data, len);
531 if (rc || strncmp (crypto->plaintext, "<?xml ", 6))
533 if (!rc)
534 rc = GPG_ERR_BAD_DATA;
536 gcry_free (crypto->plaintext);
537 crypto->plaintext = NULL;
540 crypto->plaintext_len = len;
542 done:
543 if (h)
544 gcry_cipher_close (h);
546 return rc;
549 /* Encrypt the XML data and set 'result'. At least one encryption
550 * iteration is done. */
551 gpg_error_t
552 encrypt_xml (assuan_context_t ctx, void *key, size_t keylen,
553 int algo, const void *xml, size_t len, void * *result,
554 size_t *result_len, unsigned char **iv, size_t * iv_len,
555 uint64_t iter)
557 gpg_error_t rc;
558 gcry_cipher_hd_t h;
559 size_t blocksize, keysize;
560 void *inbuf = NULL;
561 size_t olen = len;
562 uint64_t n = 0;
563 long progress;
564 unsigned char *tmpkey = NULL;
565 int init_iv = *(iv_len) == 0;
567 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
568 if (rc)
569 return rc;
571 pthread_cleanup_push (cleanup_cipher, h);
572 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
573 if (!rc)
574 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL, &blocksize);
576 if (!rc && init_iv)
578 *(iv) = xmalloc (blocksize);
579 if (!*(iv))
580 rc = GPG_ERR_ENOMEM;
582 gcry_create_nonce (*(iv), blocksize);
585 if (!rc)
587 if (init_iv)
588 *iv_len = blocksize;
590 tmpkey = gcry_malloc (keysize);
591 if (!tmpkey)
592 rc = GPG_ERR_ENOMEM;
595 pthread_cleanup_push (gcry_free, tmpkey);
597 if (!rc)
599 memcpy (tmpkey, key, keysize);
600 tmpkey[0] ^= 1;
601 rc = gcry_cipher_setkey (h, tmpkey, keysize);
602 if (!rc)
604 if (len % blocksize)
605 len += blocksize - (len % blocksize);
609 if (!rc)
611 inbuf = gcry_malloc (len);
612 if (!inbuf)
613 rc = GPG_ERR_ENOMEM;
616 pthread_cleanup_push (gcry_free, inbuf);
618 if (!rc)
620 memset (inbuf, 0, len);
621 memcpy (inbuf, xml, olen);
622 progress = config_get_long (NULL, "cipher_progress");
623 if (progress == -1)
624 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
626 if (!rc && ctx && iter)
627 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", 0, iter);
629 for (n = 0; !rc && n < iter; n++)
631 if (ctx && !(n % progress))
633 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
634 if (rc)
635 break;
638 rc = gcry_cipher_setiv (h, *(iv), blocksize);
639 if (rc)
640 break;
642 rc = iterate_crypto_once (h, inbuf, len, blocksize, STATUS_ENCRYPT);
646 if (!rc && ctx && iter)
647 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
649 if (!rc)
651 /* Do at least one iteration. */
652 rc = gcry_cipher_setiv (h, *(iv), blocksize);
653 if (!rc)
655 rc = gcry_cipher_setkey (h, key, keysize);
656 if (!rc)
657 rc = iterate_crypto_once (h, inbuf, len, blocksize,
658 STATUS_ENCRYPT);
662 pthread_cleanup_pop (rc ? 1 : 0); /* inbuf */
663 pthread_cleanup_pop (1); /* tmpkey */
664 pthread_cleanup_pop (1); /* cipher */
666 if (rc && init_iv)
668 xfree (*(iv));
669 *iv = NULL;
672 *result = rc ? NULL : inbuf;
673 *result_len = len;
674 return rc;
677 void
678 cleanup_save (struct save_s *save)
680 if (!save)
681 return;
683 #ifdef WITH_AGENT
684 if (save->pkey)
685 gcry_sexp_release (save->pkey);
687 if (save->sigpkey)
688 gcry_sexp_release (save->sigpkey);
689 #endif
691 memset (save, 0, sizeof (struct save_s));
694 /* Keep the agent ctx to retain pinentry options which will be freed in
695 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
696 void
697 cleanup_crypto_stage1 (struct crypto_s *cr)
699 if (!cr)
700 return;
702 cleanup_save (&cr->save);
704 #ifdef WITH_AGENT
705 if (cr->ciphertext_sexp)
706 gcry_sexp_release (cr->ciphertext_sexp);
708 cr->ciphertext_sexp = NULL;
709 #endif
711 gcry_free (cr->plaintext);
712 xfree (cr->ciphertext);
713 xfree (cr->filename);
714 cr->filename = NULL;
715 cr->ciphertext = NULL;
716 cr->ciphertext_len = 0;
717 cr->plaintext = NULL;
718 cr->plaintext_len = 0;
721 void
722 cleanup_crypto_stage2 (struct crypto_s *cr)
724 if (!cr)
725 return;
727 cleanup_crypto_stage1 (cr);
728 set_header_defaults (&cr->hdr);
731 void
732 cleanup_crypto (struct crypto_s **c)
734 struct crypto_s *cr = *c;
736 if (!cr)
737 return;
739 cleanup_crypto_stage2 (cr);
741 #ifdef WITH_AGENT
742 if (cr->pkey_sexp)
743 gcry_sexp_release (cr->pkey_sexp);
745 if (cr->sigpkey_sexp)
746 gcry_sexp_release (cr->sigpkey_sexp);
748 if (cr->agent)
749 cleanup_agent (cr->agent);
750 #endif
752 xfree (cr);
753 *c = NULL;
756 gpg_error_t
757 init_client_crypto (struct crypto_s **crypto)
759 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
760 gpg_error_t rc;
762 if (!new)
764 rc = GPG_ERR_ENOMEM;
765 return rc;
768 #ifdef WITH_AGENT
769 if (use_agent)
771 rc = agent_init (&new->agent);
772 if (!rc)
774 rc = send_agent_common_options (new->agent);
775 if (!rc)
776 rc = agent_set_pinentry_options (new->agent);
779 if (rc)
781 cleanup_agent (new->agent);
782 xfree (new);
783 return rc;
786 #endif
788 set_header_defaults (&new->hdr);
789 *crypto = new;
790 return 0;
793 static gpg_error_t
794 try_decrypt (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
795 const char *filename, char **key, size_t *keylen)
797 gpg_error_t rc;
798 int pin_try = 1;
799 int pin_tries = 3;
800 char *pin_title = NULL;
801 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
805 rc = decrypt_common (ctx, inquire, crypto, filename, key, keylen);
806 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE && ctx)
808 if (pin_try == 1)
809 pin_title = client->pinentry_opts.title;
811 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try+1, pin_tries);
814 while (!inquire && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
815 && ++pin_try <= pin_tries);
817 if (ctx && pin_title != client->pinentry_opts.title)
819 xfree (client->pinentry_opts.title);
820 client->pinentry_opts.title = pin_title;
823 return rc;
826 /* Common to both PKI and non-PKI files when saving a data
827 * file. Defers to gpg-agent when needed and handles keyfiles. */
828 gpg_error_t
829 export_common (assuan_context_t ctx, int inquire, struct crypto_s * crypto,
830 const void *data, size_t datalen, const char *outfile,
831 const char *keyfile, void **rkey, size_t *rkeylen,
832 int use_cache, int force, int no_passphrase)
834 gpg_error_t rc = 0;
835 void *enc_xml = NULL;
836 size_t enc_xml_len = 0;
837 unsigned char *iv = NULL;
838 size_t iv_len = 0;
839 int algo = cipher_to_gcrypt (crypto->save.hdr.flags);
840 void *key = NULL, *salted_key = NULL;
841 size_t keysize, keylen;
842 int cached = 0;
844 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
845 if (rc)
846 return rc;
848 if (keyfile)
850 int fd;
851 unsigned char *buf;
852 size_t len;
853 struct stat st;
855 if (stat (keyfile, &st) == -1)
856 return gpg_error_from_errno (errno);
858 buf = gcry_malloc (st.st_size);
859 if (!buf)
860 return GPG_ERR_ENOMEM;
862 fd = open (keyfile, O_RDONLY);
863 if (fd == -1)
864 rc = gpg_error_from_errno (errno);
865 else
867 len = read (fd, buf, st.st_size);
868 if (len != st.st_size)
869 rc = GPG_ERR_TOO_SHORT;
872 if (fd != -1)
873 close (fd);
875 key = buf;
876 keylen = st.st_size;
877 log_write (_("Using passphrase obtained from file '%s'"), keyfile);
879 if (!keylen)
881 char *tmp;
883 gcry_free (key);
884 tmp = gcry_malloc (1);
885 *tmp = 0;
886 key = tmp;
887 keylen++;
890 else
892 if (use_cache)
894 int defer = -1;
896 cache_lock ();
897 rc = cache_iscached (outfile, &defer);
898 if (!rc)
899 cached = 1;
900 else if (gpg_err_code (rc) == GPG_ERR_ENOENT
901 || gpg_err_code (rc) == GPG_ERR_NO_DATA)
902 rc = 0;
904 if (cached)
906 struct cache_data_s *cdata = cache_get_data_filename (outfile);
908 salted_key = gcry_malloc (cdata->keylen);
909 if (salted_key)
911 memcpy (salted_key, cdata->key, cdata->keylen);
912 keysize = cdata->keylen;
914 else
915 rc = GPG_ERR_ENOMEM;
918 cache_unlock ();
921 if (!rc && !cached)
923 if (force) // SAVE
925 struct crypto_s *tmp = NULL;
926 gpg_error_t rc = init_client_crypto (&tmp);
928 if (!rc)
930 rc = read_data_file (outfile, tmp);
931 if (!rc)
933 rc = try_decrypt (ctx, inquire, tmp, outfile,
934 (char **)&key, &keylen);
935 if (rc)
936 gcry_free (key);
940 cleanup_crypto (&tmp);
941 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
942 use_cache = 0;
943 else if (rc)
944 return rc;
947 if (!use_cache && !no_passphrase) // PASSWD or new file
949 gcry_free (key);
950 if (inquire)
952 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
953 (unsigned char **)&key, &keylen);
955 else
957 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
958 (char **)&key, &keylen);
961 if (rc)
962 return rc;
964 else
966 if (no_passphrase)
968 keylen = 1;
969 key = gcry_malloc (keylen);
970 memset (key, 0, keylen);
972 else
974 salted_key = key;
975 keysize = keylen;
976 cached = 1;
982 if (!rc && !cached)
984 rc = hash_key (algo, crypto->save.hdr.salt,
985 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
986 &keysize);
987 gcry_free (key);
990 if (!rc)
991 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
992 &enc_xml, &enc_xml_len, &iv, &iv_len,
993 crypto->save.hdr.iterations);
995 if (!rc)
997 if (no_passphrase && !(crypto->save.hdr.flags & PWMD_FLAG_PKI))
998 crypto->save.hdr.flags |= PWMD_FLAG_NO_PASSPHRASE;
1000 memcpy (crypto->save.hdr.iv, iv, iv_len);
1001 xfree (iv);
1002 crypto->save.hdr.datalen = enc_xml_len;
1003 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
1004 NULL);
1005 gcry_free (enc_xml);
1006 if (!rc)
1008 *rkey = salted_key;
1009 *rkeylen = keysize;
1010 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
1014 if (rc)
1015 gcry_free (salted_key);
1017 return rc;
1020 #ifdef WITH_LIBACL
1021 static void
1022 cleanup_acl (void *arg)
1024 acl_t acl = *(acl_t *) arg;
1026 if (acl)
1027 acl_free (acl);
1029 #endif
1031 static gpg_error_t
1032 write_header (struct crypto_s *crypto, int fd)
1034 ssize_t len;
1035 uint64_t n, x;
1036 uint32_t i;
1038 #ifdef WORDS_BIGENDIAN
1039 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1040 if (len == -1)
1041 goto done;
1043 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
1044 if (len == -1)
1045 goto done;
1047 len = write (fd, &crypto->save.hdr.iterations,
1048 sizeof(crypto->save.hdr.iterations));
1049 if (len == -1)
1050 goto done;
1052 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1053 if (len == -1)
1054 goto done;
1056 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1057 if (len == -1)
1058 goto done;
1060 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1061 if (len == -1)
1062 goto done;
1064 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1065 if (len == -1)
1066 goto done;
1067 #else
1068 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1069 if (len == -1)
1070 goto done;
1072 i = htonl (crypto->save.hdr.version);
1073 len = write (fd, &i, sizeof(i));
1074 if (len == -1)
1075 goto done;
1077 n = crypto->save.hdr.iterations;
1078 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1079 len = write (fd, &x, sizeof(x));
1080 if (len == -1)
1081 goto done;
1083 n = crypto->save.hdr.flags;
1084 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1085 len = write (fd, &x, sizeof(x));
1086 if (len == -1)
1087 goto done;
1089 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1090 if (len == -1)
1091 goto done;
1093 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1094 if (len == -1)
1095 goto done;
1097 i = htonl (crypto->save.hdr.datalen);
1098 len = write (fd, &i, sizeof(i));
1099 if (len == -1)
1100 goto done;
1101 #endif
1103 done:
1104 return len == -1 ? gpg_error_from_errno (errno) : 0;
1107 /* Write the data structures to disk. */
1108 gpg_error_t
1109 write_file (struct crypto_s *crypto, const char *filename,
1110 void *data, size_t data_len, void *sexp, size_t sexp_len,
1111 void *pubkey, void *sigpkey)
1113 char tmp[FILENAME_MAX] = { 0 };
1114 mode_t mode = 0;
1115 struct stat st;
1116 int fd;
1117 gpg_error_t rc = 0;
1118 size_t len;
1119 #ifdef WITH_LIBACL
1120 acl_t acl = NULL;
1121 #endif
1123 if (filename)
1125 if (lstat (filename, &st) == 0)
1127 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1129 if (!(mode & S_IWUSR))
1130 return GPG_ERR_EACCES;
1132 else if (errno != ENOENT)
1133 return gpg_error_from_errno (errno);
1135 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1136 fd = mkstemp (tmp);
1137 if (fd == -1)
1139 rc = gpg_error_from_errno (errno);
1140 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1141 return rc;
1144 else
1146 // xml_import() or convert_file() from command line.
1147 fd = STDOUT_FILENO;
1150 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1151 crypto->save.hdr.version = VERSION_HEX;
1152 rc = write_header (crypto, fd);
1153 if (!rc)
1155 if (crypto->save.hdr.flags & PWMD_FLAG_PKI)
1157 unsigned char grip[20];
1159 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1160 len = write (fd, grip, sizeof (grip));
1161 if (len == sizeof (grip))
1163 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1164 len = write (fd, grip, sizeof (grip));
1165 if (len == sizeof (grip))
1167 len = write (fd, data, data_len);
1168 if (len == data_len)
1170 len = write (fd, sexp, sexp_len);
1171 if (len != sexp_len)
1172 rc = gpg_error_from_errno (errno);
1174 else
1175 rc = gpg_error_from_errno (errno);
1178 else
1179 rc = gpg_error_from_errno (errno);
1181 else
1183 len = write (fd, data, data_len);
1184 if (len != data_len)
1185 rc = gpg_error_from_errno (errno);
1189 #ifdef WITH_LIBACL
1190 pthread_cleanup_push (cleanup_acl, &acl);
1191 #endif
1192 if (!rc)
1194 if (fsync (fd) != -1)
1196 if (filename && close (fd) != -1)
1198 #ifdef WITH_LIBACL
1199 acl = acl_get_file (filename, ACL_TYPE_ACCESS);
1200 if (!acl && errno == ENOENT)
1201 acl = acl_get_file (".", ACL_TYPE_DEFAULT);
1202 if (!acl)
1203 log_write ("ACL: %s: %s", filename,
1204 pwmd_strerror (gpg_error_from_errno (errno)));
1205 #endif
1207 if (mode && config_get_boolean (filename, "backup"))
1209 char tmp2[FILENAME_MAX];
1211 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1212 if (rename (filename, tmp2) == -1)
1213 rc = gpg_error_from_errno (errno);
1216 else if (filename)
1217 rc = gpg_error_from_errno (errno);
1219 else
1220 rc = gpg_error_from_errno (errno);
1223 if (!rc)
1225 if (filename && rename (tmp, filename) != -1)
1227 tmp[0] = 0;
1228 if (filename && mode)
1229 chmod (filename, mode);
1231 #ifdef WITH_LIBACL
1232 if (acl && acl_set_file (filename, ACL_TYPE_ACCESS, acl))
1233 log_write ("ACL: %s: %s", filename,
1234 pwmd_strerror (gpg_error_from_errno (errno)));
1235 #endif
1237 else
1238 rc = gpg_error_from_errno (errno);
1241 #ifdef WITH_LIBACL
1242 pthread_cleanup_pop (1);
1243 #endif
1244 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1245 return rc;
1248 gpg_error_t
1249 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1250 size_t keylen, void **result, size_t *rlen)
1252 gpg_error_t rc;
1253 void *tmp;
1255 /* Be sure the algorithm is available. */
1256 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1257 if (rc)
1258 return rc;
1260 /* Always allocate enough for a 256-bit key although the algorithms
1261 themselves may use less. Fixes SAVE --cipher with a different
1262 keylen than the previously saved cipher when cached. */
1263 *rlen = 32;
1264 tmp = xmalloc (*rlen);
1265 if (!tmp)
1266 return GPG_ERR_ENOMEM;
1268 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1269 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1270 if (!rc)
1271 *result = tmp;
1272 else
1273 xfree (tmp);
1275 return rc;
1278 /* The PASSWD command when not using gpg-agent. */
1279 gpg_error_t
1280 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1281 struct crypto_s **rcrypto, int no_passphrase)
1283 unsigned char *key = NULL;
1284 size_t keylen = 0;
1285 struct crypto_s *crypto = NULL;
1286 gpg_error_t rc = init_client_crypto (&crypto);
1287 int cached;
1289 if (rc)
1290 return rc;
1292 crypto->client_ctx = ctx;
1293 rc = read_data_file (filename, crypto);
1294 if (rc)
1296 cleanup_crypto (&crypto);
1297 return rc;
1300 rc = try_decrypt (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1301 if (rc)
1303 cleanup_crypto (&crypto);
1304 return rc;
1307 gcry_free (key);
1308 key = NULL;
1310 if (!rc)
1312 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1314 if (!no_passphrase)
1315 crypto->save.hdr.flags &= ~PWMD_FLAG_NO_PASSPHRASE;
1317 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1318 crypto->plaintext_len, crypto->filename, NULL,
1319 (void **)&key, &keylen, 0, 0, no_passphrase);
1322 if (!rc)
1324 rc = save_common (filename, crypto, crypto->plaintext,
1325 crypto->plaintext_len, key, keylen, &cached, 1);
1326 if (!rc)
1327 *rcrypto = crypto;
1330 if (rc)
1332 gcry_free (key);
1333 cleanup_crypto (&crypto);
1335 else if (!cached)
1336 send_status_all (STATUS_CACHE, NULL);
1338 return rc;
1341 gpg_error_t
1342 save_common (const char *filename, struct crypto_s *crypto,
1343 const unsigned char *data, size_t datalen,
1344 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1346 struct cache_data_s *cdata;
1347 gpg_error_t rc = 0;
1348 gcry_sexp_t pubkey = NULL;
1349 gcry_sexp_t sigkey = NULL;
1351 /* This is safe since it is a (somewhat) fast operation. */
1352 cache_lock ();
1353 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1354 cdata = cache_get_data_filename (filename);
1355 *cached = cdata != NULL;
1357 if (!cdata)
1358 cdata = xcalloc (1, sizeof (struct cache_data_s));
1360 #ifdef WITH_AGENT
1361 if (use_agent && !no_agent)
1363 rc = gcry_sexp_build (&pubkey, NULL, "%S", crypto->pkey_sexp);
1364 if (!rc)
1365 rc = gcry_sexp_build (&sigkey, NULL, "%S", crypto->sigpkey_sexp);
1367 #endif
1369 if (!rc)
1371 gcry_free (cdata->doc);
1372 cdata->doc = NULL;
1373 gcry_free (cdata->key);
1374 cdata->key = (unsigned char *)key;
1375 cdata->keylen = keylen;
1376 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1377 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1378 &cache_blocksize, 0);
1381 if (!rc)
1383 unsigned char md5file[16];
1385 /* Update in case of any --keygrip argument */
1386 if (cdata->pubkey)
1387 gcry_sexp_release (cdata->pubkey);
1389 if (cdata->sigkey)
1390 gcry_sexp_release (cdata->sigkey);
1392 cdata->pubkey = pubkey;
1393 cdata->sigkey = sigkey;
1394 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1395 rc = cache_set_data (md5file, cdata, crypto->grip);
1397 else
1399 if (pubkey)
1400 gcry_sexp_release (pubkey);
1402 if (sigkey)
1403 gcry_sexp_release (sigkey);
1406 pthread_cleanup_pop (1); // mutex unlock
1407 return rc;
1410 gpg_error_t
1411 getpin_common (assuan_context_t ctx, const char *filename, int which,
1412 char **rkey, size_t *rkeylen)
1414 gpg_error_t rc;
1415 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1416 struct pinentry_s *pin = pinentry_init (filename);
1418 if (!pin)
1419 return GPG_ERR_ENOMEM;
1421 if (client)
1422 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1424 rc = pinentry_lock (ctx, pin);
1425 if (!rc)
1426 rc = pinentry_getpin (pin, rkey, which);
1428 pinentry_deinit (pin);
1429 if (rc)
1430 return rc;
1432 *rkeylen = strlen (*rkey);
1433 if (!(*rkeylen))
1434 (*rkeylen)++;
1436 return rc;
1439 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1440 * both call xfree(). */
1441 gpg_error_t
1442 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1443 unsigned char **result, size_t *rlen)
1445 gpg_error_t rc;
1447 assuan_begin_confidential (ctx);
1448 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1449 assuan_end_confidential (ctx);
1450 return rc;
1453 /* Common to both PKI and non-PKI files. */
1454 gpg_error_t
1455 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1456 const char *filename, char **rkey, size_t *rkeylen)
1458 char *key = NULL;
1459 size_t keylen = 0;
1460 gpg_error_t rc = read_data_file (filename, crypto);
1461 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1462 void *salted_key = NULL;
1463 size_t keysize = 0;
1465 if (rc)
1467 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1468 return rc;
1471 key = config_get_string (filename, "passphrase");
1472 if (key)
1474 log_write (_("Trying the passphrase specified in config ..."));
1475 keylen = strlen (key);
1478 if (!key)
1480 key = config_get_string (filename, "passphrase_file");
1481 if (key)
1483 char *tmp = expand_homedir (key);
1484 int fd;
1485 struct stat st;
1487 xfree (key);
1488 key = tmp;
1489 log_write (_("Trying the passphrase using file '%s' ..."), key);
1490 fd = open (key, O_RDONLY);
1491 if (fd == -1)
1493 rc = gpg_error_from_errno (errno);
1494 log_write ("%s: %s", key, pwmd_strerror (rc));
1495 xfree (key);
1496 return rc;
1499 stat (key, &st);
1500 xfree (key);
1501 key = xmalloc (st.st_size);
1502 if (key)
1504 if (read (fd, key, st.st_size) != st.st_size)
1506 log_write ("short read() count");
1507 rc = GPG_ERR_TOO_SHORT;
1510 else
1511 rc = GPG_ERR_ENOMEM;
1513 close (fd);
1515 if (rc)
1517 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1518 xfree (key);
1519 return rc;
1522 keylen = st.st_size;
1523 if (!keylen)
1525 tmp = xmalloc (1);
1526 *tmp = 0;
1527 xfree (key);
1528 key = tmp;
1529 keylen++;
1534 if (!key && !IS_PKI (crypto) && inquire
1535 && !(crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
1537 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1538 &keylen);
1539 if (rc)
1541 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1542 return rc;
1545 if (!keylen)
1546 keylen++;
1548 else if (!key && !IS_PKI (crypto))
1550 if (crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
1552 keylen = 1;
1553 key = gcry_malloc (keylen);
1554 memset (key, 0, keylen);
1556 else
1558 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1559 if (rc)
1561 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1562 return rc;
1566 #ifdef WITH_AGENT
1567 else if (key && IS_PKI (crypto))
1569 rc = set_agent_passphrase (crypto, key, keylen);
1570 if (rc)
1572 xfree (key);
1573 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1574 return rc;
1577 else if (!key && IS_PKI (crypto))
1579 /* The cache entry has been cleared in save_command(). Will prompt. */
1580 rc = set_pinentry_mode (crypto->agent, inquire ? "loopback" : "ask");
1581 if (rc)
1582 return rc;
1584 #endif
1586 if (key && !IS_PKI (crypto))
1588 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1589 keylen, &salted_key, &keysize);
1590 xfree (key);
1591 key = (char *)salted_key;
1592 keylen = keysize;
1593 if (rc)
1595 xfree (salted_key);
1596 return rc;
1600 xfree (crypto->filename);
1601 crypto->filename = str_dup (filename);
1602 rc = decrypt_data (ctx, crypto, (unsigned char *)key, keylen);
1603 if (rc)
1605 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1606 xfree (key);
1608 else
1610 *rkey = key;
1611 *rkeylen = keylen;
1614 return rc;