/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

* plugins.d/mandos-client.c (init_gnutls_session): Retry interrupted
                                                   GnuTLS functions.
  (main): Drop privileges early, and raise them only where needed and
          lower them whenever possible.

Show diffs side-by-side

added added

removed removed

Lines of Context:
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
 
33
#ifndef _LARGEFILE_SOURCE
33
34
#define _LARGEFILE_SOURCE
 
35
#endif
 
36
#ifndef _FILE_OFFSET_BITS
34
37
#define _FILE_OFFSET_BITS 64
 
38
#endif
35
39
 
36
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
41
 
38
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
 
43
                                   stdout, ferror(), remove() */
41
44
#include <stdint.h>             /* uint16_t, uint32_t */
42
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
 
47
                                   srand(), strtof() */
45
48
#include <stdbool.h>            /* bool, false, true */
46
49
#include <string.h>             /* memset(), strcmp(), strlen(),
47
50
                                   strerror(), asprintf(), strcpy() */
56
59
#include <fcntl.h>              /* open() */
57
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
58
61
                                 */
59
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
 
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
 
63
                                   strtoimax() */
60
64
#include <assert.h>             /* assert() */
61
65
#include <errno.h>              /* perror(), errno */
62
66
#include <time.h>               /* nanosleep(), time() */
67
71
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
68
72
                                */
69
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
 
                                   getuid(), getgid(), setuid(),
 
74
                                   getuid(), getgid(), seteuid(),
71
75
                                   setgid() */
72
76
#include <arpa/inet.h>          /* inet_pton(), htons */
73
77
#include <iso646.h>             /* not, or, and */
76
80
                                   argp_parse(), ARGP_KEY_ARG,
77
81
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
78
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
79
 
                                   sigaction(), SIGTERM, sigaction */
 
83
                                   sigaction(), SIGTERM, sig_atomic_t,
 
84
                                   raise() */
80
85
 
81
86
#ifdef __linux__
82
87
#include <sys/klog.h>           /* klogctl() */
83
 
#endif
 
88
#endif  /* __linux__ */
84
89
 
85
90
/* Avahi */
86
91
/* All Avahi types, constants and functions
133
138
} mandos_context;
134
139
 
135
140
/* global context so signal handler can reach it*/
136
 
mandos_context mc;
 
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
142
                      .dh_bits = 1024, .priority = "SECURE256"
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
137
144
 
138
145
/*
139
 
 * Make additional room in "buffer" for at least BUFFER_SIZE
140
 
 * additional bytes. "buffer_capacity" is how much is currently
141
 
 * allocated, "buffer_length" is how much is already used.
 
146
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
147
 * bytes. "buffer_capacity" is how much is currently allocated,
 
148
 * "buffer_length" is how much is already used.
142
149
 */
