/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-02-05 02:42:39 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090205024239-th0d287ifnl7l3tv
* plugin-runner.c (handle_sigchld): Clarify logic.

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(), remove() */
 
39
                                   stdout, ferror(), sscanf(),
 
40
                                   remove() */
40
41
#include <stdint.h>             /* uint16_t, uint32_t */
41
42
#include <stddef.h>             /* NULL, size_t, ssize_t */
42
43
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
43
 
                                   srand(), strtof() */
44
 
#include <stdbool.h>            /* bool, false, true */
 
44
                                   srand() */
 
45
#include <stdbool.h>            /* bool, true */
45
46
#include <string.h>             /* memset(), strcmp(), strlen(),
46
47
                                   strerror(), asprintf(), strcpy() */
47
 
#include <sys/ioctl.h>          /* ioctl */
 
48
#include <sys/ioctl.h>          /* ioctl */
48
49
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
49
50
                                   sockaddr_in6, PF_INET6,
50
 
                                   SOCK_STREAM, uid_t, gid_t, open(),
51
 
                                   opendir(), DIR */
 
51
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
 
52
                                   uid_t, gid_t, open(), opendir(),
 
53
                                   DIR */
52
54
#include <sys/stat.h>           /* open() */
53
55
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
54
 
                                   inet_pton(), connect() */
 
56
                                   struct in6_addr, inet_pton(),
 
57
                                   connect() */
55
58
#include <fcntl.h>              /* open() */
56
59
#include <dirent.h>             /* opendir(), struct dirent, readdir()
57
60
                                 */
58
 
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
59
 
                                   strtoimax() */
 
61
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
60
62
#include <assert.h>             /* assert() */
61
63
#include <errno.h>              /* perror(), errno */
62
64
#include <time.h>               /* nanosleep(), time() */
63
65
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
64
66
                                   SIOCSIFFLAGS, if_indextoname(),
65
67
                                   if_nametoindex(), IF_NAMESIZE */
66
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
67
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
 
                                */
 
68
#include <netinet/in.h>
69
69
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
70
                                   getuid(), getgid(), setuid(),
71
71
                                   setgid() */
72
72
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, or, and */
 
73
#include <iso646.h>             /* not, and, or */
74
74
#include <argp.h>               /* struct argp_option, error_t, struct
75
75
                                   argp_state, struct argp,
76
76
                                   argp_parse(), ARGP_KEY_ARG,
77
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
78
 
#include <signal.h>             /* sigemptyset(), sigaddset(),
79
 
                                   sigaction(), SIGTERM, sigaction,
80
 
                                   sig_atomic_t */
81
 
 
82
78
#ifdef __linux__
83
79
#include <sys/klog.h>           /* klogctl() */
84
 
#endif  /* __linux__ */
 
80
#endif
85
81
 
86
82
/* Avahi */
87
83
/* All Avahi types, constants and functions
133
129
  gpgme_ctx_t ctx;
134
130
} mandos_context;
135
131
 
136
 
/* global context so signal handler can reach it*/
137
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
138
 
                      .dh_bits = 1024, .priority = "SECURE256"
139
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
140
 
 
141
132
/*
142
 
 * Make additional room in "buffer" for at least BUFFER_SIZE more
143
 
 * bytes. "buffer_capacity" is how much is currently allocated,
 
133
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
 
134
 * "buffer_capacity" is how much is currently allocated,
144
135
 * "buffer_length" is how much is already used.
145
136
 */
146
 
