/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

merge

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,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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
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() */
 
33
#ifndef _LARGEFILE_SOURCE
33
34
#define _LARGEFILE_SOURCE
 
35
#endif
 
36
#ifndef _FILE_OFFSET_BITS
34
37
#define _FILE_OFFSET_BITS 64
 
38
#endif
35
39
 
36
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
41
 
38
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
 
43
                                   stdout, ferror(), remove() */
41
44
#include <stdint.h>             /* uint16_t, uint32_t */
42
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
45
48
#include <stdbool.h>            /* bool, false, true */
46
49
#include <string.h>             /* memset(), strcmp(), strlen(),
47
50
                                   strerror(), asprintf(), strcpy() */
56
59
#include <fcntl.h>              /* open() */
57
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
58
61
                                 */
59
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
 
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
 
63
                                   strtoimax() */
60
64
#include <assert.h>             /* assert() */
61
 
#include <errno.h>              /* perror(), errno */
62
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
63
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
64
69
                                   SIOCSIFFLAGS, if_indextoname(),
65
70
                                   if_nametoindex(), IF_NAMESIZE */
67
72
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
73
                                */
69
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
 
                                   getuid(), getgid(), setuid(),
71
 
                                   setgid() */
72
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
75
                                   getuid(), getgid(), seteuid(),
 
76
                                   setgid(), pause() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
73
78
#include <iso646.h>             /* not, or, and */
74
79
#include <argp.h>               /* struct argp_option, error_t, struct
75
80
                                   argp_state, struct argp,
76
81
                                   argp_parse(), ARGP_KEY_ARG,
77
82
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
83
#include <signal.h>             /* sigemptyset(), sigaddset(),
 
84
                                   sigaction(), SIGTERM, sig_atomic_t,
 
85
                                   raise() */
 
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
 
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
 
78
89
#ifdef __linux__
79
90
#include <sys/klog.h>           /* klogctl() */
80
 
#endif
 
91
#endif  /* __linux__ */
81
92
 
82
93
/* Avahi */
83
94
/* All Avahi types, constants and functions
116
127
bool debug = false;
117
128
static const char mandos_protocol_version[] = "1";
118
129
const char *argp_program_version = "mandos-client " VERSION;
119
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
130
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
131
static const char sys_class_net[] = "/sys/class/net";
 
132
char *connect_to = NULL;
 
133
 
 
134
/* Doubly linked list that need to be circularly linked when used */
 
135
typedef struct server{
 
136
  const char *ip;
 
137
  uint16_t port;
 
138
  AvahiIfIndex if_index;
 
139
  int af;
 
140
  struct timespec last_seen;
 
141
  struct server *next;
 
142
  struct server *prev;
 
143
} server;
120
144
 
121
145
/* Used for passing in values through the Avahi callback functions */
122
146
typedef struct {
127
151
  gnutls_dh_params_t dh_params;
128
152
  const char *priority;
129
153
  gpgme_ctx_t ctx;
 
154
  server *current_server;
130
155
} mandos_context;
131
156
 
 
157
/* global context so signal handler can reach it*/
 
158
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
159
                      .dh_bits = 1024, .priority = "SECURE256"
 
160
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
161
                      .current_server = NULL };
 
162
 
 
163
sig_atomic_t quit_now = 0;
 
164
int signal_received = 0;
 
165
 
 
166
/* Function to use when printing errors */
 
167
void perror_plus(const char *print_text){
 
168
  fprintf(stderr, "Mandos plugin %s: ",
 
169
          program_invocation_short_name);
 
170
  perror(print_text);
 
171
}
 
172
 
132
173
/*
133
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
134
 
 * "buffer_capacity" is how much is currently allocated,
 
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
175
 * bytes. "buffer_capacity" is how much is currently allocated,
135
176
 * "buffer_length" is how much is already used.
136
177
 */
137
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
178
size_t incbuffer(char **buffer, size_t buffer_length,
138
179
                  size_t buffer_capacity){
139
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
140
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
146
187
  return buffer_capacity;
147
188
}
148
189
 
 
190
/* Add server to set of servers to retry periodically */
 
191
int add_server(const char *ip, uint16_t port,
 
192
                 AvahiIfIndex if_index,
 
193
                 int af){
 
194
  int ret;
 
195
  server *new_server = malloc(sizeof(server));
 
196
  if(new_server == NULL){
 
197
    perror_plus("malloc");
 
198
    return -1;
 
199
  }
 
200
  *new_server = (server){ .ip = strdup(ip),
 
201
                         .port = port,
 
202
                         .if_index = if_index,
 
203
                         .af = af };
 
204
  if(new_server->ip == NULL){
 
205
    perror_plus("strdup");
 
206
    return -1;
 
207
  }
 
208
  /* Special case of first server */
 
209
  if (mc.current_server == NULL){
 
210
    new_server->next = new_server;
 
211
    new_server->prev = new_server;
 
212
    mc.current_server = new_server;
 
213
  /* Place the new server last in the list */
 
214
  } else {
 
215
    new_server->next = mc.current_server;
 
216
    new_server->prev = mc.current_server->prev;
 
217
    new_server->prev->next = new_server;
 
218
    mc.current_server->prev = new_server;
 
219
  }
 
220
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
221
  if(ret == -1){
 
222
    perror_plus("clock_gettime");
 
223
    return -1;
 
224
  }
 
225
  return 0;
 
226
}
 
227
 
149
228
/* 
150
229
 * Initialize GPGME.
151
230
 */
152
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
231
static bool init_gpgme(const char *seckey,
153
232
                       const char *pubkey, const char *tempdir){
154
 
  int ret;
155
233
  gpgme_error_t rc;
156
234
  gpgme_engine_info_t engine_info;
157
235
  
160
238
   * Helper function to insert pub and seckey to the engine keyring.
161
239
   */
162
240
  bool import_key(const char *filename){
 
241
    int ret;
163
242
    int fd;
164
243
    gpgme_data_t pgp_data;
165
244
    
166
245
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
167
246
    if(fd == -1){
168
 
      perror("open");
 
247
      perror_plus("open");
169
248
      return false;
170
249
    }
171
250
    
176
255
      return false;
177
256
    }
178
257
    
179
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
258
    rc = gpgme_op_import(mc.ctx, pgp_data);
180
259
    if(rc != GPG_ERR_NO_ERROR){
181
260
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
182
261
              gpgme_strsource(rc), gpgme_strerror(rc));
185
264
    
186
265
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
187
266
    if(ret == -1){
188
 
      perror("close");
 
267
      perror_plus("close");
189
268
    }
190
269
    gpgme_data_release(pgp_data);
191
270
    return true;
192
271
  }
193
272
  
194
273
  if(debug){
195
 
    fprintf(stderr, "Initialize gpgme\n");
 
274
    fprintf(stderr, "Initializing GPGME\n");
196
275
  }
197
276
  
198
277
  /* Init GPGME */
204
283
    return false;
205
284
  }
206
285
  
207
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
286
  /* Set GPGME home directory for the OpenPGP engine only */
208
287
  rc = gpgme_get_engine_info(&engine_info);
209
288
  if(rc != GPG_ERR_NO_ERROR){
210
289
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
225
304
  }
226
305
  
227
306
  /* Create new GPGME "context" */
228
 
  rc = gpgme_new(&(mc->ctx));
 
307
  rc = gpgme_new(&(mc.ctx));
229
308
  if(rc != GPG_ERR_NO_ERROR){
230
309
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
231
310
            gpgme_strsource(rc), gpgme_strerror(rc));
236
315
    return false;
237
316
  }
238
317
  
239
 
  return true; 
 
318
  return true;
240
319
}
241
320
 
242
321
/* 
243
322
 * Decrypt OpenPGP data.
244
323
 * Returns -1 on error
245
324
 */
246
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
247
 
                                  const char *cryptotext,
 
