/mandos/release

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

« back to all changes in this revision

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

* plugins.d/mandos-client.c (SYNOPSIS, OPTIONS): Document
                                                 "--network-hook-dir"
                                                 option.

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
66
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
76
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
79
80
                                   argp_state, struct argp,
84
85
                                   raise() */
85
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
87
90
 
88
91
#ifdef __linux__
89
92
#include <sys/klog.h>           /* klogctl() */
122
125
#define PATHDIR "/conf/conf.d/mandos"
123
126
#define SECKEY "seckey.txt"
124
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
125
129
 
126
130
bool debug = false;
127
131
static const char mandos_protocol_version[] = "1";
128
132
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
130
134
static const char sys_class_net[] = "/sys/class/net";
131
135
char *connect_to = NULL;
 
136
const char *hookdir = HOOKDIR;
 
137
 
 
138
/* Doubly linked list that need to be circularly linked when used */
 
139
typedef struct server{
 
140
  const char *ip;
 
141
  uint16_t port;
 
142
  AvahiIfIndex if_index;
 
143
  int af;
 
144
  struct timespec last_seen;
 
145
  struct server *next;
 
146
  struct server *prev;
 
147
} server;
132
148
 
133
149
/* Used for passing in values through the Avahi callback functions */
134
150
typedef struct {
139
155
  gnutls_dh_params_t dh_params;
140
156
  const char *priority;
141
157
  gpgme_ctx_t ctx;
 
158
  server *current_server;
142
159
} mandos_context;
143
160
 
144
161
/* global context so signal handler can reach it*/
145
162
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
163
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
164
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
165
                      .current_server = NULL };
148
166
 
149
167
sig_atomic_t quit_now = 0;
150
168
int signal_received = 0;
151
169
 
 
170
/* Function to use when printing errors */
 
171
void perror_plus(const char *print_text){
 
172
  fprintf(stderr, "Mandos plugin %s: ",
 
173
          program_invocation_short_name);
 
174
  perror(print_text);
 
175
}
 
176
 
152
177
/*
153
178
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
179
 * bytes. "buffer_capacity" is how much is currently allocated,
166
191
  return buffer_capacity;
167
192
}
168
193
 
 
194
/* Add server to set of servers to retry periodically */
 
195
int add_server(const char *ip, uint16_t port,
 
196
                 AvahiIfIndex if_index,
 
197
                 int af){
 
198
  int ret;
 
199
  server *new_server = malloc(sizeof(server));
 
200
  if(new_server == NULL){
 
201
    perror_plus("malloc");
 
202
    return -1;
 
203
  }
 
204
  *new_server = (server){ .ip = strdup(ip),
 
205
                         .port = port,
 
206
                         .if_index = if_index,
 
207
                         .af = af };
 
208
  if(new_server->ip == NULL){
 
209
    perror_plus("strdup");
 
210
    return -1;
 
211
  }
 
212
  /* Special case of first server */
 
213
  if (mc.current_server == NULL){
 
214
    new_server->next = new_server;
 
215
    new_server->prev = new_server;
 
216
    mc.current_server = new_server;
 
217
  /* Place the new server last in the list */
 
218
  } else {
 
219
    new_server->next = mc.current_server;
 
220
    new_server->prev = mc.current_server->prev;
 
221
    new_server->prev->next = new_server;
 
222
    mc.current_server->prev = new_server;
 
223
  }
 
224
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
225
  if(ret == -1){
 
226
    perror_plus("clock_gettime");
 
227
    return -1;
 
228
  }
 
229
  return 0;
 
230
}
 
231
 
169
232
/* 
170
233
 * Initialize GPGME.
171
234
 */
185
248
    
186
249
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
250
    if(fd == -1){
188
 
      perror("open");
 
251
      perror_plus("open");
189
252
      return false;
190
253
    }
191
254
    
192
255
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
193
256
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
257
      fprintf(stderr, "Mandos plugin mandos-client: "
 
258
              "bad gpgme_data_new_from_fd: %s: %s\n",
195
259
              gpgme_strsource(rc), gpgme_strerror(rc));
196
260
      return false;
197
261
    }
198
262
    
199
263
    rc = gpgme_op_import(mc.ctx, pgp_data);
200
264
    if(rc != GPG_ERR_NO_ERROR){
201
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
265
      fprintf(stderr, "Mandos plugin mandos-client: "
 
266
              "bad gpgme_op_import: %s: %s\n",
202
267
              gpgme_strsource(rc), gpgme_strerror(rc));
203
268
      return false;
204
269
    }
205
270
    
206
271
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
272
    if(ret == -1){
208
 
      perror("close");
 
273
      perror_plus("close");
209
274
    }
210
275
    gpgme_data_release(pgp_data);
211
276
    return true;
212
277
  }
213
278
  
214
279
  if(debug){
215
 
    fprintf(stderr, "Initializing GPGME\n");
 
280
    fprintf(stderr, "Mandos plugin mandos-client: "
 
281
            "Initializing GPGME\n");
216
282
  }
217
283
  
218
284
  /* Init GPGME */
219
285
  gpgme_check_version(NULL);
220
286
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
221
287
  if(rc != GPG_ERR_NO_ERROR){
222
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
288
    fprintf(stderr, "Mandos plugin mandos-client: "
 
289
            "bad gpgme_engine_check_version: %s: %s\n",
223
290
            gpgme_strsource(rc), gpgme_strerror(rc));
224
291
    return false;
225
292
  }
226
293
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
294
  /* Set GPGME home directory for the OpenPGP engine only */
228
295
  rc = gpgme_get_engine_info(&engine_info);
229
296
  if(rc != GPG_ERR_NO_ERROR){
230
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
297
    fprintf(stderr, "Mandos plugin mandos-client: "
 
298
            "bad gpgme_get_engine_info: %s: %s\n",
231
299
            gpgme_strsource(rc), gpgme_strerror(rc));
232
300
    return false;
233
301
  }
240
308
    engine_info = engine_info->next;
241
309
  }
242
310
  if(engine_info == NULL){
243
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
311
    fprintf(stderr, "Mandos plugin mandos-client: "
 
312
            "Could not set GPGME home dir to %s\n", tempdir);
244
313
    return false;
245
314
  }
246
315
  
247
316
  /* Create new GPGME "context" */
248
317
  rc = gpgme_new(&(mc.ctx));
249
318
  if(rc != GPG_ERR_NO_ERROR){
250
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
251
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
319
    fprintf(stderr, "Mandos plugin mandos-client: "
 
320
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
321
            gpgme_strerror(rc));
252
322
    return false;
253
323
  }
254
324
  
273
343
  ssize_t plaintext_length = 0;
274
344
  
275
345
  if(debug){
276
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
346
    fprintf(stderr, "Mandos plugin mandos-client: "
 
347
            "Trying to decrypt OpenPGP data\n");
277
348
  }
278
349
  
279
350
  /* Create new GPGME data buffer from memory cryptotext */
280
351
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
281
352
                               0);
282
353
  if(rc != GPG_ERR_NO_ERROR){
283
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
354
    fprintf(stderr, "Mandos plugin mandos-client: "
 
355
            "bad gpgme_data_new_from_mem: %s: %s\n",
284
356
            gpgme_strsource(rc), gpgme_strerror(rc));
285
357
    return -1;
286
358
  }
288
360
  /* Create new empty GPGME data buffer for the plaintext */
289
361
  rc = gpgme_data_new(&dh_plain);
