/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-09 02:13:58 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090209021358-6nrlc91oi08hn5hb
* initramfs-tools-hook: Whitespace change only.

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 */
 
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
44
                                   srand() */
44
 
#include <stdbool.h>            /* bool, true */
 
45
#include <stdbool.h>            /* bool, false, 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, INET6_ADDRSTRLEN,
51
 
                                   uid_t, gid_t, open(), opendir(),
52
 
                                   DIR */
 
51
                                   SOCK_STREAM, uid_t, gid_t, open(),
 
52
                                   opendir(), DIR */
53
53
#include <sys/stat.h>           /* open() */
54
54
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
55
 
                                   struct in6_addr, inet_pton(),
56
 
                                   connect() */
 
55
                                   inet_pton(), connect() */
57
56
#include <fcntl.h>              /* open() */
58
57
#include <dirent.h>             /* opendir(), struct dirent, readdir()
59
58
                                 */
60
59
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
61
60
#include <assert.h>             /* assert() */
62
61
#include <errno.h>              /* perror(), errno */
63
 
#include <time.h>               /* time() */
 
62
#include <time.h>               /* nanosleep(), time() */
64
63
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
65
64
                                   SIOCSIFFLAGS, if_indextoname(),
66
65
                                   if_nametoindex(), IF_NAMESIZE */
67
 
#include <netinet/in.h>
 
66
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
 
67
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
 
68
                                */
68
69
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
69
70
                                   getuid(), getgid(), setuid(),
70
71
                                   setgid() */
71
72
#include <arpa/inet.h>          /* inet_pton(), htons */
72
 
#include <iso646.h>             /* not, and, or */
 
73
#include <iso646.h>             /* not, or, and */
73
74
#include <argp.h>               /* struct argp_option, error_t, struct
74
75
                                   argp_state, struct argp,
75
76
                                   argp_parse(), ARGP_KEY_ARG,
76
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
78
#ifdef __linux__
 
79
#include <sys/klog.h>           /* klogctl() */
 
80
#endif
77
81
 
78
82
/* Avahi */
79
83
/* All Avahi types, constants and functions
153
157
  
154
158
  
155
159
  /*
156
 
   * Helper function to insert pub and seckey to the enigne keyring.
 
160
   * Helper function to insert pub and seckey to the engine keyring.
157
161
   */
158
162
  bool import_key(const char *filename){
159
163
    int fd;
364
368
  return plaintext_length;
365
369
}
366
370
 
367
 
