Let the CLEARCACHE and CACHETIMEOUT commands make use of 'allowed'.
[pwmd.git] / src / crypto.c
blob7fc012f927bb38909a53205dd7a40f4a2c6ac84d
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)
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) // 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 salted_key = key;
965 keysize = keylen;
966 cached = 1;
971 if (!rc && !cached)
973 rc = hash_key (algo, crypto->save.hdr.salt,
974 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
975 &keysize);
976 gcry_free (key);
979 if (!rc)
980 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
981 &enc_xml, &enc_xml_len, &iv, &iv_len,
982 crypto->save.hdr.iterations);
984 if (!rc)
986 memcpy (crypto->save.hdr.iv, iv, iv_len);
987 xfree (iv);
988 crypto->save.hdr.datalen = enc_xml_len;
989 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
990 NULL);
991 gcry_free (enc_xml);
992 if (!rc)
994 *rkey = salted_key;
995 *rkeylen = keysize;
996 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
1000 if (rc)
1001 gcry_free (salted_key);
1003 return rc;
1006 #ifdef WITH_LIBACL
1007 static void
1008 cleanup_acl (void *arg)
1010 acl_t acl = *(acl_t *) arg;
1012 if (acl)
1013 acl_free (acl);
1015 #endif
1017 static gpg_error_t
1018 write_header (struct crypto_s *crypto, int fd)
1020 ssize_t len;
1021 uint64_t n, x;
1022 uint32_t i;
1024 #ifdef WORDS_BIGENDIAN
1025 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1026 if (len == -1)
1027 goto done;
1029 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
1030 if (len == -1)
1031 goto done;
1033 len = write (fd, &crypto->save.hdr.iterations,
1034 sizeof(crypto->save.hdr.iterations));
1035 if (len == -1)
1036 goto done;
1038 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1039 if (len == -1)
1040 goto done;
1042 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1043 if (len == -1)
1044 goto done;
1046 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1047 if (len == -1)
1048 goto done;
1050 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1051 if (len == -1)
1052 goto done;
1053 #else
1054 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1055 if (len == -1)
1056 goto done;
1058 i = htonl (crypto->save.hdr.version);
1059 len = write (fd, &i, sizeof(i));
1060 if (len == -1)
1061 goto done;
1063 n = crypto->save.hdr.iterations;
1064 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1065 len = write (fd, &x, sizeof(x));
1066 if (len == -1)
1067 goto done;
1069 n = crypto->save.hdr.flags;
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 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1076 if (len == -1)
1077 goto done;
1079 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1080 if (len == -1)
1081 goto done;
1083 i = htonl (crypto->save.hdr.datalen);
1084 len = write (fd, &i, sizeof(i));
1085 if (len == -1)
1086 goto done;
1087 #endif
1089 done:
1090 return len == -1 ? gpg_error_from_errno (errno) : 0;
1093 /* Write the data structures to disk. */
1094 gpg_error_t
1095 write_file (struct crypto_s *crypto, const char *filename,
1096 void *data, size_t data_len, void *sexp, size_t sexp_len,
1097 void *pubkey, void *sigpkey)
1099 char tmp[FILENAME_MAX] = { 0 };
1100 mode_t mode = 0;
1101 struct stat st;
1102 int fd;
1103 gpg_error_t rc = 0;
1104 size_t len;
1105 #ifdef WITH_LIBACL
1106 acl_t acl = NULL;
1107 #endif
1109 if (filename)
1111 if (lstat (filename, &st) == 0)
1113 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1115 if (!(mode & S_IWUSR))
1116 return GPG_ERR_EACCES;
1118 else if (errno != ENOENT)
1119 return gpg_error_from_errno (errno);
1121 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1122 fd = mkstemp (tmp);
1123 if (fd == -1)
1125 rc = gpg_error_from_errno (errno);
1126 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1127 return rc;
1130 else
1132 // xml_import() or convert_file() from command line.
1133 fd = STDOUT_FILENO;
1136 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1137 crypto->save.hdr.version = VERSION_HEX;
1138 rc = write_header (crypto, fd);
1139 if (!rc)
1141 if (crypto->save.hdr.flags & PWMD_FLAG_PKI)
1143 unsigned char grip[20];
1145 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1146 len = write (fd, grip, sizeof (grip));
1147 if (len == sizeof (grip))
1149 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1150 len = write (fd, grip, sizeof (grip));
1151 if (len == sizeof (grip))
1153 len = write (fd, data, data_len);
1154 if (len == data_len)
1156 len = write (fd, sexp, sexp_len);
1157 if (len != sexp_len)
1158 rc = gpg_error_from_errno (errno);
1160 else
1161 rc = gpg_error_from_errno (errno);
1164 else
1165 rc = gpg_error_from_errno (errno);
1167 else
1169 len = write (fd, data, data_len);
1170 if (len != data_len)
1171 rc = gpg_error_from_errno (errno);
1175 #ifdef WITH_LIBACL
1176 pthread_cleanup_push (cleanup_acl, &acl);
1177 #endif
1178 if (!rc)
1180 if (fsync (fd) != -1)
1182 if (filename && close (fd) != -1)
1184 #ifdef WITH_LIBACL
1185 acl = acl_get_file (filename, ACL_TYPE_ACCESS);
1186 if (!acl && errno == ENOENT)
1187 acl = acl_get_file (".", ACL_TYPE_DEFAULT);
1188 if (!acl)
1189 log_write ("ACL: %s: %s", filename,
1190 pwmd_strerror (gpg_error_from_errno (errno)));
1191 #endif
1193 if (mode && config_get_boolean (filename, "backup"))
1195 char tmp2[FILENAME_MAX];
1197 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1198 if (rename (filename, tmp2) == -1)
1199 rc = gpg_error_from_errno (errno);
1202 else if (filename)
1203 rc = gpg_error_from_errno (errno);
1205 else
1206 rc = gpg_error_from_errno (errno);
1209 if (!rc)
1211 if (filename && rename (tmp, filename) != -1)
1213 tmp[0] = 0;
1214 if (filename && mode)
1215 chmod (filename, mode);
1217 #ifdef WITH_LIBACL
1218 if (acl && acl_set_file (filename, ACL_TYPE_ACCESS, acl))
1219 log_write ("ACL: %s: %s", filename,
1220 pwmd_strerror (gpg_error_from_errno (errno)));
1221 #endif
1223 else
1224 rc = gpg_error_from_errno (errno);
1227 #ifdef WITH_LIBACL
1228 pthread_cleanup_pop (1);
1229 #endif
1230 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1231 return rc;
1234 gpg_error_t
1235 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1236 size_t keylen, void **result, size_t *rlen)
1238 gpg_error_t rc;
1239 void *tmp;
1241 /* Be sure the algorithm is available. */
1242 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1243 if (rc)
1244 return rc;
1246 /* Always allocate enough for a 256-bit key although the algorithms
1247 themselves may use less. Fixes SAVE --cipher with a different
1248 keylen than the previously saved cipher when cached. */
1249 *rlen = 32;
1250 tmp = xmalloc (*rlen);
1251 if (!tmp)
1252 return GPG_ERR_ENOMEM;
1254 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1255 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1256 if (!rc)
1257 *result = tmp;
1258 else
1259 xfree (tmp);
1261 return rc;
1264 /* The PASSWD command when not using gpg-agent. */
1265 gpg_error_t
1266 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1267 struct crypto_s **rcrypto)
1269 unsigned char *key = NULL;
1270 size_t keylen = 0;
1271 struct crypto_s *crypto = NULL;
1272 gpg_error_t rc = init_client_crypto (&crypto);
1274 if (rc)
1275 return rc;
1277 crypto->client_ctx = ctx;
1278 rc = read_data_file (filename, crypto);
1279 if (rc)
1281 cleanup_crypto (&crypto);
1282 return rc;
1285 rc = try_decrypt (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1286 if (rc)
1288 cleanup_crypto (&crypto);
1289 return rc;
1292 if (!rc)
1294 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1295 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1296 crypto->plaintext_len, crypto->filename, NULL,
1297 (void **)&key, &keylen, 0, 0);
1300 if (!rc)
1302 int cached;
1304 rc = save_common (filename, crypto, crypto->plaintext,
1305 crypto->plaintext_len, key, keylen, &cached, 1);
1306 if (!rc)
1307 *rcrypto = crypto;
1310 if (rc)
1312 gcry_free (key);
1313 cleanup_crypto (&crypto);
1316 return rc;
1319 gpg_error_t
1320 save_common (const char *filename, struct crypto_s *crypto,
1321 const unsigned char *data, size_t datalen,
1322 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1324 struct cache_data_s *cdata;
1325 gpg_error_t rc = 0;
1326 gcry_sexp_t pubkey = NULL;
1327 gcry_sexp_t sigkey = NULL;
1329 /* This is safe since it is a (somewhat) fast operation. */
1330 cache_lock ();
1331 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1332 cdata = cache_get_data_filename (filename);
1333 *cached = cdata != NULL;
1335 if (!cdata)
1336 cdata = xcalloc (1, sizeof (struct cache_data_s));
1338 #ifdef WITH_AGENT
1339 if (use_agent && !no_agent)
1341 rc = gcry_sexp_build (&pubkey, NULL, "%S", crypto->pkey_sexp);
1342 if (!rc)
1343 rc = gcry_sexp_build (&sigkey, NULL, "%S", crypto->sigpkey_sexp);
1345 #endif
1347 if (!rc)
1349 gcry_free (cdata->doc);
1350 cdata->doc = NULL;
1351 cdata->key = (unsigned char *)key;
1352 cdata->keylen = keylen;
1353 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1354 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1355 &cache_blocksize, 0);
1358 if (!rc)
1360 unsigned char md5file[16];
1362 /* Update in case of any --keygrip argument */
1363 if (cdata->pubkey)
1364 gcry_sexp_release (cdata->pubkey);
1366 if (cdata->sigkey)
1367 gcry_sexp_release (cdata->sigkey);
1369 cdata->pubkey = pubkey;
1370 cdata->sigkey = sigkey;
1371 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1372 rc = cache_set_data (md5file, cdata, crypto->grip);
1374 else
1376 if (pubkey)
1377 gcry_sexp_release (pubkey);
1379 if (sigkey)
1380 gcry_sexp_release (sigkey);
1383 pthread_cleanup_pop (1); // mutex unlock
1384 return rc;
1387 gpg_error_t
1388 getpin_common (assuan_context_t ctx, const char *filename, int which,
1389 char **rkey, size_t *rkeylen)
1391 gpg_error_t rc;
1392 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1393 struct pinentry_s *pin = pinentry_init (filename);
1395 if (!pin)
1396 return GPG_ERR_ENOMEM;
1398 if (client)
1399 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1401 rc = pinentry_lock (ctx, pin);
1402 if (!rc)
1403 rc = pinentry_getpin (pin, rkey, which);
1405 pinentry_deinit (pin);
1406 if (rc)
1407 return rc;
1409 *rkeylen = strlen (*rkey);
1410 if (!(*rkeylen))
1411 (*rkeylen)++;
1413 return rc;
1416 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1417 * both call xfree(). */
1418 gpg_error_t
1419 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1420 unsigned char **result, size_t *rlen)
1422 gpg_error_t rc;
1424 assuan_begin_confidential (ctx);
1425 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1426 assuan_end_confidential (ctx);
1427 return rc;
1430 /* Common to both PKI and non-PKI files. */
1431 gpg_error_t
1432 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1433 const char *filename, char **rkey, size_t *rkeylen)
1435 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 *salted_key = NULL;
1440 size_t keysize = 0;
1442 if (rc)
1444 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1445 return rc;
1448 key = config_get_string (filename, "passphrase");
1449 if (key)
1451 log_write (_("Trying the passphrase specified in config ..."));
1452 keylen = strlen (key);
1455 if (!key)
1457 key = config_get_string (filename, "passphrase_file");
1458 if (key)
1460 char *tmp = expand_homedir (key);
1461 int fd;
1462 struct stat st;
1464 xfree (key);
1465 key = tmp;
1466 log_write (_("Trying the passphrase using file '%s' ..."), key);
1467 fd = open (key, O_RDONLY);
1468 if (fd == -1)
1470 rc = gpg_error_from_errno (errno);
1471 log_write ("%s: %s", key, pwmd_strerror (rc));
1472 xfree (key);
1473 return rc;
1476 stat (key, &st);
1477 xfree (key);
1478 key = xmalloc (st.st_size);
1479 if (key)
1481 if (read (fd, key, st.st_size) != st.st_size)
1483 log_write ("short read() count");
1484 rc = GPG_ERR_TOO_SHORT;
1487 else
1488 rc = GPG_ERR_ENOMEM;
1490 close (fd);
1492 if (rc)
1494 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1495 xfree (key);
1496 return rc;
1499 keylen = st.st_size;
1500 if (!keylen)
1502 tmp = xmalloc (1);
1503 *tmp = 0;
1504 xfree (key);
1505 key = tmp;
1506 keylen++;
1511 if (!key && !IS_PKI (crypto) && inquire)
1513 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1514 &keylen);
1515 if (rc)
1517 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1518 return rc;
1521 if (!keylen)
1522 keylen++;
1524 else if (!key && !IS_PKI (crypto))
1526 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1527 if (rc)
1529 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1530 return rc;
1533 #ifdef WITH_AGENT
1534 else if (key && IS_PKI (crypto))
1536 rc = set_agent_passphrase (crypto, key, keylen);
1537 if (rc)
1539 xfree (key);
1540 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1541 return rc;
1544 else if (!key && IS_PKI (crypto))
1546 /* The cache entry has been cleared in save_command(). Will prompt. */
1547 rc = set_pinentry_mode (crypto->agent, inquire ? "loopback" : "ask");
1548 if (rc)
1549 return rc;
1551 #endif
1553 if (key && !IS_PKI (crypto))
1555 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1556 keylen, &salted_key, &keysize);
1557 xfree (key);
1558 key = (char *)salted_key;
1559 keylen = keysize;
1560 if (rc)
1562 xfree (salted_key);
1563 return rc;
1567 xfree (crypto->filename);
1568 crypto->filename = str_dup (filename);
1569 rc = decrypt_data (ctx, crypto, (unsigned char *)key, keylen);
1570 if (rc)
1572 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1573 xfree (key);
1575 else
1577 *rkey = key;
1578 *rkeylen = keylen;
1581 return rc;