290
362
  if(rc != GPG_ERR_NO_ERROR){
291
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
363
    fprintf(stderr, "Mandos plugin mandos-client: "
 
364
            "bad gpgme_data_new: %s: %s\n",
292
365
            gpgme_strsource(rc), gpgme_strerror(rc));
293
366
    gpgme_data_release(dh_crypto);
294
367
    return -1;
298
371
     data buffer */
299
372
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
300
373
  if(rc != GPG_ERR_NO_ERROR){
301
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
374
    fprintf(stderr, "Mandos plugin mandos-client: "
 
375
            "bad gpgme_op_decrypt: %s: %s\n",
302
376
            gpgme_strsource(rc), gpgme_strerror(rc));
303
377
    plaintext_length = -1;
304
378
    if(debug){
305
379
      gpgme_decrypt_result_t result;
306
380
      result = gpgme_op_decrypt_result(mc.ctx);
307
381
      if(result == NULL){
308
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
382
        fprintf(stderr, "Mandos plugin mandos-client: "
 
383
                "gpgme_op_decrypt_result failed\n");
309
384
      } else {
310
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
385
        fprintf(stderr, "Mandos plugin mandos-client: "
 
386
                "Unsupported algorithm: %s\n",
311
387
                result->unsupported_algorithm);
312
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
388
        fprintf(stderr, "Mandos plugin mandos-client: "
 
389
                "Wrong key usage: %u\n",
313
390
                result->wrong_key_usage);
314
391
        if(result->file_name != NULL){
315
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
392
          fprintf(stderr, "Mandos plugin mandos-client: "
 
393
                  "File name: %s\n", result->file_name);
316
394
        }
317
395
        gpgme_recipient_t recipient;
318
396
        recipient = result->recipients;
319
397
        while(recipient != NULL){
320
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
398
          fprintf(stderr, "Mandos plugin mandos-client: "
 
399
                  "Public key algorithm: %s\n",
321
400
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
322
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
323
 
          fprintf(stderr, "Secret key available: %s\n",
 
401
          fprintf(stderr, "Mandos plugin mandos-client: "
 
402
                  "Key ID: %s\n", recipient->keyid);
 
403
          fprintf(stderr, "Mandos plugin mandos-client: "
 
404
                  "Secret key available: %s\n",
324
405
                  recipient->status == GPG_ERR_NO_SECKEY
325
406
                  ? "No" : "Yes");
326
407
          recipient = recipient->next;
331
412
  }
332
413
  
333
414
  if(debug){
334
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
415
    fprintf(stderr, "Mandos plugin mandos-client: "
 
416
            "Decryption of OpenPGP data succeeded\n");
335
417
  }
336
418
  
337
419
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
420
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
 
421
    perror_plus("gpgme_data_seek");
340
422
    plaintext_length = -1;
341
423
    goto decrypt_end;
342
424
  }
347
429
                                      (size_t)plaintext_length,
348
430
                                      plaintext_capacity);
349
431
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
 
432
        perror_plus("incbuffer");
351
433
        plaintext_length = -1;
352
434
        goto decrypt_end;
353
435
    }
360
442
      break;
361
443
    }
362
444
    if(ret < 0){
363
 
      perror("gpgme_data_read");
 
445
      perror_plus("gpgme_data_read");
364
446
      plaintext_length = -1;
365
447
      goto decrypt_end;
366
448
    }
368
450
  }
369
451
  
370
452
  if(debug){
371
 
    fprintf(stderr, "Decrypted password is: ");
 
453
    fprintf(stderr, "Mandos plugin mandos-client: "
 
454
            "Decrypted password is: ");
372
455
    for(ssize_t i = 0; i < plaintext_length; i++){
373
456
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
374
457
    }
396
479
/* GnuTLS log function callback */
397
480
static void debuggnutls(__attribute__((unused)) int level,
398
481
                        const char* string){
399
 
  fprintf(stderr, "GnuTLS: %s", string);
 
482
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
400
483
}
401
484
 
402
485
static int init_gnutls_global(const char *pubkeyfilename,
404
487
  int ret;
405
488
  
406
489
  if(debug){
407
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
490
    fprintf(stderr, "Mandos plugin mandos-client: "
 
491
            "Initializing GnuTLS\n");
408
492
  }
409
493
  
410
494
  ret = gnutls_global_init();
411
495
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
413
 
            safer_gnutls_strerror(ret));
 
496
    fprintf(stderr, "Mandos plugin mandos-client: "
 
497
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
414
498
    return -1;
415
499
  }
416
500
  
423
507
  }
424
508
  
425
509
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
510
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
511
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
432
 
            safer_gnutls_strerror(ret));
 
512
    fprintf(stderr, "Mandos plugin mandos-client: "
 
513
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
433
514
    gnutls_global_deinit();
434
515
    return -1;
435
516
  }
436
517
  
437
518
  if(debug){
438
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
519
    fprintf(stderr, "Mandos plugin mandos-client: "
 
520
            "Attempting to use OpenPGP public key %s and"
439
521
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
440
522
            seckeyfilename);
441
523
  }
445
527
     GNUTLS_OPENPGP_FMT_BASE64);
446
528
  if(ret != GNUTLS_E_SUCCESS){
447
529
    fprintf(stderr,
 
530
            "Mandos plugin mandos-client: "
448
531
            "Error[%d] while reading the OpenPGP key pair ('%s',"
449
532
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
450
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
451
 
            safer_gnutls_strerror(ret));
 
533
    fprintf(stderr, "Mandos plugin mandos-client: "
 
534
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
452
535
    goto globalfail;
453
536
  }
454
537
  
455
538
  /* GnuTLS server initialization */
456
539
  ret = gnutls_dh_params_init(&mc.dh_params);
457
540
  if(ret != GNUTLS_E_SUCCESS){
458
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
541
    fprintf(stderr, "Mandos plugin mandos-client: "
 
542
            "Error in GnuTLS DH parameter initialization:"
459
543
            " %s\n", safer_gnutls_strerror(ret));
460
544
    goto globalfail;
461
545
  }
462
546
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
463
547
  if(ret != GNUTLS_E_SUCCESS){
464
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
548
    fprintf(stderr, "Mandos plugin mandos-client: "
 
549
            "Error in GnuTLS prime generation: %s\n",
465
550
            safer_gnutls_strerror(ret));
466
551
    goto globalfail;
467
552
  }
488
573
    }
489
574
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
490
575
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
576
    fprintf(stderr, "Mandos plugin mandos-client: "
 
577
            "Error in GnuTLS session initialization: %s\n",
492
578
            safer_gnutls_strerror(ret));
493
579
  }
494
580
  
502
588
      }
503
589
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
504
590
    if(ret != GNUTLS_E_SUCCESS){
505
 
      fprintf(stderr, "Syntax error at: %s\n", err);
506
 
      fprintf(stderr, "GnuTLS error: %s\n",
507
 
              safer_gnutls_strerror(ret));
 
591
      fprintf(stderr, "Mandos plugin mandos-client: "
 
592
              "Syntax error at: %s\n", err);
 
593
      fprintf(stderr, "Mandos plugin mandos-client: "
 
594
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
508
595
      gnutls_deinit(*session);
509
596
      return -1;
510
597
    }
519
606
    }
520
607
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
521
608
  if(ret != GNUTLS_E_SUCCESS){
522
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
609
    fprintf(stderr, "Mandos plugin mandos-client: "
 
610
            "Error setting GnuTLS credentials: %s\n",
523
611
            safer_gnutls_strerror(ret));
524
612
    gnutls_deinit(*session);
525
613
    return -1;
571
659
    pf = PF_INET;
572
660
    break;
573
661
  default:
574
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
662
    fprintf(stderr, "Mandos plugin mandos-client: "
 
663
            "Bad address family: %d\n", af);
575
664
    errno = EINVAL;
576
665
    return -1;
577
666
  }
582
671
  }
583
672
  
584
673
  if(debug){
585
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
674
    fprintf(stderr, "Mandos plugin mandos-client: "
 
675
            "Setting up a TCP connection to %s, port %" PRIu16
586
676
            "\n", ip, port);
587
677
  }
588
678
  
