116
51
#include <avahi-common/malloc.h>
117
52
#include <avahi-common/error.h>
120
#include <gnutls/gnutls.h> /* All GnuTLS types, constants and
123
init_gnutls_session(),
125
#include <gnutls/openpgp.h>
126
/* gnutls_certificate_set_openpgp_key_file(),
127
GNUTLS_OPENPGP_FMT_BASE64 */
54
/* Mandos client part */
55
#include <sys/types.h> /* socket(), inet_pton() */
56
#include <sys/socket.h> /* socket(), struct sockaddr_in6,
57
struct in6_addr, inet_pton() */
58
#include <gnutls/gnutls.h> /* All GnuTLS stuff */
59
#include <gnutls/openpgp.h> /* GnuTLS with openpgp stuff */
61
#include <unistd.h> /* close() */
62
#include <netinet/in.h>
63
#include <stdbool.h> /* true */
64
#include <string.h> /* memset */
65
#include <arpa/inet.h> /* inet_pton() */
66
#include <iso646.h> /* not */
67
#include <net/if.h> /* IF_NAMESIZE */
68
#include <argp.h> /* struct argp_option,
69
struct argp_state, struct argp,
130
#include <gpgme.h> /* All GPGME types, constants and
133
GPGME_PROTOCOL_OpenPGP,
72
#include <errno.h> /* perror() */
136
75
#define BUFFER_SIZE 256
138
#define PATHDIR "/conf/conf.d/mandos"
139
#define SECKEY "seckey.txt"
140
#define PUBKEY "pubkey.txt"
141
#define HOOKDIR "/lib/mandos/network-hooks.d"
143
77
bool debug = false;
78
static const char *keydir = "/conf/conf.d/mandos";
144
79
static const char mandos_protocol_version[] = "1";
145
const char *argp_program_version = "mandos-client " VERSION;
146
const char *argp_program_bug_address = "<mandos@recompile.se>";
147
static const char sys_class_net[] = "/sys/class/net";
148
char *connect_to = NULL;
149
const char *hookdir = HOOKDIR;
154
/* Doubly linked list that need to be circularly linked when used */
155
typedef struct server{
158
AvahiIfIndex if_index;
160
struct timespec last_seen;
80
const char *argp_program_version = "mandosclient 0.9";
81
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
165
83
/* Used for passing in values through the Avahi callback functions */
85
AvahiSimplePoll *simple_poll;
167
86
AvahiServer *server;
168
87
gnutls_certificate_credentials_t cred;
169
88
unsigned int dh_bits;
170
89
gnutls_dh_params_t dh_params;
171
90
const char *priority;
173
server *current_server;
175
size_t interfaces_size;
178
/* global so signal handler can reach it*/
179
AvahiSimplePoll *simple_poll;
181
sig_atomic_t quit_now = 0;
182
int signal_received = 0;
184
/* Function to use when printing errors */
185
void perror_plus(const char *print_text){
187
fprintf(stderr, "Mandos plugin %s: ",
188
program_invocation_short_name);
193
__attribute__((format (gnu_printf, 2, 3), nonnull))
194
int fprintf_plus(FILE *stream, const char *format, ...){
196
va_start (ap, format);
198
TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
199
program_invocation_short_name));
200
return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
204
* Make additional room in "buffer" for at least BUFFER_SIZE more
205
* bytes. "buffer_capacity" is how much is currently allocated,
94
* Make room in "buffer" for at least BUFFER_SIZE additional bytes.
95
* "buffer_capacity" is how much is currently allocated,
206
96
* "buffer_length" is how much is already used.
208
__attribute__((nonnull, warn_unused_result))
209
size_t incbuffer(char **buffer, size_t buffer_length,
210
size_t buffer_capacity){
211
if(buffer_length + BUFFER_SIZE > buffer_capacity){
212
char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
214
int old_errno = errno;
98
size_t adjustbuffer(char **buffer, size_t buffer_length,
99
size_t buffer_capacity){
100
if (buffer_length + BUFFER_SIZE > buffer_capacity){
101
*buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
221
105
buffer_capacity += BUFFER_SIZE;
223
107
return buffer_capacity;
226
/* Add server to set of servers to retry periodically */
227
__attribute__((nonnull, warn_unused_result))
228
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
229
int af, server **current_server){
231
server *new_server = malloc(sizeof(server));
232
if(new_server == NULL){
233
perror_plus("malloc");
236
*new_server = (server){ .ip = strdup(ip),
238
.if_index = if_index,
240
if(new_server->ip == NULL){
241
perror_plus("strdup");
245
ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
247
perror_plus("clock_gettime");
249
#pragma GCC diagnostic push
250
#pragma GCC diagnostic ignored "-Wcast-qual"
252
free((char *)(new_server->ip));
254
#pragma GCC diagnostic pop
259
/* Special case of first server */
260
if(*current_server == NULL){
261
new_server->next = new_server;
262
new_server->prev = new_server;
263
*current_server = new_server;
265
/* Place the new server last in the list */
266
new_server->next = *current_server;
267
new_server->prev = (*current_server)->prev;
268
new_server->prev->next = new_server;
269
(*current_server)->prev = new_server;
111
* Decrypt OpenPGP data using keyrings in HOMEDIR.
112
* Returns -1 on error
277
__attribute__((nonnull, warn_unused_result))
278
static bool init_gpgme(const char * const seckey,
279
const char * const pubkey,
280
const char * const tempdir,
114
static ssize_t pgp_packet_decrypt (const char *cryptotext,
117
const char *homedir){
118
gpgme_data_t dh_crypto, dh_plain;
282
120
gpgme_error_t rc;
122
size_t plaintext_capacity = 0;
123
ssize_t plaintext_length = 0;
283
124
gpgme_engine_info_t engine_info;
286
* Helper function to insert pub and seckey to the engine keyring.
288
bool import_key(const char * const filename){
291
gpgme_data_t pgp_data;
293
fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
299
rc = gpgme_data_new_from_fd(&pgp_data, fd);
300
if(rc != GPG_ERR_NO_ERROR){
301
fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
302
gpgme_strsource(rc), gpgme_strerror(rc));
306
rc = gpgme_op_import(mc->ctx, pgp_data);
307
if(rc != GPG_ERR_NO_ERROR){
308
fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
309
gpgme_strsource(rc), gpgme_strerror(rc));
315
perror_plus("close");
317
gpgme_data_release(pgp_data);
322
fprintf_plus(stderr, "Initializing GPGME\n");
127
fprintf(stderr, "Trying to decrypt OpenPGP data\n");
326
131
gpgme_check_version(NULL);
327
132
rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
328
if(rc != GPG_ERR_NO_ERROR){
329
fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
330
gpgme_strsource(rc), gpgme_strerror(rc));
133
if (rc != GPG_ERR_NO_ERROR){
134
fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
135
gpgme_strsource(rc), gpgme_strerror(rc));
334
139
/* Set GPGME home directory for the OpenPGP engine only */
335
rc = gpgme_get_engine_info(&engine_info);
336
if(rc != GPG_ERR_NO_ERROR){
337
fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
338
gpgme_strsource(rc), gpgme_strerror(rc));
140
rc = gpgme_get_engine_info (&engine_info);
141
if (rc != GPG_ERR_NO_ERROR){
142
fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
143
gpgme_strsource(rc), gpgme_strerror(rc));
341
146
while(engine_info != NULL){
342
147
if(engine_info->protocol == GPGME_PROTOCOL_OpenPGP){
343
148
gpgme_set_engine_info(GPGME_PROTOCOL_OpenPGP,
344
engine_info->file_name, tempdir);
149
engine_info->file_name, homedir);
347
152
engine_info = engine_info->next;
349
154
if(engine_info == NULL){
350
fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
355
/* Create new GPGME "context" */
356
rc = gpgme_new(&(mc->ctx));
357
if(rc != GPG_ERR_NO_ERROR){
358
fprintf_plus(stderr, "Mandos plugin mandos-client: "
359
"bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
364
if(not import_key(pubkey) or not import_key(seckey)){
372
* Decrypt OpenPGP data.
373
* Returns -1 on error
375
__attribute__((nonnull, warn_unused_result))
376
static ssize_t pgp_packet_decrypt(const char *cryptotext,
380
gpgme_data_t dh_crypto, dh_plain;
383
size_t plaintext_capacity = 0;
384
ssize_t plaintext_length = 0;
387
fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
155
fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
390
159
/* Create new GPGME data buffer from memory cryptotext */
391
160
rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
393
if(rc != GPG_ERR_NO_ERROR){
394
fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
395
gpgme_strsource(rc), gpgme_strerror(rc));
162
if (rc != GPG_ERR_NO_ERROR){
163
fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
164
gpgme_strsource(rc), gpgme_strerror(rc));
399
168
/* Create new empty GPGME data buffer for the plaintext */
400
169
rc = gpgme_data_new(&dh_plain);
401
if(rc != GPG_ERR_NO_ERROR){
402
fprintf_plus(stderr, "Mandos plugin mandos-client: "
403
"bad gpgme_data_new: %s: %s\n",
404
gpgme_strsource(rc), gpgme_strerror(rc));
170
if (rc != GPG_ERR_NO_ERROR){
171
fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
172
gpgme_strsource(rc), gpgme_strerror(rc));
405
173
gpgme_data_release(dh_crypto);
177
/* Create new GPGME "context" */
178
rc = gpgme_new(&ctx);
179
if (rc != GPG_ERR_NO_ERROR){
180
fprintf(stderr, "bad gpgme_new: %s: %s\n",
181
gpgme_strsource(rc), gpgme_strerror(rc));
182
plaintext_length = -1;
409
186
/* Decrypt data from the cryptotext data buffer to the plaintext
411
rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
412
if(rc != GPG_ERR_NO_ERROR){
413
fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
414
gpgme_strsource(rc), gpgme_strerror(rc));
188
rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
189
if (rc != GPG_ERR_NO_ERROR){
190
fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
191
gpgme_strsource(rc), gpgme_strerror(rc));
415
192
plaintext_length = -1;
417
gpgme_decrypt_result_t result;
418
result = gpgme_op_decrypt_result(mc->ctx);
420
fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
422
fprintf_plus(stderr, "Unsupported algorithm: %s\n",
423
result->unsupported_algorithm);
424
fprintf_plus(stderr, "Wrong key usage: %u\n",
425
result->wrong_key_usage);
426
if(result->file_name != NULL){
427
fprintf_plus(stderr, "File name: %s\n", result->file_name);
429
gpgme_recipient_t recipient;
430
recipient = result->recipients;
197
fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
201
gpgme_decrypt_result_t result;
202
result = gpgme_op_decrypt_result(ctx);
204
fprintf(stderr, "gpgme_op_decrypt_result failed\n");
206
fprintf(stderr, "Unsupported algorithm: %s\n",
207
result->unsupported_algorithm);
208
fprintf(stderr, "Wrong key usage: %d\n",
209
result->wrong_key_usage);
210
if(result->file_name != NULL){
211
fprintf(stderr, "File name: %s\n", result->file_name);
213
gpgme_recipient_t recipient;
214
recipient = result->recipients;
431
216
while(recipient != NULL){
432
fprintf_plus(stderr, "Public key algorithm: %s\n",
433
gpgme_pubkey_algo_name
434
(recipient->pubkey_algo));
435
fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
436
fprintf_plus(stderr, "Secret key available: %s\n",
437
recipient->status == GPG_ERR_NO_SECKEY
217
fprintf(stderr, "Public key algorithm: %s\n",
218
gpgme_pubkey_algo_name(recipient->pubkey_algo));
219
fprintf(stderr, "Key ID: %s\n", recipient->keyid);
220
fprintf(stderr, "Secret key available: %s\n",
221
recipient->status == GPG_ERR_NO_SECKEY
439
223
recipient = recipient->next;
447
fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
450
229
/* Seek back to the beginning of the GPGME plaintext data buffer */
451
if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
452
perror_plus("gpgme_data_seek");
230
if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
231
perror("pgpme_data_seek");
453
232
plaintext_length = -1;
454
233
goto decrypt_end;
457
236
*plaintext = NULL;
459
plaintext_capacity = incbuffer(plaintext,
460
(size_t)plaintext_length,
462
if(plaintext_capacity == 0){
463
perror_plus("incbuffer");
464
plaintext_length = -1;
238
plaintext_capacity = adjustbuffer(plaintext,
239
(size_t)plaintext_length,
241
if (plaintext_capacity == 0){
242
perror("adjustbuffer");
243
plaintext_length = -1;
468
247
ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
470
249
/* Print the data, if any */
476
perror_plus("gpgme_data_read");
255
perror("gpgme_data_read");
477
256
plaintext_length = -1;
478
257
goto decrypt_end;
480
259
plaintext_length += ret;
484
fprintf_plus(stderr, "Decrypted password is: ");
263
fprintf(stderr, "Decrypted password is: ");
485
264
for(ssize_t i = 0; i < plaintext_length; i++){
486
265
fprintf(stderr, "%02hhX ", (*plaintext)[i]);
541
317
/* OpenPGP credentials */
542
ret = gnutls_certificate_allocate_credentials(&mc->cred);
543
if(ret != GNUTLS_E_SUCCESS){
544
fprintf_plus(stderr, "GnuTLS memory error: %s\n",
545
safer_gnutls_strerror(ret));
318
if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
319
!= GNUTLS_E_SUCCESS) {
320
fprintf (stderr, "GnuTLS memory error: %s\n",
321
safer_gnutls_strerror(ret));
550
fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
551
" secret key %s as GnuTLS credentials\n",
326
fprintf(stderr, "Attempting to use OpenPGP certificate %s"
327
" and keyfile %s as GnuTLS credentials\n", pubkeyfile,
556
331
ret = gnutls_certificate_set_openpgp_key_file
557
(mc->cred, pubkeyfilename, seckeyfilename,
558
GNUTLS_OPENPGP_FMT_BASE64);
559
if(ret != GNUTLS_E_SUCCESS){
561
"Error[%d] while reading the OpenPGP key pair ('%s',"
562
" '%s')\n", ret, pubkeyfilename, seckeyfilename);
563
fprintf_plus(stderr, "The GnuTLS error is: %s\n",
564
safer_gnutls_strerror(ret));
332
(mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
333
if (ret != GNUTLS_E_SUCCESS) {
335
"Error[%d] while reading the OpenPGP key pair ('%s',"
336
" '%s')\n", ret, pubkeyfile, seckeyfile);
337
fprintf(stdout, "The GnuTLS error is: %s\n",
338
safer_gnutls_strerror(ret));
568
342
/* GnuTLS server initialization */
569
343
ret = gnutls_dh_params_init(&mc->dh_params);
570
if(ret != GNUTLS_E_SUCCESS){
571
fprintf_plus(stderr, "Error in GnuTLS DH parameter"
572
" initialization: %s\n",
573
safer_gnutls_strerror(ret));
576
/* If a Diffie-Hellman parameters file was given, try to use it */
577
if(dhparamsfilename != NULL){
578
gnutls_datum_t params = { .data = NULL, .size = 0 };
580
int dhpfile = open(dhparamsfilename, O_RDONLY);
583
dhparamsfilename = NULL;
586
size_t params_capacity = 0;
588
params_capacity = incbuffer((char **)¶ms.data,
590
(size_t)params_capacity);
591
if(params_capacity == 0){
592
perror_plus("incbuffer");
595
dhparamsfilename = NULL;
598
ssize_t bytes_read = read(dhpfile,
599
params.data + params.size,
605
/* check bytes_read for failure */
610
dhparamsfilename = NULL;
613
params.size += (unsigned int)bytes_read;
615
if(params.data == NULL){
616
dhparamsfilename = NULL;
618
if(dhparamsfilename == NULL){
621
ret = gnutls_dh_params_import_pkcs3(mc->dh_params, ¶ms,
622
GNUTLS_X509_FMT_PEM);
623
if(ret != GNUTLS_E_SUCCESS){
624
fprintf_plus(stderr, "Failed to parse DH parameters in file"
625
" \"%s\": %s\n", dhparamsfilename,
626
safer_gnutls_strerror(ret));
627
dhparamsfilename = NULL;
632
if(dhparamsfilename == NULL){
633
if(mc->dh_bits == 0){
634
/* Find out the optimal number of DH bits */
635
/* Try to read the private key file */
636
gnutls_datum_t buffer = { .data = NULL, .size = 0 };
638
int secfile = open(seckeyfilename, O_RDONLY);
643
size_t buffer_capacity = 0;
645
buffer_capacity = incbuffer((char **)&buffer.data,
647
(size_t)buffer_capacity);
648
if(buffer_capacity == 0){
649
perror_plus("incbuffer");
654
ssize_t bytes_read = read(secfile,
655
buffer.data + buffer.size,
661
/* check bytes_read for failure */
668
buffer.size += (unsigned int)bytes_read;
672
/* If successful, use buffer to parse private key */
673
gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
674
if(buffer.data != NULL){
676
gnutls_openpgp_privkey_t privkey = NULL;
677
ret = gnutls_openpgp_privkey_init(&privkey);
678
if(ret != GNUTLS_E_SUCCESS){
679
fprintf_plus(stderr, "Error initializing OpenPGP key"
681
safer_gnutls_strerror(ret));
685
ret = gnutls_openpgp_privkey_import
686
(privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
687
if(ret != GNUTLS_E_SUCCESS){
688
fprintf_plus(stderr, "Error importing OpenPGP key : %s",
689
safer_gnutls_strerror(ret));
695
/* Use private key to suggest an appropriate
697
sec_param = gnutls_openpgp_privkey_sec_param(privkey);
698
gnutls_openpgp_privkey_deinit(privkey);
700
fprintf_plus(stderr, "This OpenPGP key implies using"
701
" a GnuTLS security parameter \"%s\".\n",
702
safe_string(gnutls_sec_param_get_name
708
if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
709
/* Err on the side of caution */
710
sec_param = GNUTLS_SEC_PARAM_ULTRA;
712
fprintf_plus(stderr, "Falling back to security parameter"
714
safe_string(gnutls_sec_param_get_name
719
uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
723
fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
724
" implies %u DH bits; using that.\n",
725
safe_string(gnutls_sec_param_get_name
730
fprintf_plus(stderr, "Failed to get implied number of DH"
731
" bits for security parameter \"%s\"): %s\n",
732
safe_string(gnutls_sec_param_get_name
734
safer_gnutls_strerror(ret));
738
fprintf_plus(stderr, "DH bits explicitly set to %u\n",
741
ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
742
if(ret != GNUTLS_E_SUCCESS){
743
fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
744
" bits): %s\n", mc->dh_bits,
745
safer_gnutls_strerror(ret));
344
if (ret != GNUTLS_E_SUCCESS) {
345
fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
346
" %s\n", safer_gnutls_strerror(ret));
349
ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
350
if (ret != GNUTLS_E_SUCCESS) {
351
fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
352
safer_gnutls_strerror(ret));
749
356
gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
755
gnutls_certificate_free_credentials(mc->cred);
756
gnutls_dh_params_deinit(mc->dh_params);
760
__attribute__((nonnull, warn_unused_result))
761
static int init_gnutls_session(gnutls_session_t *session,
361
static int init_gnutls_session(mandos_context *mc,
362
gnutls_session_t *session){
764
364
/* GnuTLS session creation */
766
ret = gnutls_init(session, GNUTLS_SERVER);
770
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
771
if(ret != GNUTLS_E_SUCCESS){
773
"Error in GnuTLS session initialization: %s\n",
774
safer_gnutls_strerror(ret));
365
ret = gnutls_init(session, GNUTLS_SERVER);
366
if (ret != GNUTLS_E_SUCCESS){
367
fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
368
safer_gnutls_strerror(ret));
780
ret = gnutls_priority_set_direct(*session, mc->priority, &err);
782
gnutls_deinit(*session);
785
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
786
if(ret != GNUTLS_E_SUCCESS){
787
fprintf_plus(stderr, "Syntax error at: %s\n", err);
788
fprintf_plus(stderr, "GnuTLS error: %s\n",
789
safer_gnutls_strerror(ret));
790
gnutls_deinit(*session);
373
ret = gnutls_priority_set_direct(*session, mc->priority, &err);
374
if (ret != GNUTLS_E_SUCCESS) {
375
fprintf(stderr, "Syntax error at: %s\n", err);
376
fprintf(stderr, "GnuTLS error: %s\n",
377
safer_gnutls_strerror(ret));
796
ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
799
gnutls_deinit(*session);
802
} while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
803
if(ret != GNUTLS_E_SUCCESS){
804
fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
805
safer_gnutls_strerror(ret));
806
gnutls_deinit(*session);
382
ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
384
if (ret != GNUTLS_E_SUCCESS) {
385
fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
386
safer_gnutls_strerror(ret));
810
390
/* ignore client certificate if any. */
811
gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
391
gnutls_certificate_server_set_request (*session,
394
gnutls_dh_set_prime_bits (*session, mc->dh_bits);
817
400
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
818
401
__attribute__((unused)) const char *txt){}
820
/* Set effective uid to 0, return errno */
821
__attribute__((warn_unused_result))
822
int raise_privileges(void){
823
int old_errno = errno;
825
if(seteuid(0) == -1){
832
/* Set effective and real user ID to 0. Return errno. */
833
__attribute__((warn_unused_result))
834
int raise_privileges_permanently(void){
835
int old_errno = errno;
836
int ret = raise_privileges();
848
/* Set effective user ID to unprivileged saved user ID */
849
__attribute__((warn_unused_result))
850
int lower_privileges(void){
851
int old_errno = errno;
853
if(seteuid(uid) == -1){
860
/* Lower privileges permanently */
861
__attribute__((warn_unused_result))
862
int lower_privileges_permanently(void){
863
int old_errno = errno;
865
if(setuid(uid) == -1){
872
/* Helper function to add_local_route() and delete_local_route() */
873
__attribute__((nonnull, warn_unused_result))
874
static bool add_delete_local_route(const bool add,
876
AvahiIfIndex if_index){
878
char helper[] = "mandos-client-iprouteadddel";
879
char add_arg[] = "add";
880
char delete_arg[] = "delete";
881
char debug_flag[] = "--debug";
882
char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
883
if(pluginhelperdir == NULL){
885
fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
886
" variable not set; cannot run helper\n");
891
char interface[IF_NAMESIZE];
892
if(if_indextoname((unsigned int)if_index, interface) == NULL){
893
perror_plus("if_indextoname");
897
int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
899
perror_plus("open(\"/dev/null\", O_RDONLY)");
905
/* Raise privileges */
906
errno = raise_privileges_permanently();
908
perror_plus("Failed to raise privileges");
909
/* _exit(EX_NOPERM); */
915
perror_plus("setgid");
918
/* Reset supplementary groups */
920
ret = setgroups(0, NULL);
922
perror_plus("setgroups");
926
ret = dup2(devnull, STDIN_FILENO);
928
perror_plus("dup2(devnull, STDIN_FILENO)");
931
ret = close(devnull);
933
perror_plus("close");
936
ret = dup2(STDERR_FILENO, STDOUT_FILENO);
938
perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
941
int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
946
if(helperdir_fd == -1){
948
_exit(EX_UNAVAILABLE);
950
int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
953
perror_plus("openat");
955
_exit(EX_UNAVAILABLE);
959
#pragma GCC diagnostic push
960
#pragma GCC diagnostic ignored "-Wcast-qual"
962
if(fexecve(helper_fd, (char *const [])
963
{ helper, add ? add_arg : delete_arg, (char *)address,
964
interface, debug ? debug_flag : NULL, NULL },
967
#pragma GCC diagnostic pop
969
perror_plus("fexecve");
981
pret = waitpid(pid, &status, 0);
982
if(pret == -1 and errno == EINTR and quit_now){
983
int errno_raising = 0;
984
if((errno = raise_privileges()) != 0){
985
errno_raising = errno;
986
perror_plus("Failed to raise privileges in order to"
987
" kill helper program");
989
if(kill(pid, SIGTERM) == -1){
992
if((errno_raising == 0) and (errno = lower_privileges()) != 0){
993
perror_plus("Failed to lower privileges after killing"
998
} while(pret == -1 and errno == EINTR);
1000
perror_plus("waitpid");
1003
if(WIFEXITED(status)){
1004
if(WEXITSTATUS(status) != 0){
1005
fprintf_plus(stderr, "Error: iprouteadddel exited"
1006
" with status %d\n", WEXITSTATUS(status));
1011
if(WIFSIGNALED(status)){
1012
fprintf_plus(stderr, "Error: iprouteadddel died by"
1013
" signal %d\n", WTERMSIG(status));
1016
fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1020
__attribute__((nonnull, warn_unused_result))
1021
static bool add_local_route(const char *address,
1022
AvahiIfIndex if_index){
1024
fprintf_plus(stderr, "Adding route to %s\n", address);
1026
return add_delete_local_route(true, address, if_index);
1029
__attribute__((nonnull, warn_unused_result))
1030
static bool delete_local_route(const char *address,
1031
AvahiIfIndex if_index){
1033
fprintf_plus(stderr, "Removing route to %s\n", address);
1035
return add_delete_local_route(false, address, if_index);
1038
403
/* Called when a Mandos server is found */
1039
__attribute__((nonnull, warn_unused_result))
1040
static int start_mandos_communication(const char *ip, in_port_t port,
404
static int start_mandos_communication(const char *ip, uint16_t port,
1041
405
AvahiIfIndex if_index,
1042
int af, mandos_context *mc){
1043
int ret, tcp_sd = -1;
1045
struct sockaddr_storage to;
408
union { struct sockaddr in; struct sockaddr_in6 in6; } to;
1046
409
char *buffer = NULL;
1047
char *decrypted_buffer = NULL;
410
char *decrypted_buffer;
1048
411
size_t buffer_length = 0;
1049
412
size_t buffer_capacity = 0;
413
ssize_t decrypted_buffer_size;
416
char interface[IF_NAMESIZE];
1052
417
gnutls_session_t session;
1053
int pf; /* Protocol family */
1054
bool route_added = false;
1071
fprintf_plus(stderr, "Bad address family: %d\n", af);
1076
/* If the interface is specified and we have a list of interfaces */
1077
if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
1078
/* Check if the interface is one of the interfaces we are using */
1081
char *interface = NULL;
1082
while((interface=argz_next(mc->interfaces, mc->interfaces_size,
1084
if(if_nametoindex(interface) == (unsigned int)if_index){
1091
/* This interface does not match any in the list, so we don't
1092
connect to the server */
1094
char interface[IF_NAMESIZE];
1095
if(if_indextoname((unsigned int)if_index, interface) == NULL){
1096
perror_plus("if_indextoname");
1098
fprintf_plus(stderr, "Skipping server on non-used interface"
1100
if_indextoname((unsigned int)if_index,
419
ret = init_gnutls_session (mc, &session);
425
fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
429
tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
436
if(if_indextoname((unsigned int)if_index, interface) == NULL){
437
perror("if_indextoname");
440
fprintf(stderr, "Binding to interface %s\n", interface);
1108
ret = init_gnutls_session(&session, mc);
443
memset(&to,0,sizeof(to)); /* Spurious warning */
444
to.in6.sin6_family = AF_INET6;
445
/* It would be nice to have a way to detect if we were passed an
446
IPv4 address here. Now we assume an IPv6 address. */
447
ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
1114
fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
1115
PRIuMAX "\n", ip, (uintmax_t)port);
1118
tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
1121
perror_plus("socket");
1132
struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1133
*to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1134
ret = inet_pton(af, ip, &to6->sin6_addr);
1136
struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1137
*to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1138
ret = inet_pton(af, ip, &to4->sin_addr);
1142
perror_plus("inet_pton");
1148
fprintf_plus(stderr, "Bad address: %s\n", ip);
1153
((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
1154
if(IN6_IS_ADDR_LINKLOCAL
1155
(&((struct sockaddr_in6 *)&to)->sin6_addr)){
1156
if(if_index == AVAHI_IF_UNSPEC){
1157
fprintf_plus(stderr, "An IPv6 link-local address is"
1158
" incomplete without a network interface\n");
1162
/* Set the network interface number as scope */
1163
((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
1166
((struct sockaddr_in *)&to)->sin_port = htons(port);
453
fprintf(stderr, "Bad address: %s\n", ip);
456
to.in6.sin6_port = htons(port); /* Spurious warning */
458
to.in6.sin6_scope_id = (uint32_t)if_index;
1175
if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
1176
char interface[IF_NAMESIZE];
1177
if(if_indextoname((unsigned int)if_index, interface) == NULL){
1178
perror_plus("if_indextoname");
1180
fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
1181
"\n", ip, interface, (uintmax_t)port);
1184
fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
1185
ip, (uintmax_t)port);
1187
char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
1188
INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
1190
ret = getnameinfo((struct sockaddr *)&to,
1191
sizeof(struct sockaddr_in6),
1192
addrstr, sizeof(addrstr), NULL, 0,
1195
ret = getnameinfo((struct sockaddr *)&to,
1196
sizeof(struct sockaddr_in),
1197
addrstr, sizeof(addrstr), NULL, 0,
1200
if(ret == EAI_SYSTEM){
1201
perror_plus("getnameinfo");
1202
} else if(ret != 0) {
1203
fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
1204
} else if(strcmp(addrstr, ip) != 0){
1205
fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
1216
ret = connect(tcp_sd, (struct sockaddr *)&to,
1217
sizeof(struct sockaddr_in6));
1219
ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1220
sizeof(struct sockaddr_in));
1223
if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1224
and if_index != AVAHI_IF_UNSPEC
1225
and connect_to == NULL
1226
and not route_added and
1227
((af == AF_INET6 and not
1228
IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1230
or (af == AF_INET and
1231
/* Not a a IPv4LL address */
1232
(ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1233
& 0xFFFF0000L) != 0xA9FE0000L))){
1234
/* Work around Avahi bug - Avahi does not announce link-local
1235
addresses if it has a global address, so local hosts with
1236
*only* a link-local address (e.g. Mandos clients) cannot
1237
connect to a Mandos server announced by Avahi on a server
1238
host with a global address. Work around this by retrying
1239
with an explicit route added with the server's address.
1241
Avahi bug reference:
1242
https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1243
https://bugs.debian.org/587961
1246
fprintf_plus(stderr, "Mandos server unreachable, trying"
1250
route_added = add_local_route(ip, if_index);
1256
if(errno != ECONNREFUSED or debug){
1258
perror_plus("connect");
461
fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
462
char addrstr[INET6_ADDRSTRLEN] = "";
463
if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
464
sizeof(addrstr)) == NULL){
467
if(strcmp(addrstr, ip) != 0){
468
fprintf(stderr, "Canonical address form: %s\n", addrstr);
473
ret = connect(tcp_sd, &to.in, sizeof(to));
1271
479
const char *out = mandos_protocol_version;
1274
482
size_t out_size = strlen(out);
1275
ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
1276
out_size - written));
1279
perror_plus("write");
483
ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
484
out_size - written));
1281
488
goto mandos_end;
1283
490
written += (size_t)ret;
1284
491
if(written < out_size){
1287
if(out == mandos_protocol_version){
494
if (out == mandos_protocol_version){
1302
fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
1310
/* This casting via intptr_t is to eliminate warning about casting
1311
an int to a pointer type. This is exactly how the GnuTLS Guile
1312
function "set-session-transport-fd!" does it. */
1313
gnutls_transport_set_ptr(session,
1314
(gnutls_transport_ptr_t)(intptr_t)tcp_sd);
1322
ret = gnutls_handshake(session);
1327
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
1329
if(ret != GNUTLS_E_SUCCESS){
504
fprintf(stderr, "Establishing TLS session with %s\n", ip);
507
gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
509
ret = gnutls_handshake (session);
511
if (ret != GNUTLS_E_SUCCESS){
1331
fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
513
fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
1335
517
goto mandos_end;
1338
520
/* Read OpenPGP packet that contains the wanted password */
1341
fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
523
fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
1352
buffer_capacity = incbuffer(&buffer, buffer_length,
1354
if(buffer_capacity == 0){
1356
perror_plus("incbuffer");
1366
sret = gnutls_record_recv(session, buffer+buffer_length,
528
buffer_capacity = adjustbuffer(&buffer, buffer_length,
530
if (buffer_capacity == 0){
531
perror("adjustbuffer");
536
ret = gnutls_record_recv(session, buffer+buffer_length,
1373
543
case GNUTLS_E_INTERRUPTED:
1374
544
case GNUTLS_E_AGAIN:
1376
546
case GNUTLS_E_REHANDSHAKE:
1378
ret = gnutls_handshake(session);
1384
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
1386
fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
547
ret = gnutls_handshake (session);
549
fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
1390
552
goto mandos_end;
1394
fprintf_plus(stderr, "Unknown error while reading data from"
1395
" encrypted session with Mandos server\n");
1396
gnutls_bye(session, GNUTLS_SHUT_RDWR);
556
fprintf(stderr, "Unknown error while reading data from"
557
" encrypted session with Mandos server\n");
559
gnutls_bye (session, GNUTLS_SHUT_RDWR);
1398
560
goto mandos_end;
1401
buffer_length += (size_t) sret;
563
buffer_length += (size_t) ret;
1406
fprintf_plus(stderr, "Closing TLS session\n");
1415
ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
1420
} while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
1422
if(buffer_length > 0){
1423
ssize_t decrypted_buffer_size;
1424
decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
1425
&decrypted_buffer, mc);
1426
if(decrypted_buffer_size >= 0){
568
fprintf(stderr, "Closing TLS session\n");
571
gnutls_bye (session, GNUTLS_SHUT_RDWR);
573
if (buffer_length > 0){
574
decrypted_buffer_size = pgp_packet_decrypt(buffer,
578
if (decrypted_buffer_size >= 0){
1430
580
while(written < (size_t) decrypted_buffer_size){
1436
ret = (int)fwrite(decrypted_buffer + written, 1,
1437
(size_t)decrypted_buffer_size - written,
581
ret = (int)fwrite (decrypted_buffer + written, 1,
582
(size_t)decrypted_buffer_size - written,
1439
584
if(ret == 0 and ferror(stdout)){
1442
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
586
fprintf(stderr, "Error writing encrypted data: %s\n",
1448
592
written += (size_t)ret;
1450
ret = fflush(stdout);
1454
fprintf_plus(stderr, "Error writing encrypted data: %s\n",
594
free(decrypted_buffer);
1464
600
/* Shutdown procedure */
1469
if(not delete_local_route(ip, if_index)){
1470
fprintf_plus(stderr, "Failed to delete local route to %s on"
1471
" interface %d", ip, if_index);
1475
free(decrypted_buffer);
1478
ret = close(tcp_sd);
1484
perror_plus("close");
1486
gnutls_deinit(session);
605
gnutls_deinit (session);
606
gnutls_certificate_free_credentials (mc->cred);
607
gnutls_global_deinit ();
1496
__attribute__((nonnull))
1497
611
static void resolve_callback(AvahiSServiceResolver *r,
1498
612
AvahiIfIndex interface,
1499
AvahiProtocol proto,
613
AVAHI_GCC_UNUSED AvahiProtocol protocol,
1500
614
AvahiResolverEvent event,
1501
615
const char *name,
1502
616
const char *type,
1611
698
case AVAHI_BROWSER_ALL_FOR_NOW:
1612
699
case AVAHI_BROWSER_CACHE_EXHAUSTED:
1614
fprintf_plus(stderr, "No Mandos server found, still"
701
fprintf(stderr, "No Mandos server found, still searching...\n");
1621
/* Signal handler that stops main loop after SIGTERM */
1622
static void handle_sigterm(int sig){
1627
signal_received = sig;
1628
int old_errno = errno;
1629
/* set main loop to exit */
1630
if(simple_poll != NULL){
1631
avahi_simple_poll_quit(simple_poll);
1636
__attribute__((nonnull, warn_unused_result))
1637
bool get_flags(const char *ifname, struct ifreq *ifr){
1641
int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1644
perror_plus("socket");
1648
strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1649
ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1650
ret = ioctl(s, SIOCGIFFLAGS, ifr);
1654
perror_plus("ioctl SIOCGIFFLAGS");
1662
__attribute__((nonnull, warn_unused_result))
1663
bool good_flags(const char *ifname, const struct ifreq *ifr){
1665
/* Reject the loopback device */
1666
if(ifr->ifr_flags & IFF_LOOPBACK){
1668
fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1673
/* Accept point-to-point devices only if connect_to is specified */
1674
if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1676
fprintf_plus(stderr, "Accepting point-to-point interface"
1677
" \"%s\"\n", ifname);
1681
/* Otherwise, reject non-broadcast-capable devices */
1682
if(not (ifr->ifr_flags & IFF_BROADCAST)){
1684
fprintf_plus(stderr, "Rejecting non-broadcast interface"
1685
" \"%s\"\n", ifname);
1689
/* Reject non-ARP interfaces (including dummy interfaces) */
1690
if(ifr->ifr_flags & IFF_NOARP){
1692
fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1698
/* Accept this device */
1700
fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1706
* This function determines if a directory entry in /sys/class/net
1707
* corresponds to an acceptable network device.
1708
* (This function is passed to scandir(3) as a filter function.)
1710
__attribute__((nonnull, warn_unused_result))
1711
int good_interface(const struct dirent *if_entry){
1712
if(if_entry->d_name[0] == '.'){
1717
if(not get_flags(if_entry->d_name, &ifr)){
1719
fprintf_plus(stderr, "Failed to get flags for interface "
1720
"\"%s\"\n", if_entry->d_name);
1725
if(not good_flags(if_entry->d_name, &ifr)){
1732
* This function determines if a network interface is up.
1734
__attribute__((nonnull, warn_unused_result))
1735
bool interface_is_up(const char *interface){
1737
if(not get_flags(interface, &ifr)){
1739
fprintf_plus(stderr, "Failed to get flags for interface "
1740
"\"%s\"\n", interface);
1745
return (bool)(ifr.ifr_flags & IFF_UP);
1749
* This function determines if a network interface is running
1751
__attribute__((nonnull, warn_unused_result))
1752
bool interface_is_running(const char *interface){
1754
if(not get_flags(interface, &ifr)){
1756
fprintf_plus(stderr, "Failed to get flags for interface "
1757
"\"%s\"\n", interface);
1762
return (bool)(ifr.ifr_flags & IFF_RUNNING);
1765
__attribute__((nonnull, pure, warn_unused_result))
1766
int notdotentries(const struct dirent *direntry){
1767
/* Skip "." and ".." */
1768
if(direntry->d_name[0] == '.'
1769
and (direntry->d_name[1] == '\0'
1770
or (direntry->d_name[1] == '.'
1771
and direntry->d_name[2] == '\0'))){
1777
/* Is this directory entry a runnable program? */
1778
__attribute__((nonnull, warn_unused_result))
1779
int runnable_hook(const struct dirent *direntry){
1784
if((direntry->d_name)[0] == '\0'){
1789
sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1790
"abcdefghijklmnopqrstuvwxyz"
1793
if((direntry->d_name)[sret] != '\0'){
1794
/* Contains non-allowed characters */
1796
fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1802
ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1805
perror_plus("Could not stat hook");
1809
if(not (S_ISREG(st.st_mode))){
1810
/* Not a regular file */
1812
fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1817
if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1818
/* Not executable */
1820
fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1826
fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1832
__attribute__((nonnull, warn_unused_result))
1833
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1834
mandos_context *mc){
1836
struct timespec now;
1837
struct timespec waited_time;
1838
intmax_t block_time;
1841
if(mc->current_server == NULL){
1843
fprintf_plus(stderr, "Wait until first server is found."
1846
ret = avahi_simple_poll_iterate(s, -1);
1849
fprintf_plus(stderr, "Check current_server if we should run"
1852
/* the current time */
1853
ret = clock_gettime(CLOCK_MONOTONIC, &now);
1855
perror_plus("clock_gettime");
1858
/* Calculating in ms how long time between now and server
1859
who we visted longest time ago. Now - last seen. */
1860
waited_time.tv_sec = (now.tv_sec
1861
- mc->current_server->last_seen.tv_sec);
1862
waited_time.tv_nsec = (now.tv_nsec
1863
- mc->current_server->last_seen.tv_nsec);
1864
/* total time is 10s/10,000ms.
1865
Converting to s from ms by dividing by 1,000,
1866
and ns to ms by dividing by 1,000,000. */
1867
block_time = ((retry_interval
1868
- ((intmax_t)waited_time.tv_sec * 1000))
1869
- ((intmax_t)waited_time.tv_nsec / 1000000));
1872
fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1876
if(block_time <= 0){
1877
ret = start_mandos_communication(mc->current_server->ip,
1878
mc->current_server->port,
1879
mc->current_server->if_index,
1880
mc->current_server->af, mc);
1882
avahi_simple_poll_quit(s);
1885
ret = clock_gettime(CLOCK_MONOTONIC,
1886
&mc->current_server->last_seen);
1888
perror_plus("clock_gettime");
1891
mc->current_server = mc->current_server->next;
1892
block_time = 0; /* Call avahi to find new Mandos
1893
servers, but don't block */
1896
ret = avahi_simple_poll_iterate(s, (int)block_time);
1899
if(ret > 0 or errno != EINTR){
1900
return (ret != 1) ? ret : 0;
1906
__attribute__((nonnull))
1907
void run_network_hooks(const char *mode, const char *interface,
1909
struct dirent **direntries = NULL;
1910
if(hookdir_fd == -1){
1911
hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1913
if(hookdir_fd == -1){
1914
if(errno == ENOENT){
1916
fprintf_plus(stderr, "Network hook directory \"%s\" not"
1917
" found\n", hookdir);
1920
perror_plus("open");
1925
int numhooks = scandirat(hookdir_fd, ".", &direntries,
1926
runnable_hook, alphasort);
1928
perror_plus("scandir");
1931
struct dirent *direntry;
1933
int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1935
perror_plus("open(\"/dev/null\", O_RDONLY)");
1938
for(int i = 0; i < numhooks; i++){
1939
direntry = direntries[i];
1941
fprintf_plus(stderr, "Running network hook \"%s\"\n",
1944
pid_t hook_pid = fork();
1947
/* Raise privileges */
1948
errno = raise_privileges_permanently();
1950
perror_plus("Failed to raise privileges");
1957
perror_plus("setgid");
1960
/* Reset supplementary groups */
1962
ret = setgroups(0, NULL);
1964
perror_plus("setgroups");
1967
ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1969
perror_plus("setenv");
1972
ret = setenv("DEVICE", interface, 1);
1974
perror_plus("setenv");
1977
ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1979
perror_plus("setenv");
1982
ret = setenv("MODE", mode, 1);
1984
perror_plus("setenv");
1988
ret = asprintf(&delaystring, "%f", (double)delay);
1990
perror_plus("asprintf");
1993
ret = setenv("DELAY", delaystring, 1);
1996
perror_plus("setenv");
2000
if(connect_to != NULL){
2001
ret = setenv("CONNECT", connect_to, 1);
2003
perror_plus("setenv");
2007
int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
2011
perror_plus("openat");
2012
_exit(EXIT_FAILURE);
2014
if(close(hookdir_fd) == -1){
2015
perror_plus("close");
2016
_exit(EXIT_FAILURE);
2018
ret = dup2(devnull, STDIN_FILENO);
2020
perror_plus("dup2(devnull, STDIN_FILENO)");
2023
ret = close(devnull);
2025
perror_plus("close");
2028
ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2030
perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2033
if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2035
perror_plus("fexecve");
2036
_exit(EXIT_FAILURE);
2040
perror_plus("fork");
2045
if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2046
perror_plus("waitpid");
2050
if(WIFEXITED(status)){
2051
if(WEXITSTATUS(status) != 0){
2052
fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2053
" with status %d\n", direntry->d_name,
2054
WEXITSTATUS(status));
2058
} else if(WIFSIGNALED(status)){
2059
fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2060
" signal %d\n", direntry->d_name,
2065
fprintf_plus(stderr, "Warning: network hook \"%s\""
2066
" crashed\n", direntry->d_name);
2072
fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2078
if(close(hookdir_fd) == -1){
2079
perror_plus("close");
2086
__attribute__((nonnull, warn_unused_result))
2087
int bring_up_interface(const char *const interface,
2089
int old_errno = errno;
2091
struct ifreq network;
2092
unsigned int if_index = if_nametoindex(interface);
2094
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2104
if(not interface_is_up(interface)){
2106
int ioctl_errno = 0;
2107
if(not get_flags(interface, &network)){
2109
fprintf_plus(stderr, "Failed to get flags for interface "
2110
"\"%s\"\n", interface);
2114
network.ifr_flags |= IFF_UP; /* set flag */
2116
int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2119
perror_plus("socket");
2127
perror_plus("close");
2134
fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
2138
/* Raise privileges */
2139
ret_errno = raise_privileges();
2142
perror_plus("Failed to raise privileges");
2147
bool restore_loglevel = false;
2149
/* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
2150
messages about the network interface to mess up the prompt */
2151
ret_linux = klogctl(8, NULL, 5);
2152
if(ret_linux == -1){
2153
perror_plus("klogctl");
2155
restore_loglevel = true;
2158
#endif /* __linux__ */
2159
int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2160
ioctl_errno = errno;
2162
if(restore_loglevel){
2163
ret_linux = klogctl(7, NULL, 0);
2164
if(ret_linux == -1){
2165
perror_plus("klogctl");
2168
#endif /* __linux__ */
2170
/* If raise_privileges() succeeded above */
2172
/* Lower privileges */
2173
ret_errno = lower_privileges();
2176
perror_plus("Failed to lower privileges");
2180
/* Close the socket */
2183
perror_plus("close");
2186
if(ret_setflags == -1){
2187
errno = ioctl_errno;
2188
perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
2193
fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
2197
/* Sleep checking until interface is running.
2198
Check every 0.25s, up to total time of delay */
2199
for(int i=0; i < delay * 4; i++){
2200
if(interface_is_running(interface)){
2203
struct timespec sleeptime = { .tv_nsec = 250000000 };
2204
ret = nanosleep(&sleeptime, NULL);
2205
if(ret == -1 and errno != EINTR){
2206
perror_plus("nanosleep");
2214
__attribute__((nonnull, warn_unused_result))
2215
int take_down_interface(const char *const interface){
2216
int old_errno = errno;
2217
struct ifreq network;
2218
unsigned int if_index = if_nametoindex(interface);
2220
fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2224
if(interface_is_up(interface)){
2226
int ioctl_errno = 0;
2227
if(not get_flags(interface, &network) and debug){
2229
fprintf_plus(stderr, "Failed to get flags for interface "
2230
"\"%s\"\n", interface);
2234
network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2236
int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2239
perror_plus("socket");
2245
fprintf_plus(stderr, "Taking down interface \"%s\"\n",
2249
/* Raise privileges */
2250
ret_errno = raise_privileges();
2253
perror_plus("Failed to raise privileges");
2256
int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2257
ioctl_errno = errno;
2259
/* If raise_privileges() succeeded above */
2261
/* Lower privileges */
2262
ret_errno = lower_privileges();
2265
perror_plus("Failed to lower privileges");
2269
/* Close the socket */
2270
int ret = close(sd);
2272
perror_plus("close");
2275
if(ret_setflags == -1){
2276
errno = ioctl_errno;
2277
perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2282
fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
707
/* Combines file name and path and returns the malloced new
708
string. some sane checks could/should be added */
709
static const char *combinepath(const char *first, const char *second){
710
size_t f_len = strlen(first);
711
size_t s_len = strlen(second);
712
char *tmp = malloc(f_len + s_len + 2);
717
memcpy(tmp, first, f_len); /* Spurious warning */
721
memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
723
tmp[f_len + 1 + s_len] = '\0';
2290
728
int main(int argc, char *argv[]){
2291
mandos_context mc = { .server = NULL, .dh_bits = 0,
2292
.priority = "SECURE256:!CTYPE-X.509"
2293
":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2294
.current_server = NULL, .interfaces = NULL,
2295
.interfaces_size = 0 };
2296
AvahiSServiceBrowser *sb = NULL;
2301
int exitcode = EXIT_SUCCESS;
2302
char *interfaces_to_take_down = NULL;
2303
size_t interfaces_to_take_down_size = 0;
2304
char run_tempdir[] = "/run/tmp/mandosXXXXXX";
2305
char old_tempdir[] = "/tmp/mandosXXXXXX";
2306
char *tempdir = NULL;
2307
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2308
const char *seckey = PATHDIR "/" SECKEY;
2309
const char *pubkey = PATHDIR "/" PUBKEY;
2310
const char *dh_params_file = NULL;
2311
char *interfaces_hooks = NULL;
2313
bool gnutls_initialized = false;
2314
bool gpgme_initialized = false;
2316
double retry_interval = 10; /* 10s between trying a server and
2317
retrying the same server again */
2319
struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
2320
struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
2325
/* Lower any group privileges we might have, just to be safe */
2329
perror_plus("setgid");
2332
/* Lower user privileges (temporarily) */
2336
perror_plus("seteuid");
2344
struct argp_option options[] = {
2345
{ .name = "debug", .key = 128,
2346
.doc = "Debug mode", .group = 3 },
2347
{ .name = "connect", .key = 'c',
2348
.arg = "ADDRESS:PORT",
2349
.doc = "Connect directly to a specific Mandos server",
2351
{ .name = "interface", .key = 'i',
2353
.doc = "Network interface that will be used to search for"
2356
{ .name = "seckey", .key = 's',
2358
.doc = "OpenPGP secret key file base name",
2360
{ .name = "pubkey", .key = 'p',
2362
.doc = "OpenPGP public key file base name",
2364
{ .name = "dh-bits", .key = 129,
2366
.doc = "Bit length of the prime number used in the"
2367
" Diffie-Hellman key exchange",
2369
{ .name = "dh-params", .key = 134,
2371
.doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2372
" for the Diffie-Hellman key exchange",
2374
{ .name = "priority", .key = 130,
2376
.doc = "GnuTLS priority string for the TLS handshake",
2378
{ .name = "delay", .key = 131,
2380
.doc = "Maximum delay to wait for interface startup",
2382
{ .name = "retry", .key = 132,
2384
.doc = "Retry interval used when denied by the Mandos server",
2386
{ .name = "network-hook-dir", .key = 133,
2388
.doc = "Directory where network hooks are located",
2391
* These reproduce what we would get without ARGP_NO_HELP
2393
{ .name = "help", .key = '?',
2394
.doc = "Give this help list", .group = -1 },
2395
{ .name = "usage", .key = -3,
2396
.doc = "Give a short usage message", .group = -1 },
2397
{ .name = "version", .key = 'V',
2398
.doc = "Print program version", .group = -1 },
2402
error_t parse_opt(int key, char *arg,
2403
struct argp_state *state){
2406
case 128: /* --debug */
2409
case 'c': /* --connect */
2412
case 'i': /* --interface */
2413
ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
2416
argp_error(state, "%s", strerror(ret_errno));
2419
case 's': /* --seckey */
2422
case 'p': /* --pubkey */
2425
case 129: /* --dh-bits */
2427
tmpmax = strtoimax(arg, &tmp, 10);
2428
if(errno != 0 or tmp == arg or *tmp != '\0'
2429
or tmpmax != (typeof(mc.dh_bits))tmpmax){
2430
argp_error(state, "Bad number of DH bits");
2432
mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2434
case 134: /* --dh-params */
2435
dh_params_file = arg;
2437
case 130: /* --priority */
2440
case 131: /* --delay */
2442
delay = strtof(arg, &tmp);
2443
if(errno != 0 or tmp == arg or *tmp != '\0'){
2444
argp_error(state, "Bad delay");
2446
case 132: /* --retry */
2448
retry_interval = strtod(arg, &tmp);
2449
if(errno != 0 or tmp == arg or *tmp != '\0'
2450
or (retry_interval * 1000) > INT_MAX
2451
or retry_interval < 0){
2452
argp_error(state, "Bad retry interval");
2455
case 133: /* --network-hook-dir */
2459
* These reproduce what we would get without ARGP_NO_HELP
2461
case '?': /* --help */
2462
argp_state_help(state, state->out_stream,
2463
(ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
2464
& ~(unsigned int)ARGP_HELP_EXIT_OK);
2465
case -3: /* --usage */
2466
argp_state_help(state, state->out_stream,
2467
ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
2468
case 'V': /* --version */
2469
fprintf_plus(state->out_stream, "%s\n", argp_program_version);
2470
exit(argp_err_exit_status);
2473
return ARGP_ERR_UNKNOWN;
2478
struct argp argp = { .options = options, .parser = parse_opt,
2480
.doc = "Mandos client -- Get and decrypt"
2481
" passwords from a Mandos server" };
2482
ret_errno = argp_parse(&argp, argc, argv,
2483
ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2490
perror_plus("argp_parse");
2491
exitcode = EX_OSERR;
2494
exitcode = EX_USAGE;
2500
/* Work around Debian bug #633582:
2501
<https://bugs.debian.org/633582> */
2503
/* Re-raise privileges */
2504
ret = raise_privileges();
2507
perror_plus("Failed to raise privileges");
2511
if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2512
int seckey_fd = open(seckey, O_RDONLY);
2513
if(seckey_fd == -1){
2514
perror_plus("open");
2516
ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
2518
perror_plus("fstat");
2520
if(S_ISREG(st.st_mode)
2521
and st.st_uid == 0 and st.st_gid == 0){
2522
ret = fchown(seckey_fd, uid, gid);
2524
perror_plus("fchown");
2532
if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2533
int pubkey_fd = open(pubkey, O_RDONLY);
2534
if(pubkey_fd == -1){
2535
perror_plus("open");
2537
ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
2539
perror_plus("fstat");
2541
if(S_ISREG(st.st_mode)
2542
and st.st_uid == 0 and st.st_gid == 0){
2543
ret = fchown(pubkey_fd, uid, gid);
2545
perror_plus("fchown");
2553
if(dh_params_file != NULL
2554
and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2555
int dhparams_fd = open(dh_params_file, O_RDONLY);
2556
if(dhparams_fd == -1){
2557
perror_plus("open");
2559
ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2561
perror_plus("fstat");
2563
if(S_ISREG(st.st_mode)
2564
and st.st_uid == 0 and st.st_gid == 0){
2565
ret = fchown(dhparams_fd, uid, gid);
2567
perror_plus("fchown");
2575
/* Lower privileges */
2576
ret = lower_privileges();
2579
perror_plus("Failed to lower privileges");
2584
/* Remove invalid interface names (except "none") */
2586
char *interface = NULL;
2587
while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2589
if(strcmp(interface, "none") != 0
2590
and if_nametoindex(interface) == 0){
2591
if(interface[0] != '\0'){
2592
fprintf_plus(stderr, "Not using nonexisting interface"
2593
" \"%s\"\n", interface);
2595
argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2601
/* Run network hooks */
2603
if(mc.interfaces != NULL){
2604
interfaces_hooks = malloc(mc.interfaces_size);
2605
if(interfaces_hooks == NULL){
2606
perror_plus("malloc");
2609
memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2610
argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2612
run_network_hooks("start", interfaces_hooks != NULL ?
2613
interfaces_hooks : "", delay);
2617
avahi_set_log_function(empty_log);
2620
/* Initialize Avahi early so avahi_simple_poll_quit() can be called
2621
from the signal handler */
2622
/* Initialize the pseudo-RNG for Avahi */
2623
srand((unsigned int) time(NULL));
2624
simple_poll = avahi_simple_poll_new();
2625
if(simple_poll == NULL){
2626
fprintf_plus(stderr,
2627
"Avahi: Failed to create simple poll object.\n");
2628
exitcode = EX_UNAVAILABLE;
2632
sigemptyset(&sigterm_action.sa_mask);
2633
ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
2635
perror_plus("sigaddset");
2636
exitcode = EX_OSERR;
2639
ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
2641
perror_plus("sigaddset");
2642
exitcode = EX_OSERR;
2645
ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
2647
perror_plus("sigaddset");
2648
exitcode = EX_OSERR;
2651
/* Need to check if the handler is SIG_IGN before handling:
2652
| [[info:libc:Initial Signal Actions]] |
2653
| [[info:libc:Basic Signal Handling]] |
2655
ret = sigaction(SIGINT, NULL, &old_sigterm_action);
2657
perror_plus("sigaction");
2660
if(old_sigterm_action.sa_handler != SIG_IGN){
2661
ret = sigaction(SIGINT, &sigterm_action, NULL);
2663
perror_plus("sigaction");
2664
exitcode = EX_OSERR;
2668
ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
2670
perror_plus("sigaction");
2673
if(old_sigterm_action.sa_handler != SIG_IGN){
2674
ret = sigaction(SIGHUP, &sigterm_action, NULL);
2676
perror_plus("sigaction");
2677
exitcode = EX_OSERR;
2681
ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
2683
perror_plus("sigaction");
2686
if(old_sigterm_action.sa_handler != SIG_IGN){
2687
ret = sigaction(SIGTERM, &sigterm_action, NULL);
2689
perror_plus("sigaction");
2690
exitcode = EX_OSERR;
2695
/* If no interfaces were specified, make a list */
2696
if(mc.interfaces == NULL){
2697
struct dirent **direntries = NULL;
2698
/* Look for any good interfaces */
2699
ret = scandir(sys_class_net, &direntries, good_interface,
2702
/* Add all found interfaces to interfaces list */
2703
for(int i = 0; i < ret; ++i){
2704
ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2705
direntries[i]->d_name);
2708
perror_plus("argz_add");
2709
free(direntries[i]);
2713
fprintf_plus(stderr, "Will use interface \"%s\"\n",
2714
direntries[i]->d_name);
2716
free(direntries[i]);
2723
fprintf_plus(stderr, "Could not find a network interface\n");
729
AvahiSServiceBrowser *sb = NULL;
732
int exitcode = EXIT_SUCCESS;
733
const char *interface = "eth0";
734
struct ifreq network;
738
char *connect_to = NULL;
739
AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
740
const char *pubkeyfile = "pubkey.txt";
741
const char *seckeyfile = "seckey.txt";
742
mandos_context mc = { .simple_poll = NULL, .server = NULL,
743
.dh_bits = 1024, .priority = "SECURE256"};
746
struct argp_option options[] = {
747
{ .name = "debug", .key = 128,
748
.doc = "Debug mode", .group = 3 },
749
{ .name = "connect", .key = 'c',
751
.doc = "Connect directly to a sepcified mandos server",
753
{ .name = "interface", .key = 'i',
755
.doc = "Interface that Avahi will conntect through",
757
{ .name = "keydir", .key = 'd',
759
.doc = "Directory where the openpgp keyring is",
761
{ .name = "seckey", .key = 's',
763
.doc = "Secret openpgp key for gnutls authentication",
765
{ .name = "pubkey", .key = 'p',
767
.doc = "Public openpgp key for gnutls authentication",
769
{ .name = "dh-bits", .key = 129,
771
.doc = "dh-bits to use in gnutls communication",
773
{ .name = "priority", .key = 130,
775
.doc = "GNUTLS priority", .group = 1 },
780
error_t parse_opt (int key, char *arg,
781
struct argp_state *state) {
782
/* Get the INPUT argument from `argp_parse', which we know is
783
a pointer to our plugin list pointer. */
805
mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
820
return ARGP_ERR_UNKNOWN;
825
struct argp argp = { .options = options, .parser = parse_opt,
827
.doc = "Mandos client -- Get and decrypt"
828
" passwords from mandos server" };
829
argp_parse (&argp, argc, argv, 0, 0, NULL);
832
pubkeyfile = combinepath(keydir, pubkeyfile);
833
if (pubkeyfile == NULL){
834
perror("combinepath");
2724
835
exitcode = EXIT_FAILURE;
2729
/* Bring up interfaces which are down, and remove any "none"s */
2731
char *interface = NULL;
2732
while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2734
/* If interface name is "none", stop bringing up interfaces.
2735
Also remove all instances of "none" from the list */
2736
if(strcmp(interface, "none") == 0){
2737
argz_delete(&mc.interfaces, &mc.interfaces_size,
2740
while((interface = argz_next(mc.interfaces,
2741
mc.interfaces_size, interface))){
2742
if(strcmp(interface, "none") == 0){
2743
argz_delete(&mc.interfaces, &mc.interfaces_size,
2750
bool interface_was_up = interface_is_up(interface);
2751
errno = bring_up_interface(interface, delay);
2752
if(not interface_was_up){
2754
fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2755
" %s\n", interface, strerror(errno));
2757
errno = argz_add(&interfaces_to_take_down,
2758
&interfaces_to_take_down_size,
2761
perror_plus("argz_add");
2766
if(debug and (interfaces_to_take_down == NULL)){
2767
fprintf_plus(stderr, "No interfaces were brought up\n");
2771
/* If we only got one interface, explicitly use only that one */
2772
if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2774
fprintf_plus(stderr, "Using only interface \"%s\"\n",
2777
if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2784
ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2786
fprintf_plus(stderr, "init_gnutls_global failed\n");
2787
exitcode = EX_UNAVAILABLE;
2790
gnutls_initialized = true;
2797
/* Try /run/tmp before /tmp */
2798
tempdir = mkdtemp(run_tempdir);
2799
if(tempdir == NULL and errno == ENOENT){
2801
fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2802
run_tempdir, old_tempdir);
2804
tempdir = mkdtemp(old_tempdir);
2806
if(tempdir == NULL){
2807
perror_plus("mkdtemp");
2815
if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2816
fprintf_plus(stderr, "init_gpgme failed\n");
2817
exitcode = EX_UNAVAILABLE;
2820
gpgme_initialized = true;
2827
if(connect_to != NULL){
2828
/* Connect directly, do not use Zeroconf */
2829
/* (Mainly meant for debugging) */
2830
char *address = strrchr(connect_to, ':');
2832
if(address == NULL){
2833
fprintf_plus(stderr, "No colon in address\n");
2834
exitcode = EX_USAGE;
2844
tmpmax = strtoimax(address+1, &tmp, 10);
2845
if(errno != 0 or tmp == address+1 or *tmp != '\0'
2846
or tmpmax != (in_port_t)tmpmax){
2847
fprintf_plus(stderr, "Bad port number\n");
2848
exitcode = EX_USAGE;
2856
port = (in_port_t)tmpmax;
2858
/* Colon in address indicates IPv6 */
2860
if(strchr(connect_to, ':') != NULL){
2862
/* Accept [] around IPv6 address - see RFC 5952 */
2863
if(connect_to[0] == '[' and address[-1] == ']')
2871
address = connect_to;
2877
while(not quit_now){
2878
ret = start_mandos_communication(address, port, if_index, af,
2880
if(quit_now or ret == 0){
2884
fprintf_plus(stderr, "Retrying in %d seconds\n",
2885
(int)retry_interval);
2887
sleep((unsigned int)retry_interval);
2891
exitcode = EXIT_SUCCESS;
2902
AvahiServerConfig config;
2903
/* Do not publish any local Zeroconf records */
2904
avahi_server_config_init(&config);
2905
config.publish_hinfo = 0;
2906
config.publish_addresses = 0;
2907
config.publish_workstation = 0;
2908
config.publish_domain = 0;
2910
/* Allocate a new server */
2911
mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2912
&config, NULL, NULL, &ret);
2914
/* Free the Avahi configuration data */
2915
avahi_server_config_free(&config);
2918
/* Check if creating the Avahi server object succeeded */
2919
if(mc.server == NULL){
2920
fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2921
avahi_strerror(ret));
2922
exitcode = EX_UNAVAILABLE;
2930
/* Create the Avahi service browser */
2931
sb = avahi_s_service_browser_new(mc.server, if_index,
2932
AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2933
NULL, 0, browse_callback,
2936
fprintf_plus(stderr, "Failed to create service browser: %s\n",
2937
avahi_strerror(avahi_server_errno(mc.server)));
2938
exitcode = EX_UNAVAILABLE;
2946
/* Run the main loop */
2949
fprintf_plus(stderr, "Starting Avahi loop search\n");
2952
ret = avahi_loop_with_timeout(simple_poll,
2953
(int)(retry_interval * 1000), &mc);
2955
fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2956
(ret == 0) ? "successfully" : "with error");
839
seckeyfile = combinepath(keydir, seckeyfile);
840
if (seckeyfile == NULL){
841
perror("combinepath");
845
ret = init_gnutls_global(&mc, pubkeyfile, seckeyfile);
847
fprintf(stderr, "init_gnutls_global\n");
864
if_index = (AvahiIfIndex) if_nametoindex(interface);
866
fprintf(stderr, "No such interface: \"%s\"\n", interface);
870
if(connect_to != NULL){
871
/* Connect directly, do not use Zeroconf */
872
/* (Mainly meant for debugging) */
873
char *address = strrchr(connect_to, ':');
875
fprintf(stderr, "No colon in address\n");
876
exitcode = EXIT_FAILURE;
880
uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
882
perror("Bad port number");
883
exitcode = EXIT_FAILURE;
887
address = connect_to;
888
ret = start_mandos_communication(address, port, if_index, &mc);
890
exitcode = EXIT_FAILURE;
892
exitcode = EXIT_SUCCESS;
897
/* If the interface is down, bring it up */
899
sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
902
exitcode = EXIT_FAILURE;
905
strcpy(network.ifr_name, interface); /* Spurious warning */
906
ret = ioctl(sd, SIOCGIFFLAGS, &network);
908
perror("ioctl SIOCGIFFLAGS");
909
exitcode = EXIT_FAILURE;
912
if((network.ifr_flags & IFF_UP) == 0){
913
network.ifr_flags |= IFF_UP;
914
ret = ioctl(sd, SIOCSIFFLAGS, &network);
916
perror("ioctl SIOCSIFFLAGS");
917
exitcode = EXIT_FAILURE;
925
avahi_set_log_function(empty_log);
928
/* Initialize the pseudo-RNG for Avahi */
929
srand((unsigned int) time(NULL));
931
/* Allocate main Avahi loop object */
932
mc.simple_poll = avahi_simple_poll_new();
933
if (mc.simple_poll == NULL) {
934
fprintf(stderr, "Avahi: Failed to create simple poll"
936
exitcode = EXIT_FAILURE;
941
AvahiServerConfig config;
942
/* Do not publish any local Zeroconf records */
943
avahi_server_config_init(&config);
944
config.publish_hinfo = 0;
945
config.publish_addresses = 0;
946
config.publish_workstation = 0;
947
config.publish_domain = 0;
949
/* Allocate a new server */
950
mc.server = avahi_server_new(avahi_simple_poll_get
951
(mc.simple_poll), &config, NULL,
954
/* Free the Avahi configuration data */
955
avahi_server_config_free(&config);
958
/* Check if creating the Avahi server object succeeded */
959
if (mc.server == NULL) {
960
fprintf(stderr, "Failed to create Avahi server: %s\n",
961
avahi_strerror(error));
962
exitcode = EXIT_FAILURE;
966
/* Create the Avahi service browser */
967
sb = avahi_s_service_browser_new(mc.server, if_index,
969
"_mandos._tcp", NULL, 0,
970
browse_callback, &mc);
972
fprintf(stderr, "Failed to create service browser: %s\n",
973
avahi_strerror(avahi_server_errno(mc.server)));
974
exitcode = EXIT_FAILURE;
978
/* Run the main loop */
981
fprintf(stderr, "Starting Avahi loop search\n");
984
avahi_simple_poll_loop(mc.simple_poll);
2962
if(signal_received){
2963
fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
2964
argv[0], signal_received,
2965
strsignal(signal_received));
2967
fprintf_plus(stderr, "%s exiting\n", argv[0]);
2971
/* Cleanup things */
2972
free(mc.interfaces);
2975
avahi_s_service_browser_free(sb);
2977
if(mc.server != NULL)
2978
avahi_server_free(mc.server);
2980
if(simple_poll != NULL)
2981
avahi_simple_poll_free(simple_poll);
2983
if(gnutls_initialized){
2984
gnutls_certificate_free_credentials(mc.cred);
2985
gnutls_dh_params_deinit(mc.dh_params);
2988
if(gpgme_initialized){
2989
gpgme_release(mc.ctx);
2992
/* Cleans up the circular linked list of Mandos servers the client
2994
if(mc.current_server != NULL){
2995
mc.current_server->prev->next = NULL;
2996
while(mc.current_server != NULL){
2997
server *next = mc.current_server->next;
2999
#pragma GCC diagnostic push
3000
#pragma GCC diagnostic ignored "-Wcast-qual"
3002
free((char *)(mc.current_server->ip));
3004
#pragma GCC diagnostic pop
3006
free(mc.current_server);
3007
mc.current_server = next;
3011
/* Re-raise privileges */
3013
ret = raise_privileges();
3016
perror_plus("Failed to raise privileges");
3019
/* Run network hooks */
3020
run_network_hooks("stop", interfaces_hooks != NULL ?
3021
interfaces_hooks : "", delay);
3023
/* Take down the network interfaces which were brought up */
3025
char *interface = NULL;
3026
while((interface=argz_next(interfaces_to_take_down,
3027
interfaces_to_take_down_size,
3029
ret = take_down_interface(interface);
3032
perror_plus("Failed to take down interface");
3035
if(debug and (interfaces_to_take_down == NULL)){
3036
fprintf_plus(stderr, "No interfaces needed to be taken"
3042
ret = lower_privileges_permanently();
3045
perror_plus("Failed to lower privileges permanently");
3049
free(interfaces_to_take_down);
3050
free(interfaces_hooks);
3052
void clean_dir_at(int base, const char * const dirname,
3054
struct dirent **direntries = NULL;
3056
int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3062
perror_plus("open");
3064
int numentries = scandirat(dir_fd, ".", &direntries,
3065
notdotentries, alphasort);
3066
if(numentries >= 0){
3067
for(int i = 0; i < numentries; i++){
3069
fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3070
dirname, direntries[i]->d_name);
3072
dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3074
if(errno == EISDIR){
3075
dret = unlinkat(dir_fd, direntries[i]->d_name,
3078
if((dret == -1) and (errno == ENOTEMPTY)
3079
and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3080
== 0) and (level == 0)){
3081
/* Recurse only in this special case */
3082
clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3086
fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3087
direntries[i]->d_name, strerror(errno));
3090
free(direntries[i]);
3093
/* need to clean even if 0 because man page doesn't specify */
3095
if(numentries == -1){
3096
perror_plus("scandirat");
3098
dret = unlinkat(base, dirname, AT_REMOVEDIR);
3099
if(dret == -1 and errno != ENOENT){
3100
perror_plus("rmdir");
3103
perror_plus("scandirat");
3108
/* Removes the GPGME temp directory and all files inside */
3109
if(tempdir != NULL){
3110
clean_dir_at(-1, tempdir, 0);
3114
sigemptyset(&old_sigterm_action.sa_mask);
3115
old_sigterm_action.sa_handler = SIG_DFL;
3116
ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
3117
&old_sigterm_action,
3120
perror_plus("sigaction");
3123
ret = raise(signal_received);
3124
} while(ret != 0 and errno == EINTR);
3126
perror_plus("raise");
3129
TEMP_FAILURE_RETRY(pause());
989
fprintf(stderr, "%s exiting\n", argv[0]);
994
avahi_s_service_browser_free(sb);
996
if (mc.server != NULL)
997
avahi_server_free(mc.server);
999
if (mc.simple_poll != NULL)
1000
avahi_simple_poll_free(mc.simple_poll);