/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-10-28 10:04:05 UTC
  • Revision ID: teddy@recompile.se-20131028100405-u6miovq7y39m69x7
Doc fix: Refer to architecture libdir.

* debian/mandos-client.README.Debian: Refer to architecture libdir.

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