/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2013-12-31 16:02:18 UTC
  • Revision ID: teddy@recompile.se-20131231160218-plmmb0o0iifkd5l2
Specify BusName in systemd service file.

* mandos.service (BusName): Uncommented.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2013 Teddy Hogeborn
 
13
 * Copyright © 2008-2013 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
61
61
                                 */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
64
#include <errno.h>              /* perror(), errno,
66
65
                                   program_invocation_short_name */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
 
75
                                   setgid(), pause(), _exit() */
77
76
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
87
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
88
                                   WEXITSTATUS(), WTERMSIG() */
 
89
#include <grp.h>                /* setgroups() */
 
90
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
91
                                   argz_delete(), argz_append(),
 
92
                                   argz_stringify(), argz_add(),
 
93
                                   argz_count() */
90
94
 
91
95
#ifdef __linux__
92
96
#include <sys/klog.h>           /* klogctl() */
134
138
static const char sys_class_net[] = "/sys/class/net";
135
139
char *connect_to = NULL;
136
140
const char *hookdir = HOOKDIR;
 
141
uid_t uid = 65534;
 
142
gid_t gid = 65534;
137
143
 
138
144
/* Doubly linked list that need to be circularly linked when used */
139
145
typedef struct server{
140
146
  const char *ip;
141
 
  uint16_t port;
 
147
  in_port_t port;
142
148
  AvahiIfIndex if_index;
143
149
  int af;
144
150
  struct timespec last_seen;
148
154
 
149
155
/* Used for passing in values through the Avahi callback functions */
150
156
typedef struct {
151
 
  AvahiSimplePoll *simple_poll;
152
157
  AvahiServer *server;
153
158
  gnutls_certificate_credentials_t cred;
154
159
  unsigned int dh_bits;
156
161
  const char *priority;
157
162
  gpgme_ctx_t ctx;
158
163
  server *current_server;
 
164
  char *interfaces;
 
165
  size_t interfaces_size;
159
166
} mandos_context;
160
167
 
161
 
/* global context so signal handler can reach it*/
162
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
 
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
168
/* global so signal handler can reach it*/
 
169
AvahiSimplePoll *simple_poll;
166
170
 
167
171
sig_atomic_t quit_now = 0;
168
172
int signal_received = 0;
169
173
 
170
174
/* Function to use when printing errors */
171
175
void perror_plus(const char *print_text){
 
176
  int e = errno;
172
177
  fprintf(stderr, "Mandos plugin %s: ",
173
178
          program_invocation_short_name);
 
179
  errno = e;
174
180
  perror(print_text);
175
181
}
176
182
 
 
183
__attribute__((format (gnu_printf, 2, 3)))
177
184
int fprintf_plus(FILE *stream, const char *format, ...){
178
185
  va_list ap;
179
186
  va_start (ap, format);
180
187
  
181
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
182
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
188
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
189
                             program_invocation_short_name));
 
190
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
183
191
}
184
192
 
185
193
/*
200
208
}
201
209
 
202
210
/* Add server to set of servers to retry periodically */
203
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
204
 
               int af){
 
211
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
212
                int af, server **current_server){
205
213
  int ret;
206
214
  server *new_server = malloc(sizeof(server));
207
215
  if(new_server == NULL){
208
216
    perror_plus("malloc");
209
 
    return -1;
 
217
    return false;
210
218
  }
211
219
  *new_server = (server){ .ip = strdup(ip),
212
220
                          .port = port,
214
222
                          .af = af };
215
223
  if(new_server->ip == NULL){
216
224
    perror_plus("strdup");
217
 
    return -1;
 
225
    return false;
218
226
  }
219
227
  /* Special case of first server */
220
 
  if (mc.current_server == NULL){
 
228
  if(*current_server == NULL){
221
229
    new_server->next = new_server;
222
230
    new_server->prev = new_server;
223
 
    mc.current_server = new_server;
 
231
    *current_server = new_server;
224
232
  /* Place the new server last in the list */
225
233
  } else {
226
 
    new_server->next = mc.current_server;
227
 
    new_server->prev = mc.current_server->prev;
 
234
    new_server->next = *current_server;
 
235
    new_server->prev = (*current_server)->prev;
228
236
    new_server->prev->next = new_server;
229
 
    mc.current_server->prev = new_server;
 
237
    (*current_server)->prev = new_server;
230
238
  }
231
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
239
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
232
240
  if(ret == -1){
233
241
    perror_plus("clock_gettime");
234
 
    return -1;
 
242
    return false;
235
243
  }
236
 
  return 0;
 
244
  return true;
237
245
}
238
246
 
239
247
/* 
240
248
 * Initialize GPGME.
241
249
 */
242
250
static bool init_gpgme(const char *seckey, const char *pubkey,
243
 
                       const char *tempdir){
 
251
                       const char *tempdir, mandos_context *mc){
244
252
  gpgme_error_t rc;
245
253
  gpgme_engine_info_t engine_info;
246
254
  
247
 
  
248
255
  /*
249
256
   * Helper function to insert pub and seckey to the engine keyring.
250
257
   */
261
268
    
262
269
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
263
270
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
266
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
271
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
272
                   gpgme_strsource(rc), gpgme_strerror(rc));
267
273
      return false;
268
274
    }
269
275
    
270
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
276
    rc = gpgme_op_import(mc->ctx, pgp_data);
271
277
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf(stderr, "Mandos plugin mandos-client: "
273
 
              "bad gpgme_op_import: %s: %s\n",
274
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
275
280
      return false;
276
281
    }
277
282
    
284
289
  }
285
290
  
286
291
  if(debug){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "Initializing GPGME\n");
 
292
    fprintf_plus(stderr, "Initializing GPGME\n");
289
293
  }
290
294
  
291
295
  /* Init GPGME */
292
296
  gpgme_check_version(NULL);
293
297
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
294
298
  if(rc != GPG_ERR_NO_ERROR){
295
 
    fprintf(stderr, "Mandos plugin mandos-client: "
296
 
            "bad gpgme_engine_check_version: %s: %s\n",
297
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
299
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
300
                 gpgme_strsource(rc), gpgme_strerror(rc));
298
301
    return false;
299
302
  }
300
303
  
301
304
  /* Set GPGME home directory for the OpenPGP engine only */
302
305
  rc = gpgme_get_engine_info(&engine_info);
303
306
  if(rc != GPG_ERR_NO_ERROR){
304
 
    fprintf(stderr, "Mandos plugin mandos-client: "
305
 
            "bad gpgme_get_engine_info: %s: %s\n",
306
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
307
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
308
                 gpgme_strsource(rc), gpgme_strerror(rc));
307
309
    return false;
308
310
  }
309
311
  while(engine_info != NULL){
315
317
    engine_info = engine_info->next;
316
318
  }
317
319
  if(engine_info == NULL){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
320
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
321
                 tempdir);
320
322
    return false;
321
323
  }
322
324
  
323
325
  /* Create new GPGME "context" */
324
 
  rc = gpgme_new(&(mc.ctx));
 
326
  rc = gpgme_new(&(mc->ctx));
325
327
  if(rc != GPG_ERR_NO_ERROR){
326
 
    fprintf(stderr, "Mandos plugin mandos-client: "
327
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
328
 
            gpgme_strerror(rc));
 
328
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
329
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
330
                 gpgme_strerror(rc));
329
331
    return false;
330
332
  }
331
333
  
342
344
 */
343
345
static ssize_t pgp_packet_decrypt(const char *cryptotext,
344
346
                                  size_t crypto_size,
345
 
                                  char **plaintext){
 
347
                                  char **plaintext,
 
348
                                  mandos_context *mc){
346
349
  gpgme_data_t dh_crypto, dh_plain;
347
350
  gpgme_error_t rc;
348
351
  ssize_t ret;
350
353
  ssize_t plaintext_length = 0;
351
354
  
352
355
  if(debug){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "Trying to decrypt OpenPGP data\n");
 
356
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
355
357
  }
356
358
  
357
359
  /* Create new GPGME data buffer from memory cryptotext */
358
360
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
359
361
                               0);
360
362
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "Mandos plugin mandos-client: "
362
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
363
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
363
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
364
                 gpgme_strsource(rc), gpgme_strerror(rc));
364
365
    return -1;
365
366
  }
366
367
  
367
368
  /* Create new empty GPGME data buffer for the plaintext */
368
369
  rc = gpgme_data_new(&dh_plain);
369
370
  if(rc != GPG_ERR_NO_ERROR){
370
 
    fprintf(stderr, "Mandos plugin mandos-client: "
371
 
            "bad gpgme_data_new: %s: %s\n",
372
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
371
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
372
                 "bad gpgme_data_new: %s: %s\n",
 
373
                 gpgme_strsource(rc), gpgme_strerror(rc));
373
374
    gpgme_data_release(dh_crypto);
374
375
    return -1;
375
376
  }
376
377
  
377
378
  /* Decrypt data from the cryptotext data buffer to the plaintext
378
379
     data buffer */
379
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
380
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
380
381
  if(rc != GPG_ERR_NO_ERROR){
381
 
    fprintf(stderr, "Mandos plugin mandos-client: "
382
 
            "bad gpgme_op_decrypt: %s: %s\n",
383
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
382
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
383
                 gpgme_strsource(rc), gpgme_strerror(rc));
384
384
    plaintext_length = -1;
385
385
    if(debug){
386
386
      gpgme_decrypt_result_t result;
387
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
387
      result = gpgme_op_decrypt_result(mc->ctx);
388
388
      if(result == NULL){
389
 
        fprintf(stderr, "Mandos plugin mandos-client: "
390
 
                "gpgme_op_decrypt_result failed\n");
 
389
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
391
390
      } else {
392
 
        fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                "Unsupported algorithm: %s\n",
394
 
                result->unsupported_algorithm);
395
 
        fprintf(stderr, "Mandos plugin mandos-client: "
396
 
                "Wrong key usage: %u\n",
397
 
                result->wrong_key_usage);
 
391
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
392
                     result->unsupported_algorithm);
 
393
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
394
                     result->wrong_key_usage);
398
395
        if(result->file_name != NULL){
399
 
          fprintf(stderr, "Mandos plugin mandos-client: "
400
 
                  "File name: %s\n", result->file_name);
 
396
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
401
397
        }