589
679
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
680
  if(tcp_sd < 0){
591
681
    int e = errno;
592
 
    perror("socket");
 
682
    perror_plus("socket");
593
683
    errno = e;
594
684
    goto mandos_end;
595
685
  }
609
699
  }
610
700
  if(ret < 0 ){
611
701
    int e = errno;
612
 
    perror("inet_pton");
 
702
    perror_plus("inet_pton");
613
703
    errno = e;
614
704
    goto mandos_end;
615
705
  }
616
706
  if(ret == 0){
617
707
    int e = errno;
618
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
708
    fprintf(stderr, "Mandos plugin mandos-client: "
 
709
            "Bad address: %s\n", ip);
619
710
    errno = e;
620
711
    goto mandos_end;
621
712
  }
628
719
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
629
720
                              -Wunreachable-code*/
630
721
      if(if_index == AVAHI_IF_UNSPEC){
631
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
722
        fprintf(stderr, "Mandos plugin mandos-client: "
 
723
                "An IPv6 link-local address is incomplete"
632
724
                " without a network interface\n");
633
725
        errno = EINVAL;
634
726
        goto mandos_end;
651
743
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
744
      char interface[IF_NAMESIZE];
653
745
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
 
746
        perror_plus("if_indextoname");
655
747
      } else {
656
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
748
        fprintf(stderr, "Mandos plugin mandos-client: "
 
749
                "Connection to: %s%%%s, port %" PRIu16 "\n",
657
750
                ip, interface, port);
658
751
      }
659
752
    } else {
660
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
661
 
              port);
 
753
      fprintf(stderr, "Mandos plugin mandos-client: "
 
754
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
662
755
    }
663
756
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
664
757
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
671
764
                        sizeof(addrstr));
672
765
    }
673
766
    if(pcret == NULL){
674
 
      perror("inet_ntop");
 
767
      perror_plus("inet_ntop");
675
768
    } else {
676
769
      if(strcmp(addrstr, ip) != 0){
677
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
770
        fprintf(stderr, "Mandos plugin mandos-client: "
 
771
                "Canonical address form: %s\n", addrstr);
678
772
      }
679
773
    }
680
774
  }
692
786
  if(ret < 0){
693
787
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
788
      int e = errno;
695
 
      perror("connect");
 
789
      perror_plus("connect");
696
790
      errno = e;
697
791
    }
698
792
    goto mandos_end;
711
805
                                   out_size - written));
712
806
    if(ret == -1){
713
807
      int e = errno;
714
 
      perror("write");
 
808
      perror_plus("write");
715
809
      errno = e;
716
810
      goto mandos_end;
717
811
    }
734
828
  }
735
829
  
736
830
  if(debug){
737
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
831
    fprintf(stderr, "Mandos plugin mandos-client: "
 
832
            "Establishing TLS session with %s\n", ip);
738
833
  }
739
834
  
740
835
  if(quit_now){
742
837
    goto mandos_end;
743
838
  }
744
839
  
 
840
  /* Spurious warning from -Wint-to-pointer-cast */
745
841
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
842
  
747
843
  if(quit_now){
759
855
  
760
856
  if(ret != GNUTLS_E_SUCCESS){
761
857
    if(debug){
762
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
858
      fprintf(stderr, "Mandos plugin mandos-client: "
 
859
              "*** GnuTLS Handshake failed ***\n");
763
860
      gnutls_perror(ret);
764
861
    }
765
862
    errno = EPROTO;
769
866
  /* Read OpenPGP packet that contains the wanted password */
770
867
  
771
868
  if(debug){
772
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
773
 
            ip);
 
869
    fprintf(stderr, "Mandos plugin mandos-client: "
 
870
            "Retrieving OpenPGP encrypted password from %s\n", ip);
774
871
  }
775
872
  
776
873
  while(true){
784
881
                                   buffer_capacity);
785
882
    if(buffer_capacity == 0){
786
883
      int e = errno;
787
 
      perror("incbuffer");
 
884
      perror_plus("incbuffer");
788
885
      errno = e;
789
886
      goto mandos_end;
790
887
    }
814
911
          }
815
912
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
816
913
        if(ret < 0){
817
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
914
          fprintf(stderr, "Mandos plugin mandos-client: "
 
915
                  "*** GnuTLS Re-handshake failed ***\n");
818
916
          gnutls_perror(ret);
819
917
          errno = EPROTO;
820
918
          goto mandos_end;
821
919
        }
822
920
        break;
823
921
      default:
824
 
        fprintf(stderr, "Unknown error while reading data from"
 
922
        fprintf(stderr, "Mandos plugin mandos-client: "
 
923
                "Unknown error while reading data from"
825
924
                " encrypted session with Mandos server\n");
826
925
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
827
926
        errno = EIO;
833
932
  }
834
933
  
835
934
  if(debug){
836
 
    fprintf(stderr, "Closing TLS session\n");
 
935
    fprintf(stderr, "Mandos plugin mandos-client: "
 
936
            "Closing TLS session\n");
837
937
  }
838
938
  
839
939
  if(quit_now){
869
969
        if(ret == 0 and ferror(stdout)){
870
970
          int e = errno;
871
971
          if(debug){
872
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
972
            fprintf(stderr, "Mandos plugin mandos-client: "
 
973
                    "Error writing encrypted data: %s\n",
873
974
                    strerror(errno));
874
975
          }
875
976
          errno = e;
895
996
      if(e == 0){
896
997
        e = errno;
897
998
      }
898
 
      perror("close");
 
999
      perror_plus("close");
899
1000
    }
900
1001
    gnutls_deinit(session);
 
1002
    errno = e;
901
1003
    if(quit_now){
902
 
      e = EINTR;
 
1004
      errno = EINTR;
903
1005
      retval = -1;
904
1006
    }
905
 
    errno = e;
906
1007
  }
907
1008
  return retval;
908
1009
}
933
1034
  switch(event){
934
1035
  default:
935
1036
  case AVAHI_RESOLVER_FAILURE:
936
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
1037
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1038
            "(Avahi Resolver) Failed to resolve service '%s'"
937
1039
            " of type '%s' in domain '%s': %s\n", name, type, domain,
938
1040
            avahi_strerror(avahi_server_errno(mc.server)));
939
1041
    break;
943
1045
      char ip[AVAHI_ADDRESS_STR_MAX];
944
1046
      avahi_address_snprint(ip, sizeof(ip), address);
945
1047
      if(debug){
946
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1048
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1049
                "Mandos server \"%s\" found on %s (%s, %"
947
1050
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
948
1051
                ip, (intmax_t)interface, port);
949
1052
      }
951
1054
                                           avahi_proto_to_af(proto));
952
1055
      if(ret == 0){
953
1056
        avahi_simple_poll_quit(mc.simple_poll);
 
1057
      } else {
 
1058
        ret = add_server(ip, port, interface,
 
1059
                         avahi_proto_to_af(proto));
954
1060
      }
955
1061
    }
956
1062
  }
980
1086
  default:
981
1087
  case AVAHI_BROWSER_FAILURE:
982
1088
    
983
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1089
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1090
            "(Avahi browser) %s\n",
984
1091
            avahi_strerror(avahi_server_errno(mc.server)));
985
1092
    avahi_simple_poll_quit(mc.simple_poll);
986
1093
    return;
994
1101
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
995
1102
                                    name, type, domain, protocol, 0,
996
1103
                                    resolve_callback, NULL) == NULL)
997
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1104
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1105
              "Avahi: Failed to resolve service '%s': %s\n",
998
1106
              name, avahi_strerror(avahi_server_errno(mc.server)));
999
1107
    break;
1000
1108
    
1004
1112
  case AVAHI_BROWSER_ALL_FOR_NOW:
1005
1113
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1006
1114
    if(debug){
1007
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1115
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1116
              "No Mandos server found, still searching...\n");
1008
1117
    }
1009
1118
    break;
1010
1119
  }