size_t incbuffer(char **buffer, size_t buffer_length,
 
137
size_t adjustbuffer(char **buffer, size_t buffer_length,
147
138
                  size_t buffer_capacity){
148
139
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
149
140
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
158
149
/* 
159
150
 * Initialize GPGME.
160
151
 */
161
 
static bool init_gpgme(const char *seckey,
 
152
static bool init_gpgme(mandos_context *mc, const char *seckey,
162
153
                       const char *pubkey, const char *tempdir){
163
154
  int ret;
164
155
  gpgme_error_t rc;
185
176
      return false;
186
177
    }
187
178
    
188
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
179
    rc = gpgme_op_import(mc->ctx, pgp_data);
189
180
    if(rc != GPG_ERR_NO_ERROR){
190
181
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
191
182
              gpgme_strsource(rc), gpgme_strerror(rc));
201
192
  }
202
193
  
203
194
  if(debug){
204
 
    fprintf(stderr, "Initializing GPGME\n");
 
195
    fprintf(stderr, "Initialize gpgme\n");
205
196
  }
206
197
  
207
198
  /* Init GPGME */
234
225
  }
235
226
  
236
227
  /* Create new GPGME "context" */
237
 
  rc = gpgme_new(&(mc.ctx));
 
228
  rc = gpgme_new(&(mc->ctx));
238
229
  if(rc != GPG_ERR_NO_ERROR){
239
230
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
240
231
            gpgme_strsource(rc), gpgme_strerror(rc));
252
243
 * Decrypt OpenPGP data.
253
244
 * Returns -1 on error
254
245
 */
255
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
 
246
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
 
247
                                  const char *cryptotext,
256
248
                                  size_t crypto_size,
257
249
                                  char **plaintext){
258
250
  gpgme_data_t dh_crypto, dh_plain;
285
277
  
286
278
  /* Decrypt data from the cryptotext data buffer to the plaintext
287
279
     data buffer */
288
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
280
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
289
281
  if(rc != GPG_ERR_NO_ERROR){
290
282
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
291
283
            gpgme_strsource(rc), gpgme_strerror(rc));
292
284
    plaintext_length = -1;
293
285
    if(debug){
294
286
      gpgme_decrypt_result_t result;
295
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
287
      result = gpgme_op_decrypt_result(mc->ctx);
296
288
      if(result == NULL){
297
289
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
298
290
      } else {
334
326
  
335
327
  *plaintext = NULL;
336
328
  while(true){
337
 
    plaintext_capacity = incbuffer(plaintext,
 
329
    plaintext_capacity = adjustbuffer(plaintext,
338
330
                                      (size_t)plaintext_length,
339
331
                                      plaintext_capacity);
340
332
    if(plaintext_capacity == 0){
341
 
        perror("incbuffer");
 
333
        perror("adjustbuffer");
342
334
        plaintext_length = -1;
343
335
        goto decrypt_end;
344
336
    }
390
382
  fprintf(stderr, "GnuTLS: %s", string);
391
383
}
392
384
 
393
 
static int init_gnutls_global(const char *pubkeyfilename,
 
385
static int init_gnutls_global(mandos_context *mc,
 
386
                              const char *pubkeyfilename,
394
387
                              const char *seckeyfilename){
395
388
  int ret;
396
389
  
414
407
  }
415
408
  
416
409
  /* OpenPGP credentials */
417
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
410
  gnutls_certificate_allocate_credentials(&mc->cred);
418
411
  if(ret != GNUTLS_E_SUCCESS){
419
412
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
420
 
                                                    from
421
 
                                                    -Wunreachable-code
422
 
                                                 */
 
413
                                                  * from
 
414
                                                  * -Wunreachable-code
 
415
                                                  */
423
416
            safer_gnutls_strerror(ret));
424
417
    gnutls_global_deinit();
425
418
    return -1;
432
425
  }
433
426
  
434
427
  ret = gnutls_certificate_set_openpgp_key_file
435
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
428
    (mc->cred, pubkeyfilename, seckeyfilename,
436
429
     GNUTLS_OPENPGP_FMT_BASE64);
437
430
  if(ret != GNUTLS_E_SUCCESS){
438
431
    fprintf(stderr,
444
437
  }
445
438
  
446
439
  /* GnuTLS server initialization */
447
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
440
  ret = gnutls_dh_params_init(&mc->dh_params);
448
441
  if(ret != GNUTLS_E_SUCCESS){
449
442
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
450
443
            " %s\n", safer_gnutls_strerror(ret));
451
444
    goto globalfail;
452
445
  }
453
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
446
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
454
447
  if(ret != GNUTLS_E_SUCCESS){
455
448
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
456
449
            safer_gnutls_strerror(ret));
457
450
    goto globalfail;
458
451
  }
459
452
  
460
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
453
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
461
454
  
462
455
  return 0;
463
456
  
464
457
 globalfail:
465
458
  
466
 
  gnutls_certificate_free_credentials(mc.cred);
 
459
  gnutls_certificate_free_credentials(mc->cred);
467
460
  gnutls_global_deinit();
468
 
  gnutls_dh_params_deinit(mc.dh_params);
 
461
  gnutls_dh_params_deinit(mc->dh_params);
469
462
  return -1;
470
463
}
471
464
 
472
 
static int init_gnutls_session(gnutls_session_t *session){
 
465
static int init_gnutls_session(mandos_context *mc,
 
466
                               gnutls_session_t *session){
473
467
  int ret;
474
468
  /* GnuTLS session creation */
475
469
  ret = gnutls_init(session, GNUTLS_SERVER);
480
474
  
481
475
  {
482
476
    const char *err;
483
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
477
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
484
478
    if(ret != GNUTLS_E_SUCCESS){
485
479
      fprintf(stderr, "Syntax error at: %s\n", err);
486
480
      fprintf(stderr, "GnuTLS error: %s\n",
491
485
  }
492
486
  
493
487
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
494
 
                               mc.cred);
 
488
                               mc->cred);
495
489
  if(ret != GNUTLS_E_SUCCESS){
496
490
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
497
491
            safer_gnutls_strerror(ret));
503
497
  gnutls_certificate_server_set_request(*session,
504
498
                                        GNUTLS_CERT_IGNORE);
505
499
  
506
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
500
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
507
501
  
508
502
  return 0;
509
503
}
515
509
/* Called when a Mandos server is found */
516
510
static int start_mandos_communication(const char *ip, uint16_t port,
517
511
                                      AvahiIfIndex if_index,
518
 
                                      int af){
 
512
                                      mandos_context *mc){
519
513
  int ret, tcp_sd;
520
514
  ssize_t sret;
521
 
  union {
522
 
    struct sockaddr_in in;
523
 
    struct sockaddr_in6 in6;
524
 
  } to;
 
515
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
525
516
  char *buffer = NULL;
526
517
  char *decrypted_buffer;
527
518
  size_t buffer_length = 0;
529
520
  ssize_t decrypted_buffer_size;
530
521
  size_t written;
531
522
  int retval = 0;
 
523
  char interface[IF_NAMESIZE];
532
524
  gnutls_session_t session;
533
 
  int pf;                       /* Protocol family */
534
 
  
535
 
  switch(af){
536
 
  case AF_INET6:
537
 
    pf = PF_INET6;
538
 
    break;
539
 
  case AF_INET:
540
 
    pf = PF_INET;
541
 
    break;
542
 
  default:
543
 
    fprintf(stderr, "Bad address family: %d\n", af);
544
 
    return -1;
545
 
  }
546
 
  
547
 
  ret = init_gnutls_session(&session);
 
525
  
 
526
  ret = init_gnutls_session(mc, &session);
548
527
  if(ret != 0){
549
528
    return -1;
550
529
  }
551
530
  
552
531
  if(debug){
553
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
532
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
554
533
            "\n", ip, port);
555
534
  }
556
535
  
557
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
536
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
558
537
  if(tcp_sd < 0){
559
538
    perror("socket");
560
539
    return -1;
561
540
  }
562
541
  
 
542
  if(debug){
 
543
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
544
      perror("if_indextoname");
 
545
      return -1;
 
546
    }
 
547
    fprintf(stderr, "Binding to interface %s\n", interface);
 
548
  }
 
549
  
563
550
  memset(&to, 0, sizeof(to));
564
 
  if(af == AF_INET6){
565
 
    to.in6.sin6_family = (uint16_t)af;
566
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
567
 
  } else {                      /* IPv4 */
568
 
    to.in.sin_family = (sa_family_t)af;
569
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
570
 
  }
 
551
  to.in6.sin6_family = AF_INET6;
 
552
  /* It would be nice to have a way to detect if we were passed an
 
553
     IPv4 address here.   Now we assume an IPv6 address. */
 
554
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
571
555
  if(ret < 0 ){
572
556
    perror("inet_pton");
573
557
    return -1;
576
560
    fprintf(stderr, "Bad address: %s\n", ip);
577
561
    return -1;
578
562
  }
579
 
  if(af == AF_INET6){
580
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
581
 
                                       -Wconversion and
582
 
                                       -Wunreachable-code */
583
 
    
584
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
585
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
586
 
                              -Wunreachable-code*/
587
 
      if(if_index == AVAHI_IF_UNSPEC){
588
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
589
 
                " without a network interface\n");
590
 
        return -1;
591
 
      }
592
 
      /* Set the network interface number as scope */
593
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
594
 
    }
595
 
  } else {
596
 
    to.in.sin_port = htons(port); /* Spurious warnings from
 
563
  to.in6.sin6_port = htons(port); /* Spurious warnings from
597
564
                                     -Wconversion and
598
565
                                     -Wunreachable-code */
599
 
  }
 