402
398
        gpgme_recipient_t recipient;
403
399
        recipient = result->recipients;
404
400
        while(recipient != NULL){
405
 
          fprintf(stderr, "Mandos plugin mandos-client: "
406
 
                  "Public key algorithm: %s\n",
407
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
408
 
          fprintf(stderr, "Mandos plugin mandos-client: "
409
 
                  "Key ID: %s\n", recipient->keyid);
410
 
          fprintf(stderr, "Mandos plugin mandos-client: "
411
 
                  "Secret key available: %s\n",
412
 
                  recipient->status == GPG_ERR_NO_SECKEY
413
 
                  ? "No" : "Yes");
 
401
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
402
                       gpgme_pubkey_algo_name
 
403
                       (recipient->pubkey_algo));
 
404
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
405
          fprintf_plus(stderr, "Secret key available: %s\n",
 
406
                       recipient->status == GPG_ERR_NO_SECKEY
 
407
                       ? "No" : "Yes");
414
408
          recipient = recipient->next;
415
409
        }
416
410
      }
419
413
  }
420
414
  
421
415
  if(debug){
422
 
    fprintf(stderr, "Mandos plugin mandos-client: "
423
 
            "Decryption of OpenPGP data succeeded\n");
 
416
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
424
417
  }
425
418
  
426
419
  /* Seek back to the beginning of the GPGME plaintext data buffer */
457
450
  }
458
451
  
459
452
  if(debug){
460
 
    fprintf(stderr, "Mandos plugin mandos-client: "
461
 
            "Decrypted password is: ");
 
453
    fprintf_plus(stderr, "Decrypted password is: ");
462
454
    for(ssize_t i = 0; i < plaintext_length; i++){
463
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
464
456
    }
476
468
}
477
469
 
478
470
static const char * safer_gnutls_strerror(int value){
479
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
480
 
                                               -Wunreachable-code */
 
471
  const char *ret = gnutls_strerror(value);
481
472
  if(ret == NULL)
482
473
    ret = "(unknown)";
483
474
  return ret;
486
477
/* GnuTLS log function callback */
487
478
static void debuggnutls(__attribute__((unused)) int level,
488
479
                        const char* string){
489
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
480
  fprintf_plus(stderr, "GnuTLS: %s", string);
490
481
}
491
482
 
492
483
static int init_gnutls_global(const char *pubkeyfilename,
493
 
                              const char *seckeyfilename){
 
484
                              const char *seckeyfilename,
 
485
                              mandos_context *mc){
494
486
  int ret;
495
487
  
496
488
  if(debug){
497
 
    fprintf(stderr, "Mandos plugin mandos-client: "
498
 
            "Initializing GnuTLS\n");
 
489
    fprintf_plus(stderr, "Initializing GnuTLS\n");
499
490
  }
500
491
  
501
492
  ret = gnutls_global_init();
502
493
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf(stderr, "Mandos plugin mandos-client: "
504
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
494
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
495
                 safer_gnutls_strerror(ret));
505
496
    return -1;
506
497
  }
507
498
  
514
505
  }
515
506
  
516
507
  /* OpenPGP credentials */
517
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
508
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
518
509
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Mandos plugin mandos-client: "
520
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
510
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
511
                 safer_gnutls_strerror(ret));
521
512
    gnutls_global_deinit();
522
513
    return -1;
523
514
  }
524
515
  
525
516
  if(debug){
526
 
    fprintf(stderr, "Mandos plugin mandos-client: "
527
 
            "Attempting to use OpenPGP public key %s and"
528
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
529
 
            seckeyfilename);
 
517
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
518
                 " secret key %s as GnuTLS credentials\n",
 
519
                 pubkeyfilename,
 
520
                 seckeyfilename);
530
521
  }
531
522
  
532
523
  ret = gnutls_certificate_set_openpgp_key_file
533
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
524
    (mc->cred, pubkeyfilename, seckeyfilename,
534
525
     GNUTLS_OPENPGP_FMT_BASE64);
535
526
  if(ret != GNUTLS_E_SUCCESS){
536
 
    fprintf(stderr,
537
 
            "Mandos plugin mandos-client: "
538
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
539
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
527
    fprintf_plus(stderr,
 
528
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
529
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
530
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
531
                 safer_gnutls_strerror(ret));
542
532
    goto globalfail;
543
533
  }
544
534
  
545
535
  /* GnuTLS server initialization */
546
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
536
  ret = gnutls_dh_params_init(&mc->dh_params);
547
537
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Mandos plugin mandos-client: "
549
 
            "Error in GnuTLS DH parameter initialization:"
550
 
            " %s\n", safer_gnutls_strerror(ret));
 
538
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
539
                 " initialization: %s\n",
 
540
                 safer_gnutls_strerror(ret));
551
541
    goto globalfail;
552
542
  }
553
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
543
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
554
544
  if(ret != GNUTLS_E_SUCCESS){
555
 
    fprintf(stderr, "Mandos plugin mandos-client: "
556
 
            "Error in GnuTLS prime generation: %s\n",
557
 
            safer_gnutls_strerror(ret));
 
545
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
546
                 safer_gnutls_strerror(ret));
558
547
    goto globalfail;
559
548
  }
560
549
  
561
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
550
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
562
551
  
563
552
  return 0;
564
553
  
565
554
 globalfail:
566
555
  
567
 
  gnutls_certificate_free_credentials(mc.cred);
 
556
  gnutls_certificate_free_credentials(mc->cred);
568
557
  gnutls_global_deinit();
569
 
  gnutls_dh_params_deinit(mc.dh_params);
 
558
  gnutls_dh_params_deinit(mc->dh_params);
570
559
  return -1;
571
560
}
572
561
 
573
 
static int init_gnutls_session(gnutls_session_t *session){
 
562
static int init_gnutls_session(gnutls_session_t *session,
 
563
                               mandos_context *mc){
574
564
  int ret;
575
565
  /* GnuTLS session creation */
576
566
  do {
580
570
    }
581
571
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
582
572
  if(ret != GNUTLS_E_SUCCESS){
583
 
    fprintf(stderr, "Mandos plugin mandos-client: "
584
 
            "Error in GnuTLS session initialization: %s\n",
585
 
            safer_gnutls_strerror(ret));
 
573
    fprintf_plus(stderr,
 
574
                 "Error in GnuTLS session initialization: %s\n",
 
575
                 safer_gnutls_strerror(ret));
586
576
  }
587
577
  
588
578
  {
589
579
    const char *err;
590
580
    do {
591
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
581
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
592
582
      if(quit_now){
593
583
        gnutls_deinit(*session);
594
584
        return -1;
595
585
      }
596
586
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
597
587
    if(ret != GNUTLS_E_SUCCESS){
598
 
      fprintf(stderr, "Mandos plugin mandos-client: "
599
 
              "Syntax error at: %s\n", err);
600
 
      fprintf(stderr, "Mandos plugin mandos-client: "
601
 
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
588
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
589
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
590
                   safer_gnutls_strerror(ret));
602
591
      gnutls_deinit(*session);
603
592
      return -1;
604
593
    }
606
595
  
607
596
  do {
608
597
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
609
 
                                 mc.cred);
 
598
                                 mc->cred);
610
599
    if(quit_now){
611
600
      gnutls_deinit(*session);
612
601
      return -1;
613
602
    }
614
603
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
615
604
  if(ret != GNUTLS_E_SUCCESS){
616
 
    fprintf(stderr, "Mandos plugin mandos-client: "
617
 
            "Error setting GnuTLS credentials: %s\n",
618
 
            safer_gnutls_strerror(ret));
 
605
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
606
                 safer_gnutls_strerror(ret));
619
607
    gnutls_deinit(*session);
620
608
    return -1;
621
609
  }
623
611
  /* ignore client certificate if any. */
624
612
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
625
613
  
626
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
614
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
627
615
  
628
616
  return 0;
629
617
}
633
621
                      __attribute__((unused)) const char *txt){}
634
622
 
635
623
/* Called when a Mandos server is found */
636
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
624
static int start_mandos_communication(const char *ip, in_port_t port,
637
625
                                      AvahiIfIndex if_index,
638
 
                                      int af){
 
626
                                      int af, mandos_context *mc){
639
627
  int ret, tcp_sd = -1;
640
628
  ssize_t sret;
641
629
  union {
666
654
    pf = PF_INET;
667
655
    break;
668
656
  default:
669
 
    fprintf(stderr, "Mandos plugin mandos-client: "
670
 
            "Bad address family: %d\n", af);
 
657
    fprintf_plus(stderr, "Bad address family: %d\n", af);
671
658
    errno = EINVAL;
672
659
    return -1;
673
660
  }
674
661
  
675
 
  ret = init_gnutls_session(&session);
 
662
  /* If the interface is specified and we have a list of interfaces */
 
663
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
664
    /* Check if the interface is one of the interfaces we are using */
 
665
    bool match = false;
 
666
    {
 
667
      char *interface = NULL;
 
668
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
669
                                 interface))){
 
670
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
671
          match = true;
 
672
          break;
 
673
        }
 
674
      }
 
675
    }
 
676
    if(not match){
 
677
      /* This interface does not match any in the list, so we don't
 
678
         connect to the server */
 
679
      if(debug){
 
680
        char interface[IF_NAMESIZE];
 
681
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
682
          perror_plus("if_indextoname");
 
683
        } else {
 
684
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
685
                       " \"%s\"\n",
 
686
                       if_indextoname((unsigned int)if_index,
 
687
                                      interface));
 
688
        }
 
689
      }
 
690
      return -1;
 
691
    }
 
692
  }
 
693
  
 
694
  ret = init_gnutls_session(&session, mc);
676
695
  if(ret != 0){
677
696
    return -1;
678
697
  }
679
698
  
680
699
  if(debug){
681
 
    fprintf(stderr, "Mandos plugin mandos-client: "
682
 
            "Setting up a TCP connection to %s, port %" PRIu16
683
 
            "\n", ip, port);
 
700
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
701
                 PRIuMAX "\n", ip, (uintmax_t)port);
684
702
  }
685
703
  
686
704
  tcp_sd = socket(pf, SOCK_STREAM, 0);
712
730
  }