static const char * safer_gnutls_strerror(int value) {
 
371
static const char * safer_gnutls_strerror(int value){
368
372
  const char *ret = gnutls_strerror(value); /* Spurious warning from
369
373
                                               -Wunreachable-code */
370
374
  if(ret == NULL)
388
392
  }
389
393
  
390
394
  ret = gnutls_global_init();
391
 
  if(ret != GNUTLS_E_SUCCESS) {
 
395
  if(ret != GNUTLS_E_SUCCESS){
392
396
    fprintf(stderr, "GnuTLS global_init: %s\n",
393
397
            safer_gnutls_strerror(ret));
394
398
    return -1;
406
410
  gnutls_certificate_allocate_credentials(&mc->cred);
407
411
  if(ret != GNUTLS_E_SUCCESS){
408
412
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
409
 
                                                  * from
410
 
                                                  * -Wunreachable-code
411
 
                                                  */
 
413
                                                    from
 
414
                                                    -Wunreachable-code
 
415
                                                 */
412
416
            safer_gnutls_strerror(ret));
413
417
    gnutls_global_deinit();
414
418
    return -1;
423
427
  ret = gnutls_certificate_set_openpgp_key_file
424
428
    (mc->cred, pubkeyfilename, seckeyfilename,
425
429
     GNUTLS_OPENPGP_FMT_BASE64);
426
 
  if(ret != GNUTLS_E_SUCCESS) {
 
430
  if(ret != GNUTLS_E_SUCCESS){
427
431
    fprintf(stderr,
428
432
            "Error[%d] while reading the OpenPGP key pair ('%s',"
429
433
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
434
438
  
435
439
  /* GnuTLS server initialization */
436
440
  ret = gnutls_dh_params_init(&mc->dh_params);
437
 
  if(ret != GNUTLS_E_SUCCESS) {
 
441
  if(ret != GNUTLS_E_SUCCESS){
438
442
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
439
443
            " %s\n", safer_gnutls_strerror(ret));
440
444
    goto globalfail;
441
445
  }
442
446
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
443
 
  if(ret != GNUTLS_E_SUCCESS) {
 
447
  if(ret != GNUTLS_E_SUCCESS){
444
448
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
445
449
            safer_gnutls_strerror(ret));
446
450
    goto globalfail;
471
475
  {
472
476
    const char *err;
473
477
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
474
 
    if(ret != GNUTLS_E_SUCCESS) {
 
478
    if(ret != GNUTLS_E_SUCCESS){
475
479
      fprintf(stderr, "Syntax error at: %s\n", err);
476
480
      fprintf(stderr, "GnuTLS error: %s\n",
477
481
              safer_gnutls_strerror(ret));
482
486
  
483
487
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
484
488
                               mc->cred);
485
 
  if(ret != GNUTLS_E_SUCCESS) {
 
489
  if(ret != GNUTLS_E_SUCCESS){
486
490
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
487
491
            safer_gnutls_strerror(ret));
488
492
    gnutls_deinit(*session);
505
509
/* Called when a Mandos server is found */
506
510
static int start_mandos_communication(const char *ip, uint16_t port,
507
511
                                      AvahiIfIndex if_index,
508
 
                                      mandos_context *mc){
 
512
                                      mandos_context *mc, int af){
509
513
  int ret, tcp_sd;
510
514
  ssize_t sret;
511
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
515
  union {
 
516
    struct sockaddr_in in;
 
517
    struct sockaddr_in6 in6;
 
518
  } to;
512
519
  char *buffer = NULL;
513
520
  char *decrypted_buffer;
514
521
  size_t buffer_length = 0;
516
523
  ssize_t decrypted_buffer_size;
517
524
  size_t written;
518
525
  int retval = 0;
519
 
  char interface[IF_NAMESIZE];
520
526
  gnutls_session_t session;
 
527
  int pf;                       /* Protocol family */
 
528
  
 
529
  switch(af){
 
530
  case AF_INET6:
 
531
    pf = PF_INET6;
 
532
    break;
 
533
  case AF_INET:
 
534
    pf = PF_INET;
 
535
    break;
 
536
  default:
 
537
    fprintf(stderr, "Bad address family: %d\n", af);
 
538
    return -1;
 
539
  }
521
540
  
522
541
  ret = init_gnutls_session(mc, &session);
523
542
  if(ret != 0){
525
544
  }
526
545
  
527
546
  if(debug){
528
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
547
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
529
548
            "\n", ip, port);
530
549
  }
531
550
  
532
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
533
 
  if(tcp_sd < 0) {
 
551
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
552
  if(tcp_sd < 0){
534
553
    perror("socket");
535
554
    return -1;
536
555
  }
537
556
  
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
 
  
546
557
  memset(&to, 0, sizeof(to));
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);
 
558
  if(af == AF_INET6){
 
559
    to.in6.sin6_family = (uint16_t)af;
 
560
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
561
  } else {                      /* IPv4 */
 
562
    to.in.sin_family = (sa_family_t)af;
 
563
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
564
  }
551
565
  if(ret < 0 ){
552
566
    perror("inet_pton");
553
567
    return -1;
556
570
    fprintf(stderr, "Bad address: %s\n", ip);
557
571
    return -1;
558
572
  }
559
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
573
  if(af == AF_INET6){
 
574
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
575
                                       -Wconversion and
 
576
                                       -Wunreachable-code */
 
577
    
 
578
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
579
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
580
                              -Wunreachable-code*/
 
581
      if(if_index == AVAHI_IF_UNSPEC){
 
582
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
583
                " without a network interface\n");
 
584
        return -1;
 
585
      }
 
586
      /* Set the network interface number as scope */
 
587
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
588
    }
 
589
  } else {
 
590
    to.in.sin_port = htons(port); /* Spurious warnings from
560
591
                                     -Wconversion and
561
592
                                     -Wunreachable-code */
562
 
  
563
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
593
  }
564
594
  
565
595
  if(debug){
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){
 
596
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
597
      char interface[IF_NAMESIZE];
 
598
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
599
        perror("if_indextoname");
 
600
      } else {
 
601
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
602
                ip, interface, port);
 
603
      }
 
604
    } else {
 
605
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
606
              port);
 
607
    }
 
608
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
609
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
610
    const char *pcret;
 
611
    if(af == AF_INET6){
 
612
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
613
                        sizeof(addrstr));
 
614
    } else {
 
615
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
616
                        sizeof(addrstr));
 
617
    }
 
618
    if(pcret == NULL){
571
619
      perror("inet_ntop");
572
620
    } else {
573
621
      if(strcmp(addrstr, ip) != 0){
576
624
    }
577
625
  }
578
626
  
579
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
627
  if(af == AF_INET6){
 
628
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
629
  } else {
 
630
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
631
  }
580
632
  if(ret < 0){
581
633
    perror("connect");
582
634
    return -1;
628
680
  /* Read OpenPGP packet that contains the wanted password */
629
681
  
630
682
  if(debug){
631
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
683
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
632
684
            ip);
633
685
  }
634
686
  
722
774
 
723
775
static void resolve_callback(AvahiSServiceResolver *r,
724
776
                             AvahiIfIndex interface,
725
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
777
                             AvahiProtocol proto,
726
778
                             AvahiResolverEvent event,
727
779
                             const char *name,
728
780
                             const char *type,
733
785
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
734
786
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
735
787
                             flags,
736
 
                             void* userdata) {
 
788
                             void* userdata){
737
789
  mandos_context *mc = userdata;
738
790
  assert(r);
739
791
  
740
792
  /* Called whenever a service has been resolved successfully or
741
793
     timed out */
742
794
  
743
 
  switch(event) {
 
795
  switch(event){
744
796
  default:
745
797
  case AVAHI_RESOLVER_FAILURE:
746
798
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
757
809
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
758
810
                ip, (intmax_t)interface, port);
759
811
      }
760
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
812
      int ret = start_mandos_communication(ip, port, interface, mc,
 
813
                                           avahi_proto_to_af(proto));
761
814
      if(ret == 0){
762
815
        avahi_simple_poll_quit(mc->simple_poll);
763
816
      }
766
819
  avahi_s_service_resolver_free(r);
767
820
}
768
821
 
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) {
 
822
static void browse_callback(AvahiSServiceBrowser *b,
 
823
                            AvahiIfIndex interface,
 
824
                            AvahiProtocol protocol,
 
825
                            AvahiBrowserEvent event,
 
826
                            const char *name,
 
827
                            const char *type,
 
828
                            const char *domain,
 
829
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
830
                            flags,
 
831
                            void* userdata){
779
832
  mandos_context *mc = userdata;
780
833
  assert(b);
781
834
  
782
835
  /* Called whenever a new services becomes available on the LAN or
783
836
     is removed from the LAN */
784
837
  
785
 
  switch(event) {
 
838
  switch(event){
786
839
  default:
787
840
  case AVAHI_BROWSER_FAILURE:
788
841
    
818
871
}
819
872
 
820
873
int main(int argc, char *argv[]){
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);
 
874
  AvahiSServiceBrowser *sb = NULL;
 
875
  int error;
 
876
  int ret;
 
877
  intmax_t tmpmax;
 
878
  int numchars;
 
879
  int exitcode = EXIT_SUCCESS;
 
880
  const char *interface = "eth0";
 
881
  struct ifreq network;
 
882
  int sd;
 
883
  uid_t uid;
 
884
  gid_t gid;
 
885
  char *connect_to = NULL;
 
886
  char tempdir[] = "/tmp/mandosXXXXXX";
 
887
  bool tempdir_created = false;
 
888
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
889
  const char *seckey = PATHDIR "/" SECKEY;
 
890
  const char *pubkey = PATHDIR "/" PUBKEY;
 
891
  
 
892
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
893
                        .dh_bits = 1024, .priority = "SECURE256"
 
894
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
895
  bool gnutls_initialized = false;
 
896
  bool gpgme_initialized = false;
 
897
  double delay = 2.5;
 
898
  
 
899
  {
 
900
    struct argp_option options[] = {
 
901
      { .name = "debug", .key = 128,
 
902
        .doc = "Debug mode", .group = 3 },
 
903
      { .name = "connect", .key = 'c',
 
904
        .arg = "ADDRESS:PORT",
 
905
        .doc = "Connect directly to a specific Mandos server",
 
906
        .group = 1 },
 
907
      { .name = "interface", .key = 'i',
 
908
        .arg = "NAME",
 
909
        .doc = "Network interface that will be used to search for"
 
910
        " Mandos servers",
 
911
        .group = 1 },
 
912
      { .name = "seckey", .key = 's',
 
913
        .arg = "FILE",
 
914
        .doc = "OpenPGP secret key file base name",
 
915
        .group = 1 },
 
916
      { .name = "pubkey", .key = 'p',
 
917
        .arg = "FILE",
 
918
        .doc = "OpenPGP public key file base name",
 
919
        .group = 2 },
 
920
      { .name = "dh-bits", .key = 129,
 
921
        .arg = "BITS",
 
922
        .doc = "Bit length of the prime number used in the"
 
923
        " Diffie-Hellman key exchange",
 
924
        .group = 2 },
 
925
      { .name = "priority", .key = 130,
 
926
        .arg = "STRING",
 
927
        .doc = "GnuTLS priority string for the TLS handshake",
 
928
        .group = 1 },
 
929
      { .name = "delay", .key = 131,
 
930
        .arg = "SECONDS",
 
931
        .doc = "Maximum delay to wait for interface startup",
 
932
        .group = 2 },
 
933
      { .name = NULL }
 
934
    };
 
935
    
 
936
    error_t parse_opt(int key, char *arg,
 
937
                      struct argp_state *state){
 
938
      switch(key){
 
939
      case 128:                 /* --debug */
 
940
        debug = true;
 
941
        break;
 
942
      case 'c':                 /* --connect */
 
943
        connect_to = arg;
 
944
        break;
 
945
      case 'i':                 /* --interface */
 
946
        interface = arg;
 
947
        break;
 
948
      case 's':                 /* --seckey */
 
949
        seckey = arg;
 
950
        break;
 
951
      case 'p':                 /* --pubkey */
 
952
        pubkey = arg;
 
953
        break;
 
954
      case 129:                 /* --dh-bits */
 
955
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
956
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
957
           or arg[numchars] != '\0'){
 
958
          fprintf(stderr, "Bad number of DH bits\n");
 
959
          exit(EXIT_FAILURE);
 
960
        }
 
961
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
962
        break;
 
963
      case 130:                 /* --priority */
 
964
        mc.priority = arg;
 
965
        break;
 
966
      case 131:                 /* --delay */
 
967
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
968
        if(ret < 1 or arg[numchars] != '\0'){
 
969
          fprintf(stderr, "Bad delay\n");
 
970
          exit(EXIT_FAILURE);
 
971
        }
 
972
        break;
 
973
      case ARGP_KEY_ARG:
 
974
        argp_usage(state);
 
975
      case ARGP_KEY_END:
 
976
        break;
 
977
      default:
 
978
        return ARGP_ERR_UNKNOWN;
 
979
      }
 
980
      return 0;
 
981
    }
 
982
    
 
983
    struct argp argp = { .options = options, .parser = parse_opt,
 
984
                         .args_doc = "",
 
985
                         .doc = "Mandos client -- Get and decrypt"
 
986
                         " passwords from a Mandos server" };
 
987
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
988
    if(ret == ARGP_ERR_UNKNOWN){
 
989
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
990
      exitcode = EXIT_FAILURE;
 
991
      goto end;
 
992
    }
 
993
  }
 
994
  
 
995
  /* If the interface is down, bring it up */
 
996
  if(interface[0] != '\0'){
 
997
#ifdef __linux__
 
998
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
999
       messages to mess up the prompt */
 
1000
    ret = klogctl(8, NULL, 5);
 
1001
    bool restore_loglevel = true;
 
1002
    if(ret == -1){
 
1003
      restore_loglevel = false;
 
1004
      perror("klogctl");
 
1005
    }
 
1006
#endif
 
1007
    
 
1008
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1009
    if(sd < 0){
 
1010
      perror("socket");
 
1011
      exitcode = EXIT_FAILURE;
 
1012
#ifdef __linux__
 
1013
      if(restore_loglevel){
 
1014
        ret = klogctl(7, NULL, 0);
 
1015
        if(ret == -1){
 
1016
          perror("klogctl");
 
1017
        }
 
1018
      }
 
1019
#endif
 
1020
      goto end;
 
1021
    }
 
1022
    strcpy(network.ifr_name, interface);
 
1023
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1024
    if(ret == -1){
 
1025
      perror("ioctl SIOCGIFFLAGS");
 
1026
#ifdef __linux__
 
1027
      if(restore_loglevel){
 
1028
        ret = klogctl(7, NULL, 0);
 
1029
        if(ret == -1){
 
1030
          perror("klogctl");
 
1031
        }
 
1032
      }
 
1033
#endif
 
1034
      exitcode = EXIT_FAILURE;
 
1035
      goto end;
 
1036
    }
 
1037
    if((network.ifr_flags & IFF_UP) == 0){
 
1038
      network.ifr_flags |= IFF_UP;
 
1039
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1040
      if(ret == -1){
 
1041
        perror("ioctl SIOCSIFFLAGS");
 
1042
        exitcode = EXIT_FAILURE;
 
1043
#ifdef __linux__
 
1044
        if(restore_loglevel){
 
1045
          ret = klogctl(7, NULL, 0);
 
1046
          if(ret == -1){
 
1047
            perror("klogctl");
901
1048
          }
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;
913
1049
        }
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;
 
1050
#endif
925
1051
        goto end;
926
1052
      }
927
1053
    }
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);
 
1054
    /* sleep checking until interface is running */
 
1055
    for(int i=0; i < delay * 4; i++){
938
1056
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
939
1057
      if(ret == -1){
940
1058
        perror("ioctl SIOCGIFFLAGS");
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));
 
1059
      } else if(network.ifr_flags & IFF_RUNNING){
 
1060
        break;
 
1061
      }
 
1062
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1063
      ret = nanosleep(&sleeptime, NULL);
 
1064
      if(ret == -1 and errno != EINTR){
 
1065
        perror("nanosleep");
 
1066
      }
 
1067
    }
 
1068
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1069
    if(ret == -1){
 
1070
      perror("close");
 
1071
    }
 
1072
#ifdef __linux__
 
1073
    if(restore_loglevel){
 
1074
      /* Restores kernel loglevel to default */
 
1075
      ret = klogctl(7, NULL, 0);
954
1076
      if(ret == -1){
955
 
        perror("close");
 
1077
        perror("klogctl");
956
1078
      }
957
1079
    }
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
 
    
 
1080
#endif
 
1081
  }
 
1082
  
 
1083
  uid = getuid();
 
1084
  gid = getgid();
 
1085
  
 
1086
  errno = 0;
 
1087
  setgid(gid);
 
1088
  if(ret == -1){
 
1089
    perror("setgid");
 
1090
  }
 
1091
  
 
1092
  ret = setuid(uid);
 
1093
  if(ret == -1){
 
1094
    perror("setuid");
 
1095
  }
 
1096
  
 
1097
  ret = init_gnutls_global(&mc, pubkey, seckey);
 
1098
  if(ret == -1){
 
1099
    fprintf(stderr, "init_gnutls_global failed\n");
 
1100
    exitcode = EXIT_FAILURE;
 
1101
    goto end;
 
1102
  } else {
 
1103
    gnutls_initialized = true;
 
1104
  }
 
1105
  
 
1106
  if(mkdtemp(tempdir) == NULL){
 
1107
    perror("mkdtemp");
 
1108
    goto end;
 
1109
  }
 
1110
  tempdir_created = true;
 
1111
  
 
1112
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1113
    fprintf(stderr, "init_gpgme failed\n");
 
1114
    exitcode = EXIT_FAILURE;
 
1115
    goto end;
 
1116
  } else {
 
1117
    gpgme_initialized = true;
 
1118
  }
 