1011
1120
}
1012
1121
 
1013
 
/* stop main loop after sigterm has been called */
 
1122
/* Signal handler that stops main loop after SIGTERM */
1014
1123
static void handle_sigterm(int sig){
1015
1124
  if(quit_now){
1016
1125
    return;
1018
1127
  quit_now = 1;
1019
1128
  signal_received = sig;
1020
1129
  int old_errno = errno;
 
1130
  /* set main loop to exit */
1021
1131
  if(mc.simple_poll != NULL){
1022
1132
    avahi_simple_poll_quit(mc.simple_poll);
1023
1133
  }
1024
1134
  errno = old_errno;
1025
1135
}
1026
1136
 
1027
 
/* 
1028
 
 * This function determines if a directory entry in /sys/class/net
1029
 
 * corresponds to an acceptable network device.
1030
 
 * (This function is passed to scandir(3) as a filter function.)
1031
 
 */
1032
 
int good_interface(const struct dirent *if_entry){
1033
 
  ssize_t ssret;
1034
 
  char *flagname = NULL;
1035
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
 
                     if_entry->d_name);
1037
 
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
1041
 
  if(if_entry->d_name[0] == '.'){
1042
 
    return 0;
1043
 
  }
1044
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1045
 
  if(flags_fd == -1){
1046
 
    perror("open");
1047
 
    return 0;
1048
 
  }
1049
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1050
 
  /* read line from flags_fd */
1051
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
1052
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1053
 
  flagstring[(size_t)to_read] = '\0';
1054
 
  if(flagstring == NULL){
1055
 
    perror("malloc");
1056
 
    close(flags_fd);
1057
 
    return 0;
1058
 
  }
1059
 
  while(to_read > 0){
1060
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1061
 
                                             (size_t)to_read));
1062
 
    if(ssret == -1){
1063
 
      perror("read");
1064
 
      free(flagstring);
1065
 
      close(flags_fd);
1066
 
      return 0;
1067
 
    }
1068
 
    to_read -= ssret;
1069
 
    if(ssret == 0){
1070
 
      break;
1071
 
    }
1072
 
  }
1073
 
  close(flags_fd);
1074
 
  intmax_t tmpmax;
1075
 
  char *tmp;
1076
 
  errno = 0;
1077
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1078
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1079
 
                                         and not (isspace(*tmp)))
1080
 
     or tmpmax != (ifreq_flags)tmpmax){
 
1137
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1138
  int ret;
 
1139
  
 
1140
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1141
  if(s < 0){
 
1142
    perror_plus("socket");
 
1143
    return false;
 
1144
  }
 
1145
  strcpy(ifr->ifr_name, ifname);
 
1146
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1147
  if(ret == -1){
1081
1148
    if(debug){
1082
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1083
 
              flagstring, if_entry->d_name);
 
1149
      perror_plus("ioctl SIOCGIFFLAGS");
1084
1150
    }
1085
 
    free(flagstring);
1086
 
    return 0;
 
1151
    return false;
1087
1152
  }
1088
 
  free(flagstring);
1089
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1153
  return true;
 
1154
}
 
1155
 
 
1156
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1157
  
1090
1158
  /* Reject the loopback device */
1091
 
  if(flags & IFF_LOOPBACK){
 
1159
  if(ifr->ifr_flags & IFF_LOOPBACK){
1092
1160
    if(debug){
1093
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1094
 
              if_entry->d_name);
 
1161
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1162
              "Rejecting loopback interface \"%s\"\n", ifname);
1095
1163
    }
1096
 
    return 0;
 
1164
    return false;
1097
1165
  }
1098
1166
  /* Accept point-to-point devices only if connect_to is specified */
1099
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1167
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1100
1168
    if(debug){
1101
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1102
 
              if_entry->d_name);
 
1169
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1170
              "Accepting point-to-point interface \"%s\"\n", ifname);
1103
1171
    }
1104
 
    return 1;
 
1172
    return true;
1105
1173
  }
1106
1174
  /* Otherwise, reject non-broadcast-capable devices */
1107
 
  if(not (flags & IFF_BROADCAST)){
1108
 
    if(debug){
1109
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1110
 
              if_entry->d_name);
1111
 
    }
1112
 
    return 0;
1113
 
  }
 
1175
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1176
    if(debug){
 
1177
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1178
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1179
    }
 
1180
    return false;
 
1181
  }
 
1182
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1183
  if(ifr->ifr_flags & IFF_NOARP){
 
1184
    if(debug){
 
1185
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1186
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1187
    }
 
1188
    return false;
 
1189
  }
 
1190
  
1114
1191
  /* Accept this device */
1115
1192
  if(debug){
1116
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1117
 
            if_entry->d_name);
1118
 
  }
1119
 
  return 1;
 
1193
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1194
            "Interface \"%s\" is good\n", ifname);
 
1195
  }
 
1196
  return true;
 
1197
}
 
1198
 
 
1199
/* 
 
1200
 * This function determines if a directory entry in /sys/class/net
 
1201
 * corresponds to an acceptable network device.
 
1202
 * (This function is passed to scandir(3) as a filter function.)
 
1203
 */
 
1204
int good_interface(const struct dirent *if_entry){
 
1205
  if(if_entry->d_name[0] == '.'){
 
1206
    return 0;
 
1207
  }
 
1208
  
 
1209
  struct ifreq ifr;
 
1210
  if(not get_flags(if_entry->d_name, &ifr)){
 
1211
    if(debug){
 
1212
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1213
              "Failed to get flags for interface \"%s\"\n",
 
1214
              if_entry->d_name);
 
1215
    }
 
1216
    return 0;
 
1217
  }
 
1218
  
 
1219
  if(not good_flags(if_entry->d_name, &ifr)){
 
1220
    return 0;
 
1221
  }
 
1222
  return 1;
 
1223
}
 
1224
 
 
1225
/* 
 
1226
 * This function determines if a directory entry in /sys/class/net
 
1227
 * corresponds to an acceptable network device which is up.
 
1228
 * (This function is passed to scandir(3) as a filter function.)
 
1229
 */
 
1230
int up_interface(const struct dirent *if_entry){
 
1231
  if(if_entry->d_name[0] == '.'){
 
1232
    return 0;
 
1233
  }
 
1234
  
 
1235
  struct ifreq ifr;
 
1236
  if(not get_flags(if_entry->d_name, &ifr)){
 
1237
    if(debug){
 
1238
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1239
              "Failed to get flags for interface \"%s\"\n",
 
1240
              if_entry->d_name);
 
1241
    }
 
1242
    return 0;
 
1243
  }
 
1244
  
 
1245
  /* Reject down interfaces */
 
1246
  if(not (ifr.ifr_flags & IFF_UP)){
 
1247
    if(debug){
 
1248
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1249
              "Rejecting down interface \"%s\"\n",
 
1250
              if_entry->d_name);
 
1251
    }
 
1252
    return 0;
 
1253
  }
 
1254
  
 
1255
  /* Reject non-running interfaces */
 
1256
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1257
    if(debug){
 
1258
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1259
              "Rejecting non-running interface \"%s\"\n",
 
1260
              if_entry->d_name);
 
1261
    }
 
1262
    return 0;
 
1263
  }
 
1264
  
 
1265
  if(not good_flags(if_entry->d_name, &ifr)){
 
1266
    return 0;
 
1267
  }
 
1268
  return 1;
 
1269
}
 
1270
 
 
1271
int notdotentries(const struct dirent *direntry){
 
1272
  /* Skip "." and ".." */
 
1273
  if(direntry->d_name[0] == '.'
 
1274
     and (direntry->d_name[1] == '\0'
 
1275
          or (direntry->d_name[1] == '.'
 
1276
              and direntry->d_name[2] == '\0'))){
 
1277
    return 0;
 
1278
  }
 
1279
  return 1;
 
1280
}
 
