/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-08-30 03:10:29 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090830031029-cj8po3rc4g1cux1d
* mandos: White-space fixes only.
* mandos-ctl: - '' -
* plugin-runner.c: - '' -
* plugins.d/askpass-fifo.c: - '' -
* plugins.d/mandos-client.c: - '' -
* plugins.d/password-prompt.c: - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
45
 
#include <stdbool.h>            /* bool, true */
 
47
                                   srand(), strtof() */
 
48
#include <stdbool.h>            /* bool, false, true */
46
49
#include <string.h>             /* memset(), strcmp(), strlen(),
47
50
                                   strerror(), asprintf(), strcpy() */
48
 
#include <sys/ioctl.h>          /* ioctl */
 
51
#include <sys/ioctl.h>          /* ioctl */
49
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
53
                                   sockaddr_in6, PF_INET6,
51
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
52
 
                                   uid_t, gid_t, open(), opendir(),
53
 
                                   DIR */
 
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
 
55
                                   opendir(), DIR */
54
56
#include <sys/stat.h>           /* open() */
55
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
56
 
                                   struct in6_addr, inet_pton(),
57
 
                                   connect() */
 
58
                                   inet_pton(), connect() */
58
59
#include <fcntl.h>              /* open() */
59
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
60
61
                                 */
61
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
 
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
 
63
                                   strtoimax() */
62
64
#include <assert.h>             /* assert() */
63
65
#include <errno.h>              /* perror(), errno */
64
66
#include <time.h>               /* nanosleep(), time() */
65
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
66
68
                                   SIOCSIFFLAGS, if_indextoname(),
67
69
                                   if_nametoindex(), IF_NAMESIZE */
68
 
#include <netinet/in.h>
 
70
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
 
71
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
 
72
                                */
69
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
74
                                   getuid(), getgid(), setuid(),
71
75
                                   setgid() */
72
76
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, and, or */
 
77
#include <iso646.h>             /* not, or, and */
74
78
#include <argp.h>               /* struct argp_option, error_t, struct
75
79
                                   argp_state, struct argp,
76
80
                                   argp_parse(), ARGP_KEY_ARG,
77
81
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
 
83
                                   sigaction(), SIGTERM, sig_atomic_t,
 
84
                                   raise() */
 
85
 
 
86
#ifdef __linux__
78
87
#include <sys/klog.h>           /* klogctl() */
 
88
#endif  /* __linux__ */
79
89
 
80
90
/* Avahi */
81
91
/* All Avahi types, constants and functions
127
137
  gpgme_ctx_t ctx;
128
138
} mandos_context;
129
139
 
 
140
/* global context so signal handler can reach it*/
 
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
142
                      .dh_bits = 1024, .priority = "SECURE256"
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
144
 
130
145
/*
131
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
132
 
 * "buffer_capacity" is how much is currently allocated,
 
146
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
147
 * bytes. "buffer_capacity" is how much is currently allocated,
133
148
 * "buffer_length" is how much is already used.
134
149
 */
135
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
150
size_t incbuffer(char **buffer, size_t buffer_length,
136
151
                  size_t buffer_capacity){
137
152
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
138
153
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
147
162
/* 
148
163
 * Initialize GPGME.
149
164
 */
150
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
165
static bool init_gpgme(const char *seckey,
151
166
                       const char *pubkey, const char *tempdir){
152
167
  int ret;
153
168
  gpgme_error_t rc;
174
189
      return false;
175
190
    }
176
191
    
177
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
192
    rc = gpgme_op_import(mc.ctx, pgp_data);
178
193
    if(rc != GPG_ERR_NO_ERROR){
179
194
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
180
195
              gpgme_strsource(rc), gpgme_strerror(rc));
190
205
  }
191
206
  
192
207
  if(debug){
193
 
    fprintf(stderr, "Initialize gpgme\n");
 
208
    fprintf(stderr, "Initializing GPGME\n");
194
209
  }
195
210
  
196
211
  /* Init GPGME */
223
238
  }
224
239
  
225
240
  /* Create new GPGME "context" */
226
 
  rc = gpgme_new(&(mc->ctx));
 
241
  rc = gpgme_new(&(mc.ctx));
227
242
  if(rc != GPG_ERR_NO_ERROR){
228
243
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
229
244
            gpgme_strsource(rc), gpgme_strerror(rc));
234
249
    return false;
235
250
  }
236
251
  
237
 
  return true; 
 
252
  return true;
238
253
}
239
254
 
240
255
/* 
241
256
 * Decrypt OpenPGP data.
242
257
 * Returns -1 on error
243
258
 */
244
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
245
 
                                  const char *cryptotext,
 