1119
  
 
1120
  if(interface[0] != '\0'){
995
1121
    if_index = (AvahiIfIndex) if_nametoindex(interface);
996
1122
    if(if_index == 0){
997
1123
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
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
 
    
 
1124
      exitcode = EXIT_FAILURE;
 
1125
      goto end;
 
1126
    }
 
1127
  }
 
1128
  
 
1129
  if(connect_to != NULL){
 
1130
    /* Connect directly, do not use Zeroconf */
 
1131
    /* (Mainly meant for debugging) */
 
1132
    char *address = strrchr(connect_to, ':');
 
1133
    if(address == NULL){
 
1134
      fprintf(stderr, "No colon in address\n");
 
1135
      exitcode = EXIT_FAILURE;
 
1136
      goto end;
 
1137
    }
 
1138
    uint16_t port;
 
1139
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1140
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1141
       or address[numchars+1] != '\0'){
 
1142
      fprintf(stderr, "Bad port number\n");
 
1143
      exitcode = EXIT_FAILURE;
 
1144
      goto end;
 
1145
    }
 
1146
    port = (uint16_t)tmpmax;
 
1147
    *address = '\0';
 
1148
    address = connect_to;
 
1149
    /* Colon in address indicates IPv6 */
 
1150
    int af;
 
1151
    if(strchr(address, ':') != NULL){
 
1152
      af = AF_INET6;
 
1153
    } else {
 
1154
      af = AF_INET;
 
1155
    }
 
