Fix PASSWD inquiring a passphrase when PWMD_NO_PASSPHRASE was set.
[pwmd.git] / src / crypto.c
blob6df05da127f415adf147e87a07adc5b12002e89f
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 cache_lock ();
895 rc = cache_iscached (outfile, NULL);
896 if (!rc)
897 cached = 1;
898 else if (gpg_err_code (rc) == GPG_ERR_ENOENT
899 || gpg_err_code (rc) == GPG_ERR_NO_DATA)
900 rc = 0;
902 if (cached)
904 struct cache_data_s *cdata = cache_get_data_filename (outfile);
906 salted_key = gcry_malloc (cdata->keylen);
907 if (salted_key)
909 memcpy (salted_key, cdata->key, cdata->keylen);
910 keysize = cdata->keylen;
912 else
913 rc = GPG_ERR_ENOMEM;
916 cache_unlock ();
919 if (!rc && !cached)
921 if (force) // SAVE
923 struct crypto_s *tmp = NULL;
924 gpg_error_t rc = init_client_crypto (&tmp);
926 if (!rc)
928 rc = read_data_file (outfile, tmp);
929 if (!rc)
931 rc = try_decrypt (ctx, inquire, tmp, outfile,
932 (char **)&key, &keylen);
933 if (rc)
934 gcry_free (key);
938 cleanup_crypto (&tmp);
939 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
940 use_cache = 0;
941 else if (rc)
942 return rc;
945 if (!use_cache && !no_passphrase) // PASSWD or new file
947 gcry_free (key);
948 if (inquire)
950 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
951 (unsigned char **)&key, &keylen);
953 else
955 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
956 (char **)&key, &keylen);
959 if (rc)
960 return rc;
962 else
964 if (no_passphrase)
966 keylen = 1;
967 key = gcry_malloc (keylen);
968 memset (key, 0, keylen);
970 else
972 salted_key = key;
973 keysize = keylen;
974 cached = 1;
980 if (!rc && !cached)
982 rc = hash_key (algo, crypto->save.hdr.salt,
983 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
984 &keysize);
985 gcry_free (key);
988 if (!rc)
989 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
990 &enc_xml, &enc_xml_len, &iv, &iv_len,
991 crypto->save.hdr.iterations);
993 if (!rc)
995 if (no_passphrase && !(crypto->save.hdr.flags & PWMD_FLAG_PKI))
996 crypto->save.hdr.flags |= PWMD_FLAG_NO_PASSPHRASE;
998 memcpy (crypto->save.hdr.iv, iv, iv_len);
999 xfree (iv);
1000 crypto->save.hdr.datalen = enc_xml_len;
1001 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
1002 NULL);
1003 gcry_free (enc_xml);
1004 if (!rc)
1006 *rkey = salted_key;
1007 *rkeylen = keysize;
1008 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
1012 if (rc)
1013 gcry_free (salted_key);
1015 return rc;
1018 #ifdef WITH_LIBACL
1019 static void
1020 cleanup_acl (void *arg)
1022 acl_t acl = *(acl_t *) arg;
1024 if (acl)
1025 acl_free (acl);
1027 #endif
1029 static gpg_error_t
1030 write_header (struct crypto_s *crypto, int fd)
1032 ssize_t len;
1033 uint64_t n, x;
1034 uint32_t i;
1036 #ifdef WORDS_BIGENDIAN
1037 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1038 if (len == -1)
1039 goto done;
1041 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
1042 if (len == -1)
1043 goto done;
1045 len = write (fd, &crypto->save.hdr.iterations,
1046 sizeof(crypto->save.hdr.iterations));
1047 if (len == -1)
1048 goto done;
1050 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1051 if (len == -1)
1052 goto done;
1054 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1055 if (len == -1)
1056 goto done;
1058 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1059 if (len == -1)
1060 goto done;
1062 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1063 if (len == -1)
1064 goto done;
1065 #else
1066 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1067 if (len == -1)
1068 goto done;
1070 i = htonl (crypto->save.hdr.version);
1071 len = write (fd, &i, sizeof(i));
1072 if (len == -1)
1073 goto done;
1075 n = crypto->save.hdr.iterations;
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 n = crypto->save.hdr.flags;
1082 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1083 len = write (fd, &x, sizeof(x));
1084 if (len == -1)
1085 goto done;
1087 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1088 if (len == -1)
1089 goto done;
1091 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1092 if (len == -1)
1093 goto done;
1095 i = htonl (crypto->save.hdr.datalen);
1096 len = write (fd, &i, sizeof(i));
1097 if (len == -1)
1098 goto done;
1099 #endif
1101 done:
1102 return len == -1 ? gpg_error_from_errno (errno) : 0;
1105 /* Write the data structures to disk. */
1106 gpg_error_t
1107 write_file (struct crypto_s *crypto, const char *filename,
1108 void *data, size_t data_len, void *sexp, size_t sexp_len,
1109 void *pubkey, void *sigpkey)
1111 char tmp[FILENAME_MAX] = { 0 };
1112 mode_t mode = 0;
1113 struct stat st;
1114 int fd;
1115 gpg_error_t rc = 0;
1116 size_t len;
1117 #ifdef WITH_LIBACL
1118 acl_t acl = NULL;
1119 #endif
1121 if (filename)
1123 if (lstat (filename, &st) == 0)
1125 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1127 if (!(mode & S_IWUSR))
1128 return GPG_ERR_EACCES;
1130 else if (errno != ENOENT)
1131 return gpg_error_from_errno (errno);
1133 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1134 fd = mkstemp (tmp);
1135 if (fd == -1)
1137 rc = gpg_error_from_errno (errno);
1138 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1139 return rc;
1142 else
1144 // xml_import() or convert_file() from command line.
1145 fd = STDOUT_FILENO;
1148 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1149 crypto->save.hdr.version = VERSION_HEX;
1150 rc = write_header (crypto, fd);
1151 if (!rc)
1153 if (crypto->save.hdr.flags & PWMD_FLAG_PKI)
1155 unsigned char grip[20];
1157 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1158 len = write (fd, grip, sizeof (grip));
1159 if (len == sizeof (grip))
1161 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1162 len = write (fd, grip, sizeof (grip));
1163 if (len == sizeof (grip))
1165 len = write (fd, data, data_len);
1166 if (len == data_len)
1168 len = write (fd, sexp, sexp_len);
1169 if (len != sexp_len)
1170 rc = gpg_error_from_errno (errno);
1172 else
1173 rc = gpg_error_from_errno (errno);
1176 else
1177 rc = gpg_error_from_errno (errno);
1179 else
1181 len = write (fd, data, data_len);
1182 if (len != data_len)
1183 rc = gpg_error_from_errno (errno);
1187 #ifdef WITH_LIBACL
1188 pthread_cleanup_push (cleanup_acl, &acl);
1189 #endif
1190 if (!rc)
1192 if (fsync (fd) != -1)
1194 if (filename && close (fd) != -1)
1196 #ifdef WITH_LIBACL
1197 acl = acl_get_file (filename, ACL_TYPE_ACCESS);
1198 if (!acl && errno == ENOENT)
1199 acl = acl_get_file (".", ACL_TYPE_DEFAULT);
1200 if (!acl)
1201 log_write ("ACL: %s: %s", filename,
1202 pwmd_strerror (gpg_error_from_errno (errno)));
1203 #endif
1205 if (mode && config_get_boolean (filename, "backup"))
1207 char tmp2[FILENAME_MAX];
1209 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1210 if (rename (filename, tmp2) == -1)
1211 rc = gpg_error_from_errno (errno);
1214 else if (filename)
1215 rc = gpg_error_from_errno (errno);
1217 else
1218 rc = gpg_error_from_errno (errno);
1221 if (!rc)
1223 if (filename && rename (tmp, filename) != -1)
1225 tmp[0] = 0;
1226 if (filename && mode)
1227 chmod (filename, mode);
1229 #ifdef WITH_LIBACL
1230 if (acl && acl_set_file (filename, ACL_TYPE_ACCESS, acl))
1231 log_write ("ACL: %s: %s", filename,
1232 pwmd_strerror (gpg_error_from_errno (errno)));
1233 #endif
1235 else
1236 rc = gpg_error_from_errno (errno);
1239 #ifdef WITH_LIBACL
1240 pthread_cleanup_pop (1);
1241 #endif
1242 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1243 return rc;
1246 gpg_error_t
1247 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1248 size_t keylen, void **result, size_t *rlen)
1250 gpg_error_t rc;
1251 void *tmp;
1253 /* Be sure the algorithm is available. */
1254 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1255 if (rc)
1256 return rc;
1258 /* Always allocate enough for a 256-bit key although the algorithms
1259 themselves may use less. Fixes SAVE --cipher with a different
1260 keylen than the previously saved cipher when cached. */
1261 *rlen = 32;
1262 tmp = xmalloc (*rlen);
1263 if (!tmp)
1264 return GPG_ERR_ENOMEM;
1266 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1267 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1268 if (!rc)
1269 *result = tmp;
1270 else
1271 xfree (tmp);
1273 return rc;
1276 /* The PASSWD command when not using gpg-agent. */
1277 gpg_error_t
1278 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1279 struct crypto_s **rcrypto, int no_passphrase)
1281 unsigned char *key = NULL;
1282 size_t keylen = 0;
1283 struct crypto_s *crypto = NULL;
1284 gpg_error_t rc = init_client_crypto (&crypto);
1286 if (rc)
1287 return rc;
1289 crypto->client_ctx = ctx;
1290 rc = read_data_file (filename, crypto);
1291 if (rc)
1293 cleanup_crypto (&crypto);
1294 return rc;
1297 rc = try_decrypt (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1298 if (rc)
1300 cleanup_crypto (&crypto);
1301 return rc;
1304 gcry_free (key);
1305 key = NULL;
1307 if (!rc)
1309 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1311 if (!no_passphrase)
1312 crypto->save.hdr.flags &= ~PWMD_FLAG_NO_PASSPHRASE;
1314 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1315 crypto->plaintext_len, crypto->filename, NULL,
1316 (void **)&key, &keylen, 0, 0, no_passphrase);
1319 if (!rc)
1321 int cached;
1323 rc = save_common (filename, crypto, crypto->plaintext,
1324 crypto->plaintext_len, key, keylen, &cached, 1);
1325 if (!rc)
1326 *rcrypto = crypto;
1329 if (rc)
1331 gcry_free (key);
1332 cleanup_crypto (&crypto);
1335 return rc;
1338 gpg_error_t
1339 save_common (const char *filename, struct crypto_s *crypto,
1340 const unsigned char *data, size_t datalen,
1341 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1343 struct cache_data_s *cdata;
1344 gpg_error_t rc = 0;
1345 gcry_sexp_t pubkey = NULL;
1346 gcry_sexp_t sigkey = NULL;
1348 /* This is safe since it is a (somewhat) fast operation. */
1349 cache_lock ();
1350 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1351 cdata = cache_get_data_filename (filename);
1352 *cached = cdata != NULL;
1354 if (!cdata)
1355 cdata = xcalloc (1, sizeof (struct cache_data_s));
1357 #ifdef WITH_AGENT
1358 if (use_agent && !no_agent)
1360 rc = gcry_sexp_build (&pubkey, NULL, "%S", crypto->pkey_sexp);
1361 if (!rc)
1362 rc = gcry_sexp_build (&sigkey, NULL, "%S", crypto->sigpkey_sexp);
1364 #endif
1366 if (!rc)
1368 gcry_free (cdata->doc);
1369 cdata->doc = NULL;
1370 gcry_free (cdata->key);
1371 cdata->key = (unsigned char *)key;
1372 cdata->keylen = keylen;
1373 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1374 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1375 &cache_blocksize, 0);
1378 if (!rc)
1380 unsigned char md5file[16];
1382 /* Update in case of any --keygrip argument */
1383 if (cdata->pubkey)
1384 gcry_sexp_release (cdata->pubkey);
1386 if (cdata->sigkey)
1387 gcry_sexp_release (cdata->sigkey);
1389 cdata->pubkey = pubkey;
1390 cdata->sigkey = sigkey;
1391 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1392 rc = cache_set_data (md5file, cdata, crypto->grip);
1394 else
1396 if (pubkey)
1397 gcry_sexp_release (pubkey);
1399 if (sigkey)
1400 gcry_sexp_release (sigkey);
1403 pthread_cleanup_pop (1); // mutex unlock
1404 return rc;
1407 gpg_error_t
1408 getpin_common (assuan_context_t ctx, const char *filename, int which,
1409 char **rkey, size_t *rkeylen)
1411 gpg_error_t rc;
1412 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1413 struct pinentry_s *pin = pinentry_init (filename);
1415 if (!pin)
1416 return GPG_ERR_ENOMEM;
1418 if (client)
1419 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1421 rc = pinentry_lock (ctx, pin);
1422 if (!rc)
1423 rc = pinentry_getpin (pin, rkey, which);
1425 pinentry_deinit (pin);
1426 if (rc)
1427 return rc;
1429 *rkeylen = strlen (*rkey);
1430 if (!(*rkeylen))
1431 (*rkeylen)++;
1433 return rc;
1436 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1437 * both call xfree(). */
1438 gpg_error_t
1439 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1440 unsigned char **result, size_t *rlen)
1442 gpg_error_t rc;
1444 assuan_begin_confidential (ctx);
1445 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1446 assuan_end_confidential (ctx);
1447 return rc;
1450 /* Common to both PKI and non-PKI files. */
1451 gpg_error_t
1452 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1453 const char *filename, char **rkey, size_t *rkeylen)
1455 char *key = NULL;
1456 size_t keylen = 0;
1457 gpg_error_t rc = read_data_file (filename, crypto);
1458 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1459 void *salted_key = NULL;
1460 size_t keysize = 0;
1462 if (rc)
1464 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1465 return rc;
1468 key = config_get_string (filename, "passphrase");
1469 if (key)
1471 log_write (_("Trying the passphrase specified in config ..."));
1472 keylen = strlen (key);
1475 if (!key)
1477 key = config_get_string (filename, "passphrase_file");
1478 if (key)
1480 char *tmp = expand_homedir (key);
1481 int fd;
1482 struct stat st;
1484 xfree (key);
1485 key = tmp;
1486 log_write (_("Trying the passphrase using file '%s' ..."), key);
1487 fd = open (key, O_RDONLY);
1488 if (fd == -1)
1490 rc = gpg_error_from_errno (errno);
1491 log_write ("%s: %s", key, pwmd_strerror (rc));
1492 xfree (key);
1493 return rc;
1496 stat (key, &st);
1497 xfree (key);
1498 key = xmalloc (st.st_size);
1499 if (key)
1501 if (read (fd, key, st.st_size) != st.st_size)
1503 log_write ("short read() count");
1504 rc = GPG_ERR_TOO_SHORT;
1507 else
1508 rc = GPG_ERR_ENOMEM;
1510 close (fd);
1512 if (rc)
1514 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1515 xfree (key);
1516 return rc;
1519 keylen = st.st_size;
1520 if (!keylen)
1522 tmp = xmalloc (1);
1523 *tmp = 0;
1524 xfree (key);
1525 key = tmp;
1526 keylen++;
1531 if (!key && !IS_PKI (crypto) && inquire
1532 && !(crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
1534 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1535 &keylen);
1536 if (rc)
1538 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1539 return rc;
1542 if (!keylen)
1543 keylen++;
1545 else if (!key && !IS_PKI (crypto))
1547 if (crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
1549 keylen = 1;
1550 key = gcry_malloc (keylen);
1551 memset (key, 0, keylen);
1553 else
1555 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1556 if (rc)
1558 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1559 return rc;
1563 #ifdef WITH_AGENT
1564 else if (key && IS_PKI (crypto))
1566 rc = set_agent_passphrase (crypto, key, keylen);
1567 if (rc)
1569 xfree (key);
1570 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1571 return rc;
1574 else if (!key && IS_PKI (crypto))
1576 /* The cache entry has been cleared in save_command(). Will prompt. */
1577 rc = set_pinentry_mode (crypto->agent, inquire ? "loopback" : "ask");
1578 if (rc)
1579 return rc;
1581 #endif
1583 if (key && !IS_PKI (crypto))
1585 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1586 keylen, &salted_key, &keysize);
1587 xfree (key);
1588 key = (char *)salted_key;
1589 keylen = keysize;
1590 if (rc)
1592 xfree (salted_key);
1593 return rc;
1597 xfree (crypto->filename);
1598 crypto->filename = str_dup (filename);
1599 rc = decrypt_data (ctx, crypto, (unsigned char *)key, keylen);
1600 if (rc)
1602 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1603 xfree (key);
1605 else
1607 *rkey = key;
1608 *rkeylen = keylen;
1611 return rc;