713
731
  if(ret == 0){
714
732
    int e = errno;
715
 
    fprintf(stderr, "Mandos plugin mandos-client: "
716
 
            "Bad address: %s\n", ip);
 
733
    fprintf_plus(stderr, "Bad address: %s\n", ip);
717
734
    errno = e;
718
735
    goto mandos_end;
719
736
  }
720
737
  if(af == AF_INET6){
721
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
722
 
                                       -Wconversion and
723
 
                                       -Wunreachable-code */
724
 
    
 
738
    to.in6.sin6_port = htons(port);    
 
739
#ifdef __GNUC__
 
740
#pragma GCC diagnostic push
 
741
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
 
742
#endif
725
743
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
726
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
727
 
                                -Wunreachable-code*/
 
744
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
 
745
#ifdef __GNUC__
 
746
#pragma GCC diagnostic pop
 
747
#endif
728
748
      if(if_index == AVAHI_IF_UNSPEC){
729
 
        fprintf(stderr, "Mandos plugin mandos-client: "
730
 
                "An IPv6 link-local address is incomplete"
731
 
                " without a network interface\n");
 
749
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
750
                     " incomplete without a network interface\n");
732
751
        errno = EINVAL;
733
752
        goto mandos_end;
734
753
      }
736
755
      to.in6.sin6_scope_id = (uint32_t)if_index;
737
756
    }
738
757
  } else {
739
 
    to.in.sin_port = htons(port); /* Spurious warnings from
740
 
                                     -Wconversion and
741
 
                                     -Wunreachable-code */
 
758
    to.in.sin_port = htons(port);
742
759
  }
743
760
  
744
761
  if(quit_now){
752
769
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
753
770
        perror_plus("if_indextoname");
754
771
      } else {
755
 
        fprintf(stderr, "Mandos plugin mandos-client: "
756
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
757
 
                ip, interface, port);
 
772
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
773
                     "\n", ip, interface, (uintmax_t)port);
758
774
      }
759
775
    } else {
760
 
      fprintf(stderr, "Mandos plugin mandos-client: "
761
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
776
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
777
                   ip, (uintmax_t)port);
762
778
    }
763
779
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
764
780
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
774
790
      perror_plus("inet_ntop");
775
791
    } else {
776
792
      if(strcmp(addrstr, ip) != 0){
777
 
        fprintf(stderr, "Mandos plugin mandos-client: "
778
 
                "Canonical address form: %s\n", addrstr);
 
793
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
779
794
      }
780
795
    }
781
796
  }
835
850
  }
836
851
  
837
852
  if(debug){
838
 
    fprintf(stderr, "Mandos plugin mandos-client: "
839
 
            "Establishing TLS session with %s\n", ip);
 
853
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
840
854
  }
841
855
  
842
856
  if(quit_now){
844
858
    goto mandos_end;
845
859
  }
846
860
  
847
 
  /* Spurious warning from -Wint-to-pointer-cast */
848
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
861
  /* This casting via intptr_t is to eliminate warning about casting
 
862
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
863
     function "set-session-transport-fd!" does it. */
 
864
  gnutls_transport_set_ptr(session,
 
865
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
849
866
  
850
867
  if(quit_now){
851
868
    errno = EINTR;
862
879
  
863
880
  if(ret != GNUTLS_E_SUCCESS){
864
881
    if(debug){
865
 
      fprintf(stderr, "Mandos plugin mandos-client: "
866
 
              "*** GnuTLS Handshake failed ***\n");
 
882
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
867
883
      gnutls_perror(ret);
868
884
    }
869
885
    errno = EPROTO;
873
889
  /* Read OpenPGP packet that contains the wanted password */
874
890
  
875
891
  if(debug){
876
 
    fprintf(stderr, "Mandos plugin mandos-client: "
877
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
892
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
893
                 " %s\n", ip);
878
894
  }
879
895
  
880
896
  while(true){
918
934
          }
919
935
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
920
936
        if(ret < 0){
921
 
          fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
937
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
938
                       "***\n");
923
939
          gnutls_perror(ret);
924
940
          errno = EPROTO;
925
941
          goto mandos_end;
926
942
        }
927
943
        break;
928
944
      default:
929
 
        fprintf(stderr, "Mandos plugin mandos-client: "
930
 
                "Unknown error while reading data from"
931
 
                " encrypted session with Mandos server\n");
 
945
        fprintf_plus(stderr, "Unknown error while reading data from"
 
946
                     " encrypted session with Mandos server\n");
932
947
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
933
948
        errno = EIO;
934
949
        goto mandos_end;
939
954
  }
940
955
  
941
956
  if(debug){
942
 
    fprintf(stderr, "Mandos plugin mandos-client: "
943
 
            "Closing TLS session\n");
 
957
    fprintf_plus(stderr, "Closing TLS session\n");
944
958
  }
945
959
  
946
960
  if(quit_now){
959
973
  if(buffer_length > 0){
960
974
    ssize_t decrypted_buffer_size;
961
975
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
962
 
                                               &decrypted_buffer);
 
976
                                               &decrypted_buffer, mc);
963
977
    if(decrypted_buffer_size >= 0){
964
978
      
965
979
      written = 0;
975
989
        if(ret == 0 and ferror(stdout)){
976
990
          int e = errno;
977
991
          if(debug){
978
 
            fprintf(stderr, "Mandos plugin mandos-client: "
979
 
                    "Error writing encrypted data: %s\n",
980
 
                    strerror(errno));
 
992
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
993
                         strerror(errno));
981
994
          }
982
995
          errno = e;
983
996
          goto mandos_end;
1027
1040
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1028
1041
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1029
1042
                             flags,
1030
 
                             AVAHI_GCC_UNUSED void* userdata){
1031
 
  assert(r);
 
1043
                             void* mc){
 
1044
  if(r == NULL){
 
1045
    return;
 
1046
  }
1032
1047
  
1033
1048
  /* Called whenever a service has been resolved successfully or
1034
1049
     timed out */
1040
1055
  switch(event){
1041
1056
  default:
1042
1057
  case AVAHI_RESOLVER_FAILURE:
1043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1044
 
            "(Avahi Resolver) Failed to resolve service '%s'"
1045
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1046
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1058
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1059
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1060
                 domain,
 
1061
                 avahi_strerror(avahi_server_errno
 
1062
                                (((mandos_context*)mc)->server)));
1047
1063
    break;
1048
1064
    
1049
1065
  case AVAHI_RESOLVER_FOUND:
1051
1067
      char ip[AVAHI_ADDRESS_STR_MAX];
1052
1068
      avahi_address_snprint(ip, sizeof(ip), address);
1053
1069
      if(debug){
1054
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1055
 
                "Mandos server \"%s\" found on %s (%s, %"
1056
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1057
 
                ip, (intmax_t)interface, port);
 
1070
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1071
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1072
                     host_name, ip, (intmax_t)interface, port);
1058
1073
      }
1059
 
      int ret = start_mandos_communication(ip, port, interface,
1060
 
                                           avahi_proto_to_af(proto));
 
1074
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1075
                                           interface,
 
1076
                                           avahi_proto_to_af(proto),
 
1077
                                           mc);
1061
1078
      if(ret == 0){
1062
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1079
        avahi_simple_poll_quit(simple_poll);
1063
1080
      } else {
1064
 
        ret = add_server(ip, port, interface,
1065
 
                         avahi_proto_to_af(proto));
 
1081
        if(not add_server(ip, (in_port_t)port, interface,
 
1082
                          avahi_proto_to_af(proto),
 
1083
                          &((mandos_context*)mc)->current_server)){
 
1084
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1085
                       " list\n", name);
 
1086
        }
1066
1087
      }
1067
1088
    }
1068
1089
  }
1078
1099
                            const char *domain,
1079
1100
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1080
1101
                            flags,
1081
 
                            AVAHI_GCC_UNUSED void* userdata){
1082
 
  assert(b);
 
1102
                            void* mc){
 
1103
  if(b == NULL){
 
1104
    return;
 
1105
  }
1083
1106
  
1084
1107
  /* Called whenever a new services becomes available on the LAN or
1085
1108
     is removed from the LAN */
1092
1115
  default:
1093
1116
  case AVAHI_BROWSER_FAILURE:
1094
1117
    
1095
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1096
 
            "(Avahi browser) %s\n",
1097
 
            avahi_strerror(avahi_server_errno(mc.server)));
1098
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1118
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1119
                 avahi_strerror(avahi_server_errno
 
1120
                                (((mandos_context*)mc)->server)));
 
1121
    avahi_simple_poll_quit(simple_poll);
1099
1122
    return;
1100
1123
    
1101
1124
  case AVAHI_BROWSER_NEW:
1104
1127
       the callback function is called the Avahi server will free the
1105
1128
       resolver for us. */
1106
1129
    
1107
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1108
 
                                    name, type, domain, protocol, 0,
1109
 
                                    resolve_callback, NULL) == NULL)
1110
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1111
 
              "Avahi: Failed to resolve service '%s': %s\n",
1112
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1130
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1131
                                    interface, protocol, name, type,
 
1132
                                    domain, protocol, 0,
 
1133
                                    resolve_callback, mc) == NULL)
 
1134
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1135
                   " %s\n", name,
 
1136
                   avahi_strerror(avahi_server_errno
 
1137
                                  (((mandos_context*)mc)->server)));
1113
1138
    break;
1114
1139
    
1115
1140
  case AVAHI_BROWSER_REMOVE:
1118
1143
  case AVAHI_BROWSER_ALL_FOR_NOW:
1119
1144
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1120
1145
    if(debug){
1121
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1122
 
              "No Mandos server found, still searching...\n");
 
1146
      fprintf_plus(stderr, "No Mandos server found, still"
 
1147
                   " searching...\n");
1123
1148
    }
1124
1149
    break;
1125
1150
  }
1134
1159
  signal_received = sig;
1135
1160
  int old_errno = errno;
1136
1161
  /* set main loop to exit */
1137
 
  if(mc.simple_poll != NULL){
1138
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1162
  if(simple_poll != NULL){
 
1163
    avahi_simple_poll_quit(simple_poll);
1139
1164
  }
1140
1165
  errno = old_errno;
1141
1166
}
1142
1167
 
