/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: Björn Påhlsson
  • Date: 2011-11-14 18:03:35 UTC
  • mto: (505.3.9 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 525.
  • Revision ID: belorn@fukt.bsnet.se-20111114180335-3j4x5mjr7lix2jyj
New convinence error printer: fprintf_plus

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(), abort() */
 
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 */
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
76
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
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 };
144
163
 
145
164
sig_atomic_t quit_now = 0;
146
165
int signal_received = 0;
147
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
}
 
173
 
 
174
int fprintf_plus(FILE *stream, const char *format, ...){
 
175
  va_list ap;
 
176
  va_start (ap, format);
 
177
  
 
178
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
179
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
180
}
 
181
 
148
182
/*
149
183
 * Make additional room in "buffer" for at least BUFFER_SIZE more
150
184
 * bytes. "buffer_capacity" is how much is currently allocated,
162
196
  return buffer_capacity;
163
197
}
164
198
 
 
199
/* Add server to set of servers to retry periodically */
 
200
int add_server(const char *ip, uint16_t port,
 
201
                 AvahiIfIndex if_index,
 
202
                 int af){
 
203
  int ret;
 
204
  server *new_server = malloc(sizeof(server));
 
205
  if(new_server == NULL){
 
206
    perror_plus("malloc");
 
207
    return -1;
 
208
  }
 
209
  *new_server = (server){ .ip = strdup(ip),
 
210
                         .port = port,
 
211
                         .if_index = if_index,
 
212
                         .af = af };
 
213
  if(new_server->ip == NULL){
 
214
    perror_plus("strdup");
 
215
    return -1;
 
216
  }
 
217
  /* Special case of first server */
 
218
  if (mc.current_server == NULL){
 
219
    new_server->next = new_server;
 
220
    new_server->prev = new_server;
 
221
    mc.current_server = new_server;
 
222
  /* Place the new server last in the list */
 
223
  } else {
 
224
    new_server->next = mc.current_server;
 
225
    new_server->prev = mc.current_server->prev;
 
226
    new_server->prev->next = new_server;
 
227
    mc.current_server->prev = new_server;
 
228
  }
 
229
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
230
  if(ret == -1){
 
231
    perror_plus("clock_gettime");
 
232
    return -1;
 
233
  }
 
234
  return 0;
 
235
}
 
236
 
165
237
/* 
166
238
 * Initialize GPGME.
167
239
 */
181
253
    
182
254
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
183
255
    if(fd == -1){
184
 
      perror("open");
 
256
      perror_plus("open");
185
257
      return false;
186
258
    }
187
259
    
201
273
    
202
274
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
203
275
    if(ret == -1){
204
 
      perror("close");
 
276
      perror_plus("close");
205
277
    }
206
278
    gpgme_data_release(pgp_data);
207
279
    return true;
220
292
    return false;
221
293
  }
222
294
  
223
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
295
  /* Set GPGME home directory for the OpenPGP engine only */
224
296
  rc = gpgme_get_engine_info(&engine_info);
225
297
  if(rc != GPG_ERR_NO_ERROR){
226
298
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
332
404
  
333
405
  /* Seek back to the beginning of the GPGME plaintext data buffer */
334
406
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
335
 
    perror("gpgme_data_seek");
 
407
    perror_plus("gpgme_data_seek");
336
408
    plaintext_length = -1;
337
409
    goto decrypt_end;
338
410
  }
343
415
                                      (size_t)plaintext_length,
344
416
                                      plaintext_capacity);
345
417
    if(plaintext_capacity == 0){
346
 
        perror("incbuffer");
 
418
        perror_plus("incbuffer");
347
419
        plaintext_length = -1;
348
420
        goto decrypt_end;
349
421
    }
356
428
      break;
357
429
    }
358
430
    if(ret < 0){
359
 
      perror("gpgme_data_read");
 
431
      perror_plus("gpgme_data_read");
360
432
      plaintext_length = -1;
361
433
      goto decrypt_end;
362
434
    }
419
491
  }
420
492
  
421
493
  /* OpenPGP credentials */
422
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
494
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
423
495
  if(ret != GNUTLS_E_SUCCESS){
424
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
425
 
                                                    from
426
 
                                                    -Wunreachable-code
427
 
                                                 */
 
496
    fprintf(stderr, "GnuTLS memory error: %s\n",
428
497
            safer_gnutls_strerror(ret));
429
498
    gnutls_global_deinit();
430
499
    return -1;
552
621
  gnutls_session_t session;
553
622
  int pf;                       /* Protocol family */
554
623
  
 
624
  errno = 0;
 
625
  
555
626
  if(quit_now){
 
627
    errno = EINTR;
556
628
    return -1;
557
629
  }
558
630
  
565
637
    break;
566
638
  default:
567
639
    fprintf(stderr, "Bad address family: %d\n", af);
 
640
    errno = EINVAL;
568
641
    return -1;
569
642
  }
570
643
  
580
653
  
581
654
  tcp_sd = socket(pf, SOCK_STREAM, 0);
582
655
  if(tcp_sd < 0){
583
 
    perror("socket");
 
656
    int e = errno;
 
657
    perror_plus("socket");
 
658
    errno = e;
584
659
    goto mandos_end;
585
660
  }
586
661
  
587
662
  if(quit_now){
 
663
    errno = EINTR;
588
664
    goto mandos_end;
589
665
  }
590
666
  
597
673
    ret = inet_pton(af, ip, &to.in.sin_addr);
598
674
  }
599
675
  if(ret < 0 ){
600
 
    perror("inet_pton");
 
676
    int e = errno;
 
677
    perror_plus("inet_pton");
 
678
    errno = e;
601
679
    goto mandos_end;
602
680
  }
603
681
  if(ret == 0){
 
682
    int e = errno;
604
683
    fprintf(stderr, "Bad address: %s\n", ip);
 
684
    errno = e;
605
685
    goto mandos_end;
606
686
  }
607
687
  if(af == AF_INET6){
615
695
      if(if_index == AVAHI_IF_UNSPEC){
616
696
        fprintf(stderr, "An IPv6 link-local address is incomplete"
617
697
                " without a network interface\n");
 
698
        errno = EINVAL;
618
699
        goto mandos_end;
619
700
      }
620
701
      /* Set the network interface number as scope */
627
708
  }
628
709
  
629
710
  if(quit_now){
 
711
    errno = EINTR;
630
712
    goto mandos_end;
631
713
  }
632
714
  
634
716
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
635
717
      char interface[IF_NAMESIZE];
636
718
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
637
 
        perror("if_indextoname");
 
719
        perror_plus("if_indextoname");