325
static ssize_t pgp_packet_decrypt(const char *cryptotext,
248
326
                                  size_t crypto_size,
249
327
                                  char **plaintext){
250
328
  gpgme_data_t dh_crypto, dh_plain;
277
355
  
278
356
  /* Decrypt data from the cryptotext data buffer to the plaintext
279
357
     data buffer */
280
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
358
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
281
359
  if(rc != GPG_ERR_NO_ERROR){
282
360
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
283
361
            gpgme_strsource(rc), gpgme_strerror(rc));
284
362
    plaintext_length = -1;
285
363
    if(debug){
286
364
      gpgme_decrypt_result_t result;
287
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
365
      result = gpgme_op_decrypt_result(mc.ctx);
288
366
      if(result == NULL){
289
367
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
290
368
      } else {
297
375
        }
298
376
        gpgme_recipient_t recipient;
299
377
        recipient = result->recipients;
300
 
        if(recipient){
301
 
          while(recipient != NULL){
302
 
            fprintf(stderr, "Public key algorithm: %s\n",
303
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
304
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
305
 
            fprintf(stderr, "Secret key available: %s\n",
306
 
                    recipient->status == GPG_ERR_NO_SECKEY
307
 
                    ? "No" : "Yes");
308
 
            recipient = recipient->next;
309
 
          }
 
378
        while(recipient != NULL){
 
379
          fprintf(stderr, "Public key algorithm: %s\n",
 
380
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
381
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
382
          fprintf(stderr, "Secret key available: %s\n",
 
383
                  recipient->status == GPG_ERR_NO_SECKEY
 
384
                  ? "No" : "Yes");
 
385
          recipient = recipient->next;
310
386
        }
311
387
      }
312
388
    }
319
395
  
320
396
  /* Seek back to the beginning of the GPGME plaintext data buffer */
321
397
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
322
 
    perror("gpgme_data_seek");
 
398
    perror_plus("gpgme_data_seek");
323
399
    plaintext_length = -1;
324
400
    goto decrypt_end;
325
401
  }
326
402
  
327
403
  *plaintext = NULL;
328
404
  while(true){
329
 
    plaintext_capacity = adjustbuffer(plaintext,
 
405
    plaintext_capacity = incbuffer(plaintext,
330
406
                                      (size_t)plaintext_length,
331
407
                                      plaintext_capacity);
332
408
    if(plaintext_capacity == 0){
333
 
        perror("adjustbuffer");
 
409
        perror_plus("incbuffer");
334
410
        plaintext_length = -1;
335
411
        goto decrypt_end;
336
412
    }
343
419
      break;
344
420
    }
345
421
    if(ret < 0){
346
 
      perror("gpgme_data_read");
 
422
      perror_plus("gpgme_data_read");
347
423
      plaintext_length = -1;
348
424
      goto decrypt_end;
349
425
    }
382
458
  fprintf(stderr, "GnuTLS: %s", string);
383
459
}
384
460
 
385
 
static int init_gnutls_global(mandos_context *mc,
386
 
                              const char *pubkeyfilename,
 
461
static int init_gnutls_global(const char *pubkeyfilename,
387
462
                              const char *seckeyfilename){
388
463
  int ret;
389
464
  
407
482
  }
408
483
  
409
484
  /* OpenPGP credentials */
410
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
485
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
411
486
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
413
 
                                                    from
414
 
                                                    -Wunreachable-code
415
 
                                                 */
 
487
    fprintf(stderr, "GnuTLS memory error: %s\n",
416
488
            safer_gnutls_strerror(ret));
417
489
    gnutls_global_deinit();
418
490
    return -1;
425
497
  }
426
498
  
427
499
  ret = gnutls_certificate_set_openpgp_key_file
428
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
500
    (mc.cred, pubkeyfilename, seckeyfilename,
429
501
     GNUTLS_OPENPGP_FMT_BASE64);
430
502
  if(ret != GNUTLS_E_SUCCESS){
431
503
    fprintf(stderr,
437
509
  }
438
510
  
439
511
  /* GnuTLS server initialization */
440
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
512
  ret = gnutls_dh_params_init(&mc.dh_params);
441
513
  if(ret != GNUTLS_E_SUCCESS){
442
514
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
443
515
            " %s\n", safer_gnutls_strerror(ret));
444
516
    goto globalfail;
445
517
  }
446
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
518
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
447
519
  if(ret != GNUTLS_E_SUCCESS){
448
520
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
449
521
            safer_gnutls_strerror(ret));
450
522
    goto globalfail;
451
523
  }
452
524
  
453
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
525
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
454
526
  
455
527
  return 0;
456
528
  
457
529
 globalfail:
458
530
  
459
 
  gnutls_certificate_free_credentials(mc->cred);
 
531
  gnutls_certificate_free_credentials(mc.cred);
460
532
  gnutls_global_deinit();
461
 
  gnutls_dh_params_deinit(mc->dh_params);
 
533
  gnutls_dh_params_deinit(mc.dh_params);
462
534
  return -1;
463
535
}
464
536
 
465
 
static int init_gnutls_session(mandos_context *mc,
466
 
                               gnutls_session_t *session){
 
537
static int init_gnutls_session(gnutls_session_t *session){
467
538
  int ret;
468
539
  /* GnuTLS session creation */
469
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
540
  do {
 
541
    ret = gnutls_init(session, GNUTLS_SERVER);
 
542
    if(quit_now){
 
543
      return -1;
 
544
    }
 
545
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
470
546
  if(ret != GNUTLS_E_SUCCESS){
471
547
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
472
548
            safer_gnutls_strerror(ret));
474
550
  
475
551
  {
476
552
    const char *err;
477
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
553
    do {
 
554
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
555
      if(quit_now){
 
556
        gnutls_deinit(*session);
 
557
        return -1;
 
558
      }
 
559
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
478
560
    if(ret != GNUTLS_E_SUCCESS){
479
561
      fprintf(stderr, "Syntax error at: %s\n", err);
480
562
      fprintf(stderr, "GnuTLS error: %s\n",
484
566
    }
485
567
  }
486
568
  
487
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
488
 
                               mc->cred);
 
569
  do {
 
570
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
571
                                 mc.cred);
 
572
    if(quit_now){
 
573
      gnutls_deinit(*session);
 
574
      return -1;
 
575
    }
 
576
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
489
577
  if(ret != GNUTLS_E_SUCCESS){
490
578
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
491
579
            safer_gnutls_strerror(ret));
494
582
  }
495
583
  
496
584
  /* ignore client certificate if any. */
497
 
  gnutls_certificate_server_set_request(*session,
498
 
                                        GNUTLS_CERT_IGNORE);
 
585
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
499
586
  
500
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
587
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
501
588
  
502
589
  return 0;
503
590
}
509
596
/* Called when a Mandos server is found */
510
597
static int start_mandos_communication(const char *ip, uint16_t port,
511
598
                                      AvahiIfIndex if_index,
512
 
                                      mandos_context *mc, int af){
513
 
  int ret, tcp_sd;
 
599
                                      int af){
 
600
  int ret, tcp_sd = -1;
514
601
  ssize_t sret;
515
602
  union {
516
603
    struct sockaddr_in in;
517
604
    struct sockaddr_in6 in6;
518
605
  } to;
519
606
  char *buffer = NULL;
520
 
  char *decrypted_buffer;
 
607
  char *decrypted_buffer = NULL;
521
608
  size_t buffer_length = 0;
522
609
  size_t buffer_capacity = 0;
523
 
  ssize_t decrypted_buffer_size;
524
610
  size_t written;
525
 
  int retval = 0;
 
611
  int retval = -1;
526
612
  gnutls_session_t session;
527
613
  int pf;                       /* Protocol family */
528
614
  
 
615
  errno = 0;
 
616
  
 
617
  if(quit_now){
 
618
    errno = EINTR;
 
619
    return -1;
 
620
  }
 
621
  
529
622
  switch(af){
530
623
  case AF_INET6:
531
624
    pf = PF_INET6;
535
628
    break;
536
629
  default:
537
630
    fprintf(stderr, "Bad address family: %d\n", af);
 
631
    errno = EINVAL;
538
632
    return -1;
539
633
  }
540
634
  
541
 
  ret = init_gnutls_session(mc, &session);
 
635
  ret = init_gnutls_session(&session);
542
636
  if(ret != 0){
543
637
    return -1;
544
638
  }
550
644
  
551
645
  tcp_sd = socket(pf, SOCK_STREAM, 0);
552
646
  if(tcp_sd < 0){
553
 
    perror("socket");
554
 
    return -1;
 
647
    int e = errno;
 
648
    perror_plus("socket");
 
649
    errno = e;
 
650
    goto mandos_end;
 
651
  }
 
652
  
 
653
  if(quit_now){
 
654
    errno = EINTR;
 
655
    goto mandos_end;
555
656
  }
556
657
  
557
658
  memset(&to, 0, sizeof(to));
558
659
  if(af == AF_INET6){
559
 
    to.in6.sin6_family = (uint16_t)af;
 
660
    to.in6.sin6_family = (sa_family_t)af;
560
661
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
561
662
  } else {                      /* IPv4 */
562
663
    to.in.sin_family = (sa_family_t)af;
563
664
    ret = inet_pton(af, ip, &to.in.sin_addr);
564
665
  }
565
666
  if(ret < 0 ){
566
 
    perror("inet_pton");
567
 
    return -1;
 
667
    int e = errno;
 
668
    perror_plus("inet_pton");
 
669
    errno = e;
 
670
    goto mandos_end;
568
671
  }
569
672
  if(ret == 0){
 
673
    int e = errno;
570
674
    fprintf(stderr, "Bad address: %s\n", ip);
571
 
    return -1;
 
675
    errno = e;
 
676
    goto mandos_end;
572
677
  }
573
678
  if(af == AF_INET6){
574
679
    to.in6.sin6_port = htons(port); /* Spurious warnings from
581
686
      if(if_index == AVAHI_IF_UNSPEC){
582
687
        fprintf(stderr, "An IPv6 link-local address is incomplete"
583
688
                " without a network interface\n");
584
 
        return -1;
 
689
        errno = EINVAL;
 
690
        goto mandos_end;
585
691
      }
586
692
      /* Set the network interface number as scope */
587
693
      to.in6.sin6_scope_id = (uint32_t)if_index;
592
698
                                     -Wunreachable-code */
593
699
  }
594
700
  
 
701
  if(quit_now){
 
702
    errno = EINTR;
 
703
    goto mandos_end;
 
704
  }
 
705
  
595
706
  if(debug){
596
707
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
597
708
      char interface[IF_NAMESIZE];
598
709
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
599
 
        perror("if_indextoname");
 
710
        perror_plus("if_indextoname");
600
711
      } else {
601
712
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
602
713
                ip, interface, port);
616
727
                        sizeof(addrstr));
617
728
    }
618
729
    if(pcret == NULL){
619
 
      perror("inet_ntop");
 
730
      perror_plus("inet_ntop");
620
731
    } else {
621
732
      if(strcmp(addrstr, ip) != 0){
622
733
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
624
735
    }
625
736
  }
626
737
  
 
738
  if(quit_now){
 
739
    errno = EINTR;
 
740
    goto mandos_end;
 
741
  }
 
742
  
627
743
  if(af == AF_INET6){
628
744
    ret = connect(tcp_sd, &to.in6, sizeof(to));
629
745
  } else {
630
746
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
631
747
  }
632
748
  if(ret < 0){
633
 
    perror("connect");
634
 
    return -1;
 
749
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
750
      int e = errno;
 
751
      perror_plus("connect");
 
752
      errno = e;
 
753
    }
 
754
    goto mandos_end;
 
755
  }
 