259
static ssize_t pgp_packet_decrypt(const char *cryptotext,
246
260
                                  size_t crypto_size,
247
261
                                  char **plaintext){
248
262
  gpgme_data_t dh_crypto, dh_plain;
275
289
  
276
290
  /* Decrypt data from the cryptotext data buffer to the plaintext
277
291
     data buffer */
278
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
292
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
279
293
  if(rc != GPG_ERR_NO_ERROR){
280
294
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
281
295
            gpgme_strsource(rc), gpgme_strerror(rc));
282
296
    plaintext_length = -1;
283
297
    if(debug){
284
298
      gpgme_decrypt_result_t result;
285
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
299
      result = gpgme_op_decrypt_result(mc.ctx);
286
300
      if(result == NULL){
287
301
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
288
302
      } else {
295
309
        }
296
310
        gpgme_recipient_t recipient;
297
311
        recipient = result->recipients;
298
 
        if(recipient){
299
 
          while(recipient != NULL){
300
 
            fprintf(stderr, "Public key algorithm: %s\n",
301
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
302
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
303
 
            fprintf(stderr, "Secret key available: %s\n",
304
 
                    recipient->status == GPG_ERR_NO_SECKEY
305
 
                    ? "No" : "Yes");
306
 
            recipient = recipient->next;
307
 
          }
 
312
        while(recipient != NULL){
 
313
          fprintf(stderr, "Public key algorithm: %s\n",
 
314
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
315
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
316
          fprintf(stderr, "Secret key available: %s\n",
 
317
                  recipient->status == GPG_ERR_NO_SECKEY
 
318
                  ? "No" : "Yes");
 
319
          recipient = recipient->next;
308
320
        }
309
321
      }
310
322
    }
324
336
  
325
337
  *plaintext = NULL;
326
338
  while(true){
327
 
    plaintext_capacity = adjustbuffer(plaintext,
 
339
    plaintext_capacity = incbuffer(plaintext,
328
340
                                      (size_t)plaintext_length,
329
341
                                      plaintext_capacity);
330
342
    if(plaintext_capacity == 0){
331
 
        perror("adjustbuffer");
 
343
        perror("incbuffer");
332
344
        plaintext_length = -1;
333
345
        goto decrypt_end;
334
346
    }
366
378
  return plaintext_length;
367
379
}
368
380
 
369
 
static const char * safer_gnutls_strerror(int value) {
 
381
static const char * safer_gnutls_strerror(int value){
370
382
  const char *ret = gnutls_strerror(value); /* Spurious warning from
371
383
                                               -Wunreachable-code */
372
384
  if(ret == NULL)
380
392
  fprintf(stderr, "GnuTLS: %s", string);
381
393
}
382
394
 
383
 
static int init_gnutls_global(mandos_context *mc,
384
 
                              const char *pubkeyfilename,
 
395
static int init_gnutls_global(const char *pubkeyfilename,
385
396
                              const char *seckeyfilename){
386
397
  int ret;
387
398
  
390
401
  }
391
402
  
392
403
  ret = gnutls_global_init();
393
 
  if(ret != GNUTLS_E_SUCCESS) {
 
404
  if(ret != GNUTLS_E_SUCCESS){
394
405
    fprintf(stderr, "GnuTLS global_init: %s\n",
395
406
            safer_gnutls_strerror(ret));
396
407
    return -1;
405
416
  }
406
417
  
407
418
  /* OpenPGP credentials */
408
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
419
  gnutls_certificate_allocate_credentials(&mc.cred);
409
420
  if(ret != GNUTLS_E_SUCCESS){
410
421
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
411
 
                                                  * from
412
 
                                                  * -Wunreachable-code
413
 
                                                  */
 
422
                                                    from
 
423
                                                    -Wunreachable-code
 
424
                                                 */
414
425
            safer_gnutls_strerror(ret));
415
426
    gnutls_global_deinit();
416
427
    return -1;
423
434
  }
424
435
  
425
436
  ret = gnutls_certificate_set_openpgp_key_file
426
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
437
    (mc.cred, pubkeyfilename, seckeyfilename,
427
438
     GNUTLS_OPENPGP_FMT_BASE64);
428
 
  if(ret != GNUTLS_E_SUCCESS) {
 
439
  if(ret != GNUTLS_E_SUCCESS){
429
440
    fprintf(stderr,
430
441
            "Error[%d] while reading the OpenPGP key pair ('%s',"
431
442
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
435
446
  }
436
447
  
437
448
  /* GnuTLS server initialization */
438
 
  ret = gnutls_dh_params_init(&mc->dh_params);
439
 
  if(ret != GNUTLS_E_SUCCESS) {
 
449
  ret = gnutls_dh_params_init(&mc.dh_params);
 
450
  if(ret != GNUTLS_E_SUCCESS){
440
451
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
441
452
            " %s\n", safer_gnutls_strerror(ret));
442
453
    goto globalfail;
443
454
  }
444
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
445
 
  if(ret != GNUTLS_E_SUCCESS) {
 
455
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
456
  if(ret != GNUTLS_E_SUCCESS){
446
457
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
447
458
            safer_gnutls_strerror(ret));
448
459
    goto globalfail;
449
460
  }
450
461
  
451
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
462
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
452
463
  
453
464
  return 0;
454
465
  
455
466
 globalfail:
456
467
  
457
 
  gnutls_certificate_free_credentials(mc->cred);
 
468
  gnutls_certificate_free_credentials(mc.cred);
458
469
  gnutls_global_deinit();
459
 
  gnutls_dh_params_deinit(mc->dh_params);
 
470
  gnutls_dh_params_deinit(mc.dh_params);
460
471
  return -1;
461
472
}
462
473
 
463
 
static int init_gnutls_session(mandos_context *mc,
464
 
                               gnutls_session_t *session){
 
474
static int init_gnutls_session(gnutls_session_t *session){
465
475
  int ret;
466
476
  /* GnuTLS session creation */
467
477
  ret = gnutls_init(session, GNUTLS_SERVER);
472
482
  
473
483
  {
474
484
    const char *err;
475
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
476
 
    if(ret != GNUTLS_E_SUCCESS) {
 
485
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
486
    if(ret != GNUTLS_E_SUCCESS){
477
487
      fprintf(stderr, "Syntax error at: %s\n", err);
478
488
      fprintf(stderr, "GnuTLS error: %s\n",
479
489
              safer_gnutls_strerror(ret));
483
493
  }
484
494
  
485
495
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
486
 
                               mc->cred);
487
 
  if(ret != GNUTLS_E_SUCCESS) {
 
496
                               mc.cred);
 
497
  if(ret != GNUTLS_E_SUCCESS){
488
498
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
489
499
            safer_gnutls_strerror(ret));
490
500
    gnutls_deinit(*session);
495
505
  gnutls_certificate_server_set_request(*session,
496
506
                                        GNUTLS_CERT_IGNORE);
497
507
  
498
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
508
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
499
509
  
500
510
  return 0;
501
511
}
504
514
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
505
515
                      __attribute__((unused)) const char *txt){}
506
516
 
 
517
sig_atomic_t quit_now = 0;
 
518
int signal_received = 0;
 
519
 
507
520
/* Called when a Mandos server is found */
508
521
static int start_mandos_communication(const char *ip, uint16_t port,
509
522
                                      AvahiIfIndex if_index,
510
 
                                      mandos_context *mc){
 
523
                                      int af){
511
524
  int ret, tcp_sd;
512
525
  ssize_t sret;
513
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
526
  union {
 
527
    struct sockaddr_in in;
 
528
    struct sockaddr_in6 in6;
 
529
  } to;
514
530
  char *buffer = NULL;
515
531
  char *decrypted_buffer;
516
532
  size_t buffer_length = 0;
518
534
  ssize_t decrypted_buffer_size;
519
535
  size_t written;
520
536
  int retval = 0;
521
 
  char interface[IF_NAMESIZE];
522
537
  gnutls_session_t session;
523
 
  
524
 
  ret = init_gnutls_session(mc, &session);
 
538
  int pf;                       /* Protocol family */
 
539
  
 
540
  switch(af){
 
541
  case AF_INET6:
 
542
    pf = PF_INET6;
 
543
    break;
 
544
  case AF_INET:
 
545
    pf = PF_INET;
 
546
    break;
 
547
  default:
 
548
    fprintf(stderr, "Bad address family: %d\n", af);
 
549
    return -1;
 
550
  }
 
551
  
 
552
  ret = init_gnutls_session(&session);
525
553
  if(ret != 0){
526
554
    return -1;
527
555
  }
528
556
  
529
557
  if(debug){
530
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
558
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
531
559
            "\n", ip, port);
532
560
  }
533
561
  
534
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
535
 
  if(tcp_sd < 0) {
 
562
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
563
  if(tcp_sd < 0){
536
564
    perror("socket");
537
565
    return -1;
538
566
  }
539
567
  
540
 
  if(debug){
541
 
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
542
 
      perror("if_indextoname");
543
 
      return -1;
544
 
    }
545
 
    fprintf(stderr, "Binding to interface %s\n", interface);
546
 
  }
547
 
  
548
568
  memset(&to, 0, sizeof(to));
549
 
  to.in6.sin6_family = AF_INET6;
550
 
  /* It would be nice to have a way to detect if we were passed an
551
 
     IPv4 address here.   Now we assume an IPv6 address. */
552
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
 
569
  if(af == AF_INET6){
 
570
    to.in6.sin6_family = (sa_family_t)af;
 
571
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
572
  } else {                      /* IPv4 */
 
573
    to.in.sin_family = (sa_family_t)af;
 
574
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
575
  }
553
576
  if(ret < 0 ){
554
577
    perror("inet_pton");
555
578
    return -1;
558
581
    fprintf(stderr, "Bad address: %s\n", ip);
559
582
    return -1;
560
583
  }
561
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
584
  if(af == AF_INET6){
 
585
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
586
                                       -Wconversion and
 
587
                                       -Wunreachable-code */
 
588
    
 
589
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
590
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
591
                              -Wunreachable-code*/
 
592
      if(if_index == AVAHI_IF_UNSPEC){
 
593
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
594
                " without a network interface\n");
 
595
        return -1;
 
596
      }
 
597
      /* Set the network interface number as scope */
 
598
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
599
    }
 
600
  } else {
 
601
    to.in.sin_port = htons(port); /* Spurious warnings from
562
602
                                     -Wconversion and
563
603
                                     -Wunreachable-code */
564
 
  
565
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
604
  }
566
605
  
567
606
  if(debug){
568
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
569
 
            port);
570
 
    char addrstr[INET6_ADDRSTRLEN] = "";
571
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
572
 
                 sizeof(addrstr)) == NULL){
 
607
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
608
      char interface[IF_NAMESIZE];
 
609
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
610
        perror("if_indextoname");
 
611
      } else {
 
612
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
613
                ip, interface, port);
 
614
      }
 
615
    } else {
 
616
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
617
              port);
 
618
    }
 
619
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
620
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
621
    const char *pcret;
 
622
    if(af == AF_INET6){
 
623
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
624
                        sizeof(addrstr));
 
625
    } else {
 
626
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
627
                        sizeof(addrstr));
 