1156
    ret = start_mandos_communication(address, port, if_index, &mc,
 
1157
                                     af);
 
1158
    if(ret < 0){
 
1159
      exitcode = EXIT_FAILURE;
 
1160
    } else {
 
1161
      exitcode = EXIT_SUCCESS;
 
1162
    }
 
1163
    goto end;
 
1164
  }
 
1165
  
 
1166
  if(not debug){
 
1167
    avahi_set_log_function(empty_log);
 
1168
  }
 
1169
  
 
1170
  /* Initialize the pseudo-RNG for Avahi */
 
1171
  srand((unsigned int) time(NULL));
 
1172
  
 
1173
  /* Allocate main Avahi loop object */
 
1174
  mc.simple_poll = avahi_simple_poll_new();
 
1175
  if(mc.simple_poll == NULL){
 
1176
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1177
    exitcode = EXIT_FAILURE;
 
1178
    goto end;
 
1179
  }
 
1180
  
 
1181
  {
 
1182
    AvahiServerConfig config;
 
1183
    /* Do not publish any local Zeroconf records */
 
1184
    avahi_server_config_init(&config);
 
1185
    config.publish_hinfo = 0;
 
1186
    config.publish_addresses = 0;
 
1187
    config.publish_workstation = 0;
 
1188
    config.publish_domain = 0;
 
1189
    
 
1190
    /* Allocate a new server */
 
1191
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1192
                                 (mc.simple_poll), &config, NULL,
 
1193
                                 NULL, &error);
 