756
  
 
757
  if(quit_now){
 
758
    errno = EINTR;
 
759
    goto mandos_end;
635
760
  }
636
761
  
637
762
  const char *out = mandos_protocol_version;
641
766
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
642
767
                                   out_size - written));
643
768
    if(ret == -1){
644
 
      perror("write");
645
 
      retval = -1;
 
769
      int e = errno;
 
770
      perror_plus("write");
 
771
      errno = e;
646
772
      goto mandos_end;
647
773
    }
648
774
    written += (size_t)ret;
656
782
        break;
657
783
      }
658
784
    }
 
785
  
 
786
    if(quit_now){
 
787
      errno = EINTR;
 
788
      goto mandos_end;
 
789
    }
659
790
  }
660
791
  
661
792
  if(debug){
662
793
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
663
794
  }
664
795
  
 
796
  if(quit_now){
 
797
    errno = EINTR;
 
798
    goto mandos_end;
 
799
  }
 
800
  
 
801
  /* Spurious warning from -Wint-to-pointer-cast */
665
802
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
666
803
  
667
 
  do{
 
804
  if(quit_now){
 
805
    errno = EINTR;
 
806
    goto mandos_end;
 
807
  }
 
808
  
 
809
  do {
668
810
    ret = gnutls_handshake(session);
 
811
    if(quit_now){
 
812
      errno = EINTR;
 
813
      goto mandos_end;
 
814
    }
669
815
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
670
816
  
671
817
  if(ret != GNUTLS_E_SUCCESS){
673
819
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
674
820
      gnutls_perror(ret);
675
821
    }
676
 
    retval = -1;
 
822
    errno = EPROTO;
677
823
    goto mandos_end;
678
824
  }
679
825
  
685
831
  }
686
832
  
687
833
  while(true){
688
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
834
    
 
835
    if(quit_now){
 
836
      errno = EINTR;
 
837
      goto mandos_end;
 
838
    }
 
839
    
 
840
    buffer_capacity = incbuffer(&buffer, buffer_length,
689
841
                                   buffer_capacity);
690
842
    if(buffer_capacity == 0){
691
 
      perror("adjustbuffer");
692
 
      retval = -1;
 
843
      int e = errno;
 
844
      perror_plus("incbuffer");
 
845
      errno = e;
 
846
      goto mandos_end;
 
847
    }
 
848
    
 
849
    if(quit_now){
 
850
      errno = EINTR;
693
851
      goto mandos_end;
694
852
    }
695
853
    
704
862
      case GNUTLS_E_AGAIN:
705
863
        break;
706
864
      case GNUTLS_E_REHANDSHAKE:
707
 
        do{
 
865
        do {
708
866
          ret = gnutls_handshake(session);
 
867
          
 
868
          if(quit_now){
 
869
            errno = EINTR;
 
870
            goto mandos_end;
 
871
          }
709
872
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
710
873
        if(ret < 0){
711
874
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
712
875
          gnutls_perror(ret);
713
 
          retval = -1;
 
876
          errno = EPROTO;
714
877
          goto mandos_end;
715
878
        }
716
879
        break;
717
880
      default:
718
881
        fprintf(stderr, "Unknown error while reading data from"
719
882
                " encrypted session with Mandos server\n");
720
 
        retval = -1;
721
883
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
884
        errno = EIO;
722
885
        goto mandos_end;
723
886
      }
724
887
    } else {
730
893
    fprintf(stderr, "Closing TLS session\n");
731
894
  }
732
895
  
733
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
896
  if(quit_now){
 
897
    errno = EINTR;
 
898
    goto mandos_end;
 
899
  }
 
900
  
 
901
  do {
 
902
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
903
    if(quit_now){
 
904
      errno = EINTR;
 
905
      goto mandos_end;
 
906
    }
 
907
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
734
908
  
735
909
  if(buffer_length > 0){
736
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
910
    ssize_t decrypted_buffer_size;
 
911
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
737
912
                                               buffer_length,
738
913
                                               &decrypted_buffer);
739
914
    if(decrypted_buffer_size >= 0){
 
915
      
740
916
      written = 0;
741
917
      while(written < (size_t) decrypted_buffer_size){
 
918
        if(quit_now){
 
919
          errno = EINTR;
 
920
          goto mandos_end;
 
921
        }
 
922
        
742
923
        ret = (int)fwrite(decrypted_buffer + written, 1,
743
924
                          (size_t)decrypted_buffer_size - written,
744
925
                          stdout);
745
926
        if(ret == 0 and ferror(stdout)){
 
927
          int e = errno;
746
928
          if(debug){
747
929
            fprintf(stderr, "Error writing encrypted data: %s\n",
748
930
                    strerror(errno));
749
931
          }
750
 
          retval = -1;
751
 
          break;
 
932
          errno = e;
 
933
          goto mandos_end;
752
934
        }
753
935
        written += (size_t)ret;
754
936
      }
755
 
      free(decrypted_buffer);
756
 
    } else {
757
 
      retval = -1;
 
937
      retval = 0;
758
938
    }
759
 
  } else {
760
 
    retval = -1;
761
939
  }
762
940
  
763
941
  /* Shutdown procedure */
764
942
  
765
943
 mandos_end:
766
 
  free(buffer);
767
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
768
 
  if(ret == -1){
769
 
    perror("close");
 
944
  {
 
945
    int e = errno;
 
946
    free(decrypted_buffer);
 
947
    free(buffer);
 
948
    if(tcp_sd >= 0){
 
949
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
950
    }
 
951
    if(ret == -1){
 
952
      if(e == 0){
 
953
        e = errno;
 
954
      }
 
955
      perror_plus("close");
 
956
    }
 
957
    gnutls_deinit(session);
 
958
    errno = e;
 
959
    if(quit_now){
 
960
      errno = EINTR;
 
961
      retval = -1;
 
962
    }
770
963
  }
771
 
  gnutls_deinit(session);
772
964
  return retval;
773
965
}
774
966
 
785
977
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
786
978
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
787
979
                             flags,
788
 
                             void* userdata){
789
 
  mandos_context *mc = userdata;
 
980
                             AVAHI_GCC_UNUSED void* userdata){
790
981
  assert(r);
791
982
  
792
983
  /* Called whenever a service has been resolved successfully or
793
984
     timed out */
794
985
  
 
986
  if(quit_now){
 
987
    return;
 
988
  }
 
989
  
795
990
  switch(event){
796
991
  default:
797
992
  case AVAHI_RESOLVER_FAILURE:
798
993
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
799
994
            " of type '%s' in domain '%s': %s\n", name, type, domain,
800
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
995
            avahi_strerror(avahi_server_errno(mc.server)));
801
996
    break;
802
997
    
803
998
  case AVAHI_RESOLVER_FOUND:
809
1004
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
810
1005
                ip, (intmax_t)interface, port);
