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"
76 #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
);
884 pinentry_free_opts (&cl
->pinentry_opts
);
893 while (cn
->msg_queue
)
895 struct status_msg_s
*msg
= cn
->msg_queue
;
897 cn
->msg_queue
= msg
->next
;
902 if (cn
->status_msg_pipe
[0] != -1)
903 close (cn
->status_msg_pipe
[0]);
905 if (cn
->status_msg_pipe
[1] != -1)
906 close (cn
->status_msg_pipe
[1]);
908 pthread_mutex_destroy (&cn
->status_mutex
);
909 log_write (_("exiting, fd=%i"), cn
->fd
);
911 send_status_all (STATUS_CLIENTS
, NULL
);
912 pthread_cond_signal (&quit_cond
);
916 send_msg_queue (struct client_thread_s
*thd
)
918 MUTEX_LOCK (&thd
->status_mutex
);
922 read (thd
->status_msg_pipe
[0], &c
, 1);
924 while (thd
->msg_queue
)
926 struct status_msg_s
*msg
= thd
->msg_queue
;
928 thd
->msg_queue
= thd
->msg_queue
->next
;
929 MUTEX_UNLOCK (&thd
->status_mutex
);
930 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
931 MUTEX_LOCK (&thd
->status_mutex
);
939 MUTEX_UNLOCK (&thd
->status_mutex
);
944 client_thread (void *data
)
946 struct client_thread_s
*thd
= data
;
947 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
949 #ifdef HAVE_PR_SET_NAME
950 prctl (PR_SET_NAME
, "client");
952 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
956 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
957 pwmd_strerror (GPG_ERR_ENOMEM
));
961 MUTEX_LOCK (&cn_mutex
);
962 pthread_cleanup_push (cleanup_cb
, thd
);
965 MUTEX_UNLOCK (&cn_mutex
);
967 if (new_connection (cl
))
972 send_status_all (STATUS_CLIENTS
, NULL
);
973 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
976 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
987 FD_SET (thd
->fd
, &rfds
);
988 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
991 thd
->status_msg_pipe
[0] ? thd
->fd
: thd
->status_msg_pipe
[0];
993 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
996 log_write ("%s", strerror (errno
));
1000 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
1002 rc
= send_msg_queue (thd
);
1003 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1005 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
1006 pwmd_strerror (rc
));
1011 if (!FD_ISSET (thd
->fd
, &rfds
))
1014 rc
= assuan_process_next (cl
->ctx
, &eof
);
1017 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
1020 log_write ("assuan_process_next(): %s", pwmd_strerror (rc
));
1021 rc
= send_error (cl
->ctx
, rc
);
1025 log_write ("assuan_process_done(): %s", pwmd_strerror (rc
));
1030 /* Since the msg queue pipe fd's are non-blocking, check for
1031 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1032 * client has already disconnected and will be converted to
1033 * GPG_ERR_EOF during assuan_process_next().
1035 rc
= send_msg_queue (thd
);
1036 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1038 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
1039 pwmd_strerror (rc
));
1045 pthread_cleanup_pop (1);
1050 xml_import (const char *filename
, const char *outfile
,
1051 const char *keygrip
, const char *sign_keygrip
,
1052 const char *keyfile
, int no_passphrase
, const char *cipher
,
1053 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1062 struct crypto_s
*crypto
;
1065 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1070 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1071 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1075 if (stat (filename
, &st
) == -1)
1077 log_write ("%s: %s", filename
,
1078 pwmd_strerror (gpg_error_from_syserror ()));
1082 rc
= init_client_crypto (&crypto
);
1086 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1087 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1088 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1091 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1093 log_write ("%s: %s", filename
,
1094 pwmd_strerror (gpg_error_from_syserror ()));
1098 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1101 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1102 pwmd_strerror (GPG_ERR_ENOMEM
));
1106 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1108 rc
= gpg_error_from_syserror ();
1110 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1115 xmlbuf
[st
.st_size
] = 0;
1117 * Make sure the document validates.
1119 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1121 log_write ("xmlReadDoc() failed");
1127 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1128 if (!xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1130 log_write (_("Could not find root \"pwmd\" element."));
1131 rc
= GPG_ERR_BAD_DATA
;
1135 rc
= validate_import (n
? n
->children
: n
);
1139 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1144 xmlDocDumpMemory (doc
, &xml
, &len
);
1146 crypto
->save
.s2k_count
= s2k_count
;
1147 crypto
->save
.hdr
.iterations
= iterations
;
1150 rc
= export_common (NULL
, 0, crypto
, xml
, len
, outfile
, keyfile
, &key
,
1153 log_write (_("Success!"));
1158 rc
= agent_set_pinentry_options (crypto
->agent
);
1160 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
,
1161 xml
, len
, outfile
, params
, keyfile
);
1169 send_error (NULL
, rc
);
1173 cleanup_crypto (&crypto
);
1177 cleanup_crypto (&crypto
);
1182 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1184 unsigned char md5file
[16];
1189 struct cache_data_s
*cdata
;
1193 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1196 if (valid_filename (filename
) == 0)
1198 log_write (_("%s: Invalid characters in filename"), filename
);
1202 rc
= decrypt_common (NULL
, 0, crypto
, filename
, &key
, &keylen
);
1206 doc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
);
1209 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1214 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1215 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1219 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1224 rc
= get_checksum (filename
, &crc
, &len
);
1227 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1229 free_cache_data_once (cdata
);
1235 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1236 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1237 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1238 if (!rc
&& !IS_PKCS (crypto
))
1241 cdata
->keylen
= keylen
;
1248 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1250 free_cache_data_once (cdata
);
1257 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1259 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1260 crypto
->sigpkey_sexp
);
1264 int timeout
= config_get_integer (filename
, "cache_timeout");
1265 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1266 log_write (_("Successfully added '%s' to the cache."), filename
);
1271 init_client (int fd
, const char *addr
)
1274 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1279 return GPG_ERR_ENOMEM
;
1282 MUTEX_LOCK (&cn_mutex
);
1283 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1285 if (pipe (new->status_msg_pipe
) == -1)
1286 rc
= gpg_error_from_syserror ();
1290 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1291 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1292 pthread_mutex_init (&new->status_mutex
, NULL
);
1298 new->remote
= addr
? 1 : 0;
1301 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1304 close (new->status_msg_pipe
[0]);
1305 close (new->status_msg_pipe
[1]);
1306 pthread_mutex_destroy (&new->status_mutex
);
1312 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1316 cn_thread_list
= list
;
1318 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1319 (pthread_t
*) new->tid
, fd
, addr
);
1321 log_write (_("new connection: tid=%p, fd=%i"),
1322 (pthread_t
*) new->tid
, fd
);
1325 rc
= GPG_ERR_ENOMEM
;
1328 pthread_cleanup_pop (1);
1334 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1335 pwmd_strerror (rc
));
1341 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1343 get_in_addr (struct sockaddr
*sa
)
1345 if (sa
->sa_family
== AF_INET
)
1346 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1348 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1352 tcp_accept_thread (void *arg
)
1354 int sockfd
= *(int *) arg
;
1355 #ifndef HAVE_PTHREAD_CANCEL
1356 int *n
= xmalloc (sizeof (int));
1359 pthread_setspecific (signal_thread_key
, n
);
1361 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1364 #ifdef HAVE_PR_SET_NAME
1365 prctl (PR_SET_NAME
, "tcp_accept");
1367 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1371 struct sockaddr_storage raddr
;
1372 socklen_t slen
= sizeof (raddr
);
1375 char s
[INET6_ADDRSTRLEN
];
1376 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1377 #ifndef HAVE_PTHREAD_CANCEL
1380 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1385 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1388 if (errno
== EMFILE
|| errno
== ENFILE
)
1389 log_write ("accept(): %s",
1390 pwmd_strerror (gpg_error_from_syserror ()));
1391 else if (errno
!= EAGAIN
)
1393 if (!quit
) // probably EBADF
1394 log_write ("accept(): %s", strerror (errno
));
1399 #ifndef HAVE_PTHREAD_CANCEL
1400 select (0, NULL
, NULL
, NULL
, &tv
);
1408 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1410 (void) init_client (fd
, s
);
1411 n
= config_get_integer ("global", "tcp_wait");
1414 tv
.tv_sec
= (n
* 100000) / 100000;
1415 tv
.tv_usec
= (n
* 100000) % 100000;
1416 select (0, NULL
, NULL
, NULL
, &tv
);
1424 start_stop_tls_with_protocol (int ipv6
, int term
)
1426 struct addrinfo hints
, *servinfo
, *p
;
1427 int port
= config_get_integer ("global", "tcp_port");
1431 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1433 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1439 #ifdef HAVE_PTHREAD_CANCEL
1440 pthread_cancel (tls6_tid
);
1442 pthread_kill (tls6_tid
, SIGUSR2
);
1444 pthread_join (tls6_tid
, NULL
);
1447 shutdown (tls6_fd
, SHUT_RDWR
);
1457 #ifdef HAVE_PTHREAD_CANCEL
1458 pthread_cancel (tls_tid
);
1460 pthread_kill (tls_tid
, SIGUSR2
);
1462 pthread_join (tls_tid
, NULL
);
1465 shutdown (tls_fd
, SHUT_RDWR
);
1471 /* A client may still be connected. */
1472 if (!quit
&& x509_cred
!= NULL
)
1473 tls_deinit_params ();
1478 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1481 memset (&hints
, 0, sizeof (hints
));
1482 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1483 hints
.ai_socktype
= SOCK_STREAM
;
1484 hints
.ai_flags
= AI_PASSIVE
;
1485 snprintf (buf
, sizeof (buf
), "%i", port
);
1487 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1489 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1493 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1497 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1498 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1501 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1503 log_write ("socket(): %s", strerror (errno
));
1507 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1509 log_write ("setsockopt(): %s",
1510 pwmd_strerror (gpg_error_from_syserror ()));
1511 freeaddrinfo (servinfo
);
1515 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1518 log_write ("bind(): %s",
1519 pwmd_strerror (gpg_error_from_syserror ()));
1527 freeaddrinfo (servinfo
);
1532 #if HAVE_DECL_SO_BINDTODEVICE != 0
1533 char *tmp
= config_get_string ("global", "tcp_interface");
1534 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
, 1) == -1)
1536 log_write ("setsockopt(): %s",
1537 pwmd_strerror (gpg_error_from_syserror ()));
1545 if (x509_cred
== NULL
)
1547 rc
= tls_init_params ();
1552 if (listen (*fd
, 0) == -1)
1554 log_write ("listen(): %s", strerror (errno
));
1559 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1561 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1565 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1566 pwmd_strerror (rc
));
1578 start_stop_tls_with_protocol (0, 1);
1591 start_stop_tls (int term
)
1593 char *s
= config_get_string ("global", "tcp_bind");
1599 if (!strcmp (s
, "any"))
1601 b
= start_stop_tls_with_protocol (0, term
);
1603 b
= start_stop_tls_with_protocol (1, term
);
1605 else if (!strcmp (s
, "ipv4"))
1606 b
= start_stop_tls_with_protocol (0, term
);
1607 else if (!strcmp (s
, "ipv6"))
1608 b
= start_stop_tls_with_protocol (1, term
);
1618 accept_thread (void *arg
)
1620 int sockfd
= *(int *) arg
;
1621 #ifndef HAVE_PTHREAD_CANCEL
1622 int *n
= xmalloc (sizeof (int));
1625 pthread_setspecific (signal_thread_key
, n
);
1627 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1630 #ifdef HAVE_PR_SET_NAME
1631 prctl (PR_SET_NAME
, "accept");
1633 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1637 socklen_t slen
= sizeof (struct sockaddr_un
);
1638 struct sockaddr_un raddr
;
1640 #ifndef HAVE_PTHREAD_CANCEL
1641 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1642 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1648 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1651 if (errno
== EMFILE
|| errno
== ENFILE
)
1652 log_write ("accept(): %s",
1653 pwmd_strerror (gpg_error_from_syserror ()));
1654 else if (errno
!= EAGAIN
)
1656 if (!quit
) // probably EBADF
1657 log_write ("accept(): %s",
1658 pwmd_strerror (gpg_error_from_syserror ()));
1663 #ifndef HAVE_PTHREAD_CANCEL
1664 select (0, NULL
, NULL
, NULL
, &tv
);
1669 (void) init_client (fd
, NULL
);
1672 /* Just in case accept() failed for some reason other than EBADF */
1678 cache_timer_thread (void *arg
)
1680 #ifndef HAVE_PTHREAD_CANCEL
1681 int *n
= xmalloc (sizeof (int));
1684 pthread_setspecific (signal_thread_key
, n
);
1688 #ifdef HAVE_PR_SET_NAME
1689 prctl (PR_SET_NAME
, "cache timer");
1691 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1695 struct timeval tv
= { 1, 0 };
1696 #ifndef HAVE_PTHREAD_CANCEL
1699 n
= (int *) pthread_getspecific (signal_thread_key
);
1704 select (0, NULL
, NULL
, NULL
, &tv
);
1705 cache_adjust_timeout ();
1712 catch_sigabrt (int sig
)
1721 signal_loop (sigset_t sigset
)
1730 sigwait (&sigset
, &sig
);
1733 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1738 pthread_cond_signal (&rcfile_cond
);
1741 // not really handled here.
1742 catch_sigabrt (SIGABRT
);
1745 log_write (_("clearing file cache"));
1747 send_status_all (STATUS_CACHE
, NULL
);
1766 log_write ("Caught SIGSEGV. Exiting.");
1767 #ifdef HAVE_BACKTRACE
1768 BACKTRACE (__FUNCTION__
);
1774 waiting_for_exit (void *arg
)
1777 #ifndef HAVE_PTHREAD_CANCEL
1778 int *n
= xmalloc (sizeof (int));
1781 pthread_setspecific (signal_thread_key
, n
);
1785 #ifdef HAVE_PR_SET_NAME
1786 prctl (PR_SET_NAME
, "exiting");
1788 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1789 log_write (_("waiting for all clients to disconnect"));
1790 MUTEX_LOCK (&quit_mutex
);
1791 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1798 MUTEX_LOCK (&cn_mutex
);
1799 n
= slist_length (cn_thread_list
);
1800 MUTEX_UNLOCK (&cn_mutex
);
1804 #ifndef HAVE_PTHREAD_CANCEL
1805 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1812 log_write (_("%i clients remain"), n
);
1816 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1817 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1820 kill (getpid (), SIGQUIT
);
1821 pthread_cleanup_pop (1);
1826 server_loop (int sockfd
, char **socketpath
)
1828 pthread_t accept_tid
;
1829 pthread_t cache_timeout_tid
;
1830 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1837 sigemptyset (&sigset
);
1840 sigaddset (&sigset
, SIGTERM
);
1841 sigaddset (&sigset
, SIGINT
);
1843 /* Clears the file cache. */
1844 sigaddset (&sigset
, SIGUSR1
);
1846 /* Configuration file reloading. */
1847 sigaddset (&sigset
, SIGHUP
);
1849 /* For exiting cleanly. */
1850 sigaddset (&sigset
, SIGQUIT
);
1852 #ifndef HAVE_PTHREAD_CANCEL
1854 The socket, cache and rcfile threads use this signal when
1855 pthread_cancel() is unavailable. Prevent the main thread from
1856 catching this signal from another process.
1858 sigaddset (&sigset
, SIGUSR2
);
1861 /* Clears the cache and exits when something bad happens. */
1862 signal (SIGABRT
, catch_sigabrt
);
1863 sigaddset (&sigset
, SIGABRT
);
1864 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1866 #ifndef HAVE_PTHREAD_CANCEL
1867 /* Remove this signal from the watched signals in signal_loop(). */
1868 sigdelset (&sigset
, SIGUSR2
);
1871 /* Ignored everywhere. When a client disconnects abnormally this signal
1872 * gets raised. It isn't needed though because client_thread() will check
1873 * for rcs even after the client disconnects. */
1874 signal (SIGPIPE
, SIG_IGN
);
1876 /* Can show a backtrace of the stack in the log. */
1877 signal (SIGSEGV
, catchsig
);
1880 /* Needs to be done after the fork(). */
1881 if (!start_stop_tls (0))
1888 pthread_mutex_init (&quit_mutex
, NULL
);
1889 pthread_cond_init (&quit_cond
, NULL
);
1890 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
1893 if (config_get_boolean ("global", "enable_tcp"))
1894 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1895 config_get_integer ("global", "tcp_port"));
1897 log_write (_("Listening on %s"), *socketpath
);
1899 log_write (_("Listening on %s"), *socketpath
);
1902 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1905 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1906 pwmd_strerror (rc
));
1910 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
1913 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1914 pwmd_strerror (rc
));
1918 cancel_timeout_thread
= 1;
1919 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
1922 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1923 pwmd_strerror (rc
));
1927 cancel_accept_thread
= 1;
1929 signal_loop (sigset
);
1935 * We're out of the main server loop. This happens when a signal was sent
1936 * to terminate the daemon. We'll wait for all clients to disconnect
1937 * before exiting but exit immediately if another termination signal is
1940 if (cancel_accept_thread
)
1942 #ifdef HAVE_PTHREAD_CANCEL
1943 int n
= pthread_cancel (accept_tid
);
1945 int n
= pthread_kill (accept_tid
, SIGUSR2
);
1948 pthread_join (accept_tid
, NULL
);
1954 shutdown (sockfd
, SHUT_RDWR
);
1956 unlink (*socketpath
);
1957 xfree (*socketpath
);
1959 MUTEX_LOCK (&cn_mutex
);
1960 n
= slist_length (cn_thread_list
);
1961 MUTEX_UNLOCK (&cn_mutex
);
1967 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
1970 if (signal_loop (sigset
))
1972 log_write (_("Received second termination request. Exiting."));
1973 #ifdef HAVE_PTHREAD_CANCEL
1974 pthread_cancel (tid
);
1976 pthread_kill (tid
, SIGUSR2
);
1978 pthread_join (tid
, NULL
);
1982 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1983 pwmd_strerror (rc
));
1986 if (cancel_timeout_thread
)
1988 #ifdef HAVE_PTHREAD_CANCEL
1989 pthread_cancel (cache_timeout_tid
);
1991 pthread_kill (cache_timeout_tid
, SIGUSR2
);
1993 pthread_join (cache_timeout_tid
, NULL
);
1996 MUTEX_LOCK (&cn_mutex
);
1998 n
= slist_length (cn_thread_list
);
2000 for (i
= 0; i
< n
; i
++)
2002 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2012 MUTEX_UNLOCK (&cn_mutex
);
2018 pthread_cond_destroy (&quit_cond
);
2019 pthread_mutex_destroy (&quit_mutex
);
2020 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2027 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2031 /* This is called from cache.c:clear_once(). See
2032 * command.c:clearcache_command() for details about lock checking.
2035 free_cache_data (file_cache_t
* cache
)
2037 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2039 struct client_thread_s
*found
= NULL
;
2046 MUTEX_LOCK (&cn_mutex
);
2047 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2048 t
= slist_length (cn_thread_list
);
2050 for (i
= 0; i
< t
; i
++)
2052 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2057 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2058 sizeof (cache
->filename
)))
2060 if (pthread_equal (pthread_self (), thd
->tid
))
2067 /* Continue trying to find a client who has the same file open and
2068 * also has a lock. */
2069 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2079 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2080 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2082 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2084 free_cache_data_once (cache
->data
);
2086 cache
->defer_clear
= 0;
2087 cache
->timeout
= -1;
2090 cache_unlock_mutex (found
->cl
->md5file
, 0);
2096 cache
->defer_clear
= 1;
2098 pthread_cleanup_pop (1);
2104 convert_v2_datafile (const char *filename
, const char *cipher
,
2105 const char *keyfile
, const char *keygrip
,
2106 const char *sign_keygrip
, int nopass
,
2107 const char *outfile
, const char *keyparam
,
2108 unsigned long s2k_count
, uint64_t iterations
)
2113 struct crypto_s
*crypto
= NULL
;
2119 if (outfile
[0] == '-' && outfile
[1] == 0)
2122 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2123 if (access (filename
, R_OK
) == -1)
2125 log_write ("%s: %s", filename
,
2126 pwmd_strerror (gpg_error_from_syserror ()));
2132 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2134 if (access (keyfile
, R_OK
) == -1)
2136 log_write ("%s: %s", keyfile
,
2137 pwmd_strerror (gpg_error_from_syserror ()));
2142 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2145 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2151 algo
= cipher_string_to_gcrypt (cipher
);
2154 rc
= GPG_ERR_CIPHER_ALGO
;
2161 xmlDocPtr doc
= parse_doc (data
, datalen
);
2165 rc
= GPG_ERR_BAD_DATA
;
2169 rc
= convert_pre_212_elements (doc
);
2174 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2177 rc
= GPG_ERR_ENOMEM
;
2185 rc
= init_client_crypto (&crypto
);
2188 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2189 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2190 crypto
->save
.s2k_count
= s2k_count
;
2191 crypto
->save
.hdr
.iterations
= iterations
;
2195 rc
= export_common (NULL
, 0, crypto
, data
, datalen
, outfile
, keyfile
,
2196 &key
, &keylen
, 0, 0);
2201 rc
= agent_set_pinentry_options (crypto
->agent
);
2203 rc
= agent_export_common (crypto
, keygrip
, sign_keygrip
, nopass
,
2204 data
, datalen
, outfile
, keyparam
,
2205 no_passphrase_file
? NULL
: keyfile
);
2209 log_write (_("Output written to \"%s\"."), outfile
);
2219 cleanup_crypto (&crypto
);
2222 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2227 usage (const char *pn
, int status
)
2229 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2231 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2232 " -f, --rcfile=filename load the specfied configuration file\n"
2233 " (~/.pwmd/config)\n"
2234 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2236 " --no-agent disable use of gpg-agent\n"
2238 " -n, --no-fork run as a foreground process\n"
2239 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2240 " --ignore ignore file errors during startup\n"
2241 " --debug-level=keywords log protocol output (see manual for details)\n"
2242 " -o, --outfile=filename output file when importing or converting\n"
2243 " -C, --convert=filename convert a version 2 data file to version 3\n"
2244 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2245 " -k, --passphrase-file=file for use when importing or converting\n"
2246 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2248 " --no-passphrase when importing or converting\n"
2249 " --keygrip=hex public key to use when encrypting\n"
2250 " --sign-keygrip=hex private key to use when signing\n"
2251 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2252 " --cipher=string encryption cipher (aes256)\n"
2253 " --iterations=N cipher iteration count (N+1)\n"
2254 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2255 " --help this help text\n"
2256 " --version show version and compile time features\n"),
2262 main (int argc
, char *argv
[])
2265 struct sockaddr_un addr
;
2267 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2268 char *socketarg
= NULL
;
2269 char *datadir
= NULL
;
2272 char **cache_push
= NULL
;
2273 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2274 char *keyparam
= NULL
;
2275 int estatus
= EXIT_FAILURE
;
2277 char *outfile
= NULL
;
2280 int show_version
= 0;
2282 int no_passphrase
= 0;
2284 char *convertfile
= NULL
;
2285 char *cipher
= NULL
;
2286 char *keyfile
= NULL
;
2287 unsigned long s2k_count
= 0;
2288 uint64_t iterations
= 0;
2290 char *debug_level_opt
= NULL
;
2292 /* Must maintain the same order as longopts[] */
2294 { OPT_VERSION
, OPT_HELP
,
2298 OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
, OPT_DISABLE_DUMP
, OPT_IGNORE
,
2299 OPT_RCFILE
, OPT_CONVERT
, OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
,
2300 OPT_NO_PASSPHRASE_FILE
, OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
, OPT_KEYPARAM
,
2301 OPT_CIPHER
, OPT_ITERATIONS
, OPT_S2K_COUNT
, OPT_NO_PASSPHRASE
2303 const char *optstring
= "nf:C:k:I:o:";
2304 const struct option longopts
[] = {
2305 {"version", no_argument
, 0, 0},
2306 {"help", no_argument
, 0, 0},
2308 {"no-agent", no_argument
, 0, 0},
2310 {"debug-level", required_argument
, 0, 0},
2311 {"homedir", required_argument
, 0, 0},
2312 {"no-fork", no_argument
, 0, 'n'},
2313 {"disable_dump", no_argument
, 0, 0},
2314 {"ignore", no_argument
, 0, 0},
2315 {"rcfile", required_argument
, 0, 'f'},
2316 {"convert", required_argument
, 0, 'C'},
2317 {"passphrase-file", required_argument
, 0, 'k'},
2318 {"import", required_argument
, 0, 'I'},
2319 {"outfile", required_argument
, 0, 'o'},
2320 {"no-passphrase-file", no_argument
, 0, 0},
2321 {"keygrip", required_argument
, 0, 0},
2322 {"sign-keygrip", required_argument
, 0, 0},
2323 {"keyparam", required_argument
, 0, 0},
2324 {"cipher", required_argument
, 0, 0},
2325 {"cipher-iterations", required_argument
, 0, 0},
2326 {"s2k-count", required_argument
, 0, 0},
2327 {"no-passphrase", no_argument
, 0, 0},
2332 #ifdef HAVE_SETRLIMIT
2335 rl
.rlim_cur
= rl
.rlim_max
= 0;
2337 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2338 err (EXIT_FAILURE
, "setrlimit()");
2343 setlocale (LC_ALL
, "");
2344 bindtextdomain ("pwmd", LOCALEDIR
);
2345 textdomain ("pwmd");
2353 if (setup_crypto ())
2354 exit (EXIT_FAILURE
);
2357 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2359 gnutls_global_init ();
2360 gnutls_global_set_log_function (tls_log
);
2361 gnutls_global_set_log_level (1);
2365 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2376 getopt_long (argc
, argv
, optstring
, longopts
, &optindex
)) != -1)
2384 convertfile
= optarg
;
2399 rcfile
= str_dup (optarg
);
2402 usage (argv
[0], EXIT_FAILURE
);
2418 case OPT_DEBUG_LEVEL
:
2419 debug_level_opt
= optarg
;
2422 homedir
= str_dup (optarg
);
2427 case OPT_DISABLE_DUMP
:
2434 rcfile
= str_dup (optarg
);
2437 convertfile
= optarg
;
2439 case OPT_PASSPHRASE_FILE
:
2448 case OPT_NO_PASSPHRASE_FILE
:
2449 no_passphrase_file
= 1;
2454 case OPT_SIGN_KEYGRIP
:
2455 sign_keygrip
= optarg
;
2463 case OPT_ITERATIONS
:
2464 iterations
= strtoull (optarg
, NULL
, 10);
2467 s2k_count
= strtoul (optarg
, NULL
, 10);
2469 case OPT_NO_PASSPHRASE
:
2481 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
2483 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2484 "Compile time features:\n%s"), PACKAGE_STRING
,
2487 "+PWMD_HOMEDIR=" PWMD_HOMEDIR
"\n"
2525 exit (EXIT_SUCCESS
);
2530 homedir
= str_dup(PWMD_HOMEDIR
);
2532 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2535 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2536 err (EXIT_FAILURE
, "%s", homedir
);
2538 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2539 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2540 err (EXIT_FAILURE
, "%s", buf
);
2542 datadir
= str_dup (buf
);
2543 pthread_mutexattr_t attr
;
2544 pthread_mutexattr_init (&attr
);
2545 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2546 pthread_mutex_init (&rcfile_mutex
, &attr
);
2547 pthread_cond_init (&rcfile_cond
, NULL
);
2548 pthread_mutex_init (&cn_mutex
, &attr
);
2549 pthread_mutexattr_destroy (&attr
);
2550 pthread_key_create (&last_error_key
, free_key
);
2551 #ifndef HAVE_PTHREAD_CANCEL
2552 pthread_key_create (&signal_thread_key
, free_key
);
2556 rcfile
= str_asprintf ("%s/config", homedir
);
2558 global_config
= config_parse (rcfile
);
2560 exit (EXIT_FAILURE
);
2564 if (debug_level_opt
)
2565 debug_level
= str_split (debug_level_opt
, ",", 0);
2567 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2568 if (exists
&& x
!= atoi(INVALID_PRIORITY
))
2571 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2573 log_write ("setpriority(): %s",
2574 pwmd_strerror (gpg_error_from_syserror ()));
2578 #ifdef HAVE_MLOCKALL
2579 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2581 log_write ("mlockall(): %s",
2582 pwmd_strerror (gpg_error_from_syserror ()));
2587 rc
= cache_init (free_cache_data
);
2590 log_write ("pwmd: ERR %i: %s", rc
,
2591 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2592 ? _("incompatible version: 2.1.0 or later required")
2593 : pwmd_strerror (rc
));
2598 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2603 usage (argv
[0], EXIT_FAILURE
);
2605 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2606 sign_keygrip
, no_passphrase
, outfile
,
2607 keyparam
, s2k_count
, iterations
);
2608 config_free (global_config
);
2616 usage (argv
[0], EXIT_FAILURE
);
2618 if (outfile
[0] == '-' && outfile
[1] == 0)
2621 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2622 no_passphrase
, cipher
, keyparam
, s2k_count
,
2624 config_free (global_config
);
2629 p
= config_get_string ("global", "socket_path");
2631 p
= str_asprintf ("%s/socket", homedir
);
2633 socketarg
= expand_homedir (p
);
2637 disable_list_and_dump
= config_get_boolean ("global",
2638 "disable_list_and_dump");
2640 disable_list_and_dump
= secure
;
2642 cache_push
= config_get_list ("global", "cache_push");
2644 while (optind
< argc
)
2646 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2647 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2650 if (strchr (socketarg
, '/') == NULL
)
2652 socketdir
= getcwd (buf
, sizeof (buf
));
2653 socketname
= str_dup (socketarg
);
2654 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2658 socketname
= str_dup (strrchr (socketarg
, '/'));
2660 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2661 socketdir
= str_dup (socketarg
);
2662 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2665 if (chdir (datadir
))
2667 log_write ("%s: %s", datadir
,
2668 pwmd_strerror (gpg_error_from_syserror ()));
2669 unlink (socketpath
);
2674 * Set the cache entry for a file. Prompts for the password.
2678 struct crypto_s
*crypto
;
2679 gpg_error_t rc
= init_client_crypto (&crypto
);
2683 estatus
= EXIT_FAILURE
;
2690 rc
= agent_set_pinentry_options (crypto
->agent
);
2693 estatus
= EXIT_FAILURE
;
2699 for (opt
= 0; cache_push
[opt
]; opt
++)
2701 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
2703 strv_free (cache_push
);
2705 estatus
= EXIT_FAILURE
;
2706 cleanup_crypto (&crypto
);
2710 cleanup_crypto_stage1 (crypto
);
2715 (void) kill_scd (crypto
->agent
);
2718 cleanup_crypto (&crypto
);
2719 strv_free (cache_push
);
2720 log_write (!nofork
? _("Done. Daemonizing...") :
2721 _("Done. Waiting for connections..."));
2724 config_clear_keys ();
2727 * bind() doesn't like the full pathname of the socket or any non alphanum
2728 * characters so change to the directory where the socket is wanted then
2729 * create it then change to datadir.
2731 if (chdir (socketdir
))
2733 log_write ("%s: %s", socketdir
,
2734 pwmd_strerror (gpg_error_from_syserror ()));
2740 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2742 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2746 addr
.sun_family
= AF_UNIX
;
2747 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2749 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2752 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2754 if (errno
== EADDRINUSE
)
2755 log_write (_("Either there is another pwmd running or '%s' is a \n"
2756 "stale socket. Please remove it manually."), socketpath
);
2763 char *t
= config_get_string ("global", "socket_perms");
2769 mode
= strtol (t
, NULL
, 8);
2773 if (chmod (socketname
, mode
) == -1)
2775 log_write ("%s: %s", socketname
,
2776 pwmd_strerror (gpg_error_from_syserror ()));
2778 unlink (socketpath
);
2787 xfree (--socketname
);
2789 if (chdir (datadir
))
2791 log_write ("%s: %s", datadir
,
2792 pwmd_strerror (gpg_error_from_syserror ()));
2794 unlink (socketpath
);
2800 if (listen (sockfd
, 0) == -1)
2802 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2813 log_write ("fork(): %s",
2814 pwmd_strerror (gpg_error_from_syserror ()));
2823 _exit (EXIT_SUCCESS
);
2827 pthread_key_create (&thread_name_key
, free_key
);
2828 pthread_setspecific (thread_name_key
, str_dup ("main"));
2829 estatus
= server_loop (sockfd
, &socketpath
);
2832 if (socketpath
&& do_unlink
)
2834 unlink (socketpath
);
2840 gnutls_global_deinit ();
2844 #ifdef HAVE_PTHREAD_CANCEL
2845 pthread_cancel (rcfile_tid
);
2847 pthread_kill (rcfile_tid
, SIGUSR2
);
2848 pthread_cond_signal (&rcfile_cond
);
2850 pthread_join (rcfile_tid
, NULL
);
2853 pthread_cond_destroy (&rcfile_cond
);
2854 pthread_mutex_destroy (&rcfile_mutex
);
2855 pthread_key_delete (last_error_key
);
2856 pthread_key_delete (thread_name_key
);
2857 #ifndef HAVE_PTHREAD_CANCEL
2858 pthread_key_delete (signal_thread_key
);
2862 config_free (global_config
);
2865 xfree (home_directory
);
2867 xmlCleanupParser ();
2868 xmlCleanupGlobals ();
2870 if (estatus
== EXIT_SUCCESS
)
2871 log_write (_("pwmd exiting normally"));
2874 #if defined(DEBUG) && !defined(MEM_DEBUG)