628
    }
 
629
    if(pcret == NULL){
573
630
      perror("inet_ntop");
574
631
    } else {
575
632
      if(strcmp(addrstr, ip) != 0){
578
635
    }
579
636
  }
580
637
  
581
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
638
  if(af == AF_INET6){
 
639
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
640
  } else {
 
641
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
642
  }
582
643
  if(ret < 0){
583
644
    perror("connect");
584
645
    return -1;
630
691
  /* Read OpenPGP packet that contains the wanted password */
631
692
  
632
693
  if(debug){
633
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
694
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
634
695
            ip);
635
696
  }
636
697
  
637
698
  while(true){
638
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
699
    buffer_capacity = incbuffer(&buffer, buffer_length,
639
700
                                   buffer_capacity);
640
701
    if(buffer_capacity == 0){
641
 
      perror("adjustbuffer");
 
702
      perror("incbuffer");
642
703
      retval = -1;
643
704
      goto mandos_end;
644
705
    }
683
744
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
684
745
  
685
746
  if(buffer_length > 0){
686
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
747
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
687
748
                                               buffer_length,
688
749
                                               &decrypted_buffer);
689
750
    if(decrypted_buffer_size >= 0){
724
785
 
725
786
static void resolve_callback(AvahiSServiceResolver *r,
726
787
                             AvahiIfIndex interface,
727
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
788
                             AvahiProtocol proto,
728
789
                             AvahiResolverEvent event,
729
790
                             const char *name,
730
791
                             const char *type,
735
796
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
736
797
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
737
798
                             flags,
738
 
                             void* userdata) {
739
 
  mandos_context *mc = userdata;
 
799
                             AVAHI_GCC_UNUSED void* userdata){
740
800
  assert(r);
741
801
  
742
802
  /* Called whenever a service has been resolved successfully or
743
803
     timed out */
744
804
  
745
 
  switch(event) {
 
805
  if(quit_now){
 
806
    return;
 
807
  }
 
808
  
 
809
  switch(event){
746
810
  default:
747
811
  case AVAHI_RESOLVER_FAILURE:
748
812
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
749
813
            " of type '%s' in domain '%s': %s\n", name, type, domain,
750
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
814
            avahi_strerror(avahi_server_errno(mc.server)));
751
815
    break;
752
816
    
753
817
  case AVAHI_RESOLVER_FOUND:
759
823
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
760
824
                ip, (intmax_t)interface, port);
761
825
      }
762
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
826
      int ret = start_mandos_communication(ip, port, interface,
 
827
                                           avahi_proto_to_af(proto));
763
828
      if(ret == 0){
764
 
        avahi_simple_poll_quit(mc->simple_poll);
 
829
        avahi_simple_poll_quit(mc.simple_poll);
765
830
      }
766
831
    }
767
832
  }
768
833
  avahi_s_service_resolver_free(r);
769
834
}
770
835
 
771
 
static void browse_callback( AvahiSServiceBrowser *b,
772
 
                             AvahiIfIndex interface,
773
 
                             AvahiProtocol protocol,
774
 
                             AvahiBrowserEvent event,
775
 
                             const char *name,
776
 
                             const char *type,
777
 
                             const char *domain,
778
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
779
 
                             flags,
780
 
                             void* userdata) {
781
 
  mandos_context *mc = userdata;
 
836
static void browse_callback(AvahiSServiceBrowser *b,
 
837
                            AvahiIfIndex interface,
 
838
                            AvahiProtocol protocol,
 
839
                            AvahiBrowserEvent event,
 
840
                            const char *name,
 
841
                            const char *type,
 
842
                            const char *domain,
 
843
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
844
                            flags,
 
845
                            AVAHI_GCC_UNUSED void* userdata){
782
846
  assert(b);
783
847
  
784
848
  /* Called whenever a new services becomes available on the LAN or
785
849
     is removed from the LAN */
786
850
  
787
 
  switch(event) {
 
851
  switch(event){
788
852
  default:
789
853
  case AVAHI_BROWSER_FAILURE:
790
854
    
791
855
    fprintf(stderr, "(Avahi browser) %s\n",
792
 
            avahi_strerror(avahi_server_errno(mc->server)));
793
 
    avahi_simple_poll_quit(mc->simple_poll);
 
856
            avahi_strerror(avahi_server_errno(mc.server)));
 
857
    avahi_simple_poll_quit(mc.simple_poll);
794
858
    return;
795
859
    
796
860
  case AVAHI_BROWSER_NEW:
799
863
       the callback function is called the Avahi server will free the
800
864
       resolver for us. */
801
865
    
802
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
803
 
                                       protocol, name, type, domain,
804
 
                                       AVAHI_PROTO_INET6, 0,
805
 
                                       resolve_callback, mc)))
 
866
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
867
                                    name, type, domain, protocol, 0,
 