811
1006
      }
812
 
      int ret = start_mandos_communication(ip, port, interface, mc,
 
1007
      int ret = start_mandos_communication(ip, port, interface,
813
1008
                                           avahi_proto_to_af(proto));
814
1009
      if(ret == 0){
815
 
        avahi_simple_poll_quit(mc->simple_poll);
 
1010
        avahi_simple_poll_quit(mc.simple_poll);
 
1011
      } else {
 
1012
        ret = add_server(ip, port, interface,
 
1013
                         avahi_proto_to_af(proto));
816
1014
      }
817
1015
    }
818
1016
  }
828
1026
                            const char *domain,
829
1027
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
830
1028
                            flags,
831
 
                            void* userdata){
832
 
  mandos_context *mc = userdata;
 
1029
                            AVAHI_GCC_UNUSED void* userdata){
833
1030
  assert(b);
834
1031
  
835
1032
  /* Called whenever a new services becomes available on the LAN or
836
1033
     is removed from the LAN */
837
1034
  
 
1035
  if(quit_now){
 
1036
    return;
 
1037
  }
 
1038
  
838
1039
  switch(event){
839
1040
  default:
840
1041
  case AVAHI_BROWSER_FAILURE:
841
1042
    
842
1043
    fprintf(stderr, "(Avahi browser) %s\n",
843
 
            avahi_strerror(avahi_server_errno(mc->server)));
844
 
    avahi_simple_poll_quit(mc->simple_poll);
 
1044
            avahi_strerror(avahi_server_errno(mc.server)));
 
1045
    avahi_simple_poll_quit(mc.simple_poll);
845
1046
    return;
846
1047
    
847
1048
  case AVAHI_BROWSER_NEW:
850
1051
       the callback function is called the Avahi server will free the
851
1052
       resolver for us. */
852
1053
    
853
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
854
 
                                       protocol, name, type, domain,
855
 
                                       AVAHI_PROTO_INET6, 0,
856
 
                                       resolve_callback, mc)))
 
1054
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1055
                                    name, type, domain, protocol, 0,
 
1056
                                    resolve_callback, NULL) == NULL)
857
1057
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
858
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
1058
              name, avahi_strerror(avahi_server_errno(mc.server)));
859
1059
    break;
860
1060
    
861
1061
  case AVAHI_BROWSER_REMOVE:
870
1070
  }
871
1071
}
872
1072
 
 
1073
/* Signal handler that stops main loop after SIGTERM */
 
1074
static void handle_sigterm(int sig){
 
1075
  if(quit_now){
 
1076
    return;
 
1077
  }
 
1078
  quit_now = 1;
 
1079
  signal_received = sig;
 
1080
  int old_errno = errno;
 
1081
  /* set main loop to exit */
 
1082
  if(mc.simple_poll != NULL){
 
1083
    avahi_simple_poll_quit(mc.simple_poll);
 
1084
  }
 
1085
  errno = old_errno;
 
1086
}
 
1087
 
 
1088
/* 
 
1089
 * This function determines if a directory entry in /sys/class/net
 
1090
 * corresponds to an acceptable network device.
 
1091
 * (This function is passed to scandir(3) as a filter function.)
 
1092
 */
 
1093
int good_interface(const struct dirent *if_entry){
 
1094
  ssize_t ssret;
 
1095
  char *flagname = NULL;
 
1096
  if(if_entry->d_name[0] == '.'){
 
1097
    return 0;
 
1098
  }
 
1099
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1100
                     if_entry->d_name);
 
1101
  if(ret < 0){
 
1102
    perror_plus("asprintf");
 
1103
    return 0;
 
1104
  }
 
1105
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1106
  if(flags_fd == -1){
 
1107
    perror_plus("open");
 
1108
    free(flagname);
 
1109
    return 0;
 
1110
  }
 
1111
  free(flagname);
 
1112
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1113
  /* read line from flags_fd */
 
1114
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1115
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1116
  flagstring[(size_t)to_read] = '\0';
 
1117
  if(flagstring == NULL){
 
1118
    perror_plus("malloc");
 
1119
    close(flags_fd);
 
1120
    return 0;
 
1121
  }
 
1122
  while(to_read > 0){
 
1123
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1124
                                             (size_t)to_read));
 
1125
    if(ssret == -1){
 
1126
      perror_plus("read");
 
1127
      free(flagstring);
 
1128
      close(flags_fd);
 
1129
      return 0;
 
1130
    }
 
1131
    to_read -= ssret;
 
1132
    if(ssret == 0){
 
1133
      break;
 
1134
    }
 
1135
  }
 
1136
  close(flags_fd);
 
1137
  intmax_t tmpmax;
 
1138
  char *tmp;
 
1139
  errno = 0;
 
1140
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1141
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1142
                                         and not (isspace(*tmp)))
 
1143
     or tmpmax != (ifreq_flags)tmpmax){
 
1144
    if(debug){
 
1145
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1146
              flagstring, if_entry->d_name);
 
1147
    }
 
1148
    free(flagstring);
 
1149
    return 0;
 
1150
  }
 
1151
  free(flagstring);
 
1152
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1153
  /* Reject the loopback device */
 
1154
  if(flags & IFF_LOOPBACK){
 
1155
    if(debug){
 
1156
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1157
              if_entry->d_name);
 
1158
    }
 
1159
    return 0;
 
1160
  }
 
1161
  /* Accept point-to-point devices only if connect_to is specified */
 
1162
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1163
    if(debug){
 
1164
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1165
              if_entry->d_name);
 
1166
    }
 
1167
    return 1;
 
1168
  }
 
1169
  /* Otherwise, reject non-broadcast-capable devices */
 
1170
  if(not (flags & IFF_BROADCAST)){
 
1171
    if(debug){
 
1172
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1173
              if_entry->d_name);
 
1174
    }
 
1175
    return 0;
 
1176
  }
 
1177
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1178
  if(flags & IFF_NOARP){
 
1179
    if(debug){
 
1180
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1181
              if_entry->d_name);
 
1182
    }
 
1183
    return 0;
 
1184
  }
 
1185
  /* Accept this device */
 
1186
  if(debug){
 
1187
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1188
            if_entry->d_name);
 
1189
  }
 
1190
  return 1;
 
1191
}
 
1192
 
 
1193
int notdotentries(const struct dirent *direntry){
 
1194
  /* Skip "." and ".." */
 
1195
  if(direntry->d_name[0] == '.'
 
1196
     and (direntry->d_name[1] == '\0'
 
1197
          or (direntry->d_name[1] == '.'
 
1198
              and direntry->d_name[2] == '\0'))){
 
1199
    return 0;
 
1200
  }
 
1201
  return 1;
 
1202
}
 
