/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-09-17 01:21:27 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090917012127-4kwzquwuvudwucuv
* debian/control (Standards-Version): Updated to "2.8.3".

* mandos-client.conf.xml (OPTIONS/timeout): Add that a successful
                                            client request will also
                                            reset the timeout.
* mandos.xml (CHECKING): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
43
43
                                   stdout, ferror(), remove() */
44
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
47
                                   srand(), strtof() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
49
#include <string.h>             /* memset(), strcmp(), strlen(),
50
50
                                   strerror(), asprintf(), strcpy() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
65
#include <errno.h>              /* perror(), errno */
 
66
#include <time.h>               /* nanosleep(), time() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
70
69
                                   if_nametoindex(), IF_NAMESIZE */
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
75
                                   setgid() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
83
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
84
83
                                   sigaction(), SIGTERM, sig_atomic_t,
85
84
                                   raise() */
86
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
85
 
89
86
#ifdef __linux__
90
87
#include <sys/klog.h>           /* klogctl() */
127
124
bool debug = false;
128
125
static const char mandos_protocol_version[] = "1";
129
126
const char *argp_program_version = "mandos-client " VERSION;
130
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
 
static const char sys_class_net[] = "/sys/class/net";
132
 
char *connect_to = NULL;
133
 
 
134
 
/* Doubly linked list that need to be circularly linked when used */
135
 
typedef struct server{
136
 
  const char *ip;
137
 
  uint16_t port;
138
 
  AvahiIfIndex if_index;
139
 
  int af;
140
 
  struct timespec last_seen;
141
 
  struct server *next;
142
 
  struct server *prev;
143
 
} server;
 
127
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
144
128
 
145
129
/* Used for passing in values through the Avahi callback functions */
146
130
typedef struct {
151
135
  gnutls_dh_params_t dh_params;
152
136
  const char *priority;
153
137
  gpgme_ctx_t ctx;
154
 
  server *current_server;
155
138
} mandos_context;
156
139
 
157
140
/* global context so signal handler can reach it*/
158
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
159
142
                      .dh_bits = 1024, .priority = "SECURE256"
160
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
161
 
                      .current_server = NULL };
162
 
 
163
 
sig_atomic_t quit_now = 0;
164
 
int signal_received = 0;
165
 
 
166
 
/* Function to use when printing errors */
167
 
void perror_plus(const char *print_text){
168
 
  fprintf(stderr, "Mandos plugin %s: ",
169
 
          program_invocation_short_name);
170
 
  perror(print_text);
171
 
}
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
172
144
 
173
145
/*
174
146
 * Make additional room in "buffer" for at least BUFFER_SIZE more
187
159
  return buffer_capacity;
188
160
}
189
161
 
190
 
/* Add server to set of servers to retry periodically */
191
 
int add_server(const char *ip, uint16_t port,
192
 
                 AvahiIfIndex if_index,
193
 
                 int af){
194
 
  int ret;
195
 
  server *new_server = malloc(sizeof(server));
196
 
  if(new_server == NULL){
197
 
    perror_plus("malloc");
198
 
    return -1;
199
 
  }
200
 
  *new_server = (server){ .ip = strdup(ip),
201
 
                         .port = port,
202
 
                         .if_index = if_index,
203
 
                         .af = af };
204
 
  if(new_server->ip == NULL){
205
 
    perror_plus("strdup");
206
 
    return -1;
207
 
  }
208
 
  /* Special case of first server */
209
 
  if (mc.current_server == NULL){
210
 
    new_server->next = new_server;
211
 
    new_server->prev = new_server;
212
 
    mc.current_server = new_server;
213
 
  /* Place the new server last in the list */
214
 
  } else {
215
 
    new_server->next = mc.current_server;
216
 
    new_server->prev = mc.current_server->prev;
217
 
    new_server->prev->next = new_server;
218
 
    mc.current_server->prev = new_server;
219
 
  }
220
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
221
 
  if(ret == -1){
222
 
    perror_plus("clock_gettime");
223
 
    return -1;
224
 
  }
225
 
  return 0;
226
 
}
227
 
 
228
162
/* 
229
163
 * Initialize GPGME.
230
164
 */
244
178
    
245
179
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
246
180
    if(fd == -1){
247
 
      perror_plus("open");
 
181
      perror("open");
248
182
      return false;
249
183
    }
250
184
    
264
198
    
265
199
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
266
200
    if(ret == -1){
267
 
      perror_plus("close");
 
201
      perror("close");
268
202
    }
269
203
    gpgme_data_release(pgp_data);
270
204
    return true;
283
217
    return false;
284
218
  }
285
219
  
286
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
220
    /* Set GPGME home directory for the OpenPGP engine only */
287
221
  rc = gpgme_get_engine_info(&engine_info);
288
222
  if(rc != GPG_ERR_NO_ERROR){
289
223
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
395
329
  
396
330
  /* Seek back to the beginning of the GPGME plaintext data buffer */
397
331
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
398
 
    perror_plus("gpgme_data_seek");
 
332
    perror("gpgme_data_seek");
399
333
    plaintext_length = -1;
400
334
    goto decrypt_end;
401
335
  }
406
340
                                      (size_t)plaintext_length,
407
341
                                      plaintext_capacity);
408
342
    if(plaintext_capacity == 0){
409
 
        perror_plus("incbuffer");
 
343
        perror("incbuffer");
410
344
        plaintext_length = -1;
411
345
        goto decrypt_end;
412
346
    }
419
353
      break;
420
354
    }
421
355
    if(ret < 0){
422
 
      perror_plus("gpgme_data_read");
 
356
      perror("gpgme_data_read");
423
357
      plaintext_length = -1;
424
358
      goto decrypt_end;
425
359
    }
482
416
  }
483
417
  
484
418
  /* OpenPGP credentials */
485
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
419
  gnutls_certificate_allocate_credentials(&mc.cred);
486
420
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
421
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
422
                                                    from
 
423
                                                    -Wunreachable-code
 
424
                                                 */
488
425
            safer_gnutls_strerror(ret));
489
426
    gnutls_global_deinit();
490
427
    return -1;
539
476
  /* GnuTLS session creation */