638
720
      } else {
639
721
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
640
722
                ip, interface, port);
654
736
                        sizeof(addrstr));
655
737
    }
656
738
    if(pcret == NULL){
657
 
      perror("inet_ntop");
 
739
      perror_plus("inet_ntop");
658
740
    } else {
659
741
      if(strcmp(addrstr, ip) != 0){
660
742
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
663
745
  }
664
746
  
665
747
  if(quit_now){
 
748
    errno = EINTR;
666
749
    goto mandos_end;
667
750
  }
668
751
  
672
755
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
673
756
  }
674
757
  if(ret < 0){
675
 
    perror("connect");
 
758
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
759
      int e = errno;
 
760
      perror_plus("connect");
 
761
      errno = e;
 
762
    }
676
763
    goto mandos_end;
677
764
  }
678
765
  
679
766
  if(quit_now){
 
767
    errno = EINTR;
680
768
    goto mandos_end;
681
769
  }
682
770
  
687
775
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
688
776
                                   out_size - written));
689
777
    if(ret == -1){
690
 
      perror("write");
 
778
      int e = errno;
 
779
      perror_plus("write");
 
780
      errno = e;
691
781
      goto mandos_end;
692
782
    }
693
783
    written += (size_t)ret;
703
793
    }
704
794
  
705
795
    if(quit_now){
 
796
      errno = EINTR;
706
797
      goto mandos_end;
707
798
    }
708
799
  }
712
803
  }
713
804
  
714
805
  if(quit_now){
 
806
    errno = EINTR;
715
807
    goto mandos_end;
716
808
  }
717
809
  
 
810
  /* Spurious warning from -Wint-to-pointer-cast */
718
811
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
719
812
  
720
813
  if(quit_now){
 
814
    errno = EINTR;
721
815
    goto mandos_end;
722
816
  }
723
817
  
724
818
  do {
725
819
    ret = gnutls_handshake(session);
726
820
    if(quit_now){
 
821
      errno = EINTR;
727
822
      goto mandos_end;
728
823
    }
729
824
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
733
828
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
734
829
      gnutls_perror(ret);
735
830
    }
 
831
    errno = EPROTO;
736
832
    goto mandos_end;
737
833
  }
738
834
  
746
842
  while(true){
747
843
    
748
844
    if(quit_now){
 
845
      errno = EINTR;
749
846
      goto mandos_end;
750
847
    }
751
848
    
752
849
    buffer_capacity = incbuffer(&buffer, buffer_length,
753
850
                                   buffer_capacity);
754
851
    if(buffer_capacity == 0){
755
 
      perror("incbuffer");
 
852
      int e = errno;
 
853
      perror_plus("incbuffer");
 
854
      errno = e;
756
855
      goto mandos_end;
757
856
    }
758
857
    
759
858
    if(quit_now){
 
859
      errno = EINTR;
760
860
      goto mandos_end;
761
861
    }
762
862
    
775
875
          ret = gnutls_handshake(session);
776
876
          
777
877
          if(quit_now){
 
878
            errno = EINTR;
778
879
            goto mandos_end;
779
880
          }
780
881
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
781
882
        if(ret < 0){
782
883
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
783
884
          gnutls_perror(ret);
 
885
          errno = EPROTO;
784
886
          goto mandos_end;
785
887
        }
786
888
        break;
788
890
        fprintf(stderr, "Unknown error while reading data from"
789
891
                " encrypted session with Mandos server\n");
790
892
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
893
        errno = EIO;
791
894
        goto mandos_end;
792
895
      }
793
896
    } else {
800
903
  }
801
904
  
802
905
  if(quit_now){
 
906
    errno = EINTR;
803
907
    goto mandos_end;
804
908
  }
805
909
  
806
910
  do {
807
911
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
808
912
    if(quit_now){
 
913
      errno = EINTR;
809
914
      goto mandos_end;
810
915
    }
811
916
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
820
925
      written = 0;
821
926
      while(written < (size_t) decrypted_buffer_size){
822
927
        if(quit_now){
 
928
          errno = EINTR;
823
929
          goto mandos_end;
824
930
        }
825
931
        
827
933
                          (size_t)decrypted_buffer_size - written,
828
934
                          stdout);
829
935
        if(ret == 0 and ferror(stdout)){
 
936
          int e = errno;
830
937
          if(debug){
831
938
            fprintf(stderr, "Error writing encrypted data: %s\n",
832
939
                    strerror(errno));
833
940
          }
 
941
          errno = e;
834
942
          goto mandos_end;
835
943
        }
836
944
        written += (size_t)ret;
842
950
  /* Shutdown procedure */
843
951
  
844
952
 mandos_end:
845
 
  free(decrypted_buffer);
846
 
  free(buffer);
847
 
  if(tcp_sd >= 0){
848
 
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
849
 
  }
850
 
  if(ret == -1){
851
 
    perror("close");
852
 
  }
853
 
  gnutls_deinit(session);
854
 
  if(quit_now){
855
 
    retval = -1;
 
953
  {
 
954
    int e = errno;
 
955
    free(decrypted_buffer);
 
956
    free(buffer);
 
957
    if(tcp_sd >= 0){
 
958
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
959
    }
 
960
    if(ret == -1){
 
961
      if(e == 0){
 
962
        e = errno;
 
963
      }
 
964
      perror_plus("close");
 
965
    }
 
966
    gnutls_deinit(session);
 
967
    errno = e;
 
968
    if(quit_now){
 
969
      errno = EINTR;
 
970
      retval = -1;
 
971
    }
856
972
  }
857
973
  return retval;
858
974
}
901
1017
                                           avahi_proto_to_af(proto));
902
1018
      if(ret == 0){
903
1019
        avahi_simple_poll_quit(mc.simple_poll);
 
1020
      } else {
 
1021
        ret = add_server(ip, port, interface,
 
1022
                         avahi_proto_to_af(proto));
904
1023
      }
905
1024
    }
906
1025
  }
960
1079
  }
961
1080
}
962
1081
 
963
 
/* stop main loop after sigterm has been called */
 
1082
/* Signal handler that stops main loop after SIGTERM */
964
1083
static void handle_sigterm(int sig){
965
1084
  if(quit_now){
966
1085
    return;
968
1087
  quit_now = 1;
969
1088
  signal_received = sig;
970
1089
  int old_errno = errno;
 
1090
  /* set main loop to exit */
971
1091
  if(mc.simple_poll != NULL){
972
1092
    avahi_simple_poll_quit(mc.simple_poll);
973
1093
  }
974
1094
  errno = old_errno;
975
1095
}
976
1096
 
 
1097
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1098
  int ret;
 
1099
  
 
1100
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1101
  if(s < 0){
 
1102
    perror_plus("socket");
 
1103
    return false;
 
1104
  }
 
1105
  strcpy(ifr->ifr_name, ifname);
 
1106
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1107
  if(ret == -1){
 
1108
    if(debug){
 
1109
      perror_plus("ioctl SIOCGIFFLAGS");
 
1110
    }
 
1111
    return false;
 
1112
  }
 
1113
  return true;
 
1114
}
 