1203
 
 
1204
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1205
  int ret;
 
1206
  struct timespec now;
 
1207
  struct timespec waited_time;
 
1208
  intmax_t block_time;
 
1209
  
 
1210
  while(true){
 
1211
    if(mc.current_server == NULL){
 
1212
      if (debug){
 
1213
        fprintf(stderr,
 
1214
                "Wait until first server is found. No timeout!\n");
 
1215
      }
 
1216
      ret = avahi_simple_poll_iterate(s, -1);
 
1217
    } else {
 
1218
      if (debug){
 
1219
        fprintf(stderr, "Check current_server if we should run it,"
 
1220
                " or wait\n");
 
1221
      }
 
1222
      /* the current time */
 
1223
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1224
      if(ret == -1){
 
1225
        perror_plus("clock_gettime");
 
1226
        return -1;
 
1227
      }
 
1228
      /* Calculating in ms how long time between now and server
 
1229
         who we visted longest time ago. Now - last seen.  */
 
1230
      waited_time.tv_sec = (now.tv_sec
 
1231
                            - mc.current_server->last_seen.tv_sec);
 
1232
      waited_time.tv_nsec = (now.tv_nsec
 
1233
                             - mc.current_server->last_seen.tv_nsec);
 
1234
      /* total time is 10s/10,000ms.
 
1235
         Converting to s from ms by dividing by 1,000,
 
1236
         and ns to ms by dividing by 1,000,000. */
 
1237
      block_time = ((retry_interval
 
1238
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1239
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1240
      
 
1241
      if (debug){
 
1242
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1243
      }
 
1244
      
 
1245
      if(block_time <= 0){
 
1246
        ret = start_mandos_communication(mc.current_server->ip,
 
1247
                                         mc.current_server->port,
 
1248
                                         mc.current_server->if_index,
 
1249
                                         mc.current_server->af);
 
1250
        if(ret == 0){
 
1251
          avahi_simple_poll_quit(mc.simple_poll);
 
1252
          return 0;
 
1253
        }
 
1254
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1255
                            &mc.current_server->last_seen);
 
1256
        if(ret == -1){
 
1257
          perror_plus("clock_gettime");
 
1258
          return -1;
 
1259
        }
 
1260
        mc.current_server = mc.current_server->next;
 
1261
        block_time = 0;         /* Call avahi to find new Mandos
 
1262
                                   servers, but don't block */
 
1263
      }
 
1264
      
 
1265
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1266
    }
 
1267
    if(ret != 0){
 
1268
      if (ret > 0 or errno != EINTR) {
 
1269
        return (ret != 1) ? ret : 0;
 
1270
      }
 
1271
    }
 
1272
  }
 
1273
}
 
1274
 
873
1275
int main(int argc, char *argv[]){
874
1276
  AvahiSServiceBrowser *sb = NULL;
875
1277
  int error;
876
1278
  int ret;
877
1279
  intmax_t tmpmax;
878
 
  int numchars;
 
1280
  char *tmp;
879
1281
  int exitcode = EXIT_SUCCESS;
880
 
  const char *interface = "eth0";
 
1282
  const char *interface = "";
881
1283
  struct ifreq network;
882
 
  int sd;
 
1284
  int sd = -1;
 
1285
  bool take_down_interface = false;
883
1286
  uid_t uid;
884
1287
  gid_t gid;
885
 
  char *connect_to = NULL;
886
1288
  char tempdir[] = "/tmp/mandosXXXXXX";
887
1289
  bool tempdir_created = false;
888
1290
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
889
1291
  const char *seckey = PATHDIR "/" SECKEY;
890
1292
  const char *pubkey = PATHDIR "/" PUBKEY;
891
1293
  
892
 
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
893
 
                        .dh_bits = 1024, .priority = "SECURE256"
894
 
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
895
1294
  bool gnutls_initialized = false;
896
1295
  bool gpgme_initialized = false;
897
 
  double delay = 2.5;
 
1296
  float delay = 2.5f;
 
1297
  double retry_interval = 10; /* 10s between trying a server and
 
1298
                                 retrying the same server again */
 
1299
  
 
1300
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
1301
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
1302
  
 
1303
  uid = getuid();
 
1304
  gid = getgid();
 
1305
  
 
1306
  /* Lower any group privileges we might have, just to be safe */
 
1307
  errno = 0;
 
1308
  ret = setgid(gid);
 
1309
  if(ret == -1){
 
1310
    perror_plus("setgid");
 
1311
  }
 
1312
  
 
1313
  /* Lower user privileges (temporarily) */
 
1314
  errno = 0;
 
1315
  ret = seteuid(uid);
 
1316
  if(ret == -1){
 
1317
    perror_plus("seteuid");
 
1318
  }
 
1319
  
 
1320
  if(quit_now){
 
1321
    goto end;
 
1322
  }
898
1323
  
899
1324
  {
900
1325
    struct argp_option options[] = {
930
1355
        .arg = "SECONDS",
931
1356
        .doc = "Maximum delay to wait for interface startup",
932
1357
        .group = 2 },
 
1358
      { .name = "retry", .key = 132,
 
1359
        .arg = "SECONDS",
 
1360
        .doc = "Retry interval used when denied by the mandos server",
 
1361
        .group = 2 },
 
1362
      /*
 
1363
       * These reproduce what we would get without ARGP_NO_HELP
 
1364
       */
 
1365
      { .name = "help", .key = '?',
 
1366
        .doc = "Give this help list", .group = -1 },
 
1367
      { .name = "usage", .key = -3,
 
1368
        .doc = "Give a short usage message", .group = -1 },
 
1369
      { .name = "version", .key = 'V',
 
1370
        .doc = "Print program version", .group = -1 },
933
1371
      { .name = NULL }
934
1372
    };
935
1373
    
936
1374
    error_t parse_opt(int key, char *arg,
937
1375
                      struct argp_state *state){
 
1376
      errno = 0;
938
1377
      switch(key){
939
1378
      case 128:                 /* --debug */
940
1379
        debug = true;
952
1391
        pubkey = arg;
953
1392
        break;
954
1393
      case 129:                 /* --dh-bits */
955
 
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
956
 
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
957
 
           or arg[numchars] != '\0'){
958
 
          fprintf(stderr, "Bad number of DH bits\n");
959
 
          exit(EXIT_FAILURE);
 
1394
        errno = 0;
 
1395
        tmpmax = strtoimax(arg, &tmp, 10);
 
1396
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1397
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
1398
          argp_error(state, "Bad number of DH bits");
960
1399
        }
961
1400
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
962
1401
        break;
964
1403
        mc.priority = arg;
965
1404
        break;
966
1405
      case 131:                 /* --delay */
967
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
968
 
        if(ret < 1 or arg[numchars] != '\0'){
969
 
          fprintf(stderr, "Bad delay\n");
970
 
          exit(EXIT_FAILURE);
 
1406
        errno = 0;
 
1407
        delay = strtof(arg, &tmp);
 
1408
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
1409
          argp_error(state, "Bad delay");
 
1410
        }
 
1411
      case 132:                 /* --retry */
 
1412
        errno = 0;
 
1413
        retry_interval = strtod(arg, &tmp);
 
1414
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1415
           or (retry_interval * 1000) > INT_MAX
 
1416
           or retry_interval < 0){
 
1417
          argp_error(state, "Bad retry interval");
971
1418
        }
972
1419
        break;
973
 
      case ARGP_KEY_ARG:
974
 
        argp_usage(state);
975
 
      case ARGP_KEY_END:
 
1420
        /*
 
1421
         * These reproduce what we would get without ARGP_NO_HELP
 
1422
         */
 
1423
      case '?':                 /* --help */
 
1424
        argp_state_help(state, state->out_stream,
 
1425
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1426
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1427
      case -3:                  /* --usage */
 
1428
        argp_state_help(state, state->out_stream,
 
1429
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1430
      case 'V':                 /* --version */
 
1431
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1432
        exit(argp_err_exit_status);
976
1433
        break;
977
1434
      default:
978
1435
        return ARGP_ERR_UNKNOWN;
979
1436
      }
980
 
      return 0;
 
1437
      return errno;
981
1438
    }
982
1439
    
983
1440
    struct argp argp = { .options = options, .parser = parse_opt,
984
1441
                         .args_doc = "",
985
1442
                         .doc = "Mandos client -- Get and decrypt"
986
1443
                         " passwords from a Mandos server" };
987
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
988
 
    if(ret == ARGP_ERR_UNKNOWN){
989
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1444
    ret = argp_parse(&argp, argc, argv,
 
1445
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1446
    switch(ret){
 
1447
    case 0:
 
1448
      break;
 
1449
    case ENOMEM:
 
1450
    default:
 
1451
      errno = ret;
 
1452
      perror_plus("argp_parse");
 
1453
      exitcode = EX_OSERR;
 
1454
      goto end;
 
1455
    case EINVAL:
 
1456
      exitcode = EX_USAGE;
 
1457
      goto end;
 
1458
    }
 
1459
  }
 
1460
    
 
1461
  {
 
1462
    /* Work around Debian bug #633582:
 
1463
       <http://bugs.debian.org/633582> */
 
1464
    struct stat st;
 
1465
    
 
1466
    /* Re-raise priviliges */
 
1467
    errno = 0;
 
1468
    ret = seteuid(0);
 
1469
    if(ret == -1){
 
1470
      perror_plus("seteuid");
 
1471
    }
 
1472
    
 
1473
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1474
      int seckey_fd = open(seckey, O_RDONLY);
 
1475
      if(seckey_fd == -1){
 
1476
        perror_plus("open");
 
1477
      } else {
 
1478
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1479
        if(ret == -1){
 
1480
          perror_plus("fstat");
 
1481
        } else {
 
1482
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1483
            ret = fchown(seckey_fd, uid, gid);
 
1484
            if(ret == -1){
 
1485
              perror_plus("fchown");
 
1486
            }
 
1487
          }
 
1488
        }
 
1489
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1490
      }
 
1491
    }
 
1492
    
 
1493
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1494
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1495
      if(pubkey_fd == -1){
 
1496
        perror_plus("open");
 
1497
      } else {
 
1498
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1499
        if(ret == -1){
 
1500
          perror_plus("fstat");
 
1501
        } else {
 
1502
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1503
            ret = fchown(pubkey_fd, uid, gid);
 
1504
            if(ret == -1){
 
1505
              perror_plus("fchown");
 
1506
            }
 
1507
          }
 
1508
        }
 
1509
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1510
      }
 