540
477
  do {
541
478
    ret = gnutls_init(session, GNUTLS_SERVER);
542
 
    if(quit_now){
543
 
      return -1;
544
 
    }
545
479
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
546
480
  if(ret != GNUTLS_E_SUCCESS){
547
481
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
552
486
    const char *err;
553
487
    do {
554
488
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
555
 
      if(quit_now){
556
 
        gnutls_deinit(*session);
557
 
        return -1;
558
 
      }
559
489
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
560
490
    if(ret != GNUTLS_E_SUCCESS){
561
491
      fprintf(stderr, "Syntax error at: %s\n", err);
569
499
  do {
570
500
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
571
501
                                 mc.cred);
572
 
    if(quit_now){
573
 
      gnutls_deinit(*session);
574
 
      return -1;
575
 
    }
576
502
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
577
503
  if(ret != GNUTLS_E_SUCCESS){
578
504
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
593
519
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
594
520
                      __attribute__((unused)) const char *txt){}
595
521
 
 
522
sig_atomic_t quit_now = 0;
 
523
int signal_received = 0;
 
524
 
596
525
/* Called when a Mandos server is found */
597
526
static int start_mandos_communication(const char *ip, uint16_t port,
598
527
                                      AvahiIfIndex if_index,
604
533
    struct sockaddr_in6 in6;
605
534
  } to;
606
535
  char *buffer = NULL;
607
 
  char *decrypted_buffer = NULL;
 
536
  char *decrypted_buffer;
608
537
  size_t buffer_length = 0;
609
538
  size_t buffer_capacity = 0;
610
539
  size_t written;
611
 
  int retval = -1;
 
540
  int retval = 0;
612
541
  gnutls_session_t session;
613
542
  int pf;                       /* Protocol family */
614
543
  
615
 
  errno = 0;
616
 
  
617
544
  if(quit_now){
618
 
    errno = EINTR;
619
545
    return -1;
620
546
  }
621
547
  
628
554
    break;
629
555
  default:
630
556
    fprintf(stderr, "Bad address family: %d\n", af);
631
 
    errno = EINVAL;
632
557
    return -1;
633
558
  }
634
559
  
644
569
  
645
570
  tcp_sd = socket(pf, SOCK_STREAM, 0);
646
571
  if(tcp_sd < 0){
647
 
    int e = errno;
648
 
    perror_plus("socket");
649
 
    errno = e;
 
572
    perror("socket");
 
573
    retval = -1;
650
574
    goto mandos_end;
651
575
  }
652
576
  
653
577
  if(quit_now){
654
 
    errno = EINTR;
655
578
    goto mandos_end;
656
579
  }
657
580
  
664
587
    ret = inet_pton(af, ip, &to.in.sin_addr);
665
588
  }
666
589
  if(ret < 0 ){
667
 
    int e = errno;
668
 
    perror_plus("inet_pton");
669
 
    errno = e;
 
590
    perror("inet_pton");
 
591
    retval = -1;
670
592
    goto mandos_end;
671
593
  }
672
594
  if(ret == 0){
673
 
    int e = errno;
674
595
    fprintf(stderr, "Bad address: %s\n", ip);
675
 
    errno = e;
 
596
    retval = -1;
676
597
    goto mandos_end;
677
598
  }
678
599
  if(af == AF_INET6){
686
607
      if(if_index == AVAHI_IF_UNSPEC){
687
608
        fprintf(stderr, "An IPv6 link-local address is incomplete"
688
609
                " without a network interface\n");
689
 
        errno = EINVAL;
 
610
        retval = -1;
690
611
        goto mandos_end;
691
612
      }
692
613
      /* Set the network interface number as scope */
699
620
  }
700
621
  
701
622
  if(quit_now){
702
 
    errno = EINTR;
703
623
    goto mandos_end;
704
624
  }
705
625
  
707
627
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
708
628
      char interface[IF_NAMESIZE];
709
629
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
 
        perror_plus("if_indextoname");
 
630
        perror("if_indextoname");
711
631
      } else {
712
632
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
713
633
                ip, interface, port);
727
647
                        sizeof(addrstr));
728
648
    }
729
649
    if(pcret == NULL){
730
 
      perror_plus("inet_ntop");
 
650
      perror("inet_ntop");
731
651
    } else {
732
652
      if(strcmp(addrstr, ip) != 0){
733
653
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
736
656
  }
737
657
  
738
658
  if(quit_now){
739
 
    errno = EINTR;
740
659
    goto mandos_end;
741
660
  }
742
661
  
746
665
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
747
666
  }
748
667
  if(ret < 0){
749
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
750
 
      int e = errno;
751
 
      perror_plus("connect");
752
 
      errno = e;
753
 
    }
 
668
    perror("connect");
 
669
    retval = -1;
754
670
    goto mandos_end;
755
671
  }
756
672
  
757
673
  if(quit_now){
758
 
    errno = EINTR;
759
674
    goto mandos_end;
760
675
  }
761
676
  
766
681
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
767
682
                                   out_size - written));
768
683
    if(ret == -1){
769
 
      int e = errno;
770
 
      perror_plus("write");
771
 
      errno = e;
 
684
      perror("write");
 
685
      retval = -1;
772
686
      goto mandos_end;
773
687
    }
774
688
    written += (size_t)ret;
784
698
    }
785
699
  
786
700
    if(quit_now){
787
 
      errno = EINTR;
788
701
      goto mandos_end;
789
702
    }
790
703
  }
794
707
  }
795
708
  
796
709
  if(quit_now){
797
 
    errno = EINTR;
798
710
    goto mandos_end;
799
711
  }
800
712
  
801
 
  /* Spurious warning from -Wint-to-pointer-cast */
802
713
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
803
714
  
804
715
  if(quit_now){
805
 
    errno = EINTR;
806
716
    goto mandos_end;
807
717
  }
808
718
  
809
719
  do {
810
720
    ret = gnutls_handshake(session);
811
721
    if(quit_now){
812
 
      errno = EINTR;
813
722
      goto mandos_end;
814
723
    }
815
724
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
819
728
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
820
729
      gnutls_perror(ret);
821
730
    }
822
 
    errno = EPROTO;
 
731
    retval = -1;
823
732
    goto mandos_end;
824
733
  }
825
734
  