1281
 
 
1282
/* Is this directory entry a runnable program? */
 
1283
int runnable_hook(const struct dirent *direntry){
 
1284
  int ret;
 
1285
  struct stat st;
 
1286
  
 
1287
  if((direntry->d_name)[0] == '\0'){
 
1288
    /* Empty name? */
 
1289
    return 0;
 
1290
  }
 
1291
  
 
1292
  /* Save pointer to last character */
 
1293
  char *end = strchr(direntry->d_name, '\0')-1;
 
1294
  
 
1295
  if(*end == '~'){
 
1296
    /* Backup name~ */
 
1297
    return 0;
 
1298
  }
 
1299
  
 
1300
  if(((direntry->d_name)[0] == '#')
 
1301
     and (*end == '#')){
 
1302
    /* Temporary #name# */
 
1303
    return 0;
 
1304
  }
 
1305
  
 
1306
  /* XXX more rules here */
 
1307
  
 
1308
  char *fullname = NULL;
 
1309
  ret = asprintf(&fullname, "%s/%s", hookdir,
 
1310
                 direntry->d_name);
 
1311
  if(ret < 0){
 
1312
    perror_plus("asprintf");
 
1313
    return 0;
 
1314
  }
 
1315
  
 
1316
  ret = stat(fullname, &st);
 
1317
  if(ret == -1){
 
1318
    if(debug){
 
1319
      perror_plus("Could not stat plugin");
 
1320
    }
 
1321
    return 0;
 
1322
  }
 
1323
  if(not (S_ISREG(st.st_mode))){
 
1324
    /* Not a regular file */
 
1325
    return 0;
 
1326
  }
 
1327
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1328
    /* Not executable */
 
1329
    return 0;
 
1330
  }
 
1331
  return 1;
 
1332
}
 
1333
 
 
1334
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1335
  int ret;
 
1336
  struct timespec now;
 
1337
  struct timespec waited_time;
 
1338
  intmax_t block_time;
 
1339
  
 
1340
  while(true){
 
1341
    if(mc.current_server == NULL){
 
1342
      if (debug){
 
1343
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1344
                "Wait until first server is found. No timeout!\n");
 
1345
      }
 
1346
      ret = avahi_simple_poll_iterate(s, -1);
 
1347
    } else {
 
1348
      if (debug){
 
1349
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1350
                "Check current_server if we should run it,"
 
1351
                " or wait\n");
 
1352
      }
 
1353
      /* the current time */
 
1354
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1355
      if(ret == -1){
 
1356
        perror_plus("clock_gettime");
 
1357
        return -1;
 
1358
      }
 
1359
      /* Calculating in ms how long time between now and server
 
1360
         who we visted longest time ago. Now - last seen.  */
 
1361
      waited_time.tv_sec = (now.tv_sec
 
1362
                            - mc.current_server->last_seen.tv_sec);
 
1363
      waited_time.tv_nsec = (now.tv_nsec
 
1364
                             - mc.current_server->last_seen.tv_nsec);
 
1365
      /* total time is 10s/10,000ms.
 
1366
         Converting to s from ms by dividing by 1,000,
 
1367
         and ns to ms by dividing by 1,000,000. */
 
1368
      block_time = ((retry_interval
 
1369
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1370
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1371
      
 
1372
      if (debug){
 
1373
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1374
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1375
      }
 
1376
      
 
1377
      if(block_time <= 0){
 
1378
        ret = start_mandos_communication(mc.current_server->ip,
 
1379
                                         mc.current_server->port,
 
1380
                                         mc.current_server->if_index,
 
1381
                                         mc.current_server->af);
 
1382
        if(ret == 0){
 
1383
          avahi_simple_poll_quit(mc.simple_poll);
 
1384
          return 0;
 
1385
        }
 
1386
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1387
                            &mc.current_server->last_seen);
 
1388
        if(ret == -1){
 
1389
          perror_plus("clock_gettime");
 
1390
          return -1;
 
1391
        }
 
1392
        mc.current_server = mc.current_server->next;
 
1393
        block_time = 0;         /* Call avahi to find new Mandos
 
1394
                                   servers, but don't block */
 
1395
      }
 
1396
      
 
1397
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1398
    }
 
1399
    if(ret != 0){
 
1400
      if (ret > 0 or errno != EINTR){
 
1401
        return (ret != 1) ? ret : 0;
 
1402
      }
 
1403
    }
 
1404
  }
1120
1405
}
1121
1406
 
1122
1407
int main(int argc, char *argv[]){
1141
1426
  bool gnutls_initialized = false;
1142
1427
  bool gpgme_initialized = false;
1143
1428
  float delay = 2.5f;
 
1429
  double retry_interval = 10; /* 10s between trying a server and
 
1430
                                 retrying the same server again */
1144
1431
  
1145
1432
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
1433
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1152
1439
  errno = 0;
1153
1440
  ret = setgid(gid);
1154
1441
  if(ret == -1){
1155
 
    perror("setgid");
 
1442
    perror_plus("setgid");
1156
1443
  }
1157
1444
  
1158
1445
  /* Lower user privileges (temporarily) */
1159
1446
  errno = 0;
1160
1447
  ret = seteuid(uid);
1161
1448
  if(ret == -1){
1162
 
    perror("seteuid");
 
1449
    perror_plus("seteuid");
1163
1450
  }
1164
1451
  
1165
1452
  if(quit_now){
1200
1487
        .arg = "SECONDS",
1201
1488
        .doc = "Maximum delay to wait for interface startup",
1202
1489
        .group = 2 },
 
1490
      { .name = "retry", .key = 132,
 
1491
        .arg = "SECONDS",
 
1492
        .doc = "Retry interval used when denied by the mandos server",
 
1493
        .group = 2 },
 
1494
      { .name = "network-hook-dir", .key = 133,
 
1495
        .arg = "DIR",
 
1496
        .doc = "Directory where network hooks are located",
 
1497
        .group = 2 },
1203
1498
      /*
1204
1499
       * These reproduce what we would get without ARGP_NO_HELP
1205
1500
       */
1249
1544
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
1545
          argp_error(state, "Bad delay");
1251
1546
        }
 
1547
      case 132:                 /* --retry */
 
1548
        errno = 0;
 
1549
        retry_interval = strtod(arg, &tmp);
 
1550
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1551
           or (retry_interval * 1000) > INT_MAX
 
1552
           or retry_interval < 0){
 
1553
          argp_error(state, "Bad retry interval");
 
1554
        }
 
1555
        break;
 
1556
      case 133:                 /* --network-hook-dir */
 
1557
        hookdir = arg;
1252
1558
        break;
1253
1559
        /*
1254
1560
         * These reproduce what we would get without ARGP_NO_HELP
1261
1567
        argp_state_help(state, state->out_stream,
1262
1568
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1263
1569
      case 'V':                 /* --version */
 
1570
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1264
1571
        fprintf(state->out_stream, "%s\n", argp_program_version);
1265
1572
        exit(argp_err_exit_status);
1266
1573
        break;
1282
1589
    case ENOMEM:
1283
1590
    default:
1284
1591
      errno = ret;
1285
 
      perror("argp_parse");
 
1592
      perror_plus("argp_parse");
1286
1593
      exitcode = EX_OSERR;
1287
1594
      goto end;
1288
1595
    case EINVAL:
1290
1597
      goto end;
1291
1598
    }
1292
1599
  }
 