566
  
 
567
  to.in6.sin6_scope_id = (uint32_t)if_index;
600
568
  
601
569
  if(debug){
602
 
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
603
 
      char interface[IF_NAMESIZE];
604
 
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
605
 
        perror("if_indextoname");
606
 
      } else {
607
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
608
 
                ip, interface, port);
609
 
      }
610
 
    } else {
611
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
612
 
              port);
613
 
    }
614
 
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
615
 
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
616
 
    const char *pcret;
617
 
    if(af == AF_INET6){
618
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
619
 
                        sizeof(addrstr));
620
 
    } else {
621
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
622
 
                        sizeof(addrstr));
623
 
    }
624
 
    if(pcret == NULL){
 
570
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
571
            port);
 
572
    char addrstr[INET6_ADDRSTRLEN] = "";
 
573
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
 
574
                 sizeof(addrstr)) == NULL){
625
575
      perror("inet_ntop");
626
576
    } else {
627
577
      if(strcmp(addrstr, ip) != 0){
630
580
    }
631
581
  }
632
582
  
633
 
  if(af == AF_INET6){
634
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
635
 
  } else {
636
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
637
 
  }
 
583
  ret = connect(tcp_sd, &to.in, sizeof(to));
638
584
  if(ret < 0){
639
585
    perror("connect");
640
586
    return -1;
686
632
  /* Read OpenPGP packet that contains the wanted password */
687
633
  
688
634
  if(debug){
689
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
635
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
690
636
            ip);
691
637
  }