833
742
  while(true){
834
743
    
835
744
    if(quit_now){
836
 
      errno = EINTR;
837
745
      goto mandos_end;
838
746
    }
839
747
    
840
748
    buffer_capacity = incbuffer(&buffer, buffer_length,
841
749
                                   buffer_capacity);
842
750
    if(buffer_capacity == 0){
843
 
      int e = errno;
844
 
      perror_plus("incbuffer");
845
 
      errno = e;
 
751
      perror("incbuffer");
 
752
      retval = -1;
846
753
      goto mandos_end;
847
754
    }
848
755
    
849
756
    if(quit_now){
850
 
      errno = EINTR;
851
757
      goto mandos_end;
852
758
    }
853
759
    
866
772
          ret = gnutls_handshake(session);
867
773
          
868
774
          if(quit_now){
869
 
            errno = EINTR;
870
775
            goto mandos_end;
871
776
          }
872
777
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
873
778
        if(ret < 0){
874
779
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
875
780
          gnutls_perror(ret);
876
 
          errno = EPROTO;
 
781
          retval = -1;
877
782
          goto mandos_end;
878
783
        }
879
784
        break;
880
785
      default:
881
786
        fprintf(stderr, "Unknown error while reading data from"
882
787
                " encrypted session with Mandos server\n");
 
788
        retval = -1;
883
789
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
884
 
        errno = EIO;
885
790
        goto mandos_end;
886
791
      }
887
792
    } else {
894
799
  }
895
800
  
896
801
  if(quit_now){
897
 
    errno = EINTR;
898
 
    goto mandos_end;
899
 
  }
900
 
  
901
 
  do {
902
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
903
 
    if(quit_now){
904
 
      errno = EINTR;
905
 
      goto mandos_end;
906
 
    }
907
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
802
    goto mandos_end;
 
803
  }
 
804
  
 
805
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
806
  
 
807
  if(quit_now){
 
808
    goto mandos_end;
 
809
  }
908
810
  
909
811
  if(buffer_length > 0){
910
812
    ssize_t decrypted_buffer_size;
916
818
      written = 0;
917
819
      while(written < (size_t) decrypted_buffer_size){
918
820
        if(quit_now){
919
 
          errno = EINTR;
920
821
          goto mandos_end;
921
822
        }
922
823
        
924
825
                          (size_t)decrypted_buffer_size - written,
925
826
                          stdout);
926
827
        if(ret == 0 and ferror(stdout)){
927
 
          int e = errno;
928
828
          if(debug){
929
829
            fprintf(stderr, "Error writing encrypted data: %s\n",
930
830
                    strerror(errno));
931
831
          }
932
 
          errno = e;
933
 
          goto mandos_end;
 
832
          retval = -1;
 
833
          break;
934
834
        }
935
835
        written += (size_t)ret;
936
836
      }
937
 
      retval = 0;
 
837
      free(decrypted_buffer);
 
838
    } else {
 
839
      retval = -1;
938
840
    }
 
841
  } else {
 
842
    retval = -1;
939
843
  }
940
844
  
941
845
  /* Shutdown procedure */
942
846
  
943
847
 mandos_end:
944
 
  {
945
 
    int e = errno;
946
 
    free(decrypted_buffer);
947
 
    free(buffer);
948
 
    if(tcp_sd >= 0){
949
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
950
 
    }
951
 
    if(ret == -1){
952
 
      if(e == 0){
953
 
        e = errno;
954
 
      }
955
 
      perror_plus("close");
956
 
    }
957
 
    gnutls_deinit(session);
958
 
    errno = e;
959
 
    if(quit_now){
960
 
      errno = EINTR;
961
 
      retval = -1;
962
 
    }
 
848
  free(buffer);
 
849
  if(tcp_sd >= 0){
 
850
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
851
  }
 
852
  if(ret == -1){
 
853
    perror("close");
 
854
  }
 
855
  gnutls_deinit(session);
 
856
  if(quit_now){
 
857
    retval = -1;
963
858
  }
964
859
  return retval;
965
860
}
1008
903
                                           avahi_proto_to_af(proto));
1009
904
      if(ret == 0){
1010
905
        avahi_simple_poll_quit(mc.simple_poll);
1011
 
      } else {
1012
 
        ret = add_server(ip, port, interface,
1013
 
                         avahi_proto_to_af(proto));
1014
906
      }
1015
907
    }
1016
908
  }
1070
962
  }
1071
963
}
1072
964
 
1073
 
/* Signal handler that stops main loop after SIGTERM */
 
965
/* stop main loop after sigterm has been called */
1074
966
static void handle_sigterm(int sig){
1075
967
  if(quit_now){
1076
968
    return;
1078
970
  quit_now = 1;
1079
971
  signal_received = sig;
1080
972
  int old_errno = errno;
1081
 
  /* set main loop to exit */
1082
973
  if(mc.simple_poll != NULL){
1083
974
    avahi_simple_poll_quit(mc.simple_poll);
1084
975
  }
1085
976
  errno = old_errno;
1086
977
}
1087
978
 
1088
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1089
 
  int ret;
1090
 
  
1091
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1092
 
  if(s < 0){
1093
 
    perror_plus("socket");
1094
 
    return false;
1095
 
  }
1096
 
  strcpy(ifr->ifr_name, ifname);
1097
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1098
 
  if(ret == -1){
1099
 
    if(debug){
1100
 
      perror_plus("ioctl SIOCGIFFLAGS");
1101
 
    }
1102
 
    return false;
1103
 
  }
1104
 
  return true;
1105
 
}
1106
 
 
1107
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1108
 
  
1109
 
  /* Reject the loopback device */
1110
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1111
 
    if(debug){
1112
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1113
 
              ifname);
1114
 
    }
1115
 
    return false;
1116
 
  }
1117
 
  /* Accept point-to-point devices only if connect_to is specified */
1118
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1119
 
    if(debug){
1120
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1121
 
              ifname);
1122
 
    }
1123
 
    return true;
1124
 
  }
1125
 
  /* Otherwise, reject non-broadcast-capable devices */
1126
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1127
 
    if(debug){
1128
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1129
 
              ifname);
1130
 
    }
1131
 
    return false;
1132
 
  }
1133
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1134
 
  if(ifr->ifr_flags & IFF_NOARP){
1135
 
    if(debug){
1136
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1137
 
    }
1138
 
    return false;
1139
 
  }
1140
 
  
1141
 
  /* Accept this device */
1142
 
  if(debug){
1143
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1144
 
  }
1145
 
  return true;
1146
 
}
1147
 
 
1148
 