1600
    
 
1601
  {
 
1602
    /* Work around Debian bug #633582:
 
1603
       <http://bugs.debian.org/633582> */
 
1604
    struct stat st;
 
1605
    
 
1606
    /* Re-raise priviliges */
 
1607
    errno = 0;
 
1608
    ret = seteuid(0);
 
1609
    if(ret == -1){
 
1610
      perror_plus("seteuid");
 
1611
    }
 
1612
    
 
1613
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1614
      int seckey_fd = open(seckey, O_RDONLY);
 
1615
      if(seckey_fd == -1){
 
1616
        perror_plus("open");
 
1617
      } else {
 
1618
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1619
        if(ret == -1){
 
1620
          perror_plus("fstat");
 
1621
        } else {
 
1622
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1623
            ret = fchown(seckey_fd, uid, gid);
 
1624
            if(ret == -1){
 
1625
              perror_plus("fchown");
 
1626
            }
 
1627
          }
 
1628
        }
 
1629
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1630
      }
 
1631
    }
 
1632
    
 
1633
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1634
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1635
      if(pubkey_fd == -1){
 
1636
        perror_plus("open");
 
1637
      } else {
 
1638
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1639
        if(ret == -1){
 
1640
          perror_plus("fstat");
 
1641
        } else {
 
1642
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1643
            ret = fchown(pubkey_fd, uid, gid);
 
1644
            if(ret == -1){
 
1645
              perror_plus("fchown");
 
1646
            }
 
1647
          }
 
1648
        }
 
1649
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1650
      }
 
1651
    }
 
1652
    
 
1653
    /* Lower privileges */
 
1654
    errno = 0;
 
1655
    ret = seteuid(uid);
 
1656
    if(ret == -1){
 
1657
      perror_plus("seteuid");
 
1658
    }
 
1659
  }
 
1660
  
 
1661
  /* Find network hooks and run them */
 
1662
  {
 
1663
    struct dirent **direntries;
 
1664
    struct dirent *direntry;
 
1665
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1666
                           alphasort);
 
1667
    if(numhooks == -1){
 
1668
      perror_plus("scandir");
 
1669
    } else {
 
1670
      int devnull = open("/dev/null", O_RDONLY);
 
1671
      for(int i = 0; i < numhooks; i++){
 
1672
        direntry = direntries[0];
 
1673
        char *fullname = NULL;
 
1674
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1675
        if(ret < 0){
 
1676
          perror_plus("asprintf");
 
1677
          continue;
 
1678
        }
 
1679
        pid_t hook_pid = fork();
 
1680
        if(hook_pid == 0){
 
1681
          /* Child */
 
1682
          dup2(devnull, STDIN_FILENO);
 
1683
          close(devnull);
 
1684
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1685
          ret = setenv("DEVICE", interface, 1);
 
1686
          if(ret == -1){
 
1687
            perror_plus("setenv");
 
1688
            exit(1);
 
1689
          }
 
1690
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1691
          if(ret == -1){
 
1692
            perror_plus("setenv");
 
1693
            exit(1);
 
1694
          }
 
1695
          ret = setenv("MODE", "start", 1);
 
1696
          if(ret == -1){
 
1697
            perror_plus("setenv");
 
1698
            exit(1);
 
1699
          }
 
1700
          char *delaystring;
 
1701
          ret = asprintf(&delaystring, "%f", delay);
 
1702
          if(ret == -1){
 
1703
            perror_plus("asprintf");
 
1704
            exit(1);
 
1705
          }
 
1706
          ret = setenv("DELAY", delaystring, 1);
 
1707
          if(ret == -1){
 
1708
            free(delaystring);
 
1709
            perror_plus("setenv");
 
1710
            exit(1);
 
1711
          }
 
1712
          free(delaystring);
 
1713
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1714
          perror_plus("execl");
 
1715
        } else {
 
1716
          int status;
 
1717
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1718
            perror_plus("waitpid");
 
1719
            free(fullname);
 
1720
            continue;
 
1721
          }
 
1722
          if(WIFEXITED(status)){
 
1723
            if(WEXITSTATUS(status) != 0){
 
1724
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1725
                      "Warning: network hook \"%s\" exited"
 
1726
                      " with status %d\n", direntry->d_name,
 
1727
                      WEXITSTATUS(status));
 
1728
              free(fullname);
 
1729
              continue;
 
1730
            }
 
1731
          } else if(WIFSIGNALED(status)){
 
1732
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1733
                    "Warning: network hook \"%s\" died by"
 
1734
                    " signal %d\n", direntry->d_name,
 
1735
                    WTERMSIG(status));
 
1736
            free(fullname);
 
1737
            continue;
 
1738
          } else {
 
1739
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1740
                    "Warning: network hook \"%s\" crashed\n",
 
1741
                    direntry->d_name);
 
1742
            free(fullname);
 
1743
            continue;
 
1744
          }
 
1745
        }
 
1746
        free(fullname);
 
1747
        if(quit_now){
 
1748
          goto end;
 
1749
        }
 
1750
      }
 
1751
      close(devnull);
 
1752
    }
 
1753
  }
1293
1754
  
1294
1755
  if(not debug){
1295
1756
    avahi_set_log_function(empty_log);
1296
1757
  }
1297
 
 
 
1758
  
1298
1759
  if(interface[0] == '\0'){
1299
1760
    struct dirent **direntries;
1300
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1761
    /* First look for interfaces that are up */
 
1762
    ret = scandir(sys_class_net, &direntries, up_interface,
1301
1763
                  alphasort);
 
1764
    if(ret == 0){
 
1765
      /* No up interfaces, look for any good interfaces */
 
1766
      free(direntries);
 
1767
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1768
                    alphasort);
 
1769
    }
1302
1770
    if(ret >= 1){
1303
 
      /* Pick the first good interface */
 
1771
      /* Pick the first interface returned */
1304
1772
      interface = strdup(direntries[0]->d_name);
1305
1773
      if(debug){
1306
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1774
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1775
                "Using interface \"%s\"\n", interface);
1307
1776
      }
1308
1777
      if(interface == NULL){
1309
 
        perror("malloc");
 
1778
        perror_plus("malloc");
1310
1779
        free(direntries);
1311
1780
        exitcode = EXIT_FAILURE;
1312
1781
        goto end;
1314
1783
      free(direntries);
1315
1784
    } else {
1316
1785
      free(direntries);
1317
 
      fprintf(stderr, "Could not find a network interface\n");
 
1786
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1787
              "Could not find a network interface\n");
1318
1788
      exitcode = EXIT_FAILURE;
1319
1789
      goto end;
1320
1790
    }
1326
1796
  srand((unsigned int) time(NULL));
1327
1797
  mc.simple_poll = avahi_simple_poll_new();
1328
1798
  if(mc.simple_poll == NULL){
1329
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1799
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1800
            "Avahi: Failed to create simple poll object.\n");
1330
1801
    exitcode = EX_UNAVAILABLE;
1331
1802
    goto end;
1332
1803
  }
1334
1805
  sigemptyset(&sigterm_action.sa_mask);
1335
1806
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
1807
  if(ret == -1){
1337
 
    perror("sigaddset");
 
1808
    perror_plus("sigaddset");
1338
1809
    exitcode = EX_OSERR;
1339
1810
    goto end;
1340
1811
  }
1341
1812
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
1813
  if(ret == -1){
1343
 
    perror("sigaddset");
 
1814
    perror_plus("sigaddset");
1344
1815
    exitcode = EX_OSERR;
1345
1816
    goto end;
1346
1817
  }
1347
1818
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
1819
  if(ret == -1){
1349
 
    perror("sigaddset");
 
1820
    perror_plus("sigaddset");
1350
1821
    exitcode = EX_OSERR;
1351
1822
    goto end;
1352
1823
  }
1356
1827
  */
1357
1828
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
1829
  if(ret == -1){
1359
 
    perror("sigaction");
 
1830
    perror_plus("sigaction");
1360
1831
    return EX_OSERR;
1361
1832
  }
1362
1833
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
1834
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
1835
    if(ret == -1){
1365
 
      perror("sigaction");
 
1836
      perror_plus("sigaction");
1366
1837
      exitcode = EX_OSERR;
1367
1838
      goto end;
1368
1839
    }