1115
 
 
1116
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1117
  
 
1118
  /* Reject the loopback device */
 
1119
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1120
    if(debug){
 
1121
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1122
              ifname);
 
1123
    }
 
1124
    return false;
 
1125
  }
 
1126
  /* Accept point-to-point devices only if connect_to is specified */
 
1127
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1128
    if(debug){
 
1129
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1130
              ifname);
 
1131
    }
 
1132
    return true;
 
1133
  }
 
1134
  /* Otherwise, reject non-broadcast-capable devices */
 
1135
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1136
    if(debug){
 
1137
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1138
              ifname);
 
1139
    }
 
1140
    return false;
 
1141
  }
 
1142
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1143
  if(ifr->ifr_flags & IFF_NOARP){
 
1144
    if(debug){
 
1145
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1146
    }
 
1147
    return false;
 
1148
  }
 
1149
  
 
1150
  /* Accept this device */
 
1151
  if(debug){
 
1152
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1153
  }
 
1154
  return true;
 
1155
}
 
1156
 
 
1157
/* 
 
1158
 * This function determines if a directory entry in /sys/class/net
 
1159
 * corresponds to an acceptable network device.
 
1160
 * (This function is passed to scandir(3) as a filter function.)
 
1161
 */
 
1162
int good_interface(const struct dirent *if_entry){
 
1163
  int ret;
 
1164
  if(if_entry->d_name[0] == '.'){
 
1165
    return 0;
 
1166
  }
 
1167
  struct ifreq ifr;
 
1168
 
 
1169
  if(not get_flags(if_entry->d_name, &ifr)){
 
1170
    return 0;
 
1171
  }
 
1172
  
 
1173
  if(not good_flags(if_entry->d_name, &ifr)){
 
1174
    return 0;
 
1175
  }
 
1176
  return 1;
 
1177
}
 
1178
 
 
1179
/* 
 
1180
 * This function determines if a directory entry in /sys/class/net
 
1181
 * corresponds to an acceptable network device which is up.
 
1182
 * (This function is passed to scandir(3) as a filter function.)
 
1183
 */
 
1184
int up_interface(const struct dirent *if_entry){
 
1185
  ssize_t ssret;
 
1186
  char *flagname = NULL;
 
1187
  if(if_entry->d_name[0] == '.'){
 
1188
    return 0;
 
1189
  }
 
1190
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1191
                     if_entry->d_name);
 
1192
  if(ret < 0){
 
1193
    perror_plus("asprintf");
 
1194
    return 0;
 
1195
  }
 
1196
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1197
  if(flags_fd == -1){
 
1198
    perror_plus("open");
 
1199
    free(flagname);
 
1200
    return 0;
 
1201
  }
 
1202
  free(flagname);
 
1203
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1204
  /* read line from flags_fd */
 
1205
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1206
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1207
  flagstring[(size_t)to_read] = '\0';
 
1208
  if(flagstring == NULL){
 
1209
    perror_plus("malloc");
 
1210
    close(flags_fd);
 
1211
    return 0;
 
1212
  }
 
1213
  while(to_read > 0){
 
1214
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1215
                                             (size_t)to_read));
 
1216
    if(ssret == -1){
 
1217
      perror_plus("read");
 
1218
      free(flagstring);
 
1219
      close(flags_fd);
 
1220
      return 0;
 
1221
    }
 
1222
    to_read -= ssret;
 
1223
    if(ssret == 0){
 
1224
      break;
 
1225
    }
 
1226
  }
 
1227
  close(flags_fd);
 
1228
  intmax_t tmpmax;
 
1229
  char *tmp;
 
1230
  errno = 0;
 
1231
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1232
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1233
                                         and not (isspace(*tmp)))
 
1234
     or tmpmax != (ifreq_flags)tmpmax){
 
1235
    if(debug){
 
1236
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1237
              flagstring, if_entry->d_name);
 
1238
    }
 
1239
    free(flagstring);
 
1240
    return 0;
 
1241
  }
 
1242
  free(flagstring);
 
1243
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1244
  /* Reject the loopback device */
 
1245
  if(flags & IFF_LOOPBACK){
 
1246
    if(debug){
 
1247
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1248
              if_entry->d_name);
 
1249
    }
 
1250
    return 0;
 
1251
  }
 
1252
 
 
1253
  /* Reject down interfaces */
 
1254
  if(not (flags & IFF_UP)){
 
1255
    return 0;
 
1256
  }
 
1257
  
 
1258
  /* Accept point-to-point devices only if connect_to is specified */
 
1259
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1260
    if(debug){
 
1261
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1262
              if_entry->d_name);
 
1263
    }
 
1264
    return 1;
 
1265
  }
 
1266
  /* Otherwise, reject non-broadcast-capable devices */
 
1267
  if(not (flags & IFF_BROADCAST)){
 
1268
    if(debug){
 
1269
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1270
              if_entry->d_name);
 
1271
    }
 
1272
    return 0;
 
1273
  }
 
1274
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1275
  if(flags & IFF_NOARP){
 
1276
    if(debug){
 
1277
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1278
              if_entry->d_name);
 
1279
    }
 
1280
    return 0;
 
1281
  }
 
1282
  /* Accept this device */
 
1283
  if(debug){
 
1284
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1285
            if_entry->d_name);
 
1286
  }
 
1287
  return 1;
 
1288
}
 
1289
 
 
1290
int notdotentries(const struct dirent *direntry){
 
1291
  /* Skip "." and ".." */
 
1292
  if(direntry->d_name[0] == '.'
 
1293
     and (direntry->d_name[1] == '\0'
 
1294
          or (direntry->d_name[1] == '.'
 
1295
              and direntry->d_name[2] == '\0'))){
 
1296
    return 0;
 
1297
  }
 
1298
  return 1;
 
1299
}
 
1300
 
 
1301
/* Is this directory entry a runnable program? */
 
