/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-07 03:38:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090207033817-aotdjeibhz3sa4lr
* plugin-runner.c (main): If debugging, print name of failed plugins.

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,
60
61
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
61
62
#include <assert.h>             /* assert() */
62
63
#include <errno.h>              /* perror(), errno */
63
 
#include <time.h>               /* time() */
 
64
#include <time.h>               /* nanosleep(), time() */
64
65
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
65
66
                                   SIOCSIFFLAGS, if_indextoname(),
66
67
                                   if_nametoindex(), IF_NAMESIZE */
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;
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);
530
534
  }
531
535
  
532
536
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
533
 
  if(tcp_sd < 0) {
 
537
  if(tcp_sd < 0){
534
538
    perror("socket");
535
539
    return -1;
536
540
  }
733
737
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
734
738
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
735
739
                             flags,
736
 
                             void* userdata) {
 
740
                             void* userdata){
737
741
  mandos_context *mc = userdata;
738
742
  assert(r);
739
743
  
740
744
  /* Called whenever a service has been resolved successfully or
741
745
     timed out */
742
746
  
743
 
  switch(event) {
 
747
  switch(event){
744
748
  default:
745
749
  case AVAHI_RESOLVER_FAILURE:
746
750
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
766
770
  avahi_s_service_resolver_free(r);
767
771
}
768
772
 
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) {
 
773
static void browse_callback(AvahiSServiceBrowser *b,
 
774
                            AvahiIfIndex interface,
 
775
                            AvahiProtocol protocol,
 
776
                            AvahiBrowserEvent event,
 
777
                            const char *name,
 
778
                            const char *type,
 
779
                            const char *domain,
 
780
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
781
                            flags,
 
782
                            void* userdata){
779
783
  mandos_context *mc = userdata;
780
784
  assert(b);
781
785
  
782
786
  /* Called whenever a new services becomes available on the LAN or
783
787
     is removed from the LAN */
784
788
  
785
 
  switch(event) {
 
789
  switch(event){
786
790
  default:
787
791
  case AVAHI_BROWSER_FAILURE:
788
792
    
818
822
}
819
823
 
820
824
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);
901
 
          }
902
 
          mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
903
 
          break;
904
 
        case 130:               /* --priority */
905
 
          mc.priority = arg;
906
 
          break;
907
 
        case ARGP_KEY_ARG:
908
 
          argp_usage(state);
909
 
        case ARGP_KEY_END:
910
 
          break;
911
 
        default:
912
 
          return ARGP_ERR_UNKNOWN;
913
 
        }
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;
925
 
        goto end;
926
 
      }
927
 
    }
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);
 
825
  AvahiSServiceBrowser *sb = NULL;
 
826
  int error;
 
827
  int ret;
 
828
  intmax_t tmpmax;
 
829
  int numchars;
 
830
  int exitcode = EXIT_SUCCESS;
 
831
  const char *interface = "eth0";
 
832
  struct ifreq network;
 
833
  int sd;
 
834
  uid_t uid;
 
835
  gid_t gid;
 
836
  char *connect_to = NULL;
 
837
  char tempdir[] = "/tmp/mandosXXXXXX";
 
838
  bool tempdir_created = false;
 
839
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
840
  const char *seckey = PATHDIR "/" SECKEY;
 
841
  const char *pubkey = PATHDIR "/" PUBKEY;
 
842
  
 
843
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
844
                        .dh_bits = 1024, .priority = "SECURE256"
 
845
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
846
  bool gnutls_initialized = false;
 
847
  bool gpgme_initialized = false;
 
848
  double delay = 2.5;
 
