2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
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/>.
30 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
48 #include <sys/resource.h>
61 #ifdef HAVE_GETOPT_LONG
66 #include "getopt_long.h"
69 #ifdef HAVE_PR_SET_NAME
70 #include <sys/prctl.h>
73 #include "pwmd-error.h"
81 #include "util-misc.h"
82 #include "util-string.h"
89 /* In tenths of a second. */
92 /* For (tcp_)accept_thread (usec). */
93 #define ACCEPT_TIMEOUT 30000
100 static pthread_cond_t quit_cond
;
101 static pthread_mutex_t quit_mutex
;
102 static int no_passphrase_file
= 0;
104 #ifndef HAVE_PTHREAD_CANCEL
105 static pthread_key_t signal_thread_key
;
111 static pthread_t tls_tid
;
112 static pthread_t tls6_tid
;
113 static int spawned_tls
;
114 static int spawned_tls6
;
116 static int start_stop_tls (int term
);
119 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
120 static int signal_loop (sigset_t sigset
);
122 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
124 #ifndef HAVE_PTHREAD_CANCEL
125 #define INIT_THREAD_SIGNAL do { \
126 struct sigaction act; \
128 sigemptyset (&sigset); \
129 sigaddset (&sigset, SIGUSR2); \
130 pthread_sigmask (SIG_UNBLOCK, &sigset, NULL); \
131 memset (&act, 0, sizeof(act)); \
132 act.sa_flags = SA_SIGINFO; \
133 act.sa_mask = sigset; \
134 act.sa_sigaction = catch_thread_signal; \
135 sigaction (SIGUSR2, &act, NULL); \
139 catch_thread_signal (int sig
, siginfo_t
*info
, void *ctx
)
141 int *n
= (int *) pthread_getspecific (signal_thread_key
);
144 pthread_setspecific (signal_thread_key
, n
);
149 cache_push_from_rcfile ()
151 struct crypto_s
*crypto
;
153 gpg_error_t rc
= init_client_crypto (&crypto
);
157 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
164 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
167 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
173 cache_push
= config_get_list ("global", "cache_push");
178 for (p
= cache_push
; *p
; p
++)
180 (void) do_cache_push (*p
, crypto
);
181 cleanup_crypto_stage1 (crypto
);
184 strv_free (cache_push
);
188 (void) kill_scd (crypto
->agent
);
190 cleanup_crypto (&crypto
);
196 int n
= config_get_boolean ("global", "enable_logging");
200 char *p
= config_get_string ("global", "log_path");
203 logfile
= expand_homedir (p
);
212 log_syslog
= config_get_boolean ("global", "syslog");
214 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
218 reload_rcfile_thread (void *arg
)
220 #ifndef HAVE_PTHREAD_CANCEL
221 int *n
= xmalloc (sizeof (int));
224 pthread_setspecific (signal_thread_key
, n
);
228 #ifdef HAVE_PR_SET_NAME
229 prctl (PR_SET_NAME
, "reload rcfile");
231 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
232 MUTEX_LOCK (&rcfile_mutex
);
233 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
237 struct slist_s
*config
;
239 int b
= disable_list_and_dump
;
242 int tcp_require_key
= config_get_bool_param (global_config
, "global",
247 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
248 #ifndef HAVE_PTHREAD_CANCEL
249 int *n
= (int *) pthread_getspecific (signal_thread_key
);
254 users
= config_get_list ("global", "allowed");
255 log_write (_("reloading configuration file '%s'"), rcfile
);
256 config
= config_parse (rcfile
);
259 config_free (global_config
);
260 global_config
= config
;
262 cache_push_from_rcfile ();
263 config_clear_keys ();
266 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
268 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
272 config_set_bool_param (&global_config
, "global", "tcp_require_key",
273 tcp_require_key
? "true" : "false");
275 char *tmp
= strv_join (",", users
);
276 config_set_list_param (&global_config
, "global", "allowed", tmp
);
280 /* Kill existing listening threads since the configured listening
281 * protocols may have changed. */
287 pthread_cleanup_pop (1);
292 send_error (assuan_context_t ctx
, gpg_error_t e
)
294 struct client_s
*client
= assuan_get_pointer (ctx
);
296 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
303 return assuan_process_done (ctx
, 0);
307 log_write ("%s", pwmd_strerror (e
));
311 if (gpg_err_code (e
) == GPG_ERR_BAD_DATA
)
313 xmlErrorPtr xe
= client
->xml_error
;
316 xe
= xmlGetLastError ();
319 log_write ("%s", xe
->message
);
320 if (client
->last_error
)
321 xfree (client
->last_error
);
323 client
->last_error
= str_dup (xe
->message
);
326 e
= assuan_process_done (ctx
, assuan_set_error (ctx
, e
,
330 if (xe
== client
->xml_error
)
333 xmlResetLastError ();
335 client
->xml_error
= NULL
;
339 return assuan_process_done (ctx
,
340 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
344 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
347 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
351 pthread_mutex_lock (&m
);
352 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
353 t
= strv_length (debug_level
);
355 for (i
= 0; i
< t
; i
++)
357 if (!strcasecmp (debug_level
[i
], (char *) "init")
358 && cat
== ASSUAN_LOG_INIT
)
364 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
365 && cat
== ASSUAN_LOG_CTX
)
371 if (!strcasecmp (debug_level
[i
], (char *) "engine")
372 && cat
== ASSUAN_LOG_ENGINE
)
378 if (!strcasecmp (debug_level
[i
], (char *) "data")
379 && cat
== ASSUAN_LOG_DATA
)
385 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
386 && cat
== ASSUAN_LOG_SYSIO
)
392 if (!strcasecmp (debug_level
[i
], (char *) "control")
393 && cat
== ASSUAN_LOG_CONTROL
)
407 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
408 warn ("%s", logfile
);
411 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
412 write (fd
, msg
, strlen (msg
));
413 pthread_cleanup_pop (1);
419 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
424 pthread_cleanup_pop (1);
429 log_write (const char *fmt
, ...)
439 pthread_t tid
= pthread_self ();
440 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
442 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
445 pthread_mutex_lock (&m
);
446 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
447 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
449 if (!cmdline
&& logfile
)
451 if ((fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
452 warn ("%s", logfile
);
457 if (str_vasprintf (&args
, fmt
, ap
) != -1)
461 pthread_cleanup_push (xfree
, args
);
462 fprintf (stderr
, "%s\n", args
);
464 pthread_cleanup_pop (1);
468 pthread_cleanup_push (xfree
, args
);
469 name
= pthread_getspecific (thread_name_key
);
470 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
474 if (!cmdline
&& log_syslog
&& !nofork
)
475 syslog (LOG_INFO
, "%s%s", name
, args
);
478 tm
= localtime (&now
);
479 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
480 tbuf
[sizeof (tbuf
) - 1] = 0;
482 if (args
[strlen (args
) - 1] == '\n')
483 args
[strlen (args
) - 1] = 0;
485 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
, args
);
486 pthread_cleanup_pop (1);
489 pthread_cleanup_push (xfree
, line
);
490 if (logfile
&& fd
!= -1)
492 write (fd
, line
, strlen (line
));
498 fprintf (stdout
, "%s", line
);
502 pthread_cleanup_pop (1);
508 pthread_cleanup_pop (1);
509 pthread_cleanup_pop (0);
510 pthread_mutex_unlock (&m
);
515 secure_mem_check (const void *arg
)
524 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
526 if (!gcry_check_version (GCRYPT_VERSION
))
528 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
529 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
530 gcry_check_version (NULL
));
531 return GPG_ERR_UNKNOWN_VERSION
;
534 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
538 #ifdef HAVE_GETGRNAM_R
540 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
546 rc
= assuan_get_peercred (cl
->ctx
, peer
);
550 users
= config_get_list ("global", "allowed");
553 for (char **p
= users
; *p
; p
++)
555 struct passwd pw
, *result
;
556 struct group gr
, *gresult
;
561 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
570 return GPG_ERR_ENOMEM
;
573 if (!getgrnam_r (*(p
) + 1, &gr
, buf
, len
, &gresult
) && gresult
)
575 if (gresult
->gr_gid
== (*peer
)->gid
)
582 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
586 char *tbuf
= xmalloc (len
);
587 for (char **t
= gresult
->gr_mem
; *t
; t
++)
589 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
591 if (result
->pw_uid
== (*peer
)->uid
)
608 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
618 return GPG_ERR_ENOMEM
;
621 if (!getpwnam_r (*p
, &pw
, buf
, len
, &result
) && result
)
623 if (result
->pw_uid
== (*peer
)->uid
)
638 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
642 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
648 rc
= assuan_get_peercred (cl
->ctx
, peer
);
652 users
= config_get_list ("global", "allowed");
655 for (char **p
= users
; *p
; p
++)
657 struct passwd
*result
;
658 struct group
*gresult
;
662 gresult
= getgrnam (*(p
) + 1);
663 if (gresult
&& gresult
->gr_gid
== (*peer
)->gid
)
669 for (char **t
= gresult
->gr_mem
; *t
; t
++)
671 result
= getpwnam (*t
);
672 if (result
&& result
->pw_uid
== (*peer
)->uid
)
681 result
= getpwnam (*p
);
682 if (result
&& result
->pw_uid
== (*peer
)->uid
)
696 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
701 validate_peer (struct client_s
*cl
)
704 assuan_peercred_t peer
;
711 rc
= do_validate_peer (cl
, &peer
);
712 if (!rc
|| gpg_err_code (rc
) == GPG_ERR_INV_USER_ID
)
713 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
714 !rc
? _("accepted") : _("rejected"), peer
->uid
, peer
->gid
,
717 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
723 xml_error_cb (void *data
, xmlErrorPtr e
)
725 struct client_s
*client
= data
;
728 * Keep the first reported error as the one to show in the error
729 * description. Reset in send_error().
731 if (client
->xml_error
)
734 xmlCopyError (e
, client
->xml_error
);
738 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
739 int *status
, int options
)
741 return waitpid (pid
, status
, options
);
745 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
748 struct client_s
*client
= assuan_get_pointer (ctx
);
750 if (client
->thd
->remote
)
751 return tls_read_hook (ctx
, (int) fd
, data
, len
);
754 return read ((int) fd
, data
, len
);
758 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
759 const void *data
, size_t len
)
762 struct client_s
*client
= assuan_get_pointer (ctx
);
764 if (client
->thd
->remote
)
765 return tls_write_hook (ctx
, (int) fd
, data
, len
);
768 return write ((int) fd
, data
, len
);
772 new_connection (struct client_s
*cl
)
775 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
776 static struct assuan_system_hooks shooks
= {
777 ASSUAN_SYSTEM_HOOKS_VERSION
,
785 NULL
, //sendmsg both are used for FD passing
796 char *prio
= config_get_string ("global", "tls_cipher_suite");
798 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, prio
);
805 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
806 debug_level
? assuan_log_cb
: NULL
, NULL
);
810 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
811 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
815 assuan_set_pointer (cl
->ctx
, cl
);
816 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
817 rc
= register_commands (cl
->ctx
);
821 rc
= assuan_accept (cl
->ctx
);
825 rc
= validate_peer (cl
);
826 /* May not be implemented on all platforms. */
827 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
830 rc
= init_client_crypto (&cl
->crypto
);
836 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
839 cl
->crypto
->client_ctx
= cl
->ctx
;
840 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
844 log_write ("%s", pwmd_strerror (rc
));
849 * This is called after a client_thread() terminates. Set with
850 * pthread_cleanup_push().
853 cleanup_cb (void *arg
)
855 struct client_thread_s
*cn
= arg
;
856 struct client_s
*cl
= cn
->cl
;
858 MUTEX_LOCK (&cn_mutex
);
859 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
860 MUTEX_UNLOCK (&cn_mutex
);
869 gnutls_deinit (cn
->tls
->ses
);
876 assuan_release (cl
->ctx
);
877 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
881 cleanup_crypto (&cl
->crypto
);
891 while (cn
->msg_queue
)
893 struct status_msg_s
*msg
= cn
->msg_queue
;
895 cn
->msg_queue
= msg
->next
;
900 if (cn
->status_msg_pipe
[0] != -1)
901 close (cn
->status_msg_pipe
[0]);
903 if (cn
->status_msg_pipe
[1] != -1)
904 close (cn
->status_msg_pipe
[1]);
906 pthread_mutex_destroy (&cn
->status_mutex
);
907 log_write (_("exiting, fd=%i"), cn
->fd
);
909 send_status_all (STATUS_CLIENTS
, NULL
);
910 pthread_cond_signal (&quit_cond
);
914 send_msg_queue (struct client_thread_s
*thd
)
916 MUTEX_LOCK (&thd
->status_mutex
);
920 read (thd
->status_msg_pipe
[0], &c
, 1);
922 while (thd
->msg_queue
)
924 struct status_msg_s
*msg
= thd
->msg_queue
;
926 thd
->msg_queue
= thd
->msg_queue
->next
;
927 MUTEX_UNLOCK (&thd
->status_mutex
);
928 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
929 MUTEX_LOCK (&thd
->status_mutex
);
937 MUTEX_UNLOCK (&thd
->status_mutex
);
942 client_thread (void *data
)
944 struct client_thread_s
*thd
= data
;
945 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
947 #ifdef HAVE_PR_SET_NAME
948 prctl (PR_SET_NAME
, "client");
950 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
954 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
955 pwmd_strerror (GPG_ERR_ENOMEM
));
959 MUTEX_LOCK (&cn_mutex
);
960 pthread_cleanup_push (cleanup_cb
, thd
);
963 MUTEX_UNLOCK (&cn_mutex
);
965 if (new_connection (cl
))
970 send_status_all (STATUS_CLIENTS
, NULL
);
971 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
974 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
985 FD_SET (thd
->fd
, &rfds
);
986 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
989 thd
->status_msg_pipe
[0] ? thd
->fd
: thd
->status_msg_pipe
[0];
991 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
994 log_write ("%s", strerror (errno
));
998 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1000 rc
= send_msg_queue (thd
);
1001 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1003 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
1004 pwmd_strerror (rc
));
1009 if (!FD_ISSET (thd
->fd
, &rfds
))
1012 rc
= assuan_process_next (cl
->ctx
, &eof
);
1015 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1018 log_write ("assuan_process_next(): %s", pwmd_strerror (rc
));
1019 rc
= send_error (cl
->ctx
, rc
);
1023 log_write ("assuan_process_done(): %s", pwmd_strerror (rc
));
1028 /* Since the msg queue pipe fd's are non-blocking, check for
1029 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1030 * client has already disconnected and will be converted to
1031 * GPG_ERR_EOF during assuan_process_next().
1033 rc
= send_msg_queue (thd
);
1034 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1036 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
1037 pwmd_strerror (rc
));
1043 pthread_cleanup_pop (1);
1048 xml_import (const char *filename
, const char *outfile
,
1049 const char *keygrip
, const char *sign_keygrip
,
1050 const char *keyfile
, int no_passphrase
, const char *cipher
,
1051 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1060 struct crypto_s
*crypto
;
1063 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1068 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1069 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1073 if (stat (filename
, &st
) == -1)
1075 log_write ("%s: %s", filename
,
1076 pwmd_strerror (gpg_error_from_syserror ()));
1080 rc
= init_client_crypto (&crypto
);
1084 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1085 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1086 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1089 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1091 log_write ("%s: %s", filename
,
1092 pwmd_strerror (gpg_error_from_syserror ()));
1096 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1099 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1100 pwmd_strerror (GPG_ERR_ENOMEM
));
1104 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1106 rc
= gpg_error_from_syserror ();
1108 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1113 xmlbuf
[st
.st_size
] = 0;
1115 * Make sure the document validates.
1117 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1119 log_write ("xmlReadDoc() failed");
1125 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1126 if (!xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1128 log_write (_("Could not find root \"pwmd\" element."));
1129 rc
= GPG_ERR_BAD_DATA
;
1133 rc
= validate_import (n
? n
->children
: n
);
1137 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1142 xmlDocDumpMemory (doc
, &xml
, &len
);
1144 crypto
->save
.s2k_count
= s2k_count
;
1145 crypto
->save
.hdr
.iterations
= iterations
;
1147 rc
= export_common (NULL
, crypto
, no_passphrase
, xml
, len
, outfile
,
1148 keyfile
, &key
, &keylen
, 1, 0);
1152 rc
= agent_set_pinentry_options (crypto
->agent
);
1154 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1155 xml
, len
, outfile
, params
, keyfile
);
1163 send_error (NULL
, rc
);
1167 cleanup_crypto (&crypto
);
1171 cleanup_crypto (&crypto
);
1176 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1178 unsigned char md5file
[16];
1183 struct cache_data_s
*cdata
;
1187 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1190 if (valid_filename (filename
) == 0)
1192 log_write (_("%s: Invalid characters in filename"), filename
);
1196 rc
= decrypt_common (crypto
, filename
, &key
, &keylen
);
1200 doc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
);
1203 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1208 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1209 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1213 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1218 rc
= get_checksum (filename
, &crc
, &len
);
1221 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1223 free_cache_data_once (cdata
);
1229 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1230 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1231 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1232 if (!rc
&& !IS_PKCS (crypto
))
1235 cdata
->keylen
= keylen
;
1242 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1244 free_cache_data_once (cdata
);
1251 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1253 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1254 crypto
->sigpkey_sexp
);
1258 int timeout
= config_get_integer (filename
, "cache_timeout");
1259 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1260 log_write (_("Successfully added '%s' to the cache."), filename
);
1265 init_client (int fd
, const char *addr
)
1268 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1273 return GPG_ERR_ENOMEM
;
1276 MUTEX_LOCK (&cn_mutex
);
1277 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1279 if (pipe (new->status_msg_pipe
) == -1)
1280 rc
= gpg_error_from_syserror ();
1284 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1285 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1286 pthread_mutex_init (&new->status_mutex
, NULL
);
1292 new->remote
= addr
? 1 : 0;
1295 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1298 close (new->status_msg_pipe
[0]);
1299 close (new->status_msg_pipe
[1]);
1300 pthread_mutex_destroy (&new->status_mutex
);
1306 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1310 cn_thread_list
= list
;
1312 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1313 (pthread_t
*) new->tid
, fd
, addr
);
1315 log_write (_("new connection: tid=%p, fd=%i"),
1316 (pthread_t
*) new->tid
, fd
);
1319 rc
= GPG_ERR_ENOMEM
;
1322 pthread_cleanup_pop (1);
1328 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1329 pwmd_strerror (rc
));
1335 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1337 get_in_addr (struct sockaddr
*sa
)
1339 if (sa
->sa_family
== AF_INET
)
1340 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1342 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1346 tcp_accept_thread (void *arg
)
1348 int sockfd
= *(int *) arg
;
1349 #ifndef HAVE_PTHREAD_CANCEL
1350 int *n
= xmalloc (sizeof (int));
1353 pthread_setspecific (signal_thread_key
, n
);
1355 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1358 #ifdef HAVE_PR_SET_NAME
1359 prctl (PR_SET_NAME
, "tcp_accept");
1361 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1365 struct sockaddr_storage raddr
;
1366 socklen_t slen
= sizeof (raddr
);
1369 char s
[INET6_ADDRSTRLEN
];
1370 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1371 #ifndef HAVE_PTHREAD_CANCEL
1374 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1379 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1382 if (errno
== EMFILE
|| errno
== ENFILE
)
1383 log_write ("accept(): %s",
1384 pwmd_strerror (gpg_error_from_syserror ()));
1385 else if (errno
!= EAGAIN
)
1387 if (!quit
) // probably EBADF
1388 log_write ("accept(): %s", strerror (errno
));
1393 #ifndef HAVE_PTHREAD_CANCEL
1394 select (0, NULL
, NULL
, NULL
, &tv
);
1402 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1404 (void) init_client (fd
, s
);
1405 n
= config_get_integer ("global", "tcp_wait");
1408 tv
.tv_sec
= (n
* 100000) / 100000;
1409 tv
.tv_usec
= (n
* 100000) % 100000;
1410 select (0, NULL
, NULL
, NULL
, &tv
);
1418 start_stop_tls_with_protocol (int ipv6
, int term
)
1420 struct addrinfo hints
, *servinfo
, *p
;
1421 int port
= config_get_integer ("global", "tcp_port");
1425 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1427 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1433 #ifdef HAVE_PTHREAD_CANCEL
1434 pthread_cancel (tls6_tid
);
1436 pthread_kill (tls6_tid
, SIGUSR2
);
1438 pthread_join (tls6_tid
, NULL
);
1441 shutdown (tls6_fd
, SHUT_RDWR
);
1451 #ifdef HAVE_PTHREAD_CANCEL
1452 pthread_cancel (tls_tid
);
1454 pthread_kill (tls_tid
, SIGUSR2
);
1456 pthread_join (tls_tid
, NULL
);
1459 shutdown (tls_fd
, SHUT_RDWR
);
1465 /* A client may still be connected. */
1466 if (!quit
&& x509_cred
!= NULL
)
1467 tls_deinit_params ();
1472 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1475 memset (&hints
, 0, sizeof (hints
));
1476 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1477 hints
.ai_socktype
= SOCK_STREAM
;
1478 hints
.ai_flags
= AI_PASSIVE
;
1479 snprintf (buf
, sizeof (buf
), "%i", port
);
1481 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1483 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1487 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1491 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1492 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1495 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1497 log_write ("socket(): %s", strerror (errno
));
1501 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1503 log_write ("setsockopt(): %s",
1504 pwmd_strerror (gpg_error_from_syserror ()));
1505 freeaddrinfo (servinfo
);
1509 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1512 log_write ("bind(): %s",
1513 pwmd_strerror (gpg_error_from_syserror ()));
1521 freeaddrinfo (servinfo
);
1526 #if HAVE_DECL_SO_BINDTODEVICE != 0
1527 char *tmp
= config_get_string ("global", "tcp_interface");
1528 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
, 1) == -1)
1530 log_write ("setsockopt(): %s",
1531 pwmd_strerror (gpg_error_from_syserror ()));
1539 if (x509_cred
== NULL
)
1541 rc
= tls_init_params ();
1546 if (listen (*fd
, 0) == -1)
1548 log_write ("listen(): %s", strerror (errno
));
1553 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1555 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1559 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1560 pwmd_strerror (rc
));
1572 start_stop_tls_with_protocol (0, 1);
1585 start_stop_tls (int term
)
1587 char *s
= config_get_string ("global", "tcp_bind");
1593 if (!strcmp (s
, "any"))
1595 b
= start_stop_tls_with_protocol (0, term
);
1597 b
= start_stop_tls_with_protocol (1, term
);
1599 else if (!strcmp (s
, "ipv4"))
1600 b
= start_stop_tls_with_protocol (0, term
);
1601 else if (!strcmp (s
, "ipv6"))
1602 b
= start_stop_tls_with_protocol (1, term
);
1612 accept_thread (void *arg
)
1614 int sockfd
= *(int *) arg
;
1615 #ifndef HAVE_PTHREAD_CANCEL
1616 int *n
= xmalloc (sizeof (int));
1619 pthread_setspecific (signal_thread_key
, n
);
1621 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1624 #ifdef HAVE_PR_SET_NAME
1625 prctl (PR_SET_NAME
, "accept");
1627 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1631 socklen_t slen
= sizeof (struct sockaddr_un
);
1632 struct sockaddr_un raddr
;
1634 #ifndef HAVE_PTHREAD_CANCEL
1635 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1636 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1642 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1645 if (errno
== EMFILE
|| errno
== ENFILE
)
1646 log_write ("accept(): %s",
1647 pwmd_strerror (gpg_error_from_syserror ()));
1648 else if (errno
!= EAGAIN
)
1650 if (!quit
) // probably EBADF
1651 log_write ("accept(): %s",
1652 pwmd_strerror (gpg_error_from_syserror ()));
1657 #ifndef HAVE_PTHREAD_CANCEL
1658 select (0, NULL
, NULL
, NULL
, &tv
);
1663 (void) init_client (fd
, NULL
);
1666 /* Just in case accept() failed for some reason other than EBADF */
1672 cache_timer_thread (void *arg
)
1674 #ifndef HAVE_PTHREAD_CANCEL
1675 int *n
= xmalloc (sizeof (int));
1678 pthread_setspecific (signal_thread_key
, n
);
1682 #ifdef HAVE_PR_SET_NAME
1683 prctl (PR_SET_NAME
, "cache timer");
1685 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1689 struct timeval tv
= { 1, 0 };
1690 #ifndef HAVE_PTHREAD_CANCEL
1693 n
= (int *) pthread_getspecific (signal_thread_key
);
1698 select (0, NULL
, NULL
, NULL
, &tv
);
1699 cache_adjust_timeout ();
1706 catch_sigabrt (int sig
)
1715 signal_loop (sigset_t sigset
)
1724 sigwait (&sigset
, &sig
);
1727 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1732 pthread_cond_signal (&rcfile_cond
);
1735 // not really handled here.
1736 catch_sigabrt (SIGABRT
);
1739 log_write (_("clearing file cache"));
1741 send_status_all (STATUS_CACHE
, NULL
);
1760 log_write ("Caught SIGSEGV. Exiting.");
1761 #ifdef HAVE_BACKTRACE
1762 BACKTRACE (__FUNCTION__
);
1768 waiting_for_exit (void *arg
)
1771 #ifndef HAVE_PTHREAD_CANCEL
1772 int *n
= xmalloc (sizeof (int));
1775 pthread_setspecific (signal_thread_key
, n
);
1779 #ifdef HAVE_PR_SET_NAME
1780 prctl (PR_SET_NAME
, "exiting");
1782 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1783 log_write (_("waiting for all clients to disconnect"));
1784 MUTEX_LOCK (&quit_mutex
);
1785 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1792 MUTEX_LOCK (&cn_mutex
);
1793 n
= slist_length (cn_thread_list
);
1794 MUTEX_UNLOCK (&cn_mutex
);
1798 #ifndef HAVE_PTHREAD_CANCEL
1799 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1806 log_write (_("%i clients remain"), n
);
1810 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1811 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1814 kill (getpid (), SIGQUIT
);
1815 pthread_cleanup_pop (1);
1820 server_loop (int sockfd
, char **socketpath
)
1822 pthread_t accept_tid
;
1823 pthread_t cache_timeout_tid
;
1824 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1831 sigemptyset (&sigset
);
1834 sigaddset (&sigset
, SIGTERM
);
1835 sigaddset (&sigset
, SIGINT
);
1837 /* Clears the file cache. */
1838 sigaddset (&sigset
, SIGUSR1
);
1840 /* Configuration file reloading. */
1841 sigaddset (&sigset
, SIGHUP
);
1843 /* For exiting cleanly. */
1844 sigaddset (&sigset
, SIGQUIT
);
1846 #ifndef HAVE_PTHREAD_CANCEL
1848 The socket, cache and rcfile threads use this signal when
1849 pthread_cancel() is unavailable. Prevent the main thread from
1850 catching this signal from another process.
1852 sigaddset (&sigset
, SIGUSR2
);
1855 /* Clears the cache and exits when something bad happens. */
1856 signal (SIGABRT
, catch_sigabrt
);
1857 sigaddset (&sigset
, SIGABRT
);
1858 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1860 #ifndef HAVE_PTHREAD_CANCEL
1861 /* Remove this signal from the watched signals in signal_loop(). */
1862 sigdelset (&sigset
, SIGUSR2
);
1865 /* Ignored everywhere. When a client disconnects abnormally this signal
1866 * gets raised. It isn't needed though because client_thread() will check
1867 * for rcs even after the client disconnects. */
1868 signal (SIGPIPE
, SIG_IGN
);
1870 /* Can show a backtrace of the stack in the log. */
1871 signal (SIGSEGV
, catchsig
);
1874 /* Needs to be done after the fork(). */
1875 if (!start_stop_tls (0))
1882 pthread_mutex_init (&quit_mutex
, NULL
);
1883 pthread_cond_init (&quit_cond
, NULL
);
1884 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
1887 if (config_get_boolean ("global", "enable_tcp"))
1888 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1889 config_get_integer ("global", "tcp_port"));
1891 log_write (_("Listening on %s"), *socketpath
);
1893 log_write (_("Listening on %s"), *socketpath
);
1896 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1899 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1900 pwmd_strerror (rc
));
1904 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
1907 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1908 pwmd_strerror (rc
));
1912 cancel_timeout_thread
= 1;
1913 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
1916 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1917 pwmd_strerror (rc
));
1921 cancel_accept_thread
= 1;
1923 signal_loop (sigset
);
1929 * We're out of the main server loop. This happens when a signal was sent
1930 * to terminate the daemon. We'll wait for all clients to disconnect
1931 * before exiting but exit immediately if another termination signal is
1934 if (cancel_accept_thread
)
1936 #ifdef HAVE_PTHREAD_CANCEL
1937 int n
= pthread_cancel (accept_tid
);
1939 int n
= pthread_kill (accept_tid
, SIGUSR2
);
1942 pthread_join (accept_tid
, NULL
);
1948 shutdown (sockfd
, SHUT_RDWR
);
1950 unlink (*socketpath
);
1951 xfree (*socketpath
);
1953 MUTEX_LOCK (&cn_mutex
);
1954 n
= slist_length (cn_thread_list
);
1955 MUTEX_UNLOCK (&cn_mutex
);
1961 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
1964 if (signal_loop (sigset
))
1966 log_write (_("Received second termination request. Exiting."));
1967 #ifdef HAVE_PTHREAD_CANCEL
1968 pthread_cancel (tid
);
1970 pthread_kill (tid
, SIGUSR2
);
1972 pthread_join (tid
, NULL
);
1976 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1977 pwmd_strerror (rc
));
1980 if (cancel_timeout_thread
)
1982 #ifdef HAVE_PTHREAD_CANCEL
1983 pthread_cancel (cache_timeout_tid
);
1985 pthread_kill (cache_timeout_tid
, SIGUSR2
);
1987 pthread_join (cache_timeout_tid
, NULL
);
1990 MUTEX_LOCK (&cn_mutex
);
1992 n
= slist_length (cn_thread_list
);
1994 for (i
= 0; i
< n
; i
++)
1996 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2006 MUTEX_UNLOCK (&cn_mutex
);
2012 pthread_cond_destroy (&quit_cond
);
2013 pthread_mutex_destroy (&quit_mutex
);
2014 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2021 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2025 /* This is called from cache.c:clear_once(). See
2026 * command.c:clearcache_command() for details about lock checking.
2029 free_cache_data (file_cache_t
* cache
)
2031 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2033 struct client_thread_s
*found
= NULL
;
2040 MUTEX_LOCK (&cn_mutex
);
2041 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2042 t
= slist_length (cn_thread_list
);
2044 for (i
= 0; i
< t
; i
++)
2046 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2051 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2052 sizeof (cache
->filename
)))
2054 if (pthread_equal (pthread_self (), thd
->tid
))
2061 /* Continue trying to find a client who has the same file open and
2062 * also has a lock. */
2063 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2073 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2074 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2076 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2078 free_cache_data_once (cache
->data
);
2080 cache
->defer_clear
= 0;
2081 cache
->timeout
= -1;
2084 cache_unlock_mutex (found
->cl
->md5file
, 0);
2090 cache
->defer_clear
= 1;
2092 pthread_cleanup_pop (1);
2098 convert_v2_datafile (const char *filename
, const char *cipher
,
2099 const char *keyfile
, const char *keygrip
,
2100 const char *sign_keygrip
, int nopass
,
2101 const char *outfile
, const char *keyparam
,
2102 unsigned long s2k_count
, uint64_t iterations
)
2107 struct crypto_s
*crypto
= NULL
;
2113 if (outfile
[0] == '-' && outfile
[1] == 0)
2116 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2117 if (access (filename
, R_OK
) == -1)
2119 log_write ("%s: %s", filename
,
2120 pwmd_strerror (gpg_error_from_syserror ()));
2126 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2128 if (access (keyfile
, R_OK
) == -1)
2130 log_write ("%s: %s", keyfile
,
2131 pwmd_strerror (gpg_error_from_syserror ()));
2136 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2139 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2145 algo
= cipher_string_to_gcrypt (cipher
);
2148 rc
= GPG_ERR_CIPHER_ALGO
;
2155 xmlDocPtr doc
= parse_doc (data
, datalen
);
2159 rc
= GPG_ERR_BAD_DATA
;
2163 rc
= convert_pre_212_elements (doc
);
2168 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2171 rc
= GPG_ERR_ENOMEM
;
2179 rc
= init_client_crypto (&crypto
);
2182 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2183 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2184 crypto
->save
.s2k_count
= s2k_count
;
2185 crypto
->save
.hdr
.iterations
= iterations
;
2190 rc
= agent_set_pinentry_options (crypto
->agent
);
2192 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2193 data
, datalen
, outfile
, keyparam
,
2194 no_passphrase_file
? NULL
: keyfile
);
2197 rc
= export_common (NULL
, crypto
, nopass
, data
, datalen
, outfile
,
2198 keyfile
, &key
, &keylen
, 1, 0);
2200 rc
= export_common (NULL
, crypto
, nopass
, data
, datalen
, outfile
,
2201 keyfile
, &key
, &keylen
, 1, 0);
2204 log_write (_("Output written to \"%s\"."), outfile
);
2214 cleanup_crypto (&crypto
);
2217 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2222 usage (const char *pn
, int status
)
2224 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2226 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2227 " -f, --rcfile=filename load the specfied configuration file\n"
2228 " (~/.pwmd/config)\n"
2229 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2231 " --no-agent disable use of gpg-agent\n"
2233 " -n, --no-fork run as a foreground process\n"
2234 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2235 " --ignore ignore file errors during startup\n"
2236 " --debug-level=keywords log protocol output (see manual for details)\n"
2237 " -o, --outfile=filename output file when importing or converting\n"
2238 " -C, --convert=filename convert a version 2 data file to version 3\n"
2239 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2240 " -k, --passphrase-file=file for use when importing or converting\n"
2241 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2243 " --no-passphrase when importing or converting\n"
2244 " --keygrip=hex public key to use when encrypting\n"
2245 " --sign-keygrip=hex private key to use when signing\n"
2246 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2247 " --cipher=string encryption cipher (aes256)\n"
2248 " --iterations=N cipher iteration count (N+1)\n"
2249 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2250 " --help this help text\n"
2251 " --version show version and compile time features\n"),
2257 main (int argc
, char *argv
[])
2260 struct sockaddr_un addr
;
2262 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2263 char *socketarg
= NULL
;
2264 char *datadir
= NULL
;
2267 char **cache_push
= NULL
;
2268 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2269 char *keyparam
= NULL
;
2270 int estatus
= EXIT_FAILURE
;
2272 char *outfile
= NULL
;
2275 int show_version
= 0;
2277 int no_passphrase
= 0;
2279 char *convertfile
= NULL
;
2280 char *cipher
= NULL
;
2281 char *keyfile
= NULL
;
2282 unsigned long s2k_count
= 0;
2283 uint64_t iterations
= 0;
2285 char *debug_level_opt
= NULL
;
2287 /* Must maintain the same order as longopts[] */
2289 { OPT_VERSION
, OPT_HELP
,
2293 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
, OPT_IGNORE
,
2294 OPT_RCFILE
, OPT_CONVERT
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2295 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
, OPT_KEYPARAM
,
2296 OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
, OPT_NO_PASSPHRASE
2298 const char *optstring
= "nf:C:k:I:o:";
2299 const struct option longopts
[] = {
2300 {"version", no_argument
, 0, 0},
2301 {"help", no_argument
, 0, 0},
2303 {"no-agent", no_argument
, 0, 0},
2305 {"debug-level", required_argument
, 0, 0},
2306 {"homedir", required_argument
, 0, 0},
2307 {"no-fork", no_argument
, 0, 'n'},
2308 {"disable_dump", no_argument
, 0, 0},
2309 {"ignore", no_argument
, 0, 0},
2310 {"rcfile", required_argument
, 0, 'f'},
2311 {"convert", required_argument
, 0, 'C'},
2312 {"passphrase-file", required_argument
, 0, 'k'},
2313 {"import", required_argument
, 0, 'I'},
2314 {"outfile", required_argument
, 0, 'o'},
2315 {"no-passphrase-file", no_argument
, 0, 0},
2316 {"keygrip", required_argument
, 0, 0},
2317 {"sign-keygrip", required_argument
, 0, 0},
2318 {"keyparam", required_argument
, 0, 0},
2319 {"cipher", required_argument
, 0, 0},
2320 {"cipher-iterations", required_argument
, 0, 0},
2321 {"s2k-count", required_argument
, 0, 0},
2322 {"no-passphrase", no_argument
, 0, 0},
2327 #ifdef HAVE_SETRLIMIT
2330 rl
.rlim_cur
= rl
.rlim_max
= 0;
2332 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2333 err (EXIT_FAILURE
, "setrlimit()");
2338 setlocale (LC_ALL
, "");
2339 bindtextdomain ("pwmd", LOCALEDIR
);
2340 textdomain ("pwmd");
2348 if (setup_crypto ())
2349 exit (EXIT_FAILURE
);
2352 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2354 gnutls_global_init ();
2355 gnutls_global_set_log_function (tls_log
);
2356 gnutls_global_set_log_level (1);
2360 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2371 getopt_long (argc
, argv
, optstring
, longopts
, &optindex
)) != -1)
2379 convertfile
= optarg
;
2394 rcfile
= str_dup (optarg
);
2397 usage (argv
[0], EXIT_FAILURE
);
2413 case OPT_DEBUG_LEVEL
:
2414 debug_level_opt
= optarg
;
2417 homedir
= str_dup (optarg
);
2422 case OPT_DISABLE_DUMP
:
2429 rcfile
= str_dup (optarg
);
2432 convertfile
= optarg
;
2434 case OPT_PASSPHRASE_FILE
:
2443 case OPT_NO_PASSPHRASE_FILE
:
2444 no_passphrase_file
= 1;
2449 case OPT_SIGN_KEYGRIP
:
2450 sign_keygrip
= optarg
;
2458 case OPT_ITERATIONS
:
2459 iterations
= strtoull (optarg
, NULL
, 10);
2462 s2k_count
= strtoul (optarg
, NULL
, 10);
2464 case OPT_NO_PASSPHRASE
:
2476 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
2478 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2479 "Compile time features:\n%s"), PACKAGE_STRING
,
2482 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2515 exit (EXIT_SUCCESS
);
2520 homedir
= str_dup(PWMD_HOMEDIR
);
2522 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2525 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2526 err (EXIT_FAILURE
, "%s", homedir
);
2528 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2529 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2530 err (EXIT_FAILURE
, "%s", buf
);
2532 datadir
= str_dup (buf
);
2533 pthread_mutexattr_t attr
;
2534 pthread_mutexattr_init (&attr
);
2535 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2536 pthread_mutex_init (&rcfile_mutex
, &attr
);
2537 pthread_cond_init (&rcfile_cond
, NULL
);
2538 pthread_mutex_init (&cn_mutex
, &attr
);
2539 pthread_mutexattr_destroy (&attr
);
2540 pthread_key_create (&last_error_key
, free_key
);
2541 #ifndef HAVE_PTHREAD_CANCEL
2542 pthread_key_create (&signal_thread_key
, free_key
);
2546 rcfile
= str_asprintf ("%s/config", homedir
);
2548 global_config
= config_parse (rcfile
);
2550 exit (EXIT_FAILURE
);
2554 if (debug_level_opt
)
2555 debug_level
= str_split (debug_level_opt
, ",", 0);
2557 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2558 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2561 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2563 log_write ("setpriority(): %s",
2564 pwmd_strerror (gpg_error_from_syserror ()));
2568 #ifdef HAVE_MLOCKALL
2569 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2571 log_write ("mlockall(): %s",
2572 pwmd_strerror (gpg_error_from_syserror ()));
2577 rc
= cache_init (free_cache_data
);
2580 log_write ("pwmd: ERR %i: %s", rc
,
2581 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2582 ? _("incompatible version: 2.1.0 or later required")
2583 : pwmd_strerror (rc
));
2588 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2593 usage (argv
[0], EXIT_FAILURE
);
2595 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2596 sign_keygrip
, no_passphrase
, outfile
,
2597 keyparam
, s2k_count
, iterations
);
2598 config_free (global_config
);
2606 usage (argv
[0], EXIT_FAILURE
);
2608 if (outfile
[0] == '-' && outfile
[1] == 0)
2611 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2612 no_passphrase
, cipher
, keyparam
, s2k_count
,
2614 config_free (global_config
);
2619 p
= config_get_string ("global", "socket_path");
2621 p
= str_asprintf ("%s/socket", homedir
);
2623 socketarg
= expand_homedir (p
);
2627 disable_list_and_dump
= config_get_boolean ("global",
2628 "disable_list_and_dump");
2630 disable_list_and_dump
= secure
;
2632 cache_push
= config_get_list ("global", "cache_push");
2634 while (optind
< argc
)
2636 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2637 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2640 if (strchr (socketarg
, '/') == NULL
)
2642 socketdir
= getcwd (buf
, sizeof (buf
));
2643 socketname
= str_dup (socketarg
);
2644 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2648 socketname
= str_dup (strrchr (socketarg
, '/'));
2650 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2651 socketdir
= str_dup (socketarg
);
2652 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2655 if (chdir (datadir
))
2657 log_write ("%s: %s", datadir
,
2658 pwmd_strerror (gpg_error_from_syserror ()));
2659 unlink (socketpath
);
2664 * Set the cache entry for a file. Prompts for the password.
2668 struct crypto_s
*crypto
;
2669 gpg_error_t rc
= init_client_crypto (&crypto
);
2673 estatus
= EXIT_FAILURE
;
2680 rc
= agent_set_pinentry_options (crypto
->agent
);
2683 estatus
= EXIT_FAILURE
;
2689 for (opt
= 0; cache_push
[opt
]; opt
++)
2691 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
2693 strv_free (cache_push
);
2695 estatus
= EXIT_FAILURE
;
2696 cleanup_crypto (&crypto
);
2700 cleanup_crypto_stage1 (crypto
);
2705 (void) kill_scd (crypto
->agent
);
2708 cleanup_crypto (&crypto
);
2709 strv_free (cache_push
);
2710 log_write (!nofork
? _("Done. Daemonizing...") :
2711 _("Done. Waiting for connections..."));
2714 config_clear_keys ();
2717 * bind() doesn't like the full pathname of the socket or any non alphanum
2718 * characters so change to the directory where the socket is wanted then
2719 * create it then change to datadir.
2721 if (chdir (socketdir
))
2723 log_write ("%s: %s", socketdir
,
2724 pwmd_strerror (gpg_error_from_syserror ()));
2730 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2732 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2736 addr
.sun_family
= AF_UNIX
;
2737 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2739 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2742 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2744 if (errno
== EADDRINUSE
)
2745 log_write (_("Either there is another pwmd running or '%s' is a \n"
2746 "stale socket. Please remove it manually."), socketpath
);
2753 char *t
= config_get_string ("global", "socket_perms");
2759 mode
= strtol (t
, NULL
, 8);
2763 if (chmod (socketname
, mode
) == -1)
2765 log_write ("%s: %s", socketname
,
2766 pwmd_strerror (gpg_error_from_syserror ()));
2768 unlink (socketpath
);
2777 xfree (--socketname
);
2779 if (chdir (datadir
))
2781 log_write ("%s: %s", datadir
,
2782 pwmd_strerror (gpg_error_from_syserror ()));
2784 unlink (socketpath
);
2790 if (listen (sockfd
, 0) == -1)
2792 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2803 log_write ("fork(): %s",
2804 pwmd_strerror (gpg_error_from_syserror ()));
2813 _exit (EXIT_SUCCESS
);
2817 pthread_key_create (&thread_name_key
, free_key
);
2818 pthread_setspecific (thread_name_key
, str_dup ("main"));
2819 estatus
= server_loop (sockfd
, &socketpath
);
2822 if (socketpath
&& do_unlink
)
2824 unlink (socketpath
);
2830 gnutls_global_deinit ();
2834 #ifdef HAVE_PTHREAD_CANCEL
2835 pthread_cancel (rcfile_tid
);
2837 pthread_kill (rcfile_tid
, SIGUSR2
);
2838 pthread_cond_signal (&rcfile_cond
);
2840 pthread_join (rcfile_tid
, NULL
);
2843 pthread_cond_destroy (&rcfile_cond
);
2844 pthread_mutex_destroy (&rcfile_mutex
);
2845 pthread_key_delete (last_error_key
);
2846 pthread_key_delete (thread_name_key
);
2847 #ifndef HAVE_PTHREAD_CANCEL
2848 pthread_key_delete (signal_thread_key
);
2852 config_free (global_config
);
2855 xfree (home_directory
);
2857 xmlCleanupParser ();
2858 xmlCleanupGlobals ();
2860 if (estatus
== EXIT_SUCCESS
)
2861 log_write (_("pwmd exiting normally"));
2864 #if defined(DEBUG) && !defined(MEM_DEBUG)