/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

* debian/rules (install-indep): Removed "--no-start" from
                                dh_installinit.

Show diffs side-by-side

added added

removed removed

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