/* 
1149
 
 * This function determines if a directory entry in /sys/class/net
1150
 
 * corresponds to an acceptable network device.
1151
 
 * (This function is passed to scandir(3) as a filter function.)
1152
 
 */
1153
 
int good_interface(const struct dirent *if_entry){
1154
 
  int ret;
1155
 
  if(if_entry->d_name[0] == '.'){
1156
 
    return 0;
1157
 
  }
1158
 
  struct ifreq ifr;
1159
 
 
1160
 
  if(not get_flags(if_entry->d_name, &ifr)){
1161
 
    return 0;
1162
 
  }
1163
 
  
1164
 
  if(not good_flags(if_entry->d_name, &ifr)){
1165
 
    return 0;
1166
 
  }
1167
 
  return 1;
1168
 
}
1169
 
 
1170
 
int notdotentries(const struct dirent *direntry){
1171
 
  /* Skip "." and ".." */
1172
 
  if(direntry->d_name[0] == '.'
1173
 
     and (direntry->d_name[1] == '\0'
1174
 
          or (direntry->d_name[1] == '.'
1175
 
              and direntry->d_name[2] == '\0'))){
1176
 
    return 0;
1177
 
  }
1178
 
  return 1;
1179
 
}
1180
 
 
1181
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1182
 
  int ret;
1183
 
  struct timespec now;
1184
 
  struct timespec waited_time;
1185
 
  intmax_t block_time;
1186
 
  
1187
 
  while(true){
1188
 
    if(mc.current_server == NULL){
1189
 
      if (debug){
1190
 
        fprintf(stderr,
1191
 
                "Wait until first server is found. No timeout!\n");
1192
 
      }
1193
 
      ret = avahi_simple_poll_iterate(s, -1);
1194
 
    } else {
1195
 
      if (debug){
1196
 
        fprintf(stderr, "Check current_server if we should run it,"
1197
 
                " or wait\n");
1198
 
      }
1199
 
      /* the current time */
1200
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1201
 
      if(ret == -1){
1202
 
        perror_plus("clock_gettime");
1203
 
        return -1;
1204
 
      }
1205
 
      /* Calculating in ms how long time between now and server
1206
 
         who we visted longest time ago. Now - last seen.  */
1207
 
      waited_time.tv_sec = (now.tv_sec
1208
 
                            - mc.current_server->last_seen.tv_sec);
1209
 
      waited_time.tv_nsec = (now.tv_nsec
1210
 
                             - mc.current_server->last_seen.tv_nsec);
1211
 
      /* total time is 10s/10,000ms.
1212
 
         Converting to s from ms by dividing by 1,000,
1213
 
         and ns to ms by dividing by 1,000,000. */
1214
 
      block_time = ((retry_interval
1215
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1216
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1217
 
      
1218
 
      if (debug){
1219
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1220
 
      }
1221
 
      
1222
 
      if(block_time <= 0){
1223
 
        ret = start_mandos_communication(mc.current_server->ip,
1224
 
                                         mc.current_server->port,
1225
 
                                         mc.current_server->if_index,
1226
 
                                         mc.current_server->af);
1227
 
        if(ret == 0){
1228
 
          avahi_simple_poll_quit(mc.simple_poll);
1229
 
          return 0;
1230
 
        }
1231
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1232
 
                            &mc.current_server->last_seen);
1233
 
        if(ret == -1){
1234
 
          perror_plus("clock_gettime");
1235
 
          return -1;
1236
 
        }
1237
 
        mc.current_server = mc.current_server->next;
1238
 
        block_time = 0;         /* Call avahi to find new Mandos
1239
 
                                   servers, but don't block */
1240
 
      }
1241
 
      
1242
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1243
 
    }
1244
 
    if(ret != 0){
1245
 
      if (ret > 0 or errno != EINTR) {
1246
 
        return (ret != 1) ? ret : 0;
1247
 
      }
1248
 
    }
1249
 
  }
1250
 
}
1251
 
 
1252
979
int main(int argc, char *argv[]){
1253
980
  AvahiSServiceBrowser *sb = NULL;
1254
981
  int error;
1256
983
  intmax_t tmpmax;
1257
984
  char *tmp;
1258
985
  int exitcode = EXIT_SUCCESS;
1259
 
  const char *interface = "";
 
986
  const char *interface = "eth0";
1260
987
  struct ifreq network;
1261
988
  int sd = -1;
1262
989
  bool take_down_interface = false;
1263
990
  uid_t uid;
1264
991
  gid_t gid;
 
992
  char *connect_to = NULL;
1265
993
  char tempdir[] = "/tmp/mandosXXXXXX";
1266
994
  bool tempdir_created = false;
1267
995
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1271
999
  bool gnutls_initialized = false;
1272
1000
  bool gpgme_initialized = false;
1273
1001
  float delay = 2.5f;
1274
 
  double retry_interval = 10; /* 10s between trying a server and
1275
 
                                 retrying the same server again */
1276
1002
  
1277
1003
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1278
1004
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1284
1010
  errno = 0;
1285
1011
  ret = setgid(gid);
1286
1012
  if(ret == -1){
1287
 
    perror_plus("setgid");
 
1013
    perror("setgid");
1288
1014
  }
1289
1015
  
1290
1016
  /* Lower user privileges (temporarily) */
1291
1017
  errno = 0;
1292
1018
  ret = seteuid(uid);
1293
1019
  if(ret == -1){
1294
 
    perror_plus("seteuid");
 
1020
    perror("seteuid");
1295
1021
  }
1296
1022
  
1297
1023
  if(quit_now){
1332
1058
        .arg = "SECONDS",
1333
1059
        .doc = "Maximum delay to wait for interface startup",
1334
1060
        .group = 2 },
1335
 
      { .name = "retry", .key = 132,
1336
 
        .arg = "SECONDS",
1337
 
        .doc = "Retry interval used when denied by the mandos server",
1338
 
        .group = 2 },
1339
 
      /*
1340
 
       * These reproduce what we would get without ARGP_NO_HELP
1341
 
       */
1342
 
      { .name = "help", .key = '?',
1343
 
        .doc = "Give this help list", .group = -1 },
1344
 
      { .name = "usage", .key = -3,
1345
 
        .doc = "Give a short usage message", .group = -1 },
1346
 
      { .name = "version", .key = 'V',
1347
 
        .doc = "Print program version", .group = -1 },
1348
1061
      { .name = NULL }
1349
1062
    };
