Set the correct IV blocksize.
[pwmd.git] / src / crypto.c
blobed1ba674cf4fe5905a10317e1470d442f37c0ef0
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_PKCS;
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_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 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 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_PKCS)
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_PKCS))
231 goto fail;
233 #ifndef WITH_AGENT
234 rc = GPG_ERR_NOT_IMPLEMENTED;
235 goto fail;
236 #else
237 if (!use_agent)
238 return GPG_ERR_NOT_IMPLEMENTED;
240 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
241 buf = xmalloc (len);
242 if (!buf)
244 rc = GPG_ERR_ENOMEM;
245 goto fail;
248 rlen = read (fd, buf, len);
249 if (rlen != len)
251 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
252 goto fail;
255 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
256 if (rc)
257 goto fail;
259 if (crypto->pkey_sexp)
260 gcry_sexp_release (crypto->pkey_sexp);
262 if (crypto->sigpkey_sexp)
263 gcry_sexp_release (crypto->sigpkey_sexp);
265 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
266 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
267 if (!rc)
268 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
269 #endif
271 fail:
272 close (fd);
273 xfree (buf);
274 return rc;
277 #define CRYPTO_BLOCKSIZE(c) (blocksize * 1024)
280 * Useful for a large amount of data. Rather than doing all of the data in one
281 * iteration do it in chunks. This lets the command be cancelable rather than
282 * waiting for it to complete.
284 static gpg_error_t
285 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
286 size_t insize, size_t blocksize, status_msg_t which)
288 gpg_error_t rc = 0;
289 off_t len = CRYPTO_BLOCKSIZE (blocksize);
290 void *p = gcry_malloc (len);
291 off_t total = 0;
292 unsigned char *inbuf2;
294 if (!p)
295 return GPG_ERR_ENOMEM;
297 if (insize < CRYPTO_BLOCKSIZE (blocksize))
298 len = insize;
300 pthread_cleanup_push (gcry_free, p);
302 for (;;)
304 inbuf2 = inbuf + total;
305 unsigned char *tmp;
307 if (len + total > insize)
308 len = blocksize;
310 if (which == STATUS_ENCRYPT)
311 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
312 else
313 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
315 if (rc)
316 break;
318 tmp = inbuf + total;
319 memmove (tmp, p, len);
320 total += len;
321 if (total >= insize)
322 break;
324 #ifdef HAVE_PTHREAD_TESTCANCEL
325 pthread_testcancel ();
326 #endif
329 pthread_cleanup_pop (1);
330 return rc;
333 static void
334 cleanup_cipher (void *arg)
336 gcry_cipher_close ((gcry_cipher_hd_t) arg);
339 gpg_error_t
340 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
341 unsigned char *salted_key, size_t skeylen)
343 gpg_error_t rc = 0;
344 unsigned char *key = salted_key;
345 gcry_cipher_hd_t h = NULL;
346 size_t blocksize, keysize = 0;
347 int algo = cipher_to_gcrypt (crypto->hdr.flags);
348 void *outbuf = NULL;
349 uint64_t n = crypto->hdr.iterations;
350 long progress = 0;
351 #ifdef WITH_AGENT
352 size_t keylen = skeylen;
353 gcry_sexp_t sig_sexp;
355 if (crypto->hdr.flags & PWMD_FLAG_PKCS)
357 rc = agent_extract_key (crypto, &key, &keylen);
358 if (rc)
359 return rc;
361 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
362 if (!sig_sexp)
364 gcry_free (key);
365 return GPG_ERR_BAD_DATA;
368 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
369 crypto->ciphertext_len);
370 gcry_sexp_release (sig_sexp);
372 #endif
374 if (!rc)
376 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
377 if (!rc)
379 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
380 &keysize);
381 if (!rc)
383 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
384 &blocksize);
385 if (!rc)
387 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
388 if (!rc)
390 rc = gcry_cipher_setkey (h, key, keysize);
397 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
399 if (!rc)
401 outbuf = gcry_malloc (crypto->hdr.datalen);
402 if (!outbuf)
403 rc = GPG_ERR_ENOMEM;
406 pthread_cleanup_push (gcry_free, outbuf);
407 #ifdef WITH_AGENT
408 pthread_cleanup_push (gcry_free, key);
409 #endif
411 if (!rc)
413 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
414 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
415 STATUS_DECRYPT);
416 if (!rc)
418 key[0] ^= 1;
419 rc = gcry_cipher_setkey (h, key, keysize);
423 if (!rc)
425 progress = config_get_long (NULL, "cipher_progress");
426 if (progress == -1)
427 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
430 if (!rc && ctx && crypto->hdr.iterations)
431 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", 0,
432 crypto->hdr.iterations);
434 for (n = 0; !rc && n < crypto->hdr.iterations; n++)
436 if (ctx && !(n % progress))
438 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
439 crypto->hdr.iterations);
440 if (rc)
441 break;
444 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
445 if (rc)
446 break;
448 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
449 STATUS_DECRYPT);
452 if (!rc && ctx && crypto->hdr.iterations)
453 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
454 crypto->hdr.iterations);
456 #ifdef WITH_AGENT
457 pthread_cleanup_pop (0);
458 if (crypto->hdr.flags & PWMD_FLAG_PKCS)
459 gcry_free (key);
460 else if (key)
461 key[0] ^= 1;
462 #else
463 key[0] ^= 1;
464 #endif
465 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
466 pthread_cleanup_pop (1); /* cipher */
467 if (!rc)
469 char buf[] = "<?xml ";
471 if (memcmp (outbuf, buf, sizeof(buf)-1))
473 gcry_free (outbuf);
474 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
477 crypto->plaintext = outbuf;
478 crypto->plaintext_len = crypto->hdr.datalen;
481 return rc;
484 gpg_error_t
485 decrypt_xml (struct crypto_s * crypto, const void *data, size_t len)
487 gcry_cipher_hd_t h = NULL;
488 gpg_error_t rc;
490 rc = gcry_cipher_open (&h, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
491 if (rc)
492 return rc;
494 gcry_free (crypto->plaintext);
495 crypto->plaintext = gcry_malloc (len);
496 if (!crypto->plaintext)
498 rc = GPG_ERR_ENOMEM;
499 goto done;
502 rc = gcry_cipher_setiv (h, cache_iv, cache_blocksize);
503 if (rc)
504 goto done;
506 rc = gcry_cipher_setkey (h, cache_key, cache_keysize);
507 if (rc)
508 goto done;
510 rc = gcry_cipher_decrypt (h, crypto->plaintext, len, data, len);
511 if (rc || strncmp (crypto->plaintext, "<?xml ", 6))
513 if (!rc)
514 rc = GPG_ERR_BAD_DATA;
516 gcry_free (crypto->plaintext);
517 crypto->plaintext = NULL;
520 crypto->plaintext_len = len;
522 done:
523 if (h)
524 gcry_cipher_close (h);
526 return rc;
529 gpg_error_t
530 encrypt_xml (assuan_context_t ctx, void *key, size_t keylen,
531 int algo, const void *xml, size_t len, void * *result,
532 size_t *result_len, unsigned char **iv, size_t * iv_len,
533 uint64_t iter)
535 gpg_error_t rc;
536 gcry_cipher_hd_t h;
537 size_t blocksize, keysize;
538 void *inbuf = NULL;
539 size_t olen = len;
540 uint64_t n = 0;
541 long progress;
542 unsigned char *tmpkey = NULL;
543 int free_iv = *(iv_len) == 0;
545 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
546 if (rc)
547 return rc;
549 pthread_cleanup_push (cleanup_cipher, h);
550 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
551 if (!rc)
552 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL, &blocksize);
554 if (!rc && *(iv_len) == 0)
556 *(iv) = xmalloc (blocksize);
557 if (!*(iv))
558 rc = GPG_ERR_ENOMEM;
560 gcry_create_nonce (*(iv), blocksize);
563 pthread_cleanup_push (xfree, *(iv_len) == 0 ? *(iv) : NULL);
564 if (!rc)
566 *iv_len = blocksize;
567 tmpkey = gcry_malloc (keysize);
568 if (!tmpkey)
569 rc = GPG_ERR_ENOMEM;
572 pthread_cleanup_push (gcry_free, tmpkey);
574 if (!rc)
576 memcpy (tmpkey, key, keysize);
577 tmpkey[0] ^= 1;
578 rc = gcry_cipher_setkey (h, tmpkey, keysize);
579 if (!rc)
581 if (len % blocksize)
582 len += blocksize - (len % blocksize);
586 if (!rc)
588 inbuf = gcry_malloc (len);
589 if (!inbuf)
590 rc = GPG_ERR_ENOMEM;
593 pthread_cleanup_push (gcry_free, inbuf);
595 if (!rc)
597 memset (inbuf, 0, len);
598 memcpy (inbuf, xml, olen);
599 progress = config_get_long (NULL, "cipher_progress");
600 if (progress == -1)
601 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
603 if (!rc && ctx && iter)
604 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", 0, iter);
606 for (n = 0; !rc && n < iter; n++)
608 if (ctx && !(n % progress))
610 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
611 if (rc)
612 break;
615 rc = gcry_cipher_setiv (h, *(iv), blocksize);
616 if (rc)
617 break;
619 rc = iterate_crypto_once (h, inbuf, len, blocksize, STATUS_ENCRYPT);
623 if (!rc && ctx && iter)
624 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
626 if (!rc)
628 /* Do at least one iteration. */
629 rc = gcry_cipher_setiv (h, *(iv), blocksize);
630 if (!rc)
632 rc = gcry_cipher_setkey (h, key, keysize);
633 if (!rc)
634 rc = iterate_crypto_once (h, inbuf, len, blocksize,
635 STATUS_ENCRYPT);
639 pthread_cleanup_pop (rc ? 1 : 0); /* inbuf */
640 pthread_cleanup_pop (1); /* tmpkey */
641 pthread_cleanup_pop (rc && free_iv ? 1 : 0); /* iv */
642 pthread_cleanup_pop (1); /* cipher */
643 *result = rc ? NULL : inbuf;
644 *result_len = len;
645 return rc;
648 void
649 cleanup_save (struct save_s *save)
651 if (!save)
652 return;
654 #ifdef WITH_AGENT
655 if (save->pkey)
656 gcry_sexp_release (save->pkey);
658 if (save->sigpkey)
659 gcry_sexp_release (save->sigpkey);
660 #endif
662 memset (save, 0, sizeof (struct save_s));
665 /* Keep the agent ctx to retain pinentry options which will be freed in
666 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
667 void
668 cleanup_crypto_stage1 (struct crypto_s *cr)
670 if (!cr)
671 return;
673 cleanup_save (&cr->save);
675 #ifdef WITH_AGENT
676 if (cr->ciphertext_sexp)
677 gcry_sexp_release (cr->ciphertext_sexp);
679 cr->ciphertext_sexp = NULL;
680 #endif
682 gcry_free (cr->plaintext);
683 xfree (cr->ciphertext);
684 xfree (cr->filename);
685 cr->filename = NULL;
686 cr->ciphertext = NULL;
687 cr->ciphertext_len = 0;
688 cr->plaintext = NULL;
689 cr->plaintext_len = 0;
692 void
693 cleanup_crypto_stage2 (struct crypto_s *cr)
695 if (!cr)
696 return;
698 cleanup_crypto_stage1 (cr);
699 set_header_defaults (&cr->hdr);
702 void
703 cleanup_crypto (struct crypto_s **c)
705 struct crypto_s *cr = *c;
707 if (!cr)
708 return;
710 cleanup_crypto_stage2 (cr);
712 #ifdef WITH_AGENT
713 if (cr->pkey_sexp)
714 gcry_sexp_release (cr->pkey_sexp);
716 if (cr->sigpkey_sexp)
717 gcry_sexp_release (cr->sigpkey_sexp);
719 if (cr->agent)
720 cleanup_agent (cr->agent);
721 #endif
723 xfree (cr);
724 *c = NULL;
727 gpg_error_t
728 init_client_crypto (struct crypto_s **crypto)
730 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
731 gpg_error_t rc;
733 if (!new)
735 rc = GPG_ERR_ENOMEM;
736 return rc;
739 #ifdef WITH_AGENT
740 if (use_agent)
742 rc = agent_init (&new->agent);
743 if (!rc)
745 rc = send_agent_common_options (new->agent);
746 if (!rc)
747 rc = agent_set_pinentry_options (new->agent);
750 if (rc)
752 cleanup_agent (new->agent);
753 xfree (new);
754 return rc;
757 #endif
759 set_header_defaults (&new->hdr);
760 *crypto = new;
761 return 0;
764 static gpg_error_t
765 try_decrypt (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
766 const char *filename, char **key, size_t *keylen)
768 gpg_error_t rc;
769 int pin_try = 1;
770 int pin_tries = 3;
771 char *pin_title = NULL;
772 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
776 rc = decrypt_common (ctx, inquire, crypto, filename, key, keylen);
777 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE && ctx)
779 if (pin_try == 1)
780 pin_title = client->pinentry_opts.title;
782 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try+1, pin_tries);
785 while (!inquire && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
786 && ++pin_try <= pin_tries);
788 if (ctx && pin_title != client->pinentry_opts.title)
790 xfree (client->pinentry_opts.title);
791 client->pinentry_opts.title = pin_title;
794 return rc;
797 gpg_error_t
798 export_common (assuan_context_t ctx, int inquire, struct crypto_s * crypto,
799 const void *data, size_t datalen, const char *outfile,
800 const char *keyfile, void **rkey, size_t *rkeylen,
801 int use_cache, int force)
803 gpg_error_t rc = 0;
804 void *enc_xml = NULL;
805 size_t enc_xml_len = 0;
806 unsigned char *iv = NULL;
807 size_t iv_len = 0;
808 int algo = cipher_to_gcrypt (crypto->save.hdr.flags);
809 void *key = NULL, *salted_key = NULL;
810 size_t keysize, keylen;
811 int cached = 0;
813 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
814 if (rc)
815 return rc;
817 if (keyfile)
819 int fd;
820 unsigned char *buf;
821 size_t len;
822 struct stat st;
824 if (stat (keyfile, &st) == -1)
825 return gpg_error_from_syserror ();
827 buf = gcry_malloc (st.st_size);
828 if (!buf)
829 return GPG_ERR_ENOMEM;
831 fd = open (keyfile, O_RDONLY);
832 if (fd == -1)
833 rc = gpg_error_from_syserror ();
834 else
836 len = read (fd, buf, st.st_size);
837 if (len != st.st_size)
838 rc = GPG_ERR_TOO_SHORT;
841 if (fd != -1)
842 close (fd);
844 key = buf;
845 keylen = st.st_size;
846 log_write (_("Using passphrase obtained from file '%s'"), keyfile);
848 if (!keylen)
850 char *tmp;
852 gcry_free (key);
853 tmp = gcry_malloc (1);
854 *tmp = 0;
855 key = tmp;
856 keylen++;
859 else
861 if (use_cache)
863 cache_lock ();
864 cached = cache_iscached (outfile, NULL) == 0;
865 if (cached)
867 struct cache_data_s *cdata = cache_get_data_filename (outfile);
869 salted_key = gcry_malloc (cdata->keylen);
870 if (salted_key)
872 memcpy (salted_key, cdata->key, cdata->keylen);
873 keysize = cdata->keylen;
875 else
876 rc = GPG_ERR_ENOMEM;
879 cache_unlock ();
882 if (!rc && !cached)
884 if (force) // SAVE
886 struct crypto_s *tmp = NULL;
887 gpg_error_t rc = init_client_crypto (&tmp);
889 if (!rc)
891 rc = read_data_file (outfile, tmp);
892 if (!rc)
894 rc = try_decrypt (ctx, inquire, tmp, outfile,
895 (char **)&key, &keylen);
896 if (rc)
897 gcry_free (key);
901 cleanup_crypto (&tmp);
902 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
903 use_cache = 0;
904 else if (rc)
905 return rc;
908 if (!use_cache) // PASSWD or new file
910 gcry_free (key);
911 if (inquire)
913 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
914 (unsigned char **)&key, &keylen);
916 else
918 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
919 (char **)&key, &keylen);
922 if (rc)
923 return rc;
925 else
927 salted_key = key;
928 keysize = keylen;
929 cached = 1;
934 if (!rc && !cached)
936 rc = hash_key (algo, crypto->save.hdr.salt,
937 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
938 &keysize);
939 gcry_free (key);
942 if (!rc)
943 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
944 &enc_xml, &enc_xml_len, &iv, &iv_len,
945 crypto->save.hdr.iterations);
947 if (!rc)
949 memcpy (crypto->save.hdr.iv, iv, iv_len);
950 xfree (iv);
951 crypto->save.hdr.datalen = enc_xml_len;
952 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
953 NULL);
954 gcry_free (enc_xml);
955 if (!rc)
957 *rkey = salted_key;
958 *rkeylen = keysize;
959 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
963 if (rc)
964 gcry_free (salted_key);
966 return rc;
969 #ifdef WITH_LIBACL
970 static void
971 cleanup_acl (void *arg)
973 acl_t acl = *(acl_t *) arg;
975 if (acl)
976 acl_free (acl);
978 #endif
980 static gpg_error_t
981 write_header (struct crypto_s *crypto, int fd)
983 ssize_t len;
984 uint64_t n, x;
985 uint32_t i;
987 #ifdef WORDS_BIGENDIAN
988 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
989 if (len == -1)
990 goto done;
992 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
993 if (len == -1)
994 goto done;
996 len = write (fd, &crypto->save.hdr.iterations,
997 sizeof(crypto->save.hdr.iterations));
998 if (len == -1)
999 goto done;
1001 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1002 if (len == -1)
1003 goto done;
1005 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1006 if (len == -1)
1007 goto done;
1009 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1010 if (len == -1)
1011 goto done;
1013 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1014 if (len == -1)
1015 goto done;
1016 #else
1017 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1018 if (len == -1)
1019 goto done;
1021 i = htonl (crypto->save.hdr.version);
1022 len = write (fd, &i, sizeof(i));
1023 if (len == -1)
1024 goto done;
1026 n = crypto->save.hdr.iterations;
1027 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1028 len = write (fd, &x, sizeof(x));
1029 if (len == -1)
1030 goto done;
1032 n = crypto->save.hdr.flags;
1033 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1034 len = write (fd, &x, sizeof(x));
1035 if (len == -1)
1036 goto done;
1038 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1039 if (len == -1)
1040 goto done;
1042 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1043 if (len == -1)
1044 goto done;
1046 i = htonl (crypto->save.hdr.datalen);
1047 len = write (fd, &i, sizeof(i));
1048 if (len == -1)
1049 goto done;
1050 #endif
1052 done:
1053 return len == -1 ? gpg_error_from_syserror () : 0;
1056 gpg_error_t
1057 write_file (struct crypto_s *crypto, const char *filename,
1058 void *data, size_t data_len, void *sexp, size_t sexp_len,
1059 void *pubkey, void *sigpkey)
1061 char tmp[FILENAME_MAX] = { 0 };
1062 mode_t mode = 0;
1063 struct stat st;
1064 int fd;
1065 gpg_error_t rc = 0;
1066 size_t len;
1067 #ifdef WITH_LIBACL
1068 acl_t acl = NULL;
1069 #endif
1071 if (filename)
1073 if (lstat (filename, &st) == 0)
1075 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1077 if (!(mode & S_IWUSR))
1078 return GPG_ERR_EACCES;
1080 else if (errno != ENOENT)
1081 return gpg_error_from_syserror ();
1083 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1084 fd = mkstemp (tmp);
1085 if (fd == -1)
1087 rc = gpg_error_from_syserror ();
1088 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1089 return rc;
1092 else
1094 // xml_import() or convert_file() from command line.
1095 fd = STDOUT_FILENO;
1098 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1099 crypto->save.hdr.version = VERSION_HEX;
1100 rc = write_header (crypto, fd);
1101 if (!rc)
1103 if (crypto->save.hdr.flags & PWMD_FLAG_PKCS)
1105 unsigned char grip[20];
1107 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1108 len = write (fd, grip, sizeof (grip));
1109 if (len == sizeof (grip))
1111 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1112 len = write (fd, grip, sizeof (grip));
1113 if (len == sizeof (grip))
1115 len = write (fd, data, data_len);
1116 if (len == data_len)
1118 len = write (fd, sexp, sexp_len);
1119 if (len != sexp_len)
1120 rc = gpg_error_from_syserror ();
1122 else
1123 rc = gpg_error_from_syserror ();
1126 else
1127 rc = gpg_error_from_syserror ();
1129 else
1131 len = write (fd, data, data_len);
1132 if (len != data_len)
1133 rc = gpg_error_from_syserror ();
1137 #ifdef WITH_LIBACL
1138 pthread_cleanup_push (cleanup_acl, &acl);
1139 #endif
1140 if (!rc)
1142 if (fsync (fd) != -1)
1144 if (filename && close (fd) != -1)
1146 #ifdef WITH_LIBACL
1147 acl = acl_get_file (filename, ACL_TYPE_ACCESS);
1148 if (!acl && errno == ENOENT)
1149 acl = acl_get_file (".", ACL_TYPE_DEFAULT);
1150 if (!acl)
1151 log_write ("ACL: %s: %s", filename,
1152 pwmd_strerror (gpg_error_from_syserror ()));
1153 #endif
1155 if (mode && config_get_boolean (filename, "backup"))
1157 char tmp2[FILENAME_MAX];
1159 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1160 if (rename (filename, tmp2) == -1)
1161 rc = gpg_error_from_syserror ();
1164 else if (filename)
1165 rc = gpg_error_from_syserror ();
1167 else
1168 rc = gpg_error_from_syserror ();
1171 if (!rc)
1173 if (filename && rename (tmp, filename) != -1)
1175 tmp[0] = 0;
1176 if (filename && mode)
1177 chmod (filename, mode);
1179 #ifdef WITH_LIBACL
1180 if (acl && acl_set_file (filename, ACL_TYPE_ACCESS, acl))
1181 log_write ("ACL: %s: %s", filename,
1182 pwmd_strerror (gpg_error_from_syserror ()));
1183 #endif
1185 else
1186 rc = gpg_error_from_syserror ();
1189 #ifdef WITH_LIBACL
1190 pthread_cleanup_pop (1);
1191 #endif
1192 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1193 return rc;
1196 gpg_error_t
1197 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1198 size_t keylen, void **result, size_t *rlen)
1200 gpg_error_t rc;
1201 void *tmp;
1203 /* Be sure the algorithm is available. */
1204 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1205 if (rc)
1206 return rc;
1208 /* Always allocate enough for a 256-bit key although the algorithms
1209 themselves may use less. Fixes SAVE --cipher with a different
1210 keylen than the previously saved cipher when cached. */
1211 *rlen = 32;
1212 tmp = xmalloc (*rlen);
1213 if (!tmp)
1214 return GPG_ERR_ENOMEM;
1216 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1217 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1218 if (!rc)
1219 *result = tmp;
1220 else
1221 xfree (tmp);
1223 return rc;
1226 gpg_error_t
1227 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1228 struct crypto_s **rcrypto)
1230 unsigned char *key = NULL;
1231 size_t keylen = 0;
1232 struct crypto_s *crypto = NULL;
1233 gpg_error_t rc = init_client_crypto (&crypto);
1235 if (rc)
1236 return rc;
1238 crypto->client_ctx = ctx;
1239 rc = read_data_file (filename, crypto);
1240 if (rc)
1242 cleanup_crypto (&crypto);
1243 return rc;
1246 rc = try_decrypt (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1247 if (rc)
1249 cleanup_crypto (&crypto);
1250 return rc;
1253 if (!rc)
1255 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1256 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1257 crypto->plaintext_len, crypto->filename, NULL,
1258 (void **)&key, &keylen, 0, 0);
1261 if (!rc)
1263 int cached;
1265 rc = save_common (filename, crypto, crypto->plaintext,
1266 crypto->plaintext_len, key, keylen, &cached, 1);
1267 if (!rc)
1268 *rcrypto = crypto;
1271 if (rc)
1273 gcry_free (key);
1274 cleanup_crypto (&crypto);
1277 return rc;
1280 // FIXME gcry_sexp_t is updated in cdata. make a temp var in case of failure.
1281 gpg_error_t
1282 save_common (const char *filename, struct crypto_s *crypto,
1283 const unsigned char *data, size_t datalen,
1284 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1286 struct cache_data_s *cdata;
1287 gpg_error_t rc;
1289 /* This is safe since it is a fast operation. */
1290 cache_lock ();
1291 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1292 cdata = cache_get_data_filename (filename);
1293 *cached = cdata != NULL;
1295 if (!cdata)
1296 cdata = xcalloc (1, sizeof (struct cache_data_s));
1298 #ifdef WITH_AGENT
1299 if (use_agent && !no_agent)
1301 /* Update in case of any --keygrip argument */
1302 if (cdata->pubkey)
1303 gcry_sexp_release (cdata->pubkey);
1305 gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL, "%S",
1306 crypto->pkey_sexp);
1308 if (cdata->sigkey)
1309 gcry_sexp_release (cdata->sigkey);
1311 gcry_sexp_build ((gcry_sexp_t *) & cdata->sigkey, NULL, "%S",
1312 crypto->sigpkey_sexp);
1314 #endif
1316 gcry_free (cdata->doc);
1317 cdata->doc = NULL;
1318 cdata->key = (unsigned char *)key;
1319 cdata->keylen = keylen;
1320 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1321 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1322 &cache_blocksize, 0);
1323 if (!rc)
1325 unsigned char md5file[16];
1327 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1328 rc = cache_set_data (md5file, cdata, crypto->grip);
1331 pthread_cleanup_pop (1); // mutex unlock
1332 return rc;
1335 gpg_error_t
1336 getpin_common (assuan_context_t ctx, const char *filename, int which,
1337 char **rkey, size_t *rkeylen)
1339 gpg_error_t rc;
1340 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1341 struct pinentry_s *pin = pinentry_init (filename);
1343 if (!pin)
1344 return GPG_ERR_ENOMEM;
1346 if (client)
1347 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1349 rc = pinentry_lock (ctx, pin);
1350 if (!rc)
1351 rc = pinentry_getpin (pin, rkey, which);
1353 pinentry_deinit (pin);
1354 if (rc)
1355 return rc;
1357 *rkeylen = strlen (*rkey);
1358 if (!(*rkeylen))
1359 (*rkeylen)++;
1361 return rc;
1364 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1365 * both call xfree(). */
1366 gpg_error_t
1367 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1368 unsigned char **result, size_t *rlen)
1370 gpg_error_t rc;
1372 assuan_begin_confidential (ctx);
1373 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1374 assuan_end_confidential (ctx);
1375 return rc;
1378 gpg_error_t
1379 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1380 const char *filename, char **rkey, size_t *rkeylen)
1382 char *key = NULL;
1383 size_t keylen = 0;
1384 gpg_error_t rc = read_data_file (filename, crypto);
1385 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1386 void *salted_key = NULL;
1387 size_t keysize = 0;
1389 if (rc)
1391 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1392 return rc;
1395 key = config_get_string (filename, "passphrase");
1396 if (key)
1398 log_write (_("Trying the passphrase specified in config ..."));
1399 keylen = strlen (key);
1402 if (!key)
1404 key = config_get_string (filename, "passphrase_file");
1405 if (key)
1407 char *tmp = expand_homedir (key);
1408 int fd;
1409 struct stat st;
1411 xfree (key);
1412 key = tmp;
1413 log_write (_("Trying the passphrase using file '%s' ..."), key);
1414 fd = open (key, O_RDONLY);
1415 if (fd == -1)
1417 rc = gpg_error_from_syserror ();
1418 log_write ("%s: %s", key, pwmd_strerror (rc));
1419 xfree (key);
1420 return rc;
1423 stat (key, &st);
1424 xfree (key);
1425 key = xmalloc (st.st_size);
1426 if (key)
1428 if (read (fd, key, st.st_size) != st.st_size)
1430 log_write ("short read() count");
1431 rc = GPG_ERR_TOO_SHORT;
1434 else
1435 rc = GPG_ERR_ENOMEM;
1437 close (fd);
1439 if (rc)
1441 log_write ("%s", pwmd_strerror (rc));
1442 xfree (key);
1443 return rc;
1446 keylen = st.st_size;
1447 if (!keylen)
1449 tmp = xmalloc (1);
1450 *tmp = 0;
1451 xfree (key);
1452 key = tmp;
1453 keylen++;
1458 if (!key && !IS_PKCS (crypto) && inquire)
1460 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1461 &keylen);
1462 if (rc)
1464 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1465 return rc;
1468 if (!keylen)
1469 keylen++;
1471 else if (!key && !IS_PKCS (crypto))
1473 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1474 if (rc)
1476 log_write ("%s", pwmd_strerror (rc));
1477 return rc;
1480 #ifdef WITH_AGENT
1481 else if (key && IS_PKCS (crypto))
1483 rc = set_agent_passphrase (crypto, key, keylen);
1484 if (rc)
1486 xfree (key);
1487 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1488 return rc;
1491 #endif
1493 if (key && !IS_PKCS (crypto))
1495 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1496 keylen, &salted_key, &keysize);
1497 xfree (key);
1498 key = (char *)salted_key;
1499 keylen = keysize;
1500 if (rc)
1502 xfree (salted_key);
1503 return rc;
1507 xfree (crypto->filename);
1508 crypto->filename = str_dup (filename);
1509 rc = decrypt_data (ctx, crypto, (unsigned char *)key, keylen);
1510 if (rc)
1512 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1513 xfree (key);
1515 else
1517 *rkey = key;
1518 *rkeylen = keylen;
1521 return rc;