1369
1840
  }
1370
1841
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
1842
  if(ret == -1){
1372
 
    perror("sigaction");
 
1843
    perror_plus("sigaction");
1373
1844
    return EX_OSERR;
1374
1845
  }
1375
1846
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
1847
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
1848
    if(ret == -1){
1378
 
      perror("sigaction");
 
1849
      perror_plus("sigaction");
1379
1850
      exitcode = EX_OSERR;
1380
1851
      goto end;
1381
1852
    }
1382
1853
  }
1383
1854
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
1855
  if(ret == -1){
1385
 
    perror("sigaction");
 
1856
    perror_plus("sigaction");
1386
1857
    return EX_OSERR;
1387
1858
  }
1388
1859
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
1860
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
1861
    if(ret == -1){
1391
 
      perror("sigaction");
 
1862
      perror_plus("sigaction");
1392
1863
      exitcode = EX_OSERR;
1393
1864
      goto end;
1394
1865
    }
1398
1869
  if(strcmp(interface, "none") != 0){
1399
1870
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1400
1871
    if(if_index == 0){
1401
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1872
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1873
              "No such interface: \"%s\"\n", interface);
1402
1874
      exitcode = EX_UNAVAILABLE;
1403
1875
      goto end;
1404
1876
    }
1411
1883
    errno = 0;
1412
1884
    ret = seteuid(0);
1413
1885
    if(ret == -1){
1414
 
      perror("seteuid");
 
1886
      perror_plus("seteuid");
1415
1887
    }
1416
1888
    
1417
1889
#ifdef __linux__
1421
1893
    bool restore_loglevel = true;
1422
1894
    if(ret == -1){
1423
1895
      restore_loglevel = false;
1424
 
      perror("klogctl");
 
1896
      perror_plus("klogctl");
1425
1897
    }
1426
1898
#endif  /* __linux__ */
1427
1899
    
1428
1900
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
1901
    if(sd < 0){
1430
 
      perror("socket");
 
1902
      perror_plus("socket");
1431
1903
      exitcode = EX_OSERR;
1432
1904
#ifdef __linux__
1433
1905
      if(restore_loglevel){
1434
1906
        ret = klogctl(7, NULL, 0);
1435
1907
        if(ret == -1){
1436
 
          perror("klogctl");
 
1908
          perror_plus("klogctl");
1437
1909
        }
1438
1910
      }
1439
1911
#endif  /* __linux__ */
1441
1913
      errno = 0;
1442
1914
      ret = seteuid(uid);
1443
1915
      if(ret == -1){
1444
 
        perror("seteuid");
 
1916
        perror_plus("seteuid");
1445
1917
      }
1446
1918
      goto end;
1447
1919
    }
1448
1920
    strcpy(network.ifr_name, interface);
1449
1921
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
1922
    if(ret == -1){
1451
 
      perror("ioctl SIOCGIFFLAGS");
 
1923
      perror_plus("ioctl SIOCGIFFLAGS");
1452
1924
#ifdef __linux__
1453
1925
      if(restore_loglevel){
1454
1926
        ret = klogctl(7, NULL, 0);
1455
1927
        if(ret == -1){
1456
 
          perror("klogctl");
 
1928
          perror_plus("klogctl");
1457
1929
        }
1458
1930
      }
1459
1931
#endif  /* __linux__ */
1462
1934
      errno = 0;
1463
1935
      ret = seteuid(uid);
1464
1936
      if(ret == -1){
1465
 
        perror("seteuid");
 
1937
        perror_plus("seteuid");
1466
1938
      }
1467
1939
      goto end;
1468
1940
    }
1472
1944
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
1945
      if(ret == -1){
1474
1946
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1947
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1476
1948
        exitcode = EX_OSERR;
1477
1949
#ifdef __linux__
1478
1950
        if(restore_loglevel){
1479
1951
          ret = klogctl(7, NULL, 0);
1480
1952
          if(ret == -1){
1481
 
            perror("klogctl");
 
1953
            perror_plus("klogctl");
1482
1954
          }
1483
1955
        }
1484
1956
#endif  /* __linux__ */
1486
1958
        errno = 0;
1487
1959
        ret = seteuid(uid);
1488
1960
        if(ret == -1){
1489
 
          perror("seteuid");
 
1961
          perror_plus("seteuid");
1490
1962
        }
1491
1963
        goto end;
1492
1964
      }
1493
1965
    }
1494
 
    /* sleep checking until interface is running */
 
1966
    /* Sleep checking until interface is running.
 
1967
       Check every 0.25s, up to total time of delay */
1495
1968
    for(int i=0; i < delay * 4; i++){
1496
1969
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
1970
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
 
1971
        perror_plus("ioctl SIOCGIFFLAGS");
1499
1972
      } else if(network.ifr_flags & IFF_RUNNING){
1500
1973
        break;
1501
1974
      }
1502
1975
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
1976
      ret = nanosleep(&sleeptime, NULL);
1504
1977
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
 
1978
        perror_plus("nanosleep");
1506
1979
      }
1507
1980
    }
1508
1981
    if(not take_down_interface){
1509
1982
      /* We won't need the socket anymore */
1510
1983
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
1984
      if(ret == -1){
1512
 
        perror("close");
 
1985
        perror_plus("close");
1513
1986
      }
1514
1987
    }
1515
1988
#ifdef __linux__
1517
1990
      /* Restores kernel loglevel to default */
1518
1991
      ret = klogctl(7, NULL, 0);
1519
1992
      if(ret == -1){
1520
 
        perror("klogctl");
 
1993
        perror_plus("klogctl");
1521
1994
      }
1522
1995
    }
1523
1996
#endif  /* __linux__ */
1527
2000
      /* Lower privileges */
1528
2001
      ret = seteuid(uid);
1529
2002
      if(ret == -1){
1530
 
        perror("seteuid");
 
2003
        perror_plus("seteuid");
1531
2004
      }
1532
2005
    } else {
1533
2006
      /* Lower privileges permanently */
1534
2007
      ret = setuid(uid);
1535
2008
      if(ret == -1){
1536
 
        perror("setuid");
 
2009
        perror_plus("setuid");
1537
2010
      }
1538
2011
    }
1539
2012
  }
1544
2017
  
1545
2018
  ret = init_gnutls_global(pubkey, seckey);
1546
2019
  if(ret == -1){
1547
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2020
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2021
            "init_gnutls_global failed\n");
1548
2022
    exitcode = EX_UNAVAILABLE;
1549
2023
    goto end;
1550
2024
  } else {
1555
2029
    goto end;
1556
2030
  }
1557
2031
  
 
2032
  if(mkdtemp(tempdir) == NULL){
 
2033
    perror_plus("mkdtemp");
 
2034
    goto end;
 
2035
  }
1558
2036
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
2037
  
1565
2038
  if(quit_now){
1566
2039
    goto end;
1567
2040
  }
1568
2041
  
1569
2042
  if(not init_gpgme(pubkey, seckey, tempdir)){
1570
 
    fprintf(stderr, "init_gpgme failed\n");
 
2043
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2044
            "init_gpgme failed\n");
1571
2045
    exitcode = EX_UNAVAILABLE;
1572
2046
    goto end;
1573
2047
  } else {
1583
2057
    /* (Mainly meant for debugging) */
1584
2058
    char *address = strrchr(connect_to, ':');
1585
2059
    if(address == NULL){
1586
 
      fprintf(stderr, "No colon in address\n");
 
2060
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2061
              "No colon in address\n");
1587
2062
      exitcode = EX_USAGE;
1588
2063
      goto end;
1589
2064
    }
1597
2072
    tmpmax = strtoimax(address+1, &tmp, 10);
1598
2073
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1599
2074
       or tmpmax != (uint16_t)tmpmax){
1600
 
      fprintf(stderr, "Bad port number\n");
 
2075
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2076
              "Bad port number\n");