1302
int runnable_hook(const struct dirent *direntry){
 
1303
  int ret;
 
1304
  struct stat st;
 
1305
  
 
1306
  if((direntry->d_name)[0] == '\0'){
 
1307
    /* Empty name? */
 
1308
    return 0;
 
1309
  }
 
1310
  
 
1311
  /* Save pointer to last character */
 
1312
  char *end = strchr(direntry->d_name, '\0')-1;
 
1313
  
 
1314
  if(*end == '~'){
 
1315
    /* Backup name~ */
 
1316
    return 0;
 
1317
  }
 
1318
  
 
1319
  if(((direntry->d_name)[0] == '#')
 
1320
     and (*end == '#')){
 
1321
    /* Temporary #name# */
 
1322
    return 0;
 
1323
  }
 
1324
  
 
1325
  /* XXX more rules here */
 
1326
  
 
1327
  ret = stat(direntry->d_name, &st);
 
1328
  if(ret == -1){
 
1329
    if(debug){
 
1330
      perror_plus("Could not stat plugin");
 
1331
    }
 
1332
    return 0;
 
1333
  }
 
1334
  if(not (st.st_mode & S_ISREG)){
 
1335
    /* Not a regular file */
 
1336
    return 0;
 
1337
  }
 
1338
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1339
    /* Not executable */
 
1340
    return 0;
 
1341
  }
 
1342
  return 1;
 
1343
}
 
1344
 
 
1345
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1346
  int ret;
 
1347
  struct timespec now;
 
1348
  struct timespec waited_time;
 
1349
  intmax_t block_time;
 
1350
  
 
1351
  while(true){
 
1352
    if(mc.current_server == NULL){
 
1353
      if (debug){
 
1354
        fprintf(stderr,
 
1355
                "Wait until first server is found. No timeout!\n");
 
1356
      }
 
1357
      ret = avahi_simple_poll_iterate(s, -1);
 
1358
    } else {
 
1359
      if (debug){
 
1360
        fprintf(stderr, "Check current_server if we should run it,"
 
1361
                " or wait\n");
 
1362
      }
 
1363
      /* the current time */
 
1364
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1365
      if(ret == -1){
 
1366
        perror_plus("clock_gettime");
 
1367
        return -1;
 
1368
      }
 
1369
      /* Calculating in ms how long time between now and server
 
1370
         who we visted longest time ago. Now - last seen.  */
 
1371
      waited_time.tv_sec = (now.tv_sec
 
1372
                            - mc.current_server->last_seen.tv_sec);
 
1373
      waited_time.tv_nsec = (now.tv_nsec
 
1374
                             - mc.current_server->last_seen.tv_nsec);
 
1375
      /* total time is 10s/10,000ms.
 
1376
         Converting to s from ms by dividing by 1,000,
 
1377
         and ns to ms by dividing by 1,000,000. */
 
1378
      block_time = ((retry_interval
 
1379
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1380
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1381
      
 
1382
      if (debug){
 
1383
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1384
      }
 
1385
      
 
1386
      if(block_time <= 0){
 
1387
        ret = start_mandos_communication(mc.current_server->ip,
 
1388
                                         mc.current_server->port,
 
1389
                                         mc.current_server->if_index,
 
1390
                                         mc.current_server->af);
 
1391
        if(ret == 0){
 
1392
          avahi_simple_poll_quit(mc.simple_poll);
 
1393
          return 0;
 
1394
        }
 
1395
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1396
                            &mc.current_server->last_seen);
 
1397
        if(ret == -1){
 
1398
          perror_plus("clock_gettime");
 
1399
          return -1;
 
1400
        }
 
1401
        mc.current_server = mc.current_server->next;
 
1402
        block_time = 0;         /* Call avahi to find new Mandos
 
1403
                                   servers, but don't block */
 
1404
      }
 
1405
      
 
1406
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1407
    }
 
1408
    if(ret != 0){
 
1409
      if (ret > 0 or errno != EINTR) {
 
1410
        return (ret != 1) ? ret : 0;
 
1411
      }
 
1412
    }
 
1413
  }
 
1414
}
 
1415
 
977
1416
int main(int argc, char *argv[]){
978
1417
  AvahiSServiceBrowser *sb = NULL;
979
1418
  int error;
981
1420
  intmax_t tmpmax;
982
1421
  char *tmp;
983
1422
  int exitcode = EXIT_SUCCESS;
984
 
  const char *interface = "eth0";
 
1423
  const char *interface = "";
985
1424
  struct ifreq network;
986
1425
  int sd = -1;
987
1426
  bool take_down_interface = false;
988
1427
  uid_t uid;
989
1428
  gid_t gid;
990
 
  char *connect_to = NULL;
991
1429
  char tempdir[] = "/tmp/mandosXXXXXX";
992
1430
  bool tempdir_created = false;
993
1431
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
997
1435
  bool gnutls_initialized = false;
998
1436
  bool gpgme_initialized = false;
999
1437
  float delay = 2.5f;
 
1438
  double retry_interval = 10; /* 10s between trying a server and
 
1439
                                 retrying the same server again */
1000
1440
  
1001
1441
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1002
1442
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1008
1448
  errno = 0;
1009
1449
  ret = setgid(gid);
1010
1450
  if(ret == -1){
1011
 
    perror("setgid");
 
1451
    perror_plus("setgid");
1012
1452
  }
1013
1453
  
1014
1454
  /* Lower user privileges (temporarily) */
1015
1455
  errno = 0;
1016
1456
  ret = seteuid(uid);
1017
1457
  if(ret == -1){
1018
 
    perror("seteuid");
 
1458
    perror_plus("seteuid");
1019
1459
  }
1020
1460
  
1021
1461
  if(quit_now){
1056
1496
        .arg = "SECONDS",
1057
1497
        .doc = "Maximum delay to wait for interface startup",
1058
1498
        .group = 2 },
 
1499
      { .name = "retry", .key = 132,
 
1500
        .arg = "SECONDS",
 
1501
        .doc = "Retry interval used when denied by the mandos server",
 
1502
        .group = 2 },
 
1503
      /*
 
1504
       * These reproduce what we would get without ARGP_NO_HELP
 
1505
       */
 
1506
      { .name = "help", .key = '?',
 
1507
        .doc = "Give this help list", .group = -1 },
 
1508
      { .name = "usage", .key = -3,
 
1509
        .doc = "Give a short usage message", .group = -1 },
 
1510
      { .name = "version", .key = 'V',
 
1511
        .doc = "Print program version", .group = -1 },
1059
1512
      { .name = NULL }
1060
1513
    };
1061
1514
    
