/mandos/release

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

« back to all changes in this revision

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

* init.d-mandos (Required-Start, Required-Stop): Bug fix: Added
                 "$syslog", thanks to Petter Reinholdtsen
                 <pere@hungry.com> (Debian bug #546928).

* initramfs-tools-script: Removed erroneous comment.

* plugins.d/askpass-fifo.c: Removed TEMP_FAILURE_RETRY since it is
                            not needed.

* plugins.d/mandos-client.c (main): Bug fix: Initialize
                                    "old_sigterm_action".

* plugins.d/splashy.c (main): Bug fix: really check return value from
                              "sigaddset".  Fix some warnings on
                              64-bit systems.

* plugins.d/usplash.c (termination_handler, main): Save received
                                                   signal and
                                                   re-raise it on
                                                   exit.
  (usplash_write): Do not close FIFO, instead, take an additional file
                   descriptor pointer to it and open only when needed
                   (all callers changed).  Abort immediately on EINTR.
                   Bug fix:  Add NUL byte on single-word commands.
                   Ignore "interrupted_by_signal".
  (makeprompt, find_usplash): New; broken out from "main()".
  (find_usplash): Bug fix: close /proc/<pid>/cmdline FD on error.
  (main): Reorganized to jump to a new "failure" label on any error.
          Bug fix: check return values from sigaddset.
          New variable "usplash_accessed" to flag if usplash(8) needs
          to be killed and restarted.  Removed the "an_error_occured"
          variable.

Show diffs side-by-side

added added

removed removed

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