Fix ACL crash for non-existing user.
[pwmd.git] / src / crypto.c
blob29030f79c87ab47d017e7ef786fa83a52f8c58bb
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
32 #include "pwmd-error.h"
33 #include "util-misc.h"
34 #include "common.h"
35 #include "rcfile.h"
36 #include "pinentry.h"
37 #include "crypto.h"
38 #include "cache.h"
39 #include "mem.h"
40 #include "util-string.h"
42 static uint8_t pwmd_magic[5] = { '\177', 'P', 'W', 'M', 'D' };
44 /* Sets the default cipher values for new files. */
45 void
46 set_header_defaults (file_header_t * hdr)
48 char *s = config_get_string (NULL, "cipher");
49 int flags = cipher_string_to_cipher (s);
51 xfree (s);
52 memset (hdr, 0, sizeof (file_header_t));
53 memcpy (hdr->magic, pwmd_magic, sizeof (hdr->magic));
54 if (flags == -1)
55 log_write (_
56 ("Invalid 'cipher' in configuration file. Using a default of aes256."));
57 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
58 hdr->version = VERSION_HEX;
60 #ifdef WITH_AGENT
61 if (use_agent)
62 hdr->flags |= PWMD_FLAG_PKI;
63 #endif
66 static gpg_error_t
67 read_header (file_header_t *hdr, int fd)
69 ssize_t len;
70 uint32_t i;
71 uint64_t n;
73 #ifdef WORDS_BIGENDIAN
74 len = read (fd, &hdr->magic, sizeof(hdr->magic));
75 if (len == -1)
76 goto done;
78 len = read (fd, &hdr->version, sizeof(hdr->version));
79 if (len == -1)
80 goto done;
82 len = read (fd, &hdr->iterations, sizeof(hdr->iterations));
83 if (len == -1)
84 goto done;
86 len = read (fd, &hdr->flags, sizeof(hdr->flags));
87 if (len == -1)
88 goto done;
90 len = read (fd, &hdr->iv, sizeof(hdr->iv));
91 if (len == -1)
92 goto done;
94 len = read (fd, &hdr->salt, sizeof(hdr->salt));
95 if (len == -1)
96 goto done;
98 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
99 if (len == -1)
100 goto done;
101 #else
102 len = read (fd, &hdr->magic, sizeof(hdr->magic));
103 if (len == -1)
104 goto done;
106 len = read (fd, &i, sizeof(hdr->version));
107 if (len == -1)
108 goto done;
109 hdr->version = ntohl (i);
111 len = read (fd, &n, sizeof(hdr->iterations));
112 if (len == -1)
113 goto done;
114 hdr->iterations = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
116 len = read (fd, &n, sizeof(hdr->flags));
117 if (len == -1)
118 goto done;
119 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
121 len = read (fd, &hdr->iv, sizeof(hdr->iv));
122 if (len == -1)
123 goto done;
125 len = read (fd, &hdr->salt, sizeof(hdr->salt));
126 if (len == -1)
127 goto done;
129 len = read (fd, &i, sizeof(hdr->datalen));
130 if (len == -1)
131 goto done;
132 hdr->datalen = ntohl (i);
133 #endif
135 done:
136 return len == -1 ? gpg_error_from_errno (errno) : 0;
139 /* Read the header of a data file to determine cipher and other. The
140 * header is stored big endian in the file and is converted to little
141 * endian when needed. */
142 gpg_error_t
143 read_data_header (const char *filename, file_header_t * rhdr,
144 struct stat *rst, int *rfd)
146 gpg_error_t rc = 0;
147 struct stat st;
148 file_header_t hdr;
149 int fd;
151 if (lstat (filename, &st) == -1)
152 return gpg_error_from_errno (errno);
154 if (!S_ISREG (st.st_mode))
155 return gpg_error (GPG_ERR_ENOANO);
157 fd = open (filename, O_RDONLY);
158 if (fd == -1)
159 return gpg_error_from_errno (errno);
161 rc = read_header (&hdr, fd);
162 if (!rc && memcmp (hdr.magic, pwmd_magic, sizeof (hdr.magic)))
163 rc = GPG_ERR_BAD_DATA;
164 else if (!rc && hdr.version < 0x030000)
165 rc = GPG_ERR_UNKNOWN_VERSION;
167 if (rc)
168 close (fd);
169 else
171 if (rhdr)
172 *rhdr = hdr;
173 if (rst)
174 *rst = st;
175 if (rfd)
176 *rfd = fd;
177 else
178 close (fd);
181 return gpg_error (rc);
184 gpg_error_t
185 read_data_file (const char *filename, struct crypto_s * crypto)
187 int fd;
188 gpg_error_t rc = 0;
189 size_t len, rlen;
190 char *buf = NULL;
191 struct stat st;
193 if (!filename)
194 return GPG_ERR_INV_PARAMETER;
196 cleanup_crypto_stage1 (crypto);
197 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
198 if (rc)
199 return gpg_error (rc);
201 crypto->ciphertext_len = crypto->hdr.datalen;
202 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
203 if (!crypto->ciphertext)
205 rc = GPG_ERR_ENOMEM;
206 goto done;
209 /* The keygrips for PKI files are stored after the header. They are
210 * stored in the file to let file(1) magic(5) show the grips. */
211 if (crypto->hdr.flags & PWMD_FLAG_PKI)
213 rlen = read (fd, crypto->grip, 20);
214 if (rlen != 20)
216 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
217 goto done;
220 rlen = read (fd, crypto->sign_grip, 20);
221 if (rlen != 20)
223 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
224 goto done;
228 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
229 if (len != crypto->hdr.datalen)
231 rc = len == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
232 goto done;
235 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
236 goto done;
238 if (!use_agent)
240 rc = GPG_ERR_NOT_IMPLEMENTED;
241 goto done;
244 #ifdef WITH_AGENT
245 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
246 buf = xmalloc (len);
247 if (!buf)
249 rc = GPG_ERR_ENOMEM;
250 goto done;
253 /* Remaining data file bytes are the encrypted key and XML. */
254 rlen = read (fd, buf, len);
255 if (rlen != len)
257 rc = rlen == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
258 goto done;
261 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
262 if (rc)
263 goto done;
265 if (crypto->pkey_sexp)
266 gcry_sexp_release (crypto->pkey_sexp);
268 if (crypto->sigpkey_sexp)
269 gcry_sexp_release (crypto->sigpkey_sexp);
271 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
272 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
273 if (!rc)
274 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
275 #endif
277 done:
278 close (fd);
279 xfree (buf);
280 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
281 rc = gpg_error (rc);
283 return rc;
286 #define CRYPTO_BLOCKSIZE(c) (blocksize * 1024)
289 * Useful for a large amount of data. Rather than doing all of the data in one
290 * iteration do it in chunks. This lets the command be cancelable rather than
291 * waiting for it to complete.
293 static gpg_error_t
294 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
295 size_t insize, size_t blocksize, status_msg_t which)
297 gpg_error_t rc = 0;
298 off_t len = CRYPTO_BLOCKSIZE (blocksize);
299 void *p = gcry_malloc (len);
300 off_t total = 0;
302 if (!p)
303 return gpg_error (GPG_ERR_ENOMEM);
305 if (insize < CRYPTO_BLOCKSIZE (blocksize))
306 len = insize;
308 pthread_cleanup_push (gcry_free, p);
310 for (;;)
312 unsigned char *inbuf2 = inbuf + total;
313 unsigned char *tmp;
315 if (len + total > insize)
316 len = blocksize;
318 if (which == STATUS_ENCRYPT)
319 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
320 else
321 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
323 if (rc)
324 break;
326 tmp = inbuf + total;
327 memmove (tmp, p, len);
328 total += len;
329 if (total >= insize)
330 break;
332 #ifdef HAVE_PTHREAD_TESTCANCEL
333 pthread_testcancel ();
334 #endif
337 pthread_cleanup_pop (1);
338 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
339 rc = gpg_error (rc);
341 return rc;
344 static void
345 cleanup_cipher (void *arg)
347 gcry_cipher_close ((gcry_cipher_hd_t) arg);
350 /* Decrypt the XML data. For PKI data files the key is retrieved from
351 * gpg-agent and the signature verified. */
352 gpg_error_t
353 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
354 unsigned char *salted_key, size_t skeylen)
356 gpg_error_t rc = 0;
357 unsigned char *key = salted_key;
358 gcry_cipher_hd_t h = NULL;
359 size_t blocksize, keysize = 0;
360 int algo = cipher_to_gcrypt (crypto->hdr.flags);
361 void *outbuf = NULL;
362 uint64_t n = crypto->hdr.iterations;
363 long progress = 0;
364 #ifdef WITH_AGENT
365 size_t keylen = skeylen;
366 gcry_sexp_t sig_sexp;
368 if (crypto->hdr.flags & PWMD_FLAG_PKI)
370 rc = agent_extract_key (crypto, &key, &keylen);
371 if (rc)
372 return rc;
374 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
375 if (!sig_sexp)
377 gcry_free (key);
378 return GPG_ERR_BAD_DATA;
381 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
382 crypto->ciphertext_len);
383 gcry_sexp_release (sig_sexp);
385 #endif
387 if (!rc)
389 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
390 if (!rc)
392 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
393 &keysize);
394 if (!rc)
396 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
397 &blocksize);
398 if (!rc)
400 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
401 if (!rc)
403 rc = gcry_cipher_setkey (h, key, keysize);
410 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
412 if (!rc)
414 outbuf = gcry_malloc (crypto->hdr.datalen);
415 if (!outbuf)
416 rc = GPG_ERR_ENOMEM;
419 pthread_cleanup_push (gcry_free, outbuf);
420 #ifdef WITH_AGENT
421 pthread_cleanup_push (gcry_free, key);
422 #endif
424 if (!rc)
426 if (!key)
427 rc = GPG_ERR_INV_PARAMETER;
428 else
430 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
431 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
432 STATUS_DECRYPT);
435 if (!rc)
437 key[0] ^= 1;
438 rc = gcry_cipher_setkey (h, key, keysize);
442 if (!rc)
444 progress = config_get_long (NULL, "cipher_progress");
445 if (progress == -1)
446 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
449 if (!rc && ctx && crypto->hdr.iterations)
450 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", 0,
451 crypto->hdr.iterations);
453 for (n = 0; !rc && n < crypto->hdr.iterations; n++)
455 if (ctx && progress && !(n % progress))
457 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
458 crypto->hdr.iterations);
459 if (rc)
460 break;
463 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
464 if (rc)
465 break;
467 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
468 STATUS_DECRYPT);
471 if (!rc && ctx && crypto->hdr.iterations)
472 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
473 crypto->hdr.iterations);
475 #ifdef WITH_AGENT
476 pthread_cleanup_pop (0);
477 if (crypto->hdr.flags & PWMD_FLAG_PKI)
478 gcry_free (key);
479 else if (key)
480 key[0] ^= 1;
481 #else
482 key[0] ^= 1;
483 #endif
484 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
485 pthread_cleanup_pop (1); /* cipher */
486 if (!rc)
488 char buf[] = "<?xml ";
490 if (memcmp (outbuf, buf, sizeof(buf)-1))
492 gcry_free (outbuf);
493 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
496 crypto->plaintext = outbuf;
497 crypto->plaintext_len = crypto->hdr.datalen;
500 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
501 rc = gpg_error (rc);
503 return rc;
506 /* The cached document is encrypted with encrypt_xml(). This decrypts
507 * it from the OPEN command. */
508 gpg_error_t
509 decrypt_cache (struct crypto_s * crypto, const void *data, size_t len)
511 gcry_cipher_hd_t h = NULL;
512 gpg_error_t rc;
514 rc = gcry_cipher_open (&h, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
515 if (rc)
516 return rc;
518 gcry_free (crypto->plaintext);
519 crypto->plaintext = gcry_malloc (len);
520 if (!crypto->plaintext)
522 rc = GPG_ERR_ENOMEM;
523 goto done;
526 rc = gcry_cipher_setiv (h, cache_iv, cache_blocksize);
527 if (rc)
528 goto done;
530 rc = gcry_cipher_setkey (h, cache_key, cache_keysize);
531 if (rc)
532 goto done;
534 rc = gcry_cipher_decrypt (h, crypto->plaintext, len, data, len);
535 if (rc || strncmp (crypto->plaintext, "<?xml ", 6))
537 if (!rc)
538 rc = GPG_ERR_BAD_DATA;
540 gcry_free (crypto->plaintext);
541 crypto->plaintext = NULL;
544 crypto->plaintext_len = len;
546 done:
547 if (h)
548 gcry_cipher_close (h);
550 return rc;
553 /* Encrypt the XML data and set 'result'. At least one encryption
554 * iteration is done. */
555 gpg_error_t
556 encrypt_xml (assuan_context_t ctx, void *key, size_t keylen,
557 int algo, const void *xml, size_t len, void * *result,
558 size_t *result_len, unsigned char **iv, size_t * iv_len,
559 uint64_t iter)
561 gpg_error_t rc;
562 gcry_cipher_hd_t h;
563 size_t blocksize, keysize;
564 void *inbuf = NULL;
565 size_t olen = len;
566 uint64_t n = 0;
567 unsigned char *tmpkey = NULL;
568 int init_iv = *(iv_len) == 0;
570 if (!key)
571 return GPG_ERR_INV_PARAMETER;
573 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
574 if (rc)
575 return rc;
577 pthread_cleanup_push (cleanup_cipher, h);
578 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
579 if (!rc)
580 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL, &blocksize);
582 if (!rc && init_iv)
584 *(iv) = xmalloc (blocksize);
585 if (!*(iv))
586 rc = GPG_ERR_ENOMEM;
588 gcry_create_nonce (*(iv), blocksize);
591 if (!rc)
593 if (init_iv)
594 *iv_len = blocksize;
596 tmpkey = gcry_malloc (keysize);
597 if (!tmpkey)
598 rc = GPG_ERR_ENOMEM;
601 pthread_cleanup_push (gcry_free, tmpkey);
603 if (!rc)
605 memcpy (tmpkey, key, keysize);
606 tmpkey[0] ^= 1;
607 rc = gcry_cipher_setkey (h, tmpkey, keysize);
608 if (!rc)
610 if (len % blocksize)
611 len += blocksize - (len % blocksize);
615 if (!rc)
617 inbuf = gcry_malloc (len);
618 if (!inbuf)
619 rc = GPG_ERR_ENOMEM;
622 pthread_cleanup_push (gcry_free, inbuf);
624 if (!rc)
626 long progress = config_get_long (NULL, "cipher_progress");
628 memset (inbuf, 0, len);
629 memcpy (inbuf, xml, olen);
631 if (progress == -1)
632 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
634 if (!rc && ctx && iter)
635 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", 0, iter);
637 for (n = 0; !rc && n < iter; n++)
639 if (ctx && progress && !(n % progress))
641 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
642 if (rc)
643 break;
646 rc = gcry_cipher_setiv (h, *(iv), blocksize);
647 if (rc)
648 break;
650 rc = iterate_crypto_once (h, inbuf, len, blocksize, STATUS_ENCRYPT);
654 if (!rc && ctx && iter)
655 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
657 if (!rc)
659 /* Do at least one iteration. */
660 rc = gcry_cipher_setiv (h, *(iv), blocksize);
661 if (!rc)
663 rc = gcry_cipher_setkey (h, key, keysize);
664 if (!rc)
665 rc = iterate_crypto_once (h, inbuf, len, blocksize,
666 STATUS_ENCRYPT);
670 pthread_cleanup_pop (rc ? 1 : 0); /* inbuf */
671 pthread_cleanup_pop (1); /* tmpkey */
672 pthread_cleanup_pop (1); /* cipher */
674 if (rc && init_iv)
676 xfree (*(iv));
677 *iv = NULL;
680 *result = rc ? NULL : inbuf;
681 *result_len = len;
682 return rc;
685 void
686 cleanup_save (struct save_s *save)
688 if (!save)
689 return;
691 #ifdef WITH_AGENT
692 if (save->pkey)
693 gcry_sexp_release (save->pkey);
695 if (save->sigpkey)
696 gcry_sexp_release (save->sigpkey);
697 #endif
699 memset (save, 0, sizeof (struct save_s));
702 /* Keep the agent ctx to retain pinentry options which will be freed in
703 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
704 void
705 cleanup_crypto_stage1 (struct crypto_s *cr)
707 if (!cr)
708 return;
710 cleanup_save (&cr->save);
712 #ifdef WITH_AGENT
713 if (cr->ciphertext_sexp)
714 gcry_sexp_release (cr->ciphertext_sexp);
716 cr->ciphertext_sexp = NULL;
717 #endif
719 gcry_free (cr->plaintext);
720 xfree (cr->ciphertext);
721 xfree (cr->filename);
722 cr->filename = NULL;
723 cr->ciphertext = NULL;
724 cr->ciphertext_len = 0;
725 cr->plaintext = NULL;
726 cr->plaintext_len = 0;
729 void
730 cleanup_crypto_stage2 (struct crypto_s *cr)
732 if (!cr)
733 return;
735 cleanup_crypto_stage1 (cr);
736 set_header_defaults (&cr->hdr);
739 void
740 cleanup_crypto (struct crypto_s **c)
742 struct crypto_s *cr = *c;
744 if (!cr)
745 return;
747 cleanup_crypto_stage2 (cr);
749 #ifdef WITH_AGENT
750 if (cr->pkey_sexp)
751 gcry_sexp_release (cr->pkey_sexp);
753 if (cr->sigpkey_sexp)
754 gcry_sexp_release (cr->sigpkey_sexp);
756 if (cr->agent)
757 cleanup_agent (cr->agent);
758 #endif
760 xfree (cr);
761 *c = NULL;
764 gpg_error_t
765 init_client_crypto (struct crypto_s **crypto)
767 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
768 gpg_error_t rc;
770 if (!new)
772 rc = GPG_ERR_ENOMEM;
773 return rc;
776 #ifdef WITH_AGENT
777 if (use_agent)
779 rc = agent_init (&new->agent);
780 if (!rc)
782 rc = send_agent_common_options (new->agent);
783 if (!rc)
784 rc = agent_set_pinentry_options (new->agent);
787 if (rc)
789 cleanup_agent (new->agent);
790 xfree (new);
791 return rc;
794 #endif
796 set_header_defaults (&new->hdr);
797 *crypto = new;
798 return 0;
801 static gpg_error_t
802 try_decrypt (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
803 const char *filename, char **key, size_t *keylen)
805 gpg_error_t rc;
806 int pin_try = 1;
807 int pin_tries = 3;
808 char *pin_title = NULL;
809 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
813 rc = decrypt_common (ctx, inquire, crypto, filename, key, keylen);
814 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE && ctx)
816 if (pin_try == 1)
817 pin_title = client->pinentry_opts.title;
819 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try+1, pin_tries);
822 while (!inquire && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
823 && ++pin_try <= pin_tries);
825 if (ctx && pin_title != client->pinentry_opts.title)
827 xfree (client->pinentry_opts.title);
828 client->pinentry_opts.title = pin_title;
831 return rc;
834 /* Common to both PKI and non-PKI files when saving a data
835 * file. Defers to gpg-agent when needed and handles keyfiles. */
836 gpg_error_t
837 export_common (assuan_context_t ctx, int inquire, struct crypto_s * crypto,
838 const void *data, size_t datalen, const char *outfile,
839 const char *keyfile, void **rkey, size_t *rkeylen,
840 int use_cache, int force, int no_passphrase)
842 gpg_error_t rc = 0;
843 void *enc_xml = NULL;
844 size_t enc_xml_len = 0;
845 unsigned char *iv = NULL;
846 size_t iv_len = 0;
847 int algo = cipher_to_gcrypt (crypto->save.hdr.flags);
848 void *key = NULL, *salted_key = NULL;
849 size_t keysize, keylen = 0;
850 int cached = 0;
852 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
853 if (rc)
854 return rc;
856 if (keyfile)
858 int fd;
859 unsigned char *buf;
860 struct stat st;
862 if (stat (keyfile, &st) == -1)
863 return gpg_error_from_errno (errno);
865 buf = gcry_malloc (st.st_size);
866 if (!buf)
867 return GPG_ERR_ENOMEM;
869 fd = open (keyfile, O_RDONLY);
870 if (fd == -1)
871 rc = gpg_error_from_errno (errno);
872 else
874 size_t len = read (fd, buf, st.st_size);
876 if (len != st.st_size)
877 rc = GPG_ERR_TOO_SHORT;
880 if (fd != -1)
881 close (fd);
883 key = buf;
884 keylen = st.st_size;
885 log_write (_("Using passphrase obtained from file '%s'"), keyfile);
887 if (!keylen)
889 char *tmp;
891 gcry_free (key);
892 tmp = gcry_malloc (1);
893 *tmp = 0;
894 key = tmp;
895 keylen++;
898 else
900 if (use_cache)
902 int defer = -1;
904 cache_lock ();
905 rc = cache_iscached (outfile, &defer);
906 if (!rc)
907 cached = 1;
908 else if (gpg_err_code (rc) == GPG_ERR_ENOENT
909 || gpg_err_code (rc) == GPG_ERR_NO_DATA)
910 rc = 0;
912 if (cached)
914 struct cache_data_s *cdata = cache_get_data_filename (outfile);
916 salted_key = gcry_malloc (cdata->keylen);
917 if (salted_key)
919 memcpy (salted_key, cdata->key, cdata->keylen);
920 keysize = cdata->keylen;
922 else
923 rc = GPG_ERR_ENOMEM;
926 cache_unlock ();
929 if (!rc && !cached)
931 if (force) // SAVE
933 struct crypto_s *tmp = NULL;
934 gpg_error_t rc = init_client_crypto (&tmp);
936 if (!rc)
938 rc = read_data_file (outfile, tmp);
939 if (!rc)
941 rc = try_decrypt (ctx, inquire, tmp, outfile,
942 (char **)&key, &keylen);
943 if (rc)
944 gcry_free (key);
948 cleanup_crypto (&tmp);
949 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
950 use_cache = 0;
951 else if (rc)
952 return rc;
955 if (!use_cache && !no_passphrase) // PASSWD or new file
957 gcry_free (key);
958 if (inquire)
960 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
961 (unsigned char **)&key, &keylen);
963 else
965 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
966 (char **)&key, &keylen);
969 if (rc)
970 return rc;
972 else
974 if (no_passphrase)
976 keylen = 1;
977 key = gcry_malloc (keylen);
978 memset (key, 0, keylen);
980 else
982 salted_key = key;
983 keysize = keylen;
984 cached = 1;
990 if (!rc && !cached)
992 rc = hash_key (algo, crypto->save.hdr.salt,
993 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
994 &keysize);
995 gcry_free (key);
998 if (!rc)
999 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
1000 &enc_xml, &enc_xml_len, &iv, &iv_len,
1001 crypto->save.hdr.iterations);
1003 if (!rc)
1005 if (no_passphrase && !(crypto->save.hdr.flags & PWMD_FLAG_PKI))
1006 crypto->save.hdr.flags |= PWMD_FLAG_NO_PASSPHRASE;
1008 memcpy (crypto->save.hdr.iv, iv, iv_len);
1009 xfree (iv);
1010 crypto->save.hdr.datalen = enc_xml_len;
1011 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
1012 NULL);
1013 gcry_free (enc_xml);
1014 if (!rc)
1016 *rkey = salted_key;
1017 *rkeylen = keysize;
1018 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
1022 if (rc)
1023 gcry_free (salted_key);
1025 return rc;
1028 static gpg_error_t
1029 write_header (struct crypto_s *crypto, int fd)
1031 ssize_t len;
1032 uint64_t n, x;
1033 uint32_t i;
1035 #ifdef WORDS_BIGENDIAN
1036 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1037 if (len == -1)
1038 goto done;
1040 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
1041 if (len == -1)
1042 goto done;
1044 len = write (fd, &crypto->save.hdr.iterations,
1045 sizeof(crypto->save.hdr.iterations));
1046 if (len == -1)
1047 goto done;
1049 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1050 if (len == -1)
1051 goto done;
1053 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1054 if (len == -1)
1055 goto done;
1057 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1058 if (len == -1)
1059 goto done;
1061 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1062 if (len == -1)
1063 goto done;
1064 #else
1065 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1066 if (len == -1)
1067 goto done;
1069 i = htonl (crypto->save.hdr.version);
1070 len = write (fd, &i, sizeof(i));
1071 if (len == -1)
1072 goto done;
1074 n = crypto->save.hdr.iterations;
1075 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1076 len = write (fd, &x, sizeof(x));
1077 if (len == -1)
1078 goto done;
1080 n = crypto->save.hdr.flags;
1081 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1082 len = write (fd, &x, sizeof(x));
1083 if (len == -1)
1084 goto done;
1086 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1087 if (len == -1)
1088 goto done;
1090 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1091 if (len == -1)
1092 goto done;
1094 i = htonl (crypto->save.hdr.datalen);
1095 len = write (fd, &i, sizeof(i));
1096 if (len == -1)
1097 goto done;
1098 #endif
1100 done:
1101 return len == -1 ? gpg_error_from_errno (errno) : 0;
1104 /* Write the data structures to disk. */
1105 gpg_error_t
1106 write_file (struct crypto_s *crypto, const char *filename,
1107 void *data, size_t data_len, void *sexp, size_t sexp_len,
1108 void *pubkey, void *sigpkey)
1110 char tmp[FILENAME_MAX] = { 0 };
1111 mode_t mode = 0;
1112 struct stat st;
1113 int fd;
1114 gpg_error_t rc = 0;
1116 if (filename)
1118 mode_t mask;
1120 if (lstat (filename, &st) == 0)
1122 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1124 if (!(mode & S_IWUSR))
1125 return GPG_ERR_EACCES;
1127 else if (errno != ENOENT)
1128 return gpg_error_from_errno (errno);
1130 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1131 mask = umask (600);
1132 fd = mkstemp (tmp);
1133 if (fd == -1)
1135 rc = gpg_error_from_errno (errno);
1136 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1137 umask (mask);
1138 return rc;
1141 umask (mask);
1143 else
1145 // xml_import() or convert_file() from command line.
1146 fd = STDOUT_FILENO;
1149 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1150 crypto->save.hdr.version = VERSION_HEX;
1151 rc = write_header (crypto, fd);
1152 if (!rc)
1154 size_t len;
1156 if (crypto->save.hdr.flags & PWMD_FLAG_PKI)
1158 unsigned char grip[20];
1160 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1161 len = write (fd, grip, sizeof (grip));
1162 if (len == sizeof (grip))
1164 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1165 len = write (fd, grip, sizeof (grip));
1166 if (len == sizeof (grip))
1168 len = write (fd, data, data_len);
1169 if (len == data_len)
1171 len = write (fd, sexp, sexp_len);
1172 if (len != sexp_len)
1173 rc = gpg_error_from_errno (errno);
1175 else
1176 rc = gpg_error_from_errno (errno);
1179 else
1180 rc = gpg_error_from_errno (errno);
1182 else
1184 len = write (fd, data, data_len);
1185 if (len != data_len)
1186 rc = gpg_error_from_errno (errno);
1190 if (!rc)
1192 if (fsync (fd) != -1)
1194 if (filename && close (fd) != -1)
1197 if (mode && config_get_boolean (filename, "backup"))
1199 char tmp2[FILENAME_MAX];
1201 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1202 if (rename (filename, tmp2) == -1)
1203 rc = gpg_error_from_errno (errno);
1206 else if (filename)
1207 rc = gpg_error_from_errno (errno);
1209 else
1210 rc = gpg_error_from_errno (errno);
1213 if (!rc)
1215 if (filename && rename (tmp, filename) != -1)
1217 if (filename && mode)
1218 chmod (filename, mode);
1221 else
1222 rc = gpg_error_from_errno (errno);
1225 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1226 return rc;
1229 gpg_error_t
1230 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1231 size_t keylen, void **result, size_t *rlen)
1233 gpg_error_t rc;
1234 void *tmp;
1236 /* Be sure the algorithm is available. */
1237 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1238 if (rc)
1239 return rc;
1241 /* Always allocate enough for a 256-bit key although the algorithms
1242 themselves may use less. Fixes SAVE --cipher with a different
1243 keylen than the previously saved cipher when cached. */
1244 *rlen = 32;
1245 tmp = xmalloc (*rlen);
1246 if (!tmp)
1247 return GPG_ERR_ENOMEM;
1249 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1250 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1251 if (!rc)
1252 *result = tmp;
1253 else
1254 xfree (tmp);
1256 return rc;
1259 /* The PASSWD command when not using gpg-agent. */
1260 gpg_error_t
1261 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1262 struct crypto_s **rcrypto, int no_passphrase)
1264 unsigned char *key = NULL;
1265 size_t keylen = 0;
1266 struct crypto_s *crypto = NULL;
1267 gpg_error_t rc = init_client_crypto (&crypto);
1268 int cached;
1270 if (rc)
1271 return rc;
1273 crypto->client_ctx = ctx;
1274 rc = read_data_file (filename, crypto);
1275 if (rc)
1277 cleanup_crypto (&crypto);
1278 return rc;
1281 rc = try_decrypt (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1282 if (rc)
1284 cleanup_crypto (&crypto);
1285 return rc;
1288 gcry_free (key);
1289 key = NULL;
1291 if (!rc)
1293 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1295 if (!no_passphrase)
1296 crypto->save.hdr.flags &= ~PWMD_FLAG_NO_PASSPHRASE;
1298 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1299 crypto->plaintext_len, crypto->filename, NULL,
1300 (void **)&key, &keylen, 0, 0, no_passphrase);
1303 if (!rc)
1305 rc = save_common (filename, crypto, crypto->plaintext,
1306 crypto->plaintext_len, key, keylen, &cached, 1);
1307 if (!rc)
1308 *rcrypto = crypto;
1311 if (rc)
1313 gcry_free (key);
1314 cleanup_crypto (&crypto);
1316 else if (!cached)
1317 send_status_all (STATUS_CACHE, NULL);
1319 return rc;
1322 gpg_error_t
1323 save_common (const char *filename, struct crypto_s *crypto,
1324 const unsigned char *data, size_t datalen,
1325 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1327 struct cache_data_s *cdata;
1328 gpg_error_t rc = 0;
1329 gcry_sexp_t pubkey = NULL;
1330 gcry_sexp_t sigkey = NULL;
1332 /* This is safe since it is a (somewhat) fast operation. */
1333 cache_lock ();
1334 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1335 cdata = cache_get_data_filename (filename);
1336 *cached = cdata != NULL;
1338 if (!cdata)
1339 cdata = xcalloc (1, sizeof (struct cache_data_s));
1341 #ifdef WITH_AGENT
1342 if (use_agent && !no_agent)
1344 rc = gcry_sexp_build (&pubkey, NULL, "%S", crypto->pkey_sexp);
1345 if (!rc)
1346 rc = gcry_sexp_build (&sigkey, NULL, "%S", crypto->sigpkey_sexp);
1348 #endif
1350 if (!rc)
1352 gcry_free (cdata->doc);
1353 cdata->doc = NULL;
1354 gcry_free (cdata->key);
1355 cdata->key = (unsigned char *)key;
1356 cdata->keylen = keylen;
1357 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1358 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1359 &cache_blocksize, 0);
1362 if (!rc)
1364 unsigned char md5file[16];
1366 /* Update in case of any --keygrip argument */
1367 if (cdata->pubkey)
1368 gcry_sexp_release (cdata->pubkey);
1370 if (cdata->sigkey)
1371 gcry_sexp_release (cdata->sigkey);
1373 cdata->pubkey = pubkey;
1374 cdata->sigkey = sigkey;
1375 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1376 rc = cache_set_data (md5file, cdata, crypto->grip);
1378 else
1380 if (pubkey)
1381 gcry_sexp_release (pubkey);
1383 if (sigkey)
1384 gcry_sexp_release (sigkey);
1387 pthread_cleanup_pop (1); // mutex unlock
1388 return rc;
1391 gpg_error_t
1392 getpin_common (assuan_context_t ctx, const char *filename, int which,
1393 char **rkey, size_t *rkeylen)
1395 gpg_error_t rc;
1396 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1397 struct pinentry_s *pin = pinentry_init (filename);
1399 if (!pin)
1400 return GPG_ERR_ENOMEM;
1402 if (client)
1403 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1405 rc = pinentry_lock (ctx, pin);
1406 if (!rc)
1407 rc = pinentry_getpin (pin, rkey, which);
1409 pinentry_deinit (pin);
1410 if (rc)
1411 return rc;
1413 *rkeylen = strlen (*rkey);
1414 if (!(*rkeylen))
1415 (*rkeylen)++;
1417 return rc;
1420 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1421 * both call xfree(). */
1422 gpg_error_t
1423 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1424 unsigned char **result, size_t *rlen)
1426 gpg_error_t rc;
1428 assuan_begin_confidential (ctx);
1429 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1430 assuan_end_confidential (ctx);
1431 return rc;
1434 /* Common to both PKI and non-PKI files. */
1435 gpg_error_t
1436 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1437 const char *filename, char **rkey, size_t *rkeylen)
1439 char *key = NULL;
1440 size_t keylen = 0;
1441 gpg_error_t rc = read_data_file (filename, crypto);
1442 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1443 void *salted_key = NULL;
1444 size_t keysize = 0;
1446 if (rc)
1448 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1449 return rc;
1452 key = config_get_string (filename, "passphrase");
1453 if (key)
1455 log_write (_("Trying the passphrase specified in config ..."));
1456 keylen = strlen (key);
1459 if (!key)
1461 key = config_get_string (filename, "passphrase_file");
1462 if (key)
1464 char *tmp = expand_homedir (key);
1465 int fd;
1466 struct stat st;
1468 xfree (key);
1469 key = tmp;
1470 log_write (_("Trying the passphrase using file '%s' ..."), key);
1471 fd = open (key, O_RDONLY);
1472 if (fd == -1)
1474 rc = gpg_error_from_errno (errno);
1475 log_write ("%s: %s", key, pwmd_strerror (rc));
1476 xfree (key);
1477 return rc;
1480 if (stat (key, &st) == -1)
1482 rc = gpg_error_from_errno (errno);
1483 log_write ("%s: %s", key, pwmd_strerror (rc));
1484 xfree (key);
1485 close(fd);
1486 return rc;
1489 xfree (key);
1490 key = xmalloc (st.st_size);
1491 if (key)
1493 if (read (fd, key, st.st_size) != st.st_size)
1495 log_write ("short read() count");
1496 rc = GPG_ERR_TOO_SHORT;
1499 else
1500 rc = GPG_ERR_ENOMEM;
1502 close (fd);
1504 if (rc)
1506 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1507 xfree (key);
1508 return rc;
1511 keylen = st.st_size;
1512 if (!keylen)
1514 tmp = xmalloc (1);
1515 *tmp = 0;
1516 xfree (key);
1517 key = tmp;
1518 keylen++;
1523 if (!key && !IS_PKI (crypto) && inquire
1524 && !(crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
1526 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1527 &keylen);
1528 if (!rc)
1529 if (!keylen)
1530 keylen++;
1532 else if (!key && !IS_PKI (crypto))
1534 if (crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
1536 keylen = 1;
1537 key = gcry_malloc (keylen);
1538 memset (key, 0, keylen);
1540 else
1541 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1543 else if (key && IS_PKI (crypto))
1545 #ifdef WITH_AGENT
1546 rc = set_agent_passphrase (crypto, key, keylen);
1547 #else
1548 rc = GPG_ERR_NOT_IMPLEMENTED;
1549 #endif
1551 else if (!key && IS_PKI (crypto))
1553 #ifdef WITH_AGENT
1554 /* The cache entry has been cleared in save_command(). Will prompt. */
1555 rc = set_pinentry_mode (crypto->agent, inquire ? "loopback" : "ask");
1556 #else
1557 rc = GPG_ERR_NOT_IMPLEMENTED;
1558 #endif
1561 if (rc)
1563 xfree (key);
1564 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1565 return rc;
1568 if (key && !IS_PKI (crypto))
1570 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1571 keylen, &salted_key, &keysize);
1572 xfree (key);
1573 key = (char *)salted_key;
1574 keylen = keysize;
1575 if (rc)
1577 xfree (salted_key);
1578 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1579 return rc;
1583 xfree (crypto->filename);
1584 crypto->filename = str_dup (filename);
1585 rc = decrypt_data (ctx, crypto, (unsigned char *)key, keylen);
1586 if (rc)
1588 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1589 xfree (key);
1591 else
1593 *rkey = key;
1594 *rkeylen = keylen;
1597 return rc;