/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

merge

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, protocol,
858
 
                                    name, type, domain, protocol, 0,
859
 
                                    resolve_callback, NULL) == NULL)
 
804
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
805
                                       protocol, name, type, domain,
 
806
                                       AVAHI_PROTO_INET6, 0,
 
807
                                       resolve_callback, mc)))
860
808
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
861
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
809
              name, avahi_strerror(avahi_server_errno(mc->server)));
862
810
    break;
863
811
    
864
812
  case AVAHI_BROWSER_REMOVE:
873
821
  }
874
822
}
875
823
 
876
 
sig_atomic_t quit_now = 0;
877
 
 
878
 
/* stop main loop after sigterm has been called */
879
 
static void handle_sigterm(__attribute__((unused)) int sig){
880
 
  if(quit_now){
881
 
    return;
882
 
  }
883
 
  quit_now = 1;
884
 
  int old_errno = errno;
885
 
  if(mc.simple_poll != NULL){
886
 
    avahi_simple_poll_quit(mc.simple_poll);
887
 
  }
888
 
  errno = old_errno;
889
 
}
890
 
 
891
824
int main(int argc, char *argv[]){
892
825
  AvahiSServiceBrowser *sb = NULL;
893
826
  int error;
894
827
  int ret;
895
828
  intmax_t tmpmax;
896
 
  char *tmp;
 
829
  int numchars;
897
830
  int exitcode = EXIT_SUCCESS;
898
831
  const char *interface = "eth0";
899
832
  struct ifreq network;
907
840
  const char *seckey = PATHDIR "/" SECKEY;
908
841
  const char *pubkey = PATHDIR "/" PUBKEY;
909
842
  
 
843
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
844
                        .dh_bits = 1024, .priority = "SECURE256"
 
845
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
910
846
  bool gnutls_initialized = false;
911
847
  bool gpgme_initialized = false;
912
 
  float delay = 2.5f;
913
 
  
914
 
  struct sigaction old_sigterm_action;
915
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
848
  double delay = 2.5;
916
849
  
917
850
  {
918
851
    struct argp_option options[] = {
924
857
        .group = 1 },
925
858
      { .name = "interface", .key = 'i',
926
859
        .arg = "NAME",
927
 
        .doc = "Network interface that will be used to search for"
928
 
        " Mandos servers",
 
860
        .doc = "Interface that will be used to search for Mandos"
 
861
        " servers",
929
862
        .group = 1 },
930
863
      { .name = "seckey", .key = 's',
931
864
        .arg = "FILE",
970
903
        pubkey = arg;
971
904
        break;
972
905
      case 129:                 /* --dh-bits */
973
 
        errno = 0;
974
 
        tmpmax = strtoimax(arg, &tmp, 10);
975
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
976
 
           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'){
977
909
          fprintf(stderr, "Bad number of DH bits\n");
978
910
          exit(EXIT_FAILURE);
979
911
        }
983
915
        mc.priority = arg;
984
916
        break;
985
917
      case 131:                 /* --delay */
986
 
        errno = 0;
987
 
        delay = strtof(arg, &tmp);
988
 
        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'){
989
920
          fprintf(stderr, "Bad delay\n");
990
921
          exit(EXIT_FAILURE);
991
922
        }
1012
943
    }
1013
944
  }
1014
945
  
1015
 
  if(not debug){
1016
 
    avahi_set_log_function(empty_log);
1017
 
  }
1018
 
  
1019
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1020
 
     from the signal handler */
1021
 
  /* Initialize the pseudo-RNG for Avahi */
1022
 
  srand((unsigned int) time(NULL));
1023
 
  mc.simple_poll = avahi_simple_poll_new();
1024
 
  if(mc.simple_poll == NULL){
1025
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1026
 
    exitcode = EXIT_FAILURE;
1027
 
    goto end;
1028
 
  }
1029
 
  
1030
 
  sigemptyset(&sigterm_action.sa_mask);
1031
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1032
 
  if(ret == -1){
1033
 
    perror("sigaddset");
1034
 
    exitcode = EXIT_FAILURE;
1035
 
    goto end;
1036
 
  }
1037
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1038
 
  if(ret == -1){
1039
 
    perror("sigaddset");
1040
 
    exitcode = EXIT_FAILURE;
1041
 
    goto end;
1042
 
  }
1043
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1044
 
  if(ret == -1){
1045
 
    perror("sigaddset");
1046
 
    exitcode = EXIT_FAILURE;
1047
 
    goto end;
1048
 
  }
1049
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1050
 
  if(ret == -1){
1051
 
    perror("sigaction");
1052
 
    exitcode = EXIT_FAILURE;
1053
 
    goto end;
1054
 
  }  
1055
 
  
1056
946
  /* If the interface is down, bring it up */