1194
    
 
1195
    /* Free the Avahi configuration data */
 
1196
    avahi_server_config_free(&config);
 
1197
  }
 
1198
  
 
1199
  /* Check if creating the Avahi server object succeeded */
 
1200
  if(mc.server == NULL){
 
1201
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1202
            avahi_strerror(error));
 
1203
    exitcode = EXIT_FAILURE;
 
1204
    goto end;
 
1205
  }
 
1206
  
 
1207
  /* Create the Avahi service browser */
 
1208
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1209
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1210
                                   NULL, 0, browse_callback, &mc);
 
1211
  if(sb == NULL){
 
1212
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1213
            avahi_strerror(avahi_server_errno(mc.server)));
 
1214
    exitcode = EXIT_FAILURE;
 
1215
    goto end;
 
1216
  }
 
1217
  
 
1218
  /* Run the main loop */
 
1219
  
 
1220
  if(debug){
 
1221
    fprintf(stderr, "Starting Avahi loop search\n");
 
1222
  }
 
1223
  
 
1224
  avahi_simple_poll_loop(mc.simple_poll);
 
1225
  
1092
1226
 end:
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;
 
1227
  
 
1228
  if(debug){
 
1229
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1230
  }
 
1231
  
 
1232
  /* Cleanup things */
 