1143
1168
bool get_flags(const char *ifname, struct ifreq *ifr){
1144
1169
  int ret;
 
1170
  error_t ret_errno;
1145
1171
  
1146
1172
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1147
1173
  if(s < 0){
 
1174
    ret_errno = errno;
1148
1175
    perror_plus("socket");
 
1176
    errno = ret_errno;
1149
1177
    return false;
1150
1178
  }
1151
1179
  strcpy(ifr->ifr_name, ifname);
1152
1180
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1153
1181
  if(ret == -1){
1154
1182
    if(debug){
 
1183
      ret_errno = errno;
1155
1184
      perror_plus("ioctl SIOCGIFFLAGS");
 
1185
      errno = ret_errno;
1156
1186
    }
1157
1187
    return false;
1158
1188
  }
1164
1194
  /* Reject the loopback device */
1165
1195
  if(ifr->ifr_flags & IFF_LOOPBACK){
1166
1196
    if(debug){
1167
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1168
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1197
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1198
                   ifname);
1169
1199
    }
1170
1200
    return false;
1171
1201
  }
1172
1202
  /* Accept point-to-point devices only if connect_to is specified */
1173
1203
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1174
1204
    if(debug){
1175
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1176
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1205
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1206
                   " \"%s\"\n", ifname);
1177
1207
    }
1178
1208
    return true;
1179
1209
  }
1180
1210
  /* Otherwise, reject non-broadcast-capable devices */
1181
1211
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1182
1212
    if(debug){
1183
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1184
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1213
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1214
                   " \"%s\"\n", ifname);
1185
1215
    }
1186
1216
    return false;
1187
1217
  }
1188
1218
  /* Reject non-ARP interfaces (including dummy interfaces) */
1189
1219
  if(ifr->ifr_flags & IFF_NOARP){
1190
1220
    if(debug){
1191
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1192
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1221
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1222
                   ifname);
1193
1223
    }
1194
1224
    return false;
1195
1225
  }
1196
1226
  
1197
1227
  /* Accept this device */
1198
1228
  if(debug){
1199
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1200
 
            "Interface \"%s\" is good\n", ifname);
 
1229
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1201
1230
  }
1202
1231
  return true;
1203
1232
}
1215
1244
  struct ifreq ifr;
1216
1245
  if(not get_flags(if_entry->d_name, &ifr)){
1217
1246
    if(debug){
1218
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1219
 
              "Failed to get flags for interface \"%s\"\n",
1220
 
              if_entry->d_name);
1221
 
    }
1222
 
    return 0;
1223
 
  }
1224
 
  
1225
 
  if(not good_flags(if_entry->d_name, &ifr)){
1226
 
    return 0;
1227
 
  }
1228
 
  return 1;
1229
 
}
1230
 
 
1231
 
/* 
1232
 
 * This function determines if a directory entry in /sys/class/net
1233
 
 * corresponds to an acceptable network device which is up.
1234
 
 * (This function is passed to scandir(3) as a filter function.)
1235
 
 */
1236
 
int up_interface(const struct dirent *if_entry){
1237
 
  if(if_entry->d_name[0] == '.'){
1238
 
    return 0;
1239
 
  }
1240
 
  
1241
 
  struct ifreq ifr;
1242
 
  if(not get_flags(if_entry->d_name, &ifr)){
1243
 
    if(debug){
1244
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1245
 
              "Failed to get flags for interface \"%s\"\n",
1246
 
              if_entry->d_name);
1247
 
    }
1248
 
    return 0;
1249
 
  }
1250
 
  
1251
 
  /* Reject down interfaces */
1252
 
  if(not (ifr.ifr_flags & IFF_UP)){
1253
 
    if(debug){
1254
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1255
 
              "Rejecting down interface \"%s\"\n",
1256
 
              if_entry->d_name);
1257
 
    }
1258
 
    return 0;
1259
 
  }
1260
 
  
1261
 
  /* Reject non-running interfaces */
1262
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1263
 
    if(debug){
1264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1265
 
              "Rejecting non-running interface \"%s\"\n",
1266
 
              if_entry->d_name);
1267
 
    }
1268
 
    return 0;
1269
 
  }
1270
 
  
1271
 
  if(not good_flags(if_entry->d_name, &ifr)){
1272
 
    return 0;
1273
 
  }
1274
 
  return 1;
 
1247
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1248
                   "\"%s\"\n", if_entry->d_name);
 
1249
    }
 
1250
    return 0;
 
1251
  }
 
1252
  
 
1253
  if(not good_flags(if_entry->d_name, &ifr)){
 
1254
    return 0;
 
1255
  }
 
1256
  return 1;
 
1257
}
 
1258
 
 
1259
/* 
 
1260
 * This function determines if a network interface is up.
 
1261
 */
 
1262
bool interface_is_up(const char *interface){
 
1263
  struct ifreq ifr;
 
1264
  if(not get_flags(interface, &ifr)){
 
1265
    if(debug){
 
1266
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1267
                   "\"%s\"\n", interface);
 
1268
    }
 
1269
    return false;
 
1270
  }
 
1271
  
 
1272
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1273
}
 
1274
 
 
1275
/* 
 
1276
 * This function determines if a network interface is running
 
1277
 */
 
1278
bool interface_is_running(const char *interface){
 
1279
  struct ifreq ifr;
 
1280
  if(not get_flags(interface, &ifr)){
 
1281
    if(debug){
 
1282
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1283
                   "\"%s\"\n", interface);
 
1284
    }
 
1285
    return false;
 
1286
  }
 
1287
  
 
1288
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1275
1289
}
1276
1290
 
1277
1291
int notdotentries(const struct dirent *direntry){
1303
1317
  if((direntry->d_name)[sret] != '\0'){
1304
1318
    /* Contains non-allowed characters */
1305
1319
    if(debug){
1306
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1307
 
              "Ignoring hook \"%s\" with bad name\n",
1308
 
              direntry->d_name);
 
1320
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1321
                   direntry->d_name);
1309
1322
    }
1310
1323
    return 0;
1311
1324
  }
1327
1340
  if(not (S_ISREG(st.st_mode))){
1328
1341
    /* Not a regular file */
1329
1342
    if(debug){
1330
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1331
 
              "Ignoring hook \"%s\" - not a file\n",
1332
 
              direntry->d_name);
 
1343
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1344
                   direntry->d_name);
1333
1345
    }
1334
1346
    return 0;
1335
1347
  }
1336
1348
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1337
1349
    /* Not executable */
1338
1350
    if(debug){
1339
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1340
 
              "Ignoring hook \"%s\" - not executable\n",
1341
 
              direntry->d_name);
 
1351
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1352
                   direntry->d_name);
1342
1353
    }
1343
1354
    return 0;
1344
1355
  }
 
1356
  if(debug){
 
1357
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1358
                 direntry->d_name);
 
1359
  }
1345
1360
  return 1;
1346
1361
}
1347
1362
 
1348
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1363
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1364
                            mandos_context *mc){
1349
1365
  int ret;
1350
1366
  struct timespec now;
1351
1367
  struct timespec waited_time;
1352
1368
  intmax_t block_time;
1353
1369
  
1354
1370
  while(true){
1355
 
    if(mc.current_server == NULL){
 
1371
    if(mc->current_server == NULL){
1356
1372
      if (debug){
1357
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1358
 
                "Wait until first server is found. No timeout!\n");
 
1373
        fprintf_plus(stderr, "Wait until first server is found."
 
1374
                     " No timeout!\n");
1359
1375
      }
1360
1376
      ret = avahi_simple_poll_iterate(s, -1);
1361
1377
    } else {
1362
1378
      if (debug){
1363
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1364
 
                "Check current_server if we should run it,"
1365
 
                " or wait\n");
 
1379
        fprintf_plus(stderr, "Check current_server if we should run"
 
1380
                     " it, or wait\n");
1366
1381
      }
1367
1382
      /* the current time */
1368
1383
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1373
1388
      /* Calculating in ms how long time between now and server
1374
1389
         who we visted longest time ago. Now - last seen.  */
1375
1390
      waited_time.tv_sec = (now.tv_sec
1376
 
                            - mc.current_server->last_seen.tv_sec);
 
1391
                            - mc->current_server->last_seen.tv_sec);
1377
1392
      waited_time.tv_nsec = (now.tv_nsec
1378
 
                             - mc.current_server->last_seen.tv_nsec);
 
1393
                             - mc->current_server->last_seen.tv_nsec);
1379
1394
      /* total time is 10s/10,000ms.
1380
1395
         Converting to s from ms by dividing by 1,000,
1381
1396
         and ns to ms by dividing by 1,000,000. */
1384
1399
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1385
1400
      
1386
1401
      if (debug){
1387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1388
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1402
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1403
                     block_time);
1389
1404
      }
1390
1405
      
1391
1406
      if(block_time <= 0){
1392
 
        ret = start_mandos_communication(mc.current_server->ip,
1393
 
                                         mc.current_server->port,
1394
 
                                         mc.current_server->if_index,
1395
 
                                         mc.current_server->af);
 
1407
        ret = start_mandos_communication(mc->current_server->ip,
 
1408
                                         mc->current_server->port,
 
1409
                                         mc->current_server->if_index,
 
1410
                                         mc->current_server->af, mc);
1396
1411
        if(ret == 0){
1397
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1412
          avahi_simple_poll_quit(s);
1398
1413
          return 0;
1399
1414
        }
1400
1415
        ret = clock_gettime(CLOCK_MONOTONIC,
1401
 
                            &mc.current_server->last_seen);
 
1416
                            &mc->current_server->last_seen);
1402
1417
        if(ret == -1){
1403
1418
          perror_plus("clock_gettime");
1404
1419
          return -1;
1405
1420
        }
1406
 
        mc.current_server = mc.current_server->next;
 
1421
        mc->current_server = mc->current_server->next;
1407
1422
        block_time = 0;         /* Call avahi to find new Mandos
1408
1423
                                   servers, but don't block */
1409
1424
      }
1418
1433
  }
1419
1434
}
1420
1435
 
 
1436
/* Set effective uid to 0, return errno */
 