1057
 
  if(interface[0] != '\0'){
 
947
  {
1058
948
#ifdef __linux__
1059
949
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1060
950
       messages to mess up the prompt */
1061
951
    ret = klogctl(8, NULL, 5);
1062
 
    bool restore_loglevel = true;
1063
952
    if(ret == -1){
1064
 
      restore_loglevel = false;
1065
953
      perror("klogctl");
1066
954
    }
1067
 
#endif  /* __linux__ */
 
955
#endif
1068
956
    
1069
957
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1070
958
    if(sd < 0){
1071
959
      perror("socket");
1072
960
      exitcode = EXIT_FAILURE;
1073
961
#ifdef __linux__
1074
 
      if(restore_loglevel){
1075
 
        ret = klogctl(7, NULL, 0);
1076
 
        if(ret == -1){
1077
 
          perror("klogctl");
1078
 
        }
 
962
      ret = klogctl(7, NULL, 0);
 
963
      if(ret == -1){
 
964
        perror("klogctl");
1079
965
      }
1080
 
#endif  /* __linux__ */
 
966
#endif
1081
967
      goto end;
1082
968
    }
1083
969
    strcpy(network.ifr_name, interface);
1085
971
    if(ret == -1){
1086
972
      perror("ioctl SIOCGIFFLAGS");
1087
973
#ifdef __linux__
1088
 
      if(restore_loglevel){
1089
 
        ret = klogctl(7, NULL, 0);
1090
 
        if(ret == -1){
1091
 
          perror("klogctl");
1092
 
        }
 
974
      ret = klogctl(7, NULL, 0);
 
975
      if(ret == -1){
 
976
        perror("klogctl");
1093
977
      }
1094
 
#endif  /* __linux__ */
 
978
#endif
1095
979
      exitcode = EXIT_FAILURE;
1096
980
      goto end;
1097
981
    }
1102
986
        perror("ioctl SIOCSIFFLAGS");
1103
987
        exitcode = EXIT_FAILURE;
1104
988
#ifdef __linux__
1105
 
        if(restore_loglevel){
1106
 
          ret = klogctl(7, NULL, 0);
1107
 
          if(ret == -1){
1108
 
            perror("klogctl");
1109
 
          }
 
989
        ret = klogctl(7, NULL, 0);
 
990
        if(ret == -1){
 
991
          perror("klogctl");
1110
992
        }
1111
 
#endif  /* __linux__ */
 
993
#endif
1112
994
        goto end;
1113
995
      }
1114
996
    }
1131
1013
      perror("close");
1132
1014
    }
1133
1015
#ifdef __linux__
1134
 
    if(restore_loglevel){
1135
 
      /* Restores kernel loglevel to default */
1136
 
      ret = klogctl(7, NULL, 0);
1137
 
      if(ret == -1){
1138
 
        perror("klogctl");
1139
 
      }
 
1016
    /* Restores kernel loglevel to default */
 
1017
    ret = klogctl(7, NULL, 0);
 
1018
    if(ret == -1){
 
1019
      perror("klogctl");
1140
1020
    }
1141
 
#endif  /* __linux__ */
 
1021
#endif
1142
1022
  }
1143
1023
  
1144
1024
  uid = getuid();
1145
1025
  gid = getgid();
1146
1026
  
1147
 
  errno = 0;
1148
1027
  setgid(gid);
1149
1028
  if(ret == -1){
1150
1029
    perror("setgid");
1155
1034
    perror("setuid");
1156
1035
  }
1157
1036
  
1158
 
  ret = init_gnutls_global(pubkey, seckey);
 
1037
  ret = init_gnutls_global(&mc, pubkey, seckey);
1159
1038
  if(ret == -1){
1160
1039
    fprintf(stderr, "init_gnutls_global failed\n");
1161
1040
    exitcode = EXIT_FAILURE;
1170
1049
  }
1171
1050
  tempdir_created = true;
1172
1051
  
1173
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1052
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
1174
1053
    fprintf(stderr, "init_gpgme failed\n");
1175
1054
    exitcode = EXIT_FAILURE;
1176
1055
    goto end;
1178
1057
    gpgme_initialized = true;
1179
1058
  }
1180
1059
  
1181
 
  if(interface[0] != '\0'){
1182
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1183
 
    if(if_index == 0){
1184
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1185
 
      exitcode = EXIT_FAILURE;
1186
 
      goto end;
1187
 
    }
 
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;
1188
1065
  }
1189
1066
  
1190
1067
  if(connect_to != NULL){
1197
1074
      goto end;
1198
1075
    }
1199
1076
    uint16_t port;
1200
 
    errno = 0;
1201
 
    tmpmax = strtoimax(address+1, &tmp, 10);
1202
 
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1203
 
       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'){
1204
1080
      fprintf(stderr, "Bad port number\n");
1205
1081
      exitcode = EXIT_FAILURE;
1206
1082
      goto end;
1208
1084
    port = (uint16_t)tmpmax;
1209
1085
    *address = '\0';
1210
1086
    address = connect_to;
1211
 
    /* Colon in address indicates IPv6 */
1212
 
    int af;
1213
 
    if(strchr(address, ':') != NULL){
1214
 
      af = AF_INET6;
1215
 
    } else {
1216
 
      af = AF_INET;
1217
 
    }
1218
 
    ret = start_mandos_communication(address, port, if_index, af);
 
1087
    ret = start_mandos_communication(address, port, if_index, &mc);
1219
1088
    if(ret < 0){
1220
1089
      exitcode = EXIT_FAILURE;
1221
1090
    } else {
1223
1092
    }
1224
1093
    goto end;
1225
1094
  }
1226
 
    
 
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
  
1227
1111
  {
1228
1112
    AvahiServerConfig config;
1229
1113
    /* Do not publish any local Zeroconf records */
1252
1136
  
1253
1137
  /* Create the Avahi service browser */
1254
1138
  sb = avahi_s_service_browser_new(mc.server, if_index,
1255
 
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1256
 
                                   NULL, 0, browse_callback, NULL);
 
1139
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1140
                                   NULL, 0, browse_callback, &mc);
1257
1141
  if(sb == NULL){
1258
1142
    fprintf(stderr, "Failed to create service browser: %s\n",
1259
1143
            avahi_strerror(avahi_server_errno(mc.server)));