143
150
size_t incbuffer(char **buffer, size_t buffer_length,
144
151
                  size_t buffer_capacity){
157
164
 */
158
165
static bool init_gpgme(const char *seckey,
159
166
                       const char *pubkey, const char *tempdir){
160
 
  int ret;
161
167
  gpgme_error_t rc;
162
168
  gpgme_engine_info_t engine_info;
163
169
  
166
172
   * Helper function to insert pub and seckey to the engine keyring.
167
173
   */
168
174
  bool import_key(const char *filename){
 
175
    int ret;
169
176
    int fd;
170
177
    gpgme_data_t pgp_data;
171
178
    
242
249
    return false;
243
250
  }
244
251
  
245
 
  return true; 
 
252
  return true;
246
253
}
247
254
 
248
255
/* 
302
309
        }
303
310
        gpgme_recipient_t recipient;
304
311
        recipient = result->recipients;
305
 
        if(recipient){
306
 
          while(recipient != NULL){
307
 
            fprintf(stderr, "Public key algorithm: %s\n",
308
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
309
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
310
 
            fprintf(stderr, "Secret key available: %s\n",
311
 
                    recipient->status == GPG_ERR_NO_SECKEY
312
 
                    ? "No" : "Yes");
313
 
            recipient = recipient->next;
314
 
          }
 
312
        while(recipient != NULL){
 
313
          fprintf(stderr, "Public key algorithm: %s\n",
 
314
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
315
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
316
          fprintf(stderr, "Secret key available: %s\n",
 
317
                  recipient->status == GPG_ERR_NO_SECKEY
 
318
                  ? "No" : "Yes");
 
319
          recipient = recipient->next;
315
320
        }
316
321
      }
317
322
    }
469
474
static int init_gnutls_session(gnutls_session_t *session){
470
475
  int ret;
471
476
  /* GnuTLS session creation */
472
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
477
  do {
 
478
    ret = gnutls_init(session, GNUTLS_SERVER);
 
479
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
473
480
  if(ret != GNUTLS_E_SUCCESS){
474
481
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
475
482
            safer_gnutls_strerror(ret));
477
484
  
478
485
  {
479
486
    const char *err;
480
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
487
    do {
 
488
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
489
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
481
490
    if(ret != GNUTLS_E_SUCCESS){
482
491
      fprintf(stderr, "Syntax error at: %s\n", err);
483
492
      fprintf(stderr, "GnuTLS error: %s\n",
487
496
    }
488
497
  }
489
498
  
490
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
491
 
                               mc.cred);
 
499
  do {
 
500
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
501
                                 mc.cred);
 
502
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
492
503
  if(ret != GNUTLS_E_SUCCESS){
493
504
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
494
505
            safer_gnutls_strerror(ret));
497
508
  }
498
509
  
499
510
  /* ignore client certificate if any. */
500
 
  gnutls_certificate_server_set_request(*session,
501
 
                                        GNUTLS_CERT_IGNORE);
 
511
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
502
512
  
503
513
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
504
514
  
509
519
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
510
520
                      __attribute__((unused)) const char *txt){}
511
521
 
 
522
sig_atomic_t quit_now = 0;
 
523
int signal_received = 0;
 
524
 
512
525
/* Called when a Mandos server is found */
513
526
static int start_mandos_communication(const char *ip, uint16_t port,
514
527
                                      AvahiIfIndex if_index,
515
528
                                      int af){
516
 
  int ret, tcp_sd;
 
529
  int ret, tcp_sd = -1;
517
530
  ssize_t sret;
518
531
  union {
519
532
    struct sockaddr_in in;
523
536
  char *decrypted_buffer;
524
537
  size_t buffer_length = 0;
525
538
  size_t buffer_capacity = 0;
526
 
  ssize_t decrypted_buffer_size;
527
539
  size_t written;
528
540
  int retval = 0;
529
541
  gnutls_session_t session;
530
542
  int pf;                       /* Protocol family */
531
543
  
 
544
  if(quit_now){
 
545
    return -1;
 
546
  }
 
547
  
532
548
  switch(af){
533
549
  case AF_INET6:
534
550
    pf = PF_INET6;
554
570
  tcp_sd = socket(pf, SOCK_STREAM, 0);
555
571
  if(tcp_sd < 0){
556
572
    perror("socket");
557
 
    return -1;
 
573
    retval = -1;
 
574
    goto mandos_end;
 
575
  }
 
576
  
 
577
  if(quit_now){
 
578
    goto mandos_end;
558
579
  }
559
580
  
560
581
  memset(&to, 0, sizeof(to));
561
582
  if(af == AF_INET6){
562
 
    to.in6.sin6_family = (uint16_t)af;
 
583
    to.in6.sin6_family = (sa_family_t)af;
563
584
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
564
585
  } else {                      /* IPv4 */
565
586
    to.in.sin_family = (sa_family_t)af;
567
588
  }
568
589
  if(ret < 0 ){
569
590
    perror("inet_pton");
570
 
    return -1;
 
591
    retval = -1;
 
592
    goto mandos_end;
571
593
  }
572
594
  if(ret == 0){
573
595
    fprintf(stderr, "Bad address: %s\n", ip);
574
 
    return -1;
 
596
    retval = -1;
 
597
    goto mandos_end;
575
598
  }
576
599
  if(af == AF_INET6){
577
600
    to.in6.sin6_port = htons(port); /* Spurious warnings from
584
607
      if(if_index == AVAHI_IF_UNSPEC){
585
608
        fprintf(stderr, "An IPv6 link-local address is incomplete"
586
609
                " without a network interface\n");
587
 
        return -1;
 
610
        retval = -1;
 
611
        goto mandos_end;
588
612
      }
589
613
      /* Set the network interface number as scope */
590
614
      to.in6.sin6_scope_id = (uint32_t)if_index;
595
619
                                     -Wunreachable-code */
596
620
  }
597
621
  
 
622
  if(quit_now){
 
623
    goto mandos_end;
 
624
  }
 
625
  
598
626
  if(debug){
599
627
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
600
628
      char interface[IF_NAMESIZE];
627
655
    }
628
656
  }
629
657
  
 
658
  if(quit_now){
 
659
    goto mandos_end;
 
660
  }
 
661
  
630
662
  if(af == AF_INET6){
631
663
    ret = connect(tcp_sd, &to.in6, sizeof(to));
632
664
  } else {
634
666
  }
635
667
  if(ret < 0){
636
668
    perror("connect");
637
 
    return -1;
 
669
    retval = -1;
 
670
    goto mandos_end;
 
671
  }
 
672
  
 
673
  if(quit_now){
 
674
    goto mandos_end;
638
675
  }
639
676
  
640
677
  const char *out = mandos_protocol_version;
659
696
        break;
660
697
      }
661
698
    }
 
699
  
 
700
    if(quit_now){
 
701
      goto mandos_end;
 
702
    }
662
703
  }