849
  
 
850
  {
 
851
    struct argp_option options[] = {
 
852
      { .name = "debug", .key = 128,
 
853
        .doc = "Debug mode", .group = 3 },
 
854
      { .name = "connect", .key = 'c',
 
855
        .arg = "ADDRESS:PORT",
 
856
        .doc = "Connect directly to a specific Mandos server",
 
857
        .group = 1 },
 
858
      { .name = "interface", .key = 'i',
 
859
        .arg = "NAME",
 
860
        .doc = "Interface that will be used to search for Mandos"
 
861
        " servers",
 
862
        .group = 1 },
 
863
      { .name = "seckey", .key = 's',
 
864
        .arg = "FILE",
 
865
        .doc = "OpenPGP secret key file base name",
 
866
        .group = 1 },
 
867
      { .name = "pubkey", .key = 'p',
 
868
        .arg = "FILE",
 
869
        .doc = "OpenPGP public key file base name",
 
870
        .group = 2 },
 
871
      { .name = "dh-bits", .key = 129,
 
872
        .arg = "BITS",
 
873
        .doc = "Bit length of the prime number used in the"
 
874
        " Diffie-Hellman key exchange",
 
875
        .group = 2 },
 
876
      { .name = "priority", .key = 130,
 
877
        .arg = "STRING",
 
878
        .doc = "GnuTLS priority string for the TLS handshake",
 
879
        .group = 1 },
 
880
      { .name = "delay", .key = 131,
 
881
        .arg = "SECONDS",
 
882
        .doc = "Maximum delay to wait for interface startup",
 
883
        .group = 2 },
 
884
      { .name = NULL }
 
885
    };
 
886
    
 
887
    error_t parse_opt(int key, char *arg,
 
888
                      struct argp_state *state){
 
889
      switch(key){
 
890
      case 128:                 /* --debug */
 
891
        debug = true;
 
892
        break;
 
893
      case 'c':                 /* --connect */
 
894
        connect_to = arg;
 
895
        break;
 
896
      case 'i':                 /* --interface */
 
897
        interface = arg;
 
898
        break;
 
899
      case 's':                 /* --seckey */
 
900
        seckey = arg;
 
901
        break;
 
902
      case 'p':                 /* --pubkey */
 
903
        pubkey = arg;
 
904
        break;
 
905
      case 129:                 /* --dh-bits */
 
906
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
907
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
908
           or arg[numchars] != '\0'){
 
909
          fprintf(stderr, "Bad number of DH bits\n");
 
910
          exit(EXIT_FAILURE);
 
911
        }
 
912
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
913
        break;
 
914
      case 130:                 /* --priority */
 
915
        mc.priority = arg;
 
916
        break;
 
917
      case 131:                 /* --delay */
 
918
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
919
        if(ret < 1 or arg[numchars] != '\0'){
 
920
          fprintf(stderr, "Bad delay\n");
 
921
          exit(EXIT_FAILURE);
 
922
        }
 
923
        break;
 
924
      case ARGP_KEY_ARG:
 
925
        argp_usage(state);
 
926
      case ARGP_KEY_END:
 
927
        break;
 
928
      default:
 
929
        return ARGP_ERR_UNKNOWN;
 
930
      }
 
931
      return 0;
 
932
    }
 
933
    
 
934
    struct argp argp = { .options = options, .parser = parse_opt,
 
935
                         .args_doc = "",
 
936
                         .doc = "Mandos client -- Get and decrypt"
 
937
                         " passwords from a Mandos server" };
 
938
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
939
    if(ret == ARGP_ERR_UNKNOWN){
 
940
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
941
      exitcode = EXIT_FAILURE;
 
942
      goto end;
 
943
    }
 
944
  }
 
945
  
 
946
  /* If the interface is down, bring it up */
 