868
                                    resolve_callback, NULL) == NULL)
806
869
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
807
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
870
              name, avahi_strerror(avahi_server_errno(mc.server)));
808
871
    break;
809
872
    
810
873
  case AVAHI_BROWSER_REMOVE:
819
882
  }
820
883
}
821
884
 
 
885
/* stop main loop after sigterm has been called */
 
886
static void handle_sigterm(int sig){
 
887
  if(quit_now){
 
888
    return;
 
889
  }
 
890
  quit_now = 1;
 
891
  signal_received = sig;
 
892
  int old_errno = errno;
 
893
  if(mc.simple_poll != NULL){
 
894
    avahi_simple_poll_quit(mc.simple_poll);
 
895
  }
 
896
  errno = old_errno;
 
897
}
 
898
 
822
899
int main(int argc, char *argv[]){
823
 
    AvahiSServiceBrowser *sb = NULL;
824
 
    int error;
825
 
    int ret;
826
 
    intmax_t tmpmax;
827
 
    int numchars;
828
 
    int exitcode = EXIT_SUCCESS;
829
 
    const char *interface = "eth0";
830
 
    struct ifreq network;
831
 
    int sd;
832
 
    uid_t uid;
833
 
    gid_t gid;
834
 
    char *connect_to = NULL;
835
 
    char tempdir[] = "/tmp/mandosXXXXXX";
836
 
    bool tempdir_created = false;
837
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
838
 
    const char *seckey = PATHDIR "/" SECKEY;
839
 
    const char *pubkey = PATHDIR "/" PUBKEY;
840
 
    
841
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
842
 
                          .dh_bits = 1024, .priority = "SECURE256"
843
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
844
 
    bool gnutls_initialized = false;
845
 
    bool gpgme_initialized = false;
846
 
    double delay = 2.5;
847
 
    
848
 
    {
849
 
      struct argp_option options[] = {
850
 
        { .name = "debug", .key = 128,
851
 
          .doc = "Debug mode", .group = 3 },
852
 
        { .name = "connect", .key = 'c',
853
 
          .arg = "ADDRESS:PORT",
854
 
          .doc = "Connect directly to a specific Mandos server",
855
 
          .group = 1 },
856
 
        { .name = "interface", .key = 'i',
857
 
          .arg = "NAME",
858
 
          .doc = "Interface that will be used to search for Mandos"
859
 
          " servers",
860
 
          .group = 1 },
861
 
        { .name = "seckey", .key = 's',
862
 
          .arg = "FILE",
863
 
          .doc = "OpenPGP secret key file base name",
864
 
          .group = 1 },
865
 
        { .name = "pubkey", .key = 'p',
866
 
          .arg = "FILE",
867
 
          .doc = "OpenPGP public key file base name",
868
 
          .group = 2 },
869
 
        { .name = "dh-bits", .key = 129,
870
 
          .arg = "BITS",
871
 
          .doc = "Bit length of the prime number used in the"
872
 
          " Diffie-Hellman key exchange",
873
 
          .group = 2 },
874
 
        { .name = "priority", .key = 130,
875
 
          .arg = "STRING",
876
 
          .doc = "GnuTLS priority string for the TLS handshake",
877
 
          .group = 1 },
878
 
        { .name = "delay", .key = 131,
879
 
          .arg = "SECONDS",
880
 
          .doc = "Maximum delay to wait for interface startup",
881
 
          .group = 2 },
882
 
        { .name = NULL }
883
 
      };
884
 
      
885
 
      error_t parse_opt(int key, char *arg,
886
 
                        struct argp_state *state) {
887
 
        switch(key) {
888
 
        case 128:               /* --debug */
889
 
          debug = true;
890
 
          break;
891
 
        case 'c':               /* --connect */
892
 
          connect_to = arg;
893
 
          break;
894
 
        case 'i':               /* --interface */
895
 
          interface = arg;
896
 
          break;
897
 
        case 's':               /* --seckey */
898
 
          seckey = arg;
899
 
          break;
900
 
        case 'p':               /* --pubkey */
901
 
          pubkey = arg;
902
 
          break;
903
 
        case 129:               /* --dh-bits */
904
 
          ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
905
 
          if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
906
 
             or arg[numchars] != '\0'){
907
 
            fprintf(stderr, "Bad number of DH bits\n");
908
 
            exit(EXIT_FAILURE);
909
 
          }
910
 
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
911
 
          break;
912
 
        case 130:               /* --priority */
913
 
          mc.priority = arg;
914
 
          break;
915
 
        case 131:               /* --delay */
916
 
          ret = sscanf(arg, "%lf%n", &delay, &numchars);
917
 
          if(ret < 1 or arg[numchars] != '\0'){
918
 
            fprintf(stderr, "Bad delay\n");
919
 
            exit(EXIT_FAILURE);
920
 
          }
921
 
          break;
922
 
        case ARGP_KEY_ARG:
923
 
          argp_usage(state);
924
 
        case ARGP_KEY_END:
925
 
          break;
926
 
        default:
927
 
          return ARGP_ERR_UNKNOWN;
928
 
        }
929
 
        return 0;
930
 
      }
931
 
      
932
 
      struct argp argp = { .options = options, .parser = parse_opt,
933
 
                           .args_doc = "",
934
 
                           .doc = "Mandos client -- Get and decrypt"
935
 
                           " passwords from a Mandos server" };
936
 
      ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
937
 
      if(ret == ARGP_ERR_UNKNOWN){
938
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
939
 
        exitcode = EXIT_FAILURE;
940
 
        goto end;
941
 
      }
942
 
    }
943
 
    
944
 
    /* If the interface is down, bring it up */