663
704
  
664
705
  if(debug){
665
706
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
666
707
  }
667
708
  
 
709
  if(quit_now){
 
710
    goto mandos_end;
 
711
  }
 
712
  
668
713
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
669
714
  
670
 
  do{
 
715
  if(quit_now){
 
716
    goto mandos_end;
 
717
  }
 
718
  
 
719
  do {
671
720
    ret = gnutls_handshake(session);
 
721
    if(quit_now){
 
722
      goto mandos_end;
 
723
    }
672
724
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
673
725
  
674
726
  if(ret != GNUTLS_E_SUCCESS){
688
740
  }
689
741
  
690
742
  while(true){
 
743
    
 
744
    if(quit_now){
 
745
      goto mandos_end;
 
746
    }
 
747
    
691
748
    buffer_capacity = incbuffer(&buffer, buffer_length,
692
749
                                   buffer_capacity);
693
750
    if(buffer_capacity == 0){
696
753
      goto mandos_end;
697
754
    }
698
755
    
 
756
    if(quit_now){
 
757
      goto mandos_end;
 
758
    }
 
759
    
699
760
    sret = gnutls_record_recv(session, buffer+buffer_length,
700
761
                              BUFFER_SIZE);
701
762
    if(sret == 0){
707
768
      case GNUTLS_E_AGAIN:
708
769
        break;
709
770
      case GNUTLS_E_REHANDSHAKE:
710
 
        do{
 
771
        do {
711
772
          ret = gnutls_handshake(session);
 
773
          
 
774
          if(quit_now){
 
775
            goto mandos_end;
 
776
          }
712
777
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
713
778
        if(ret < 0){
714
779
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
733
798
    fprintf(stderr, "Closing TLS session\n");
734
799
  }
735
800
  
 
801
  if(quit_now){
 
802
    goto mandos_end;
 
803
  }
 
804
  
736
805
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
737
806
  
 
807
  if(quit_now){
 
808
    goto mandos_end;
 
809
  }
 
810
  
738
811
  if(buffer_length > 0){
 
812
    ssize_t decrypted_buffer_size;
739
813
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
740
814
                                               buffer_length,
741
815
                                               &decrypted_buffer);
742
816
    if(decrypted_buffer_size >= 0){
 
817
      
743
818
      written = 0;
744
819
      while(written < (size_t) decrypted_buffer_size){
 
820
        if(quit_now){
 
821
          goto mandos_end;
 
822
        }
 
823
        
745
824
        ret = (int)fwrite(decrypted_buffer + written, 1,
746
825
                          (size_t)decrypted_buffer_size - written,
747
826
                          stdout);
767
846
  
768
847
 mandos_end:
769
848
  free(buffer);
770
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
849
  if(tcp_sd >= 0){
 
850
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
851
  }
771
852
  if(ret == -1){
772
853
    perror("close");
773
854
  }
774
855
  gnutls_deinit(session);
 
856
  if(quit_now){
 
857
    retval = -1;
 
858
  }
775
859
  return retval;
776
860
}
777
861
 
794
878
  /* Called whenever a service has been resolved successfully or
795
879
     timed out */
796
880
  
 
881
  if(quit_now){
 
882
    return;
 
883
  }
 
884
  
797
885
  switch(event){
798
886
  default:
799
887
  case AVAHI_RESOLVER_FAILURE:
836
924
  /* Called whenever a new services becomes available on the LAN or
837
925
     is removed from the LAN */
838
926
  
 
927
  if(quit_now){
 
928
    return;
 
929
  }
 
930
  
839
931
  switch(event){
840
932
  default:
841
933
  case AVAHI_BROWSER_FAILURE:
851
943
       the callback function is called the Avahi server will free the
852
944
       resolver for us. */
853
945
    
854
 
    if(!(avahi_s_service_resolver_new(mc.server, interface,
855
 
                                       protocol, name, type, domain,
856
 
                                       AVAHI_PROTO_INET6, 0,
857
 
                                       resolve_callback, NULL)))
 
946
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
947
                                    name, type, domain, protocol, 0,
 
948
                                    resolve_callback, NULL) == NULL)
858
949
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
859
950
              name, avahi_strerror(avahi_server_errno(mc.server)));
860
951
    break;
871
962
  }
872
963
}
873
964
 
874
 
static void handle_sigterm(__attribute__((unused)) int sig){
 
965
/* stop main loop after sigterm has been called */
 
966
static void handle_sigterm(int sig){
 
967
  if(quit_now){
 
968
    return;
 
969
  }
 
970
  quit_now = 1;
 
971
  signal_received = sig;
875
972
  int old_errno = errno;
876
 
  avahi_simple_poll_quit(mc.simple_poll);
 
973
  if(mc.simple_poll != NULL){
 
974
    avahi_simple_poll_quit(mc.simple_poll);
 
975
  }
877
976
  errno = old_errno;
878
977
}
879
978
 
882
981
  int error;
883
982
  int ret;
884
983
  intmax_t tmpmax;
885
 
  int numchars;
 
984
  char *tmp;
886
985
  int exitcode = EXIT_SUCCESS;
887
986
  const char *interface = "eth0";
888
987
  struct ifreq network;
889
 
  int sd;
 
988
  int sd = -1;
 
989
  bool take_down_interface = false;
890
990
  uid_t uid;
891
991
  gid_t gid;
892
992
  char *connect_to = NULL;
896
996
  const char *seckey = PATHDIR "/" SECKEY;
897
997
  const char *pubkey = PATHDIR "/" PUBKEY;
898
998
  
899
 
  /* Initialize Mandos context */
900
 
  mc = (mandos_context){ .simple_poll = NULL, .server = NULL,
901
 
                         .dh_bits = 1024, .priority = "SECURE256"
902
 
                         ":!CTYPE-X.509:+CTYPE-OPENPGP" };
903
999
  bool gnutls_initialized = false;
904
1000
  bool gpgme_initialized = false;
905
 
  double delay = 2.5;
906
 
 
 
1001
  float delay = 2.5f;
 
1002
  
907
1003
  struct sigaction old_sigterm_action;
908
1004
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
909
1005
  
 
1006
  uid = getuid();
 
1007
  gid = getgid();
 
1008
  
 
1009
  /* Lower any group privileges we might have, just to be safe */
 
1010
  errno = 0;
 
1011
  ret = setgid(gid);
 
1012
  if(ret == -1){
 
1013
    perror("setgid");
 
1014
  }
 
1015
  
 
1016
  /* Lower user privileges (temporarily) */
 
1017
  errno = 0;
 
1018
  ret = seteuid(uid);
 
1019
  if(ret == -1){
 
1020
    perror("seteuid");
 
1021
  }
 
1022
  
 
1023
  if(quit_now){
 
1024
    goto end;
 
1025
  }
 
1026
  
910
1027
  {
911
1028
    struct argp_option options[] = {
912
1029
      { .name = "debug", .key = 128,
963
1080
        pubkey = arg;
964
1081
        break;
965
1082
      case 129:                 /* --dh-bits */
966
 
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
967
 
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
968
 
           or arg[numchars] != '\0'){
 
1083
        errno = 0;
 
1084
        tmpmax = strtoimax(arg, &tmp, 10);
 
1085
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1086
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
969
1087
          fprintf(stderr, "Bad number of DH bits\n");
970
1088
          exit(EXIT_FAILURE);
971
1089
        }
975
1093
        mc.priority = arg;
976
1094
        break;
977
1095
      case 131:                 /* --delay */
978
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
979
 
        if(ret < 1 or arg[numchars] != '\0'){
 
1096
        errno = 0;
 
1097
        delay = strtof(arg, &tmp);
 
1098
        if(errno != 0 or tmp == arg or *tmp != '\0'){
980
1099
          fprintf(stderr, "Bad delay\n");
981
1100
          exit(EXIT_FAILURE);
982
1101
        }
1003
1122
    }
1004
1123
  }
1005
1124
  
 
1125
  if(not debug){
 
1126
    avahi_set_log_function(empty_log);
 
1127
  }
 
1128
  
 
1129
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1130
     from the signal handler */
 
1131
  /* Initialize the pseudo-RNG for Avahi */
 
1132
  srand((unsigned int) time(NULL));
 
1133
  mc.simple_poll = avahi_simple_poll_new();
 
1134
  if(mc.simple_poll == NULL){
 
1135
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1136
    exitcode = EXIT_FAILURE;
 
1137
    goto end;
 
1138
  }
 
1139
  
 
1140
  sigemptyset(&sigterm_action.sa_mask);
 
1141
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1142
  if(ret == -1){
 
1143
    perror("sigaddset");
 
1144
    exitcode = EXIT_FAILURE;
 
1145
    goto end;
 
1146
  }
 
1147
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1148
  if(ret == -1){
 
1149
    perror("sigaddset");
 
1150
    exitcode = EXIT_FAILURE;
 
1151
    goto end;
 
1152
  }
 
1153
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1154
  if(ret == -1){
 
1155
    perror("sigaddset");
 
1156
    exitcode = EXIT_FAILURE;
 
1157
    goto end;
 
1158
  }
 
1159
  /* Need to check if the handler is SIG_IGN before handling:
 
1160
     | [[info:libc:Initial Signal Actions]] |
 
1161
     | [[info:libc:Basic Signal Handling]]  |
 
1162
  */
 
1163
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1164
  if(ret == -1){
 
1165
    perror("sigaction");
 
1166
    return EXIT_FAILURE;
 
1167
  }
 
1168
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1169
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1170
    if(ret == -1){
 
1171
      perror("sigaction");
 
1172
      exitcode = EXIT_FAILURE;
 
1173
      goto end;
 
1174
    }
 
1175
  }
 
1176
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1177
  if(ret == -1){
 
1178
    perror("sigaction");
 
1179
    return EXIT_FAILURE;
 
1180
  }
 
1181
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1182
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1183
    if(ret == -1){
 
1184
      perror("sigaction");
 
1185
      exitcode = EXIT_FAILURE;
 
1186
      goto end;
 
1187
    }
 
1188
  }
 
1189
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1190
  if(ret == -1){
 
1191
    perror("sigaction");
 
1192
    return EXIT_FAILURE;
 
1193
  }
 
1194
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1195
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1196
    if(ret == -1){
 
1197
      perror("sigaction");
 
1198
      exitcode = EXIT_FAILURE;
 
1199
      goto end;
 
1200
    }
 
1201
  }
 
1202
  
1006
1203
  /* If the interface is down, bring it up */
1007
1204
  if(interface[0] != '\0'){
 
1205
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1206
    if(if_index == 0){
 
1207
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1208
      exitcode = EXIT_FAILURE;
 
1209
      goto end;
 
1210
    }
 
1211
    
 
1212
    if(quit_now){
 
1213
      goto end;
 
1214
    }
 
1215
    
 
1216
    /* Re-raise priviliges */
 
1217
    errno = 0;
 
1218
    ret = seteuid(0);
 
1219
    if(ret == -1){
 
1220
      perror("seteuid");
 
1221
    }
 
1222
    
1008
1223
#ifdef __linux__
1009
1224
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1010
1225
       messages to mess up the prompt */
1014
1229
      restore_loglevel = false;
1015
1230
      perror("klogctl");
1016
1231
    }
1017
 
#endif
 
1232
#endif  /* __linux__ */
1018
1233
    
1019
1234
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1020
1235
    if(sd < 0){
1027
1242
          perror("klogctl");
1028
1243
        }
1029
1244
      }
1030
 
#endif
 
1245
#endif  /* __linux__ */
 
1246
      /* Lower privileges */
 
1247
      errno = 0;
 
1248
      ret = seteuid(uid);
 
1249
      if(ret == -1){
 
1250
        perror("seteuid");
 
1251
      }
1031
1252
      goto end;
1032
1253
    }
1033
1254
    strcpy(network.ifr_name, interface);
1041
1262
          perror("klogctl");
1042
1263
        }