1350
1063
    
1351
1064
    error_t parse_opt(int key, char *arg,
1352
1065
                      struct argp_state *state){
1353
 
      errno = 0;
1354
1066
      switch(key){
1355
1067
      case 128:                 /* --debug */
1356
1068
        debug = true;
1372
1084
        tmpmax = strtoimax(arg, &tmp, 10);
1373
1085
        if(errno != 0 or tmp == arg or *tmp != '\0'
1374
1086
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1375
 
          argp_error(state, "Bad number of DH bits");
 
1087
          fprintf(stderr, "Bad number of DH bits\n");
 
1088
          exit(EXIT_FAILURE);
1376
1089
        }
1377
1090
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1378
1091
        break;
1383
1096
        errno = 0;
1384
1097
        delay = strtof(arg, &tmp);
1385
1098
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1386
 
          argp_error(state, "Bad delay");
1387
 
        }
1388
 
      case 132:                 /* --retry */
1389
 
        errno = 0;
1390
 
        retry_interval = strtod(arg, &tmp);
1391
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1392
 
           or (retry_interval * 1000) > INT_MAX
1393
 
           or retry_interval < 0){
1394
 
          argp_error(state, "Bad retry interval");
 
1099
          fprintf(stderr, "Bad delay\n");
 
1100
          exit(EXIT_FAILURE);
1395
1101
        }
1396
1102
        break;
1397
 
        /*
1398
 
         * These reproduce what we would get without ARGP_NO_HELP
1399
 
         */
1400
 
      case '?':                 /* --help */
1401
 
        argp_state_help(state, state->out_stream,
1402
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1403
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1404
 
      case -3:                  /* --usage */
1405
 
        argp_state_help(state, state->out_stream,
1406
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1407
 
      case 'V':                 /* --version */
1408
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1409
 
        exit(argp_err_exit_status);
 
1103
      case ARGP_KEY_ARG:
 
1104
        argp_usage(state);
 
1105
      case ARGP_KEY_END:
1410
1106
        break;
1411
1107
      default:
1412
1108
        return ARGP_ERR_UNKNOWN;
1413
1109
      }
1414
 
      return errno;
 
1110
      return 0;
1415
1111
    }
1416
1112
    
1417
1113
    struct argp argp = { .options = options, .parser = parse_opt,
1418
1114
                         .args_doc = "",
1419
1115
                         .doc = "Mandos client -- Get and decrypt"
1420
1116
                         " passwords from a Mandos server" };
1421
 
    ret = argp_parse(&argp, argc, argv,
1422
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1423
 
    switch(ret){
1424
 
    case 0:
1425
 
      break;
1426
 
    case ENOMEM:
1427
 
    default:
1428
 
      errno = ret;
1429
 
      perror_plus("argp_parse");
1430
 
      exitcode = EX_OSERR;
1431
 
      goto end;
1432
 
    case EINVAL:
1433
 
      exitcode = EX_USAGE;
1434
 
      goto end;
1435
 
    }
1436
 
  }
1437
 
    
1438
 
  {
1439
 
    /* Work around Debian bug #633582:
1440
 
       <http://bugs.debian.org/633582> */
1441
 
    struct stat st;
1442
 
    
1443
 
    /* Re-raise priviliges */
1444
 
    errno = 0;
1445
 
    ret = seteuid(0);
1446
 
    if(ret == -1){
1447
 
      perror_plus("seteuid");
1448
 
    }
1449
 
    
1450
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1451
 
      int seckey_fd = open(seckey, O_RDONLY);
1452
 
      if(seckey_fd == -1){
1453
 
        perror_plus("open");
1454
 
      } else {
1455
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1456
 
        if(ret == -1){
1457
 
          perror_plus("fstat");
1458
 
        } else {
1459
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1460
 
            ret = fchown(seckey_fd, uid, gid);
1461
 
            if(ret == -1){
1462
 
              perror_plus("fchown");
1463
 
            }
1464
 
          }
1465
 
        }
1466
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1467
 
      }
1468
 
    }
1469
 
    
1470
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1471
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1472
 
      if(pubkey_fd == -1){
1473
 
        perror_plus("open");
1474
 
      } else {
1475
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1476
 
        if(ret == -1){
1477
 
          perror_plus("fstat");
1478
 
        } else {
1479
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1480
 
            ret = fchown(pubkey_fd, uid, gid);
1481
 
            if(ret == -1){
1482
 
              perror_plus("fchown");
1483
 
            }
1484
 
          }
1485
 
        }
1486
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1487
 
      }
1488
 
    }
1489
 
    
1490
 
    /* Lower privileges */
1491
 
    errno = 0;
1492
 
    ret = seteuid(uid);
1493
 
    if(ret == -1){
1494
 
      perror_plus("seteuid");
 
1117
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1118
    if(ret == ARGP_ERR_UNKNOWN){
 
1119
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1120
      exitcode = EXIT_FAILURE;
 
1121
      goto end;
1495
1122
    }
1496
1123
  }
1497
1124
  
1498
1125
  if(not debug){
1499
1126
    avahi_set_log_function(empty_log);
1500
1127
  }
1501
 
 
1502
 
  if(interface[0] == '\0'){
1503
 
    struct dirent **direntries;
1504
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1505
 
                  alphasort);
1506
 
    if(ret >= 1){
1507
 
      /* Pick the first good interface */
1508
 
      interface = strdup(direntries[0]->d_name);
1509
 
      if(debug){
1510
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1511
 
      }
1512
 
      if(interface == NULL){
1513
 
        perror_plus("malloc");
1514
 
        free(direntries);
1515
 
        exitcode = EXIT_FAILURE;
1516
 
        goto end;
1517
 
      }
1518
 
      free(direntries);
1519
 
    } else {
1520
 
      free(direntries);
1521
 
      fprintf(stderr, "Could not find a network interface\n");
1522
 
      exitcode = EXIT_FAILURE;
1523
 
      goto end;
1524
 
    }
1525
 
  }
1526
1128
  
1527
1129
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1528
1130
     from the signal handler */
1531
1133
  mc.simple_poll = avahi_simple_poll_new();
1532
1134
  if(mc.simple_poll == NULL){
1533
1135
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1534
 
    exitcode = EX_UNAVAILABLE;
 
1136
    exitcode = EXIT_FAILURE;
1535
1137
    goto end;
1536
1138
  }