947
  {
 
948
#ifdef __linux__
 
949
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
950
       messages to mess up the prompt */
 
951
    ret = klogctl(8, NULL, 5);
 
952
    if(ret == -1){
 
953
      perror("klogctl");
 
954
    }
 
955
#endif
 
956
    
 
957
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
958
    if(sd < 0){
 
959
      perror("socket");
 
960
      exitcode = EXIT_FAILURE;
 
961
#ifdef __linux__
 
962
      ret = klogctl(7, NULL, 0);
 
963
      if(ret == -1){
 
964
        perror("klogctl");
 
965
      }
 
966
#endif
 
967
      goto end;
 
968
    }
 
969
    strcpy(network.ifr_name, interface);
 
970
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
971
    if(ret == -1){
 
972
      perror("ioctl SIOCGIFFLAGS");
 
973
#ifdef __linux__
 
974
      ret = klogctl(7, NULL, 0);
 
975
      if(ret == -1){
 
976
        perror("klogctl");
 
977
      }
 
978
#endif
 
979
      exitcode = EXIT_FAILURE;
 
980
      goto end;
 
981
    }
 
982
    if((network.ifr_flags & IFF_UP) == 0){
 
983
      network.ifr_flags |= IFF_UP;
 
984
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
985
      if(ret == -1){
 
986
        perror("ioctl SIOCSIFFLAGS");
 
987
        exitcode = EXIT_FAILURE;
 
988
#ifdef __linux__
 
989
        ret = klogctl(7, NULL, 0);
 
990
        if(ret == -1){
 
991
          perror("klogctl");
 
992
        }
 
993
#endif
 
994
        goto end;
 
995
      }
 
996
    }
 
997
    /* sleep checking until interface is running */
 
998
    for(int i=0; i < delay * 4; i++){
938
999
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
939
1000
      if(ret == -1){
940
1001
        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));
954
 
      if(ret == -1){
955
 
        perror("close");
956
 
      }
957
 
    }
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
 
    
995
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
996
 
    if(if_index == 0){
997
 
      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
 
    
 
1002
      } else if(network.ifr_flags & IFF_RUNNING){
 
1003
        break;
 
1004
      }
 
1005
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1006
      ret = nanosleep(&sleeptime, NULL);
 
1007
      if(ret == -1 and errno != EINTR){
 
1008
        perror("nanosleep");
 
1009
      }
 
1010
    }
 
1011
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1012
    if(ret == -1){
 
1013
      perror("close");
 
1014
    }
 
1015
#ifdef __linux__
 
1016
    /* Restores kernel loglevel to default */
 
1017
    ret = klogctl(7, NULL, 0);
 
1018
    if(ret == -1){
 
1019
      perror("klogctl");
 
1020
    }
 
1021
#endif
 
1022
  }
 
1023
  
 
1024
  uid = getuid();
 
1025
  gid = getgid();
 
1026
  
 
1027
  setgid(gid);
 
1028
  if(ret == -1){
 
1029
    perror("setgid");
 
1030
  }
 
1031
  
 
1032
  ret = setuid(uid);
 
1033
  if(ret == -1){
 
1034
    perror("setuid");
 
1035
  }
 
1036
  
 
1037
  ret = init_gnutls_global(&mc, pubkey, seckey);
 
1038
  if(ret == -1){
 
1039
    fprintf(stderr, "init_gnutls_global failed\n");
 
1040
    exitcode = EXIT_FAILURE;
 
1041
    goto end;
 
1042
  } else {
 
1043
    gnutls_initialized = true;
 
1044
  }
 
1045
  
 
1046
  if(mkdtemp(tempdir) == NULL){
 
1047
    perror("mkdtemp");
 
1048
    goto end;
 
1049
  }
 
1050
  tempdir_created = true;
 
1051
  
 
1052
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1053
    fprintf(stderr, "init_gpgme failed\n");
 
1054
    exitcode = EXIT_FAILURE;
 
1055
    goto end;
 
1056
  } else {
 
1057
    gpgme_initialized = true;
 
1058
  }
 
1059
  
 
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;
 
1065
  }
 
1066
  
 
1067
  if(connect_to != NULL){
 
1068
    /* Connect directly, do not use Zeroconf */
 
1069
    /* (Mainly meant for debugging) */
 
1070
    char *address = strrchr(connect_to, ':');
 
1071
    if(address == NULL){
 
1072
      fprintf(stderr, "No colon in address\n");
 
1073
      exitcode = EXIT_FAILURE;
 
1074
      goto end;
 
1075
    }
 
1076
    uint16_t port;
 
1077
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1078
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1079
       or address[numchars+1] != '\0'){
 
1080
      fprintf(stderr, "Bad port number\n");
 
1081
      exitcode = EXIT_FAILURE;
 
1082
      goto end;
 
1083
    }
 
1084
    port = (uint16_t)tmpmax;
 
1085
    *address = '\0';
 
1086
    address = connect_to;
 
1087
    ret = start_mandos_communication(address, port, if_index, &mc);
 
1088
    if(ret < 0){
 
1089
      exitcode = EXIT_FAILURE;
 
1090
    } else {
 
1091
      exitcode = EXIT_SUCCESS;
 
1092
    }
 
1093
    goto end;
 