1437
error_t raise_privileges(void){
 
1438
  error_t old_errno = errno;
 
1439
  error_t ret_errno = 0;
 
1440
  if(seteuid(0) == -1){
 
1441
    ret_errno = errno;
 
1442
    perror_plus("seteuid");
 
1443
  }
 
1444
  errno = old_errno;
 
1445
  return ret_errno;
 
1446
}
 
1447
 
 
1448
/* Set effective and real user ID to 0.  Return errno. */
 
1449
error_t raise_privileges_permanently(void){
 
1450
  error_t old_errno = errno;
 
1451
  error_t ret_errno = raise_privileges();
 
1452
  if(ret_errno != 0){
 
1453
    errno = old_errno;
 
1454
    return ret_errno;
 
1455
  }
 
1456
  if(setuid(0) == -1){
 
1457
    ret_errno = errno;
 
1458
    perror_plus("seteuid");
 
1459
  }
 
1460
  errno = old_errno;
 
1461
  return ret_errno;
 
1462
}
 
1463
 
 
1464
/* Set effective user ID to unprivileged saved user ID */
 
1465
error_t lower_privileges(void){
 
1466
  error_t old_errno = errno;
 
1467
  error_t ret_errno = 0;
 
1468
  if(seteuid(uid) == -1){
 
1469
    ret_errno = errno;
 
1470
    perror_plus("seteuid");
 
1471
  }
 
1472
  errno = old_errno;
 
1473
  return ret_errno;
 
1474
}
 
1475
 
 
1476
/* Lower privileges permanently */
 
1477
error_t lower_privileges_permanently(void){
 
1478
  error_t old_errno = errno;
 
1479
  error_t ret_errno = 0;
 
1480
  if(setuid(uid) == -1){
 
1481
    ret_errno = errno;
 
1482
    perror_plus("setuid");
 
1483
  }
 
1484
  errno = old_errno;
 
1485
  return ret_errno;
 
1486
}
 
1487
 
 
1488
bool run_network_hooks(const char *mode, const char *interface,
 
1489
                       const float delay){
 
1490
  struct dirent **direntries;
 
1491
  struct dirent *direntry;
 
1492
  int ret;
 
1493
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1494
                         alphasort);
 
1495
  if(numhooks == -1){
 
1496
    if(errno == ENOENT){
 
1497
      if(debug){
 
1498
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1499
                     " found\n", hookdir);
 
1500
      }
 
1501
    } else {
 
1502
      perror_plus("scandir");
 
1503
    }
 
1504
  } else {
 
1505
    int devnull = open("/dev/null", O_RDONLY);
 
1506
    for(int i = 0; i < numhooks; i++){
 
1507
      direntry = direntries[i];
 
1508
      char *fullname = NULL;
 
1509
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1510
      if(ret < 0){
 
1511
        perror_plus("asprintf");
 
1512
        continue;
 
1513
      }
 
1514
      if(debug){
 
1515
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1516
                     direntry->d_name);
 
1517
      }
 
1518
      pid_t hook_pid = fork();
 
1519
      if(hook_pid == 0){
 
1520
        /* Child */
 
1521
        /* Raise privileges */
 
1522
        raise_privileges_permanently();
 
1523
        /* Set group */
 
1524
        errno = 0;
 
1525
        ret = setgid(0);
 
1526
        if(ret == -1){
 
1527
          perror_plus("setgid");
 
1528
        }
 
1529
        /* Reset supplementary groups */
 
1530
        errno = 0;
 
1531
        ret = setgroups(0, NULL);
 
1532
        if(ret == -1){
 
1533
          perror_plus("setgroups");
 
1534
        }
 
1535
        dup2(devnull, STDIN_FILENO);
 
1536
        close(devnull);
 
1537
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1538
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1539
        if(ret == -1){
 
1540
          perror_plus("setenv");
 
1541
          _exit(EX_OSERR);
 
1542
        }
 
1543
        ret = setenv("DEVICE", interface, 1);
 
1544
        if(ret == -1){
 
1545
          perror_plus("setenv");
 
1546
          _exit(EX_OSERR);
 
1547
        }
 
1548
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1549
        if(ret == -1){
 
1550
          perror_plus("setenv");
 
1551
          _exit(EX_OSERR);
 
1552
        }
 
1553
        ret = setenv("MODE", mode, 1);
 
1554
        if(ret == -1){
 
1555
          perror_plus("setenv");
 
1556
          _exit(EX_OSERR);
 
1557
        }
 
1558
        char *delaystring;
 
1559
        ret = asprintf(&delaystring, "%f", delay);
 
1560
        if(ret == -1){
 
1561
          perror_plus("asprintf");
 
1562
          _exit(EX_OSERR);
 
1563
        }
 
1564
        ret = setenv("DELAY", delaystring, 1);
 
1565
        if(ret == -1){
 
1566
          free(delaystring);
 
1567
          perror_plus("setenv");
 
1568
          _exit(EX_OSERR);
 
1569
        }
 
1570
        free(delaystring);
 
1571
        if(connect_to != NULL){
 
1572
          ret = setenv("CONNECT", connect_to, 1);
 
1573
          if(ret == -1){
 
1574
            perror_plus("setenv");
 
1575
            _exit(EX_OSERR);
 
1576
          }
 
1577
        }
 
1578
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1579
          perror_plus("execl");
 
1580
          _exit(EXIT_FAILURE);
 
1581
        }
 
1582
      } else {
 
1583
        int status;
 
1584
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1585
          perror_plus("waitpid");
 
1586
          free(fullname);
 
1587
          continue;
 
1588
        }
 
1589
        if(WIFEXITED(status)){
 
1590
          if(WEXITSTATUS(status) != 0){
 
1591
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1592
                         " with status %d\n", direntry->d_name,
 
1593
                         WEXITSTATUS(status));
 
1594
            free(fullname);
 
1595
            continue;
 
1596
          }
 
1597
        } else if(WIFSIGNALED(status)){
 
1598
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1599
                       " signal %d\n", direntry->d_name,
 
1600
                       WTERMSIG(status));
 
1601
          free(fullname);
 
1602
          continue;
 
1603
        } else {
 
1604
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1605
                       " crashed\n", direntry->d_name);
 
1606
          free(fullname);
 
1607
          continue;
 
1608
        }
 
1609
      }
 
1610
      free(fullname);
 
1611
      if(debug){
 
1612
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1613
                     direntry->d_name);
 
1614
      }
 
1615
    }
 
1616
    close(devnull);
 
1617
  }
 
1618
  return true;
 
1619
}
 
1620
 
 
1621
error_t bring_up_interface(const char *const interface,
 
1622
                           const float delay){
 
1623
  int sd = -1;
 
1624
  error_t old_errno = errno;
 
1625
  error_t ret_errno = 0;
 
1626
  int ret, ret_setflags;
 
1627
  struct ifreq network;
 
1628
  unsigned int if_index = if_nametoindex(interface);
 
1629
  if(if_index == 0){
 
1630
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1631
    errno = old_errno;
 
1632
    return ENXIO;
 
1633
  }
 
1634
  
 
1635
  if(quit_now){
 
1636
    errno = old_errno;
 
1637
    return EINTR;
 
1638
  }
 
1639
  
 
1640
  if(not interface_is_up(interface)){
 
1641
    if(not get_flags(interface, &network) and debug){
 
1642
      ret_errno = errno;
 
1643
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1644
                   "\"%s\"\n", interface);
 
1645
      return ret_errno;
 
1646
    }
 
1647
    network.ifr_flags |= IFF_UP;
 
1648
    
 
1649
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1650
    if(sd < 0){
 
1651
      ret_errno = errno;
 
1652
      perror_plus("socket");
 
1653
      errno = old_errno;
 
1654
      return ret_errno;
 
1655
    }
 
1656
  
 
1657
    if(quit_now){
 
1658
      close(sd);
 
1659
      errno = old_errno;
 
1660
      return EINTR;
 
1661
    }
 
1662
    
 
1663
    if(debug){
 
1664
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1665
                   interface);
 
1666
    }
 
1667
    
 
1668
    /* Raise priviliges */
 
1669
    raise_privileges();
 
1670
    
 
1671
#ifdef __linux__
 
1672
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1673
       messages about the network interface to mess up the prompt */
 
1674
    int ret_linux = klogctl(8, NULL, 5);
 
1675
    bool restore_loglevel = true;
 
1676
    if(ret_linux == -1){
 
1677
      restore_loglevel = false;
 
1678
      perror_plus("klogctl");
 
1679
    }
 
1680
#endif  /* __linux__ */
 
1681
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1682
    ret_errno = errno;
 
1683
#ifdef __linux__
 
1684
    if(restore_loglevel){
 
1685
      ret_linux = klogctl(7, NULL, 0);
 
1686
      if(ret_linux == -1){
 
1687
        perror_plus("klogctl");
 
1688
      }
 
1689
    }
 
1690
#endif  /* __linux__ */
 
1691
    
 
1692
    /* Lower privileges */
 
1693
    lower_privileges();
 
1694
    
 
1695
    /* Close the socket */
 
1696
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1697
    if(ret == -1){
 
1698
      perror_plus("close");
 
1699
    }
 
1700
    
 
1701
    if(ret_setflags == -1){
 
1702
      errno = ret_errno;
 
1703
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1704
      errno = old_errno;
 
1705
      return ret_errno;
 
1706
    }
 
1707
  } else if(debug){
 
1708
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1709
                 interface);
 
1710
  }
 
1711
  
 
1712
  /* Sleep checking until interface is running.
 
1713
     Check every 0.25s, up to total time of delay */
 
1714
  for(int i=0; i < delay * 4; i++){
 
1715
    if(interface_is_running(interface)){
 
1716
      break;
 
1717
    }
 
1718
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1719
    ret = nanosleep(&sleeptime, NULL);
 
1720
    if(ret == -1 and errno != EINTR){
 
1721
      perror_plus("nanosleep");
 
1722
    }
 
1723
  }
 
1724
  
 
1725
  errno = old_errno;
 
1726
  return 0;
 
1727
}
 