1062
1515
    error_t parse_opt(int key, char *arg,
1063
1516
                      struct argp_state *state){
 
1517
      errno = 0;
1064
1518
      switch(key){
1065
1519
      case 128:                 /* --debug */
1066
1520
        debug = true;
1082
1536
        tmpmax = strtoimax(arg, &tmp, 10);
1083
1537
        if(errno != 0 or tmp == arg or *tmp != '\0'
1084
1538
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1085
 
          fprintf(stderr, "Bad number of DH bits\n");
1086
 
          exit(EXIT_FAILURE);
 
1539
          argp_error(state, "Bad number of DH bits");
1087
1540
        }
1088
1541
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1089
1542
        break;
1094
1547
        errno = 0;
1095
1548
        delay = strtof(arg, &tmp);
1096
1549
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1097
 
          fprintf(stderr, "Bad delay\n");
1098
 
          exit(EXIT_FAILURE);
 
1550
          argp_error(state, "Bad delay");
 
1551
        }
 
1552
      case 132:                 /* --retry */
 
1553
        errno = 0;
 
1554
        retry_interval = strtod(arg, &tmp);
 
1555
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1556
           or (retry_interval * 1000) > INT_MAX
 
1557
           or retry_interval < 0){
 
1558
          argp_error(state, "Bad retry interval");
1099
1559
        }
1100
1560
        break;
1101
 
      case ARGP_KEY_ARG:
1102
 
        argp_usage(state);
1103
 
      case ARGP_KEY_END:
 
1561
        /*
 
1562
         * These reproduce what we would get without ARGP_NO_HELP
 
1563
         */
 
1564
      case '?':                 /* --help */
 
1565
        argp_state_help(state, state->out_stream,
 
1566
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1567
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1568
      case -3:                  /* --usage */
 
1569
        argp_state_help(state, state->out_stream,
 
1570
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1571
      case 'V':                 /* --version */
 
1572
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1573
        exit(argp_err_exit_status);
1104
1574
        break;
1105
1575
      default:
1106
1576
        return ARGP_ERR_UNKNOWN;
1107
1577
      }
1108
 
      return 0;
 
1578
      return errno;
1109
1579
    }
1110
1580
    
1111
1581
    struct argp argp = { .options = options, .parser = parse_opt,
1112
1582
                         .args_doc = "",
1113
1583
                         .doc = "Mandos client -- Get and decrypt"
1114
1584
                         " passwords from a Mandos server" };
1115
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1116
 
    if(ret == ARGP_ERR_UNKNOWN){
1117
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1118
 
      exitcode = EXIT_FAILURE;
1119
 
      goto end;
1120
 
    }
 
1585
    ret = argp_parse(&argp, argc, argv,
 
1586
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1587
    switch(ret){
 
1588
    case 0:
 
1589
      break;
 
1590
    case ENOMEM:
 
1591
    default:
 
1592
      errno = ret;
 
1593
      perror_plus("argp_parse");
 
1594
      exitcode = EX_OSERR;
 
1595
      goto end;
 
1596
    case EINVAL:
 
1597
      exitcode = EX_USAGE;
 
1598
      goto end;
 
1599
    }
 
1600
  }
 
1601
    
 
1602
  {
 
1603
    /* Work around Debian bug #633582:
 
1604
       <http://bugs.debian.org/633582> */
 
1605
    struct stat st;
 
1606
    
 
1607
    /* Re-raise priviliges */
 
1608
    errno = 0;
 
1609
    ret = seteuid(0);
 
1610
    if(ret == -1){
 
1611
      perror_plus("seteuid");
 
1612
    }
 
1613
    
 
1614
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1615
      int seckey_fd = open(seckey, O_RDONLY);
 
1616
      if(seckey_fd == -1){
 
1617
        perror_plus("open");
 
1618
      } else {
 
1619
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1620
        if(ret == -1){
 
1621
          perror_plus("fstat");
 
1622
        } else {
 
1623
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1624
            ret = fchown(seckey_fd, uid, gid);
 
1625
            if(ret == -1){
 
1626
              perror_plus("fchown");
 
1627
            }
 
1628
          }
 
1629
        }
 
1630
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1631
      }
 
1632
    }
 
1633
    
 
1634
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1635
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1636
      if(pubkey_fd == -1){
 
1637
        perror_plus("open");
 
1638
      } else {
 
1639
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1640
        if(ret == -1){
 
1641
          perror_plus("fstat");
 
1642
        } else {
 
1643
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1644
            ret = fchown(pubkey_fd, uid, gid);
 
1645
            if(ret == -1){
 
1646
              perror_plus("fchown");
 
1647
            }
 
1648
          }
 
1649
        }
 
1650
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1651
      }
 
1652
    }
 
1653
    
 
1654
    /* Lower privileges */
 
1655
    errno = 0;
 
1656
    ret = seteuid(uid);
 
1657
    if(ret == -1){
 
1658
      perror_plus("seteuid");
 
1659
    }
 
1660
  }
 
1661
  
 
1662
  /* Find network hooks and run them */
 
1663
  {
 
1664
    struct dirent **direntries;
 
1665
    struct dirent *direntry;
 
1666
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
 
1667
                           alphasort);
 
1668
    int devnull = open("/dev/null", O_RDONLY);
 
1669
    for(int i = 0; i < numhooks; i++){
 
1670
      direntry = direntries[0];
 
1671
      char *fullname = NULL;
 
1672
      ret = asprintf(&fullname, "%s/%s", tempdir,
 
1673
                     direntry->d_name);
 
1674
      if(ret < 0){
 
1675
        perror_plus("asprintf");
 
1676
        continue;
 
1677
      }
 
1678
      pid_t hook_pid = fork();
 
1679
      if(hook_pid == 0){
 
1680
        /* Child */
 
1681
        dup2(devnull, STDIN_FILENO);
 
1682
        close(devnull);
 
1683
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1684
        setenv("DEVICE", interface, 1);
 
1685
        setenv("VERBOSE", debug ? "1" : "0", 1);
 
1686
        setenv("MODE", "start", 1);
 
1687
        /* setenv( XXX more here */
 
1688
        ret = execl(fullname, direntry->d_name, "start");
 
1689
        perror_plus("execl");
 
1690
      }
 
1691
      free(fullname);
 
1692
      if(quit_now){
 
1693
        goto end;
 
1694
      }
 
1695
    }
 
1696
    close(devnull);
1121
1697
  }
1122
1698
  
1123
1699
  if(not debug){
1124
1700
    avahi_set_log_function(empty_log);
1125
1701
  }
1126
1702
  
 
1703
  if(interface[0] == '\0'){
 
1704
    struct dirent **direntries;
 
1705
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1706
                  alphasort);
 