945
 
    {
946
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
947
 
         messages to mess up the prompt */
948
 
      ret = klogctl(8, NULL, 5);
 
900
  AvahiSServiceBrowser *sb = NULL;
 
901
  int error;
 
902
  int ret;
 
903
  intmax_t tmpmax;
 
904
  char *tmp;
 
905
  int exitcode = EXIT_SUCCESS;
 
906
  const char *interface = "eth0";
 
907
  struct ifreq network;
 
908
  int sd = -1;
 
909
  bool take_down_interface = false;
 
910
  uid_t uid;
 
911
  gid_t gid;
 
912
  char *connect_to = NULL;
 
913
  char tempdir[] = "/tmp/mandosXXXXXX";
 
914
  bool tempdir_created = false;
 
915
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
916
  const char *seckey = PATHDIR "/" SECKEY;
 
917
  const char *pubkey = PATHDIR "/" PUBKEY;
 
918
  
 
919
  bool gnutls_initialized = false;
 
920
  bool gpgme_initialized = false;
 
921
  float delay = 2.5f;
 
922
  
 
923
  struct sigaction old_sigterm_action;
 
924
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
925
  
 
926
  {
 
927
    struct argp_option options[] = {
 
928
      { .name = "debug", .key = 128,
 
929
        .doc = "Debug mode", .group = 3 },
 
930
      { .name = "connect", .key = 'c',
 
931
        .arg = "ADDRESS:PORT",
 
932
        .doc = "Connect directly to a specific Mandos server",
 
933
        .group = 1 },
 
934
      { .name = "interface", .key = 'i',
 
935
        .arg = "NAME",
 
936
        .doc = "Network interface that will be used to search for"
 
937
        " Mandos servers",
 
938
        .group = 1 },
 
939
      { .name = "seckey", .key = 's',
 
940
        .arg = "FILE",
 
941
        .doc = "OpenPGP secret key file base name",
 
942
        .group = 1 },
 
943
      { .name = "pubkey", .key = 'p',
 
944
        .arg = "FILE",
 
945
        .doc = "OpenPGP public key file base name",
 
946
        .group = 2 },
 
947
      { .name = "dh-bits", .key = 129,
 
948
        .arg = "BITS",
 
949
        .doc = "Bit length of the prime number used in the"
 
950
        " Diffie-Hellman key exchange",
 
951
        .group = 2 },
 
952
      { .name = "priority", .key = 130,
 
953
        .arg = "STRING",
 
954
        .doc = "GnuTLS priority string for the TLS handshake",
 
955
        .group = 1 },
 
956
      { .name = "delay", .key = 131,
 
957
        .arg = "SECONDS",
 
958
        .doc = "Maximum delay to wait for interface startup",
 
959
        .group = 2 },
 
960
      { .name = NULL }
 
961
    };
 
962
    
 
963
    error_t parse_opt(int key, char *arg,
 
964
                      struct argp_state *state){
 
965
      switch(key){
 
966
      case 128:                 /* --debug */
 
967
        debug = true;
 
968
        break;
 
969
      case 'c':                 /* --connect */
 
970
        connect_to = arg;
 
971
        break;
 
972
      case 'i':                 /* --interface */
 
973
        interface = arg;
 
974
        break;
 
975
      case 's':                 /* --seckey */
 
976
        seckey = arg;
 
977
        break;
 
978
      case 'p':                 /* --pubkey */
 
979
        pubkey = arg;
 
980
        break;
 
981
      case 129:                 /* --dh-bits */
 
982
        errno = 0;
 
983
        tmpmax = strtoimax(arg, &tmp, 10);
 
984
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
985
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
986
          fprintf(stderr, "Bad number of DH bits\n");
 
987
          exit(EXIT_FAILURE);
 
988
        }
 
989
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
990
        break;
 
991
      case 130:                 /* --priority */
 
992
        mc.priority = arg;
 
993
        break;
 
994
      case 131:                 /* --delay */
 
995
        errno = 0;
 
996
        delay = strtof(arg, &tmp);
 
997
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
998
          fprintf(stderr, "Bad delay\n");
 
999
          exit(EXIT_FAILURE);
 
1000
        }
 
1001
        break;
 
1002
      case ARGP_KEY_ARG:
 
1003
        argp_usage(state);
 
1004
      case ARGP_KEY_END:
 
1005
        break;
 
1006
      default:
 
1007
        return ARGP_ERR_UNKNOWN;
 
1008
      }
 
1009
      return 0;
 
1010
    }
 
1011
    
 
1012
    struct argp argp = { .options = options, .parser = parse_opt,
 
1013
                         .args_doc = "",
 
1014
                         .doc = "Mandos client -- Get and decrypt"
 
1015
                         " passwords from a Mandos server" };
 
1016
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1017
    if(ret == ARGP_ERR_UNKNOWN){
 
1018
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1019
      exitcode = EXIT_FAILURE;
 
1020
      goto end;
 
1021
    }
 
1022
  }
 
1023
  
 
1024
  if(not debug){
 
1025
    avahi_set_log_function(empty_log);
 
1026
  }
 
1027
  
 
1028
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1029
     from the signal handler */
 
1030
  /* Initialize the pseudo-RNG for Avahi */
 
1031
  srand((unsigned int) time(NULL));
 
1032
  mc.simple_poll = avahi_simple_poll_new();
 
1033
  if(mc.simple_poll == NULL){
 
1034
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1035
    exitcode = EXIT_FAILURE;
 
1036
    goto end;
 
1037
  }
 
1038
  
 
1039
  sigemptyset(&sigterm_action.sa_mask);
 
1040
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1041
  if(ret == -1){
 
1042
    perror("sigaddset");
 
1043
    exitcode = EXIT_FAILURE;
 
1044
    goto end;
 
1045
  }
 
1046
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1047
  if(ret == -1){
 
1048
    perror("sigaddset");
 
1049
    exitcode = EXIT_FAILURE;
 
1050
    goto end;
 
1051
  }
 
1052
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1053
  if(ret == -1){
 
1054
    perror("sigaddset");
 
1055
    exitcode = EXIT_FAILURE;
 
1056
    goto end;
 
1057
  }
 
1058
  ret = sigaction(SIGINT, &sigterm_action, &old_sigterm_action);
 
1059
  if(ret == -1){
 
1060
    perror("sigaction");
 
1061
    exitcode = EXIT_FAILURE;
 
1062
    goto end;
 
1063
  }
 
1064
  ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1065
  if(ret == -1){
 
1066
    perror("sigaction");
 
1067
    exitcode = EXIT_FAILURE;
 
1068
    goto end;
 
1069
  }
 
1070
  ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1071
  if(ret == -1){
 
1072
    perror("sigaction");
 
1073
    exitcode = EXIT_FAILURE;
 
1074
    goto end;
 
1075
  }
 
1076
  
 
1077
  /* If the interface is down, bring it up */
 