1728
 
 
1729
error_t take_down_interface(const char *const interface){
 
1730
  int sd = -1;
 
1731
  error_t old_errno = errno;
 
1732
  error_t ret_errno = 0;
 
1733
  int ret, ret_setflags;
 
1734
  struct ifreq network;
 
1735
  unsigned int if_index = if_nametoindex(interface);
 
1736
  if(if_index == 0){
 
1737
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1738
    errno = old_errno;
 
1739
    return ENXIO;
 
1740
  }
 
1741
  if(interface_is_up(interface)){
 
1742
    if(not get_flags(interface, &network) and debug){
 
1743
      ret_errno = errno;
 
1744
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1745
                   "\"%s\"\n", interface);
 
1746
      return ret_errno;
 
1747
    }
 
1748
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1749
    
 
1750
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1751
    if(sd < 0){
 
1752
      ret_errno = errno;
 
1753
      perror_plus("socket");
 
1754
      errno = old_errno;
 
1755
      return ret_errno;
 
1756
    }
 
1757
    
 
1758
    if(debug){
 
1759
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1760
                   interface);
 
1761
    }
 
1762
    
 
1763
    /* Raise priviliges */
 
1764
    raise_privileges();
 
1765
    
 
1766
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1767
    ret_errno = errno;
 
1768
    
 
1769
    /* Lower privileges */
 
1770
    lower_privileges();
 
1771
    
 
1772
    /* Close the socket */
 
1773
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1774
    if(ret == -1){
 
1775
      perror_plus("close");
 
1776
    }
 
1777
    
 
1778
    if(ret_setflags == -1){
 
1779
      errno = ret_errno;
 
1780
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1781
      errno = old_errno;
 
1782
      return ret_errno;
 
1783
    }
 
1784
  } else if(debug){
 
1785
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1786
                 interface);
 
1787
  }
 
1788
  
 
1789
  errno = old_errno;
 
1790
  return 0;
 
1791
}
 
1792
 
1421
1793
int main(int argc, char *argv[]){
 
1794
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1795
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1796
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
1797
                        .interfaces = NULL, .interfaces_size = 0 };
1422
1798
  AvahiSServiceBrowser *sb = NULL;
1423
 
  int error;
 
1799
  error_t ret_errno;
1424
1800
  int ret;
1425
1801
  intmax_t tmpmax;
1426
1802
  char *tmp;
1427
1803
  int exitcode = EXIT_SUCCESS;
1428
 
  const char *interface = "";
1429
 
  struct ifreq network;
1430
 
  int sd = -1;
1431
 
  bool take_down_interface = false;
1432
 
  uid_t uid;
1433
 
  gid_t gid;
 
1804
  char *interfaces_to_take_down = NULL;
 
1805
  size_t interfaces_to_take_down_size = 0;
1434
1806
  char tempdir[] = "/tmp/mandosXXXXXX";
1435
1807
  bool tempdir_created = false;
1436
1808
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1437
1809
  const char *seckey = PATHDIR "/" SECKEY;
1438
1810
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1811
  char *interfaces_hooks = NULL;
 
1812
  size_t interfaces_hooks_size = 0;
1439
1813
  
1440
1814
  bool gnutls_initialized = false;
1441
1815
  bool gpgme_initialized = false;
1503
1877
        .group = 2 },
1504
1878
      { .name = "retry", .key = 132,
1505
1879
        .arg = "SECONDS",
1506
 
        .doc = "Retry interval used when denied by the mandos server",
 
1880
        .doc = "Retry interval used when denied by the Mandos server",
1507
1881
        .group = 2 },
1508
1882
      { .name = "network-hook-dir", .key = 133,
1509
1883
        .arg = "DIR",
1532
1906
        connect_to = arg;
1533
1907
        break;
1534
1908
      case 'i':                 /* --interface */
1535
 
        interface = arg;
 
1909
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
1910
                                 arg, (int)',');
 
1911
        if(ret_errno != 0){
 
1912
          argp_error(state, "%s", strerror(ret_errno));
 
1913
        }
1536
1914
        break;
1537
1915
      case 's':                 /* --seckey */
1538
1916
        seckey = arg;
1581
1959
        argp_state_help(state, state->out_stream,
1582
1960
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1583
1961
      case 'V':                 /* --version */
1584
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1585
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1962
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1586
1963
        exit(argp_err_exit_status);
1587
1964
        break;
1588
1965
      default:
1615
1992
  {
1616
1993
    /* Work around Debian bug #633582:
1617
1994
       <http://bugs.debian.org/633582> */
1618
 
    struct stat st;
1619
1995
    
1620
1996
    /* Re-raise priviliges */
1621
 
    errno = 0;
1622
 
    ret = seteuid(0);
1623
 
    if(ret == -1){
1624
 
      perror_plus("seteuid");
1625
 
    }
1626
 
    
1627
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1628
 
      int seckey_fd = open(seckey, O_RDONLY);
1629
 
      if(seckey_fd == -1){
1630
 
        perror_plus("open");
1631
 
      } else {
1632
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1633
 
        if(ret == -1){
1634
 
          perror_plus("fstat");
1635
 
        } else {
1636
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1637
 
            ret = fchown(seckey_fd, uid, gid);
1638
 
            if(ret == -1){
1639
 
              perror_plus("fchown");
1640
 
            }
1641
 
          }
1642
 
        }
1643
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1644
 
      }
1645
 
    }
1646
 
    
1647
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1648
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1649
 
      if(pubkey_fd == -1){
1650
 
        perror_plus("open");
1651
 
      } else {
1652
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1653
 
        if(ret == -1){
1654
 
          perror_plus("fstat");
1655
 
        } else {
1656
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1657
 
            ret = fchown(pubkey_fd, uid, gid);
1658
 
            if(ret == -1){
1659
 
              perror_plus("fchown");
1660
 
            }
1661
 
          }
1662
 
        }
1663
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1664
 
      }
1665
 
    }
1666
 
    
1667
 
    /* Lower privileges */
1668
 
    errno = 0;
1669
 
    ret = seteuid(uid);
1670
 
    if(ret == -1){
1671
 
      perror_plus("seteuid");
1672
 
    }
1673
 
  }
1674
 
  
1675
 
  /* Find network hooks and run them */
1676
 
  {
1677
 
    struct dirent **direntries;
1678
 
    struct dirent *direntry;
1679
 
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
1680
 
                           alphasort);
1681
 
    if(numhooks == -1){
1682
 
      perror_plus("scandir");
1683
 
    } else {
1684
 
      int devnull = open("/dev/null", O_RDONLY);
1685
 
      for(int i = 0; i < numhooks; i++){
1686
 
        direntry = direntries[0];
1687
 
        char *fullname = NULL;
1688
 
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1689
 
        if(ret < 0){
1690
 
          perror_plus("asprintf");
1691
 
          continue;
1692
 
        }
1693
 
        pid_t hook_pid = fork();
1694
 
        if(hook_pid == 0){
1695
 
          /* Child */
1696
 
          dup2(devnull, STDIN_FILENO);
1697
 
          close(devnull);
1698
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1699
 
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1700
 
          if(ret == -1){
1701
 
            perror_plus("setenv");
1702
 
            exit(1);
1703
 
          }
1704
 
          ret = setenv("DEVICE", interface, 1);
1705
 
          if(ret == -1){
1706
 
            perror_plus("setenv");
1707
 
            exit(1);
1708
 
          }
1709
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1710
 
          if(ret == -1){
1711
 
            perror_plus("setenv");
1712
 
            exit(1);
1713
 
          }
1714
 
          ret = setenv("MODE", "start", 1);
1715
 
          if(ret == -1){
1716
 
            perror_plus("setenv");
1717
 
            exit(1);
1718
 
          }
1719
 
          char *delaystring;
1720
 
          ret = asprintf(&delaystring, "%f", delay);
1721
 
          if(ret == -1){
1722
 
            perror_plus("asprintf");
1723
 
            exit(1);
1724
 
          }
1725
 
          ret = setenv("DELAY", delaystring, 1);
1726
 
          if(ret == -1){
1727
 
            free(delaystring);
1728
 
            perror_plus("setenv");
1729
 
            exit(1);
1730
 
          }
1731
 
          free(delaystring);
1732
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1733
 
          perror_plus("execl");
1734
 
        } else {
1735
 
          int status;
1736
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1737
 
            perror_plus("waitpid");
1738
 
            free(fullname);
1739
 
            continue;
1740
 
          }
1741
 
          if(WIFEXITED(status)){
1742
 
            if(WEXITSTATUS(status) != 0){
1743
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1744
 
                      "Warning: network hook \"%s\" exited"
1745
 
                      " with status %d\n", direntry->d_name,
1746
 
                      WEXITSTATUS(status));
1747
 
              free(fullname);
1748
 
              continue;
1749
 
            }
1750
 
          } else if(WIFSIGNALED(status)){
1751
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1752
 
                    "Warning: network hook \"%s\" died by"
1753
 
                    " signal %d\n", direntry->d_name,
1754
 
                    WTERMSIG(status));
1755
 
            free(fullname);
1756
 
            continue;
1757
 
          } else {
1758
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1759
 
                    "Warning: network hook \"%s\" crashed\n",
1760
 
                    direntry->d_name);
1761
 
            free(fullname);
1762
 
            continue;
1763
 
          }
1764
 
        }
1765
 
        free(fullname);
1766
 
        if(quit_now){
1767
 
          goto end;
1768
 
        }
1769
 
      }
1770
 
      close(devnull);
 
1997
    if(raise_privileges() == 0){
 
1998
      struct stat st;
 
1999
      
 
2000
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
2001
        int seckey_fd = open(seckey, O_RDONLY);
 
2002
        if(seckey_fd == -1){
 
2003
          perror_plus("open");
 
2004
        } else {
 
2005
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
2006
          if(ret == -1){
 
2007
            perror_plus("fstat");
 
2008
          } else {
 
2009
            if(S_ISREG(st.st_mode)
 
2010
               and st.st_uid == 0 and st.st_gid == 0){
 
2011
              ret = fchown(seckey_fd, uid, gid);
 
2012
              if(ret == -1){
 
2013
                perror_plus("fchown");
 
2014
              }
 
2015
            }
 
2016
          }
 
2017
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2018
        }
 
2019
      }
 
2020
    
 
2021
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
2022
        int pubkey_fd = open(pubkey, O_RDONLY);
 