1233
  if(sb != NULL)
 
1234
    avahi_s_service_browser_free(sb);
 
1235
  
 
1236
  if(mc.server != NULL)
 
1237
    avahi_server_free(mc.server);
 
1238
  
 
1239
  if(mc.simple_poll != NULL)
 
1240
    avahi_simple_poll_free(mc.simple_poll);
 
1241
  
 
1242
  if(gnutls_initialized){
 
1243
    gnutls_certificate_free_credentials(mc.cred);
 
1244
    gnutls_global_deinit();
 
1245
    gnutls_dh_params_deinit(mc.dh_params);
 
1246
  }
 
1247
  
 
1248
  if(gpgme_initialized){
 
1249
    gpgme_release(mc.ctx);
 
1250
  }
 
1251
  
 
1252
  /* Removes the temp directory used by GPGME */
 
1253
  if(tempdir_created){
 
1254
    DIR *d;
 
1255
    struct dirent *direntry;
 
1256
    d = opendir(tempdir);
 
1257
    if(d == NULL){
 
1258
      if(errno != ENOENT){
 
1259
        perror("opendir");
 
1260
      }
 
1261
    } else {
 
1262
      while(true){
 
1263
        direntry = readdir(d);
 
1264
        if(direntry == NULL){
 
1265
          break;
 
1266
        }
 
1267
        /* Skip "." and ".." */
 
1268
        if(direntry->d_name[0] == '.'
 
1269
           and (direntry->d_name[1] == '\0'
 
1270
                or (direntry->d_name[1] == '.'
 
1271
                    and direntry->d_name[2] == '\0'))){
 
1272
          continue;
 
1273
        }
 
1274
        char *fullname = NULL;
 
1275
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1276
                       direntry->d_name);
 
1277
        if(ret < 0){
 
1278
          perror("asprintf");
 
1279
          continue;
 
1280
        }
 
1281
        ret = remove(fullname);
 
1282
        if(ret == -1){
 
1283
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1284
                  strerror(errno));
 
1285
        }
 
1286
        free(fullname);
 
1287
      }
 
1288
      closedir(d);
 
1289
    }
 
1290
    ret = rmdir(tempdir);
 
1291
    if(ret == -1 and errno != ENOENT){
 
1292
      perror("rmdir");
 
1293
    }
 
1294
  }
 
1295
  
 
1296
  return exitcode;
1158
1297
}