1078
  if(interface[0] != '\0'){
 
1079
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1080
    if(if_index == 0){
 
1081
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1082
      exitcode = EXIT_FAILURE;
 
1083
      goto end;
 
1084
    }
 
1085
    
 
1086
    if(quit_now){
 
1087
      goto end;
 
1088
    }
 
1089
    
 
1090
#ifdef __linux__
 
1091
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1092
       messages to mess up the prompt */
 
1093
    ret = klogctl(8, NULL, 5);
 
1094
    bool restore_loglevel = true;
 
1095
    if(ret == -1){
 
1096
      restore_loglevel = false;
 
1097
      perror("klogctl");
 
1098
    }
 
1099
#endif  /* __linux__ */
 
1100
    
 
1101
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1102
    if(sd < 0){
 
1103
      perror("socket");
 
1104
      exitcode = EXIT_FAILURE;
 
1105
#ifdef __linux__
 
1106
      if(restore_loglevel){
 
1107
        ret = klogctl(7, NULL, 0);
 
1108
        if(ret == -1){
 
1109
          perror("klogctl");
 
1110
        }
 
1111
      }
 
1112
#endif  /* __linux__ */
 
1113
      goto end;
 
1114
    }
 
1115
    strcpy(network.ifr_name, interface);
 
1116
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1117
    if(ret == -1){
 
1118
      perror("ioctl SIOCGIFFLAGS");
 
1119
#ifdef __linux__
 
1120
      if(restore_loglevel){
 
1121
        ret = klogctl(7, NULL, 0);
 
1122
        if(ret == -1){
 
1123
          perror("klogctl");
 
1124
        }
 
1125
      }
 
1126
#endif  /* __linux__ */
 
1127
      exitcode = EXIT_FAILURE;
 
1128
      goto end;
 
1129
    }
 
1130
    if((network.ifr_flags & IFF_UP) == 0){
 
1131
      network.ifr_flags |= IFF_UP;
 
1132
      take_down_interface = true;
 
1133
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
949
1134
      if(ret == -1){
950
 
        perror("klogctl");
951
 
      }
952
 
      
953
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
954
 
      if(sd < 0) {
955
 
        perror("socket");
 
1135
        take_down_interface = false;
 
1136
        perror("ioctl SIOCSIFFLAGS");
956
1137
        exitcode = EXIT_FAILURE;
957
 
        ret = klogctl(7, NULL, 0);
958
 
        if(ret == -1){
959
 
          perror("klogctl");
 
1138
#ifdef __linux__
 
1139
        if(restore_loglevel){
 
1140
          ret = klogctl(7, NULL, 0);
 
1141
          if(ret == -1){
 
1142
            perror("klogctl");
 
1143
          }
960
1144
        }
 
1145
#endif  /* __linux__ */
961
1146
        goto end;
962
1147
      }
963
 
      strcpy(network.ifr_name, interface);
 
1148
    }
 
1149
    /* sleep checking until interface is running */
 
1150
    for(int i=0; i < delay * 4; i++){
964
1151
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
965
1152
      if(ret == -1){
966
1153
        perror("ioctl SIOCGIFFLAGS");
967
 
        ret = klogctl(7, NULL, 0);
968
 
        if(ret == -1){
969
 
          perror("klogctl");
970
 
        }
971
 
        exitcode = EXIT_FAILURE;
972
 
        goto end;
973
 
      }
974
 
      if((network.ifr_flags & IFF_UP) == 0){
975
 
        network.ifr_flags |= IFF_UP;
976
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
977
 
        if(ret == -1){
978
 
          perror("ioctl SIOCSIFFLAGS");
979
 
          exitcode = EXIT_FAILURE;
980
 
          ret = klogctl(7, NULL, 0);
981
 
          if(ret == -1){
982
 
            perror("klogctl");
983
 
          }
984
 
          goto end;
985
 
        }
986
 
      }
987
 
      /* sleep checking until interface is running */
988
 
      for(int i=0; i < delay * 4; i++){
989
 
        ret = ioctl(sd, SIOCGIFFLAGS, &network);
990
 
        if(ret == -1){
991
 
          perror("ioctl SIOCGIFFLAGS");
992
 
        } else if(network.ifr_flags & IFF_RUNNING){
993
 
          break;
994
 
        }
995
 
        struct timespec sleeptime = { .tv_nsec = 250000000 };
996
 
        nanosleep(&sleeptime, NULL);
997
 
      }
 
1154
      } else if(network.ifr_flags & IFF_RUNNING){
 
1155
        break;
 
1156
      }
 
1157
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1158
      ret = nanosleep(&sleeptime, NULL);
 
1159
      if(ret == -1 and errno != EINTR){
 
1160
        perror("nanosleep");
 
1161
      }
 
1162
    }
 
1163
    if(not take_down_interface){
 
1164
      /* We won't need the socket anymore */
998
1165
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
999
1166
      if(ret == -1){
1000
1167
        perror("close");
1001
1168
      }
 
1169
    }
 
1170
#ifdef __linux__
 
1171
    if(restore_loglevel){
1002
1172
      /* Restores kernel loglevel to default */
1003
1173
      ret = klogctl(7, NULL, 0);
1004
1174
      if(ret == -1){
1005
1175
        perror("klogctl");
1006
1176
      }
1007
1177
    }
1008
 
    
1009
 
    uid = getuid();
1010
 
    gid = getgid();
1011
 
    
1012
 
    setgid(gid);
1013
 
    if(ret == -1){
1014
 
      perror("setgid");
1015
 
    }
1016
 
    
1017
 
    ret = setuid(uid);
1018
 
    if(ret == -1){
1019
 
      perror("setuid");
1020
 
    }
1021
 
    
1022
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
1023
 
    if(ret == -1){
1024
 
      fprintf(stderr, "init_gnutls_global failed\n");
1025
 
      exitcode = EXIT_FAILURE;
1026
 
      goto end;
1027
 
    } else {
1028
 
      gnutls_initialized = true;
1029
 
    }
1030
 
    
1031
 
    if(mkdtemp(tempdir) == NULL){
1032
 
      perror("mkdtemp");
1033
 
      goto end;
1034
 
    }
1035
 
    tempdir_created = true;
1036
 
    
1037
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
1038
 
      fprintf(stderr, "init_gpgme failed\n");
1039
 
      exitcode = EXIT_FAILURE;
1040
 
      goto end;
1041
 
    } else {
1042
 
      gpgme_initialized = true;
1043
 
    }
1044
 
    
1045
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1046
 
    if(if_index == 0){
1047
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1048
 
      exitcode = EXIT_FAILURE;
1049
 
      goto end;
1050
 
    }
1051
 
    
1052
 
    if(connect_to != NULL){
1053
 
      /* Connect directly, do not use Zeroconf */
1054
 
      /* (Mainly meant for debugging) */
1055
 
      char *address = strrchr(connect_to, ':');
1056
 
      if(address == NULL){
1057
 
        fprintf(stderr, "No colon in address\n");
1058
 
        exitcode = EXIT_FAILURE;
1059
 
        goto end;
1060
 
      }
1061
 
      uint16_t port;
1062
 
      ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1063
 
      if(ret < 1 or tmpmax != (uint16_t)tmpmax
1064
 
         or address[numchars+1] != '\0'){
1065
 
        fprintf(stderr, "Bad port number\n");
1066
 
        exitcode = EXIT_FAILURE;
1067
 
        goto end;
1068
 
      }
1069
 
      port = (uint16_t)tmpmax;
1070
 
      *address = '\0';
1071
 
      address = connect_to;
1072
 
      ret = start_mandos_communication(address, port, if_index, &mc);
1073
 
      if(ret < 0){
1074
 
        exitcode = EXIT_FAILURE;
1075
 
      } else {
1076
 
        exitcode = EXIT_SUCCESS;
1077
 
      }
1078
 
      goto end;
1079
 
    }
1080
 
    
1081
 
    if(not debug){
1082
 
      avahi_set_log_function(empty_log);
1083
 
    }
1084
 
    
1085
 
    /* Initialize the pseudo-RNG for Avahi */
1086
 
    srand((unsigned int) time(NULL));
