Require the key to decrypt before generating a new keypair.
[pwmd.git] / src / crypto.c
blob2b14f5e02a43ee5e8c8e24417ec6672e5c1eac76
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 void
49 set_header_defaults (file_header_t * hdr)
51 char *s = config_get_string (NULL, "cipher");
52 int flags = cipher_string_to_cipher (s);
54 xfree (s);
55 memset (hdr, 0, sizeof (file_header_t));
56 memcpy (hdr->magic, pwmd_magic, sizeof (hdr->magic));
57 if (flags == -1)
58 log_write (_
59 ("Invalid 'cipher' in configuration file. Using a default of aes256."));
60 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
61 hdr->version = VERSION_HEX;
63 #ifdef WITH_AGENT
64 if (use_agent)
65 hdr->flags |= PWMD_FLAG_PKI;
66 #endif
69 static gpg_error_t
70 read_header (file_header_t *hdr, int fd)
72 ssize_t len;
73 uint32_t i;
74 uint64_t n;
76 #ifdef WORDS_BIGENDIAN
77 len = read (fd, &hdr->magic, sizeof(hdr->magic));
78 if (len == -1)
79 goto done;
81 len = read (fd, &hdr->version, sizeof(hdr->version));
82 if (len == -1)
83 goto done;
85 len = read (fd, &hdr->iterations, sizeof(hdr->iterations));
86 if (len == -1)
87 goto done;
89 len = read (fd, &hdr->flags, sizeof(hdr->flags));
90 if (len == -1)
91 goto done;
93 len = read (fd, &hdr->iv, sizeof(hdr->iv));
94 if (len == -1)
95 goto done;
97 len = read (fd, &hdr->salt, sizeof(hdr->salt));
98 if (len == -1)
99 goto done;
101 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
102 if (len == -1)
103 goto done;
104 #else
105 len = read (fd, &hdr->magic, sizeof(hdr->magic));
106 if (len == -1)
107 goto done;
109 len = read (fd, &i, sizeof(hdr->version));
110 if (len == -1)
111 goto done;
112 hdr->version = ntohl (i);
114 len = read (fd, &n, sizeof(hdr->iterations));
115 if (len == -1)
116 goto done;
117 hdr->iterations = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
119 len = read (fd, &n, sizeof(hdr->flags));
120 if (len == -1)
121 goto done;
122 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
124 len = read (fd, &hdr->iv, sizeof(hdr->iv));
125 if (len == -1)
126 goto done;
128 len = read (fd, &hdr->salt, sizeof(hdr->salt));
129 if (len == -1)
130 goto done;
132 len = read (fd, &i, sizeof(hdr->datalen));
133 if (len == -1)
134 goto done;
135 hdr->datalen = ntohl (i);
136 #endif
138 done:
139 return len == -1 ? gpg_error_from_syserror () : 0;
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_syserror ();
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_syserror ();
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 (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 cleanup_crypto_stage1 (crypto);
194 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
195 if (rc)
196 return gpg_error (rc);
198 crypto->ciphertext_len = crypto->hdr.datalen;
199 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
200 if (!crypto->ciphertext)
202 rc = GPG_ERR_ENOMEM;
203 goto fail;
206 if (crypto->hdr.flags & PWMD_FLAG_PKI)
208 rlen = read (fd, crypto->grip, 20);
209 if (rlen != 20)
211 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
212 goto fail;
215 rlen = read (fd, crypto->sign_grip, 20);
216 if (rlen != 20)
218 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
219 goto fail;
223 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
224 if (len != crypto->hdr.datalen)
226 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
227 goto fail;
230 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
231 goto fail;
233 #ifndef WITH_AGENT
234 rc = GPG_ERR_NOT_IMPLEMENTED;
235 goto fail;
236 #else
237 if (!use_agent)
239 rc = GPG_ERR_NOT_IMPLEMENTED;
240 goto fail;
243 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
244 buf = xmalloc (len);
245 if (!buf)
247 rc = GPG_ERR_ENOMEM;
248 goto fail;
251 rlen = read (fd, buf, len);
252 if (rlen != len)
254 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
255 goto fail;
258 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
259 if (rc)
260 goto fail;
262 if (crypto->pkey_sexp)
263 gcry_sexp_release (crypto->pkey_sexp);
265 if (crypto->sigpkey_sexp)
266 gcry_sexp_release (crypto->sigpkey_sexp);
268 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
269 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
270 if (!rc)
271 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
272 #endif
274 fail:
275 close (fd);
276 xfree (buf);
277 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
278 rc = gpg_error (rc);
280 return rc;
283 #define CRYPTO_BLOCKSIZE(c) (blocksize * 1024)
286 * Useful for a large amount of data. Rather than doing all of the data in one
287 * iteration do it in chunks. This lets the command be cancelable rather than
288 * waiting for it to complete.
290 static gpg_error_t
291 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
292 size_t insize, size_t blocksize, status_msg_t which)
294 gpg_error_t rc = 0;
295 off_t len = CRYPTO_BLOCKSIZE (blocksize);
296 void *p = gcry_malloc (len);
297 off_t total = 0;
298 unsigned char *inbuf2;
300 if (!p)
301 return gpg_error (GPG_ERR_ENOMEM);
303 if (insize < CRYPTO_BLOCKSIZE (blocksize))
304 len = insize;
306 pthread_cleanup_push (gcry_free, p);
308 for (;;)
310 inbuf2 = inbuf + total;
311 unsigned char *tmp;
313 if (len + total > insize)
314 len = blocksize;
316 if (which == STATUS_ENCRYPT)
317 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
318 else
319 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
321 if (rc)
322 break;
324 tmp = inbuf + total;
325 memmove (tmp, p, len);
326 total += len;
327 if (total >= insize)
328 break;
330 #ifdef HAVE_PTHREAD_TESTCANCEL
331 pthread_testcancel ();
332 #endif
335 pthread_cleanup_pop (1);
336 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
337 rc = gpg_error (rc);
339 return rc;
342 static void
343 cleanup_cipher (void *arg)
345 gcry_cipher_close ((gcry_cipher_hd_t) arg);
348 gpg_error_t
349 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
350 unsigned char *salted_key, size_t skeylen)
352 gpg_error_t rc = 0;
353 unsigned char *key = salted_key;
354 gcry_cipher_hd_t h = NULL;
355 size_t blocksize, keysize = 0;
356 int algo = cipher_to_gcrypt (crypto->hdr.flags);
357 void *outbuf = NULL;
358 uint64_t n = crypto->hdr.iterations;
359 long progress = 0;
360 #ifdef WITH_AGENT
361 size_t keylen = skeylen;
362 gcry_sexp_t sig_sexp;
364 if (crypto->hdr.flags & PWMD_FLAG_PKI)
366 rc = agent_extract_key (crypto, &key, &keylen);
367 if (rc)
368 return rc;
370 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
371 if (!sig_sexp)
373 gcry_free (key);
374 return GPG_ERR_BAD_DATA;
377 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
378 crypto->ciphertext_len);
379 gcry_sexp_release (sig_sexp);
381 #endif
383 if (!rc)
385 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
386 if (!rc)
388 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
389 &keysize);
390 if (!rc)
392 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
393 &blocksize);
394 if (!rc)
396 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
397 if (!rc)
399 rc = gcry_cipher_setkey (h, key, keysize);
406 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
408 if (!rc)
410 outbuf = gcry_malloc (crypto->hdr.datalen);
411 if (!outbuf)
412 rc = GPG_ERR_ENOMEM;
415 pthread_cleanup_push (gcry_free, outbuf);
416 #ifdef WITH_AGENT
417 pthread_cleanup_push (gcry_free, key);
418 #endif
420 if (!rc)
422 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
423 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
424 STATUS_DECRYPT);
425 if (!rc)
427 key[0] ^= 1;
428 rc = gcry_cipher_setkey (h, key, keysize);
432 if (!rc)
434 progress = config_get_long (NULL, "cipher_progress");
435 if (progress == -1)
436 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
439 if (!rc && ctx && crypto->hdr.iterations)
440 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", 0,
441 crypto->hdr.iterations);
443 for (n = 0; !rc && n < crypto->hdr.iterations; n++)
445 if (ctx && !(n % progress))
447 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
448 crypto->hdr.iterations);
449 if (rc)
450 break;
453 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
454 if (rc)
455 break;
457 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
458 STATUS_DECRYPT);
461 if (!rc && ctx && crypto->hdr.iterations)
462 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
463 crypto->hdr.iterations);
465 #ifdef WITH_AGENT
466 pthread_cleanup_pop (0);
467 if (crypto->hdr.flags & PWMD_FLAG_PKI)
468 gcry_free (key);
469 else if (key)
470 key[0] ^= 1;
471 #else
472 key[0] ^= 1;
473 #endif
474 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
475 pthread_cleanup_pop (1); /* cipher */
476 if (!rc)
478 char buf[] = "<?xml ";
480 if (memcmp (outbuf, buf, sizeof(buf)-1))
482 gcry_free (outbuf);
483 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
486 crypto->plaintext = outbuf;
487 crypto->plaintext_len = crypto->hdr.datalen;
490 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
491 rc = gpg_error (rc);
493 return rc;
496 gpg_error_t
497 decrypt_xml (struct crypto_s * crypto, const void *data, size_t len)
499 gcry_cipher_hd_t h = NULL;
500 gpg_error_t rc;
502 rc = gcry_cipher_open (&h, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
503 if (rc)
504 return rc;
506 gcry_free (crypto->plaintext);
507 crypto->plaintext = gcry_malloc (len);
508 if (!crypto->plaintext)
510 rc = GPG_ERR_ENOMEM;
511 goto done;
514 rc = gcry_cipher_setiv (h, cache_iv, cache_blocksize);
515 if (rc)
516 goto done;
518 rc = gcry_cipher_setkey (h, cache_key, cache_keysize);
519 if (rc)
520 goto done;
522 rc = gcry_cipher_decrypt (h, crypto->plaintext, len, data, len);
523 if (rc || strncmp (crypto->plaintext, "<?xml ", 6))
525 if (!rc)
526 rc = GPG_ERR_BAD_DATA;
528 gcry_free (crypto->plaintext);
529 crypto->plaintext = NULL;
532 crypto->plaintext_len = len;
534 done:
535 if (h)
536 gcry_cipher_close (h);
538 return rc;
541 gpg_error_t
542 encrypt_xml (assuan_context_t ctx, void *key, size_t keylen,
543 int algo, const void *xml, size_t len, void * *result,
544 size_t *result_len, unsigned char **iv, size_t * iv_len,
545 uint64_t iter)
547 gpg_error_t rc;
548 gcry_cipher_hd_t h;
549 size_t blocksize, keysize;
550 void *inbuf = NULL;
551 size_t olen = len;
552 uint64_t n = 0;
553 long progress;
554 unsigned char *tmpkey = NULL;
555 int free_iv = *(iv_len) == 0;
557 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
558 if (rc)
559 return rc;
561 pthread_cleanup_push (cleanup_cipher, h);
562 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
563 if (!rc)
564 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL, &blocksize);
566 if (!rc && *(iv_len) == 0)
568 *(iv) = xmalloc (blocksize);
569 if (!*(iv))
570 rc = GPG_ERR_ENOMEM;
572 gcry_create_nonce (*(iv), blocksize);
575 pthread_cleanup_push (xfree, *(iv_len) == 0 ? *(iv) : NULL);
576 if (!rc)
578 *iv_len = blocksize;
579 tmpkey = gcry_malloc (keysize);
580 if (!tmpkey)
581 rc = GPG_ERR_ENOMEM;
584 pthread_cleanup_push (gcry_free, tmpkey);
586 if (!rc)
588 memcpy (tmpkey, key, keysize);
589 tmpkey[0] ^= 1;
590 rc = gcry_cipher_setkey (h, tmpkey, keysize);
591 if (!rc)
593 if (len % blocksize)
594 len += blocksize - (len % blocksize);
598 if (!rc)
600 inbuf = gcry_malloc (len);
601 if (!inbuf)
602 rc = GPG_ERR_ENOMEM;
605 pthread_cleanup_push (gcry_free, inbuf);
607 if (!rc)
609 memset (inbuf, 0, len);
610 memcpy (inbuf, xml, olen);
611 progress = config_get_long (NULL, "cipher_progress");
612 if (progress == -1)
613 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
615 if (!rc && ctx && iter)
616 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", 0, iter);
618 for (n = 0; !rc && n < iter; n++)
620 if (ctx && !(n % progress))
622 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
623 if (rc)
624 break;
627 rc = gcry_cipher_setiv (h, *(iv), blocksize);
628 if (rc)
629 break;
631 rc = iterate_crypto_once (h, inbuf, len, blocksize, STATUS_ENCRYPT);
635 if (!rc && ctx && iter)
636 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
638 if (!rc)
640 /* Do at least one iteration. */
641 rc = gcry_cipher_setiv (h, *(iv), blocksize);
642 if (!rc)
644 rc = gcry_cipher_setkey (h, key, keysize);
645 if (!rc)
646 rc = iterate_crypto_once (h, inbuf, len, blocksize,
647 STATUS_ENCRYPT);
651 pthread_cleanup_pop (rc ? 1 : 0); /* inbuf */
652 pthread_cleanup_pop (1); /* tmpkey */
653 pthread_cleanup_pop (rc && free_iv ? 1 : 0); /* iv */
654 pthread_cleanup_pop (1); /* cipher */
655 *result = rc ? NULL : inbuf;
656 *result_len = len;
657 return rc;
660 void
661 cleanup_save (struct save_s *save)
663 if (!save)
664 return;
666 #ifdef WITH_AGENT
667 if (save->pkey)
668 gcry_sexp_release (save->pkey);
670 if (save->sigpkey)
671 gcry_sexp_release (save->sigpkey);
672 #endif
674 memset (save, 0, sizeof (struct save_s));
677 /* Keep the agent ctx to retain pinentry options which will be freed in
678 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
679 void
680 cleanup_crypto_stage1 (struct crypto_s *cr)
682 if (!cr)
683 return;
685 cleanup_save (&cr->save);
687 #ifdef WITH_AGENT
688 if (cr->ciphertext_sexp)
689 gcry_sexp_release (cr->ciphertext_sexp);
691 cr->ciphertext_sexp = NULL;
692 #endif
694 gcry_free (cr->plaintext);
695 xfree (cr->ciphertext);
696 xfree (cr->filename);
697 cr->filename = NULL;
698 cr->ciphertext = NULL;
699 cr->ciphertext_len = 0;
700 cr->plaintext = NULL;
701 cr->plaintext_len = 0;
704 void
705 cleanup_crypto_stage2 (struct crypto_s *cr)
707 if (!cr)
708 return;
710 cleanup_crypto_stage1 (cr);
711 set_header_defaults (&cr->hdr);
714 void
715 cleanup_crypto (struct crypto_s **c)
717 struct crypto_s *cr = *c;
719 if (!cr)
720 return;
722 cleanup_crypto_stage2 (cr);
724 #ifdef WITH_AGENT
725 if (cr->pkey_sexp)
726 gcry_sexp_release (cr->pkey_sexp);
728 if (cr->sigpkey_sexp)
729 gcry_sexp_release (cr->sigpkey_sexp);
731 if (cr->agent)
732 cleanup_agent (cr->agent);
733 #endif
735 xfree (cr);
736 *c = NULL;
739 gpg_error_t
740 init_client_crypto (struct crypto_s **crypto)
742 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
743 gpg_error_t rc;
745 if (!new)
747 rc = GPG_ERR_ENOMEM;
748 return rc;
751 #ifdef WITH_AGENT
752 if (use_agent)
754 rc = agent_init (&new->agent);
755 if (!rc)
757 rc = send_agent_common_options (new->agent);
758 if (!rc)
759 rc = agent_set_pinentry_options (new->agent);
762 if (rc)
764 cleanup_agent (new->agent);
765 xfree (new);
766 return rc;
769 #endif
771 set_header_defaults (&new->hdr);
772 *crypto = new;
773 return 0;
776 static gpg_error_t
777 try_decrypt (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
778 const char *filename, char **key, size_t *keylen)
780 gpg_error_t rc;
781 int pin_try = 1;
782 int pin_tries = 3;
783 char *pin_title = NULL;
784 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
788 rc = decrypt_common (ctx, inquire, crypto, filename, key, keylen);
789 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE && ctx)
791 if (pin_try == 1)
792 pin_title = client->pinentry_opts.title;
794 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try+1, pin_tries);
797 while (!inquire && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
798 && ++pin_try <= pin_tries);
800 if (ctx && pin_title != client->pinentry_opts.title)
802 xfree (client->pinentry_opts.title);
803 client->pinentry_opts.title = pin_title;
806 return rc;
809 gpg_error_t
810 export_common (assuan_context_t ctx, int inquire, struct crypto_s * crypto,
811 const void *data, size_t datalen, const char *outfile,
812 const char *keyfile, void **rkey, size_t *rkeylen,
813 int use_cache, int force)
815 gpg_error_t rc = 0;
816 void *enc_xml = NULL;
817 size_t enc_xml_len = 0;
818 unsigned char *iv = NULL;
819 size_t iv_len = 0;
820 int algo = cipher_to_gcrypt (crypto->save.hdr.flags);
821 void *key = NULL, *salted_key = NULL;
822 size_t keysize, keylen;
823 int cached = 0;
825 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
826 if (rc)
827 return rc;
829 if (keyfile)
831 int fd;
832 unsigned char *buf;
833 size_t len;
834 struct stat st;
836 if (stat (keyfile, &st) == -1)
837 return gpg_error_from_syserror ();
839 buf = gcry_malloc (st.st_size);
840 if (!buf)
841 return GPG_ERR_ENOMEM;
843 fd = open (keyfile, O_RDONLY);
844 if (fd == -1)
845 rc = gpg_error_from_syserror ();
846 else
848 len = read (fd, buf, st.st_size);
849 if (len != st.st_size)
850 rc = GPG_ERR_TOO_SHORT;
853 if (fd != -1)
854 close (fd);
856 key = buf;
857 keylen = st.st_size;
858 log_write (_("Using passphrase obtained from file '%s'"), keyfile);
860 if (!keylen)
862 char *tmp;
864 gcry_free (key);
865 tmp = gcry_malloc (1);
866 *tmp = 0;
867 key = tmp;
868 keylen++;
871 else
873 if (use_cache)
875 cache_lock ();
876 cached = cache_iscached (outfile, NULL) == 0;
877 if (cached)
879 struct cache_data_s *cdata = cache_get_data_filename (outfile);
881 salted_key = gcry_malloc (cdata->keylen);
882 if (salted_key)
884 memcpy (salted_key, cdata->key, cdata->keylen);
885 keysize = cdata->keylen;
887 else
888 rc = GPG_ERR_ENOMEM;
891 cache_unlock ();
894 if (!rc && !cached)
896 if (force) // SAVE
898 struct crypto_s *tmp = NULL;
899 gpg_error_t rc = init_client_crypto (&tmp);
901 if (!rc)
903 rc = read_data_file (outfile, tmp);
904 if (!rc)
906 rc = try_decrypt (ctx, inquire, tmp, outfile,
907 (char **)&key, &keylen);
908 if (rc)
909 gcry_free (key);
913 cleanup_crypto (&tmp);
914 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
915 use_cache = 0;
916 else if (rc)
917 return rc;
920 if (!use_cache) // PASSWD or new file
922 gcry_free (key);
923 if (inquire)
925 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
926 (unsigned char **)&key, &keylen);
928 else
930 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
931 (char **)&key, &keylen);
934 if (rc)
935 return rc;
937 else
939 salted_key = key;
940 keysize = keylen;
941 cached = 1;
946 if (!rc && !cached)
948 rc = hash_key (algo, crypto->save.hdr.salt,
949 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
950 &keysize);
951 gcry_free (key);
954 if (!rc)
955 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
956 &enc_xml, &enc_xml_len, &iv, &iv_len,
957 crypto->save.hdr.iterations);
959 if (!rc)
961 memcpy (crypto->save.hdr.iv, iv, iv_len);
962 xfree (iv);
963 crypto->save.hdr.datalen = enc_xml_len;
964 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
965 NULL);
966 gcry_free (enc_xml);
967 if (!rc)
969 *rkey = salted_key;
970 *rkeylen = keysize;
971 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
975 if (rc)
976 gcry_free (salted_key);
978 return rc;
981 #ifdef WITH_LIBACL
982 static void
983 cleanup_acl (void *arg)
985 acl_t acl = *(acl_t *) arg;
987 if (acl)
988 acl_free (acl);
990 #endif
992 static gpg_error_t
993 write_header (struct crypto_s *crypto, int fd)
995 ssize_t len;
996 uint64_t n, x;
997 uint32_t i;
999 #ifdef WORDS_BIGENDIAN
1000 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1001 if (len == -1)
1002 goto done;
1004 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
1005 if (len == -1)
1006 goto done;
1008 len = write (fd, &crypto->save.hdr.iterations,
1009 sizeof(crypto->save.hdr.iterations));
1010 if (len == -1)
1011 goto done;
1013 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1014 if (len == -1)
1015 goto done;
1017 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1018 if (len == -1)
1019 goto done;
1021 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1022 if (len == -1)
1023 goto done;
1025 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1026 if (len == -1)
1027 goto done;
1028 #else
1029 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1030 if (len == -1)
1031 goto done;
1033 i = htonl (crypto->save.hdr.version);
1034 len = write (fd, &i, sizeof(i));
1035 if (len == -1)
1036 goto done;
1038 n = crypto->save.hdr.iterations;
1039 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1040 len = write (fd, &x, sizeof(x));
1041 if (len == -1)
1042 goto done;
1044 n = crypto->save.hdr.flags;
1045 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1046 len = write (fd, &x, sizeof(x));
1047 if (len == -1)
1048 goto done;
1050 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1051 if (len == -1)
1052 goto done;
1054 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1055 if (len == -1)
1056 goto done;
1058 i = htonl (crypto->save.hdr.datalen);
1059 len = write (fd, &i, sizeof(i));
1060 if (len == -1)
1061 goto done;
1062 #endif
1064 done:
1065 return len == -1 ? gpg_error_from_syserror () : 0;
1068 gpg_error_t
1069 write_file (struct crypto_s *crypto, const char *filename,
1070 void *data, size_t data_len, void *sexp, size_t sexp_len,
1071 void *pubkey, void *sigpkey)
1073 char tmp[FILENAME_MAX] = { 0 };
1074 mode_t mode = 0;
1075 struct stat st;
1076 int fd;
1077 gpg_error_t rc = 0;
1078 size_t len;
1079 #ifdef WITH_LIBACL
1080 acl_t acl = NULL;
1081 #endif
1083 if (filename)
1085 if (lstat (filename, &st) == 0)
1087 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1089 if (!(mode & S_IWUSR))
1090 return GPG_ERR_EACCES;
1092 else if (errno != ENOENT)
1093 return gpg_error_from_syserror ();
1095 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1096 fd = mkstemp (tmp);
1097 if (fd == -1)
1099 rc = gpg_error_from_syserror ();
1100 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1101 return rc;
1104 else
1106 // xml_import() or convert_file() from command line.
1107 fd = STDOUT_FILENO;
1110 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1111 crypto->save.hdr.version = VERSION_HEX;
1112 rc = write_header (crypto, fd);
1113 if (!rc)
1115 if (crypto->save.hdr.flags & PWMD_FLAG_PKI)
1117 unsigned char grip[20];
1119 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1120 len = write (fd, grip, sizeof (grip));
1121 if (len == sizeof (grip))
1123 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1124 len = write (fd, grip, sizeof (grip));
1125 if (len == sizeof (grip))
1127 len = write (fd, data, data_len);
1128 if (len == data_len)
1130 len = write (fd, sexp, sexp_len);
1131 if (len != sexp_len)
1132 rc = gpg_error_from_syserror ();
1134 else
1135 rc = gpg_error_from_syserror ();
1138 else
1139 rc = gpg_error_from_syserror ();
1141 else
1143 len = write (fd, data, data_len);
1144 if (len != data_len)
1145 rc = gpg_error_from_syserror ();
1149 #ifdef WITH_LIBACL
1150 pthread_cleanup_push (cleanup_acl, &acl);
1151 #endif
1152 if (!rc)
1154 if (fsync (fd) != -1)
1156 if (filename && close (fd) != -1)
1158 #ifdef WITH_LIBACL
1159 acl = acl_get_file (filename, ACL_TYPE_ACCESS);
1160 if (!acl && errno == ENOENT)
1161 acl = acl_get_file (".", ACL_TYPE_DEFAULT);
1162 if (!acl)
1163 log_write ("ACL: %s: %s", filename,
1164 pwmd_strerror (gpg_error_from_syserror ()));
1165 #endif
1167 if (mode && config_get_boolean (filename, "backup"))
1169 char tmp2[FILENAME_MAX];
1171 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1172 if (rename (filename, tmp2) == -1)
1173 rc = gpg_error_from_syserror ();
1176 else if (filename)
1177 rc = gpg_error_from_syserror ();
1179 else
1180 rc = gpg_error_from_syserror ();
1183 if (!rc)
1185 if (filename && rename (tmp, filename) != -1)
1187 tmp[0] = 0;
1188 if (filename && mode)
1189 chmod (filename, mode);
1191 #ifdef WITH_LIBACL
1192 if (acl && acl_set_file (filename, ACL_TYPE_ACCESS, acl))
1193 log_write ("ACL: %s: %s", filename,
1194 pwmd_strerror (gpg_error_from_syserror ()));
1195 #endif
1197 else
1198 rc = gpg_error_from_syserror ();
1201 #ifdef WITH_LIBACL
1202 pthread_cleanup_pop (1);
1203 #endif
1204 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1205 return rc;
1208 gpg_error_t
1209 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1210 size_t keylen, void **result, size_t *rlen)
1212 gpg_error_t rc;
1213 void *tmp;
1215 /* Be sure the algorithm is available. */
1216 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1217 if (rc)
1218 return rc;
1220 /* Always allocate enough for a 256-bit key although the algorithms
1221 themselves may use less. Fixes SAVE --cipher with a different
1222 keylen than the previously saved cipher when cached. */
1223 *rlen = 32;
1224 tmp = xmalloc (*rlen);
1225 if (!tmp)
1226 return GPG_ERR_ENOMEM;
1228 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1229 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1230 if (!rc)
1231 *result = tmp;
1232 else
1233 xfree (tmp);
1235 return rc;
1238 gpg_error_t
1239 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1240 struct crypto_s **rcrypto)
1242 unsigned char *key = NULL;
1243 size_t keylen = 0;
1244 struct crypto_s *crypto = NULL;
1245 gpg_error_t rc = init_client_crypto (&crypto);
1247 if (rc)
1248 return rc;
1250 crypto->client_ctx = ctx;
1251 rc = read_data_file (filename, crypto);
1252 if (rc)
1254 cleanup_crypto (&crypto);
1255 return rc;
1258 rc = try_decrypt (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1259 if (rc)
1261 cleanup_crypto (&crypto);
1262 return rc;
1265 if (!rc)
1267 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1268 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1269 crypto->plaintext_len, crypto->filename, NULL,
1270 (void **)&key, &keylen, 0, 0);
1273 if (!rc)
1275 int cached;
1277 rc = save_common (filename, crypto, crypto->plaintext,
1278 crypto->plaintext_len, key, keylen, &cached, 1);
1279 if (!rc)
1280 *rcrypto = crypto;
1283 if (rc)
1285 gcry_free (key);
1286 cleanup_crypto (&crypto);
1289 return rc;
1292 // FIXME gcry_sexp_t is updated in cdata. make a temp var in case of failure.
1293 gpg_error_t
1294 save_common (const char *filename, struct crypto_s *crypto,
1295 const unsigned char *data, size_t datalen,
1296 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1298 struct cache_data_s *cdata;
1299 gpg_error_t rc;
1301 /* This is safe since it is a fast operation. */
1302 cache_lock ();
1303 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1304 cdata = cache_get_data_filename (filename);
1305 *cached = cdata != NULL;
1307 if (!cdata)
1308 cdata = xcalloc (1, sizeof (struct cache_data_s));
1310 #ifdef WITH_AGENT
1311 if (use_agent && !no_agent)
1313 /* Update in case of any --keygrip argument */
1314 if (cdata->pubkey)
1315 gcry_sexp_release (cdata->pubkey);
1317 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1318 crypto->pkey_sexp);
1320 if (cdata->sigkey)
1321 gcry_sexp_release (cdata->sigkey);
1323 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1324 crypto->sigpkey_sexp);
1326 #endif
1328 gcry_free (cdata->doc);
1329 cdata->doc = NULL;
1330 cdata->key = (unsigned char *)key;
1331 cdata->keylen = keylen;
1332 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1333 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1334 &cache_blocksize, 0);
1335 if (!rc)
1337 unsigned char md5file[16];
1339 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1340 rc = cache_set_data (md5file, cdata, crypto->grip);
1343 pthread_cleanup_pop (1); // mutex unlock
1344 return rc;
1347 gpg_error_t
1348 getpin_common (assuan_context_t ctx, const char *filename, int which,
1349 char **rkey, size_t *rkeylen)
1351 gpg_error_t rc;
1352 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1353 struct pinentry_s *pin = pinentry_init (filename);
1355 if (!pin)
1356 return GPG_ERR_ENOMEM;
1358 if (client)
1359 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1361 rc = pinentry_lock (ctx, pin);
1362 if (!rc)
1363 rc = pinentry_getpin (pin, rkey, which);
1365 pinentry_deinit (pin);
1366 if (rc)
1367 return rc;
1369 *rkeylen = strlen (*rkey);
1370 if (!(*rkeylen))
1371 (*rkeylen)++;
1373 return rc;
1376 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1377 * both call xfree(). */
1378 gpg_error_t
1379 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1380 unsigned char **result, size_t *rlen)
1382 gpg_error_t rc;
1384 assuan_begin_confidential (ctx);
1385 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1386 assuan_end_confidential (ctx);
1387 return rc;
1390 gpg_error_t
1391 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1392 const char *filename, char **rkey, size_t *rkeylen)
1394 char *key = NULL;
1395 size_t keylen = 0;
1396 gpg_error_t rc = read_data_file (filename, crypto);
1397 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1398 void *salted_key = NULL;
1399 size_t keysize = 0;
1401 if (rc)
1403 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1404 return rc;
1407 key = config_get_string (filename, "passphrase");
1408 if (key)
1410 log_write (_("Trying the passphrase specified in config ..."));
1411 keylen = strlen (key);
1414 if (!key)
1416 key = config_get_string (filename, "passphrase_file");
1417 if (key)
1419 char *tmp = expand_homedir (key);
1420 int fd;
1421 struct stat st;
1423 xfree (key);
1424 key = tmp;
1425 log_write (_("Trying the passphrase using file '%s' ..."), key);
1426 fd = open (key, O_RDONLY);
1427 if (fd == -1)
1429 rc = gpg_error_from_syserror ();
1430 log_write ("%s: %s", key, pwmd_strerror (rc));
1431 xfree (key);
1432 return rc;
1435 stat (key, &st);
1436 xfree (key);
1437 key = xmalloc (st.st_size);
1438 if (key)
1440 if (read (fd, key, st.st_size) != st.st_size)
1442 log_write ("short read() count");
1443 rc = GPG_ERR_TOO_SHORT;
1446 else
1447 rc = GPG_ERR_ENOMEM;
1449 close (fd);
1451 if (rc)
1453 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1454 xfree (key);
1455 return rc;
1458 keylen = st.st_size;
1459 if (!keylen)
1461 tmp = xmalloc (1);
1462 *tmp = 0;
1463 xfree (key);
1464 key = tmp;
1465 keylen++;
1470 if (!key && !IS_PKI (crypto) && inquire)
1472 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1473 &keylen);
1474 if (rc)
1476 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1477 return rc;
1480 if (!keylen)
1481 keylen++;
1483 else if (!key && !IS_PKI (crypto))
1485 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1486 if (rc)
1488 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1489 return rc;
1492 #ifdef WITH_AGENT
1493 else if (key && IS_PKI (crypto))
1495 rc = set_agent_passphrase (crypto, key, keylen);
1496 if (rc)
1498 xfree (key);
1499 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1500 return rc;
1503 else if (!key && IS_PKI (crypto))
1505 /* The cache entry has been cleared in save_command(). Will prompt. */
1506 rc = set_pinentry_mode (crypto->agent, inquire ? "loopback" : "ask");
1507 if (rc)
1508 return rc;
1510 #endif
1512 if (key && !IS_PKI (crypto))
1514 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1515 keylen, &salted_key, &keysize);
1516 xfree (key);
1517 key = (char *)salted_key;
1518 keylen = keysize;
1519 if (rc)
1521 xfree (salted_key);
1522 return rc;
1526 xfree (crypto->filename);
1527 crypto->filename = str_dup (filename);
1528 rc = decrypt_data (ctx, crypto, (unsigned char *)key, keylen);
1529 if (rc)
1531 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1532 xfree (key);
1534 else
1536 *rkey = key;
1537 *rkeylen = keylen;
1540 return rc;