1043
1264
      }
1044
 
#endif
 
1265
#endif  /* __linux__ */
1045
1266
      exitcode = EXIT_FAILURE;
 
1267
      /* Lower privileges */
 
1268
      errno = 0;
 
1269
      ret = seteuid(uid);
 
1270
      if(ret == -1){
 
1271
        perror("seteuid");
 
1272
      }
1046
1273
      goto end;
1047
1274
    }
1048
1275
    if((network.ifr_flags & IFF_UP) == 0){
1049
1276
      network.ifr_flags |= IFF_UP;
 
1277
      take_down_interface = true;
1050
1278
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1051
1279
      if(ret == -1){
 
1280
        take_down_interface = false;
1052
1281
        perror("ioctl SIOCSIFFLAGS");
1053
1282
        exitcode = EXIT_FAILURE;
1054
1283
#ifdef __linux__
1058
1287
            perror("klogctl");
1059
1288
          }
1060
1289
        }
1061
 
#endif
 
1290
#endif  /* __linux__ */
 
1291
        /* Lower privileges */
 
1292
        errno = 0;
 
1293
        ret = seteuid(uid);
 
1294
        if(ret == -1){
 
1295
          perror("seteuid");
 
1296
        }
1062
1297
        goto end;
1063
1298
      }
1064
1299
    }