1087
 
    
1088
 
    /* Allocate main Avahi loop object */
1089
 
    mc.simple_poll = avahi_simple_poll_new();
1090
 
    if(mc.simple_poll == NULL) {
1091
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
1092
 
                " object.\n");
1093
 
        exitcode = EXIT_FAILURE;
1094
 
        goto end;
1095
 
    }
1096
 
    
1097
 
    {
1098
 
      AvahiServerConfig config;
1099
 
      /* Do not publish any local Zeroconf records */
1100
 
      avahi_server_config_init(&config);
1101
 
      config.publish_hinfo = 0;
1102
 
      config.publish_addresses = 0;
1103
 
      config.publish_workstation = 0;
1104
 
      config.publish_domain = 0;
1105
 
      
1106
 
      /* Allocate a new server */
1107
 
      mc.server = avahi_server_new(avahi_simple_poll_get
1108
 
                                   (mc.simple_poll), &config, NULL,
1109
 
                                   NULL, &error);
1110
 
      
1111
 
      /* Free the Avahi configuration data */
1112
 
      avahi_server_config_free(&config);
1113
 
    }
1114
 
    
1115
 
    /* Check if creating the Avahi server object succeeded */
1116
 
    if(mc.server == NULL) {
1117
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1118
 
                avahi_strerror(error));
1119
 
        exitcode = EXIT_FAILURE;
1120
 
        goto end;
1121
 
    }
1122
 
    
1123
 
    /* Create the Avahi service browser */
1124
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1125
 
                                     AVAHI_PROTO_INET6,
1126
 
                                     "_mandos._tcp", NULL, 0,
1127
 
                                     browse_callback, &mc);
1128
 
    if(sb == NULL) {
1129
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1130
 
                avahi_strerror(avahi_server_errno(mc.server)));
1131
 
        exitcode = EXIT_FAILURE;
1132
 
        goto end;
1133
 
    }
1134
 
    
1135
 
    /* Run the main loop */
1136
 
    
1137
 
    if(debug){
1138
 
      fprintf(stderr, "Starting Avahi loop search\n");
1139
 
    }
1140
 
 
1141
 
    avahi_simple_poll_loop(mc.simple_poll);
1142
 
    
 
1178
#endif  /* __linux__ */
 
1179
  }
 
1180
  
 
1181
  if(quit_now){
 
1182
    goto end;
 
1183
  }
 
1184
  
 
1185
  uid = getuid();
 
1186
  gid = getgid();
 
1187
  
 
1188
  errno = 0;
 
1189
  setgid(gid);
 
1190
  if(ret == -1){
 
1191
    perror("setgid");
 
1192
  }
 
1193
  
 
1194
  ret = setuid(uid);
 
1195
  if(ret == -1){
 
1196
    perror("setuid");
 
1197
  }
 
1198
  
 
1199
  if(quit_now){
 
1200
    goto end;
 
1201
  }
 
1202
  
 
1203
  ret = init_gnutls_global(pubkey, seckey);
 
1204
  if(ret == -1){
 
1205
    fprintf(stderr, "init_gnutls_global failed\n");
 
1206
    exitcode = EXIT_FAILURE;
 
1207
    goto end;
 
1208
  } else {
 
1209
    gnutls_initialized = true;
 
1210
  }
 
1211
  
 
1212
  if(quit_now){
 
1213
    goto end;
 
1214
  }
 
1215
  
 
1216
  tempdir_created = true;
 
1217
  if(mkdtemp(tempdir) == NULL){
 
1218
    tempdir_created = false;
 
1219
    perror("mkdtemp");
 
1220
    goto end;
 
1221
  }
 
1222
  
 
1223
  if(quit_now){
 
1224
    goto end;
 
1225
  }
 
1226
  
 
1227
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1228
    fprintf(stderr, "init_gpgme failed\n");
 
1229
    exitcode = EXIT_FAILURE;
 
1230
    goto end;
 
1231
  } else {
 
1232
    gpgme_initialized = true;
 
1233
  }
 
1234
  
 
1235
  if(quit_now){
 
1236
    goto end;
 
1237
  }
 
1238
  
 
1239
  if(connect_to != NULL){
 
1240
    /* Connect directly, do not use Zeroconf */
 
1241
    /* (Mainly meant for debugging) */
 
1242
    char *address = strrchr(connect_to, ':');
 
1243
    if(address == NULL){
 
1244
      fprintf(stderr, "No colon in address\n");
 
1245
      exitcode = EXIT_FAILURE;
 
1246
      goto end;
 
1247
    }
 
1248
    
 
1249
    if(quit_now){
 
1250
      goto end;
 
1251
    }
 
1252
    
 
1253
    uint16_t port;
 
1254
    errno = 0;
 
1255
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1256
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1257
       or tmpmax != (uint16_t)tmpmax){
 
1258
      fprintf(stderr, "Bad port number\n");
 
1259
      exitcode = EXIT_FAILURE;
 
1260
      goto end;
 
1261
    }
 
1262
  
 
1263
    if(quit_now){
 
1264
      goto end;
 
1265
    }
 
1266
    
 
1267
    port = (uint16_t)tmpmax;
 
1268
    *address = '\0';
 
1269
    address = connect_to;
 
1270
    /* Colon in address indicates IPv6 */
 
1271
    int af;
 
1272
    if(strchr(address, ':') != NULL){
 
1273
      af = AF_INET6;
 
1274
    } else {
 
1275
      af = AF_INET;
 
1276
    }
 
1277
    
 
1278
    if(quit_now){
 
1279
      goto end;
 
1280
    }
 
1281
    
 
1282
    ret = start_mandos_communication(address, port, if_index, af);
 
1283
    if(ret < 0){
 
1284
      exitcode = EXIT_FAILURE;
 
1285
    } else {
 
1286
      exitcode = EXIT_SUCCESS;
 
1287
    }
 
1288
    goto end;
 
1289
  }
 
1290
  
 
1291
  if(quit_now){
 
1292
    goto end;
 
1293
  }
 
1294
  
 
1295
  {
 
1296
    AvahiServerConfig config;
 
1297
    /* Do not publish any local Zeroconf records */
 
1298
    avahi_server_config_init(&config);
 
1299
    config.publish_hinfo = 0;
 
1300
    config.publish_addresses = 0;
 
1301
    config.publish_workstation = 0;
 
1302
    config.publish_domain = 0;
 
1303
    
 
1304
    /* Allocate a new server */
 
1305
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1306
                                 (mc.simple_poll), &config, NULL,
 
1307
                                 NULL, &error);
 
1308
    
 
1309
    /* Free the Avahi configuration data */
 
1310
    avahi_server_config_free(&config);
 
1311
  }
 
1312
  
 
1313
  /* Check if creating the Avahi server object succeeded */
 
1314
  if(mc.server == NULL){
 
1315
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1316
            avahi_strerror(error));
 
1317
    exitcode = EXIT_FAILURE;
 
