Add ACL tests.
[pwmd.git] / src / crypto.c
blob51ca0218aed70eba676dde4ac4e55a404ac88c2c
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
32 #include "pwmd-error.h"
33 #include "util-misc.h"
34 #include "common.h"
35 #include "rcfile.h"
36 #include "pinentry.h"
37 #include "crypto.h"
38 #include "cache.h"
39 #include "mem.h"
40 #include "util-string.h"
42 static uint8_t pwmd_magic[5] = { '\177', 'P', 'W', 'M', 'D' };
44 /* Sets the default cipher values for new files. */
45 void
46 set_header_defaults (file_header_t * hdr)
48 char *s = config_get_string (NULL, "cipher");
49 int flags = cipher_string_to_cipher (s);
51 xfree (s);
52 memset (hdr, 0, sizeof (file_header_t));
53 memcpy (hdr->magic, pwmd_magic, sizeof (hdr->magic));
54 if (flags == -1)
55 log_write (_
56 ("Invalid 'cipher' in configuration file. Using a default of aes256."));
57 hdr->flags = flags == -1 ? PWMD_CIPHER_AES256 : flags;
58 hdr->version = VERSION_HEX;
60 #ifdef WITH_AGENT
61 if (use_agent)
62 hdr->flags |= PWMD_FLAG_PKI;
63 #endif
66 static gpg_error_t
67 read_header (file_header_t *hdr, int fd)
69 ssize_t len;
70 uint32_t i;
71 uint64_t n;
73 #ifdef WORDS_BIGENDIAN
74 len = read (fd, &hdr->magic, sizeof(hdr->magic));
75 if (len == -1)
76 goto done;
78 len = read (fd, &hdr->version, sizeof(hdr->version));
79 if (len == -1)
80 goto done;
82 len = read (fd, &hdr->iterations, sizeof(hdr->iterations));
83 if (len == -1)
84 goto done;
86 len = read (fd, &hdr->flags, sizeof(hdr->flags));
87 if (len == -1)
88 goto done;
90 len = read (fd, &hdr->iv, sizeof(hdr->iv));
91 if (len == -1)
92 goto done;
94 len = read (fd, &hdr->salt, sizeof(hdr->salt));
95 if (len == -1)
96 goto done;
98 len = read (fd, &hdr->datalen, sizeof(hdr->datalen));
99 if (len == -1)
100 goto done;
101 #else
102 len = read (fd, &hdr->magic, sizeof(hdr->magic));
103 if (len == -1)
104 goto done;
106 len = read (fd, &i, sizeof(hdr->version));
107 if (len == -1)
108 goto done;
109 hdr->version = ntohl (i);
111 len = read (fd, &n, sizeof(hdr->iterations));
112 if (len == -1)
113 goto done;
114 hdr->iterations = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
116 len = read (fd, &n, sizeof(hdr->flags));
117 if (len == -1)
118 goto done;
119 hdr->flags = (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
121 len = read (fd, &hdr->iv, sizeof(hdr->iv));
122 if (len == -1)
123 goto done;
125 len = read (fd, &hdr->salt, sizeof(hdr->salt));
126 if (len == -1)
127 goto done;
129 len = read (fd, &i, sizeof(hdr->datalen));
130 if (len == -1)
131 goto done;
132 hdr->datalen = ntohl (i);
133 #endif
135 done:
136 return len == -1 ? gpg_error_from_errno (errno) : 0;
139 /* Read the header of a data file to determine cipher and other. The
140 * header is stored big endian in the file and is converted to little
141 * endian when needed. */
142 gpg_error_t
143 read_data_header (const char *filename, file_header_t * rhdr,
144 struct stat *rst, int *rfd)
146 gpg_error_t rc = 0;
147 struct stat st;
148 file_header_t hdr;
149 int fd;
151 if (lstat (filename, &st) == -1)
152 return gpg_error_from_errno (errno);
154 if (!S_ISREG (st.st_mode))
155 return gpg_error (GPG_ERR_ENOANO);
157 fd = open (filename, O_RDONLY);
158 if (fd == -1)
159 return gpg_error_from_errno (errno);
161 rc = read_header (&hdr, fd);
162 if (!rc && memcmp (hdr.magic, pwmd_magic, sizeof (hdr.magic)))
163 rc = GPG_ERR_BAD_DATA;
164 else if (!rc && hdr.version < 0x030000)
165 rc = GPG_ERR_UNKNOWN_VERSION;
167 if (rc)
168 close (fd);
169 else
171 if (rhdr)
172 *rhdr = hdr;
173 if (rst)
174 *rst = st;
175 if (rfd)
176 *rfd = fd;
177 else
178 close (fd);
181 return gpg_error (rc);
184 gpg_error_t
185 read_data_file (const char *filename, struct crypto_s * crypto)
187 int fd;
188 gpg_error_t rc = 0;
189 size_t len, rlen;
190 char *buf = NULL;
191 struct stat st;
193 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 done;
206 /* The keygrips for PKI files are stored after the header. They are
207 * stored in the file to let file(1) magic(5) show the grips. */
208 if (crypto->hdr.flags & PWMD_FLAG_PKI)
210 rlen = read (fd, crypto->grip, 20);
211 if (rlen != 20)
213 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
214 goto done;
217 rlen = read (fd, crypto->sign_grip, 20);
218 if (rlen != 20)
220 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
221 goto done;
225 len = read (fd, crypto->ciphertext, crypto->hdr.datalen);
226 if (len != crypto->hdr.datalen)
228 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
229 goto done;
232 if (!(crypto->hdr.flags & PWMD_FLAG_PKI))
233 goto done;
235 if (!use_agent)
237 rc = GPG_ERR_NOT_IMPLEMENTED;
238 goto done;
241 #ifdef WITH_AGENT
242 len = st.st_size - sizeof (file_header_t) - crypto->hdr.datalen - 40;
243 buf = xmalloc (len);
244 if (!buf)
246 rc = GPG_ERR_ENOMEM;
247 goto done;
250 /* Remaining data file bytes are the encrypted key and XML. */
251 rlen = read (fd, buf, len);
252 if (rlen != len)
254 rc = rc == -1 ? gpg_error_from_errno (errno) : GPG_ERR_BAD_DATA;
255 goto done;
258 rc = gcry_sexp_new (&crypto->ciphertext_sexp, buf, rlen, 1);
259 if (rc)
260 goto done;
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 done:
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;
299 if (!p)
300 return gpg_error (GPG_ERR_ENOMEM);
302 if (insize < CRYPTO_BLOCKSIZE (blocksize))
303 len = insize;
305 pthread_cleanup_push (gcry_free, p);
307 for (;;)
309 unsigned char *inbuf2 = inbuf + total;
310 unsigned char *tmp;
312 if (len + total > insize)
313 len = blocksize;
315 if (which == STATUS_ENCRYPT)
316 rc = gcry_cipher_encrypt (h, p, len, inbuf2, len);
317 else
318 rc = gcry_cipher_decrypt (h, p, len, inbuf2, len);
320 if (rc)
321 break;
323 tmp = inbuf + total;
324 memmove (tmp, p, len);
325 total += len;
326 if (total >= insize)
327 break;
329 #ifdef HAVE_PTHREAD_TESTCANCEL
330 pthread_testcancel ();
331 #endif
334 pthread_cleanup_pop (1);
335 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
336 rc = gpg_error (rc);
338 return rc;
341 static void
342 cleanup_cipher (void *arg)
344 gcry_cipher_close ((gcry_cipher_hd_t) arg);
347 /* Decrypt the XML data. For PKI data files the key is retrieved from
348 * gpg-agent and the signature verified. */
349 gpg_error_t
350 decrypt_data (assuan_context_t ctx, struct crypto_s *crypto,
351 unsigned char *salted_key, size_t skeylen)
353 gpg_error_t rc = 0;
354 unsigned char *key = salted_key;
355 gcry_cipher_hd_t h = NULL;
356 size_t blocksize, keysize = 0;
357 int algo = cipher_to_gcrypt (crypto->hdr.flags);
358 void *outbuf = NULL;
359 uint64_t n = crypto->hdr.iterations;
360 long progress = 0;
361 #ifdef WITH_AGENT
362 size_t keylen = skeylen;
363 gcry_sexp_t sig_sexp;
365 if (crypto->hdr.flags & PWMD_FLAG_PKI)
367 rc = agent_extract_key (crypto, &key, &keylen);
368 if (rc)
369 return rc;
371 sig_sexp = gcry_sexp_find_token (crypto->ciphertext_sexp, "sig-val", 0);
372 if (!sig_sexp)
374 gcry_free (key);
375 return GPG_ERR_BAD_DATA;
378 rc = agent_verify (crypto->sigpkey_sexp, sig_sexp, crypto->ciphertext,
379 crypto->ciphertext_len);
380 gcry_sexp_release (sig_sexp);
382 #endif
384 if (!rc)
386 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
387 if (!rc)
389 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL,
390 &keysize);
391 if (!rc)
393 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL,
394 &blocksize);
395 if (!rc)
397 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
398 if (!rc)
400 rc = gcry_cipher_setkey (h, key, keysize);
407 pthread_cleanup_push (cleanup_cipher, rc ? NULL : h);
409 if (!rc)
411 outbuf = gcry_malloc (crypto->hdr.datalen);
412 if (!outbuf)
413 rc = GPG_ERR_ENOMEM;
416 pthread_cleanup_push (gcry_free, outbuf);
417 #ifdef WITH_AGENT
418 pthread_cleanup_push (gcry_free, key);
419 #endif
421 if (!rc)
423 memcpy (outbuf, crypto->ciphertext, crypto->hdr.datalen);
424 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
425 STATUS_DECRYPT);
426 if (!rc)
428 key[0] ^= 1;
429 rc = gcry_cipher_setkey (h, key, keysize);
433 if (!rc)
435 progress = config_get_long (NULL, "cipher_progress");
436 if (progress == -1)
437 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
440 if (!rc && ctx && crypto->hdr.iterations)
441 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", 0,
442 crypto->hdr.iterations);
444 for (n = 0; !rc && n < crypto->hdr.iterations; n++)
446 if (ctx && !(n % progress))
448 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
449 crypto->hdr.iterations);
450 if (rc)
451 break;
454 rc = gcry_cipher_setiv (h, crypto->hdr.iv, blocksize);
455 if (rc)
456 break;
458 rc = iterate_crypto_once (h, outbuf, crypto->hdr.datalen, blocksize,
459 STATUS_DECRYPT);
462 if (!rc && ctx && crypto->hdr.iterations)
463 rc = send_status (ctx, STATUS_DECRYPT, "%llu %llu", n,
464 crypto->hdr.iterations);
466 #ifdef WITH_AGENT
467 pthread_cleanup_pop (0);
468 if (crypto->hdr.flags & PWMD_FLAG_PKI)
469 gcry_free (key);
470 else if (key)
471 key[0] ^= 1;
472 #else
473 key[0] ^= 1;
474 #endif
475 pthread_cleanup_pop (rc ? 1 : 0); /* outbuf */
476 pthread_cleanup_pop (1); /* cipher */
477 if (!rc)
479 char buf[] = "<?xml ";
481 if (memcmp (outbuf, buf, sizeof(buf)-1))
483 gcry_free (outbuf);
484 return gpg_error (GPG_ERR_BAD_PASSPHRASE);
487 crypto->plaintext = outbuf;
488 crypto->plaintext_len = crypto->hdr.datalen;
491 if (rc && gpg_err_source (rc) == GPG_ERR_SOURCE_UNKNOWN)
492 rc = gpg_error (rc);
494 return rc;
497 /* The cached document is encrypted with encrypt_xml(). This decrypts
498 * it from the OPEN command. */
499 gpg_error_t
500 decrypt_cache (struct crypto_s * crypto, const void *data, size_t len)
502 gcry_cipher_hd_t h = NULL;
503 gpg_error_t rc;
505 rc = gcry_cipher_open (&h, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
506 if (rc)
507 return rc;
509 gcry_free (crypto->plaintext);
510 crypto->plaintext = gcry_malloc (len);
511 if (!crypto->plaintext)
513 rc = GPG_ERR_ENOMEM;
514 goto done;
517 rc = gcry_cipher_setiv (h, cache_iv, cache_blocksize);
518 if (rc)
519 goto done;
521 rc = gcry_cipher_setkey (h, cache_key, cache_keysize);
522 if (rc)
523 goto done;
525 rc = gcry_cipher_decrypt (h, crypto->plaintext, len, data, len);
526 if (rc || strncmp (crypto->plaintext, "<?xml ", 6))
528 if (!rc)
529 rc = GPG_ERR_BAD_DATA;
531 gcry_free (crypto->plaintext);
532 crypto->plaintext = NULL;
535 crypto->plaintext_len = len;
537 done:
538 if (h)
539 gcry_cipher_close (h);
541 return rc;
544 /* Encrypt the XML data and set 'result'. At least one encryption
545 * iteration is done. */
546 gpg_error_t
547 encrypt_xml (assuan_context_t ctx, void *key, size_t keylen,
548 int algo, const void *xml, size_t len, void * *result,
549 size_t *result_len, unsigned char **iv, size_t * iv_len,
550 uint64_t iter)
552 gpg_error_t rc;
553 gcry_cipher_hd_t h;
554 size_t blocksize, keysize;
555 void *inbuf = NULL;
556 size_t olen = len;
557 uint64_t n = 0;
558 unsigned char *tmpkey = NULL;
559 int init_iv = *(iv_len) == 0;
561 rc = gcry_cipher_open (&h, algo, GCRY_CIPHER_MODE_CBC, 0);
562 if (rc)
563 return rc;
565 pthread_cleanup_push (cleanup_cipher, h);
566 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
567 if (!rc)
568 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_BLKLEN, NULL, &blocksize);
570 if (!rc && init_iv)
572 *(iv) = xmalloc (blocksize);
573 if (!*(iv))
574 rc = GPG_ERR_ENOMEM;
576 gcry_create_nonce (*(iv), blocksize);
579 if (!rc)
581 if (init_iv)
582 *iv_len = blocksize;
584 tmpkey = gcry_malloc (keysize);
585 if (!tmpkey)
586 rc = GPG_ERR_ENOMEM;
589 pthread_cleanup_push (gcry_free, tmpkey);
591 if (!rc)
593 memcpy (tmpkey, key, keysize);
594 tmpkey[0] ^= 1;
595 rc = gcry_cipher_setkey (h, tmpkey, keysize);
596 if (!rc)
598 if (len % blocksize)
599 len += blocksize - (len % blocksize);
603 if (!rc)
605 inbuf = gcry_malloc (len);
606 if (!inbuf)
607 rc = GPG_ERR_ENOMEM;
610 pthread_cleanup_push (gcry_free, inbuf);
612 if (!rc)
614 long progress = config_get_long (NULL, "cipher_progress");
616 memset (inbuf, 0, len);
617 memcpy (inbuf, xml, olen);
619 if (progress == -1)
620 progress = strtol (DEFAULT_ITERATION_PROGRESS, NULL, 10);
622 if (!rc && ctx && iter)
623 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", 0, iter);
625 for (n = 0; !rc && n < iter; n++)
627 if (ctx && !(n % progress))
629 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
630 if (rc)
631 break;
634 rc = gcry_cipher_setiv (h, *(iv), blocksize);
635 if (rc)
636 break;
638 rc = iterate_crypto_once (h, inbuf, len, blocksize, STATUS_ENCRYPT);
642 if (!rc && ctx && iter)
643 rc = send_status (ctx, STATUS_ENCRYPT, "%llu %llu", n, iter);
645 if (!rc)
647 /* Do at least one iteration. */
648 rc = gcry_cipher_setiv (h, *(iv), blocksize);
649 if (!rc)
651 rc = gcry_cipher_setkey (h, key, keysize);
652 if (!rc)
653 rc = iterate_crypto_once (h, inbuf, len, blocksize,
654 STATUS_ENCRYPT);
658 pthread_cleanup_pop (rc ? 1 : 0); /* inbuf */
659 pthread_cleanup_pop (1); /* tmpkey */
660 pthread_cleanup_pop (1); /* cipher */
662 if (rc && init_iv)
664 xfree (*(iv));
665 *iv = NULL;
668 *result = rc ? NULL : inbuf;
669 *result_len = len;
670 return rc;
673 void
674 cleanup_save (struct save_s *save)
676 if (!save)
677 return;
679 #ifdef WITH_AGENT
680 if (save->pkey)
681 gcry_sexp_release (save->pkey);
683 if (save->sigpkey)
684 gcry_sexp_release (save->sigpkey);
685 #endif
687 memset (save, 0, sizeof (struct save_s));
690 /* Keep the agent ctx to retain pinentry options which will be freed in
691 * cleanup_cb(). Also keep .pubkey since it may be needed for a SAVE. */
692 void
693 cleanup_crypto_stage1 (struct crypto_s *cr)
695 if (!cr)
696 return;
698 cleanup_save (&cr->save);
700 #ifdef WITH_AGENT
701 if (cr->ciphertext_sexp)
702 gcry_sexp_release (cr->ciphertext_sexp);
704 cr->ciphertext_sexp = NULL;
705 #endif
707 gcry_free (cr->plaintext);
708 xfree (cr->ciphertext);
709 xfree (cr->filename);
710 cr->filename = NULL;
711 cr->ciphertext = NULL;
712 cr->ciphertext_len = 0;
713 cr->plaintext = NULL;
714 cr->plaintext_len = 0;
717 void
718 cleanup_crypto_stage2 (struct crypto_s *cr)
720 if (!cr)
721 return;
723 cleanup_crypto_stage1 (cr);
724 set_header_defaults (&cr->hdr);
727 void
728 cleanup_crypto (struct crypto_s **c)
730 struct crypto_s *cr = *c;
732 if (!cr)
733 return;
735 cleanup_crypto_stage2 (cr);
737 #ifdef WITH_AGENT
738 if (cr->pkey_sexp)
739 gcry_sexp_release (cr->pkey_sexp);
741 if (cr->sigpkey_sexp)
742 gcry_sexp_release (cr->sigpkey_sexp);
744 if (cr->agent)
745 cleanup_agent (cr->agent);
746 #endif
748 xfree (cr);
749 *c = NULL;
752 gpg_error_t
753 init_client_crypto (struct crypto_s **crypto)
755 struct crypto_s *new = xcalloc (1, sizeof (struct crypto_s));
756 gpg_error_t rc;
758 if (!new)
760 rc = GPG_ERR_ENOMEM;
761 return rc;
764 #ifdef WITH_AGENT
765 if (use_agent)
767 rc = agent_init (&new->agent);
768 if (!rc)
770 rc = send_agent_common_options (new->agent);
771 if (!rc)
772 rc = agent_set_pinentry_options (new->agent);
775 if (rc)
777 cleanup_agent (new->agent);
778 xfree (new);
779 return rc;
782 #endif
784 set_header_defaults (&new->hdr);
785 *crypto = new;
786 return 0;
789 static gpg_error_t
790 try_decrypt (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
791 const char *filename, char **key, size_t *keylen)
793 gpg_error_t rc;
794 int pin_try = 1;
795 int pin_tries = 3;
796 char *pin_title = NULL;
797 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
801 rc = decrypt_common (ctx, inquire, crypto, filename, key, keylen);
802 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE && ctx)
804 if (pin_try == 1)
805 pin_title = client->pinentry_opts.title;
807 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try+1, pin_tries);
810 while (!inquire && gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
811 && ++pin_try <= pin_tries);
813 if (ctx && pin_title != client->pinentry_opts.title)
815 xfree (client->pinentry_opts.title);
816 client->pinentry_opts.title = pin_title;
819 return rc;
822 /* Common to both PKI and non-PKI files when saving a data
823 * file. Defers to gpg-agent when needed and handles keyfiles. */
824 gpg_error_t
825 export_common (assuan_context_t ctx, int inquire, struct crypto_s * crypto,
826 const void *data, size_t datalen, const char *outfile,
827 const char *keyfile, void **rkey, size_t *rkeylen,
828 int use_cache, int force, int no_passphrase)
830 gpg_error_t rc = 0;
831 void *enc_xml = NULL;
832 size_t enc_xml_len = 0;
833 unsigned char *iv = NULL;
834 size_t iv_len = 0;
835 int algo = cipher_to_gcrypt (crypto->save.hdr.flags);
836 void *key = NULL, *salted_key = NULL;
837 size_t keysize, keylen;
838 int cached = 0;
840 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &keysize);
841 if (rc)
842 return rc;
844 if (keyfile)
846 int fd;
847 unsigned char *buf;
848 struct stat st;
850 if (stat (keyfile, &st) == -1)
851 return gpg_error_from_errno (errno);
853 buf = gcry_malloc (st.st_size);
854 if (!buf)
855 return GPG_ERR_ENOMEM;
857 fd = open (keyfile, O_RDONLY);
858 if (fd == -1)
859 rc = gpg_error_from_errno (errno);
860 else
862 size_t len = read (fd, buf, st.st_size);
864 if (len != st.st_size)
865 rc = GPG_ERR_TOO_SHORT;
868 if (fd != -1)
869 close (fd);
871 key = buf;
872 keylen = st.st_size;
873 log_write (_("Using passphrase obtained from file '%s'"), keyfile);
875 if (!keylen)
877 char *tmp;
879 gcry_free (key);
880 tmp = gcry_malloc (1);
881 *tmp = 0;
882 key = tmp;
883 keylen++;
886 else
888 if (use_cache)
890 int defer = -1;
892 cache_lock ();
893 rc = cache_iscached (outfile, &defer);
894 if (!rc)
895 cached = 1;
896 else if (gpg_err_code (rc) == GPG_ERR_ENOENT
897 || gpg_err_code (rc) == GPG_ERR_NO_DATA)
898 rc = 0;
900 if (cached)
902 struct cache_data_s *cdata = cache_get_data_filename (outfile);
904 salted_key = gcry_malloc (cdata->keylen);
905 if (salted_key)
907 memcpy (salted_key, cdata->key, cdata->keylen);
908 keysize = cdata->keylen;
910 else
911 rc = GPG_ERR_ENOMEM;
914 cache_unlock ();
917 if (!rc && !cached)
919 if (force) // SAVE
921 struct crypto_s *tmp = NULL;
922 gpg_error_t rc = init_client_crypto (&tmp);
924 if (!rc)
926 rc = read_data_file (outfile, tmp);
927 if (!rc)
929 rc = try_decrypt (ctx, inquire, tmp, outfile,
930 (char **)&key, &keylen);
931 if (rc)
932 gcry_free (key);
936 cleanup_crypto (&tmp);
937 if (rc && gpg_err_code (rc) == GPG_ERR_ENOENT)
938 use_cache = 0;
939 else if (rc)
940 return rc;
943 if (!use_cache && !no_passphrase) // PASSWD or new file
945 gcry_free (key);
946 if (inquire)
948 rc = inquire_passphrase (ctx, "NEW_PASSPHRASE",
949 (unsigned char **)&key, &keylen);
951 else
953 rc = getpin_common (ctx, outfile, PINENTRY_SAVE,
954 (char **)&key, &keylen);
957 if (rc)
958 return rc;
960 else
962 if (no_passphrase)
964 keylen = 1;
965 key = gcry_malloc (keylen);
966 memset (key, 0, keylen);
968 else
970 salted_key = key;
971 keysize = keylen;
972 cached = 1;
978 if (!rc && !cached)
980 rc = hash_key (algo, crypto->save.hdr.salt,
981 sizeof(crypto->save.hdr.salt), key, keylen, &salted_key,
982 &keysize);
983 gcry_free (key);
986 if (!rc)
987 rc = encrypt_xml (ctx, salted_key, keysize, algo, data, datalen,
988 &enc_xml, &enc_xml_len, &iv, &iv_len,
989 crypto->save.hdr.iterations);
991 if (!rc)
993 if (no_passphrase && !(crypto->save.hdr.flags & PWMD_FLAG_PKI))
994 crypto->save.hdr.flags |= PWMD_FLAG_NO_PASSPHRASE;
996 memcpy (crypto->save.hdr.iv, iv, iv_len);
997 xfree (iv);
998 crypto->save.hdr.datalen = enc_xml_len;
999 rc = write_file (crypto, outfile, enc_xml, enc_xml_len, NULL, 0, NULL,
1000 NULL);
1001 gcry_free (enc_xml);
1002 if (!rc)
1004 *rkey = salted_key;
1005 *rkeylen = keysize;
1006 memcpy (&crypto->hdr, &crypto->save.hdr, sizeof (file_header_t));
1010 if (rc)
1011 gcry_free (salted_key);
1013 return rc;
1016 static gpg_error_t
1017 write_header (struct crypto_s *crypto, int fd)
1019 ssize_t len;
1020 uint64_t n, x;
1021 uint32_t i;
1023 #ifdef WORDS_BIGENDIAN
1024 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1025 if (len == -1)
1026 goto done;
1028 len = write (fd, &crypto->save.hdr.version, sizeof(crypto->save.hdr.version));
1029 if (len == -1)
1030 goto done;
1032 len = write (fd, &crypto->save.hdr.iterations,
1033 sizeof(crypto->save.hdr.iterations));
1034 if (len == -1)
1035 goto done;
1037 len = write (fd, &crypto->save.hdr.flags, sizeof(crypto->save.hdr.flags));
1038 if (len == -1)
1039 goto done;
1041 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1042 if (len == -1)
1043 goto done;
1045 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1046 if (len == -1)
1047 goto done;
1049 len = write (fd, &crypto->save.hdr.datalen, sizeof(crypto->save.hdr.datalen));
1050 if (len == -1)
1051 goto done;
1052 #else
1053 len = write (fd, &crypto->save.hdr.magic, sizeof(crypto->save.hdr.magic));
1054 if (len == -1)
1055 goto done;
1057 i = htonl (crypto->save.hdr.version);
1058 len = write (fd, &i, sizeof(i));
1059 if (len == -1)
1060 goto done;
1062 n = crypto->save.hdr.iterations;
1063 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1064 len = write (fd, &x, sizeof(x));
1065 if (len == -1)
1066 goto done;
1068 n = crypto->save.hdr.flags;
1069 x = (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
1070 len = write (fd, &x, sizeof(x));
1071 if (len == -1)
1072 goto done;
1074 len = write (fd, &crypto->save.hdr.iv, sizeof(crypto->save.hdr.iv));
1075 if (len == -1)
1076 goto done;
1078 len = write (fd, &crypto->save.hdr.salt, sizeof(crypto->save.hdr.salt));
1079 if (len == -1)
1080 goto done;
1082 i = htonl (crypto->save.hdr.datalen);
1083 len = write (fd, &i, sizeof(i));
1084 if (len == -1)
1085 goto done;
1086 #endif
1088 done:
1089 return len == -1 ? gpg_error_from_errno (errno) : 0;
1092 /* Write the data structures to disk. */
1093 gpg_error_t
1094 write_file (struct crypto_s *crypto, const char *filename,
1095 void *data, size_t data_len, void *sexp, size_t sexp_len,
1096 void *pubkey, void *sigpkey)
1098 char tmp[FILENAME_MAX] = { 0 };
1099 mode_t mode = 0;
1100 struct stat st;
1101 int fd;
1102 gpg_error_t rc = 0;
1104 if (filename)
1106 if (lstat (filename, &st) == 0)
1108 mode = st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1110 if (!(mode & S_IWUSR))
1111 return GPG_ERR_EACCES;
1113 else if (errno != ENOENT)
1114 return gpg_error_from_errno (errno);
1116 snprintf (tmp, sizeof (tmp), "%s.XXXXXX", filename);
1117 fd = mkstemp (tmp);
1118 if (fd == -1)
1120 rc = gpg_error_from_errno (errno);
1121 log_write ("%s: %s", tmp, pwmd_strerror (rc));
1122 return rc;
1125 else
1127 // xml_import() or convert_file() from command line.
1128 fd = STDOUT_FILENO;
1131 pthread_cleanup_push (cleanup_unlink_cb, tmp);
1132 crypto->save.hdr.version = VERSION_HEX;
1133 rc = write_header (crypto, fd);
1134 if (!rc)
1136 size_t len;
1138 if (crypto->save.hdr.flags & PWMD_FLAG_PKI)
1140 unsigned char grip[20];
1142 gcry_pk_get_keygrip ((gcry_sexp_t) pubkey, grip);
1143 len = write (fd, grip, sizeof (grip));
1144 if (len == sizeof (grip))
1146 gcry_pk_get_keygrip ((gcry_sexp_t) sigpkey, grip);
1147 len = write (fd, grip, sizeof (grip));
1148 if (len == sizeof (grip))
1150 len = write (fd, data, data_len);
1151 if (len == data_len)
1153 len = write (fd, sexp, sexp_len);
1154 if (len != sexp_len)
1155 rc = gpg_error_from_errno (errno);
1157 else
1158 rc = gpg_error_from_errno (errno);
1161 else
1162 rc = gpg_error_from_errno (errno);
1164 else
1166 len = write (fd, data, data_len);
1167 if (len != data_len)
1168 rc = gpg_error_from_errno (errno);
1172 if (!rc)
1174 if (fsync (fd) != -1)
1176 if (filename && close (fd) != -1)
1179 if (mode && config_get_boolean (filename, "backup"))
1181 char tmp2[FILENAME_MAX];
1183 snprintf (tmp2, sizeof (tmp2), "%s.backup", filename);
1184 if (rename (filename, tmp2) == -1)
1185 rc = gpg_error_from_errno (errno);
1188 else if (filename)
1189 rc = gpg_error_from_errno (errno);
1191 else
1192 rc = gpg_error_from_errno (errno);
1195 if (!rc)
1197 if (filename && rename (tmp, filename) != -1)
1199 if (filename && mode)
1200 chmod (filename, mode);
1203 else
1204 rc = gpg_error_from_errno (errno);
1207 pthread_cleanup_pop (rc ? 1 : 0); // unlink
1208 return rc;
1211 gpg_error_t
1212 hash_key (int algo, unsigned char *salt, size_t salt_len, const void *key,
1213 size_t keylen, void **result, size_t *rlen)
1215 gpg_error_t rc;
1216 void *tmp;
1218 /* Be sure the algorithm is available. */
1219 rc = gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, rlen);
1220 if (rc)
1221 return rc;
1223 /* Always allocate enough for a 256-bit key although the algorithms
1224 themselves may use less. Fixes SAVE --cipher with a different
1225 keylen than the previously saved cipher when cached. */
1226 *rlen = 32;
1227 tmp = xmalloc (*rlen);
1228 if (!tmp)
1229 return GPG_ERR_ENOMEM;
1231 rc = gcry_kdf_derive(key, keylen, GCRY_KDF_ITERSALTED_S2K, GCRY_MD_SHA1,
1232 salt, salt_len, DEFAULT_KDFS2K_ITERATIONS, *rlen, tmp);
1233 if (!rc)
1234 *result = tmp;
1235 else
1236 xfree (tmp);
1238 return rc;
1241 /* The PASSWD command when not using gpg-agent. */
1242 gpg_error_t
1243 change_passwd (assuan_context_t ctx, const char *filename, int inquire,
1244 struct crypto_s **rcrypto, int no_passphrase)
1246 unsigned char *key = NULL;
1247 size_t keylen = 0;
1248 struct crypto_s *crypto = NULL;
1249 gpg_error_t rc = init_client_crypto (&crypto);
1250 int cached;
1252 if (rc)
1253 return rc;
1255 crypto->client_ctx = ctx;
1256 rc = read_data_file (filename, crypto);
1257 if (rc)
1259 cleanup_crypto (&crypto);
1260 return rc;
1263 rc = try_decrypt (ctx, inquire, crypto, filename, (char **)&key, &keylen);
1264 if (rc)
1266 cleanup_crypto (&crypto);
1267 return rc;
1270 gcry_free (key);
1271 key = NULL;
1273 if (!rc)
1275 memcpy (&crypto->save.hdr, &crypto->hdr, sizeof (file_header_t));
1277 if (!no_passphrase)
1278 crypto->save.hdr.flags &= ~PWMD_FLAG_NO_PASSPHRASE;
1280 rc = export_common (ctx, inquire, crypto, crypto->plaintext,
1281 crypto->plaintext_len, crypto->filename, NULL,
1282 (void **)&key, &keylen, 0, 0, no_passphrase);
1285 if (!rc)
1287 rc = save_common (filename, crypto, crypto->plaintext,
1288 crypto->plaintext_len, key, keylen, &cached, 1);
1289 if (!rc)
1290 *rcrypto = crypto;
1293 if (rc)
1295 gcry_free (key);
1296 cleanup_crypto (&crypto);
1298 else if (!cached)
1299 send_status_all (STATUS_CACHE, NULL);
1301 return rc;
1304 gpg_error_t
1305 save_common (const char *filename, struct crypto_s *crypto,
1306 const unsigned char *data, size_t datalen,
1307 const unsigned char *key, size_t keylen, int *cached, int no_agent)
1309 struct cache_data_s *cdata;
1310 gpg_error_t rc = 0;
1311 gcry_sexp_t pubkey = NULL;
1312 gcry_sexp_t sigkey = NULL;
1314 /* This is safe since it is a (somewhat) fast operation. */
1315 cache_lock ();
1316 pthread_cleanup_push (cleanup_cache_mutex, NULL);
1317 cdata = cache_get_data_filename (filename);
1318 *cached = cdata != NULL;
1320 if (!cdata)
1321 cdata = xcalloc (1, sizeof (struct cache_data_s));
1323 #ifdef WITH_AGENT
1324 if (use_agent && !no_agent)
1326 rc = gcry_sexp_build (&pubkey, NULL, "%S", crypto->pkey_sexp);
1327 if (!rc)
1328 rc = gcry_sexp_build (&sigkey, NULL, "%S", crypto->sigpkey_sexp);
1330 #endif
1332 if (!rc)
1334 gcry_free (cdata->doc);
1335 cdata->doc = NULL;
1336 gcry_free (cdata->key);
1337 cdata->key = (unsigned char *)key;
1338 cdata->keylen = keylen;
1339 rc = encrypt_xml (NULL, cache_key, cache_keysize, GCRY_CIPHER_AES, data,
1340 datalen, &cdata->doc, &cdata->doclen, &cache_iv,
1341 &cache_blocksize, 0);
1344 if (!rc)
1346 unsigned char md5file[16];
1348 /* Update in case of any --keygrip argument */
1349 if (cdata->pubkey)
1350 gcry_sexp_release (cdata->pubkey);
1352 if (cdata->sigkey)
1353 gcry_sexp_release (cdata->sigkey);
1355 cdata->pubkey = pubkey;
1356 cdata->sigkey = sigkey;
1357 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
1358 rc = cache_set_data (md5file, cdata, crypto->grip);
1360 else
1362 if (pubkey)
1363 gcry_sexp_release (pubkey);
1365 if (sigkey)
1366 gcry_sexp_release (sigkey);
1369 pthread_cleanup_pop (1); // mutex unlock
1370 return rc;
1373 gpg_error_t
1374 getpin_common (assuan_context_t ctx, const char *filename, int which,
1375 char **rkey, size_t *rkeylen)
1377 gpg_error_t rc;
1378 struct client_s *client = ctx ? assuan_get_pointer (ctx) : NULL;
1379 struct pinentry_s *pin = pinentry_init (filename);
1381 if (!pin)
1382 return GPG_ERR_ENOMEM;
1384 if (client)
1385 pinentry_merge_options (&pin->pinentry_opts, &client->pinentry_opts);
1387 rc = pinentry_lock (ctx, pin);
1388 if (!rc)
1389 rc = pinentry_getpin (pin, rkey, which);
1391 pinentry_deinit (pin);
1392 if (rc)
1393 return rc;
1395 *rkeylen = strlen (*rkey);
1396 if (!(*rkeylen))
1397 (*rkeylen)++;
1399 return rc;
1402 /* Note: 'key' is freed with gcry_free() and not xfree(). Although
1403 * both call xfree(). */
1404 gpg_error_t
1405 inquire_passphrase (assuan_context_t ctx, const char *keyword,
1406 unsigned char **result, size_t *rlen)
1408 gpg_error_t rc;
1410 assuan_begin_confidential (ctx);
1411 rc = assuan_inquire (ctx, keyword, result, rlen, 0);
1412 assuan_end_confidential (ctx);
1413 return rc;
1416 /* Common to both PKI and non-PKI files. */
1417 gpg_error_t
1418 decrypt_common (assuan_context_t ctx, int inquire, struct crypto_s *crypto,
1419 const char *filename, char **rkey, size_t *rkeylen)
1421 char *key = NULL;
1422 size_t keylen = 0;
1423 gpg_error_t rc = read_data_file (filename, crypto);
1424 int algo = cipher_to_gcrypt (crypto->hdr.flags);
1425 void *salted_key = NULL;
1426 size_t keysize = 0;
1428 if (rc)
1430 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1431 return rc;
1434 key = config_get_string (filename, "passphrase");
1435 if (key)
1437 log_write (_("Trying the passphrase specified in config ..."));
1438 keylen = strlen (key);
1441 if (!key)
1443 key = config_get_string (filename, "passphrase_file");
1444 if (key)
1446 char *tmp = expand_homedir (key);
1447 int fd;
1448 struct stat st;
1450 xfree (key);
1451 key = tmp;
1452 log_write (_("Trying the passphrase using file '%s' ..."), key);
1453 fd = open (key, O_RDONLY);
1454 if (fd == -1)
1456 rc = gpg_error_from_errno (errno);
1457 log_write ("%s: %s", key, pwmd_strerror (rc));
1458 xfree (key);
1459 return rc;
1462 stat (key, &st);
1463 xfree (key);
1464 key = xmalloc (st.st_size);
1465 if (key)
1467 if (read (fd, key, st.st_size) != st.st_size)
1469 log_write ("short read() count");
1470 rc = GPG_ERR_TOO_SHORT;
1473 else
1474 rc = GPG_ERR_ENOMEM;
1476 close (fd);
1478 if (rc)
1480 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1481 xfree (key);
1482 return rc;
1485 keylen = st.st_size;
1486 if (!keylen)
1488 tmp = xmalloc (1);
1489 *tmp = 0;
1490 xfree (key);
1491 key = tmp;
1492 keylen++;
1497 if (!key && !IS_PKI (crypto) && inquire
1498 && !(crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
1500 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
1501 &keylen);
1502 if (rc)
1504 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1505 return rc;
1508 if (!keylen)
1509 keylen++;
1511 else if (!key && !IS_PKI (crypto))
1513 if (crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
1515 keylen = 1;
1516 key = gcry_malloc (keylen);
1517 memset (key, 0, keylen);
1519 else
1521 rc = getpin_common (ctx, filename, PINENTRY_OPEN, &key, &keylen);
1522 if (rc)
1524 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1525 return rc;
1529 #ifdef WITH_AGENT
1530 else if (key && IS_PKI (crypto))
1532 rc = set_agent_passphrase (crypto, key, keylen);
1533 if (rc)
1535 xfree (key);
1536 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1537 return rc;
1540 else if (!key && IS_PKI (crypto))
1542 /* The cache entry has been cleared in save_command(). Will prompt. */
1543 rc = set_pinentry_mode (crypto->agent, inquire ? "loopback" : "ask");
1544 if (rc)
1545 return rc;
1547 #endif
1549 if (key && !IS_PKI (crypto))
1551 rc = hash_key (algo, crypto->hdr.salt, sizeof(crypto->hdr.salt), key,
1552 keylen, &salted_key, &keysize);
1553 xfree (key);
1554 key = (char *)salted_key;
1555 keylen = keysize;
1556 if (rc)
1558 xfree (salted_key);
1559 return rc;
1563 xfree (crypto->filename);
1564 crypto->filename = str_dup (filename);
1565 rc = decrypt_data (ctx, crypto, (unsigned char *)key, keylen);
1566 if (rc)
1568 log_write ("ERR %i: %s", rc, pwmd_strerror (rc));
1569 xfree (key);
1571 else
1573 *rkey = key;
1574 *rkeylen = keylen;
1577 return rc;