1537
1139
  
1538
1140
  sigemptyset(&sigterm_action.sa_mask);
1539
1141
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1540
1142
  if(ret == -1){
1541
 
    perror_plus("sigaddset");
1542
 
    exitcode = EX_OSERR;
 
1143
    perror("sigaddset");
 
1144
    exitcode = EXIT_FAILURE;
1543
1145
    goto end;
1544
1146
  }
1545
1147
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1546
1148
  if(ret == -1){
1547
 
    perror_plus("sigaddset");
1548
 
    exitcode = EX_OSERR;
 
1149
    perror("sigaddset");
 
1150
    exitcode = EXIT_FAILURE;
1549
1151
    goto end;
1550
1152
  }
1551
1153
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1552
1154
  if(ret == -1){
1553
 
    perror_plus("sigaddset");
1554
 
    exitcode = EX_OSERR;
 
1155
    perror("sigaddset");
 
1156
    exitcode = EXIT_FAILURE;
1555
1157
    goto end;
1556
1158
  }
1557
1159
  /* Need to check if the handler is SIG_IGN before handling:
1560
1162
  */
1561
1163
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1562
1164
  if(ret == -1){
1563
 
    perror_plus("sigaction");
1564
 
    return EX_OSERR;
 
1165
    perror("sigaction");
 
1166
    return EXIT_FAILURE;
1565
1167
  }
1566
1168
  if(old_sigterm_action.sa_handler != SIG_IGN){
1567
1169
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1568
1170
    if(ret == -1){
1569
 
      perror_plus("sigaction");
1570
 
      exitcode = EX_OSERR;
 
1171
      perror("sigaction");
 
1172
      exitcode = EXIT_FAILURE;
1571
1173
      goto end;
1572
1174
    }
1573
1175
  }
1574
1176
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1575
1177
  if(ret == -1){
1576
 
    perror_plus("sigaction");
1577
 
    return EX_OSERR;
 
1178
    perror("sigaction");
 
1179
    return EXIT_FAILURE;
1578
1180
  }
1579
1181
  if(old_sigterm_action.sa_handler != SIG_IGN){
1580
1182
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1581
1183
    if(ret == -1){
1582
 
      perror_plus("sigaction");
1583
 
      exitcode = EX_OSERR;
 
1184
      perror("sigaction");
 
1185
      exitcode = EXIT_FAILURE;
1584
1186
      goto end;
1585
1187
    }
1586
1188
  }
1587
1189
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1588
1190
  if(ret == -1){
1589
 
    perror_plus("sigaction");
1590
 
    return EX_OSERR;
 
1191
    perror("sigaction");
 
1192
    return EXIT_FAILURE;
1591
1193
  }
1592
1194
  if(old_sigterm_action.sa_handler != SIG_IGN){
1593
1195
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1594
1196
    if(ret == -1){
1595
 
      perror_plus("sigaction");
1596
 
      exitcode = EX_OSERR;
 
1197
      perror("sigaction");
 
1198
      exitcode = EXIT_FAILURE;
1597
1199
      goto end;
1598
1200
    }
1599
1201
  }
1600
1202
  
1601
1203
  /* If the interface is down, bring it up */
1602
 
  if(strcmp(interface, "none") != 0){
 
1204
  if(interface[0] != '\0'){
1603
1205
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1604
1206
    if(if_index == 0){
1605
1207
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1606
 
      exitcode = EX_UNAVAILABLE;
 
1208
      exitcode = EXIT_FAILURE;
1607
1209
      goto end;
1608
1210
    }
1609
1211
    
1615
1217
    errno = 0;
1616
1218
    ret = seteuid(0);
1617
1219
    if(ret == -1){
1618
 
      perror_plus("seteuid");
 
1220
      perror("seteuid");
1619
1221
    }
1620
1222
    
1621
1223
#ifdef __linux__
1622
1224
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1623
 
       messages about the network interface to mess up the prompt */
 
1225
       messages to mess up the prompt */
1624
1226
    ret = klogctl(8, NULL, 5);
1625
1227
    bool restore_loglevel = true;
1626
1228
    if(ret == -1){
1627
1229
      restore_loglevel = false;
1628
 
      perror_plus("klogctl");
 
1230
      perror("klogctl");
1629
1231
    }
1630
1232
#endif  /* __linux__ */
1631
1233
    
1632
1234
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1633
1235
    if(sd < 0){
1634
 
      perror_plus("socket");
1635
 
      exitcode = EX_OSERR;
 
1236
      perror("socket");
 
1237
      exitcode = EXIT_FAILURE;
1636
1238
#ifdef __linux__
1637
1239
      if(restore_loglevel){
1638
1240
        ret = klogctl(7, NULL, 0);
1639
1241
        if(ret == -1){
1640
 
          perror_plus("klogctl");
 
1242
          perror("klogctl");
1641
1243
        }
1642
1244
      }
1643
1245
#endif  /* __linux__ */
1645
1247
      errno = 0;
1646
1248
      ret = seteuid(uid);
1647
1249
      if(ret == -1){
1648
 
        perror_plus("seteuid");
 
1250
        perror("seteuid");
1649
1251
      }
1650
1252
      goto end;
1651
1253
    }
1652
1254
    strcpy(network.ifr_name, interface);
1653
1255
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1654
1256
    if(ret == -1){
1655
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1257
      perror("ioctl SIOCGIFFLAGS");
1656
1258
#ifdef __linux__
1657
1259
      if(restore_loglevel){
1658
1260
        ret = klogctl(7, NULL, 0);
1659
1261
        if(ret == -1){
1660
 
          perror_plus("klogctl");
 
1262
          perror("klogctl");
1661
1263
        }
1662
1264
      }
1663
1265
#endif  /* __linux__ */
1664
 
      exitcode = EX_OSERR;
 
1266
      exitcode = EXIT_FAILURE;
1665
1267
      /* Lower privileges */
1666
1268
      errno = 0;
1667
1269
      ret = seteuid(uid);
1668
1270
      if(ret == -1){
1669
 
        perror_plus("seteuid");
 
1271
        perror("seteuid");
1670
1272
      }
1671
1273
      goto end;
1672
1274
    }
1676
1278
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1677
1279
      if(ret == -1){
1678
1280
        take_down_interface = false;
1679
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1680
 
        exitcode = EX_OSERR;
 
1281
        perror("ioctl SIOCSIFFLAGS");
 
1282
        exitcode = EXIT_FAILURE;
1681
1283
#ifdef __linux__
1682
1284
        if(restore_loglevel){
1683
1285
          ret = klogctl(7, NULL, 0);
1684
1286
          if(ret == -1){
1685
 
            perror_plus("klogctl");
 
1287
            perror("klogctl");
1686
1288
          }
1687
1289
        }
1688
1290
#endif  /* __linux__ */
1690
1292
        errno = 0;
1691
1293
        ret = seteuid(uid);
1692
1294
        if(ret == -1){
1693
 
          perror_plus("seteuid");
 
1295
          perror("seteuid");
1694
1296
        }
1695
1297
        goto end;
1696
1298
      }
1697
1299
    }
1698
 
    /* Sleep checking until interface is running.
1699
 
       Check every 0.25s, up to total time of delay */
 
1300
    /* sleep checking until interface is running */
1700
1301
    for(int i=0; i < delay * 4; i++){
1701
1302
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1702
1303
      if(ret == -1){
1703
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1304
        perror("ioctl SIOCGIFFLAGS");
1704
1305
      } else if(network.ifr_flags & IFF_RUNNING){
1705
1306
        break;
1706
1307
      }
1707
1308
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1708
1309
      ret = nanosleep(&sleeptime, NULL);
1709
1310
      if(ret == -1 and errno != EINTR){
1710
 
        perror_plus("nanosleep");
 
1311
        perror("nanosleep");
1711
1312
      }
1712
1313
    }
1713
1314
    if(not take_down_interface){
1714
1315
      /* We won't need the socket anymore */
1715
1316
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1716
1317
      if(ret == -1){
1717
 
        perror_plus("close");
 
1318
        perror("close");
1718
1319
      }
1719
1320
    }
1720
1321
#ifdef __linux__
1722
1323
      /* Restores kernel loglevel to default */
1723
1324
      ret = klogctl(7, NULL, 0);
1724
1325
      if(ret == -1){
1725
 
        perror_plus("klogctl");
 
1326
        perror("klogctl");
1726
1327
      }
1727
1328
    }
