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"
88 /* In tenths of a second. */
91 /* For (tcp_)accept_thread (usec). */
92 #define ACCEPT_TIMEOUT 30000
99 static pthread_cond_t quit_cond
;
100 static pthread_mutex_t quit_mutex
;
101 static int no_passphrase_file
= 0;
103 #ifndef HAVE_PTHREAD_CANCEL
104 static pthread_key_t signal_thread_key
;
110 static pthread_t tls_tid
;
111 static pthread_t tls6_tid
;
112 static int spawned_tls
;
113 static int spawned_tls6
;
115 static int start_stop_tls (int term
);
118 static int do_cache_push (const char *filename
, struct crypto_s
*crypto
);
119 static int signal_loop (sigset_t sigset
);
121 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
123 #ifndef HAVE_PTHREAD_CANCEL
125 catch_thread_signal (int sig
)
127 int *n
= (int *) pthread_getspecific (signal_thread_key
);
130 pthread_setspecific (signal_thread_key
, n
);
135 cache_push_from_rcfile ()
137 struct crypto_s
*crypto
;
139 gpg_error_t rc
= init_client_crypto (&crypto
);
143 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
147 rc
= set_agent_option (crypto
->agent
, "pinentry-mode", "error");
150 log_write ("%s: %s", __FUNCTION__
, pwmd_strerror (rc
));
154 cache_push
= config_get_list ("global", "cache_push");
159 for (p
= cache_push
; *p
; p
++)
161 (void) do_cache_push (*p
, crypto
);
162 cleanup_crypto_stage1 (crypto
);
165 strv_free (cache_push
);
168 (void) kill_scd (crypto
->agent
);
169 cleanup_crypto (&crypto
);
175 int n
= config_get_boolean ("global", "enable_logging");
179 char *p
= config_get_string ("global", "log_path");
182 logfile
= expand_homedir (p
);
191 log_syslog
= config_get_boolean ("global", "syslog");
193 openlog ("pwmd", LOG_NDELAY
| LOG_PID
, LOG_DAEMON
);
197 reload_rcfile_thread (void *arg
)
199 #ifndef HAVE_PTHREAD_CANCEL
200 int *n
= xmalloc (sizeof (int));
203 pthread_setspecific (signal_thread_key
, n
);
204 signal (SIGUSR2
, catch_thread_signal
);
207 #ifdef HAVE_PR_SET_NAME
208 prctl (PR_SET_NAME
, "reload rcfile");
210 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
211 MUTEX_LOCK (&rcfile_mutex
);
212 pthread_cleanup_push (cleanup_mutex_cb
, &rcfile_mutex
);
216 struct slist_s
*config
;
218 int b
= disable_list_and_dump
;
221 int tcp_require_key
= config_get_bool_param (global_config
, "global",
226 pthread_cond_wait (&rcfile_cond
, &rcfile_mutex
);
227 #ifndef HAVE_PTHREAD_CANCEL
228 int *n
= (int *) pthread_getspecific (signal_thread_key
);
233 users
= config_get_list ("global", "allowed");
234 log_write (_("reloading configuration file '%s'"), rcfile
);
235 config
= config_parse (rcfile
);
238 config_free (global_config
);
239 global_config
= config
;
241 cache_push_from_rcfile ();
242 config_clear_keys ();
245 disable_list_and_dump
= !disable_list_and_dump
? b
: 1;
247 if (config_get_bool_param (global_config
, "global", "tcp_require_key",
251 config_set_bool_param (&global_config
, "global", "tcp_require_key",
252 tcp_require_key
? "true" : "false");
254 char *tmp
= strv_join (",", users
);
255 config_set_list_param (&global_config
, "global", "allowed", tmp
);
259 /* Kill existing listening threads since the configured listening
260 * protocols may have changed. */
266 pthread_cleanup_pop (1);
271 send_error (assuan_context_t ctx
, gpg_error_t e
)
273 struct client_s
*client
= assuan_get_pointer (ctx
);
275 if (gpg_err_source (e
) == GPG_ERR_SOURCE_UNKNOWN
)
282 return assuan_process_done (ctx
, 0);
286 log_write ("%s", pwmd_strerror (e
));
290 if (gpg_err_code (e
) == GPG_ERR_BAD_DATA
)
292 xmlErrorPtr xe
= client
->xml_error
;
295 xe
= xmlGetLastError ();
298 log_write ("%s", xe
->message
);
299 if (client
->last_error
)
300 xfree (client
->last_error
);
302 client
->last_error
= str_dup (xe
->message
);
305 e
= assuan_process_done (ctx
, assuan_set_error (ctx
, e
,
309 if (xe
== client
->xml_error
)
312 xmlResetLastError ();
314 client
->xml_error
= NULL
;
318 return assuan_process_done (ctx
,
319 assuan_set_error (ctx
, e
, pwmd_strerror (e
)));
323 assuan_log_cb (assuan_context_t ctx
, void *data
, unsigned cat
,
326 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
330 pthread_mutex_lock (&m
);
331 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
332 t
= strv_length (debug_level
);
334 for (i
= 0; i
< t
; i
++)
336 if (!strcasecmp (debug_level
[i
], (char *) "init")
337 && cat
== ASSUAN_LOG_INIT
)
343 if (!strcasecmp (debug_level
[i
], (char *) "ctx")
344 && cat
== ASSUAN_LOG_CTX
)
350 if (!strcasecmp (debug_level
[i
], (char *) "engine")
351 && cat
== ASSUAN_LOG_ENGINE
)
357 if (!strcasecmp (debug_level
[i
], (char *) "data")
358 && cat
== ASSUAN_LOG_DATA
)
364 if (!strcasecmp (debug_level
[i
], (char *) "sysio")
365 && cat
== ASSUAN_LOG_SYSIO
)
371 if (!strcasecmp (debug_level
[i
], (char *) "control")
372 && cat
== ASSUAN_LOG_CONTROL
)
386 open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
387 warn ("%s", logfile
);
390 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
391 write (fd
, msg
, strlen (msg
));
392 pthread_cleanup_pop (1);
398 fprintf (stderr
, "%s%s", data
? (char *) data
: "", msg
);
403 pthread_cleanup_pop (1);
408 log_write (const char *fmt
, ...)
418 pthread_t tid
= pthread_self ();
419 static pthread_mutex_t m
= PTHREAD_MUTEX_INITIALIZER
;
421 if ((!logfile
&& !isatty (STDERR_FILENO
) && !log_syslog
) || !fmt
)
424 pthread_mutex_lock (&m
);
425 pthread_cleanup_push ((void (*)(void *)) pthread_mutex_unlock
, &m
);
426 pthread_cleanup_push (cleanup_fd_cb
, &fd
);
428 if (!cmdline
&& logfile
)
430 if ((fd
= open (logfile
, O_WRONLY
| O_CREAT
| O_APPEND
, 0600)) == -1)
431 warn ("%s", logfile
);
436 if (str_vasprintf (&args
, fmt
, ap
) != -1)
440 pthread_cleanup_push (xfree
, args
);
441 fprintf (stderr
, "%s\n", args
);
443 pthread_cleanup_pop (1);
447 pthread_cleanup_push (xfree
, args
);
448 name
= pthread_getspecific (thread_name_key
);
449 snprintf (buf
, sizeof (buf
), "%s(%p): ", name
? name
: _("unknown"),
453 if (!cmdline
&& log_syslog
&& !nofork
)
454 syslog (LOG_INFO
, "%s%s", name
, args
);
457 tm
= localtime (&now
);
458 strftime (tbuf
, sizeof (tbuf
), "%b %d %Y %H:%M:%S ", tm
);
459 tbuf
[sizeof (tbuf
) - 1] = 0;
461 if (args
[strlen (args
) - 1] == '\n')
462 args
[strlen (args
) - 1] = 0;
464 line
= str_asprintf ("%s %i %s%s\n", tbuf
, getpid (), name
, args
);
465 pthread_cleanup_pop (1);
468 pthread_cleanup_push (xfree
, line
);
469 if (logfile
&& fd
!= -1)
471 write (fd
, line
, strlen (line
));
477 fprintf (stdout
, "%s", line
);
481 pthread_cleanup_pop (1);
487 pthread_cleanup_pop (1);
488 pthread_cleanup_pop (0);
489 pthread_mutex_unlock (&m
);
494 secure_mem_check (const void *arg
)
503 gcry_control (GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
505 if (!gcry_check_version (GCRYPT_VERSION
))
507 fprintf (stderr
, _("gcry_check_version(): Incompatible libgcrypt. "
508 "Wanted %s, got %s.\n"), GCRYPT_VERSION
,
509 gcry_check_version (NULL
));
510 return GPG_ERR_UNKNOWN_VERSION
;
513 gcry_set_allocation_handler (xmalloc
, xmalloc
, NULL
, xrealloc
, xfree
);
517 #ifdef HAVE_GETGRNAM_R
519 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
525 rc
= assuan_get_peercred (cl
->ctx
, peer
);
529 users
= config_get_list ("global", "allowed");
532 for (char **p
= users
; *p
; p
++)
534 struct passwd pw
, *result
;
535 struct group gr
, *gresult
;
540 size_t len
= sysconf (_SC_GETGR_R_SIZE_MAX
);
549 return GPG_ERR_ENOMEM
;
552 if (!getgrnam_r (*(p
) + 1, &gr
, buf
, len
, &gresult
) && gresult
)
554 if (gresult
->gr_gid
== (*peer
)->gid
)
561 len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
565 char *tbuf
= xmalloc (len
);
566 for (char **t
= gresult
->gr_mem
; *t
; t
++)
568 if (!getpwnam_r (*t
, &pw
, tbuf
, len
, &result
) && result
)
570 if (result
->pw_uid
== (*peer
)->uid
)
587 size_t len
= sysconf (_SC_GETPW_R_SIZE_MAX
);
597 return GPG_ERR_ENOMEM
;
600 if (!getpwnam_r (*p
, &pw
, buf
, len
, &result
) && result
)
602 if (result
->pw_uid
== (*peer
)->uid
)
617 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
621 do_validate_peer (struct client_s
*cl
, assuan_peercred_t
* peer
)
627 rc
= assuan_get_peercred (cl
->ctx
, peer
);
631 users
= config_get_list ("global", "allowed");
634 for (char **p
= users
; *p
; p
++)
636 struct passwd
*result
;
637 struct group
*gresult
;
641 gresult
= getgrnam (*(p
) + 1);
642 if (gresult
&& gresult
->gr_gid
== (*peer
)->gid
)
648 for (char **t
= gresult
->gr_mem
; *t
; t
++)
650 result
= getpwnam (*t
);
651 if (result
&& result
->pw_uid
== (*peer
)->uid
)
660 result
= getpwnam (*p
);
661 if (result
&& result
->pw_uid
== (*peer
)->uid
)
675 return allowed
? 0 : GPG_ERR_INV_USER_ID
;
680 validate_peer (struct client_s
*cl
)
683 assuan_peercred_t peer
;
690 rc
= do_validate_peer (cl
, &peer
);
691 log_write ("peer %s: uid=%i, gid=%i, pid=%i",
692 !rc
? _("accepted") : _("rejected"), peer
->uid
, peer
->gid
,
698 xml_error_cb (void *data
, xmlErrorPtr e
)
700 struct client_s
*client
= data
;
703 * Keep the first reported error as the one to show in the error
704 * description. Reset in send_error().
706 if (client
->xml_error
)
709 xmlCopyError (e
, client
->xml_error
);
713 hook_waitpid (assuan_context_t ctx
, pid_t pid
, int action
,
714 int *status
, int options
)
716 return waitpid (pid
, status
, options
);
720 hook_read (assuan_context_t ctx
, assuan_fd_t fd
, void *data
, size_t len
)
723 struct client_s
*client
= assuan_get_pointer (ctx
);
725 if (client
->thd
->remote
)
726 return tls_read_hook (ctx
, (int) fd
, data
, len
);
729 return read ((int) fd
, data
, len
);
733 hook_write (assuan_context_t ctx
, assuan_fd_t fd
,
734 const void *data
, size_t len
)
737 struct client_s
*client
= assuan_get_pointer (ctx
);
739 if (client
->thd
->remote
)
740 return tls_write_hook (ctx
, (int) fd
, data
, len
);
743 return write ((int) fd
, data
, len
);
747 new_connection (struct client_s
*cl
)
750 static struct assuan_malloc_hooks mhooks
= { xmalloc
, xrealloc
, xfree
};
751 static struct assuan_system_hooks shooks
= {
752 ASSUAN_SYSTEM_HOOKS_VERSION
,
760 NULL
, //sendmsg both are used for FD passing
771 char *prio
= config_get_string ("global", "tls_cipher_suite");
773 cl
->thd
->tls
= tls_init (cl
->thd
->fd
, prio
);
780 rc
= assuan_new_ext (&cl
->ctx
, GPG_ERR_SOURCE_DEFAULT
, &mhooks
,
781 debug_level
? assuan_log_cb
: NULL
, NULL
);
785 assuan_ctx_set_system_hooks (cl
->ctx
, &shooks
);
786 rc
= assuan_init_socket_server (cl
->ctx
, cl
->thd
->fd
, 2);
790 assuan_set_pointer (cl
->ctx
, cl
);
791 assuan_set_hello_line (cl
->ctx
, PACKAGE_STRING
);
792 rc
= register_commands (cl
->ctx
);
796 rc
= assuan_accept (cl
->ctx
);
800 rc
= validate_peer (cl
);
801 /* May not be implemented on all platforms. */
802 if (rc
&& gpg_err_code (rc
) != GPG_ERR_ASS_GENERAL
)
805 rc
= init_client_crypto (&cl
->crypto
);
809 cl
->crypto
->agent
->client_ctx
= cl
->ctx
;
810 cl
->crypto
->client_ctx
= cl
->ctx
;
811 xmlSetStructuredErrorFunc (cl
, xml_error_cb
);
815 log_write ("%s", pwmd_strerror (rc
));
820 * This is called after a client_thread() terminates. Set with
821 * pthread_cleanup_push().
824 cleanup_cb (void *arg
)
826 struct client_thread_s
*cn
= arg
;
827 struct client_s
*cl
= cn
->cl
;
829 MUTEX_LOCK (&cn_mutex
);
830 cn_thread_list
= slist_remove (cn_thread_list
, cn
);
831 MUTEX_UNLOCK (&cn_mutex
);
840 gnutls_deinit (cn
->tls
->ses
);
847 assuan_release (cl
->ctx
);
848 else if (cl
->thd
&& cl
->thd
->fd
!= -1)
852 cleanup_crypto (&cl
->crypto
);
862 while (cn
->msg_queue
)
864 struct status_msg_s
*msg
= cn
->msg_queue
;
866 cn
->msg_queue
= msg
->next
;
871 if (cn
->status_msg_pipe
[0] != -1)
872 close (cn
->status_msg_pipe
[0]);
874 if (cn
->status_msg_pipe
[1] != -1)
875 close (cn
->status_msg_pipe
[1]);
877 pthread_mutex_destroy (&cn
->status_mutex
);
878 log_write (_("exiting, fd=%i"), cn
->fd
);
880 send_status_all (STATUS_CLIENTS
, NULL
);
881 pthread_cond_signal (&quit_cond
);
885 send_msg_queue (struct client_thread_s
*thd
)
887 MUTEX_LOCK (&thd
->status_mutex
);
891 read (thd
->status_msg_pipe
[0], &c
, 1);
893 while (thd
->msg_queue
)
895 struct status_msg_s
*msg
= thd
->msg_queue
;
897 thd
->msg_queue
= thd
->msg_queue
->next
;
898 MUTEX_UNLOCK (&thd
->status_mutex
);
899 rc
= send_status (thd
->cl
->ctx
, msg
->s
, msg
->line
);
900 MUTEX_LOCK (&thd
->status_mutex
);
908 MUTEX_UNLOCK (&thd
->status_mutex
);
913 client_thread (void *data
)
915 struct client_thread_s
*thd
= data
;
916 struct client_s
*cl
= xcalloc (1, sizeof (struct client_s
));
918 #ifdef HAVE_PR_SET_NAME
919 prctl (PR_SET_NAME
, "client");
921 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
925 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
926 pwmd_strerror (GPG_ERR_ENOMEM
));
930 MUTEX_LOCK (&cn_mutex
);
931 pthread_cleanup_push (cleanup_cb
, thd
);
934 MUTEX_UNLOCK (&cn_mutex
);
936 if (new_connection (cl
))
941 send_status_all (STATUS_CLIENTS
, NULL
);
942 rc
= send_status (cl
->ctx
, STATUS_CACHE
, NULL
);
945 log_write ("%s(%i): %s", __FILE__
, __LINE__
, pwmd_strerror (rc
));
956 FD_SET (thd
->fd
, &rfds
);
957 FD_SET (thd
->status_msg_pipe
[0], &rfds
);
960 thd
->status_msg_pipe
[0] ? thd
->fd
: thd
->status_msg_pipe
[0];
962 n
= select (n
+ 1, &rfds
, NULL
, NULL
, NULL
);
965 log_write ("%s", strerror (errno
));
969 if (FD_ISSET (thd
->status_msg_pipe
[0], &rfds
))
971 rc
= send_msg_queue (thd
);
972 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
974 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
980 if (!FD_ISSET (thd
->fd
, &rfds
))
983 rc
= assuan_process_next (cl
->ctx
, &eof
);
986 if (gpg_err_code (rc
) == GPG_ERR_EOF
|| eof
)
989 log_write ("assuan_process_next(): %s", pwmd_strerror (rc
));
990 rc
= send_error (cl
->ctx
, rc
);
994 log_write ("assuan_process_done(): %s", pwmd_strerror (rc
));
999 /* Since the msg queue pipe fd's are non-blocking, check for
1000 * pending status msgs here. GPG_ERR_EPIPE can be seen when the
1001 * client has already disconnected and will be converted to
1002 * GPG_ERR_EOF during assuan_process_next().
1004 rc
= send_msg_queue (thd
);
1005 if (rc
&& gpg_err_code (rc
) != GPG_ERR_EPIPE
)
1007 log_write ("%s(%i): %s", __FUNCTION__
, __LINE__
,
1008 pwmd_strerror (rc
));
1014 pthread_cleanup_pop (1);
1019 xml_import (const char *filename
, const char *outfile
,
1020 const char *keygrip
, const char *sign_keygrip
,
1021 const char *keyfile
, int no_passphrase
, const char *cipher
,
1022 const char *params
, unsigned long s2k_count
, uint64_t iterations
)
1031 struct crypto_s
*crypto
;
1032 int algo
= cipher
? cipher_string_to_gcrypt ((char *) cipher
) :
1037 log_write ("ERR %i: %s", gpg_error (GPG_ERR_CIPHER_ALGO
),
1038 pwmd_strerror (GPG_ERR_CIPHER_ALGO
));
1042 if (stat (filename
, &st
) == -1)
1044 log_write ("%s: %s", filename
,
1045 pwmd_strerror (gpg_error_from_syserror ()));
1049 rc
= init_client_crypto (&crypto
);
1053 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
1054 crypto
->save
.hdr
.flags
= set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
1055 log_write (_("Importing XML from '%s'. Output will be written to '%s' ..."),
1058 if ((fd
= open (filename
, O_RDONLY
)) == -1)
1060 log_write ("%s: %s", filename
,
1061 pwmd_strerror (gpg_error_from_syserror ()));
1065 if ((xmlbuf
= xmalloc (st
.st_size
+ 1)) == NULL
)
1068 log_write ("%s(%i): %s", __FILE__
, __LINE__
,
1069 pwmd_strerror (GPG_ERR_ENOMEM
));
1073 if (read (fd
, xmlbuf
, st
.st_size
) == -1)
1075 rc
= gpg_error_from_syserror ();
1077 log_write ("%s: %s", filename
, pwmd_strerror (rc
));
1082 xmlbuf
[st
.st_size
] = 0;
1084 * Make sure the document validates.
1086 if ((doc
= xmlReadDoc (xmlbuf
, NULL
, "UTF-8", XML_PARSE_NOBLANKS
)) == NULL
)
1088 log_write ("xmlReadDoc() failed");
1094 xmlNodePtr n
= xmlDocGetRootElement (doc
);
1095 if (!xmlStrEqual (n
->name
, (xmlChar
*) "pwmd"))
1097 log_write (_("Could not find root \"pwmd\" element."));
1098 rc
= GPG_ERR_BAD_DATA
;
1102 rc
= validate_import (n
? n
->children
: n
);
1106 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1111 xmlDocDumpMemory (doc
, &xml
, &len
);
1113 crypto
->save
.s2k_count
= s2k_count
;
1114 crypto
->save
.hdr
.iterations
= iterations
;
1115 rc
= set_pinentry_options (crypto
->agent
);
1117 rc
= export_common (crypto
, keygrip
, sign_keygrip
, no_passphrase
, xml
,
1118 len
, outfile
, params
, keyfile
);
1123 send_error (NULL
, rc
);
1127 cleanup_crypto (&crypto
);
1131 cleanup_crypto (&crypto
);
1136 do_cache_push (const char *filename
, struct crypto_s
*crypto
)
1138 unsigned char md5file
[16];
1143 struct cache_data_s
*cdata
;
1147 log_write (_("Trying to add datafile '%s' to the file cache ..."),
1150 if (valid_filename (filename
) == 0)
1152 log_write (_("%s: Invalid characters in filename"), filename
);
1156 rc
= read_data_file (filename
, crypto
);
1159 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1163 if ((key
= config_get_string (filename
, "passphrase")))
1165 log_write (_("Trying the passphrase specified in config ..."));
1166 keylen
= strlen (key
);
1168 else if ((key
= config_get_string (filename
, "passphrase_file")))
1170 int fd
= open ((char *) key
, O_RDONLY
);
1173 log_write (_("Trying the passphrase using file '%s' ..."), key
);
1176 log_write ("%s: %s", key
,
1177 pwmd_strerror (gpg_error_from_syserror ()));
1182 stat ((char *) key
, &st
);
1184 key
= xmalloc (st
.st_size
);
1185 if (read (fd
, key
, st
.st_size
) != st
.st_size
)
1187 log_write ("short read() count");
1193 keylen
= st
.st_size
;
1198 rc
= set_agent_passphrase (crypto
, key
, keylen
);
1202 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1207 crypto
->filename
= str_dup (filename
);
1208 rc
= decrypt_data (NULL
, crypto
);
1211 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1215 doc
= parse_doc ((char *) crypto
->plaintext
, crypto
->plaintext_len
);
1218 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1222 gcry_md_hash_buffer (GCRY_MD_MD5
, md5file
, filename
, strlen (filename
));
1223 cdata
= xcalloc (1, sizeof (struct cache_data_s
));
1227 log_write ("%s", pwmd_strerror (GPG_ERR_ENOMEM
));
1231 rc
= get_checksum (filename
, &crc
, &len
);
1234 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1236 free_cache_data_once (cdata
);
1241 rc
= encrypt_xml (NULL
, cache_key
, cache_keysize
, GCRY_CIPHER_AES
,
1242 crypto
->plaintext
, crypto
->plaintext_len
, &cdata
->doc
,
1243 &cdata
->doclen
, &cache_iv
, &cache_blocksize
, 0);
1246 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
1248 free_cache_data_once (cdata
);
1252 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->pubkey
, NULL
, "%S",
1254 gcry_sexp_build ((gcry_sexp_t
*) & cdata
->sigkey
, NULL
, "%S",
1255 crypto
->sigpkey_sexp
);
1256 int timeout
= config_get_integer (filename
, "cache_timeout");
1257 cache_add_file (md5file
, crypto
->grip
, cdata
, timeout
);
1258 log_write (_("Successfully added '%s' to the cache."), filename
);
1263 init_client (int fd
, const char *addr
)
1266 struct client_thread_s
*new = xcalloc (1, sizeof (struct client_thread_s
));
1271 return GPG_ERR_ENOMEM
;
1274 MUTEX_LOCK (&cn_mutex
);
1275 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
1277 if (pipe (new->status_msg_pipe
) == -1)
1278 rc
= gpg_error_from_syserror ();
1282 fcntl (new->status_msg_pipe
[0], F_SETFL
, O_NONBLOCK
);
1283 fcntl (new->status_msg_pipe
[1], F_SETFL
, O_NONBLOCK
);
1284 pthread_mutex_init (&new->status_mutex
, NULL
);
1290 new->remote
= addr
? 1 : 0;
1293 rc
= create_thread (client_thread
, new, &new->tid
, 1);
1296 close (new->status_msg_pipe
[0]);
1297 close (new->status_msg_pipe
[1]);
1298 pthread_mutex_destroy (&new->status_mutex
);
1304 struct slist_s
*list
= slist_append (cn_thread_list
, new);
1308 cn_thread_list
= list
;
1310 log_write (_("new connection: tid=%p, fd=%i, addr=%s"),
1311 (pthread_t
*) new->tid
, fd
, addr
);
1313 log_write (_("new connection: tid=%p, fd=%i"),
1314 (pthread_t
*) new->tid
, fd
);
1317 rc
= GPG_ERR_ENOMEM
;
1320 pthread_cleanup_pop (1);
1326 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1327 pwmd_strerror (rc
));
1333 /* From Beej's Guide to Network Programming. It's a good tutorial. */
1335 get_in_addr (struct sockaddr
*sa
)
1337 if (sa
->sa_family
== AF_INET
)
1338 return &(((struct sockaddr_in
*) sa
)->sin_addr
);
1340 return &(((struct sockaddr_in6
*) sa
)->sin6_addr
);
1344 tcp_accept_thread (void *arg
)
1346 int sockfd
= *(int *) arg
;
1347 #ifndef HAVE_PTHREAD_CANCEL
1348 int *n
= xmalloc (sizeof (int));
1351 pthread_setspecific (signal_thread_key
, n
);
1352 signal (SIGUSR2
, catch_thread_signal
);
1353 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1356 #ifdef HAVE_PR_SET_NAME
1357 prctl (PR_SET_NAME
, "tcp_accept");
1359 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1363 struct sockaddr_storage raddr
;
1364 socklen_t slen
= sizeof (raddr
);
1367 char s
[INET6_ADDRSTRLEN
];
1368 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1369 #ifndef HAVE_PTHREAD_CANCEL
1372 sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1377 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1380 if (errno
== EMFILE
|| errno
== ENFILE
)
1381 log_write ("accept(): %s",
1382 pwmd_strerror (gpg_error_from_syserror ()));
1383 else if (errno
!= EAGAIN
)
1385 if (!quit
) // probably EBADF
1386 log_write ("accept(): %s", strerror (errno
));
1391 #ifndef HAVE_PTHREAD_CANCEL
1392 select (0, NULL
, NULL
, NULL
, &tv
);
1400 inet_ntop (raddr
.ss_family
, get_in_addr ((struct sockaddr
*) &raddr
),
1402 (void) init_client (fd
, s
);
1403 n
= config_get_integer ("global", "tcp_wait");
1406 tv
.tv_sec
= (n
* 100000) / 100000;
1407 tv
.tv_usec
= (n
* 100000) % 100000;
1408 select (0, NULL
, NULL
, NULL
, &tv
);
1416 start_stop_tls_with_protocol (int ipv6
, int term
)
1418 struct addrinfo hints
, *servinfo
, *p
;
1419 int port
= config_get_integer ("global", "tcp_port");
1423 int *fd
= ipv6
? &tls6_fd
: &tls_fd
;
1425 if (term
|| config_get_boolean ("global", "enable_tcp") == 0)
1431 #ifdef HAVE_PTHREAD_CANCEL
1432 pthread_cancel (tls6_tid
);
1434 pthread_kill (tls6_tid
, SIGUSR2
);
1436 pthread_join (tls6_tid
, NULL
);
1439 shutdown (tls6_fd
, SHUT_RDWR
);
1449 #ifdef HAVE_PTHREAD_CANCEL
1450 pthread_cancel (tls_tid
);
1452 pthread_kill (tls_tid
, SIGUSR2
);
1454 pthread_join (tls_tid
, NULL
);
1457 shutdown (tls_fd
, SHUT_RDWR
);
1463 /* A client may still be connected. */
1464 if (!quit
&& x509_cred
!= NULL
)
1465 tls_deinit_params ();
1470 if ((ipv6
&& tls6_fd
!= -1) || (!ipv6
&& tls_fd
!= -1))
1473 memset (&hints
, 0, sizeof (hints
));
1474 hints
.ai_family
= ipv6
? AF_INET6
: AF_INET
;
1475 hints
.ai_socktype
= SOCK_STREAM
;
1476 hints
.ai_flags
= AI_PASSIVE
;
1477 snprintf (buf
, sizeof (buf
), "%i", port
);
1479 if ((n
= getaddrinfo (NULL
, buf
, &hints
, &servinfo
)) == -1)
1481 log_write ("getaddrinfo(): %s", gai_strerror (n
));
1485 for (n
= 0, p
= servinfo
; p
!= NULL
; p
= p
->ai_next
)
1489 if ((ipv6
&& p
->ai_family
!= AF_INET6
)
1490 || (!ipv6
&& p
->ai_family
!= AF_INET
))
1493 if ((*fd
= socket (p
->ai_family
, p
->ai_socktype
, p
->ai_protocol
)) == -1)
1495 log_write ("socket(): %s", strerror (errno
));
1499 if (setsockopt (*fd
, SOL_SOCKET
, SO_REUSEADDR
, &r
, sizeof (int)) == -1)
1501 log_write ("setsockopt(): %s",
1502 pwmd_strerror (gpg_error_from_syserror ()));
1503 freeaddrinfo (servinfo
);
1507 if (bind (*fd
, p
->ai_addr
, p
->ai_addrlen
) == -1)
1510 log_write ("bind(): %s",
1511 pwmd_strerror (gpg_error_from_syserror ()));
1519 freeaddrinfo (servinfo
);
1524 #ifdef HAVE_DECL_SO_BINDTODEVICE
1525 char *tmp
= config_get_string ("global", "tcp_interface");
1526 if (tmp
&& setsockopt (*fd
, SOL_SOCKET
, SO_BINDTODEVICE
, tmp
, 1) == -1)
1528 log_write ("setsockopt(): %s",
1529 pwmd_strerror (gpg_error_from_syserror ()));
1537 if (x509_cred
== NULL
)
1539 rc
= tls_init_params ();
1544 if (listen (*fd
, 0) == -1)
1546 log_write ("listen(): %s", strerror (errno
));
1551 rc
= create_thread (tcp_accept_thread
, fd
, &tls6_tid
, 0);
1553 rc
= create_thread (tcp_accept_thread
, fd
, &tls_tid
, 0);
1557 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1558 pwmd_strerror (rc
));
1570 start_stop_tls_with_protocol (0, 1);
1583 start_stop_tls (int term
)
1585 char *s
= config_get_string ("global", "tcp_bind");
1591 if (!strcmp (s
, "any"))
1593 b
= start_stop_tls_with_protocol (0, term
);
1595 b
= start_stop_tls_with_protocol (1, term
);
1597 else if (!strcmp (s
, "ipv4"))
1598 b
= start_stop_tls_with_protocol (0, term
);
1599 else if (!strcmp (s
, "ipv6"))
1600 b
= start_stop_tls_with_protocol (1, term
);
1610 accept_thread (void *arg
)
1612 int sockfd
= *(int *) arg
;
1613 #ifndef HAVE_PTHREAD_CANCEL
1614 int *n
= xmalloc (sizeof (int));
1617 pthread_setspecific (signal_thread_key
, n
);
1618 signal (SIGUSR2
, catch_thread_signal
);
1619 fcntl (sockfd
, F_SETFL
, O_NONBLOCK
);
1622 #ifdef HAVE_PR_SET_NAME
1623 prctl (PR_SET_NAME
, "accept");
1625 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1629 socklen_t slen
= sizeof (struct sockaddr_un
);
1630 struct sockaddr_un raddr
;
1632 #ifndef HAVE_PTHREAD_CANCEL
1633 struct timeval tv
= { 0, ACCEPT_TIMEOUT
};
1634 int *sigusr2
= (int *) pthread_getspecific (signal_thread_key
);
1640 fd
= accept (sockfd
, (struct sockaddr
*) &raddr
, &slen
);
1643 if (errno
== EMFILE
|| errno
== ENFILE
)
1644 log_write ("accept(): %s",
1645 pwmd_strerror (gpg_error_from_syserror ()));
1646 else if (errno
!= EAGAIN
)
1648 if (!quit
) // probably EBADF
1649 log_write ("accept(): %s",
1650 pwmd_strerror (gpg_error_from_syserror ()));
1655 #ifndef HAVE_PTHREAD_CANCEL
1656 select (0, NULL
, NULL
, NULL
, &tv
);
1661 (void) init_client (fd
, NULL
);
1664 /* Just in case accept() failed for some reason other than EBADF */
1670 cache_timer_thread (void *arg
)
1672 #ifndef HAVE_PTHREAD_CANCEL
1673 int *n
= xmalloc (sizeof (int));
1676 pthread_setspecific (signal_thread_key
, n
);
1677 signal (SIGUSR2
, catch_thread_signal
);
1680 #ifdef HAVE_PR_SET_NAME
1681 prctl (PR_SET_NAME
, "cache timer");
1683 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1687 struct timeval tv
= { 1, 0 };
1688 #ifndef HAVE_PTHREAD_CANCEL
1691 n
= (int *) pthread_getspecific (signal_thread_key
);
1696 select (0, NULL
, NULL
, NULL
, &tv
);
1697 cache_adjust_timeout ();
1704 catch_sigabrt (int sig
)
1713 signal_loop (sigset_t sigset
)
1723 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1724 #ifdef HAVE_SIGTIMEDWAIT
1725 sig
= sigtimedwait (&sigset
, NULL
, &ts
);
1728 sig
= __rt_sigtimedwait (&sigset
, NULL
, &ts
, _NSIG
/ 8);
1733 if (errno
!= EAGAIN
)
1734 log_write ("sigwaitinfo(): %s",
1735 pwmd_strerror (gpg_error_from_syserror ()));
1740 log_write (_("caught signal %i (%s)"), sig
, strsignal (sig
));
1745 pthread_cond_signal (&rcfile_cond
);
1748 // not really handled here.
1749 catch_sigabrt (SIGABRT
);
1752 log_write (_("clearing file cache"));
1754 send_status_all (STATUS_CACHE
, NULL
);
1773 log_write ("Caught SIGSEGV. Exiting.");
1774 #ifdef HAVE_BACKTRACE
1775 BACKTRACE (__FUNCTION__
);
1781 waiting_for_exit (void *arg
)
1784 #ifndef HAVE_PTHREAD_CANCEL
1785 int *n
= xmalloc (sizeof (int));
1788 pthread_setspecific (signal_thread_key
, n
);
1789 signal (SIGUSR2
, catch_thread_signal
);
1792 #ifdef HAVE_PR_SET_NAME
1793 prctl (PR_SET_NAME
, "exiting");
1795 pthread_setspecific (thread_name_key
, str_dup (__FUNCTION__
));
1796 log_write (_("waiting for all clients to disconnect"));
1797 MUTEX_LOCK (&quit_mutex
);
1798 pthread_cleanup_push (cleanup_mutex_cb
, &quit_mutex
);
1805 MUTEX_LOCK (&cn_mutex
);
1806 n
= slist_length (cn_thread_list
);
1807 MUTEX_UNLOCK (&cn_mutex
);
1811 #ifndef HAVE_PTHREAD_CANCEL
1812 int *s
= (int *) pthread_getspecific (signal_thread_key
);
1819 log_write (_("%i clients remain"), n
);
1823 INIT_TIMESPEC (SIG_TIMEOUT
, ts
);
1824 pthread_cond_timedwait (&quit_cond
, &quit_mutex
, &ts
);
1827 kill (getpid (), SIGCHLD
);
1828 pthread_cleanup_pop (1);
1833 server_loop (int sockfd
, char **socketpath
)
1835 pthread_t accept_tid
;
1836 pthread_t cache_timeout_tid
;
1837 int cancel_timeout_thread
= 0, cancel_accept_thread
= 0;
1844 sigemptyset (&sigset
);
1847 sigaddset (&sigset
, SIGTERM
);
1848 sigaddset (&sigset
, SIGINT
);
1850 /* Clears the file cache. */
1851 sigaddset (&sigset
, SIGUSR1
);
1853 /* Configuration file reloading. */
1854 sigaddset (&sigset
, SIGHUP
);
1856 /* For exiting cleanly. */
1857 sigaddset (&sigset
, SIGCHLD
);
1859 /* Clears the cache and exits when something bad happens. */
1860 signal (SIGABRT
, catch_sigabrt
);
1861 sigaddset (&sigset
, SIGABRT
);
1862 sigprocmask (SIG_BLOCK
, &sigset
, NULL
);
1864 /* Ignored everywhere. When a client disconnects abnormally this signal
1865 * gets raised. It isn't needed though because client_thread() will check
1866 * for rcs even after the client disconnects. */
1867 signal (SIGPIPE
, SIG_IGN
);
1869 /* Can show a backtrace of the stack in the log. */
1870 signal (SIGSEGV
, catchsig
);
1873 /* Needs to be done after the fork(). */
1874 if (!start_stop_tls (0))
1881 pthread_mutex_init (&quit_mutex
, NULL
);
1882 pthread_cond_init (&quit_cond
, NULL
);
1883 log_write (_("%s started for user %s"), PACKAGE_STRING
, get_username ());
1884 #ifndef HAVE_DECL_SO_PEERCRED
1885 log_write (_("Peer credential checking is NOT supported on this OS."));
1888 if (config_get_boolean ("global", "enable_tcp"))
1889 log_write (_("Listening on %s and TCP port %i"), *socketpath
,
1890 config_get_integer ("global", "tcp_port"));
1892 log_write (_("Listening on %s"), *socketpath
);
1894 log_write (_("Listening on %s"), *socketpath
);
1897 rc
= create_thread (reload_rcfile_thread
, NULL
, &rcfile_tid
, 0);
1900 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1901 pwmd_strerror (rc
));
1905 rc
= create_thread (cache_timer_thread
, NULL
, &cache_timeout_tid
, 0);
1908 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1909 pwmd_strerror (rc
));
1913 cancel_timeout_thread
= 1;
1914 rc
= create_thread (accept_thread
, &sockfd
, &accept_tid
, 0);
1917 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1918 pwmd_strerror (rc
));
1922 cancel_accept_thread
= 1;
1924 signal_loop (sigset
);
1930 * We're out of the main server loop. This happens when a signal was sent
1931 * to terminate the daemon. We'll wait for all clients to disconnect
1932 * before exiting but exit immediately if another termination signal is
1935 if (cancel_accept_thread
)
1937 #ifdef HAVE_PTHREAD_CANCEL
1938 int n
= pthread_cancel (accept_tid
);
1940 int n
= pthread_kill (accept_tid
, SIGUSR2
);
1943 pthread_join (accept_tid
, NULL
);
1946 shutdown (sockfd
, SHUT_RDWR
);
1948 unlink (*socketpath
);
1949 xfree (*socketpath
);
1951 MUTEX_LOCK (&cn_mutex
);
1952 n
= slist_length (cn_thread_list
);
1953 MUTEX_UNLOCK (&cn_mutex
);
1959 rc
= create_thread (waiting_for_exit
, NULL
, &tid
, 0);
1962 if (signal_loop (sigset
))
1964 log_write (_("Received second termination request. Exiting."));
1965 #ifdef HAVE_PTHREAD_CANCEL
1966 pthread_cancel (tid
);
1968 pthread_kill (tid
, SIGUSR2
);
1970 pthread_join (tid
, NULL
);
1974 log_write ("%s(%i): pthread_create(): %s", __FILE__
, __LINE__
,
1975 pwmd_strerror (rc
));
1978 if (cancel_timeout_thread
)
1980 #ifdef HAVE_PTHREAD_CANCEL
1981 pthread_cancel (cache_timeout_tid
);
1983 pthread_kill (cache_timeout_tid
, SIGUSR2
);
1985 pthread_join (cache_timeout_tid
, NULL
);
1988 MUTEX_LOCK (&cn_mutex
);
1990 n
= slist_length (cn_thread_list
);
1992 for (i
= 0; i
< n
; i
++)
1994 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2004 MUTEX_UNLOCK (&cn_mutex
);
2010 pthread_cond_destroy (&quit_cond
);
2011 pthread_mutex_destroy (&quit_mutex
);
2012 return segv
? EXIT_FAILURE
: EXIT_SUCCESS
;;
2019 ("Failed to add a file to the cache. Use --ignore to force startup. Exiting."));
2023 /* This is called from cache.c:clear_once(). See
2024 * command.c:clearcache_command() for details about lock checking.
2027 free_cache_data (file_cache_t
* cache
)
2029 gpg_error_t rc
= GPG_ERR_NO_DATA
;
2031 struct client_thread_s
*found
= NULL
;
2038 MUTEX_LOCK (&cn_mutex
);
2039 pthread_cleanup_push (cleanup_mutex_cb
, &cn_mutex
);
2040 t
= slist_length (cn_thread_list
);
2042 for (i
= 0; i
< t
; i
++)
2044 struct client_thread_s
*thd
= slist_nth_data (cn_thread_list
, i
);
2049 if (!memcmp (thd
->cl
->md5file
, cache
->filename
,
2050 sizeof (cache
->filename
)))
2052 if (pthread_equal (pthread_self (), thd
->tid
))
2059 /* Continue trying to find a client who has the same file open and
2060 * also has a lock. */
2061 rc
= cache_lock_mutex (thd
->cl
->ctx
, thd
->cl
->md5file
, -1, 0, -1);
2071 if (self
&& (!rc
|| rc
== GPG_ERR_NO_DATA
))
2072 rc
= cache_lock_mutex (found
->cl
->ctx
, found
->cl
->md5file
, -1, 0, -1);
2074 if (exiting
|| !rc
|| rc
== GPG_ERR_NO_DATA
)
2076 free_cache_data_once (cache
->data
);
2078 cache
->defer_clear
= 0;
2079 cache
->timeout
= -1;
2082 cache_unlock_mutex (found
->cl
->md5file
, 0);
2088 cache
->defer_clear
= 1;
2090 pthread_cleanup_pop (1);
2096 convert_v2_datafile (const char *filename
, const char *cipher
,
2097 const char *keyfile
, const char *keygrip
,
2098 const char *sign_keygrip
, int nopass
,
2099 const char *outfile
, const char *keyparam
,
2100 unsigned long s2k_count
, uint64_t iterations
)
2105 struct crypto_s
*crypto
= NULL
;
2109 if (outfile
[0] == '-' && outfile
[1] == 0)
2112 log_write (_("Converting version 2 data file \"%s\" ..."), filename
);
2113 if (access (filename
, R_OK
) == -1)
2115 log_write ("%s: %s", filename
,
2116 pwmd_strerror (gpg_error_from_syserror ()));
2122 log_write (_("Using passphrase file \"%s\" for decryption ..."),
2124 if (access (keyfile
, R_OK
) == -1)
2126 log_write ("%s: %s", keyfile
,
2127 pwmd_strerror (gpg_error_from_syserror ()));
2132 rc
= read_v2_datafile (filename
, keyfile
, &data
, &datalen
, &ver
, &algo
);
2135 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2141 algo
= cipher_string_to_gcrypt (cipher
);
2144 rc
= GPG_ERR_CIPHER_ALGO
;
2151 xmlDocPtr doc
= parse_doc (data
, datalen
);
2155 rc
= GPG_ERR_BAD_DATA
;
2159 rc
= convert_pre_212_elements (doc
);
2164 xmlDocDumpFormatMemory (doc
, (xmlChar
**) & data
, (int *) &datalen
,
2167 rc
= GPG_ERR_ENOMEM
;
2175 rc
= init_client_crypto (&crypto
);
2178 rc
= set_pinentry_options (crypto
->agent
);
2181 memcpy (&crypto
->save
.hdr
, &crypto
->hdr
, sizeof (file_header_t
));
2182 crypto
->save
.hdr
.flags
=
2183 set_cipher_flag (crypto
->save
.hdr
.flags
, algo
);
2184 crypto
->save
.s2k_count
= s2k_count
;
2185 crypto
->save
.hdr
.iterations
= iterations
;
2186 rc
= export_common (crypto
, keygrip
, sign_keygrip
, nopass
, data
,
2187 datalen
, outfile
, keyparam
,
2188 no_passphrase_file
? NULL
: keyfile
);
2190 log_write (_("Output written to \"%s\"."), outfile
);
2199 cleanup_crypto (&crypto
);
2202 log_write ("ERR %i: %s", rc
, pwmd_strerror (rc
));
2207 usage (const char *pn
, int status
)
2209 FILE *fp
= status
== EXIT_FAILURE
? stderr
: stdout
;
2211 fprintf (fp
, _("Usage: %s [OPTIONS] [file1] [...]\n"
2212 " -f, --rcfile=filename load the specfied configuration file\n"
2213 " (~/.pwmd/config)\n"
2214 " --homedir alternate pwmd home directory (~/.pwmd)\n"
2215 " -n, --no-fork run as a foreground process\n"
2216 " -D, --disable-dump disable the LIST, XPATH and DUMP commands\n"
2217 " --ignore ignore file errors during startup\n"
2218 " --debug-level=keywords log protocol output (see manual for details)\n"
2219 " -o, --outfile=filename output file when importing or converting\n"
2220 " -C, --convert=filename convert a version 2 data file to version 3\n"
2221 " -I, --import=filename import a pwmd DTD formatted XML file)\n"
2222 " -k, --passphrase-file=file for use when importing or converting\n"
2223 " --no-passphrase-file prompt instead of using --passphrase-file when\n"
2225 " --no-passphrase when importing or converting\n"
2226 " --keygrip=hex public key to use when encrypting\n"
2227 " --sign-keygrip=hex private key to use when signing\n"
2228 " --keyparam=s-exp custom key parameters to use (RSA-2048)\n"
2229 " --cipher=string encryption cipher (aes256)\n"
2230 " --iterations=N cipher iteration count (N+1)\n"
2231 " --s2k-count=N hash iteration count (>65536, calibrated)\n"
2232 " --help this help text\n"
2233 " --version show version and compile time features\n"),
2239 main (int argc
, char *argv
[])
2242 struct sockaddr_un addr
;
2244 char *socketpath
= NULL
, *socketdir
, *socketname
= NULL
;
2245 char *socketarg
= NULL
;
2246 char *datadir
= NULL
;
2249 char **cache_push
= NULL
;
2250 char *import
= NULL
, *keygrip
= NULL
, *sign_keygrip
= NULL
;
2251 char *keyparam
= NULL
;
2252 int estatus
= EXIT_FAILURE
;
2254 char *outfile
= NULL
;
2257 int show_version
= 0;
2259 int no_passphrase
= 0;
2261 char *convertfile
= NULL
;
2262 char *cipher
= NULL
;
2263 char *keyfile
= NULL
;
2264 unsigned long s2k_count
= 0;
2265 uint64_t iterations
= 0;
2267 char *debug_level_opt
= NULL
;
2269 /* Must maintain the same order as longopts[] */
2271 { OPT_VERSION
, OPT_HELP
, OPT_DEBUG_LEVEL
, OPT_HOMEDIR
, OPT_NO_FORK
,
2272 OPT_DISABLE_DUMP
, OPT_IGNORE
, OPT_RCFILE
, OPT_CONVERT
,
2273 OPT_PASSPHRASE_FILE
, OPT_IMPORT
, OPT_OUTFILE
, OPT_NO_PASSPHRASE_FILE
,
2274 OPT_KEYGRIP
, OPT_SIGN_KEYGRIP
, OPT_KEYPARAM
, OPT_CIPHER
,
2275 OPT_ITERATIONS
, OPT_S2K_COUNT
, OPT_NO_PASSPHRASE
2277 const char *optstring
= "nf:C:k:I:o:";
2278 const struct option longopts
[] = {
2279 {"version", no_argument
, 0, 0},
2280 {"help", no_argument
, 0, 0},
2281 {"debug-level", required_argument
, 0, 0},
2282 {"homedir", required_argument
, 0, 0},
2283 {"no-fork", no_argument
, 0, 'n'},
2284 {"disable_dump", no_argument
, 0, 0},
2285 {"ignore", no_argument
, 0, 0},
2286 {"rcfile", required_argument
, 0, 'f'},
2287 {"convert", required_argument
, 0, 'C'},
2288 {"passphrase-file", required_argument
, 0, 'k'},
2289 {"import", required_argument
, 0, 'I'},
2290 {"outfile", required_argument
, 0, 'o'},
2291 {"no-passphrase-file", no_argument
, 0, 0},
2292 {"keygrip", required_argument
, 0, 0},
2293 {"sign-keygrip", required_argument
, 0, 0},
2294 {"keyparam", required_argument
, 0, 0},
2295 {"cipher", required_argument
, 0, 0},
2296 {"cipher-iterations", required_argument
, 0, 0},
2297 {"s2k-count", required_argument
, 0, 0},
2298 {"no-passphrase", no_argument
, 0, 0},
2303 #ifdef HAVE_SETRLIMIT
2306 rl
.rlim_cur
= rl
.rlim_max
= 0;
2308 if (setrlimit (RLIMIT_CORE
, &rl
) != 0)
2309 err (EXIT_FAILURE
, "setrlimit()");
2314 setlocale (LC_ALL
, "");
2315 bindtextdomain ("pwmd", LOCALEDIR
);
2316 textdomain ("pwmd");
2324 if (setup_crypto ())
2325 exit (EXIT_FAILURE
);
2328 gnutls_global_set_mem_functions (xmalloc
, xmalloc
, secure_mem_check
,
2330 gnutls_global_init ();
2331 gnutls_global_set_log_function (tls_log
);
2332 gnutls_global_set_log_level (1);
2336 xmlMemSetup (xfree
, xmalloc
, xrealloc
, str_dup
);
2344 getopt_long (argc
, argv
, optstring
, longopts
, &optindex
)) != -1)
2352 convertfile
= optarg
;
2367 rcfile
= str_dup (optarg
);
2370 usage (argv
[0], EXIT_FAILURE
);
2381 case OPT_DEBUG_LEVEL
:
2382 debug_level_opt
= optarg
;
2385 homedir
= str_dup (optarg
);
2390 case OPT_DISABLE_DUMP
:
2397 rcfile
= str_dup (optarg
);
2400 convertfile
= optarg
;
2402 case OPT_PASSPHRASE_FILE
:
2411 case OPT_NO_PASSPHRASE_FILE
:
2412 no_passphrase_file
= 1;
2417 case OPT_SIGN_KEYGRIP
:
2418 sign_keygrip
= optarg
;
2426 case OPT_ITERATIONS
:
2427 iterations
= strtoull (optarg
, NULL
, 10);
2430 s2k_count
= strtoul (optarg
, NULL
, 10);
2432 case OPT_NO_PASSPHRASE
:
2444 "Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012\n"
2446 "Released under the terms of the GPL v2. Use at your own risk.\n\n"
2447 "Compile time features:\n%s"), PACKAGE_STRING
,
2475 exit (EXIT_SUCCESS
);
2479 homedir
= str_asprintf ("%s/.pwmd", get_home_dir ());
2481 if (mkdir (homedir
, 0700) == -1 && errno
!= EEXIST
)
2482 err (EXIT_FAILURE
, "%s", homedir
);
2484 snprintf (buf
, sizeof (buf
), "%s/data", homedir
);
2485 if (mkdir (buf
, 0700) == -1 && errno
!= EEXIST
)
2486 err (EXIT_FAILURE
, "%s", buf
);
2488 datadir
= str_dup (buf
);
2489 pthread_mutexattr_t attr
;
2490 pthread_mutexattr_init (&attr
);
2491 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
2492 pthread_mutex_init (&rcfile_mutex
, &attr
);
2493 pthread_cond_init (&rcfile_cond
, NULL
);
2494 pthread_mutex_init (&cn_mutex
, &attr
);
2495 pthread_mutexattr_destroy (&attr
);
2496 pthread_key_create (&last_error_key
, free_key
);
2497 #ifndef HAVE_PTHREAD_CANCEL
2498 pthread_key_create (&signal_thread_key
, free_key
);
2502 rcfile
= str_asprintf ("%s/config", homedir
);
2504 global_config
= config_parse (rcfile
);
2506 exit (EXIT_FAILURE
);
2510 if (debug_level_opt
)
2511 debug_level
= str_split (debug_level_opt
, ",", 0);
2513 x
= config_get_int_param (global_config
, "global", "priority", &exists
);
2517 if (setpriority (PRIO_PROCESS
, 0, x
) == -1)
2519 log_write ("setpriority(): %s",
2520 pwmd_strerror (gpg_error_from_syserror ()));
2524 #ifdef HAVE_MLOCKALL
2525 if (disable_mlock
== 0 && mlockall (MCL_CURRENT
| MCL_FUTURE
) == -1)
2527 log_write ("mlockall(): %s",
2528 pwmd_strerror (gpg_error_from_syserror ()));
2533 rc
= cache_init (free_cache_data
);
2536 log_write ("pwmd: ERR %i: %s", rc
,
2537 gpg_err_code (rc
) == GPG_ERR_UNKNOWN_VERSION
2538 ? _("incompatible version: 2.1.0 or later required")
2539 : pwmd_strerror (rc
));
2544 s2k_count
= config_get_ulong (NULL
, "s2k_count");
2549 usage (argv
[0], EXIT_FAILURE
);
2551 estatus
= convert_v2_datafile (convertfile
, cipher
, keyfile
, keygrip
,
2552 sign_keygrip
, no_passphrase
, outfile
,
2553 keyparam
, s2k_count
, iterations
);
2554 config_free (global_config
);
2562 usage (argv
[0], EXIT_FAILURE
);
2564 if (outfile
[0] == '-' && outfile
[1] == 0)
2567 estatus
= xml_import (import
, outfile
, keygrip
, sign_keygrip
, keyfile
,
2568 no_passphrase
, cipher
, keyparam
, s2k_count
,
2570 config_free (global_config
);
2575 p
= config_get_string ("global", "socket_path");
2577 p
= str_asprintf ("%s/socket", homedir
);
2579 socketarg
= expand_homedir (p
);
2583 disable_list_and_dump
= config_get_boolean ("global",
2584 "disable_list_and_dump");
2586 disable_list_and_dump
= secure
;
2588 cache_push
= config_get_list ("global", "cache_push");
2590 while (optind
< argc
)
2592 if (strv_printf (&cache_push
, "%s", argv
[optind
++]) == 0)
2593 errx (EXIT_FAILURE
, "%s", pwmd_strerror (GPG_ERR_ENOMEM
));
2596 if (strchr (socketarg
, '/') == NULL
)
2598 socketdir
= getcwd (buf
, sizeof (buf
));
2599 socketname
= str_dup (socketarg
);
2600 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2604 socketname
= str_dup (strrchr (socketarg
, '/'));
2606 socketarg
[strlen (socketarg
) - strlen (socketname
) - 1] = 0;
2607 socketdir
= str_dup (socketarg
);
2608 socketpath
= str_asprintf ("%s/%s", socketdir
, socketname
);
2611 if (chdir (datadir
))
2613 log_write ("%s: %s", datadir
,
2614 pwmd_strerror (gpg_error_from_syserror ()));
2615 unlink (socketpath
);
2620 * Set the cache entry for a file. Prompts for the password.
2624 struct crypto_s
*crypto
;
2625 gpg_error_t rc
= init_client_crypto (&crypto
);
2629 estatus
= EXIT_FAILURE
;
2633 rc
= set_pinentry_options (crypto
->agent
);
2636 estatus
= EXIT_FAILURE
;
2640 for (opt
= 0; cache_push
[opt
]; opt
++)
2642 if (!do_cache_push (cache_push
[opt
], crypto
) && !force
)
2644 strv_free (cache_push
);
2646 estatus
= EXIT_FAILURE
;
2647 cleanup_crypto (&crypto
);
2651 cleanup_crypto_stage1 (crypto
);
2654 (void) kill_scd (crypto
->agent
);
2655 cleanup_crypto (&crypto
);
2656 strv_free (cache_push
);
2657 log_write (!nofork
? _("Done. Daemonizing...") :
2658 _("Done. Waiting for connections..."));
2661 config_clear_keys ();
2664 * bind() doesn't like the full pathname of the socket or any non alphanum
2665 * characters so change to the directory where the socket is wanted then
2666 * create it then change to datadir.
2668 if (chdir (socketdir
))
2670 log_write ("%s: %s", socketdir
,
2671 pwmd_strerror (gpg_error_from_syserror ()));
2677 if ((sockfd
= socket (PF_UNIX
, SOCK_STREAM
, 0)) == -1)
2679 log_write ("socket(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2683 addr
.sun_family
= AF_UNIX
;
2684 snprintf (addr
.sun_path
, sizeof (addr
.sun_path
), "%s", socketname
);
2686 if (bind (sockfd
, (struct sockaddr
*) &addr
, sizeof (struct sockaddr
)) ==
2689 log_write ("bind(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2691 if (errno
== EADDRINUSE
)
2692 log_write (_("Either there is another pwmd running or '%s' is a \n"
2693 "stale socket. Please remove it manually."), socketpath
);
2700 char *t
= config_get_string ("global", "socket_perms");
2706 mode
= strtol (t
, NULL
, 8);
2710 if (chmod (socketname
, mode
) == -1)
2712 log_write ("%s: %s", socketname
,
2713 pwmd_strerror (gpg_error_from_syserror ()));
2715 unlink (socketpath
);
2724 xfree (--socketname
);
2726 if (chdir (datadir
))
2728 log_write ("%s: %s", datadir
,
2729 pwmd_strerror (gpg_error_from_syserror ()));
2731 unlink (socketpath
);
2737 if (listen (sockfd
, 0) == -1)
2739 log_write ("listen(): %s", pwmd_strerror (gpg_error_from_syserror ()));
2750 log_write ("fork(): %s",
2751 pwmd_strerror (gpg_error_from_syserror ()));
2760 _exit (EXIT_SUCCESS
);
2764 pthread_key_create (&thread_name_key
, free_key
);
2765 pthread_setspecific (thread_name_key
, str_dup ("main"));
2766 estatus
= server_loop (sockfd
, &socketpath
);
2769 if (socketpath
&& do_unlink
)
2771 unlink (socketpath
);
2777 gnutls_global_deinit ();
2781 #ifdef HAVE_PTHREAD_CANCEL
2782 pthread_cancel (rcfile_tid
);
2784 pthread_kill (rcfile_tid
, SIGUSR2
);
2785 pthread_cond_signal (&rcfile_cond
);
2787 pthread_join (rcfile_tid
, NULL
);
2790 pthread_cond_destroy (&rcfile_cond
);
2791 pthread_mutex_destroy (&rcfile_mutex
);
2792 pthread_key_delete (last_error_key
);
2793 #ifndef HAVE_PTHREAD_CANCEL
2794 pthread_key_delete (signal_thread_key
);
2798 config_free (global_config
);
2801 xfree (home_directory
);
2803 xmlCleanupParser ();
2804 xmlCleanupGlobals ();
2806 if (estatus
== EXIT_SUCCESS
)
2807 log_write (_("pwmd exiting normally"));
2810 #if defined(DEBUG) && !defined(MEM_DEBUG)