2023
        if(pubkey_fd == -1){
 
2024
          perror_plus("open");
 
2025
        } else {
 
2026
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
2027
          if(ret == -1){
 
2028
            perror_plus("fstat");
 
2029
          } else {
 
2030
            if(S_ISREG(st.st_mode)
 
2031
               and st.st_uid == 0 and st.st_gid == 0){
 
2032
              ret = fchown(pubkey_fd, uid, gid);
 
2033
              if(ret == -1){
 
2034
                perror_plus("fchown");
 
2035
              }
 
2036
            }
 
2037
          }
 
2038
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2039
        }
 
2040
      }
 
2041
    
 
2042
      /* Lower privileges */
 
2043
      lower_privileges();
 
2044
    }
 
2045
  }
 
2046
  
 
2047
  /* Remove invalid interface names (except "none") */
 
2048
  {
 
2049
    char *interface = NULL;
 
2050
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2051
                                 interface))){
 
2052
      if(strcmp(interface, "none") != 0
 
2053
         and if_nametoindex(interface) == 0){
 
2054
        if(interface[0] != '\0'){
 
2055
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2056
                       " \"%s\"\n", interface);
 
2057
        }
 
2058
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2059
        interface = NULL;
 
2060
      }
 
2061
    }
 
2062
  }
 
2063
  
 
2064
  /* Run network hooks */
 
2065
  {
 
2066
    if(mc.interfaces != NULL){
 
2067
      interfaces_hooks = malloc(mc.interfaces_size);
 
2068
      if(interfaces_hooks == NULL){
 
2069
        perror_plus("malloc");
 
2070
        goto end;
 
2071
      }
 
2072
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2073
      interfaces_hooks_size = mc.interfaces_size;
 
2074
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
 
2075
                     (int)',');
 
2076
    }
 
2077
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2078
                             interfaces_hooks : "", delay)){
 
2079
      goto end;
1771
2080
    }
1772
2081
  }
1773
2082
  
1775
2084
    avahi_set_log_function(empty_log);
1776
2085
  }
1777
2086
  
1778
 
  if(interface[0] == '\0'){
1779
 
    struct dirent **direntries;
1780
 
    /* First look for interfaces that are up */
1781
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1782
 
                  alphasort);
1783
 
    if(ret == 0){
1784
 
      /* No up interfaces, look for any good interfaces */
1785
 
      free(direntries);
1786
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1787
 
                    alphasort);
1788
 
    }
1789
 
    if(ret >= 1){
1790
 
      /* Pick the first interface returned */
1791
 
      interface = strdup(direntries[0]->d_name);
1792
 
      if(debug){
1793
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1794
 
                "Using interface \"%s\"\n", interface);
1795
 
      }
1796
 
      if(interface == NULL){
1797
 
        perror_plus("malloc");
1798
 
        free(direntries);
1799
 
        exitcode = EXIT_FAILURE;
1800
 
        goto end;
1801
 
      }
1802
 
      free(direntries);
1803
 
    } else {
1804
 
      free(direntries);
1805
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1806
 
              "Could not find a network interface\n");
1807
 
      exitcode = EXIT_FAILURE;
1808
 
      goto end;
1809
 
    }
1810
 
  }
1811
 
  
1812
2087
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1813
2088
     from the signal handler */
1814
2089
  /* Initialize the pseudo-RNG for Avahi */
1815
2090
  srand((unsigned int) time(NULL));
1816
 
  mc.simple_poll = avahi_simple_poll_new();
1817
 
  if(mc.simple_poll == NULL){
1818
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1819
 
            "Avahi: Failed to create simple poll object.\n");
 
2091
  simple_poll = avahi_simple_poll_new();
 
2092
  if(simple_poll == NULL){
 
2093
    fprintf_plus(stderr,
 
2094
                 "Avahi: Failed to create simple poll object.\n");
1820
2095
    exitcode = EX_UNAVAILABLE;
1821
2096
    goto end;
1822
2097
  }
1884
2159
    }
1885
2160
  }
1886
2161
  
1887
 
  /* If the interface is down, bring it up */
1888
 
  if(strcmp(interface, "none") != 0){
1889
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1890
 
    if(if_index == 0){
1891
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1892
 
              "No such interface: \"%s\"\n", interface);
1893
 
      exitcode = EX_UNAVAILABLE;
1894
 
      goto end;
1895
 
    }
1896
 
    
1897
 
    if(quit_now){
1898
 
      goto end;
1899
 
    }
1900
 
    
1901
 
    /* Re-raise priviliges */
1902
 
    errno = 0;
1903
 
    ret = seteuid(0);
1904
 
    if(ret == -1){
1905
 
      perror_plus("seteuid");
1906
 
    }
1907
 
    
1908
 
#ifdef __linux__
1909
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1910
 
       messages about the network interface to mess up the prompt */
1911
 
    ret = klogctl(8, NULL, 5);
1912
 
    bool restore_loglevel = true;
1913
 
    if(ret == -1){
1914
 
      restore_loglevel = false;
1915
 
      perror_plus("klogctl");
1916
 
    }
1917
 
#endif  /* __linux__ */
1918
 
    
1919
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1920
 
    if(sd < 0){
1921
 
      perror_plus("socket");
1922
 
      exitcode = EX_OSERR;
1923
 
#ifdef __linux__
1924
 
      if(restore_loglevel){
1925
 
        ret = klogctl(7, NULL, 0);
1926
 
        if(ret == -1){
1927
 
          perror_plus("klogctl");
1928
 
        }
1929
 
      }
1930
 
#endif  /* __linux__ */
1931
 
      /* Lower privileges */
1932
 
      errno = 0;
1933
 
      ret = seteuid(uid);
1934
 
      if(ret == -1){
1935
 
        perror_plus("seteuid");
1936
 
      }
1937
 
      goto end;
1938
 
    }
1939
 
    strcpy(network.ifr_name, interface);
1940
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1941
 
    if(ret == -1){
1942
 
      perror_plus("ioctl SIOCGIFFLAGS");
1943
 
#ifdef __linux__
1944
 
      if(restore_loglevel){
1945
 
        ret = klogctl(7, NULL, 0);
1946
 
        if(ret == -1){
1947
 
          perror_plus("klogctl");
1948
 
        }
1949
 
      }
1950
 
#endif  /* __linux__ */
1951
 
      exitcode = EX_OSERR;
1952
 
      /* Lower privileges */
1953
 
      errno = 0;
1954
 
      ret = seteuid(uid);
1955
 
      if(ret == -1){
1956
 
        perror_plus("seteuid");
1957
 
      }
1958
 
      goto end;
1959
 
    }
1960
 
    if((network.ifr_flags & IFF_UP) == 0){
1961
 
      network.ifr_flags |= IFF_UP;
1962
 
      take_down_interface = true;
1963
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1964
 
      if(ret == -1){
1965
 
        take_down_interface = false;
1966
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1967
 
        exitcode = EX_OSERR;
1968
 
#ifdef __linux__
1969
 
        if(restore_loglevel){
1970
 
          ret = klogctl(7, NULL, 0);
1971
 
          if(ret == -1){
1972
 
            perror_plus("klogctl");
 
2162
  /* If no interfaces were specified, make a list */
 
2163
  if(mc.interfaces == NULL){
 
2164
    struct dirent **direntries;
 
2165
    /* Look for any good interfaces */
 
2166
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2167
                  alphasort);
 
2168
    if(ret >= 1){
 
2169
      /* Add all found interfaces to interfaces list */
 
2170
      for(int i = 0; i < ret; ++i){
 
2171
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2172
                             direntries[i]->d_name);
 
2173
        if(ret_errno != 0){
 
2174
          perror_plus("argz_add");
 
2175
          continue;
 
2176
        }
 
2177
        if(debug){
 
2178
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2179
                       direntries[i]->d_name);
 
2180
        }
 
2181
      }
 
2182
      free(direntries);
 
2183
    } else {
 
2184
      free(direntries);
 
2185
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2186
      exitcode = EXIT_FAILURE;
 
2187
      goto end;
 
2188
    }
 
2189
  }
 
2190
  
 
2191
  /* Bring up interfaces which are down, and remove any "none"s */
 
2192
  {
 
2193
    char *interface = NULL;
 
2194
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2195
                                 interface))){
 
2196
      /* If interface name is "none", stop bringing up interfaces.
 
2197
         Also remove all instances of "none" from the list */
 
2198
      if(strcmp(interface, "none") == 0){
 
2199
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2200
                    interface);
 
2201
        interface = NULL;
 
2202
        while((interface = argz_next(mc.interfaces,
 
2203
                                     mc.interfaces_size, interface))){
 
2204
          if(strcmp(interface, "none") == 0){
 
2205
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2206
                        interface);
 
2207
            interface = NULL;
1973
2208
          }
1974
2209
        }
1975
 
#endif  /* __linux__ */
1976
 
        /* Lower privileges */
1977
 
        errno = 0;
1978
 
        ret = seteuid(uid);
1979
 
        if(ret == -1){
1980
 
          perror_plus("seteuid");
1981
 
        }
1982
 
        goto end;
1983
 
      }
1984
 
    }
1985
 
    /* Sleep checking until interface is running.
1986
 
       Check every 0.25s, up to total time of delay */
1987
 
    for(int i=0; i < delay * 4; i++){
1988
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1989
 
      if(ret == -1){
1990
 
        perror_plus("ioctl SIOCGIFFLAGS");
1991
 
      } else if(network.ifr_flags & IFF_RUNNING){
1992
2210
        break;
1993
2211
      }
1994
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1995
 
      ret = nanosleep(&sleeptime, NULL);
1996
 
      if(ret == -1 and errno != EINTR){
1997
 
        perror_plus("nanosleep");
1998
 
      }
1999
 
    }
2000
 
    if(not take_down_interface){
2001
 
      /* We won't need the socket anymore */
2002
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2003
 
      if(ret == -1){
2004
 
        perror_plus("close");
2005
 
      }
2006
 
    }
2007
 
#ifdef __linux__
2008
 
    if(restore_loglevel){
2009
 
      /* Restores kernel loglevel to default */
2010
 
      ret = klogctl(7, NULL, 0);
2011
 
      if(ret == -1){
2012
 
        perror_plus("klogctl");
2013
 
      }
2014
 
    }
2015
 
#endif  /* __linux__ */
2016
 
    /* Lower privileges */
2017
 
    errno = 0;