692
638
  
693
639
  while(true){
694
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
 
640
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
695
641
                                   buffer_capacity);
696
642
    if(buffer_capacity == 0){
697
 
      perror("incbuffer");
 
643
      perror("adjustbuffer");
698
644
      retval = -1;
699
645
      goto mandos_end;
700
646
    }
739
685
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
740
686
  
741
687
  if(buffer_length > 0){
742
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
688
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
743
689
                                               buffer_length,
744
690
                                               &decrypted_buffer);
745
691
    if(decrypted_buffer_size >= 0){
780
726
 
781
727
static void resolve_callback(AvahiSServiceResolver *r,
782
728
                             AvahiIfIndex interface,
783
 
                             AvahiProtocol proto,
 
729
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
784
730
                             AvahiResolverEvent event,
785
731
                             const char *name,
786
732
                             const char *type,
791
737
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
792
738
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
793
739
                             flags,
794
 
                             AVAHI_GCC_UNUSED void* userdata){
 
740
                             void* userdata){
 
741
  mandos_context *mc = userdata;
795
742
  assert(r);
796
743
  
797
744
  /* Called whenever a service has been resolved successfully or
802
749
  case AVAHI_RESOLVER_FAILURE:
803
750
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
804
751
            " of type '%s' in domain '%s': %s\n", name, type, domain,
805
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
752
            avahi_strerror(avahi_server_errno(mc->server)));
806
753
    break;
807
754
    
808
755
  case AVAHI_RESOLVER_FOUND:
814
761
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
815
762
                ip, (intmax_t)interface, port);
816
763
      }
817
 
      int ret = start_mandos_communication(ip, port, interface,
818
 
                                           avahi_proto_to_af(proto));
 
764
      int ret = start_mandos_communication(ip, port, interface, mc);
819
765
      if(ret == 0){
820
 
        avahi_simple_poll_quit(mc.simple_poll);
 
766
        avahi_simple_poll_quit(mc->simple_poll);
821
767
      }
822
768
    }
823
769
  }
833
779
                            const char *domain,
834
780
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
835
781
                            flags,
836
 
                            AVAHI_GCC_UNUSED void* userdata){
 
782
                            void* userdata){
 
783
  mandos_context *mc = userdata;
837
784
  assert(b);
838
785
  
839
786
  /* Called whenever a new services becomes available on the LAN or
844
791
  case AVAHI_BROWSER_FAILURE:
845
792
    
846
793
    fprintf(stderr, "(Avahi browser) %s\n",
847
 
            avahi_strerror(avahi_server_errno(mc.server)));
848
 
    avahi_simple_poll_quit(mc.simple_poll);
 
794
            avahi_strerror(avahi_server_errno(mc->server)));
 
795
    avahi_simple_poll_quit(mc->simple_poll);
849
796
    return;
850
797
    
851
798
  case AVAHI_BROWSER_NEW:
854
801
       the callback function is called the Avahi server will free the
855
802
       resolver for us. */
856
803
    
857
 
    if(!(avahi_s_service_resolver_new(mc.server, interface,
 
804
    if(!(avahi_s_service_resolver_new(mc->server, interface,
858
805
                                       protocol, name, type, domain,
859
806
                                       AVAHI_PROTO_INET6, 0,
860
 
                                       resolve_callback, NULL)))
 
807
                                       resolve_callback, mc)))
861
808
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
862
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
809
              name, avahi_strerror(avahi_server_errno(mc->server)));
863
810
    break;
864
811
    
865
812
  case AVAHI_BROWSER_REMOVE:
874
821
  }