1728
1329
#endif  /* __linux__ */
1732
1333
      /* Lower privileges */
1733
1334
      ret = seteuid(uid);
1734
1335
      if(ret == -1){
1735
 
        perror_plus("seteuid");
 
1336
        perror("seteuid");
1736
1337
      }
1737
1338
    } else {
1738
1339
      /* Lower privileges permanently */
1739
1340
      ret = setuid(uid);
1740
1341
      if(ret == -1){
1741
 
        perror_plus("setuid");
 
1342
        perror("setuid");
1742
1343
      }
1743
1344
    }
1744
1345
  }
1750
1351
  ret = init_gnutls_global(pubkey, seckey);
1751
1352
  if(ret == -1){
1752
1353
    fprintf(stderr, "init_gnutls_global failed\n");
1753
 
    exitcode = EX_UNAVAILABLE;
 
1354
    exitcode = EXIT_FAILURE;
1754
1355
    goto end;
1755
1356
  } else {
1756
1357
    gnutls_initialized = true;
1760
1361
    goto end;
1761
1362
  }
1762
1363
  
 
1364
  tempdir_created = true;
1763
1365
  if(mkdtemp(tempdir) == NULL){
1764
 
    perror_plus("mkdtemp");
 
1366
    tempdir_created = false;
 
1367
    perror("mkdtemp");
1765
1368
    goto end;
1766
1369
  }
1767
 
  tempdir_created = true;
1768
1370
  
1769
1371
  if(quit_now){
1770
1372
    goto end;
1772
1374
  
1773
1375
  if(not init_gpgme(pubkey, seckey, tempdir)){
1774
1376
    fprintf(stderr, "init_gpgme failed\n");
1775
 
    exitcode = EX_UNAVAILABLE;
 
1377
    exitcode = EXIT_FAILURE;
1776
1378
    goto end;
1777
1379
  } else {
1778
1380
    gpgme_initialized = true;
1788
1390
    char *address = strrchr(connect_to, ':');
1789
1391
    if(address == NULL){
1790
1392
      fprintf(stderr, "No colon in address\n");
1791
 
      exitcode = EX_USAGE;
 
1393
      exitcode = EXIT_FAILURE;
1792
1394
      goto end;
1793
1395
    }
1794
1396
    
1802
1404
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1803
1405
       or tmpmax != (uint16_t)tmpmax){
1804
1406
      fprintf(stderr, "Bad port number\n");
1805
 
      exitcode = EX_USAGE;
 
1407
      exitcode = EXIT_FAILURE;
1806
1408
      goto end;
1807
1409
    }
1808
1410
  
1812
1414
    
1813
1415
    port = (uint16_t)tmpmax;
1814
1416
    *address = '\0';
 
1417
    address = connect_to;
1815
1418
    /* Colon in address indicates IPv6 */
1816
1419
    int af;
1817
 
    if(strchr(connect_to, ':') != NULL){
 
1420
    if(strchr(address, ':') != NULL){
1818
1421
      af = AF_INET6;
1819
 
      /* Accept [] around IPv6 address - see RFC 5952 */
1820
 
      if(connect_to[0] == '[' and address[-1] == ']')
1821
 
        {
1822
 
          connect_to++;
1823
 
          address[-1] = '\0';
1824
 
        }
1825
1422
    } else {
1826
1423
      af = AF_INET;
1827
1424
    }
1828
 
    address = connect_to;
1829
1425
    
1830
1426
    if(quit_now){
1831
1427
      goto end;
1832
1428
    }
1833
1429
    
1834
 
    while(not quit_now){
1835
 
      ret = start_mandos_communication(address, port, if_index, af);
1836
 
      if(quit_now or ret == 0){
1837
 
        break;
1838
 
      }
1839
 
      if(debug){
1840
 
        fprintf(stderr, "Retrying in %d seconds\n",
1841
 
                (int)retry_interval);
1842
 
      }
1843
 
      sleep((int)retry_interval);
1844
 
    }
1845
 
    
1846
 
    if (not quit_now){
 
1430
    ret = start_mandos_communication(address, port, if_index, af);
 
1431
    if(ret < 0){
 
1432
      exitcode = EXIT_FAILURE;
 
1433
    } else {
1847
1434
      exitcode = EXIT_SUCCESS;
1848
1435
    }
1849
 
 
1850
1436
    goto end;
1851
1437
  }
1852
1438
  
1876
1462
  if(mc.server == NULL){
1877
1463
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1878
1464
            avahi_strerror(error));
1879
 
    exitcode = EX_UNAVAILABLE;
 
1465
    exitcode = EXIT_FAILURE;
1880
1466
    goto end;
1881
1467
  }
1882
1468
  
1891
1477
  if(sb == NULL){
1892
1478
    fprintf(stderr, "Failed to create service browser: %s\n",
1893
1479
            avahi_strerror(avahi_server_errno(mc.server)));
1894
 
    exitcode = EX_UNAVAILABLE;
 
1480
    exitcode = EXIT_FAILURE;
1895
1481
    goto end;
1896
1482
  }
1897
1483
  
1904
1490
  if(debug){
1905
1491
    fprintf(stderr, "Starting Avahi loop search\n");
1906
1492
  }
1907
 
 
1908
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
1909
 
                                (int)(retry_interval * 1000));