1076
1311
        perror("nanosleep");
1077
1312
      }
1078
1313
    }
1079
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1080
 
    if(ret == -1){
1081
 
      perror("close");
 
1314
    if(not take_down_interface){
 
1315
      /* We won't need the socket anymore */
 
1316
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1317
      if(ret == -1){
 
1318
        perror("close");
 
1319
      }
1082
1320
    }
1083
1321
#ifdef __linux__
1084
1322
    if(restore_loglevel){
1088
1326
        perror("klogctl");
1089
1327
      }
1090
1328
    }
1091
 
#endif
1092
 
  }
1093
 
  
1094
 
  uid = getuid();
1095
 
  gid = getgid();
1096
 
  
1097
 
  errno = 0;
1098
 
  setgid(gid);
1099
 
  if(ret == -1){
1100
 
    perror("setgid");
1101
 
  }
1102
 
  
1103
 
  ret = setuid(uid);
1104
 
  if(ret == -1){
1105
 
    perror("setuid");
 
1329
#endif  /* __linux__ */
 
1330
    /* Lower privileges */
 
1331
    errno = 0;
 
1332
    if(take_down_interface){
 
1333
      /* Lower privileges */
 
1334
      ret = seteuid(uid);
 
1335
      if(ret == -1){
 
1336
        perror("seteuid");
 
1337
      }
 
1338
    } else {
 
1339
      /* Lower privileges permanently */
 
1340
      ret = setuid(uid);
 
1341
      if(ret == -1){
 
1342
        perror("setuid");
 
1343
      }
 
1344
    }
 
1345
  }
 
