Unofficial pwmd_tcp_connect() to a remote server. GnuTLS is used for
[libpwmd.git] / libpwmd.c
blobfc15efdb85d08f93515574eeab2fbac7970104af
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2008 Ben Kibbey <bjk@luxsci.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02110-1301 USA
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <string.h>
26 #include <sys/socket.h>
27 #include <sys/un.h>
28 #include <signal.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <sys/wait.h>
32 #include <fcntl.h>
33 #include <pwd.h>
34 #include <time.h>
35 #include <sys/types.h>
36 #include <limits.h>
37 #include <sys/select.h>
38 #include <netdb.h>
39 #include <netinet/in.h>
40 #include <sys/socket.h>
41 #include <libpwmd.h>
43 #ifdef HAVE_CONFIG_H
44 #include <config.h>
45 #endif
47 #ifdef WITH_GNUTLS
48 #include <gnutls/gnutls.h>
49 #include <gnutls/x509.h>
50 #endif
52 #ifdef HAVE_ASSUAN_H
53 #include <assuan.h>
54 #endif
56 #ifdef HAVE_SETLOCALE
57 #include <locale.h>
58 #endif
60 #include "gettext.h"
61 #define N_(msgid) dgettext("libpwmd", msgid)
63 #ifndef MEM_DEBUG
64 #include "mem.h"
65 #else
66 #define xfree free
67 #define xrealloc realloc
68 #define xmalloc malloc
69 #define xstrdup strdup
70 #define xcalloc calloc
71 #endif
73 #include "types.h"
75 #ifdef USE_PINENTRY
76 static pwm_t *gpwm;
77 static int gelapsed, gtimeout;
78 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd);
79 static gpg_error_t global_error;
80 #endif
82 const char *pwmd_strerror(gpg_error_t e)
84 gpg_err_code_t code = gpg_err_code(e);
86 if (code >= GPG_ERR_USER_1 && code < gpg_err_code(EPWMD_MAX)) {
87 switch (code) {
88 case GPG_ERR_USER_1:
89 default:
90 return N_("Unknown error");
91 case GPG_ERR_USER_2:
92 return N_("No cache slots available");
93 case GPG_ERR_USER_3:
94 return N_("Recursion loop");
95 case GPG_ERR_USER_4:
96 return N_("No file is open");
97 case GPG_ERR_USER_5:
98 return N_("General LibXML error");
99 case GPG_ERR_USER_6:
100 return N_("File modified");
104 return gpg_strerror(e);
107 gpg_error_t pwmd_init()
109 #ifdef WITH_GNUTLS
110 gnutls_global_set_mem_functions(xmalloc, xmalloc, NULL, xrealloc, xfree);
111 gnutls_global_init ();
112 #endif
113 #ifdef ENABLE_NLS
114 bindtextdomain("libpwmd", LOCALEDIR);
115 #endif
116 gpg_err_init();
117 assuan_set_malloc_hooks(xmalloc, xrealloc, xfree);
118 assuan_set_assuan_err_source(GPG_ERR_SOURCE_DEFAULT);
119 return 0;
122 static pwm_t *_socket_connect_finalize(pwm_t *pwm, assuan_context_t ctx)
124 int active[2];
125 int n = assuan_get_active_fds(ctx, 0, active, sizeof(active));
127 pwm->fd = n <= 0 ? -1 : dup(active[0]);
128 pwm->ctx = ctx;
129 #ifdef USE_PINENTRY
130 pwm->pid = -1;
131 pwm->pinentry_tries = 3;
132 #endif
133 assuan_set_pointer(ctx, pwm);
134 return pwm;
137 #ifdef WITH_GNUTLS
138 static int read_hook(assuan_context_t ctx, assuan_fd_t fd, void *data,
139 size_t len, ssize_t *ret)
141 pwm_t *pwm = assuan_get_pointer(ctx);
143 if (!pwm || !pwm->session)
144 *ret = read((int)fd, data, len);
145 else {
146 do {
147 *ret = gnutls_record_recv(pwm->session, data, len);
149 if (*ret == GNUTLS_E_REHANDSHAKE) {
150 *ret = gnutls_rehandshake(pwm->session);
152 if (*ret == GNUTLS_E_WARNING_ALERT_RECEIVED ||
153 *ret == GNUTLS_A_NO_RENEGOTIATION) {
154 fprintf(stderr, "%s", gnutls_strerror(*ret));
155 continue;
158 if (*ret != GNUTLS_E_SUCCESS) {
159 fprintf(stderr, "%s", gnutls_strerror(*ret));
160 *ret = 0;
161 break;
164 *ret = gnutls_handshake(pwm->session);
166 if (*ret != GNUTLS_E_SUCCESS) {
167 fprintf(stderr, "%s", gnutls_strerror(*ret));
168 *ret = 0;
169 break;
172 continue;
174 } while (*ret == GNUTLS_E_INTERRUPTED || *ret == GNUTLS_E_AGAIN);
177 return *ret <= 0 ? 0 : 1;
180 static int write_hook(assuan_context_t ctx, assuan_fd_t fd, const void *data,
181 size_t len, ssize_t *ret)
183 pwm_t *pwm = assuan_get_pointer(ctx);
185 if (!pwm || !pwm->session)
186 *ret = write((int)fd, data, len);
187 else {
188 do {
189 *ret = gnutls_record_send(pwm->session, data, len);
190 } while (*ret == GNUTLS_E_INTERRUPTED || *ret == GNUTLS_E_AGAIN);
193 return *ret <= 0 ? 0 : 1;
196 static void _tls_deinit(pwm_t *pwm)
198 //FIXME hangs when missing cert
199 gnutls_bye(pwm->session, GNUTLS_SHUT_RDWR);
200 gnutls_deinit(pwm->session);
201 gnutls_certificate_free_credentials(pwm->x509);
204 static gpg_error_t verify_certificate(pwm_t *pwm)
206 unsigned int status;
207 const gnutls_datum_t *cert_list;
208 unsigned int cert_list_size;
209 int i;
210 gnutls_x509_crt_t cert;
211 gpg_error_t rc;
213 rc = gnutls_certificate_verify_peers2(pwm->session, &status);
215 if (rc < 0)
216 return GPG_ERR_UNKNOWN_ERRNO;
218 if (status & GNUTLS_CERT_INVALID)
219 return GPG_ERR_MISSING_CERT;
221 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
222 return GPG_ERR_BAD_SIGNATURE;
224 if (status & GNUTLS_CERT_REVOKED)
225 return GPG_ERR_CERT_REVOKED;
227 if (gnutls_certificate_type_get(pwm->session) != GNUTLS_CRT_X509)
228 return GPG_ERR_UNSUPPORTED_CERT;
230 if (gnutls_x509_crt_init(&cert) < 0)
231 return gpg_error_from_errno(ENOMEM);
233 cert_list = gnutls_certificate_get_peers (pwm->session, &cert_list_size);
235 if (!cert_list) {
236 rc = GPG_ERR_MISSING_CERT;
237 goto done;
240 for (i = 0; i < cert_list_size; i++) {
241 if (gnutls_x509_crt_import(cert, &cert_list[i], GNUTLS_X509_FMT_DER) < 0) {
242 rc = GPG_ERR_BAD_CERT_CHAIN;
243 goto done;
247 /* Beware here we do not check for errors.
249 if (gnutls_x509_crt_get_expiration_time(cert) < time (0)) {
250 rc = GPG_ERR_CERT_EXPIRED;
251 goto done;
254 if (gnutls_x509_crt_get_activation_time(cert) > time (0)) {
255 rc = GPG_ERR_CERT_TOO_YOUNG;
256 goto done;
259 #if 0
260 if (!gnutls_x509_crt_check_hostname (cert, hostname))
262 printf ("The certificate's owner does not match hostname '%s'\n",
263 hostname);
264 return 1;
266 #endif
268 done:
269 gnutls_x509_crt_deinit(cert);
270 return rc;
273 static gpg_error_t _tls_init(pwm_t *pwm, int fd, const char *cert,
274 const char *key, const char *ca)
276 gpg_error_t rc;
277 const char *errstr;
279 rc = gnutls_certificate_allocate_credentials(&pwm->x509);
281 if (rc)
282 return gpg_error_from_errno(ENOMEM);
284 /* The client certificate must be signed by the CA of the pwmd server
285 * certificate in order for the client to authenticate successfully. Man in
286 * the middle attacks are still possible if the attacker is running a pwmd
287 * that doesn't require client certificate authentication. So require the
288 * client to verify the server certificate.
290 gnutls_certificate_set_x509_trust_file (pwm->x509, ca, GNUTLS_X509_FMT_PEM);
292 rc = gnutls_certificate_set_x509_key_file(pwm->x509, cert, key,
293 GNUTLS_X509_FMT_PEM);
294 rc = gnutls_init(&pwm->session, GNUTLS_CLIENT);
295 rc = gnutls_priority_set_direct(pwm->session, "SECURE256", &errstr);
296 rc = gnutls_credentials_set(pwm->session, GNUTLS_CRD_CERTIFICATE, pwm->x509);
297 gnutls_transport_set_ptr(pwm->session, (gnutls_transport_ptr_t) fd);
298 rc = gnutls_handshake(pwm->session);
300 if (rc < 0) {
301 gnutls_perror (rc);
302 rc = GPG_ERR_INV_CIPHER_MODE;
303 _tls_deinit(pwm);
304 return rc;
307 rc = verify_certificate(pwm);
308 if (rc)
309 _tls_deinit(pwm);
310 return rc;
313 static void _tls_assuan_deinit(assuan_context_t ctx)
315 pwm_t *pwm = assuan_get_pointer(ctx);
317 _tls_deinit(pwm);
320 pwm_t *pwmd_tcp_connect(const char *host, gpg_error_t *rc, const char *cert,
321 const char *key, const char *ca)
323 char *p;
324 int port = 6466;
325 int fd;
326 struct hostent *he;
327 struct sockaddr_in their_addr;
328 assuan_context_t ctx;
329 char *tcert, *tkey, *tca;
330 char buf[PATH_MAX];
331 struct passwd *pw = getpwuid(getuid());
332 pwm_t *pwm;
333 struct assuan_io_hooks io_hooks = {read_hook, write_hook};
335 if (!host) {
336 *rc = GPG_ERR_INV_ARG;
337 return NULL;
340 p = strchr(host, ':');
342 if (p) {
343 char *pp;
345 port = strtol(++p, &pp, 10);
347 if (pp) {
348 *rc = GPG_ERR_INV_ARG;
349 return NULL;
353 if ((he = gethostbyname(host)) == NULL) {
354 *rc = gpg_error_from_syserror();
355 return NULL;
358 fd = socket(PF_INET, SOCK_STREAM, 0);
360 if (fd == -1) {
361 *rc = gpg_error_from_syserror();
362 return NULL;
365 their_addr.sin_family = PF_INET;
366 their_addr.sin_port = htons(port);
367 their_addr.sin_addr = *((struct in_addr *)he->h_addr);
368 memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
370 if (connect(fd, (struct sockaddr *)&their_addr, sizeof(their_addr)) == -1) {
371 *rc = gpg_error_from_syserror();
372 return NULL;
375 if (!cert) {
376 snprintf(buf, sizeof(buf), "%s/.pwmd/client-cert.pem", pw->pw_dir);
377 tcert = xstrdup(buf);
379 else
380 tcert = xstrdup(cert);
382 if (!tcert) {
383 *rc = gpg_error_from_syserror();
384 return NULL;
387 if (!key) {
388 snprintf(buf, sizeof(buf), "%s/.pwmd/client-key.pem", pw->pw_dir);
389 tkey = xstrdup(buf);
391 else
392 tkey = xstrdup(key);
394 if (!tkey) {
395 *rc = gpg_error_from_syserror();
396 xfree(tcert);
397 return NULL;
400 if (!ca) {
401 snprintf(buf, sizeof(buf), "%s/.pwmd/ca-cert.pem", pw->pw_dir);
402 tca = xstrdup(buf);
404 else
405 tca = xstrdup(ca);
407 if (!tca) {
408 *rc = gpg_error_from_syserror();
409 xfree(tcert);
410 xfree(tkey);
411 return NULL;
414 if ((pwm = (pwm_t *)xcalloc(1, sizeof(pwm_t))) == NULL) {
415 *rc = gpg_error_from_syserror();
416 xfree(tcert);
417 xfree(tkey);
418 xfree(tca);
419 return NULL;
422 *rc = _tls_init(pwm, fd, tcert, tkey, tca);
423 xfree(tcert);
424 xfree(tkey);
425 xfree(tca);
427 if (*rc) {
428 close(fd);
429 xfree(pwm);
430 return NULL;
433 assuan_set_io_hooks(&io_hooks);
434 *rc = assuan_socket_connect_fd(&ctx, fd, 0, pwm);
436 if (*rc) {
437 xfree(pwm);
438 return NULL;
441 assuan_set_finish_handler(ctx, _tls_assuan_deinit);
442 return _socket_connect_finalize(pwm, ctx);
444 #endif
446 pwm_t *pwmd_connect(const char *path, gpg_error_t *rc)
448 pwm_t *pwm = NULL;
449 char *socketpath = NULL;
450 struct passwd *pw;
451 assuan_context_t ctx;
453 if (!path) {
454 pw = getpwuid(getuid());
455 socketpath = (char *)xmalloc(strlen(pw->pw_dir) + strlen("/.pwmd/socket") + 1);
456 sprintf(socketpath, "%s/.pwmd/socket", pw->pw_dir);
458 else
459 socketpath = xstrdup(path);
461 *rc = assuan_socket_connect_ext(&ctx, socketpath, -1, 0);
462 xfree(socketpath);
464 if (*rc)
465 return NULL;
467 if ((pwm = (pwm_t *)xcalloc(1, sizeof(pwm_t))) == NULL) {
468 *rc = gpg_error_from_syserror();
469 return NULL;
472 return _socket_connect_finalize(pwm, ctx);
475 gpg_error_t pwmd_pending_line(pwm_t *pwm, char **line, size_t *len)
477 if (!pwm)
478 return GPG_ERR_INV_ARG;
480 if (assuan_pending_line(pwm->ctx))
481 return assuan_read_line(pwm->ctx, line, len);
483 return GPG_ERR_NO_DATA;
486 void pwmd_close(pwm_t *pwm)
488 if (!pwm)
489 return;
491 if (pwm->ctx)
492 assuan_disconnect(pwm->ctx);
494 if (pwm->password)
495 xfree(pwm->password);
497 if (pwm->title)
498 xfree(pwm->title);
500 if (pwm->desc)
501 xfree(pwm->desc);
503 if (pwm->prompt)
504 xfree(pwm->prompt);
506 if (pwm->pinentry_tty)
507 xfree(pwm->pinentry_tty);
509 if (pwm->pinentry_display)
510 xfree(pwm->pinentry_display);
512 if (pwm->pinentry_term)
513 xfree(pwm->pinentry_term);
515 if (pwm->filename)
516 xfree(pwm->filename);
518 xfree(pwm);
521 static int mem_realloc_cb(void *data, const void *buffer, size_t len)
523 membuf_t *mem = (membuf_t *)data;
524 void *p;
526 if (!buffer)
527 return 0;
529 if ((p = xrealloc(mem->buf, mem->len + len)) == NULL)
530 return 1;
532 mem->buf = p;
533 memcpy((char *)mem->buf + mem->len, buffer, len);
534 mem->len += len;
535 return 0;
538 void pwmd_free_result(void *data)
540 xfree(data);
543 static int _inquire_cb(void *data, const char *keyword)
545 pwm_t *pwm = (pwm_t *)data;
546 gpg_error_t rc = 0;
547 int flags = fcntl(pwm->fd, F_GETFL);
549 /* Shouldn't get this far without a callback. */
550 if (!pwm->inquire_func)
551 return GPG_ERR_INV_ARG;
554 * Since the socket file descriptor is probably set to non-blocking, set to
555 * blocking to prevent GPG_ERR_EAGAIN errors. This should be fixes when
556 * asynchronous INQUIRE is supported by either libassuan or a later
557 * libpwmd.
559 fcntl(pwm->fd, F_SETFL, 0);
561 for (;;) {
562 char *result = NULL;
563 size_t len;
564 gpg_error_t arc;
566 rc = pwm->inquire_func(pwm->inquire_data, keyword, rc, &result, &len);
567 rc = gpg_err_code(rc);
569 if (rc == GPG_ERR_EOF || !rc) {
570 if (len <= 0 || !result || !*result) {
571 rc = 0;
572 break;
575 arc = assuan_send_data(pwm->ctx, result, len);
577 if (rc == GPG_ERR_EOF) {
578 rc = arc;
579 break;
582 rc = arc;
584 else if (rc)
585 break;
588 fcntl(pwm->fd, F_SETFL, flags);
589 return rc;
592 gpg_error_t pwmd_finalize(pwm_t *pwm)
594 if (!pwm || pwm->fd < 0)
595 return GPG_ERR_INV_ARG;
597 pwm->state = ASYNC_INIT;
598 pwm->ntries = 0;
599 pwm->is_open_cmd = 0;
600 return 0;
603 static gpg_error_t do_nb_command(pwm_t *pwm, const char *cmd, const char *arg)
605 char *buf;
606 gpg_error_t rc;
607 size_t len = strlen(cmd) + 2;
609 len += arg ? strlen(arg) : 0;
611 if (pwm->state != ASYNC_INIT)
612 return GPG_ERR_UNEXPECTED;
614 buf = (char *)xmalloc(len);
616 if (!buf) {
617 rc = gpg_error_from_errno(ENOMEM);
618 goto fail;
621 snprintf(buf, len, "%s %s", cmd, arg ? arg : "");
622 rc = assuan_write_line(pwm->ctx, buf);
623 xfree(buf);
625 if (!rc)
626 pwm->state = ASYNC_PROCESS;
628 fail:
629 return rc;
632 gpg_error_t pwmd_open_async(pwm_t *pwm, const char *filename)
634 if (!pwm || !filename)
635 return GPG_ERR_INV_ARG;
637 /* For pinentry retries. */
638 if (!pwm->is_open_cmd) {
639 if (pwm->filename)
640 xfree(pwm->filename);
642 pwm->filename = xstrdup(filename);
645 pwm->is_open_cmd = 1;
646 return do_nb_command(pwm, "OPEN", filename);
649 gpg_error_t pwmd_save_async(pwm_t *pwm)
651 if (!pwm)
652 return GPG_ERR_INV_ARG;
654 return do_nb_command(pwm, "SAVE", NULL);
657 static gpg_error_t parse_assuan_line(pwm_t *pwm)
659 gpg_error_t rc;
660 char *line;
661 size_t len;
663 rc = assuan_read_line(pwm->ctx, &line, &len);
665 if (!rc) {
666 if (line[0] == 'O' && line[1] == 'K' &&
667 (line[2] == 0 || line[2] == ' ')) {
668 pwm->state = ASYNC_DONE;
670 else if (line[0] == '#') {
672 else if (line[0] == 'S' && (line[1] == 0 || line[1] == ' ')) {
673 if (pwm->status_func) {
674 pwm->status_func(pwm->status_data,
675 line[1] == 0 ? line+1 : line+2);
678 else if (line[0] == 'E' && line[1] == 'R' && line[2] == 'R' &&
679 (line[3] == 0 || line[3] == ' ')) {
680 line += 4;
681 rc = atoi(line);
682 pwm->state = ASYNC_DONE;
686 return rc;
689 pwmd_async_t pwmd_process(pwm_t *pwm, gpg_error_t *rc)
691 fd_set rfds;
692 int n;
693 struct timeval tv = {0, 0};
695 *rc = 0;
697 if (!pwm || pwm->fd < 0) {
698 *rc = GPG_ERR_INV_ARG;
699 return ASYNC_DONE;
701 else if (pwm->state == ASYNC_DONE)
702 return pwm->state;
703 else if (pwm->state == ASYNC_INIT) {
704 *rc = GPG_ERR_UNEXPECTED;
705 return ASYNC_DONE;
708 FD_ZERO(&rfds);
709 FD_SET(pwm->fd, &rfds);
710 n = select(pwm->fd+1, &rfds, NULL, NULL, &tv);
712 if (n > 0) {
713 if (FD_ISSET(pwm->fd, &rfds))
714 *rc = parse_assuan_line(pwm);
717 while (!*rc && assuan_pending_line(pwm->ctx))
718 *rc = parse_assuan_line(pwm);
720 if (pwm->is_open_cmd && gpg_err_code(*rc) == EPWMD_BADKEY &&
721 ++pwm->ntries < pwm->pinentry_tries) {
722 pwm->state = ASYNC_INIT;
723 *rc = pwmd_open_async(pwm, pwm->filename);
726 return pwm->state;
729 static gpg_error_t assuan_command(pwm_t *pwm, assuan_context_t ctx,
730 char **result, const char *cmd)
732 membuf_t data;
733 gpg_error_t rc;
735 data.len = 0;
736 data.buf = NULL;
738 rc = assuan_transact(ctx, cmd, mem_realloc_cb, &data, _inquire_cb, pwm,
739 pwm->status_func, pwm->status_data);
741 if (rc) {
742 if (data.buf) {
743 xfree(data.buf);
744 data.buf = NULL;
747 else {
748 if (data.buf) {
749 mem_realloc_cb(&data, "", 1);
750 *result = (char *)data.buf;
754 return gpg_err_code(rc);
757 gpg_error_t pwmd_inquire(pwm_t *pwm, const char *cmd, pwmd_inquire_fn fn,
758 void *data)
760 if (!pwm || !cmd || !fn)
761 return GPG_ERR_INV_ARG;
763 pwm->inquire_func = fn;
764 pwm->inquire_data = data;
765 return assuan_command(pwm, pwm->ctx, NULL, cmd);
768 gpg_error_t pwmd_terminate_pinentry(pwm_t *pwm)
770 #ifndef USE_PINENTRY
771 return GPG_ERR_NOT_IMPLEMENTED;
772 #else
773 if (!pwm || pwm->pid == -1)
774 return GPG_ERR_INV_ARG;
776 if (kill(pwm->pid, 0) == 0) {
777 if (kill(pwm->pid, SIGTERM) == -1) {
778 if (kill(pwm->pid, SIGKILL) == -1)
779 return gpg_error_from_errno(errno);
782 pwm->pin_error = GPG_ERR_TIMEOUT;
784 else
785 return gpg_error_from_errno(errno);
787 return 0;
788 #endif
791 #ifdef USE_PINENTRY
792 static gpg_error_t set_pinentry_strings(pwm_t *pwm, int which)
794 char *buf;
795 char tmp[ASSUAN_LINELENGTH];
796 gpg_error_t error;
798 if (!pwm->title)
799 pwm->title = xstrdup(N_("LibPWMD"));
801 if (!pwm->prompt)
802 pwm->prompt = xstrdup(N_("Password:"));
804 if (!pwm->desc && !which)
805 pwm->desc = xstrdup(N_("Enter a password."));
807 if (which == 1) {
808 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Invalid password, please try again."));
809 buf = xstrdup(tmp);
811 else if (which == 2) {
812 snprintf(tmp, sizeof(tmp), "SETERROR %s", N_("Please type the password again for confirmation."));
813 buf = xstrdup(tmp);
815 else {
816 buf = (char *)xmalloc(strlen("SETERROR ") + strlen(pwm->desc) + 1);
817 sprintf(buf, "SETERROR %s", pwm->desc);
820 error = pinentry_command(pwm, NULL, buf);
821 xfree(buf);
823 if (error)
824 return error;
826 buf = (char *)xmalloc(strlen("SETPROMPT ") + strlen(pwm->prompt) + 1);
827 sprintf(buf, "SETPROMPT %s", pwm->prompt);
828 error = pinentry_command(pwm, NULL, buf);
829 xfree(buf);
831 if (error)
832 return error;
834 buf = (char *)xmalloc(strlen("SETDESC ") + strlen(pwm->title) + 1);
835 sprintf(buf, "SETDESC %s", pwm->title);
836 error = pinentry_command(pwm, NULL, buf);
837 xfree(buf);
838 return error;
841 static void update_pinentry_settings(pwm_t *pwm)
843 FILE *fp;
844 char buf[LINE_MAX];
845 struct passwd *pw = getpwuid(getuid());
846 char *p;
848 snprintf(buf, sizeof(buf), "%s/.pwmd/pinentry.conf", pw->pw_dir);
850 if ((fp = fopen(buf, "r")) == NULL)
851 return;
853 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
854 char name[32], val[256];
856 if (sscanf(p, " %31[a-zA-Z] = %255s", name, val) != 2)
857 continue;
859 if (strcasecmp(name, "TTYNAME") == 0) {
860 xfree(pwm->pinentry_tty);
861 pwm->pinentry_tty = xstrdup(val);
863 else if (strcasecmp(name, "TTYTYPE") == 0) {
864 xfree(pwm->pinentry_term);
865 pwm->pinentry_term = xstrdup(val);
867 else if (strcasecmp(name, "DISPLAY") == 0) {
868 xfree(pwm->pinentry_display);
869 pwm->pinentry_display = xstrdup(val);
871 else if (strcasecmp(name, "PATH") == 0) {
872 xfree(pwm->pinentry_path);
873 pwm->pinentry_path = xstrdup(val);
877 fclose(fp);
880 static gpg_error_t launch_pinentry(pwm_t *pwm)
882 int rc;
883 assuan_context_t ctx;
884 int child_list[] = {-1};
885 char *display = getenv("DISPLAY");
886 const char *argv[6];
887 int have_display = 0;
888 char *tty = NULL;
890 update_pinentry_settings(pwm);
892 if (pwm->pinentry_display || display)
893 have_display = 1;
894 else {
895 tty = pwm->pinentry_tty ? pwm->pinentry_tty : ttyname(STDOUT_FILENO);
897 if (!tty)
898 return gpg_error_from_errno(errno);
901 if (!have_display && !tty)
902 return GPG_ERR_ENOTTY;
904 argv[0] = "pinentry";
905 argv[1] = have_display ? "--display" : "--ttyname";
906 argv[2] = have_display ? pwm->pinentry_display ? pwm->pinentry_display : display : tty;
907 argv[3] = NULL;
909 if (!have_display) {
910 argv[3] = "--ttytype";
911 argv[4] = pwm->pinentry_term ? pwm->pinentry_term : getenv("TERM");
912 argv[5] = NULL;
915 rc = assuan_pipe_connect(&ctx, pwm->pinentry_path ? pwm->pinentry_path : PINENTRY_PATH, argv, child_list);
917 if (rc)
918 return rc;
920 pwm->pid = assuan_get_pid(ctx);
921 pwm->pctx = ctx;
922 return set_pinentry_strings(pwm, 0);
925 static gpg_error_t pinentry_command(pwm_t *pwm, char **result, const char *cmd)
927 gpg_error_t n;
929 if (!pwm->pctx) {
930 n = launch_pinentry(pwm);
932 if (n)
933 return n;
936 return assuan_command(pwm, pwm->pctx, result, cmd);
939 static void pinentry_disconnect(pwm_t *pwm)
941 if (pwm->pctx)
942 assuan_disconnect(pwm->pctx);
944 pwm->pctx = NULL;
945 pwm->pid = -1;
949 * Only called from a child process.
951 static void catchsig(int sig)
953 switch (sig) {
954 case SIGALRM:
955 if (gelapsed++ >= gtimeout) {
956 global_error = pwmd_terminate_pinentry(gpwm);
958 if (!global_error)
959 global_error = GPG_ERR_TIMEOUT;
961 break;
964 alarm(1);
965 break;
966 default:
967 break;
972 * Borrowed from libassuan.
974 static char *percent_escape(const char *atext)
976 const unsigned char *s;
977 int len = strlen(atext) * 3 + 1;
978 char *buf = (char *)xmalloc(len), *p = buf;
980 if (!buf)
981 return NULL;
983 for (s=(const unsigned char *)atext; *s; s++) {
984 if (*s < ' ') {
985 sprintf (p, "%%%02X", *s);
986 p += 3;
988 else
989 *p++ = *s;
992 *p = 0;
993 return buf;
995 #endif
997 static gpg_error_t send_command(pwm_t *pwm, char **result, const char *cmd)
999 if (!cmd)
1000 return GPG_ERR_INV_ARG;
1002 return assuan_command(pwm, pwm->ctx, result, cmd);
1006 * Avoid sending the BYE command here. libassuan will close the file
1007 * descriptor and release the assuan context. Use pwmd_close() instead.
1009 gpg_error_t pwmd_command(pwm_t *pwm, char **result, const char *cmd, ...)
1011 va_list ap;
1012 char *buf;
1013 size_t len;
1014 gpg_error_t error;
1016 if (!pwm || !cmd)
1017 return GPG_ERR_INV_ARG;
1019 *result = NULL;
1020 va_start(ap, cmd);
1022 * C99 allows the dst pointer to be null which will calculate the length
1023 * of the result and return it.
1025 len = vsnprintf(NULL, 0, cmd, ap);
1026 buf = (char *)xmalloc(len + 1);
1027 len = vsnprintf(buf, len + 1, cmd, ap);
1028 va_end(ap);
1029 error = send_command(pwm, result, buf);
1030 xfree(buf);
1031 return error;
1034 #ifdef USE_PINENTRY
1035 static gpg_error_t do_getpin(pwm_t *pwm, char **result)
1037 if (gtimeout) {
1038 signal(SIGALRM, catchsig);
1039 alarm(1);
1042 *result = NULL;
1043 return pinentry_command(pwm, result, "GETPIN");
1046 static gpg_error_t getpin(pwm_t *pwm, char **result, int *try_n, int which)
1048 int pin_try = *try_n;
1049 gpg_error_t error;
1051 getpin_again:
1052 *try_n = pin_try;
1054 if (pin_try == -1) {
1055 error = set_pinentry_strings(pwm, which);
1057 if (error) {
1058 pinentry_disconnect(pwm);
1059 return error;
1062 else {
1063 if (pwm->pinentry_tries-1 != pin_try) {
1064 error = set_pinentry_strings(pwm, 1);
1066 if (error) {
1067 pinentry_disconnect(pwm);
1068 return error;
1073 error = do_getpin(pwm, result);
1076 * Since there was input cancel any timeout setting.
1078 alarm(0);
1080 if (error) {
1081 if (error == GPG_ERR_CANCELED)
1082 return GPG_ERR_CANCELED;
1084 if (pin_try != -1 && pin_try--)
1085 goto getpin_again;
1087 if (pwm->pctx)
1088 pinentry_disconnect(pwm);
1090 *try_n = pin_try;
1091 return error;
1094 return 0;
1096 #endif
1098 gpg_error_t pwmd_open_nb_finalize(pwm_t *pwm, pwmd_nb_status_t *pw)
1100 gpg_error_t error;
1102 #ifndef USE_PINENTRY
1103 return GPG_ERR_NOT_IMPLEMENTED;
1104 #endif
1106 if (!pwm || !pw || !pw->filename[0])
1107 return GPG_ERR_INV_ARG;
1109 close(pw->fd);
1111 if (pw->error) {
1112 error = pw->error;
1113 goto fail;
1116 if (pwm->filename)
1117 xfree(pwm->filename);
1119 pwm->filename = xstrdup(pw->filename);
1120 memset(pw, 0, sizeof(pwmd_nb_status_t));
1121 return 0;
1123 fail:
1124 memset(pw, 0, sizeof(pwmd_nb_status_t));
1125 return error;
1128 static gpg_error_t do_open_command(pwm_t *pwm, const char *filename, char *password)
1130 char buf[ASSUAN_LINELENGTH];
1131 gpg_error_t error;
1132 char *result = NULL;
1134 snprintf(buf, sizeof(buf), "OPEN %s %s", filename, password ? password : "");
1135 error = send_command(pwm, &result, buf);
1136 memset(buf, 0, sizeof(buf));
1138 if (error && result)
1139 xfree(result);
1141 return error;
1144 static int do_pwmd_open(pwm_t *pwm, gpg_error_t *error, const char *filename,
1145 int nb, int timeout)
1147 char *result = NULL;
1148 char *password = NULL;
1149 char path[PATH_MAX];
1150 #ifdef USE_PINENTRY
1151 int pin_try;
1152 #endif
1154 if (!pwm || !filename || !*filename) {
1155 *error = GPG_ERR_INV_ARG;
1156 return nb ? -1 : 1;
1159 #ifdef USE_PINENTRY
1160 pin_try = pwm->pinentry_tries - 1;
1161 #endif
1164 * Avoid calling pinentry if the password is cached on the server or if
1165 * this is a new file.
1167 *error = pwmd_command(pwm, &result, "GETCONFIG data_directory");
1169 if (*error)
1170 return nb ? -1 : 1;
1172 snprintf(path, sizeof(path), "%s/%s", result, filename);
1173 pwmd_free_result(result);
1175 if (access(path, R_OK) == -1) {
1176 if (errno == ENOENT)
1177 goto gotpassword;
1180 *error = pwmd_command(pwm, &result, "ISCACHED %s", filename);
1182 if (*error == EPWMD_CACHE_NOT_FOUND) {
1183 if (pwm->passfunc) {
1184 password = pwm->passfunc(pwm, pwm->passdata);
1185 goto gotpassword;
1188 #ifdef USE_PINENTRY
1190 * Get the password from pinentry.
1192 if (pwm->use_pinentry) {
1194 * Nonblocking is wanted. fork() then return a file descriptor
1195 * that the client can use to read() from.
1197 if (nb) {
1198 int p[2];
1199 pid_t pid;
1200 pwmd_nb_status_t pw;
1202 if (pipe(p) == -1) {
1203 *error = gpg_error_from_syserror();
1204 return -1;
1207 pid = fork();
1209 switch (pid) {
1210 case 0:
1211 close(p[0]);
1212 strncpy(pw.filename, filename, sizeof(pw.filename));
1213 pw.filename[sizeof(pw.filename)-1] = 0;
1214 pw.fd = p[0];
1216 if (timeout > 0) {
1217 gpwm = pwm;
1218 gtimeout = timeout;
1219 gelapsed = 0;
1222 getpin_nb_again:
1223 *error = getpin(pwm, &password, &pin_try, 0);
1225 if (*error) {
1226 getpin_nb_fail:
1227 if (pwm->pctx)
1228 pinentry_disconnect(pwm);
1230 if (gtimeout && gelapsed >= gtimeout)
1231 *error = GPG_ERR_TIMEOUT;
1233 pw.error = *error;
1234 write(p[1], &pw, sizeof(pw));
1235 close(p[1]);
1236 _exit(1);
1240 * Don't count the time it takes to open the file
1241 * which may have many iterations.
1243 signal(SIGALRM, SIG_DFL);
1244 *error = do_open_command(pwm, filename, password);
1246 if (timeout)
1247 signal(SIGALRM, catchsig);
1249 if (pwm->pctx && *error == EPWMD_BADKEY) {
1250 if (pin_try-- > 0)
1251 goto getpin_nb_again;
1253 goto getpin_nb_fail;
1256 pinentry_disconnect(pwm);
1257 pw.error = 0;
1258 write(p[1], &pw, sizeof(pw));
1259 close(p[1]);
1260 _exit(0);
1261 break;
1262 case -1:
1263 *error = gpg_error_from_syserror();
1264 close(p[0]);
1265 close(p[1]);
1266 return -1;
1267 default:
1268 break;
1271 close(p[1]);
1272 return p[0];
1275 else {
1276 #endif
1278 * Not using pinentry and the file was not found
1279 * in the cache.
1281 password = pwm->password;
1282 #ifdef USE_PINENTRY
1284 #endif
1286 else if (*error)
1287 return nb ? -1 : 1;
1289 gotpassword:
1290 *error = do_open_command(pwm, filename, password);
1293 * Keep the user defined password set with pwmd_setopt(). The password may
1294 * be needed later (pwmd_save()) depending on the pwmd file cache settings.
1296 if (password && password != pwm->password)
1297 xfree(password);
1299 #ifdef USE_PINENTRY
1300 if (*error == EPWMD_BADKEY) {
1301 if (pin_try-- > 0 && !nb) {
1302 *error = pwmd_command(pwm, &result, "OPTION TITLE=%s",
1303 N_("Invalid password, please try again."));
1305 if (*error)
1306 return 1;
1308 goto gotpassword;
1311 if (nb)
1312 pinentry_disconnect(pwm);
1314 return nb ? -1 : 1;
1316 #endif
1318 if (!*error) {
1319 if (pwm->filename)
1320 xfree(pwm->filename);
1322 pwm->filename = xstrdup(filename);
1326 * The file is cached or the file is a new file.
1328 if (nb)
1329 return *error ? -1 : -2;
1331 return *error ? 1 : 0;
1334 gpg_error_t pwmd_open(pwm_t *pwm, const char *filename)
1336 gpg_error_t error;
1338 do_pwmd_open(pwm, &error, filename, 0, 0);
1339 return error;
1342 int pwmd_open_nb(pwm_t *pwm, gpg_error_t *error, const char *filename,
1343 int timeout)
1345 #ifndef USE_PINENTRY
1346 *error = GPG_ERR_NOT_IMPLEMENTED;
1347 return -1;
1348 #else
1349 return do_pwmd_open(pwm, error, filename, 1, timeout);
1350 #endif
1353 #ifdef USE_PINENTRY
1354 static gpg_error_t do_save_getpin(pwm_t *pwm, char **password)
1356 int confirm = 0;
1357 gpg_error_t error;
1358 char *result = NULL;
1359 int pin_try = -1;
1361 again:
1362 error = getpin(pwm, &result, &pin_try, confirm ? 2 : 0);
1364 if (error) {
1365 if (pwm->pctx)
1366 pinentry_disconnect(pwm);
1368 if (*password)
1369 xfree(*password);
1371 return error;
1374 if (!confirm++) {
1375 *password = result;
1376 goto again;
1379 if (strcmp(*password, result)) {
1380 xfree(*password);
1381 xfree(result);
1382 pinentry_disconnect(pwm);
1383 error = EPWMD_BADKEY;
1384 return error;
1387 xfree(result);
1388 pinentry_disconnect(pwm);
1389 return 0;
1391 #endif
1393 static gpg_error_t do_save_command(pwm_t *pwm, char *password)
1395 char buf[ASSUAN_LINELENGTH];
1396 gpg_error_t error;
1397 char *result = NULL;
1399 snprintf(buf, sizeof(buf), "SAVE %s", password ? password : "");
1400 error = send_command(pwm, &result, buf);
1401 memset(&buf, 0, sizeof(buf));
1403 if (error && result)
1404 xfree(result);
1406 return error;
1409 gpg_error_t pwmd_save_nb_finalize(pwm_t *pwm, pwmd_nb_status_t *pw)
1411 gpg_error_t rc;
1413 #ifndef USE_PINENTRY
1414 return GPG_ERR_NOT_IMPLEMENTED;
1415 #endif
1417 if (!pwm || !pw || !pw->filename[0])
1418 return GPG_ERR_INV_ARG;
1420 close(pw->fd);
1421 rc = pw->error;
1422 memset(pw, 0, sizeof(pwmd_nb_status_t));
1423 return rc;
1426 static int do_pwmd_save(pwm_t *pwm, gpg_error_t *error, int nb)
1428 char *result = NULL;
1429 char *password = NULL;
1431 if (!pwm) {
1432 *error = GPG_ERR_INV_ARG;
1433 return nb ? -1 : 1;
1436 if (pwm->use_pinentry || pwm->passfunc) {
1437 *error = pwmd_command(pwm, &result, "ISCACHED %s", pwm->filename);
1439 if (*error == EPWMD_CACHE_NOT_FOUND) {
1440 #ifdef USE_PINENTRY
1441 if (pwm->use_pinentry) {
1442 if (nb) {
1443 int p[2];
1444 pid_t pid;
1445 pwmd_nb_status_t pw;
1447 if (pipe(p) == -1) {
1448 *error = gpg_error_from_syserror();
1449 return -1;
1452 pid = fork();
1454 switch (pid) {
1455 case 0:
1456 close(p[0]);
1457 strncpy(pw.filename, pwm->filename, sizeof(pw.filename));
1458 pw.filename[sizeof(pw.filename)-1] = 0;
1459 pw.fd = p[0];
1461 do {
1462 password = NULL;
1463 *error = do_save_getpin(pwm, &password);
1464 } while (*error == EPWMD_BADKEY);
1466 if (*error) {
1467 if (pwm->pctx)
1468 pinentry_disconnect(pwm);
1470 pw.error = *error;
1471 write(p[1], &pw, sizeof(pw));
1472 close(p[1]);
1473 _exit(1);
1476 *error = do_save_command(pwm, password);
1477 pinentry_disconnect(pwm);
1478 pw.error = *error;
1479 write(p[1], &pw, sizeof(pw));
1480 close(p[1]);
1481 _exit(0);
1482 break;
1483 case -1:
1484 *error = gpg_error_from_syserror();
1485 close(p[0]);
1486 close(p[1]);
1487 return -1;
1488 default:
1489 break;
1492 close(p[1]);
1493 return p[0];
1496 *error = do_save_getpin(pwm, &password);
1498 if (*error)
1499 return 1;
1501 else {
1502 #endif
1503 if (pwm->passfunc)
1504 password = (*pwm->passfunc)(pwm, pwm->passdata);
1505 #ifdef USE_PINENTRY
1507 #endif
1509 else {
1510 if (*error)
1511 return nb ? -1 : 1;
1514 else
1515 password = pwm->password;
1517 *error = do_save_command(pwm, password);
1519 if (password && password != pwm->password)
1520 xfree(password);
1522 if (nb)
1523 return *error ? -1 : -2;
1525 return *error ? 1 : 0;
1528 int pwmd_save_nb(pwm_t *pwm, gpg_error_t *error)
1530 #ifndef USE_PINENTRY
1531 *error = GPG_ERR_NOT_IMPLEMENTED;
1532 return -1;
1533 #else
1534 return do_pwmd_save(pwm, error, 1);
1535 #endif
1538 gpg_error_t pwmd_save(pwm_t *pwm)
1540 gpg_error_t error;
1542 do_pwmd_save(pwm, &error, 0);
1543 return error;
1546 gpg_error_t pwmd_setopt(pwm_t *pwm, pwmd_option_t opt, ...)
1548 va_list ap;
1549 #ifdef USE_PINENTRY
1550 int n = va_arg(ap, int);
1551 char *result;
1552 #endif
1553 char *arg1;
1554 gpg_error_t error = 0;
1556 if (!pwm)
1557 return GPG_ERR_INV_ARG;
1559 va_start(ap, opt);
1561 switch (opt) {
1562 case PWMD_OPTION_STATUS_FUNC:
1563 pwm->status_func = va_arg(ap, pwmd_status_fn);
1564 break;
1565 case PWMD_OPTION_STATUS_DATA:
1566 pwm->status_data = va_arg(ap, void *);
1567 break;
1568 case PWMD_OPTION_PASSWORD_FUNC:
1569 pwm->passfunc = va_arg(ap, pwmd_password_fn);
1570 break;
1571 case PWMD_OPTION_PASSWORD_DATA:
1572 pwm->passdata = va_arg(ap, void *);
1573 break;
1574 case PWMD_OPTION_PASSWORD:
1575 arg1 = va_arg(ap, char *);
1577 if (pwm->password)
1578 xfree(pwm->password);
1580 pwm->password = xstrdup(arg1);
1581 break;
1582 #ifdef USE_PINENTRY
1583 case PWMD_OPTION_PINENTRY:
1584 n = va_arg(ap, int);
1586 if (n != 0 && n != 1) {
1587 va_end(ap);
1588 error = GPG_ERR_INV_VALUE;
1590 else {
1591 pwm->use_pinentry = n;
1592 error = pwmd_command(pwm, &result, "OPTION PINENTRY=%i",
1593 !pwm->use_pinentry);
1595 break;
1596 case PWMD_OPTION_PINENTRY_TRIES:
1597 n = va_arg(ap, int);
1599 if (n <= 0) {
1600 va_end(ap);
1601 error = GPG_ERR_INV_VALUE;
1603 else
1604 pwm->pinentry_tries = n;
1605 break;
1606 case PWMD_OPTION_PINENTRY_PATH:
1607 if (pwm->pinentry_path)
1608 xfree(pwm->pinentry_path);
1610 pwm->pinentry_path = xstrdup(va_arg(ap, char *));
1611 break;
1612 case PWMD_OPTION_PINENTRY_TTY:
1613 if (pwm->pinentry_tty)
1614 xfree(pwm->pinentry_tty);
1616 pwm->pinentry_tty = xstrdup(va_arg(ap, char *));
1617 break;
1618 case PWMD_OPTION_PINENTRY_DISPLAY:
1619 if (pwm->pinentry_display)
1620 xfree(pwm->pinentry_display);
1622 pwm->pinentry_display = xstrdup(va_arg(ap, char *));
1623 break;
1624 case PWMD_OPTION_PINENTRY_TERM:
1625 if (pwm->pinentry_term)
1626 xfree(pwm->pinentry_term);
1628 pwm->pinentry_term = xstrdup(va_arg(ap, char *));
1629 break;
1630 case PWMD_OPTION_PINENTRY_TITLE:
1631 if (pwm->title)
1632 xfree(pwm->title);
1633 pwm->title = percent_escape(va_arg(ap, char *));
1634 break;
1635 case PWMD_OPTION_PINENTRY_PROMPT:
1636 if (pwm->prompt)
1637 xfree(pwm->prompt);
1638 pwm->prompt = percent_escape(va_arg(ap, char *));
1639 break;
1640 case PWMD_OPTION_PINENTRY_DESC:
1641 if (pwm->desc)
1642 xfree(pwm->desc);
1643 pwm->desc = percent_escape(va_arg(ap, char *));
1644 break;
1645 #else
1646 case PWMD_OPTION_PINENTRY:
1647 case PWMD_OPTION_PINENTRY_TRIES:
1648 case PWMD_OPTION_PINENTRY_PATH:
1649 case PWMD_OPTION_PINENTRY_TTY:
1650 case PWMD_OPTION_PINENTRY_DISPLAY:
1651 case PWMD_OPTION_PINENTRY_TERM:
1652 case PWMD_OPTION_PINENTRY_TITLE:
1653 case PWMD_OPTION_PINENTRY_PROMPT:
1654 case PWMD_OPTION_PINENTRY_DESC:
1655 error = GPG_ERR_NOT_IMPLEMENTED;
1656 break;
1657 #endif
1658 default:
1659 error = GPG_ERR_NOT_IMPLEMENTED;
1660 break;
1663 va_end(ap);
1664 return error;
1667 gpg_error_t pwmd_assuan_ctx(pwm_t *pwm, assuan_context_t *ctx, int *fd)
1669 if (!pwm)
1670 return GPG_ERR_INV_ARG;
1672 *ctx = pwm->ctx;
1673 *fd = pwm->fd;
1674 return 0;