1094
  }
 
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
  
 
1111
  {
 
1112
    AvahiServerConfig config;
 
1113
    /* Do not publish any local Zeroconf records */
 
1114
    avahi_server_config_init(&config);
 
1115
    config.publish_hinfo = 0;
 
1116
    config.publish_addresses = 0;
 
1117
    config.publish_workstation = 0;
 
1118
    config.publish_domain = 0;
 
1119
    
 
1120
    /* Allocate a new server */
 
1121
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1122
                                 (mc.simple_poll), &config, NULL,
 
1123
                                 NULL, &error);
 
1124
    
 
1125
    /* Free the Avahi configuration data */
 
1126
    avahi_server_config_free(&config);
 
1127
  }
 
1128
  
 
1129
  /* Check if creating the Avahi server object succeeded */
 
1130
  if(mc.server == NULL){
 
1131
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1132
            avahi_strerror(error));
 
1133
    exitcode = EXIT_FAILURE;
 
1134
    goto end;
 
1135
  }
 
1136
  
 
1137
  /* Create the Avahi service browser */
 
1138
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1139
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1140
                                   NULL, 0, browse_callback, &mc);
 
1141
  if(sb == NULL){
 
1142
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1143
            avahi_strerror(avahi_server_errno(mc.server)));
 
1144
    exitcode = EXIT_FAILURE;
 
1145
    goto end;
 
1146
  }
 
1147
  
 
1148
  /* Run the main loop */
 
1149
  
 
1150
  if(debug){
 
1151
    fprintf(stderr, "Starting Avahi loop search\n");
 
1152
  }
 
1153
  
 
1154
  avahi_simple_poll_loop(mc.simple_poll);
 
1155
  
1092
1156
 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;
 
1157
  
 
1158
  if(debug){
 
1159
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1160
  }
 
1161
  
 
1162
  /* Cleanup things */
 
1163
  if(sb != NULL)
 
1164
    avahi_s_service_browser_free(sb);
 
1165
  
 
1166
  if(mc.server != NULL)
 
1167
    avahi_server_free(mc.server);
 
1168
  
 
1169
  if(mc.simple_poll != NULL)
 
1170
    avahi_simple_poll_free(mc.simple_poll);
 
1171
  
 
1172
  if(gnutls_initialized){
 
1173
    gnutls_certificate_free_credentials(mc.cred);
 
1174
    gnutls_global_deinit();
 
1175
    gnutls_dh_params_deinit(mc.dh_params);
 
1176
  }
 
1177
  
 
1178
  if(gpgme_initialized){
 
1179
    gpgme_release(mc.ctx);
 
1180
  }
 
1181
  
 
1182
  /* Removes the temp directory used by GPGME */
 
1183
  if(tempdir_created){
 
1184
    DIR *d;
 
1185
    struct dirent *direntry;
 
1186
    d = opendir(tempdir);
 
1187
    if(d == NULL){
 
1188
      if(errno != ENOENT){
 
1189
        perror("opendir");
 
1190
      }
 
1191
    } else {
 
1192
      while(true){
 
1193
        direntry = readdir(d);
 
1194
        if(direntry == NULL){
 
1195
          break;
 
1196
        }
 
1197
        /* Skip "." and ".." */
 
1198
        if(direntry->d_name[0] == '.'
 
1199
           and (direntry->d_name[1] == '\0'
 
1200
                or (direntry->d_name[1] == '.'
 
1201
                    and direntry->d_name[2] == '\0'))){
 
1202
          continue;
 
1203
        }
 
1204
        char *fullname = NULL;
 
1205
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1206
                       direntry->d_name);
 
1207
        if(ret < 0){
 
1208
          perror("asprintf");
 
1209
          continue;
 
1210
        }
 
1211
        ret = remove(fullname);
 
1212
        if(ret == -1){
 
1213
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1214
                  strerror(errno));
 
1215
        }
 
1216
        free(fullname);
 
1217
      }
 
1218
      closedir(d);
 
1219
    }
 
1220
    ret = rmdir(tempdir);
 
1221
    if(ret == -1 and errno != ENOENT){
 
1222
      perror("rmdir");
 
1223
    }
 
1224
  }
 
1225
  
 
1226
  return exitcode;
1158
1227
}