1511
    }
 
1512
    
 
1513
    /* Lower privileges */
 
1514
    errno = 0;
 
1515
    ret = seteuid(uid);
 
1516
    if(ret == -1){
 
1517
      perror_plus("seteuid");
 
1518
    }
 
1519
  }
 
1520
  
 
1521
  if(not debug){
 
1522
    avahi_set_log_function(empty_log);
 
1523
  }
 
1524
 
 
1525
  if(interface[0] == '\0'){
 
1526
    struct dirent **direntries;
 
1527
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1528
                  alphasort);
 
1529
    if(ret >= 1){
 
1530
      /* Pick the first good interface */
 
1531
      interface = strdup(direntries[0]->d_name);
 
1532
      if(debug){
 
1533
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1534
      }
 
1535
      if(interface == NULL){
 
1536
        perror_plus("malloc");
 
1537
        free(direntries);
 
1538
        exitcode = EXIT_FAILURE;
 
1539
        goto end;
 
1540
      }
 
1541
      free(direntries);
 
1542
    } else {
 
1543
      free(direntries);
 
1544
      fprintf(stderr, "Could not find a network interface\n");
990
1545
      exitcode = EXIT_FAILURE;
991
1546
      goto end;
992
1547
    }
993
1548
  }
994
1549
  
 
1550
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1551
     from the signal handler */
 
1552
  /* Initialize the pseudo-RNG for Avahi */
 
1553
  srand((unsigned int) time(NULL));
 
1554
  mc.simple_poll = avahi_simple_poll_new();
 
1555
  if(mc.simple_poll == NULL){
 
1556
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1557
    exitcode = EX_UNAVAILABLE;
 
1558
    goto end;
 
1559
  }
 
1560
  
 
1561
  sigemptyset(&sigterm_action.sa_mask);
 
1562
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1563
  if(ret == -1){
 
1564
    perror_plus("sigaddset");
 
1565
    exitcode = EX_OSERR;
 
1566
    goto end;
 
1567
  }
 
1568
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1569
  if(ret == -1){
 
1570
    perror_plus("sigaddset");
 
1571
    exitcode = EX_OSERR;
 
1572
    goto end;
 
1573
  }
 
1574
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1575
  if(ret == -1){
 
1576
    perror_plus("sigaddset");
 
1577
    exitcode = EX_OSERR;
 
1578
    goto end;
 
1579
  }
 
1580
  /* Need to check if the handler is SIG_IGN before handling:
 
1581
     | [[info:libc:Initial Signal Actions]] |
 
1582
     | [[info:libc:Basic Signal Handling]]  |
 
1583
  */
 
1584
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1585
  if(ret == -1){
 
1586
    perror_plus("sigaction");
 
1587
    return EX_OSERR;
 
1588
  }
 
1589
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1590
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1591
    if(ret == -1){
 
1592
      perror_plus("sigaction");
 
1593
      exitcode = EX_OSERR;
 
1594
      goto end;
 
1595
    }
 
1596
  }
 
1597
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1598
  if(ret == -1){
 
1599
    perror_plus("sigaction");
 
1600
    return EX_OSERR;
 
1601
  }
 
1602
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1603
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1604
    if(ret == -1){
 
1605
      perror_plus("sigaction");
 
1606
      exitcode = EX_OSERR;
 
1607
      goto end;
 
1608
    }
 
1609
  }
 
1610
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1611
  if(ret == -1){
 
1612
    perror_plus("sigaction");
 
1613
    return EX_OSERR;
 
1614
  }
 
1615
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1616
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1617
    if(ret == -1){
 
1618
      perror_plus("sigaction");
 
1619
      exitcode = EX_OSERR;
 
1620
      goto end;
 
1621
    }
 
1622
  }
 
1623
  
995
1624
  /* If the interface is down, bring it up */