2018
 
    if(take_down_interface){
2019
 
      /* Lower privileges */
2020
 
      ret = seteuid(uid);
2021
 
      if(ret == -1){
2022
 
        perror_plus("seteuid");
2023
 
      }
2024
 
    } else {
2025
 
      /* Lower privileges permanently */
2026
 
      ret = setuid(uid);
2027
 
      if(ret == -1){
2028
 
        perror_plus("setuid");
2029
 
      }
2030
 
    }
 
2212
      bool interface_was_up = interface_is_up(interface);
 
2213
      ret = bring_up_interface(interface, delay);
 
2214
      if(not interface_was_up){
 
2215
        if(ret != 0){
 
2216
          errno = ret;
 
2217
          perror_plus("Failed to bring up interface");
 
2218
        } else {
 
2219
          ret_errno = argz_add(&interfaces_to_take_down,
 
2220
                               &interfaces_to_take_down_size,
 
2221
                               interface);
 
2222
        }
 
2223
      }
 
2224
    }
 
2225
    if(debug and (interfaces_to_take_down == NULL)){
 
2226
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2227
    }
 
2228
  }
 
2229
  
 
2230
  /* If we only got one interface, explicitly use only that one */
 
2231
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2232
    if(debug){
 
2233
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2234
                   mc.interfaces);
 
2235
    }
 
2236
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2031
2237
  }
2032
2238
  
2033
2239
  if(quit_now){
2034
2240
    goto end;
2035
2241
  }
2036
2242
  
2037
 
  ret = init_gnutls_global(pubkey, seckey);
 
2243
  ret = init_gnutls_global(pubkey, seckey, &mc);
2038
2244
  if(ret == -1){
2039
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2040
 
            "init_gnutls_global failed\n");
 
2245
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2041
2246
    exitcode = EX_UNAVAILABLE;
2042
2247
    goto end;
2043
2248
  } else {
2058
2263
    goto end;
2059
2264
  }
2060
2265
  
2061
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
2062
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2063
 
            "init_gpgme failed\n");
 
2266
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2267
    fprintf_plus(stderr, "init_gpgme failed\n");
2064
2268
    exitcode = EX_UNAVAILABLE;
2065
2269
    goto end;
2066
2270
  } else {
2075
2279
    /* Connect directly, do not use Zeroconf */
2076
2280
    /* (Mainly meant for debugging) */
2077
2281
    char *address = strrchr(connect_to, ':');
 
2282
    
2078
2283
    if(address == NULL){
2079
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2080
 
              "No colon in address\n");
 
2284
      fprintf_plus(stderr, "No colon in address\n");
2081
2285
      exitcode = EX_USAGE;
2082
2286
      goto end;
2083
2287
    }
2086
2290
      goto end;
2087
2291
    }
2088
2292
    
2089
 
    uint16_t port;
 
2293
    in_port_t port;
2090
2294
    errno = 0;
2091
2295
    tmpmax = strtoimax(address+1, &tmp, 10);
2092
2296
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2093
 
       or tmpmax != (uint16_t)tmpmax){
2094
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2095
 
              "Bad port number\n");
 
2297
       or tmpmax != (in_port_t)tmpmax){
 
2298
      fprintf_plus(stderr, "Bad port number\n");
2096
2299
      exitcode = EX_USAGE;
2097
2300
      goto end;
2098
2301
    }
2099
 
  
 
2302
    
2100
2303
    if(quit_now){
2101
2304
      goto end;
2102
2305
    }
2103
2306
    
2104
 
    port = (uint16_t)tmpmax;
 
2307
    port = (in_port_t)tmpmax;
2105
2308
    *address = '\0';
2106
2309
    /* Colon in address indicates IPv6 */
2107
2310
    int af;
2123
2326
    }
2124
2327
    
2125
2328
    while(not quit_now){
2126
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2329
      ret = start_mandos_communication(address, port, if_index, af,
 
2330
                                       &mc);
2127
2331
      if(quit_now or ret == 0){
2128
2332
        break;
2129
2333
      }
2130
2334
      if(debug){
2131
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2132
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2335
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2336
                     (int)retry_interval);
2133
2337
      }
2134
 
      sleep((int)retry_interval);
 
2338
      sleep((unsigned int)retry_interval);
2135
2339
    }
2136
2340
    
2137
2341
    if (not quit_now){
2155
2359
    config.publish_domain = 0;
2156
2360
    
2157
2361
    /* Allocate a new server */
2158
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2159
 
                                 (mc.simple_poll), &config, NULL,
2160
 
                                 NULL, &error);
 
2362
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2363
                                 &config, NULL, NULL, &ret_errno);
2161
2364
    
2162
2365
    /* Free the Avahi configuration data */
2163
2366
    avahi_server_config_free(&config);
2165
2368
  
2166
2369
  /* Check if creating the Avahi server object succeeded */
2167
2370
  if(mc.server == NULL){
2168
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2169
 
            "Failed to create Avahi server: %s\n",
2170
 
            avahi_strerror(error));
 
2371
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2372
                 avahi_strerror(ret_errno));
2171
2373
    exitcode = EX_UNAVAILABLE;
2172
2374
    goto end;
2173
2375
  }
2179
2381
  /* Create the Avahi service browser */
2180
2382
  sb = avahi_s_service_browser_new(mc.server, if_index,
2181
2383
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2182
 
                                   NULL, 0, browse_callback, NULL);
 
2384
                                   NULL, 0, browse_callback,
 
2385
                                   (void *)&mc);
2183
2386
  if(sb == NULL){
2184
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2185
 
            "Failed to create service browser: %s\n",
2186
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2387
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2388
                 avahi_strerror(avahi_server_errno(mc.server)));
2187
2389
    exitcode = EX_UNAVAILABLE;
2188
2390
    goto end;
2189
2391
  }
2195
2397
  /* Run the main loop */
2196
2398
  
2197
2399
  if(debug){
2198
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2199
 
            "Starting Avahi loop search\n");
 
2400
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2200
2401
  }
2201
2402
 
2202
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2203
 
                                (int)(retry_interval * 1000));
 
2403
  ret = avahi_loop_with_timeout(simple_poll,
 
2404
                                (int)(retry_interval * 1000), &mc);
2204
2405
  if(debug){
2205
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2206
 
            "avahi_loop_with_timeout exited %s\n",
2207
 
            (ret == 0) ? "successfully" : "with error");
 
2406
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2407
                 (ret == 0) ? "successfully" : "with error");
2208
2408
  }
2209
2409
  
2210
2410
 end:
2211
2411
  
2212
2412
  if(debug){
2213
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2214
 
            "%s exiting\n", argv[0]);
 
2413
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2215
2414
  }
2216
2415
  
2217
2416
  /* Cleanup things */
 
2417
  free(mc.interfaces);
 
2418
  
2218
2419
  if(sb != NULL)
2219
2420
    avahi_s_service_browser_free(sb);
2220
2421
  
2221
2422
  if(mc.server != NULL)
2222
2423
    avahi_server_free(mc.server);
2223
2424
  
2224
 
  if(mc.simple_poll != NULL)
2225
 
    avahi_simple_poll_free(mc.simple_poll);
 
2425
  if(simple_poll != NULL)
 
2426
    avahi_simple_poll_free(simple_poll);
2226
2427
  
2227
2428
  if(gnutls_initialized){
2228
2429
    gnutls_certificate_free_credentials(mc.cred);
2233
2434
  if(gpgme_initialized){
2234
2435
    gpgme_release(mc.ctx);
2235
2436
  }
2236
 
 
 
2437
  
2237
2438
  /* Cleans up the circular linked list of Mandos servers the client
2238
2439
     has seen */
2239
2440
  if(mc.current_server != NULL){
2245
2446
    }
2246
2447
  }
2247
2448
  
2248
 
  /* XXX run network hooks "stop" here  */
2249
 
  
2250
 
  /* Take down the network interface */
2251
 
  if(take_down_interface){
2252
 
    /* Re-raise priviliges */
2253
 
    errno = 0;
2254
 
    ret = seteuid(0);
2255
 
    if(ret == -1){
2256
 
      perror_plus("seteuid");
2257
 
    }
2258
 
    if(geteuid() == 0){
2259
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2260
 
      if(ret == -1){
2261
 
        perror_plus("ioctl SIOCGIFFLAGS");
2262
 
      } else if(network.ifr_flags & IFF_UP){
2263
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2264
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2265
 
        if(ret == -1){
2266
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2449
  /* Re-raise priviliges */
 
2450
  {
 
2451
    raise_privileges();
 
2452
    
 
2453
    /* Run network hooks */
 
2454
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2455
                      interfaces_hooks : "", delay);
 
2456
    
 
2457
    /* Take down the network interfaces which were brought up */
 
2458
    {
 
2459
      char *interface = NULL;
 
2460
      while((interface=argz_next(interfaces_to_take_down,
 
2461
                                 interfaces_to_take_down_size,
 
2462
                                 interface))){
 
2463
        ret_errno = take_down_interface(interface);
 
2464
        if(ret_errno != 0){
 
2465
          errno = ret_errno;
 
2466
          perror_plus("Failed to take down interface");
2267
2467
        }
2268
2468
      }
2269
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2270
 
      if(ret == -1){
2271
 
        perror_plus("close");
2272
 
      }
2273
 
      /* Lower privileges permanently */
2274
 
      errno = 0;
2275
 
      ret = setuid(uid);
2276
 
      if(ret == -1){
2277
 
        perror_plus("setuid");
 
2469
      if(debug and (interfaces_to_take_down == NULL)){
 
2470
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2471
                     " down\n");
2278
2472
      }
2279
2473
    }
 
2474
    
 
2475
    lower_privileges_permanently();
2280
2476
  }
2281
2477
  
 
2478
  free(interfaces_to_take_down);
 
2479
  free(interfaces_hooks);
 
2480
  
2282
2481
  /* Removes the GPGME temp directory and all files inside */
2283
2482
  if(tempdir_created){
2284
2483
    struct dirent **direntries = NULL;
2297
2496
        }
2298
2497
        ret = remove(fullname);
2299
2498
        if(ret == -1){
2300
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2301
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2499
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2500
                       strerror(errno));
2302
2501
        }
2303
2502
        free(fullname);
2304
2503
      }