/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

Intermediate commit - this does *not* work yet.

* plugins.d/mandos-client.c (HOOKDIR): New.
  (up_interface): New.
  (runnable_hook): New.
  (main): Run network hooks with "start" argument.

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