1601
2077
      exitcode = EX_USAGE;
1602
2078
      goto end;
1603
2079
    }
1608
2084
    
1609
2085
    port = (uint16_t)tmpmax;
1610
2086
    *address = '\0';
1611
 
    address = connect_to;
1612
2087
    /* Colon in address indicates IPv6 */
1613
2088
    int af;
1614
 
    if(strchr(address, ':') != NULL){
 
2089
    if(strchr(connect_to, ':') != NULL){
1615
2090
      af = AF_INET6;
 
2091
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2092
      if(connect_to[0] == '[' and address[-1] == ']')
 
2093
        {
 
2094
          connect_to++;
 
2095
          address[-1] = '\0';
 
2096
        }
1616
2097
    } else {
1617
2098
      af = AF_INET;
1618
2099
    }
 
2100
    address = connect_to;
1619
2101
    
1620
2102
    if(quit_now){
1621
2103
      goto end;
1622
2104
    }
1623
 
 
 
2105
    
1624
2106
    while(not quit_now){
1625
2107
      ret = start_mandos_communication(address, port, if_index, af);
1626
2108
      if(quit_now or ret == 0){
1627
2109
        break;
1628
2110
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
 
2111
      if(debug){
 
2112
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2113
                "Retrying in %d seconds\n", (int)retry_interval);
 
2114
      }
 
2115
      sleep((int)retry_interval);
 
2116
    }
 
2117
    
1632
2118
    if (not quit_now){
1633
2119
      exitcode = EXIT_SUCCESS;
1634
2120
    }
1635
 
 
 
2121
    
1636
2122
    goto end;
1637
2123
  }
1638
2124
  
1660
2146
  
1661
2147
  /* Check if creating the Avahi server object succeeded */
1662
2148
  if(mc.server == NULL){
1663
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2149
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2150
            "Failed to create Avahi server: %s\n",
1664
2151
            avahi_strerror(error));
1665
2152
    exitcode = EX_UNAVAILABLE;
1666
2153
    goto end;
1675
2162
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1676
2163
                                   NULL, 0, browse_callback, NULL);
1677
2164
  if(sb == NULL){
1678
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2165
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2166
            "Failed to create service browser: %s\n",
1679
2167
            avahi_strerror(avahi_server_errno(mc.server)));
1680
2168
    exitcode = EX_UNAVAILABLE;
1681
2169
    goto end;
1688
2176
  /* Run the main loop */
1689
2177
  
1690
2178
  if(debug){
1691
 
    fprintf(stderr, "Starting Avahi loop search\n");
1692
 
  }
1693
 
  
1694
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2179
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2180
            "Starting Avahi loop search\n");
 
2181
  }
 
2182
 
 
2183
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2184
                                (int)(retry_interval * 1000));
 
2185
  if(debug){
 
2186
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2187
            "avahi_loop_with_timeout exited %s\n",
 
2188
            (ret == 0) ? "successfully" : "with error");
 
2189
  }
1695
2190
  
1696
2191
 end:
1697
2192
  
1698
2193
  if(debug){
1699
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2194
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2195
            "%s exiting\n", argv[0]);
1700
2196
  }
1701
2197
  
1702
2198
  /* Cleanup things */
1718
2214
  if(gpgme_initialized){
1719
2215
    gpgme_release(mc.ctx);
1720
2216
  }
 
2217
 
 
2218
  /* Cleans up the circular linked list of Mandos servers the client
 
2219
     has seen */
 
2220
  if(mc.current_server != NULL){
 
2221
    mc.current_server->prev->next = NULL;
 
2222
    while(mc.current_server != NULL){
 
2223
      server *next = mc.current_server->next;
 
2224
      free(mc.current_server);
 
2225
      mc.current_server = next;
 
2226
    }
 
2227
  }
 
2228
  
 
2229
  /* XXX run network hooks "stop" here  */
1721
2230
  
1722
2231
  /* Take down the network interface */
1723
2232
  if(take_down_interface){
1725
2234
    errno = 0;
1726
2235
    ret = seteuid(0);
1727
2236
    if(ret == -1){
1728
 
      perror("seteuid");
 
2237
      perror_plus("seteuid");
1729
2238
    }
1730
2239
    if(geteuid() == 0){
1731
2240
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
2241
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
1734
 
      } else if(network.ifr_flags & IFF_UP) {
 
2242
        perror_plus("ioctl SIOCGIFFLAGS");
 
2243
      } else if(network.ifr_flags & IFF_UP){
1735
2244
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
2245
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
2246
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
2247
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1739
2248
        }
1740
2249
      }
1741
2250
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
2251
      if(ret == -1){
1743
 
        perror("close");
 
2252
        perror_plus("close");
1744
2253
      }
1745
2254
      /* Lower privileges permanently */
1746
2255
      errno = 0;
1747
2256
      ret = setuid(uid);
1748
2257
      if(ret == -1){
1749
 
        perror("setuid");
 
2258
        perror_plus("setuid");
1750
2259
      }
1751
2260
    }
1752
2261
  }
1753
2262
  
1754
 
  /* Removes the temp directory used by GPGME */
 
2263
  /* Removes the GPGME temp directory and all files inside */
1755
2264
  if(tempdir_created){
1756
 
    DIR *d;
1757
 
    struct dirent *direntry;
1758
 
    d = opendir(tempdir);
1759
 
    if(d == NULL){
1760
 
      if(errno != ENOENT){
1761
 
        perror("opendir");
1762
 
      }
1763
 
    } else {
1764
 
      while(true){
1765
 
        direntry = readdir(d);
1766
 
        if(direntry == NULL){
1767
 
          break;
1768
 
        }
1769
 
        /* Skip "." and ".." */
1770
 
        if(direntry->d_name[0] == '.'
1771
 
           and (direntry->d_name[1] == '\0'
1772
 
                or (direntry->d_name[1] == '.'
1773
 
                    and direntry->d_name[2] == '\0'))){
1774
 
          continue;
1775
 
        }
 
2265
    struct dirent **direntries = NULL;
 
2266
    struct dirent *direntry = NULL;
 
2267
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2268
                             alphasort);
 
2269
    if (numentries > 0){
 
2270
      for(int i = 0; i < numentries; i++){
 
2271
        direntry = direntries[i];
1776
2272
        char *fullname = NULL;
1777
2273
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
2274
                       direntry->d_name);
1779
2275
        if(ret < 0){
1780
 
          perror("asprintf");
 
2276
          perror_plus("asprintf");
1781
2277
          continue;
1782
2278
        }
1783
2279
        ret = remove(fullname);
1784
2280
        if(ret == -1){
1785
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1786
 
                  strerror(errno));
 
2281
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2282
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
1787
2283
        }
1788
2284
        free(fullname);
1789
2285
      }
1790
 
      closedir(d);
 
2286
    }
 
2287
 
 
2288
    /* need to clean even if 0 because man page doesn't specify */
 
2289
    free(direntries);
 
2290
    if (numentries == -1){
 
2291
      perror_plus("scandir");
1791
2292
    }
1792
2293
    ret = rmdir(tempdir);
1793
2294
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
 
2295
      perror_plus("rmdir");
1795
2296
    }
1796
2297
  }
1797
2298
  
1802
2303
                                            &old_sigterm_action,
1803
2304
                                            NULL));
1804
2305
    if(ret == -1){
1805
 
      perror("sigaction");
 
2306
      perror_plus("sigaction");
1806
2307
    }
1807
2308
    do {
1808
2309
      ret = raise(signal_received);
1809
2310
    } while(ret != 0 and errno == EINTR);
1810
2311
    if(ret != 0){
1811
 
      perror("raise");
 
2312
      perror_plus("raise");
1812
2313
      abort();
1813
2314
    }
1814
2315
    TEMP_FAILURE_RETRY(pause());