1707
    if(ret >= 1){
 
1708
      /* Pick the first good interface */
 
1709
      interface = strdup(direntries[0]->d_name);
 
1710
      if(debug){
 
1711
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1712
      }
 
1713
      if(interface == NULL){
 
1714
        perror_plus("malloc");
 
1715
        free(direntries);
 
1716
        exitcode = EXIT_FAILURE;
 
1717
        goto end;
 
1718
      }
 
1719
      free(direntries);
 
1720
    } else {
 
1721
      free(direntries);
 
1722
      fprintf(stderr, "Could not find a network interface\n");
 
1723
      exitcode = EXIT_FAILURE;
 
1724
      goto end;
 
1725
    }
 
1726
  }
 
1727
  
1127
1728
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1128
1729
     from the signal handler */
1129
1730
  /* Initialize the pseudo-RNG for Avahi */
1131
1732
  mc.simple_poll = avahi_simple_poll_new();
1132
1733
  if(mc.simple_poll == NULL){
1133
1734
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1134
 
    exitcode = EXIT_FAILURE;
 
1735
    exitcode = EX_UNAVAILABLE;
1135
1736
    goto end;
1136
1737
  }
1137
1738
  
1138
1739
  sigemptyset(&sigterm_action.sa_mask);
1139
1740
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1140
1741
  if(ret == -1){
1141
 
    perror("sigaddset");
1142
 
    exitcode = EXIT_FAILURE;
 
1742
    perror_plus("sigaddset");
 
1743
    exitcode = EX_OSERR;
1143
1744
    goto end;
1144
1745
  }
1145
1746
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1146
1747
  if(ret == -1){
1147
 
    perror("sigaddset");
1148
 
    exitcode = EXIT_FAILURE;
 
1748
    perror_plus("sigaddset");
 
1749
    exitcode = EX_OSERR;
1149
1750
    goto end;
1150
1751
  }
1151
1752
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1152
1753
  if(ret == -1){
1153
 
    perror("sigaddset");
1154
 
    exitcode = EXIT_FAILURE;
 
1754
    perror_plus("sigaddset");
 
1755
    exitcode = EX_OSERR;
1155
1756
    goto end;
1156
1757
  }
1157
1758
  /* Need to check if the handler is SIG_IGN before handling:
1160
1761
  */
1161
1762
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1162
1763
  if(ret == -1){
1163
 
    perror("sigaction");
1164
 
    return EXIT_FAILURE;
 
1764
    perror_plus("sigaction");
 
1765
    return EX_OSERR;
1165
1766
  }
1166
1767
  if(old_sigterm_action.sa_handler != SIG_IGN){
1167
1768
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1168
1769
    if(ret == -1){
1169
 
      perror("sigaction");
1170
 
      exitcode = EXIT_FAILURE;
 
1770
      perror_plus("sigaction");
 
1771
      exitcode = EX_OSERR;
1171
1772
      goto end;
1172
1773
    }
1173
1774
  }
1174
1775
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1175
1776
  if(ret == -1){
1176
 
    perror("sigaction");
1177
 
    return EXIT_FAILURE;
 
1777
    perror_plus("sigaction");
 
1778
    return EX_OSERR;
1178
1779
  }
1179
1780
  if(old_sigterm_action.sa_handler != SIG_IGN){
1180
1781
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1181
1782
    if(ret == -1){
1182
 
      perror("sigaction");
1183
 
      exitcode = EXIT_FAILURE;
 
1783
      perror_plus("sigaction");
 
1784
      exitcode = EX_OSERR;
1184
1785
      goto end;
1185
1786
    }
1186
1787
  }
1187
1788
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1188
1789
  if(ret == -1){
1189
 
    perror("sigaction");
1190
 
    return EXIT_FAILURE;
 
1790
    perror_plus("sigaction");
 
1791
    return EX_OSERR;
1191
1792
  }
1192
1793
  if(old_sigterm_action.sa_handler != SIG_IGN){
1193
1794
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1194
1795
    if(ret == -1){
1195
 
      perror("sigaction");
1196
 
      exitcode = EXIT_FAILURE;
 
1796
      perror_plus("sigaction");
 
1797
      exitcode = EX_OSERR;
1197
1798
      goto end;
1198
1799
    }
1199
1800
  }
1200
1801
  
1201
1802
  /* If the interface is down, bring it up */
