Fix crash when/if gpg-agent dies.
[pwmd.git] / src / crypto.c
blob8a62f5909db591f27dc1ddc082e6848a2fe8e0c6
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
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>
30 #ifdef WITH_LIBACL
31 #include <sys/acl.h>
32 #endif
34 #include "pwmd-error.h"
35 #include "util-misc.h"
36 #include "common.h"
37 #include "rcfile.h"
38 #include "pinentry.h"
39 #include "crypto.h"
40 #include "cache.h"
41 #include "mem.h"
42 #include "util-string.h"
44 static uint8_t pwmd_magic[5] = { '\177', 'P', 'W', 'M', 'D' };
46 void
47 set_header_defaults (file_header_t * hdr)
49 char *s = config_get_string (NULL, "cipher");
50 int flags = cipher_string_to_cipher (s);
52 xfree (s);
53 memset (hdr, 0, sizeof (file_header_t));
54 memcpy (hdr->magic, pwmd_magic, sizeof (hdr->magic));
55 if (flags == -1)
56 log_write (_
57 ("Invalid 'cipher' in configuration file. Using a default of aes256."));
58 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
59 hdr->version = VERSION_HEX;
61 #ifdef WITH_AGENT
62 if (use_agent)
63 hdr->flags |= PWMD_FLAG_PKCS;
64 #endif
67 gpg_error_t
68 read_data_header (const char *filename, file_header_t * rhdr,
69 struct stat *rst, int *rfd)
71 gpg_error_t rc = 0;
72 size_t len;
73 struct stat st;
74 file_header_t hdr;
75 int fd;
77 if (lstat (filename, &st) == -1)
78 return gpg_error_from_syserror ();
80 if (!S_ISREG (st.st_mode))
81 return GPG_ERR_ENOANO;
83 fd = open (filename, O_RDONLY);
84 if (fd == -1)
85 return gpg_error_from_syserror ();
87 len = read (fd, &hdr, sizeof (file_header_t));
88 if (len != sizeof (file_header_t))
89 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
91 if (!rc && memcmp (hdr.magic, pwmd_magic, sizeof (hdr.magic)))
92 rc = GPG_ERR_BAD_DATA;
93 else if (hdr.version < 0x030000)
94 rc = GPG_ERR_UNKNOWN_VERSION;
96 if (rc)
97 close (fd);
98 else
100 if (rhdr)
101 *rhdr = hdr;
102 if (rst)
103 *rst = st;
104 if (rfd)
105 *rfd = fd;
106 else
107 close (fd);
110 return rc;
113 gpg_error_t
114 read_data_file (const char *filename, struct crypto_s * crypto)
116 int fd;
117 gpg_error_t rc = 0;
118 size_t len, rlen;
119 char *buf = NULL;
120 struct stat st;
122 cleanup_crypto_stage1 (crypto);
123 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
124 if (rc)
125 return rc;
127 crypto->ciphertext_len = crypto->hdr.datalen;
128 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
129 if (!crypto->ciphertext)
131 rc = GPG_ERR_ENOMEM;
132 goto fail;
135 if (crypto->hdr.flags & PWMD_FLAG_PKCS)
137 rlen = read (fd, crypto->grip, 20);
138 if (rlen != 20)
140 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
141 goto fail;
144 rlen = read (fd, crypto->sign_grip, 20);
145 if (rlen != 20)
147 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
148 goto fail;
152 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
153 if (len != crypto->hdr.datalen)
155 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
156 goto fail;
159 if (!(crypto->hdr.flags & PWMD_FLAG_PKCS))
160 goto fail;
162 #ifndef WITH_AGENT
163 rc = GPG_ERR_NOT_IMPLEMENTED;
164 goto fail;
165 #else
166 if (!use_agent)
167 return GPG_ERR_NOT_IMPLEMENTED;
169 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
170 buf = xmalloc (len);
171 if (!buf)
173 rc = GPG_ERR_ENOMEM;
174 goto fail;
177 rlen = read (fd, buf, len);
178 if (rlen != len)
180 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
181 goto fail;
184 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
185 if (rc)
186 goto fail;
188 if (crypto->pkey_sexp)
189 gcry_sexp_release (crypto->pkey_sexp);
191 if (crypto->sigpkey_sexp)
192 gcry_sexp_release (crypto->sigpkey_sexp);
194 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
195 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
196 if (!rc)
197 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
198 #endif
200 fail:
201 close (fd);
202 xfree (buf);
203 return rc;
206 #define CRYPTO_BLOCKSIZE(c) (blocksize * 1024)
209 * Useful for a large amount of data. Rather than doing all of the data in one
210 * iteration do it in chunks. This lets the command be cancelable rather than
211 * waiting for it to complete.
213 static gpg_error_t
214 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
215 size_t insize, size_t blocksize, status_msg_t which)
217 gpg_error_t rc = 0;
218 off_t len = CRYPTO_BLOCKSIZE (blocksize);
219 void *p = gcry_malloc (len);
220 off_t total = 0;
221 unsigned char *inbuf2;
223 if (!p)
224 return GPG_ERR_ENOMEM;
226 if (insize < CRYPTO_BLOCKSIZE (blocksize))
227 len = insize;
229 pthread_cleanup_push (gcry_free, p);
231 for (;;)
233 inbuf2 = inbuf + total;
234 unsigned char *tmp;
236 if (len + total > insize)
237 len = blocksize;
239 if (which == STATUS_ENCRYPT)
240 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
241 else
242 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
244 if (rc)
245 break;
247 tmp = inbuf + total;
248 memmove (tmp, p, len);
249 total += len;
250 if (total >= insize)
251 break;
253 #ifdef HAVE_PTHREAD_TESTCANCEL
254 pthread_testcancel ();
255 #endif
258 pthread_cleanup_pop (1);
259 return rc;
262 static void
263 cleanup_cipher (void *arg)
265 gcry_cipher_close ((gcry_cipher_hd_t) arg);
268 gpg_error_t
269 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
270 unsigned char *salted_key, size_t skeylen)
272 gpg_error_t rc = 0;
273 unsigned char *key = salted_key;
274 gcry_cipher_hd_t h = NULL;
275 size_t blocksize, keysize = 0;
276 int algo = cipher_to_gcrypt (crypto->hdr.flags);
277 void *outbuf = NULL;
278 uint64_t n = crypto->hdr.iterations;
279 long progress = 0;
280 #ifdef WITH_AGENT
281 size_t keylen = skeylen;
282 gcry_sexp_t sig_sexp;
284 if (crypto->hdr.flags & PWMD_FLAG_PKCS)
286 rc = agent_extract_key (crypto, &key, &keylen);
287 if (rc)
288 return rc;
290 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
291 if (!sig_sexp)
293 gcry_free (key);
294 return GPG_ERR_BAD_DATA;
297 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
298 crypto->ciphertext_len);
299 gcry_sexp_release (sig_sexp);
301 #endif
303 if (!rc)
305 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
306 if (!rc)
308 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
309 &keysize);
310 if (!rc)
312 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
313 &blocksize);
314 if (!rc)
316 rc = gcry_cipher_setiv (h, crypto->hdr.iv,
317 sizeof (crypto->hdr.iv));
318 if (!rc)
320 rc = gcry_cipher_setkey (h, key, keysize);
327 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
329 if (!rc)
331 outbuf = gcry_malloc (crypto->hdr.datalen);
332 if (!outbuf)
333 rc = GPG_ERR_ENOMEM;
336 pthread_cleanup_push (gcry_free, outbuf);
337 #ifdef WITH_AGENT
338 pthread_cleanup_push (gcry_free, key);
339 #endif
341 if (!rc)
343 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
344 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
345 STATUS_DECRYPT);
346 if (!rc)
348 key[0] ^= 1;
349 rc = gcry_cipher_setkey (h, key, keysize);
353 if (!rc)
355 progress = config_get_long (NULL, "cipher_progress");
356 if (progress == -1)
357 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
360 if (!rc && ctx && crypto->hdr.iterations)
361 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", 0,
362 crypto->hdr.iterations);
364 for (n = 0; !rc && n < crypto->hdr.iterations; n++)
366 if (ctx && !(n % progress))
368 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
369 crypto->hdr.iterations);
370 if (rc)
371 break;
374 rc = gcry_cipher_setiv (h, crypto->hdr.iv, sizeof (crypto->hdr.iv));
375 if (rc)
376 break;
378 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
379 STATUS_DECRYPT);
382 if (!rc && ctx && crypto->hdr.iterations)
383 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
384 crypto->hdr.iterations);
386 #ifdef WITH_AGENT
387 pthread_cleanup_pop (0);
388 if (crypto->hdr.flags & PWMD_FLAG_PKCS)
389 gcry_free (key);
390 else if (key)
391 key[0] ^= 1;
392 #else
393 key[0] ^= 1;
394 #endif
395 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
396 pthread_cleanup_pop (1); /* cipher */
397 if (!rc)
399 char buf[] = "<?xml ";
401 if (memcmp (outbuf, buf, sizeof(buf)-1))
403 gcry_free (outbuf);
404 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
407 crypto->plaintext = outbuf;
408 crypto->plaintext_len = crypto->hdr.datalen;
411 return rc;
414 gpg_error_t
415 decrypt_xml (struct crypto_s * crypto, const void *data, size_t len)
417 gcry_cipher_hd_t h = NULL;
418 gpg_error_t rc;
420 rc = gcry_cipher_open (&h, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
421 if (rc)
422 return rc;
424 gcry_free (crypto->plaintext);
425 crypto->plaintext = gcry_malloc (len);
426 if (!crypto->plaintext)
428 rc = GPG_ERR_ENOMEM;
429 goto done;
432 rc = gcry_cipher_setiv (h, cache_iv, cache_blocksize);
433 if (rc)
434 goto done;
436 rc = gcry_cipher_setkey (h, cache_key, cache_keysize);
437 if (rc)
438 goto done;
440 rc = gcry_cipher_decrypt (h, crypto->plaintext, len, data, len);
441 if (rc || strncmp (crypto->plaintext, "<?xml ", 6))
443 if (!rc)
444 rc = GPG_ERR_BAD_DATA;
446 gcry_free (crypto->plaintext);
447 crypto->plaintext = NULL;
450 crypto->plaintext_len = len;
452 done:
453 if (h)
454 gcry_cipher_close (h);
456 return rc;
459 gpg_error_t
460 encrypt_xml (assuan_context_t ctx, void *key, size_t keylen,
461 int algo, const void *xml, size_t len, void * *result,
462 size_t *result_len, unsigned char **iv, size_t * iv_len,
463 uint64_t iter)
465 gpg_error_t rc;
466 gcry_cipher_hd_t h;
467 size_t blocksize, keysize;
468 void *inbuf = NULL;
469 size_t olen = len;
470 uint64_t n = 0;
471 long progress;
472 unsigned char *tmpkey = NULL;
473 int free_iv = *(iv_len) == 0;
475 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
476 if (rc)
477 return rc;
479 pthread_cleanup_push (cleanup_cipher, h);
480 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
481 if (!rc)
482 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL, &blocksize);
484 if (!rc && *(iv_len) == 0)
486 *(iv) = xmalloc (blocksize);
487 if (!*(iv))
488 rc = GPG_ERR_ENOMEM;
490 gcry_create_nonce (*(iv), blocksize);
493 pthread_cleanup_push (xfree, *(iv_len) == 0 ? *(iv) : NULL);
494 if (!rc)
496 *iv_len = blocksize;
497 tmpkey = gcry_malloc (keysize);
498 if (!tmpkey)
499 rc = GPG_ERR_ENOMEM;
502 pthread_cleanup_push (gcry_free, tmpkey);
504 if (!rc)
506 memcpy (tmpkey, key, keysize);
507 tmpkey[0] ^= 1;
508 rc = gcry_cipher_setkey (h, tmpkey, keysize);
509 if (!rc)
511 if (len % blocksize)
512 len += blocksize - (len % blocksize);
516 if (!rc)
518 inbuf = gcry_malloc (len);
519 if (!inbuf)
520 rc = GPG_ERR_ENOMEM;
523 pthread_cleanup_push (gcry_free, inbuf);
525 if (!rc)
527 memset (inbuf, 0, len);
528 memcpy (inbuf, xml, olen);
529 progress = config_get_long (NULL, "cipher_progress");
530 if (progress == -1)
531 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
533 if (!rc && ctx && iter)
534 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", 0, iter);
536 for (n = 0; !rc && n < iter; n++)
538 if (ctx && !(n % progress))
540 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
541 if (rc)
542 break;
545 rc = gcry_cipher_setiv (h, *(iv), blocksize);
546 if (rc)
547 break;
549 rc = iterate_crypto_once (h, inbuf, len, blocksize, STATUS_ENCRYPT);
553 if (!rc && ctx && iter)
554 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
556 if (!rc)
558 /* Do at least one iteration. */
559 rc = gcry_cipher_setiv (h, *(iv), blocksize);
560 if (!rc)
562 rc = gcry_cipher_setkey (h, key, keysize);
563 if (!rc)
564 rc = iterate_crypto_once (h, inbuf, len, blocksize,
565 STATUS_ENCRYPT);
569 pthread_cleanup_pop (rc ? 1 : 0); /* inbuf */
570 pthread_cleanup_pop (1); /* tmpkey */
571 pthread_cleanup_pop (rc && free_iv ? 1 : 0); /* iv */
572 pthread_cleanup_pop (1); /* cipher */
573 *result = rc ? NULL : inbuf;
574 *result_len = len;
575 return rc;
578 void
579 cleanup_save (struct save_s *save)
581 if (!save)
582 return;
584 #ifdef WITH_AGENT
585 if (save->pkey)
586 gcry_sexp_release (save->pkey);
588 if (save->sigpkey)
589 gcry_sexp_release (save->sigpkey);
590 #endif
592 memset (save, 0, sizeof (struct save_s));
595 /* Keep the agent ctx to retain pinentry options which will be freed in
596 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
597 void
598 cleanup_crypto_stage1 (struct crypto_s *cr)
600 if (!cr)
601 return;
603 cleanup_save (&cr->save);
605 #ifdef WITH_AGENT
606 if (cr->ciphertext_sexp)
607 gcry_sexp_release (cr->ciphertext_sexp);
609 cr->ciphertext_sexp = NULL;
610 #endif
612 gcry_free (cr->plaintext);
613 xfree (cr->ciphertext);
614 xfree (cr->filename);
615 cr->filename = NULL;
616 cr->ciphertext = NULL;
617 cr->ciphertext_len = 0;
618 cr->plaintext = NULL;
619 cr->plaintext_len = 0;
622 void
623 cleanup_crypto_stage2 (struct crypto_s *cr)
625 if (!cr)
626 return;
628 cleanup_crypto_stage1 (cr);
629 set_header_defaults (&cr->hdr);
632 void
633 cleanup_crypto (struct crypto_s **c)
635 struct crypto_s *cr = *c;
637 if (!cr)
638 return;
640 cleanup_crypto_stage2 (cr);
642 #ifdef WITH_AGENT
643 if (cr->pkey_sexp)
644 gcry_sexp_release (cr->pkey_sexp);
646 if (cr->sigpkey_sexp)
647 gcry_sexp_release (cr->sigpkey_sexp);
649 if (cr->agent)
650 cleanup_agent (cr->agent);
651 #endif
653 xfree (cr);
654 *c = NULL;
657 gpg_error_t
658 init_client_crypto (struct crypto_s **crypto)
660 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
661 gpg_error_t rc;
663 if (!new)
665 rc = GPG_ERR_ENOMEM;
666 return rc;
669 #ifdef WITH_AGENT
670 if (use_agent)
672 rc = agent_init (&new->agent);
673 if (!rc)
675 rc = send_agent_common_options (new->agent);
676 if (!rc)
677 rc = agent_set_pinentry_options (new->agent);
680 if (rc)
682 cleanup_agent (new->agent);
683 xfree (new);
684 return rc;
687 #endif
689 set_header_defaults (&new->hdr);
690 *crypto = new;
691 return 0;
694 gpg_error_t
695 export_common (assuan_context_t ctx, int inquire, struct crypto_s * crypto,
696 const void *data, size_t datalen, const char *outfile,
697 const char *keyfile, void **rkey, size_t *rkeylen,
698 int use_cache, int force)
700 gpg_error_t rc = 0;
701 void *enc_xml = NULL;
702 size_t enc_xml_len = 0;
703 unsigned char *iv = NULL;
704 size_t iv_len = 0;
705 int algo = cipher_to_gcrypt (crypto->save.hdr.flags);
706 void *key = NULL, *salted_key = NULL;
707 size_t keysize, keylen;
708 int cached = 0;
710 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
711 if (rc)
712 return rc;
714 if (keyfile)
716 int fd;
717 unsigned char *buf;
718 size_t len;
719 struct stat st;
721 if (stat (keyfile, &st) == -1)
722 return gpg_error_from_syserror ();
724 buf = gcry_malloc (st.st_size);
725 if (!buf)
726 return GPG_ERR_ENOMEM;
728 fd = open (keyfile, O_RDONLY);
729 if (fd == -1)
730 rc = gpg_error_from_syserror ();
731 else
733 len = read (fd, buf, st.st_size);
734 if (len != st.st_size)
735 rc = GPG_ERR_TOO_SHORT;
738 if (fd != -1)
739 close (fd);
741 key = buf;
742 keylen = st.st_size;
743 log_write (_("Using passphrase obtained from file '%s'"), keyfile);
745 if (!keylen)
747 char *tmp;
749 gcry_free (key);
750 tmp = gcry_malloc (1);
751 *tmp = 0;
752 key = tmp;
753 keylen++;
756 else
758 if (use_cache)
760 cache_lock ();
761 cached = cache_iscached (outfile, NULL) == 0;
762 if (cached)
764 struct cache_data_s *cdata = cache_get_data_filename (outfile);
766 salted_key = gcry_malloc (cdata->keylen);
767 if (salted_key)
769 memcpy (salted_key, cdata->key, cdata->keylen);
770 keysize = cdata->keylen;
772 else
773 rc = GPG_ERR_ENOMEM;
776 cache_unlock ();
779 if (!rc && !cached)
781 if (force) // SAVE
783 struct crypto_s *tmp = NULL;
784 gpg_error_t rc = init_client_crypto (&tmp);
786 if (!rc)
788 rc = read_data_file (outfile, tmp);
789 if (!rc)
791 rc = decrypt_common (ctx, inquire, tmp, outfile,
792 (char **)&key, &keylen);
793 if (rc)
794 gcry_free (key);
798 cleanup_crypto (&tmp);
799 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
800 use_cache = 0;
801 else if (rc)
802 return rc;
805 if (!use_cache) // PASSWD or new file
807 gcry_free (key);
808 if (inquire)
810 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
811 (unsigned char **)&key, &keylen);
813 else
815 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
816 (char **)&key, &keylen);
819 if (rc)
820 return rc;
822 else
824 salted_key = key;
825 keysize = keylen;
826 cached = 1;
831 if (!rc && !cached)
833 rc = hash_key (algo, crypto->save.hdr.salt,
834 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
835 &keysize);
836 gcry_free (key);
839 if (!rc)
840 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
841 &enc_xml, &enc_xml_len, &iv, &iv_len,
842 crypto->save.hdr.iterations);
844 if (!rc)
846 memcpy (crypto->save.hdr.iv, iv, iv_len);
847 xfree (iv);
848 crypto->save.hdr.datalen = enc_xml_len;
849 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
850 NULL);
851 gcry_free (enc_xml);
852 if (!rc)
854 *rkey = salted_key;
855 *rkeylen = keysize;
856 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
860 if (rc)
861 gcry_free (salted_key);
863 return rc;
866 #ifdef WITH_LIBACL
867 static void
868 cleanup_acl (void *arg)
870 acl_t acl = *(acl_t *) arg;
872 if (acl)
873 acl_free (acl);
875 #endif
877 gpg_error_t
878 write_file (struct crypto_s *crypto, const char *filename,
879 void *data, size_t data_len, void *sexp, size_t sexp_len,
880 void *pubkey, void *sigpkey)
882 char tmp[FILENAME_MAX] = { 0 };
883 mode_t mode = 0;
884 struct stat st;
885 int fd;
886 gpg_error_t rc = 0;
887 size_t len;
888 #ifdef WITH_LIBACL
889 acl_t acl = NULL;
890 #endif
892 if (filename)
894 if (lstat (filename, &st) == 0)
896 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
898 if (!(mode & S_IWUSR))
899 return GPG_ERR_EACCES;
901 else if (errno != ENOENT)
902 return gpg_error_from_syserror ();
904 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
905 fd = mkstemp (tmp);
906 if (fd == -1)
908 rc = gpg_error_from_syserror ();
909 log_write ("%s: %s", tmp, pwmd_strerror (rc));
910 return rc;
913 else
915 // xml_import() or convert_file() from command line.
916 fd = STDOUT_FILENO;
919 pthread_cleanup_push (cleanup_unlink_cb, tmp);
920 crypto->save.hdr.version = VERSION_HEX;
921 len = write (fd, &crypto->save.hdr, sizeof (file_header_t));
922 if (len == sizeof (file_header_t))
924 if (crypto->save.hdr.flags & PWMD_FLAG_PKCS)
926 unsigned char grip[20];
928 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
929 len = write (fd, grip, sizeof (grip));
930 if (len == sizeof (grip))
932 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
933 len = write (fd, grip, sizeof (grip));
934 if (len == sizeof (grip))
936 len = write (fd, data, data_len);
937 if (len == data_len)
939 len = write (fd, sexp, sexp_len);
940 if (len != sexp_len)
941 rc = gpg_error_from_syserror ();
943 else
944 rc = gpg_error_from_syserror ();
947 else
948 rc = gpg_error_from_syserror ();
950 else
952 len = write (fd, data, data_len);
953 if (len != data_len)
954 rc = gpg_error_from_syserror ();
957 else
958 rc = gpg_error_from_syserror ();
960 #ifdef WITH_LIBACL
961 pthread_cleanup_push (cleanup_acl, &acl);
962 #endif
963 if (!rc)
965 if (fsync (fd) != -1)
967 if (filename && close (fd) != -1)
969 #ifdef WITH_LIBACL
970 acl = acl_get_file (filename, ACL_TYPE_ACCESS);
971 if (!acl && errno == ENOENT)
972 acl = acl_get_file (".", ACL_TYPE_DEFAULT);
973 if (!acl)
974 log_write ("ACL: %s: %s", filename,
975 pwmd_strerror (gpg_error_from_syserror ()));
976 #endif
978 if (mode && config_get_boolean (filename, "backup"))
980 char tmp2[FILENAME_MAX];
982 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
983 if (rename (filename, tmp2) == -1)
984 rc = gpg_error_from_syserror ();
987 else if (filename)
988 rc = gpg_error_from_syserror ();
990 else
991 rc = gpg_error_from_syserror ();
994 if (!rc)
996 if (filename && rename (tmp, filename) != -1)
998 tmp[0] = 0;
999 if (filename && mode)
1000 chmod (filename, mode);
1002 #ifdef WITH_LIBACL
1003 if (acl && acl_set_file (filename, ACL_TYPE_ACCESS, acl))
1004 log_write ("ACL: %s: %s", filename,
1005 pwmd_strerror (gpg_error_from_syserror ()));
1006 #endif
1008 else
1009 rc = gpg_error_from_syserror ();
1012 #ifdef WITH_LIBACL
1013 pthread_cleanup_pop (1);
1014 #endif
1015 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1016 return rc;
1019 gpg_error_t
1020 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1021 size_t keylen, void **result, size_t *rlen)
1023 gpg_error_t rc;
1024 void *tmp;
1026 /* Be sure the algorithm is available. */
1027 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1028 if (rc)
1029 return rc;
1031 /* Always allocate enough for a 256-bit key although the algorithms
1032 themselves may use less. Fixes SAVE --cipher with a different
1033 keylen than the previously saved cipher when cached. */
1034 *rlen = 32;
1035 tmp = xmalloc (*rlen);
1036 if (!tmp)
1037 return GPG_ERR_ENOMEM;
1039 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1040 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1041 if (!rc)
1042 *result = tmp;
1043 else
1044 xfree (tmp);
1046 return rc;
1049 gpg_error_t
1050 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1051 struct crypto_s **rcrypto)
1053 unsigned char *key = NULL;
1054 size_t keylen = 0;
1055 struct crypto_s *crypto = NULL;
1056 gpg_error_t rc = init_client_crypto (&crypto);
1058 if (rc)
1059 return rc;
1061 crypto->client_ctx = ctx;
1062 rc = read_data_file (filename, crypto);
1063 if (rc)
1065 cleanup_crypto (&crypto);
1066 return rc;
1069 rc = decrypt_common (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1070 gcry_free (key);
1071 key = NULL;
1072 if (rc)
1074 cleanup_crypto (&crypto);
1075 return rc;
1078 if (!rc)
1080 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1081 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1082 crypto->plaintext_len, crypto->filename, NULL,
1083 (void **)&key, &keylen, 0, 0);
1086 if (!rc)
1088 int cached;
1090 rc = save_common (filename, crypto, crypto->plaintext,
1091 crypto->plaintext_len, key, keylen, &cached, 1);
1092 if (!rc)
1093 *rcrypto = crypto;
1096 if (rc)
1098 gcry_free (key);
1099 cleanup_crypto (&crypto);
1102 return rc;
1105 // FIXME gcry_sexp_t is updated in cdata. make a temp var in case of failure.
1106 gpg_error_t
1107 save_common (const char *filename, struct crypto_s *crypto,
1108 const unsigned char *data, size_t datalen,
1109 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1111 struct cache_data_s *cdata;
1112 gpg_error_t rc;
1114 /* This is safe since it is a fast operation. */
1115 cache_lock ();
1116 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1117 cdata = cache_get_data_filename (filename);
1118 *cached = cdata != NULL;
1120 if (!cdata)
1121 cdata = xcalloc (1, sizeof (struct cache_data_s));
1123 #ifdef WITH_AGENT
1124 if (use_agent && !no_agent)
1126 /* Update in case of any --keygrip argument */
1127 if (cdata->pubkey)
1128 gcry_sexp_release (cdata->pubkey);
1130 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1131 crypto->pkey_sexp);
1133 if (cdata->sigkey)
1134 gcry_sexp_release (cdata->sigkey);
1136 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1137 crypto->sigpkey_sexp);
1139 #endif
1141 gcry_free (cdata->doc);
1142 cdata->doc = NULL;
1143 cdata->key = (unsigned char *)key;
1144 cdata->keylen = keylen;
1145 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1146 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1147 &cache_blocksize, 0);
1148 if (!rc)
1150 unsigned char md5file[16];
1152 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1153 rc = cache_set_data (md5file, cdata, crypto->grip);
1156 pthread_cleanup_pop (1); // mutex unlock
1157 return rc;
1160 gpg_error_t
1161 getpin_common (assuan_context_t ctx, const char *filename, int which,
1162 char **rkey, size_t *rkeylen)
1164 gpg_error_t rc;
1165 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1166 struct pinentry_s *pin = pinentry_init (filename);
1168 if (!pin)
1169 return GPG_ERR_ENOMEM;
1171 if (client)
1172 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1174 rc = pinentry_lock (ctx, pin);
1175 if (!rc)
1176 rc = pinentry_getpin (pin, rkey, which);
1178 pinentry_deinit (pin);
1179 if (rc)
1180 return rc;
1182 *rkeylen = strlen (*rkey);
1183 if (!(*rkeylen))
1184 (*rkeylen)++;
1186 return rc;
1189 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1190 * both call xfree(). */
1191 gpg_error_t
1192 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1193 unsigned char **result, size_t *rlen)
1195 gpg_error_t rc;
1197 assuan_begin_confidential (ctx);
1198 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1199 assuan_end_confidential (ctx);
1200 return rc;
1203 gpg_error_t
1204 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1205 const char *filename, char **rkey, size_t *rkeylen)
1207 char *key = NULL;
1208 size_t keylen = 0;
1209 gpg_error_t rc = read_data_file (filename, crypto);
1210 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1211 void *salted_key = NULL;
1212 size_t keysize = 0;
1214 if (rc)
1216 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1217 return rc;
1220 key = config_get_string (filename, "passphrase");
1221 if (key)
1223 log_write (_("Trying the passphrase specified in config ..."));
1224 keylen = strlen (key);
1227 if (!key)
1229 key = config_get_string (filename, "passphrase_file");
1230 if (key)
1232 char *tmp = expand_homedir (key);
1233 int fd;
1234 struct stat st;
1236 xfree (key);
1237 key = tmp;
1238 log_write (_("Trying the passphrase using file '%s' ..."), key);
1239 fd = open (key, O_RDONLY);
1240 if (fd == -1)
1242 rc = gpg_error_from_syserror ();
1243 log_write ("%s: %s", key, pwmd_strerror (rc));
1244 xfree (key);
1245 return rc;
1248 stat (key, &st);
1249 xfree (key);
1250 key = xmalloc (st.st_size);
1251 if (key)
1253 if (read (fd, key, st.st_size) != st.st_size)
1255 log_write ("short read() count");
1256 rc = GPG_ERR_TOO_SHORT;
1259 else
1260 rc = GPG_ERR_ENOMEM;
1262 close (fd);
1264 if (rc)
1266 log_write ("%s", pwmd_strerror (rc));
1267 xfree (key);
1268 return rc;
1271 keylen = st.st_size;
1272 if (!keylen)
1274 tmp = xmalloc (1);
1275 *tmp = 0;
1276 xfree (key);
1277 key = tmp;
1278 keylen++;
1283 if (!key && !IS_PKCS (crypto) && inquire)
1285 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1286 &keylen);
1287 if (rc)
1289 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1290 return rc;
1293 if (!keylen)
1294 keylen++;
1296 else if (!key && !IS_PKCS (crypto))
1298 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1299 if (rc)
1301 log_write ("%s", pwmd_strerror (rc));
1302 return rc;
1305 #ifdef WITH_AGENT
1306 else if (key && IS_PKCS (crypto))
1308 rc = set_agent_passphrase (crypto, key, keylen);
1309 if (rc)
1311 xfree (key);
1312 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1313 return rc;
1316 #endif
1318 if (key && !IS_PKCS (crypto))
1320 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1321 keylen, &salted_key, &keysize);
1322 xfree (key);
1323 key = (char *)salted_key;
1324 keylen = keysize;
1325 if (rc)
1327 xfree (salted_key);
1328 return rc;
1332 xfree (crypto->filename);
1333 crypto->filename = str_dup (filename);
1334 rc = decrypt_data (NULL, crypto, (unsigned char *)key, keylen);
1335 if (rc)
1337 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1338 xfree (key);
1340 else
1342 *rkey = key;
1343 *rkeylen = keylen;
1346 return rc;