Write the data file header in big endian format.
[pwmd.git] / src / crypto.c
blob13d38c43fccee15d3372e1a35c9306deb1102ee4
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>
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 static gpg_error_t
68 read_header (file_header_t *hdr, int fd)
70 ssize_t len;
71 uint32_t i;
72 uint64_t n, x;
74 #ifdef WORDS_BIGENDIAN
75 len = read (fd, &hdr->magic, sizeof(hdr->magic));
76 if (len == -1)
77 goto done;
79 len = read (fd, &hdr->version, sizeof(hdr->version));
80 if (len == -1)
81 goto done;
83 len = read (fd, &hdr->iterations, sizeof(hdr->iterations));
84 if (len == -1)
85 goto done;
87 len = read (fd, &hdr->flags, sizeof(hdr->flags));
88 if (len == -1)
89 goto done;
91 len = read (fd, &hdr->iv, sizeof(hdr->iv));
92 if (len == -1)
93 goto done;
95 len = read (fd, &hdr->salt, sizeof(hdr->salt));
96 if (len == -1)
97 goto done;
99 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
100 if (len == -1)
101 goto done;
102 #else
103 len = read (fd, &hdr->magic, sizeof(hdr->magic));
104 if (len == -1)
105 goto done;
107 len = read (fd, &i, sizeof(hdr->version));
108 if (len == -1)
109 goto done;
110 hdr->version = ntohl (i);
112 len = read (fd, &n, sizeof(hdr->iterations));
113 if (len == -1)
114 goto done;
115 hdr->iterations = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
117 len = read (fd, &n, sizeof(hdr->flags));
118 if (len == -1)
119 goto done;
120 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
122 len = read (fd, &hdr->iv, sizeof(hdr->iv));
123 if (len == -1)
124 goto done;
126 len = read (fd, &hdr->salt, sizeof(hdr->salt));
127 if (len == -1)
128 goto done;
130 len = read (fd, &i, sizeof(hdr->datalen));
131 if (len == -1)
132 goto done;
133 hdr->datalen = ntohl (i);
134 #endif
136 done:
137 return len == -1 ? gpg_error_from_syserror () : 0;
140 gpg_error_t
141 read_data_header (const char *filename, file_header_t * rhdr,
142 struct stat *rst, int *rfd)
144 gpg_error_t rc = 0;
145 size_t len;
146 struct stat st;
147 file_header_t hdr;
148 int fd;
150 if (lstat (filename, &st) == -1)
151 return gpg_error_from_syserror ();
153 if (!S_ISREG (st.st_mode))
154 return GPG_ERR_ENOANO;
156 fd = open (filename, O_RDONLY);
157 if (fd == -1)
158 return gpg_error_from_syserror ();
160 rc = read_header (&hdr, fd);
161 if (!rc && memcmp (hdr.magic, pwmd_magic, sizeof (hdr.magic)))
162 rc = GPG_ERR_BAD_DATA;
163 else if (hdr.version < 0x030000)
164 rc = GPG_ERR_UNKNOWN_VERSION;
166 if (rc)
167 close (fd);
168 else
170 if (rhdr)
171 *rhdr = hdr;
172 if (rst)
173 *rst = st;
174 if (rfd)
175 *rfd = fd;
176 else
177 close (fd);
180 return rc;
183 gpg_error_t
184 read_data_file (const char *filename, struct crypto_s * crypto)
186 int fd;
187 gpg_error_t rc = 0;
188 size_t len, rlen;
189 char *buf = NULL;
190 struct stat st;
192 cleanup_crypto_stage1 (crypto);
193 rc = read_data_header (filename, &crypto->hdr, &st, &fd);
194 if (rc)
195 return rc;
197 crypto->ciphertext_len = crypto->hdr.datalen;
198 crypto->ciphertext = xmalloc (crypto->hdr.datalen);
199 if (!crypto->ciphertext)
201 rc = GPG_ERR_ENOMEM;
202 goto fail;
205 if (crypto->hdr.flags & PWMD_FLAG_PKCS)
207 rlen = read (fd, crypto->grip, 20);
208 if (rlen != 20)
210 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
211 goto fail;
214 rlen = read (fd, crypto->sign_grip, 20);
215 if (rlen != 20)
217 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
218 goto fail;
222 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
223 if (len != crypto->hdr.datalen)
225 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
226 goto fail;
229 if (!(crypto->hdr.flags & PWMD_FLAG_PKCS))
230 goto fail;
232 #ifndef WITH_AGENT
233 rc = GPG_ERR_NOT_IMPLEMENTED;
234 goto fail;
235 #else
236 if (!use_agent)
237 return GPG_ERR_NOT_IMPLEMENTED;
239 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
240 buf = xmalloc (len);
241 if (!buf)
243 rc = GPG_ERR_ENOMEM;
244 goto fail;
247 rlen = read (fd, buf, len);
248 if (rlen != len)
250 rc = rc == -1 ? gpg_error_from_syserror () : GPG_ERR_BAD_DATA;
251 goto fail;
254 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
255 if (rc)
256 goto fail;
258 if (crypto->pkey_sexp)
259 gcry_sexp_release (crypto->pkey_sexp);
261 if (crypto->sigpkey_sexp)
262 gcry_sexp_release (crypto->sigpkey_sexp);
264 crypto->pkey_sexp = crypto->sigpkey_sexp = NULL;
265 rc = get_pubkey_bin (crypto, crypto->grip, &crypto->pkey_sexp);
266 if (!rc)
267 rc = get_pubkey_bin (crypto, crypto->sign_grip, &crypto->sigpkey_sexp);
268 #endif
270 fail:
271 close (fd);
272 xfree (buf);
273 return rc;
276 #define CRYPTO_BLOCKSIZE(c) (blocksize * 1024)
279 * Useful for a large amount of data. Rather than doing all of the data in one
280 * iteration do it in chunks. This lets the command be cancelable rather than
281 * waiting for it to complete.
283 static gpg_error_t
284 iterate_crypto_once (gcry_cipher_hd_t h, unsigned char *inbuf,
285 size_t insize, size_t blocksize, status_msg_t which)
287 gpg_error_t rc = 0;
288 off_t len = CRYPTO_BLOCKSIZE (blocksize);
289 void *p = gcry_malloc (len);
290 off_t total = 0;
291 unsigned char *inbuf2;
293 if (!p)
294 return GPG_ERR_ENOMEM;
296 if (insize < CRYPTO_BLOCKSIZE (blocksize))
297 len = insize;
299 pthread_cleanup_push (gcry_free, p);
301 for (;;)
303 inbuf2 = inbuf + total;
304 unsigned char *tmp;
306 if (len + total > insize)
307 len = blocksize;
309 if (which == STATUS_ENCRYPT)
310 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
311 else
312 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
314 if (rc)
315 break;
317 tmp = inbuf + total;
318 memmove (tmp, p, len);
319 total += len;
320 if (total >= insize)
321 break;
323 #ifdef HAVE_PTHREAD_TESTCANCEL
324 pthread_testcancel ();
325 #endif
328 pthread_cleanup_pop (1);
329 return rc;
332 static void
333 cleanup_cipher (void *arg)
335 gcry_cipher_close ((gcry_cipher_hd_t) arg);
338 gpg_error_t
339 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
340 unsigned char *salted_key, size_t skeylen)
342 gpg_error_t rc = 0;
343 unsigned char *key = salted_key;
344 gcry_cipher_hd_t h = NULL;
345 size_t blocksize, keysize = 0;
346 int algo = cipher_to_gcrypt (crypto->hdr.flags);
347 void *outbuf = NULL;
348 uint64_t n = crypto->hdr.iterations;
349 long progress = 0;
350 #ifdef WITH_AGENT
351 size_t keylen = skeylen;
352 gcry_sexp_t sig_sexp;
354 if (crypto->hdr.flags & PWMD_FLAG_PKCS)
356 rc = agent_extract_key (crypto, &key, &keylen);
357 if (rc)
358 return rc;
360 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
361 if (!sig_sexp)
363 gcry_free (key);
364 return GPG_ERR_BAD_DATA;
367 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
368 crypto->ciphertext_len);
369 gcry_sexp_release (sig_sexp);
371 #endif
373 if (!rc)
375 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
376 if (!rc)
378 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
379 &keysize);
380 if (!rc)
382 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
383 &blocksize);
384 if (!rc)
386 rc = gcry_cipher_setiv (h, crypto->hdr.iv,
387 sizeof (crypto->hdr.iv));
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, sizeof (crypto->hdr.iv));
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;