1910
 
  if(debug){
1911
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1912
 
            (ret == 0) ? "successfully" : "with error");
1913
 
  }
 
1493
  
 
1494
  avahi_simple_poll_loop(mc.simple_poll);
1914
1495
  
1915
1496
 end:
1916
1497
  
1937
1518
  if(gpgme_initialized){
1938
1519
    gpgme_release(mc.ctx);
1939
1520
  }
1940
 
 
1941
 
  /* Cleans up the circular linked list of Mandos servers the client
1942
 
     has seen */
1943
 
  if(mc.current_server != NULL){
1944
 
    mc.current_server->prev->next = NULL;
1945
 
    while(mc.current_server != NULL){
1946
 
      server *next = mc.current_server->next;
1947
 
      free(mc.current_server);
1948
 
      mc.current_server = next;
1949
 
    }
1950
 
  }
1951
1521
  
1952
1522
  /* Take down the network interface */
1953
1523
  if(take_down_interface){
1955
1525
    errno = 0;
1956
1526
    ret = seteuid(0);
1957
1527
    if(ret == -1){
1958
 
      perror_plus("seteuid");
 
1528
      perror("seteuid");
1959
1529
    }
1960
1530
    if(geteuid() == 0){
1961
1531
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1962
1532
      if(ret == -1){
1963
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1533
        perror("ioctl SIOCGIFFLAGS");
1964
1534
      } else if(network.ifr_flags & IFF_UP) {
1965
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1535
        network.ifr_flags &= ~IFF_UP; /* clear flag */
1966
1536
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1967
1537
        if(ret == -1){
1968
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1538
          perror("ioctl SIOCSIFFLAGS");
1969
1539
        }
1970
1540
      }
1971
1541
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1972
1542
      if(ret == -1){
1973
 
        perror_plus("close");
 
1543
        perror("close");
1974
1544
      }
1975
1545
      /* Lower privileges permanently */
1976
1546
      errno = 0;
1977
1547
      ret = setuid(uid);
1978
1548
      if(ret == -1){
1979
 
        perror_plus("setuid");
 
1549
        perror("setuid");
1980
1550
      }
1981
1551
    }
1982
1552
  }
1983
1553
  
1984
 
  /* Removes the GPGME temp directory and all files inside */
 
1554
  /* Removes the temp directory used by GPGME */
1985
1555
  if(tempdir_created){
1986
 
    struct dirent **direntries = NULL;
1987
 
    struct dirent *direntry = NULL;
1988
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
1989
 
                             alphasort);
1990
 
    if (numentries > 0){
1991
 
      for(int i = 0; i < numentries; i++){
1992
 
        direntry = direntries[i];
 
1556
    DIR *d;
 
1557
    struct dirent *direntry;
 
1558
    d = opendir(tempdir);
 
1559
    if(d == NULL){
 
1560
      if(errno != ENOENT){
 
1561
        perror("opendir");
 
1562
      }
 
1563
    } else {
 
1564
      while(true){
 
1565
        direntry = readdir(d);
 
1566
        if(direntry == NULL){
 
1567
          break;
 
1568
        }
 
1569
        /* Skip "." and ".." */
 
1570
        if(direntry->d_name[0] == '.'
 
1571
           and (direntry->d_name[1] == '\0'
 
1572
                or (direntry->d_name[1] == '.'
 
1573
                    and direntry->d_name[2] == '\0'))){
 
1574
          continue;
 
1575
        }
1993
1576
        char *fullname = NULL;
1994
1577
        ret = asprintf(&fullname, "%s/%s", tempdir,
1995
1578
                       direntry->d_name);
1996
1579
        if(ret < 0){
1997
 
          perror_plus("asprintf");
 
1580
          perror("asprintf");
1998
1581
          continue;
1999
1582
        }
2000
1583
        ret = remove(fullname);
2004
1587
        }
2005
1588
        free(fullname);
2006
1589
      }
2007
 
    }
2008
 
 
2009
 
    /* need to clean even if 0 because man page doesn't specify */
2010
 
    free(direntries);
2011
 
    if (numentries == -1){
2012
 
      perror_plus("scandir");
 
1590
      closedir(d);
2013
1591
    }
2014
1592
    ret = rmdir(tempdir);
2015
1593
    if(ret == -1 and errno != ENOENT){
2016
 
      perror_plus("rmdir");
 
1594
      perror("rmdir");
2017
1595
    }
2018
1596
  }
2019
1597
  
2020
1598
  if(quit_now){
2021
1599
    sigemptyset(&old_sigterm_action.sa_mask);
2022
1600
    old_sigterm_action.sa_handler = SIG_DFL;
2023
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2024
 
                                            &old_sigterm_action,
2025
 
                                            NULL));
 
1601
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
2026
1602
    if(ret == -1){
2027
 
      perror_plus("sigaction");
2028
 
    }
2029
 
    do {
2030
 
      ret = raise(signal_received);
2031
 
    } while(ret != 0 and errno == EINTR);
2032
 
    if(ret != 0){
2033
 
      perror_plus("raise");
2034
 
      abort();
2035
 
    }
2036
 
    TEMP_FAILURE_RETRY(pause());
 
1603
      perror("sigaction");
 
1604
    }
 
1605
    raise(signal_received);
2037
1606
  }
2038
1607
  
2039
1608
  return exitcode;