996
 
  if(interface[0] != '\0'){
 
1625
  if(strcmp(interface, "none") != 0){
 
1626
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1627
    if(if_index == 0){
 
1628
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1629
      exitcode = EX_UNAVAILABLE;
 
1630
      goto end;
 
1631
    }
 
1632
    
 
1633
    if(quit_now){
 
1634
      goto end;
 
1635
    }
 
1636
    
 
1637
    /* Re-raise priviliges */
 
1638
    errno = 0;
 
1639
    ret = seteuid(0);
 
1640
    if(ret == -1){
 
1641
      perror_plus("seteuid");
 
1642
    }
 
1643
    
997
1644
#ifdef __linux__
998
1645
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
999
 
       messages to mess up the prompt */
 
1646
       messages about the network interface to mess up the prompt */
1000
1647
    ret = klogctl(8, NULL, 5);
1001
1648
    bool restore_loglevel = true;
1002
1649
    if(ret == -1){
1003
1650
      restore_loglevel = false;
1004
 
      perror("klogctl");
 
1651
      perror_plus("klogctl");
1005
1652
    }
1006
 
#endif
 
1653
#endif  /* __linux__ */
1007
1654
    
1008
1655
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1009
1656
    if(sd < 0){
1010
 
      perror("socket");
1011
 
      exitcode = EXIT_FAILURE;
 
1657
      perror_plus("socket");
 
1658
      exitcode = EX_OSERR;
1012
1659
#ifdef __linux__
1013
1660
      if(restore_loglevel){
1014
1661
        ret = klogctl(7, NULL, 0);
1015
1662
        if(ret == -1){
1016
 
          perror("klogctl");
 
1663
          perror_plus("klogctl");
1017
1664
        }
1018
1665
      }
1019
 
#endif
 
1666
#endif  /* __linux__ */
 
1667
      /* Lower privileges */
 
1668
      errno = 0;
 
1669
      ret = seteuid(uid);
 
1670
      if(ret == -1){
 
1671
        perror_plus("seteuid");
 
1672
      }
1020
1673
      goto end;
1021
1674
    }
1022
1675
    strcpy(network.ifr_name, interface);
1023
1676
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1024
1677
    if(ret == -1){
1025
 
      perror("ioctl SIOCGIFFLAGS");
 
1678
      perror_plus("ioctl SIOCGIFFLAGS");
1026
1679
#ifdef __linux__
1027
1680
      if(restore_loglevel){
1028
1681
        ret = klogctl(7, NULL, 0);
1029
1682
        if(ret == -1){
1030
 
          perror("klogctl");
 
1683
          perror_plus("klogctl");
1031
1684
        }
1032
1685
      }
1033
 
#endif
1034
 
      exitcode = EXIT_FAILURE;
 
1686
#endif  /* __linux__ */
 
1687
      exitcode = EX_OSERR;
 
1688
      /* Lower privileges */
 
1689
      errno = 0;
 
1690
      ret = seteuid(uid);
 
1691
      if(ret == -1){
 
1692
        perror_plus("seteuid");
 
1693
      }
1035
1694
      goto end;
1036
1695
    }
1037
1696
    if((network.ifr_flags & IFF_UP) == 0){
1038
1697
      network.ifr_flags |= IFF_UP;
 
1698
      take_down_interface = true;
1039
1699
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1040
1700
      if(ret == -1){
1041
 
        perror("ioctl SIOCSIFFLAGS");
1042
 
        exitcode = EXIT_FAILURE;
 
1701
        take_down_interface = false;
 
1702
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1703
        exitcode = EX_OSERR;
1043
1704
#ifdef __linux__
1044
1705
        if(restore_loglevel){
1045
1706
          ret = klogctl(7, NULL, 0);
1046
1707
          if(ret == -1){
1047
 
            perror("klogctl");
 
1708
            perror_plus("klogctl");
1048
1709
          }
1049
1710
        }
1050
 
#endif
 
1711
#endif  /* __linux__ */
 
1712
        /* Lower privileges */
 
1713
        errno = 0;
 
1714
        ret = seteuid(uid);
 
1715
        if(ret == -1){
 
1716
          perror_plus("seteuid");
 
1717
        }
1051
1718
        goto end;
1052
1719
      }
1053
1720
    }
1054
 
    /* sleep checking until interface is running */
 
1721
    /* Sleep checking until interface is running.
 
1722
       Check every 0.25s, up to total time of delay */
1055
1723
    for(int i=0; i < delay * 4; i++){
1056
1724
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1057
1725
      if(ret == -1){
1058
 
        perror("ioctl SIOCGIFFLAGS");
 
1726
        perror_plus("ioctl SIOCGIFFLAGS");
1059
1727
      } else if(network.ifr_flags & IFF_RUNNING){
1060
1728
        break;
1061
1729
      }
1062
1730
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1063
1731
      ret = nanosleep(&sleeptime, NULL);
1064
1732
      if(ret == -1 and errno != EINTR){
1065
 
        perror("nanosleep");
 
1733
        perror_plus("nanosleep");
1066
1734
      }
1067
1735
    }
1068
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1069
 
    if(ret == -1){
1070
 
      perror("close");
 
1736
    if(not take_down_interface){
 
1737
      /* We won't need the socket anymore */
 
1738
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1739
      if(ret == -1){
 
1740
        perror_plus("close");
 
1741
      }
1071
1742
    }
1072
1743
#ifdef __linux__
1073
1744
    if(restore_loglevel){
1074
1745
      /* Restores kernel loglevel to default */
1075
1746
      ret = klogctl(7, NULL, 0);
1076
1747
      if(ret == -1){
1077
 
        perror("klogctl");
1078
 
      }
1079
 
    }
1080
 
#endif
1081
 
  }
1082
 
  
1083
 
  uid = getuid();
1084
 
  gid = getgid();
1085
 
  
1086
 
  errno = 0;
1087
 
  setgid(gid);
1088
 
  if(ret == -1){
1089
 
    perror("setgid");
1090
 
  }
1091
 
  
1092
 
  ret = setuid(uid);
1093
 
  if(ret == -1){
1094
 
    perror("setuid");
1095
 
  }
1096
 
  
1097
 
  ret = init_gnutls_global(&mc, pubkey, seckey);
 
1748
        perror_plus("klogctl");
 
1749
      }
 
1750
    }
 
1751
#endif  /* __linux__ */
 
1752
    /* Lower privileges */
 
1753
    errno = 0;
 
1754
    if(take_down_interface){
 
1755
      /* Lower privileges */
 
1756
      ret = seteuid(uid);
 
1757
      if(ret == -1){
 
1758
        perror_plus("seteuid");
 
1759
      }
 
1760
    } else {
 
1761
      /* Lower privileges permanently */
 
1762
      ret = setuid(uid);
 
1763
      if(ret == -1){
 
1764
        perror_plus("setuid");
 
1765
      }
 
1766
    }
 
1767
  }
 
1768
  
 
1769
  if(quit_now){
 
1770
    goto end;
 
1771
  }
 
1772
  
 
1773
  ret = init_gnutls_global(pubkey, seckey);
1098
1774
  if(ret == -1){
1099
1775
    fprintf(stderr, "init_gnutls_global failed\n");
1100
 
    exitcode = EXIT_FAILURE;
 
1776
    exitcode = EX_UNAVAILABLE;
1101
1777
    goto end;
1102
1778
  } else {
1103
1779
    gnutls_initialized = true;
1104
1780
  }
1105
1781
  
 
1782
  if(quit_now){
 
1783
    goto end;
 
1784
  }
 
1785
  
1106
1786
  if(mkdtemp(tempdir) == NULL){
1107
 
    perror("mkdtemp");
 
1787
    perror_plus("mkdtemp");
1108
1788
    goto end;
1109
1789
  }
1110
1790
  tempdir_created = true;
1111
1791
  
1112
 
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1792
  if(quit_now){
 
1793
    goto end;
 
1794
  }
 
1795
  
 
1796
  if(not init_gpgme(pubkey, seckey, tempdir)){
1113
1797
    fprintf(stderr, "init_gpgme failed\n");
1114
 
    exitcode = EXIT_FAILURE;
 
1798
    exitcode = EX_UNAVAILABLE;
1115
1799
    goto end;
1116
1800
  } else {
1117
1801
    gpgme_initialized = true;
1118
1802
  }
1119
1803
  
1120
 
  if(interface[0] != '\0'){
1121
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1122
 
    if(if_index == 0){
1123
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1124
 
      exitcode = EXIT_FAILURE;
1125
 
      goto end;
1126
 
    }
 
1804
  if(quit_now){
 
1805
    goto end;
1127
1806
  }
1128
1807
  
1129
1808
  if(connect_to != NULL){
1132
1811
    char *address = strrchr(connect_to, ':');
1133
1812
    if(address == NULL){
1134
1813
      fprintf(stderr, "No colon in address\n");
1135
 
      exitcode = EXIT_FAILURE;
1136
 
      goto end;
1137
 
    }
 
1814
      exitcode = EX_USAGE;
 
1815
      goto end;
 
1816
    }
 
1817
    
 
1818
    if(quit_now){
 
1819
      goto end;
 
1820
    }
 
1821
    
1138
1822
    uint16_t port;
1139
 
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1140
 
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
1141
 
       or address[numchars+1] != '\0'){
 
1823
    errno = 0;
 
1824
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1825
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1826
       or tmpmax != (uint16_t)tmpmax){
1142
1827
      fprintf(stderr, "Bad port number\n");
1143
 
      exitcode = EXIT_FAILURE;
1144
 
      goto end;
1145
 
    }
 
1828
      exitcode = EX_USAGE;
 
1829
      goto end;
 
1830
    }
 
1831
  
 
1832
    if(quit_now){
 
1833
      goto end;
 
1834
    }
 
1835
    
1146
1836
    port = (uint16_t)tmpmax;
1147
1837
    *address = '\0';
1148
 
    address = connect_to;
1149
1838
    /* Colon in address indicates IPv6 */
1150
1839
    int af;