875
822
}
876
823
 
877
 
sig_atomic_t quit_now = 0;
878
 
 
879
 
/* stop main loop after sigterm has been called */
880
 
static void handle_sigterm(__attribute__((unused)) int sig){
881
 
  if(quit_now){
882
 
    return;
883
 
  }
884
 
  quit_now = 1;
885
 
  int old_errno = errno;
886
 
  if(mc.simple_poll != NULL){
887
 
    avahi_simple_poll_quit(mc.simple_poll);
888
 
  }
889
 
  errno = old_errno;
890
 
}
891
 
 
892
824
int main(int argc, char *argv[]){
893
825
  AvahiSServiceBrowser *sb = NULL;
894
826
  int error;
895
827
  int ret;
896
828
  intmax_t tmpmax;
897
 
  char *tmp;
 
829
  int numchars;
898
830
  int exitcode = EXIT_SUCCESS;
899
831
  const char *interface = "eth0";
900
832
  struct ifreq network;
908
840
  const char *seckey = PATHDIR "/" SECKEY;
909
841
  const char *pubkey = PATHDIR "/" PUBKEY;
910
842
  
911
 
  /* Initialize Mandos context */
912
 
  mc = (mandos_context){ .simple_poll = NULL, .server = NULL,
913
 
                         .dh_bits = 1024, .priority = "SECURE256"
914
 
                         ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
843
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
844
                        .dh_bits = 1024, .priority = "SECURE256"
 
845
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
915
846
  bool gnutls_initialized = false;
916
847
  bool gpgme_initialized = false;
917
 
  float delay = 2.5f;
918
 
  
919
 
  struct sigaction old_sigterm_action;
920
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
848
  double delay = 2.5;
921
849
  
922
850
  {
923
851
    struct argp_option options[] = {
929
857
        .group = 1 },
930
858
      { .name = "interface", .key = 'i',
931
859
        .arg = "NAME",
932
 
        .doc = "Network interface that will be used to search for"
933
 
        " Mandos servers",
 
860
        .doc = "Interface that will be used to search for Mandos"
 
861
        " servers",
934
862
        .group = 1 },
935
863
      { .name = "seckey", .key = 's',
936
864
        .arg = "FILE",
975
903
        pubkey = arg;
976
904
        break;
977
905
      case 129:                 /* --dh-bits */
978
 
        errno = 0;
979
 
        tmpmax = strtoimax(arg, &tmp, 10);
980
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
981
 
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
906
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
907
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
908
           or arg[numchars] != '\0'){
982
909
          fprintf(stderr, "Bad number of DH bits\n");
983
910
          exit(EXIT_FAILURE);
984
911
        }
988
915
        mc.priority = arg;
989
916
        break;
990
917
      case 131:                 /* --delay */
991
 
        errno = 0;
992
 
        delay = strtof(arg, &tmp);
993
 
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
918
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
919
        if(ret < 1 or arg[numchars] != '\0'){
994
920
          fprintf(stderr, "Bad delay\n");
995
921
          exit(EXIT_FAILURE);
996
922
        }
1017
943
    }
1018
944
  }
1019
945
  
1020
 
  if(not debug){
1021
 
    avahi_set_log_function(empty_log);
1022
 
  }
1023
 
  
1024
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1025
 
     from the signal handler */
1026
 
  /* Initialize the pseudo-RNG for Avahi */
1027
 
  srand((unsigned int) time(NULL));
1028
 
  mc.simple_poll = avahi_simple_poll_new();
1029
 
  if(mc.simple_poll == NULL){
1030
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1031
 
    exitcode = EXIT_FAILURE;
1032
 
    goto end;
1033
 
  }
1034
 
  
1035
 
  sigemptyset(&sigterm_action.sa_mask);
1036
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1037
 
  if(ret == -1){
1038
 
    perror("sigaddset");
1039
 
    exitcode = EXIT_FAILURE;
1040
 
    goto end;
1041
 
  }
1042
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1043
 
  if(ret == -1){
1044
 
    perror("sigaddset");
1045
 
    exitcode = EXIT_FAILURE;
1046
 
    goto end;
1047
 
  }
1048
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1049
 
  if(ret == -1){
1050
 
    perror("sigaddset");
1051
 
    exitcode = EXIT_FAILURE;
1052
 
    goto end;
1053
 
  }
1054
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1055
 
  if(ret == -1){
1056
 
    perror("sigaction");
1057
 
    exitcode = EXIT_FAILURE;
1058
 
    goto end;
1059
 
  }  
1060
 
  
1061
946
  /* If the interface is down, bring it up */
1062
 
  if(interface[0] != '\0'){
 
947
  {
1063
948
#ifdef __linux__
1064
949
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1065
950
       messages to mess up the prompt */
1066
951
    ret = klogctl(8, NULL, 5);
1067
 
    bool restore_loglevel = true;
1068
952
    if(ret == -1){
1069
 
      restore_loglevel = false;
1070
953
      perror("klogctl");
1071
954
    }
1072
 
#endif  /* __linux__ */
 
955
#endif
1073
956
    
1074
957
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1075
958
    if(sd < 0){
1076
959
      perror("socket");
1077
960
      exitcode = EXIT_FAILURE;
1078
961
#ifdef __linux__
1079
 
      if(restore_loglevel){
1080
 
        ret = klogctl(7, NULL, 0);
1081
 
        if(ret == -1){
1082
 
          perror("klogctl");
1083
 
        }
 
962
      ret = klogctl(7, NULL, 0);
 
963
      if(ret == -1){
 
964
        perror("klogctl");
1084
965
      }
1085
 
#endif  /* __linux__ */
 
966
#endif
1086
967
      goto end;
1087
968
    }
1088
969
    strcpy(network.ifr_name, interface);
1090
971
    if(ret == -1){
1091
972
      perror("ioctl SIOCGIFFLAGS");
1092
973
#ifdef __linux__
1093
 
      if(restore_loglevel){
1094
 
        ret = klogctl(7, NULL, 0);
1095
 
        if(ret == -1){
1096
 
          perror("klogctl");
1097
 
        }
 
974
      ret = klogctl(7, NULL, 0);
 
975
      if(ret == -1){
 
976
        perror("klogctl");
1098
977
      }
1099
 
#endif  /* __linux__ */
 
978
#endif
1100
979
      exitcode = EXIT_FAILURE;
1101
980
      goto end;
1102
981
    }
1107
986
        perror("ioctl SIOCSIFFLAGS");
1108
987
        exitcode = EXIT_FAILURE;
1109
988
#ifdef __linux__
1110
 
        if(restore_loglevel){
1111
 
          ret = klogctl(7, NULL, 0);
1112
 
          if(ret == -1){
1113
 
            perror("klogctl");
1114
 
          }
 
989
        ret = klogctl(7, NULL, 0);
 
990
        if(ret == -1){
 
991
          perror("klogctl");
1115
992
        }
1116
 
#endif  /* __linux__ */
 
993
#endif
1117
994
        goto end;
1118
995
      }
1119
996
    }
1136
1013
      perror("close");
1137
1014
    }
1138
1015
#ifdef __linux__
1139
 
    if(restore_loglevel){
1140
 
      /* Restores kernel loglevel to default */
1141
 
      ret = klogctl(7, NULL, 0);
1142
 
      if(ret == -1){
1143
 
        perror("klogctl");
1144
 
      }
 
1016
    /* Restores kernel loglevel to default */
 
1017
    ret = klogctl(7, NULL, 0);
 
1018
    if(ret == -1){
 
1019
      perror("klogctl");
1145
1020
    }
1146
 
#endif  /* __linux__ */
 
1021
#endif
1147
1022
  }
1148
1023
  
1149
1024
  uid = getuid();
1150
1025
  gid = getgid();
1151
1026
  
1152
 
  errno = 0;
1153
1027
  setgid(gid);
1154
1028
  if(ret == -1){
1155
1029
    perror("setgid");
1160
1034
    perror("setuid");
1161
1035
  }
1162
1036
  
1163
 
  ret = init_gnutls_global(pubkey, seckey);
 
1037
  ret = init_gnutls_global(&mc, pubkey, seckey);
1164
1038
  if(ret == -1){
1165
1039
    fprintf(stderr, "init_gnutls_global failed\n");
1166
1040
    exitcode = EXIT_FAILURE;
1175
1049
  }
1176
1050
  tempdir_created = true;
1177
1051
  
1178
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1052
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
1179
1053
    fprintf(stderr, "init_gpgme failed\n");
1180
1054
    exitcode = EXIT_FAILURE;
1181
1055
    goto end;
1183
1057
    gpgme_initialized = true;
1184
1058
  }
1185
1059
  
1186
 
  if(interface[0] != '\0'){
1187
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1188
 
    if(if_index == 0){
1189
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1190
 
      exitcode = EXIT_FAILURE;
1191
 
      goto end;
1192
 
    }
 
1060
  if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1061
  if(if_index == 0){
 
1062
    fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1063
    exitcode = EXIT_FAILURE;
 
1064
    goto end;
1193
1065
  }
1194
1066
  
1195
1067
  if(connect_to != NULL){
1202
1074
      goto end;
1203
1075
    }
1204
1076
    uint16_t port;
1205
 
    errno = 0;
1206
 
    tmpmax = strtoimax(address+1, &tmp, 10);
1207
 
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1208
 
       or tmpmax != (uint16_t)tmpmax){
 
1077
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1078
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1079
       or address[numchars+1] != '\0'){
1209
1080
      fprintf(stderr, "Bad port number\n");
1210
1081
      exitcode = EXIT_FAILURE;
1211
1082
      goto end;
1213
1084
    port = (uint16_t)tmpmax;
1214
1085
    *address = '\0';
1215
1086
    address = connect_to;
1216
 
    /* Colon in address indicates IPv6 */
1217
 
    int af;
1218
 
    if(strchr(address, ':') != NULL){
1219
 
      af = AF_INET6;
1220
 
    } else {
1221
 
      af = AF_INET;
1222
 
    }
1223
 
    ret = start_mandos_communication(address, port, if_index, af);
 
1087
    ret = start_mandos_communication(address, port, if_index, &mc);
1224
1088
    if(ret < 0){
1225
1089
      exitcode = EXIT_FAILURE;
1226
1090
    } else {
1228
1092
    }
1229
1093
    goto end;
1230
1094
  }
1231
 
    
 
1095
  
 
1096
  if(not debug){
 
1097
    avahi_set_log_function(empty_log);
 
1098
  }
 
1099
  
 
1100
  /* Initialize the pseudo-RNG for Avahi */
 
1101
  srand((unsigned int) time(NULL));
 
1102
  
 
1103
  /* Allocate main Avahi loop object */
 
1104
  mc.simple_poll = avahi_simple_poll_new();
 
1105
  if(mc.simple_poll == NULL){
 
1106
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1107
    exitcode = EXIT_FAILURE;
 
1108
    goto end;
 
1109
  }
 
1110
  
1232
1111
  {
1233
1112
    AvahiServerConfig config;
1234
1113
    /* Do not publish any local Zeroconf records */
1258
1137
  /* Create the Avahi service browser */
1259
1138
  sb = avahi_s_service_browser_new(mc.server, if_index,
1260
1139
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1261
 
                                   NULL, 0, browse_callback, NULL);
 
1140
                                   NULL, 0, browse_callback, &mc);
1262
1141
  if(sb == NULL){
1263
1142
    fprintf(stderr, "Failed to create service browser: %s\n",
1264
1143
            avahi_strerror(avahi_server_errno(mc.server)));