1346
  
 
1347
  if(quit_now){
 
1348
    goto end;
1106
1349
  }
1107
1350
  
1108
1351
  ret = init_gnutls_global(pubkey, seckey);
1114
1357
    gnutls_initialized = true;
1115
1358
  }
1116
1359
  
 
1360
  if(quit_now){
 
1361
    goto end;
 
1362
  }
 
1363
  
 
1364
  tempdir_created = true;
1117
1365
  if(mkdtemp(tempdir) == NULL){
 
1366
    tempdir_created = false;
1118
1367
    perror("mkdtemp");
1119
1368
    goto end;
1120
1369
  }
1121
 
  tempdir_created = true;
 
1370
  
 
1371
  if(quit_now){
 
1372
    goto end;
 
1373
  }
1122
1374
  
1123
1375
  if(not init_gpgme(pubkey, seckey, tempdir)){
1124
1376
    fprintf(stderr, "init_gpgme failed\n");
1128
1380
    gpgme_initialized = true;
1129
1381
  }
1130
1382
  
1131
 
  if(interface[0] != '\0'){
1132
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1133
 
    if(if_index == 0){
1134
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1135
 
      exitcode = EXIT_FAILURE;
1136
 
      goto end;
1137
 
    }
 
1383
  if(quit_now){
 
1384
    goto end;
1138
1385
  }
1139
1386
  
1140
1387
  if(connect_to != NULL){
1146
1393
      exitcode = EXIT_FAILURE;
1147
1394
      goto end;
1148
1395
    }
 
1396
    
 
1397
    if(quit_now){
 
1398
      goto end;
 
1399
    }
 
1400
    
1149
1401
    uint16_t port;
1150
 
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1151
 
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
1152
 
       or address[numchars+1] != '\0'){
 
1402
    errno = 0;
 
1403
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1404
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1405
       or tmpmax != (uint16_t)tmpmax){
1153
1406
      fprintf(stderr, "Bad port number\n");
1154
1407
      exitcode = EXIT_FAILURE;
1155
1408
      goto end;
1156
1409
    }
 