1151
 
    if(strchr(address, ':') != NULL){
 
1840
    if(strchr(connect_to, ':') != NULL){
1152
1841
      af = AF_INET6;
 
1842
      /* Accept [] around IPv6 address - see RFC 5952 */
 
1843
      if(connect_to[0] == '[' and address[-1] == ']')
 
1844
        {
 
1845
          connect_to++;
 
1846
          address[-1] = '\0';
 
1847
        }
1153
1848
    } else {
1154
1849
      af = AF_INET;
1155
1850
    }
1156
 
    ret = start_mandos_communication(address, port, if_index, &mc,
1157
 
                                     af);
1158
 
    if(ret < 0){
1159
 
      exitcode = EXIT_FAILURE;
1160
 
    } else {
 
1851
    address = connect_to;
 
1852
    
 
1853
    if(quit_now){
 
1854
      goto end;
 
1855
    }
 
1856
    
 
1857
    while(not quit_now){
 
1858
      ret = start_mandos_communication(address, port, if_index, af);
 
1859
      if(quit_now or ret == 0){
 
1860
        break;
 
1861
      }
 
1862
      if(debug){
 
1863
        fprintf(stderr, "Retrying in %d seconds\n",
 
1864
                (int)retry_interval);
 
1865
      }
 
1866
      sleep((int)retry_interval);
 
1867
    }
 
1868
    
 
1869
    if (not quit_now){
1161
1870
      exitcode = EXIT_SUCCESS;
1162
1871
    }
 
1872
 
1163
1873
    goto end;
1164
1874
  }
1165
1875
  
1166
 
  if(not debug){
1167
 
    avahi_set_log_function(empty_log);
1168
 
  }
1169
 
  
1170
 
  /* Initialize the pseudo-RNG for Avahi */
1171
 
  srand((unsigned int) time(NULL));
1172
 
  
1173
 
  /* Allocate main Avahi loop object */
1174
 
  mc.simple_poll = avahi_simple_poll_new();
1175
 
  if(mc.simple_poll == NULL){
1176
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1177
 
    exitcode = EXIT_FAILURE;
 
1876
  if(quit_now){
1178
1877
    goto end;
1179
1878
  }
1180
1879
  
1200
1899
  if(mc.server == NULL){
1201
1900
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1202
1901
            avahi_strerror(error));
1203
 
    exitcode = EXIT_FAILURE;
 
1902
    exitcode = EX_UNAVAILABLE;
 
1903
    goto end;
 
1904
  }
 
1905
  
 
1906
  if(quit_now){
1204
1907
    goto end;
1205
1908
  }
1206
1909
  
1207
1910
  /* Create the Avahi service browser */
1208
1911
  sb = avahi_s_service_browser_new(mc.server, if_index,
1209
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1210
 
                                   NULL, 0, browse_callback, &mc);
 
1912
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1913
                                   NULL, 0, browse_callback, NULL);
1211
1914
  if(sb == NULL){
1212
1915
    fprintf(stderr, "Failed to create service browser: %s\n",
1213
1916
            avahi_strerror(avahi_server_errno(mc.server)));
1214
 
    exitcode = EXIT_FAILURE;
 
1917
    exitcode = EX_UNAVAILABLE;
 
1918
    goto end;
 
1919
  }
 
1920
  
 
1921
  if(quit_now){
1215
1922
    goto end;
1216
1923
  }
1217
1924
  
1220
1927
  if(debug){
1221
1928
    fprintf(stderr, "Starting Avahi loop search\n");
1222
1929
  }
1223
 
  
1224
 
  avahi_simple_poll_loop(mc.simple_poll);
 
1930
 
 
1931
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
1932
                                (int)(retry_interval * 1000));
 
1933
  if(debug){
 
1934
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1935
            (ret == 0) ? "successfully" : "with error");
 
1936
  }
1225
1937
  
1226
1938
 end:
1227
1939
  
1248
1960
  if(gpgme_initialized){
1249
1961
    gpgme_release(mc.ctx);
1250
1962
  }
1251
 
  
1252
 
  /* Removes the temp directory used by GPGME */
 
1963
 
 
1964
  /* Cleans up the circular linked list of Mandos servers the client
 
1965
     has seen */
 
1966
  if(mc.current_server != NULL){
 
1967
    mc.current_server->prev->next = NULL;
 
1968
    while(mc.current_server != NULL){
 
1969
      server *next = mc.current_server->next;
 
1970
      free(mc.current_server);
 
1971
      mc.current_server = next;
 
1972
    }
 
1973
  }
 
1974
  
 
1975
  /* Take down the network interface */
 
1976
  if(take_down_interface){
 
1977
    /* Re-raise priviliges */
 
1978
    errno = 0;
 
1979
    ret = seteuid(0);
 
1980
    if(ret == -1){
 
1981
      perror_plus("seteuid");
 
1982
    }
 
1983
    if(geteuid() == 0){
 
1984
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1985
      if(ret == -1){
 
1986
        perror_plus("ioctl SIOCGIFFLAGS");
 
1987
      } else if(network.ifr_flags & IFF_UP) {
 
1988
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1989
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1990
        if(ret == -1){
 
1991
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1992
        }
 
1993
      }
 
1994
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1995
      if(ret == -1){
 
1996
        perror_plus("close");
 
1997
      }
 
1998
      /* Lower privileges permanently */
 
1999
      errno = 0;
 
2000
      ret = setuid(uid);
 
2001
      if(ret == -1){
 
2002
        perror_plus("setuid");
 
2003
      }
 
2004
    }
 
2005
  }
 
2006
  
 
2007
  /* Removes the GPGME temp directory and all files inside */
1253
2008
  if(tempdir_created){
1254
 
    DIR *d;
1255
 
    struct dirent *direntry;
1256
 
    d = opendir(tempdir);
1257
 
    if(d == NULL){
1258
 
      if(errno != ENOENT){
1259
 
        perror("opendir");
1260
 
      }
1261
 
    } else {
1262
 
      while(true){
1263
 
        direntry = readdir(d);
1264
 
        if(direntry == NULL){
1265
 
          break;
1266
 
        }
1267
 
        /* Skip "." and ".." */
1268
 
        if(direntry->d_name[0] == '.'
1269
 
           and (direntry->d_name[1] == '\0'
1270
 
                or (direntry->d_name[1] == '.'
1271
 
                    and direntry->d_name[2] == '\0'))){
1272
 
          continue;
1273
 
        }
 
2009
    struct dirent **direntries = NULL;
 
2010
    struct dirent *direntry = NULL;
 
2011
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2012
                             alphasort);
 
2013
    if (numentries > 0){
 
2014
      for(int i = 0; i < numentries; i++){
 
2015
        direntry = direntries[i];
1274
2016
        char *fullname = NULL;
1275
2017
        ret = asprintf(&fullname, "%s/%s", tempdir,
1276
2018
                       direntry->d_name);
1277
2019
        if(ret < 0){
1278
 
          perror("asprintf");
 
2020
          perror_plus("asprintf");
1279
2021
          continue;
1280
2022
        }
1281
2023
        ret = remove(fullname);
1285
2027
        }
1286
2028
        free(fullname);
1287
2029
      }
1288
 
      closedir(d);
 
2030
    }
 
2031
 
 
2032
    /* need to clean even if 0 because man page doesn't specify */
 
2033
    free(direntries);
 
2034
    if (numentries == -1){
 
2035
      perror_plus("scandir");
1289
2036
    }
1290
2037
    ret = rmdir(tempdir);
1291
2038
    if(ret == -1 and errno != ENOENT){
1292
 
      perror("rmdir");
1293
 
    }
 
2039
      perror_plus("rmdir");
 
2040
    }
 
2041
  }
 
2042
  
 
2043
  if(quit_now){
 
2044
    sigemptyset(&old_sigterm_action.sa_mask);
 
2045
    old_sigterm_action.sa_handler = SIG_DFL;
 
2046
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
2047
                                            &old_sigterm_action,
 
2048
                                            NULL));
 
2049
    if(ret == -1){
 
2050
      perror_plus("sigaction");
 
2051
    }
 
2052
    do {
 
2053
      ret = raise(signal_received);
 
2054
    } while(ret != 0 and errno == EINTR);
 
2055
    if(ret != 0){
 
2056
      perror_plus("raise");
 
2057
      abort();
 
2058
    }
 
2059
    TEMP_FAILURE_RETRY(pause());
1294
2060
  }
1295
2061
  
1296
2062
  return exitcode;