1202
 
  if(interface[0] != '\0'){
 
1803
  if(strcmp(interface, "none") != 0){
1203
1804
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1204
1805
    if(if_index == 0){
1205
1806
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1206
 
      exitcode = EXIT_FAILURE;
 
1807
      exitcode = EX_UNAVAILABLE;
1207
1808
      goto end;
1208
1809
    }
1209
1810
    
1215
1816
    errno = 0;
1216
1817
    ret = seteuid(0);
1217
1818
    if(ret == -1){
1218
 
      perror("seteuid");
 
1819
      perror_plus("seteuid");
1219
1820
    }
1220
1821
    
1221
1822
#ifdef __linux__
1222
1823
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1223
 
       messages to mess up the prompt */
 
1824
       messages about the network interface to mess up the prompt */
1224
1825
    ret = klogctl(8, NULL, 5);
1225
1826
    bool restore_loglevel = true;
1226
1827
    if(ret == -1){
1227
1828
      restore_loglevel = false;
1228
 
      perror("klogctl");
 
1829
      perror_plus("klogctl");
1229
1830
    }
1230
1831
#endif  /* __linux__ */
1231
1832
    
1232
1833
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1233
1834
    if(sd < 0){
1234
 
      perror("socket");
1235
 
      exitcode = EXIT_FAILURE;
 
1835
      perror_plus("socket");
 
1836
      exitcode = EX_OSERR;
1236
1837
#ifdef __linux__
1237
1838
      if(restore_loglevel){
1238
1839
        ret = klogctl(7, NULL, 0);
1239
1840
        if(ret == -1){
1240
 
          perror("klogctl");
 
1841
          perror_plus("klogctl");
1241
1842
        }
1242
1843
      }
1243
1844
#endif  /* __linux__ */
1245
1846
      errno = 0;
1246
1847
      ret = seteuid(uid);
1247
1848
      if(ret == -1){
1248
 
        perror("seteuid");
 
1849
        perror_plus("seteuid");
1249
1850
      }
1250
1851
      goto end;
1251
1852
    }
1252
1853
    strcpy(network.ifr_name, interface);
1253
1854
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1254
1855
    if(ret == -1){
1255
 
      perror("ioctl SIOCGIFFLAGS");
 
1856
      perror_plus("ioctl SIOCGIFFLAGS");
1256
1857
#ifdef __linux__
1257
1858
      if(restore_loglevel){
1258
1859
        ret = klogctl(7, NULL, 0);
1259
1860
        if(ret == -1){
1260
 
          perror("klogctl");
 
1861
          perror_plus("klogctl");
1261
1862
        }
1262
1863
      }
1263
1864
#endif  /* __linux__ */
1264
 
      exitcode = EXIT_FAILURE;
 
1865
      exitcode = EX_OSERR;
1265
1866
      /* Lower privileges */
1266
1867
      errno = 0;
1267
1868
      ret = seteuid(uid);
1268
1869
      if(ret == -1){
1269
 
        perror("seteuid");
 
1870
        perror_plus("seteuid");
1270
1871
      }
1271
1872
      goto end;
1272
1873
    }
1276
1877
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1277
1878
      if(ret == -1){
1278
1879
        take_down_interface = false;
1279
 
        perror("ioctl SIOCSIFFLAGS");
1280
 
        exitcode = EXIT_FAILURE;
 
1880
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1881
        exitcode = EX_OSERR;
1281
1882
#ifdef __linux__
1282
1883
        if(restore_loglevel){
1283
1884
          ret = klogctl(7, NULL, 0);
1284
1885
          if(ret == -1){
1285
 
            perror("klogctl");
 
1886
            perror_plus("klogctl");
1286
1887
          }
1287
1888
        }
1288
1889
#endif  /* __linux__ */
1290
1891
        errno = 0;
1291
1892
        ret = seteuid(uid);
1292
1893
        if(ret == -1){
1293
 
          perror("seteuid");
 
1894
          perror_plus("seteuid");
1294
1895
        }
1295
1896
        goto end;
1296
1897
      }
1297
1898
    }
1298
 
    /* sleep checking until interface is running */
 
1899
    /* Sleep checking until interface is running.
 
1900
       Check every 0.25s, up to total time of delay */
1299
1901
    for(int i=0; i < delay * 4; i++){
1300
1902
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1301
1903
      if(ret == -1){
1302
 
        perror("ioctl SIOCGIFFLAGS");
 
1904
        perror_plus("ioctl SIOCGIFFLAGS");
1303
1905
      } else if(network.ifr_flags & IFF_RUNNING){
1304
1906
        break;
1305
1907
      }
1306
1908
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1307
1909
      ret = nanosleep(&sleeptime, NULL);
1308
1910
      if(ret == -1 and errno != EINTR){
1309
 
        perror("nanosleep");
 
1911
        perror_plus("nanosleep");
1310
1912
      }
1311
1913
    }
1312
1914
    if(not take_down_interface){
1313
1915
      /* We won't need the socket anymore */
1314
1916
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1315
1917
      if(ret == -1){
1316
 
        perror("close");
 
1918
        perror_plus("close");
1317
1919
      }
1318
1920
    }
1319
1921
#ifdef __linux__
1321
1923
      /* Restores kernel loglevel to default */
1322
1924
      ret = klogctl(7, NULL, 0);
1323
1925
      if(ret == -1){
1324
 
        perror("klogctl");
 
1926
        perror_plus("klogctl");
1325
1927
      }
1326
1928
    }
1327
1929
#endif  /* __linux__ */
1331
1933
      /* Lower privileges */
1332
1934
      ret = seteuid(uid);
1333
1935
      if(ret == -1){
1334
 
        perror("seteuid");
 
1936
        perror_plus("seteuid");
1335
1937
      }
1336
1938
    } else {
1337
1939
      /* Lower privileges permanently */
1338
1940
      ret = setuid(uid);
1339
1941
      if(ret == -1){
1340
 
        perror("setuid");
 
1942
        perror_plus("setuid");
1341
1943
      }
1342
1944
    }
1343
1945
  }
1349
1951
  ret = init_gnutls_global(pubkey, seckey);
1350
1952
  if(ret == -1){
1351
1953
    fprintf(stderr, "init_gnutls_global failed\n");
1352
 
    exitcode = EXIT_FAILURE;
 
1954
    exitcode = EX_UNAVAILABLE;
1353
1955
    goto end;
1354
1956
  } else {
1355
1957
    gnutls_initialized = true;
1359
1961
    goto end;
1360
1962
  }
1361
1963
  
 
1964
  if(mkdtemp(tempdir) == NULL){
 
1965
    perror_plus("mkdtemp");
 
1966
    goto end;
 
1967
  }
1362
1968
  tempdir_created = true;
1363
 
  if(mkdtemp(tempdir) == NULL){
1364
 
    tempdir_created = false;
1365
 
    perror("mkdtemp");
1366
 
    goto end;
1367
 
  }
1368
1969
  
1369
1970
  if(quit_now){
1370
1971
    goto end;
1372
1973
  
1373
1974
  if(not init_gpgme(pubkey, seckey, tempdir)){
1374
1975
    fprintf(stderr, "init_gpgme failed\n");
1375
 
    exitcode = EXIT_FAILURE;
 
1976
    exitcode = EX_UNAVAILABLE;
1376
1977
    goto end;
1377
1978
  } else {
1378
1979
    gpgme_initialized = true;
1388
1989
    char *address = strrchr(connect_to, ':');
1389
1990
    if(address == NULL){
1390
1991
      fprintf(stderr, "No colon in address\n");
1391
 
      exitcode = EXIT_FAILURE;
 
1992
      exitcode = EX_USAGE;
1392
1993
      goto end;
1393
1994
    }
1394
1995
    
1402
2003
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1403
2004
       or tmpmax != (uint16_t)tmpmax){
1404
2005
      fprintf(stderr, "Bad port number\n");
1405
 
      exitcode = EXIT_FAILURE;
 
2006
      exitcode = EX_USAGE;
1406
2007
      goto end;
1407
2008
    }
1408
2009
  
1412
2013
    
1413
2014
    port = (uint16_t)tmpmax;
1414
2015
    *address = '\0';
1415
 
    address = connect_to;
1416
2016
    /* Colon in address indicates IPv6 */
1417
2017
    int af;
1418
 
    if(strchr(address, ':') != NULL){
 
2018
    if(strchr(connect_to, ':') != NULL){
1419
2019
      af = AF_INET6;
 
2020
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2021
      if(connect_to[0] == '[' and address[-1] == ']')
 
2022
        {
 
2023
          connect_to++;
 
2024
          address[-1] = '\0';
 
2025
        }
1420
2026
    } else {
1421
2027
      af = AF_INET;
1422
2028
    }
 
2029
    address = connect_to;
1423
2030
    
1424
2031
    if(quit_now){
1425
2032
      goto end;
1426
2033
    }
1427
2034
    
1428
 
    ret = start_mandos_communication(address, port, if_index, af);
1429
 
    if(ret < 0){
1430
 
      exitcode = EXIT_FAILURE;
1431
 
    } else {
 
2035
    while(not quit_now){
 
2036
      ret = start_mandos_communication(address, port, if_index, af);
 
2037
      if(quit_now or ret == 0){
 
2038
        break;
 
2039
      }
 
2040
      if(debug){
 
2041
        fprintf(stderr, "Retrying in %d seconds\n",
 
2042
                (int)retry_interval);
 
2043
      }
 
2044
      sleep((int)retry_interval);
 
2045
    }
 
2046
    
 
2047
    if (not quit_now){
1432
2048
      exitcode = EXIT_SUCCESS;
1433
2049
    }
 
2050
    
1434
2051
    goto end;
1435
2052
  }
1436
2053
  
1460
2077
  if(mc.server == NULL){
1461
2078
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1462
2079
            avahi_strerror(error));
1463
 
    exitcode = EXIT_FAILURE;
 
2080
    exitcode = EX_UNAVAILABLE;
1464
2081
    goto end;
1465
2082
  }
1466
2083
  
1475
2092
  if(sb == NULL){
1476
2093
    fprintf(stderr, "Failed to create service browser: %s\n",
1477
2094
            avahi_strerror(avahi_server_errno(mc.server)));
1478
 
    exitcode = EXIT_FAILURE;
 
2095
    exitcode = EX_UNAVAILABLE;
1479
2096
    goto end;
1480
2097
  }
1481
2098
  
1488
2105
  if(debug){
1489
2106
    fprintf(stderr, "Starting Avahi loop search\n");
1490
2107
  }
1491
 
  
1492
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2108
 
 
2109
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2110
                                (int)(retry_interval * 1000));
 