1410
  
 
1411
    if(quit_now){
 
1412
      goto end;
 
1413
    }
 
1414
    
1157
1415
    port = (uint16_t)tmpmax;
1158
1416
    *address = '\0';
1159
1417
    address = connect_to;
1164
1422
    } else {
1165
1423
      af = AF_INET;
1166
1424
    }
 
1425
    
 
1426
    if(quit_now){
 
1427
      goto end;
 
1428
    }
 
1429
    
1167
1430
    ret = start_mandos_communication(address, port, if_index, af);
1168
1431
    if(ret < 0){
1169
1432
      exitcode = EXIT_FAILURE;
1173
1436
    goto end;
1174
1437
  }
1175
1438
  
1176
 
  if(not debug){
1177
 
    avahi_set_log_function(empty_log);
1178
 
  }
1179
 
  
1180
 
  /* Initialize the pseudo-RNG for Avahi */
1181
 
  srand((unsigned int) time(NULL));
1182
 
  
1183
 
  /* Allocate main Avahi loop object */
1184
 
  mc.simple_poll = avahi_simple_poll_new();
1185
 
  if(mc.simple_poll == NULL){
1186
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1187
 
    exitcode = EXIT_FAILURE;
 
1439
  if(quit_now){
1188
1440
    goto end;
1189
1441
  }
1190
1442
  
1214
1466
    goto end;
1215
1467
  }