1318
    goto end;
 
1319
  }
 
1320
  
 
1321
  if(quit_now){
 
1322
    goto end;
 
1323
  }
 
1324
  
 
1325
  /* Create the Avahi service browser */
 
1326
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1327
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1328
                                   NULL, 0, browse_callback, NULL);
 
1329
  if(sb == NULL){
 
1330
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1331
            avahi_strerror(avahi_server_errno(mc.server)));
 
1332
    exitcode = EXIT_FAILURE;
 
1333
    goto end;
 
1334
  }
 
1335
  
 
1336
  if(quit_now){
 
1337
    goto end;
 
1338
  }
 
1339
  
 
1340
  /* Run the main loop */
 
1341
  
 
1342
  if(debug){
 
1343
    fprintf(stderr, "Starting Avahi loop search\n");
 
1344
  }
 
1345
  
 
1346
  avahi_simple_poll_loop(mc.simple_poll);
 
1347
  
1143
1348
 end:
1144
 
    
1145
 
    if(debug){
1146
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1147
 
    }
1148
 
    
1149
 
    /* Cleanup things */
1150
 
    if(sb != NULL)
1151
 
        avahi_s_service_browser_free(sb);
1152
 
    
1153
 
    if(mc.server != NULL)
1154
 
        avahi_server_free(mc.server);
1155
 
    
1156
 
    if(mc.simple_poll != NULL)
1157
 
        avahi_simple_poll_free(mc.simple_poll);
1158
 
    
1159
 
    if(gnutls_initialized){
1160
 
      gnutls_certificate_free_credentials(mc.cred);
1161
 
      gnutls_global_deinit();
1162
 
      gnutls_dh_params_deinit(mc.dh_params);
1163
 
    }
1164
 
    
1165
 
    if(gpgme_initialized){
1166
 
      gpgme_release(mc.ctx);
1167
 
    }
1168
 
    
1169
 
    /* Removes the temp directory used by GPGME */
1170
 
    if(tempdir_created){
1171
 
      DIR *d;
1172
 
      struct dirent *direntry;
1173
 
      d = opendir(tempdir);
1174
 
      if(d == NULL){
1175
 
        if(errno != ENOENT){
1176
 
          perror("opendir");
1177
 
        }
1178
 
      } else {
1179
 
        while(true){
1180
 
          direntry = readdir(d);
1181
 
          if(direntry == NULL){
1182
 
            break;
1183
 
          }
1184
 
          /* Skip "." and ".." */
1185
 
          if(direntry->d_name[0] == '.'
1186
 
             and (direntry->d_name[1] == '\0'
1187
 
                  or (direntry->d_name[1] == '.'
1188
 
                      and direntry->d_name[2] == '\0'))){
1189
 
            continue;
1190
 
          }
1191
 
          char *fullname = NULL;
1192
 
          ret = asprintf(&fullname, "%s/%s", tempdir,
1193
 
                         direntry->d_name);
1194
 
          if(ret < 0){
1195
 
            perror("asprintf");
1196
 
            continue;
1197
 
          }
1198
 
          ret = remove(fullname);
1199
 
          if(ret == -1){
1200
 
            fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1201
 
                    strerror(errno));
1202
 
          }
1203
 
          free(fullname);
1204
 
        }
1205
 
        closedir(d);
1206
 
      }
1207
 
      ret = rmdir(tempdir);
1208
 
      if(ret == -1 and errno != ENOENT){
1209
 
        perror("rmdir");
1210
 
      }
1211
 
    }
1212
 
    
1213
 
    return exitcode;
 
1349
  
 
1350
  if(debug){
 
1351
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1352
  }
 
1353
  
 
1354
  /* Cleanup things */
 
1355
  if(sb != NULL)
 
1356
    avahi_s_service_browser_free(sb);
 
1357
  
 
1358
  if(mc.server != NULL)
 
1359
    avahi_server_free(mc.server);
 
1360
  
 
1361
  if(mc.simple_poll != NULL)
 
1362
    avahi_simple_poll_free(mc.simple_poll);
 
1363
  
 
1364
  if(gnutls_initialized){
 
1365
    gnutls_certificate_free_credentials(mc.cred);
 
1366
    gnutls_global_deinit();
 
1367
    gnutls_dh_params_deinit(mc.dh_params);
 
1368
  }
 
1369
  
 
1370
  if(gpgme_initialized){
 
1371
    gpgme_release(mc.ctx);
 
1372
  }
 
1373
  
 
1374
  /* Take down the network interface */
 
1375
  if(take_down_interface){
 
1376
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1377
    if(ret == -1){
 
1378
      perror("ioctl SIOCGIFFLAGS");
 
1379
    } else if(network.ifr_flags & IFF_UP) {
 
1380
      network.ifr_flags &= ~IFF_UP; /* clear flag */
 
1381
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1382
      if(ret == -1){
 
1383
        perror("ioctl SIOCSIFFLAGS");
 
1384
      }
 
1385
    }
 
1386
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1387
    if(ret == -1){
 
1388
      perror("close");
 
1389
    }
 
1390
  }
 
1391
  
 
1392
  /* Removes the temp directory used by GPGME */
 
1393
  if(tempdir_created){
 
1394
    DIR *d;
 
1395
    struct dirent *direntry;
 
1396
    d = opendir(tempdir);
 
1397
    if(d == NULL){
 
1398
      if(errno != ENOENT){
 
1399
        perror("opendir");
 
1400
      }
 
1401
    } else {
 
1402
      while(true){
 
1403
        direntry = readdir(d);
 
1404
        if(direntry == NULL){
 
1405
          break;
 
1406
        }
 
1407
        /* Skip "." and ".." */
 
1408
        if(direntry->d_name[0] == '.'
 
1409
           and (direntry->d_name[1] == '\0'
 
1410
                or (direntry->d_name[1] == '.'
 
1411
                    and direntry->d_name[2] == '\0'))){
 
1412
          continue;
 
1413
        }
 
1414
        char *fullname = NULL;
 
1415
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1416
                       direntry->d_name);
 
1417
        if(ret < 0){
 
1418
          perror("asprintf");
 
1419
          continue;
 
1420
        }
 
1421
        ret = remove(fullname);
 
1422
        if(ret == -1){
 
1423
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1424
                  strerror(errno));
 
1425
        }
 
1426
        free(fullname);
 
1427
      }
 
1428
      closedir(d);
 
1429
    }
 
1430
    ret = rmdir(tempdir);
 
1431
    if(ret == -1 and errno != ENOENT){
 
1432
      perror("rmdir");
 
1433
    }
 
1434
  }
 
1435
  
 
1436
  if(quit_now){
 
1437
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
 
1438
    if(ret == -1){
 
1439
      perror("sigaction");
 
1440
    }
 
1441
    raise(signal_received);
 
1442
  }
 
1443
  
 
1444
  return exitcode;
1214
1445
}