2111
  if(debug){
 
2112
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2113
            (ret == 0) ? "successfully" : "with error");
 
2114
  }
1493
2115
  
1494
2116
 end:
1495
2117
  
1516
2138
  if(gpgme_initialized){
1517
2139
    gpgme_release(mc.ctx);
1518
2140
  }
 
2141
 
 
2142
  /* Cleans up the circular linked list of Mandos servers the client
 
2143
     has seen */
 
2144
  if(mc.current_server != NULL){
 
2145
    mc.current_server->prev->next = NULL;
 
2146
    while(mc.current_server != NULL){
 
2147
      server *next = mc.current_server->next;
 
2148
      free(mc.current_server);
 
2149
      mc.current_server = next;
 
2150
    }
 
2151
  }
 
2152
  
 
2153
  /* XXX run network hooks "stop" here  */
1519
2154
  
1520
2155
  /* Take down the network interface */
1521
2156
  if(take_down_interface){
1523
2158
    errno = 0;
1524
2159
    ret = seteuid(0);
1525
2160
    if(ret == -1){
1526
 
      perror("seteuid");
 
2161
      perror_plus("seteuid");
1527
2162
    }
1528
2163
    if(geteuid() == 0){
1529
2164
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1530
2165
      if(ret == -1){
1531
 
        perror("ioctl SIOCGIFFLAGS");
 
2166
        perror_plus("ioctl SIOCGIFFLAGS");
1532
2167
      } else if(network.ifr_flags & IFF_UP) {
1533
 
        network.ifr_flags &= ~IFF_UP; /* clear flag */
 
2168
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1534
2169
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1535
2170
        if(ret == -1){
1536
 
          perror("ioctl SIOCSIFFLAGS");
 
2171
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1537
2172
        }
1538
2173
      }
1539
2174
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1540
2175
      if(ret == -1){
1541
 
        perror("close");
 
2176
        perror_plus("close");
1542
2177
      }
1543
2178
      /* Lower privileges permanently */
1544
2179
      errno = 0;
1545
2180
      ret = setuid(uid);
1546
2181
      if(ret == -1){
1547
 
        perror("setuid");
 
2182
        perror_plus("setuid");
1548
2183
      }
1549
2184
    }
1550
2185
  }
1551
2186
  
1552
 
  /* Removes the temp directory used by GPGME */
 
2187
  /* Removes the GPGME temp directory and all files inside */
1553
2188
  if(tempdir_created){
1554
 
    DIR *d;
1555
 
    struct dirent *direntry;
1556
 
    d = opendir(tempdir);
1557
 
    if(d == NULL){
1558
 
      if(errno != ENOENT){
1559
 
        perror("opendir");
1560
 
      }
1561
 
    } else {
1562
 
      while(true){
1563
 
        direntry = readdir(d);
1564
 
        if(direntry == NULL){
1565
 
          break;
1566
 
        }
1567
 
        /* Skip "." and ".." */
1568
 
        if(direntry->d_name[0] == '.'
1569
 
           and (direntry->d_name[1] == '\0'
1570
 
                or (direntry->d_name[1] == '.'
1571
 
                    and direntry->d_name[2] == '\0'))){
1572
 
          continue;
1573
 
        }
 
2189
    struct dirent **direntries = NULL;
 
2190
    struct dirent *direntry = NULL;
 
2191
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2192
                             alphasort);
 
2193
    if (numentries > 0){
 
2194
      for(int i = 0; i < numentries; i++){
 
2195
        direntry = direntries[i];
1574
2196
        char *fullname = NULL;
1575
2197
        ret = asprintf(&fullname, "%s/%s", tempdir,
1576
2198
                       direntry->d_name);
1577
2199
        if(ret < 0){
1578
 
          perror("asprintf");
 
2200
          perror_plus("asprintf");
1579
2201
          continue;
1580
2202
        }
1581
2203
        ret = remove(fullname);
1585
2207
        }
1586
2208
        free(fullname);
1587
2209
      }
1588
 
      closedir(d);
 
2210
    }
 
2211
 
 
2212
    /* need to clean even if 0 because man page doesn't specify */
 
2213
    free(direntries);
 
2214
    if (numentries == -1){
 
2215
      perror_plus("scandir");
1589
2216
    }
1590
2217
    ret = rmdir(tempdir);
1591
2218
    if(ret == -1 and errno != ENOENT){
1592
 
      perror("rmdir");
 
2219
      perror_plus("rmdir");
1593
2220
    }
1594
2221
  }
1595
2222
  
1600
2227
                                            &old_sigterm_action,
1601
2228
                                            NULL));
1602
2229
    if(ret == -1){
1603
 
      perror("sigaction");
 
2230
      perror_plus("sigaction");
1604
2231
    }
1605
2232
    do {
1606
2233
      ret = raise(signal_received);
1607
2234
    } while(ret != 0 and errno == EINTR);
1608
2235
    if(ret != 0){
1609
 
      perror("raise");
 
2236
      perror_plus("raise");
1610
2237
      abort();
1611
2238
    }
1612
2239
    TEMP_FAILURE_RETRY(pause());