1216
1468
  
 
1469
  if(quit_now){
 
1470
    goto end;
 
1471
  }
 
1472
  
1217
1473
  /* Create the Avahi service browser */
1218
1474
  sb = avahi_s_service_browser_new(mc.server, if_index,
1219
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1475
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1220
1476
                                   NULL, 0, browse_callback, NULL);
1221
1477
  if(sb == NULL){
1222
1478
    fprintf(stderr, "Failed to create service browser: %s\n",
1225
1481
    goto end;
1226
1482
  }
1227
1483
  
1228
 
  sigemptyset(&sigterm_action.sa_mask);
1229
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1230
 
  if(ret == -1){
1231
 
    perror("sigaddset");
1232
 
    exitcode = EXIT_FAILURE;
 
1484
  if(quit_now){
1233
1485
    goto end;
1234
1486
  }
1235
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1236
 
  if(ret == -1){
1237
 
    perror("sigaction");
1238
 
    exitcode = EXIT_FAILURE;
1239
 
    goto end;
1240
 
  }  
1241
1487
  
1242
1488
  /* Run the main loop */
1243
1489
  
1273
1519
    gpgme_release(mc.ctx);
1274
1520
  }
1275
1521
  
 
1522
  /* Take down the network interface */
 
1523
  if(take_down_interface){
 
1524
    /* Re-raise priviliges */
 
1525
    errno = 0;
 
1526
    ret = seteuid(0);
 
1527
    if(ret == -1){
 
1528
      perror("seteuid");
 
1529
    }
 
1530
    if(geteuid() == 0){
 
1531
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1532
      if(ret == -1){
 
1533
        perror("ioctl SIOCGIFFLAGS");
 
1534
      } else if(network.ifr_flags & IFF_UP) {
 
1535
        network.ifr_flags &= ~IFF_UP; /* clear flag */
 
1536
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1537
        if(ret == -1){
 
1538
          perror("ioctl SIOCSIFFLAGS");
 
1539
        }
 
1540
      }
 
1541
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1542
      if(ret == -1){
 
1543
        perror("close");
 
1544
      }
 
1545
      /* Lower privileges permanently */
 
1546
      errno = 0;
 
1547
      ret = setuid(uid);
 
1548
      if(ret == -1){
 
1549
        perror("setuid");
 
1550
      }
 
1551
    }
 
1552
  }
 
1553
  
1276
1554
  /* Removes the temp directory used by GPGME */
1277
1555
  if(tempdir_created){
1278
1556
    DIR *d;
1317
1595
    }
1318
1596
  }
1319
1597
  
 
1598
  if(quit_now){
 
1599
    sigemptyset(&old_sigterm_action.sa_mask);
 
1600
    old_sigterm_action.sa_handler = SIG_DFL;
 
1601
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
 
1602
    if(ret == -1){
 
1603
      perror("sigaction");
 
1604
    }
 
1605
    raise(signal_received);
 
1606
  }
 
1607
  
1320
1608
  return exitcode;
1321
1609
}