/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-09-07 23:48:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090907234817-op1lgg9gpruejsiv
* initramfs-tools-hook: Bug fix: Really install user-supplied plugins.
                        Bug fix: Warn about empty plugin directory.

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 */
72
71
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
 
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
74
                                   getuid(), getgid(), setuid(),
 
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;
536
474
static int init_gnutls_session(gnutls_session_t *session){
537
475
  int ret;
538
476
  /* GnuTLS session creation */
539
 
  do {
540
 
    ret = gnutls_init(session, GNUTLS_SERVER);
541
 
    if(quit_now){
542
 
      return -1;
543
 
    }
544
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
477
  ret = gnutls_init(session, GNUTLS_SERVER);
545
478
  if(ret != GNUTLS_E_SUCCESS){
546
479
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
547
480
            safer_gnutls_strerror(ret));
549
482
  
550
483
  {
551
484
    const char *err;
552
 
    do {
553
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
554
 
      if(quit_now){
555
 
        gnutls_deinit(*session);
556
 
        return -1;
557
 
      }
558
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
485
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
559
486
    if(ret != GNUTLS_E_SUCCESS){
560
487
      fprintf(stderr, "Syntax error at: %s\n", err);
561
488
      fprintf(stderr, "GnuTLS error: %s\n",
565
492
    }
566
493
  }
567
494
  
568
 
  do {
569
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
570
 
                                 mc.cred);
571
 
    if(quit_now){
572
 
      gnutls_deinit(*session);
573
 
      return -1;
574
 
    }
575
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
495
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
496
                               mc.cred);
576
497
  if(ret != GNUTLS_E_SUCCESS){
577
498
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
578
499
            safer_gnutls_strerror(ret));
581
502
  }
582
503
  
583
504
  /* ignore client certificate if any. */
584
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
505
  gnutls_certificate_server_set_request(*session,
 
506
                                        GNUTLS_CERT_IGNORE);
585
507
  
586
508
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
587
509
  
592
514
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
593
515
                      __attribute__((unused)) const char *txt){}
594
516
 
 
517
sig_atomic_t quit_now = 0;
 
518
int signal_received = 0;
 
519
 
595
520
/* Called when a Mandos server is found */
596
521
static int start_mandos_communication(const char *ip, uint16_t port,
597
522
                                      AvahiIfIndex if_index,
603
528
    struct sockaddr_in6 in6;
604
529
  } to;
605
530
  char *buffer = NULL;
606
 
  char *decrypted_buffer = NULL;
 
531
  char *decrypted_buffer;
607
532
  size_t buffer_length = 0;
608
533
  size_t buffer_capacity = 0;
609
534
  size_t written;
610
 
  int retval = -1;
 
535
  int retval = 0;
611
536
  gnutls_session_t session;
612
537
  int pf;                       /* Protocol family */
613
538
  
614
 
  errno = 0;
615
 
  
616
539
  if(quit_now){
617
 
    errno = EINTR;
618
540
    return -1;
619
541
  }
620
542
  
627
549
    break;
628
550
  default:
629
551
    fprintf(stderr, "Bad address family: %d\n", af);
630
 
    errno = EINVAL;
631
552
    return -1;
632
553
  }
633
554
  
643
564
  
644
565
  tcp_sd = socket(pf, SOCK_STREAM, 0);
645
566
  if(tcp_sd < 0){
646
 
    int e = errno;
647
 
    perror_plus("socket");
648
 
    errno = e;
 
567
    perror("socket");
 
568
    retval = -1;
649
569
    goto mandos_end;
650
570
  }
651
571
  
652
572
  if(quit_now){
653
 
    errno = EINTR;
654
573
    goto mandos_end;
655
574
  }
656
575
  
663
582
    ret = inet_pton(af, ip, &to.in.sin_addr);
664
583
  }
665
584
  if(ret < 0 ){
666
 
    int e = errno;
667
 
    perror_plus("inet_pton");
668
 
    errno = e;
 
585
    perror("inet_pton");
 
586
    retval = -1;
669
587
    goto mandos_end;
670
588
  }
671
589
  if(ret == 0){
672
 
    int e = errno;
673
590
    fprintf(stderr, "Bad address: %s\n", ip);
674
 
    errno = e;
 
591
    retval = -1;
675
592
    goto mandos_end;
676
593
  }
677
594
  if(af == AF_INET6){
685
602
      if(if_index == AVAHI_IF_UNSPEC){
686
603
        fprintf(stderr, "An IPv6 link-local address is incomplete"
687
604
                " without a network interface\n");
688
 
        errno = EINVAL;
 
605
        retval = -1;
689
606
        goto mandos_end;
690
607
      }
691
608
      /* Set the network interface number as scope */
698
615
  }
699
616
  
700
617
  if(quit_now){
701
 
    errno = EINTR;
702
618
    goto mandos_end;
703
619
  }
704
620
  
706
622
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
707
623
      char interface[IF_NAMESIZE];
708
624
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
 
        perror_plus("if_indextoname");
 
625
        perror("if_indextoname");
710
626
      } else {
711
627
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
712
628
                ip, interface, port);
726
642
                        sizeof(addrstr));
727
643
    }
728
644
    if(pcret == NULL){
729
 
      perror_plus("inet_ntop");
 
645
      perror("inet_ntop");
730
646
    } else {
731
647
      if(strcmp(addrstr, ip) != 0){
732
648
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
735
651
  }
736
652
  
737
653
  if(quit_now){
738
 
    errno = EINTR;
739
654
    goto mandos_end;
740
655
  }
741
656
  
745
660
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
746
661
  }
747
662
  if(ret < 0){
748
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
749
 
      int e = errno;
750
 
      perror_plus("connect");
751
 
      errno = e;
752
 
    }
 
663
    perror("connect");
 
664
    retval = -1;
753
665
    goto mandos_end;
754
666
  }
755
667
  
756
668
  if(quit_now){
757
 
    errno = EINTR;
758
669
    goto mandos_end;
759
670
  }
760
671
  
765
676
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
677
                                   out_size - written));
767
678
    if(ret == -1){
768
 
      int e = errno;
769
 
      perror_plus("write");
770
 
      errno = e;
 
679
      perror("write");
 
680
      retval = -1;
771
681
      goto mandos_end;
772
682
    }
773
683
    written += (size_t)ret;
783
693
    }
784
694
  
785
695
    if(quit_now){
786
 
      errno = EINTR;
787
696
      goto mandos_end;
788
697
    }
789
698
  }
793
702
  }
794
703
  
795
704
  if(quit_now){
796
 
    errno = EINTR;
797
705
    goto mandos_end;
798
706
  }
799
707
  
800
 
  /* Spurious warning from -Wint-to-pointer-cast */
801
708
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
802
709
  
803
710
  if(quit_now){
804
 
    errno = EINTR;
805
711
    goto mandos_end;
806
712
  }
807
713
  
808
714
  do {
809
715
    ret = gnutls_handshake(session);
810
716
    if(quit_now){
811
 
      errno = EINTR;
812
717
      goto mandos_end;
813
718
    }
814
719
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
818
723
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
819
724
      gnutls_perror(ret);
820
725
    }
821
 
    errno = EPROTO;
 
726
    retval = -1;
822
727
    goto mandos_end;
823
728
  }
824
729
  
832
737
  while(true){
833
738
    
834
739
    if(quit_now){
835
 
      errno = EINTR;
836
740
      goto mandos_end;
837
741
    }
838
742
    
839
743
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
744
                                   buffer_capacity);
841
745
    if(buffer_capacity == 0){
842
 
      int e = errno;
843
 
      perror_plus("incbuffer");
844
 
      errno = e;
 
746
      perror("incbuffer");
 
747
      retval = -1;
845
748
      goto mandos_end;
846
749
    }
847
750
    
848
751
    if(quit_now){
849
 
      errno = EINTR;
850
752
      goto mandos_end;
851
753
    }
852
754
    
865
767
          ret = gnutls_handshake(session);
866
768
          
867
769
          if(quit_now){
868
 
            errno = EINTR;
869
770
            goto mandos_end;
870
771
          }
871
772
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
773
        if(ret < 0){
873
774
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
874
775
          gnutls_perror(ret);
875
 
          errno = EPROTO;
 
776
          retval = -1;
876
777
          goto mandos_end;
877
778
        }
878
779
        break;
879
780
      default:
880
781
        fprintf(stderr, "Unknown error while reading data from"
881
782
                " encrypted session with Mandos server\n");
 
783
        retval = -1;
882
784
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
 
        errno = EIO;
884
785
        goto mandos_end;
885
786
      }
886
787
    } else {
893
794
  }
894
795
  
895
796
  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);
 
797
    goto mandos_end;
 
798
  }
 
799
  
 
800
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
801
  
 
802
  if(quit_now){
 
803
    goto mandos_end;
 
804
  }
907
805
  
908
806
  if(buffer_length > 0){
909
807
    ssize_t decrypted_buffer_size;
915
813
      written = 0;
916
814
      while(written < (size_t) decrypted_buffer_size){
917
815
        if(quit_now){
918
 
          errno = EINTR;
919
816
          goto mandos_end;
920
817
        }
921
818
        
923
820
                          (size_t)decrypted_buffer_size - written,
924
821
                          stdout);
925
822
        if(ret == 0 and ferror(stdout)){
926
 
          int e = errno;
927
823
          if(debug){
928
824
            fprintf(stderr, "Error writing encrypted data: %s\n",
929
825
                    strerror(errno));
930
826
          }
931
 
          errno = e;
932
 
          goto mandos_end;
 
827
          retval = -1;
 
828
          break;
933
829
        }
934
830
        written += (size_t)ret;
935
831
      }
936
 
      retval = 0;
 
832
      free(decrypted_buffer);
 
833
    } else {
 
834
      retval = -1;
937
835
    }
 
836
  } else {
 
837
    retval = -1;
938
838
  }
939
839
  
940
840
  /* Shutdown procedure */
941
841
  
942
842
 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
 
    }
 
843
  free(buffer);
 
844
  if(tcp_sd >= 0){
 
845
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
846
  }
 
847
  if(ret == -1){
 
848
    perror("close");
 
849
  }
 
850
  gnutls_deinit(session);
 
851
  if(quit_now){
 
852
    retval = -1;
962
853
  }
963
854
  return retval;
964
855
}
1007
898
                                           avahi_proto_to_af(proto));
1008
899
      if(ret == 0){
1009
900
        avahi_simple_poll_quit(mc.simple_poll);
1010
 
      } else {
1011
 
        ret = add_server(ip, port, interface,
1012
 
                         avahi_proto_to_af(proto));
1013
901
      }
1014
902
    }
1015
903
  }
1069
957
  }
1070
958
}
1071
959
 
1072
 
/* Signal handler that stops main loop after SIGTERM */
 
960
/* stop main loop after sigterm has been called */
1073
961
static void handle_sigterm(int sig){
1074
962
  if(quit_now){
1075
963
    return;
1077
965
  quit_now = 1;
1078
966
  signal_received = sig;
1079
967
  int old_errno = errno;
1080
 
  /* set main loop to exit */
1081
968
  if(mc.simple_poll != NULL){
1082
969
    avahi_simple_poll_quit(mc.simple_poll);
1083
970
  }
1084
971
  errno = old_errno;
1085
972
}
1086
973
 
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
974
int main(int argc, char *argv[]){
1275
975
  AvahiSServiceBrowser *sb = NULL;
1276
976
  int error;
1278
978
  intmax_t tmpmax;
1279
979
  char *tmp;
1280
980
  int exitcode = EXIT_SUCCESS;
1281
 
  const char *interface = "";
 
981
  const char *interface = "eth0";
1282
982
  struct ifreq network;
1283
983
  int sd = -1;
1284
984
  bool take_down_interface = false;
1285
985
  uid_t uid;
1286
986
  gid_t gid;
 
987
  char *connect_to = NULL;
1287
988
  char tempdir[] = "/tmp/mandosXXXXXX";
1288
989
  bool tempdir_created = false;
1289
990
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1293
994
  bool gnutls_initialized = false;
1294
995
  bool gpgme_initialized = false;
1295
996
  float delay = 2.5f;
1296
 
  double retry_interval = 10; /* 10s between trying a server and
1297
 
                                 retrying the same server again */
1298
997
  
1299
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
998
  struct sigaction old_sigterm_action;
1300
999
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1301
1000
  
1302
 
  uid = getuid();
1303
 
  gid = getgid();
1304
 
  
1305
 
  /* Lower any group privileges we might have, just to be safe */
1306
 
  errno = 0;
1307
 
  ret = setgid(gid);
1308
 
  if(ret == -1){
1309
 
    perror_plus("setgid");
1310
 
  }
1311
 
  
1312
 
  /* Lower user privileges (temporarily) */
1313
 
  errno = 0;
1314
 
  ret = seteuid(uid);
1315
 
  if(ret == -1){
1316
 
    perror_plus("seteuid");
1317
 
  }
1318
 
  
1319
 
  if(quit_now){
1320
 
    goto end;
1321
 
  }
1322
 
  
1323
1001
  {
1324
1002
    struct argp_option options[] = {
1325
1003
      { .name = "debug", .key = 128,
1354
1032
        .arg = "SECONDS",
1355
1033
        .doc = "Maximum delay to wait for interface startup",
1356
1034
        .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
1035
      { .name = NULL }
1371
1036
    };
1372
1037
    
1373
1038
    error_t parse_opt(int key, char *arg,
1374
1039
                      struct argp_state *state){
1375
 
      errno = 0;
1376
1040
      switch(key){
1377
1041
      case 128:                 /* --debug */
1378
1042
        debug = true;
1394
1058
        tmpmax = strtoimax(arg, &tmp, 10);
1395
1059
        if(errno != 0 or tmp == arg or *tmp != '\0'
1396
1060
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1397
 
          argp_error(state, "Bad number of DH bits");
 
1061
          fprintf(stderr, "Bad number of DH bits\n");
 
1062
          exit(EXIT_FAILURE);
1398
1063
        }
1399
1064
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1400
1065
        break;
1405
1070
        errno = 0;
1406
1071
        delay = strtof(arg, &tmp);
1407
1072
        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");
 
1073
          fprintf(stderr, "Bad delay\n");
 
1074
          exit(EXIT_FAILURE);
1416
1075
        }
1417
1076
        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);
 
1077
      case ARGP_KEY_ARG:
 
1078
        argp_usage(state);
 
1079
      case ARGP_KEY_END:
1431
1080
        break;
1432
1081
      default:
1433
1082
        return ARGP_ERR_UNKNOWN;
1434
1083
      }
1435
 
      return errno;
 
1084
      return 0;
1436
1085
    }
1437
1086
    
1438
1087
    struct argp argp = { .options = options, .parser = parse_opt,
1439
1088
                         .args_doc = "",
1440
1089
                         .doc = "Mandos client -- Get and decrypt"
1441
1090
                         " 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");
 
1091
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1092
    if(ret == ARGP_ERR_UNKNOWN){
 
1093
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1094
      exitcode = EXIT_FAILURE;
 
1095
      goto end;
1512
1096
    }
1513
1097
  }
1514
1098
  
1515
1099
  if(not debug){
1516
1100
    avahi_set_log_function(empty_log);
1517
1101
  }
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
1102
  
1544
1103
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1545
1104
     from the signal handler */
1548
1107
  mc.simple_poll = avahi_simple_poll_new();
1549
1108
  if(mc.simple_poll == NULL){
1550
1109
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1551
 
    exitcode = EX_UNAVAILABLE;
 
1110
    exitcode = EXIT_FAILURE;
1552
1111
    goto end;
1553
1112
  }
1554
1113
  
1555
1114
  sigemptyset(&sigterm_action.sa_mask);
1556
1115
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1557
1116
  if(ret == -1){
1558
 
    perror_plus("sigaddset");
1559
 
    exitcode = EX_OSERR;
 
1117
    perror("sigaddset");
 
1118
    exitcode = EXIT_FAILURE;
1560
1119
    goto end;
1561
1120
  }
1562
1121
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1563
1122
  if(ret == -1){
1564
 
    perror_plus("sigaddset");
1565
 
    exitcode = EX_OSERR;
 
1123
    perror("sigaddset");
 
1124
    exitcode = EXIT_FAILURE;
1566
1125
    goto end;
1567
1126
  }
1568
1127
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1569
1128
  if(ret == -1){
1570
 
    perror_plus("sigaddset");
1571
 
    exitcode = EX_OSERR;
 
1129
    perror("sigaddset");
 
1130
    exitcode = EXIT_FAILURE;
1572
1131
    goto end;
1573
1132
  }
1574
1133
  /* Need to check if the handler is SIG_IGN before handling:
1577
1136
  */
1578
1137
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1579
1138
  if(ret == -1){
1580
 
    perror_plus("sigaction");
1581
 
    return EX_OSERR;
 
1139
    perror("sigaction");
 
1140
    return EXIT_FAILURE;
1582
1141
  }
1583
1142
  if(old_sigterm_action.sa_handler != SIG_IGN){
1584
1143
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1585
1144
    if(ret == -1){
1586
 
      perror_plus("sigaction");
1587
 
      exitcode = EX_OSERR;
 
1145
      perror("sigaction");
 
1146
      exitcode = EXIT_FAILURE;
1588
1147
      goto end;
1589
1148
    }
1590
1149
  }
1591
1150
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1592
1151
  if(ret == -1){
1593
 
    perror_plus("sigaction");
1594
 
    return EX_OSERR;
 
1152
    perror("sigaction");
 
1153
    return EXIT_FAILURE;
1595
1154
  }
1596
1155
  if(old_sigterm_action.sa_handler != SIG_IGN){
1597
1156
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1598
1157
    if(ret == -1){
1599
 
      perror_plus("sigaction");
1600
 
      exitcode = EX_OSERR;
 
1158
      perror("sigaction");
 
1159
      exitcode = EXIT_FAILURE;
1601
1160
      goto end;
1602
1161
    }
1603
1162
  }
1604
1163
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1605
1164
  if(ret == -1){
1606
 
    perror_plus("sigaction");
1607
 
    return EX_OSERR;
 
1165
    perror("sigaction");
 
1166
    return EXIT_FAILURE;
1608
1167
  }
1609
1168
  if(old_sigterm_action.sa_handler != SIG_IGN){
1610
1169
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1611
1170
    if(ret == -1){
1612
 
      perror_plus("sigaction");
1613
 
      exitcode = EX_OSERR;
 
1171
      perror("sigaction");
 
1172
      exitcode = EXIT_FAILURE;
1614
1173
      goto end;
1615
1174
    }
1616
1175
  }
1617
1176
  
1618
1177
  /* If the interface is down, bring it up */
1619
 
  if(strcmp(interface, "none") != 0){
 
1178
  if(interface[0] != '\0'){
1620
1179
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1621
1180
    if(if_index == 0){
1622
1181
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1623
 
      exitcode = EX_UNAVAILABLE;
 
1182
      exitcode = EXIT_FAILURE;
1624
1183
      goto end;
1625
1184
    }
1626
1185
    
1628
1187
      goto end;
1629
1188
    }
1630
1189
    
1631
 
    /* Re-raise priviliges */
1632
 
    errno = 0;
1633
 
    ret = seteuid(0);
1634
 
    if(ret == -1){
1635
 
      perror_plus("seteuid");
1636
 
    }
1637
 
    
1638
1190
#ifdef __linux__
1639
1191
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1640
 
       messages about the network interface to mess up the prompt */
 
1192
       messages to mess up the prompt */
1641
1193
    ret = klogctl(8, NULL, 5);
1642
1194
    bool restore_loglevel = true;
1643
1195
    if(ret == -1){
1644
1196
      restore_loglevel = false;
1645
 
      perror_plus("klogctl");
 
1197
      perror("klogctl");
1646
1198
    }
1647
1199
#endif  /* __linux__ */
1648
1200
    
1649
1201
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1650
1202
    if(sd < 0){
1651
 
      perror_plus("socket");
1652
 
      exitcode = EX_OSERR;
 
1203
      perror("socket");
 
1204
      exitcode = EXIT_FAILURE;
1653
1205
#ifdef __linux__
1654
1206
      if(restore_loglevel){
1655
1207
        ret = klogctl(7, NULL, 0);
1656
1208
        if(ret == -1){
1657
 
          perror_plus("klogctl");
 
1209
          perror("klogctl");
1658
1210
        }
1659
1211
      }
1660
1212
#endif  /* __linux__ */
1661
 
      /* Lower privileges */
1662
 
      errno = 0;
1663
 
      ret = seteuid(uid);
1664
 
      if(ret == -1){
1665
 
        perror_plus("seteuid");
1666
 
      }
1667
1213
      goto end;
1668
1214
    }
1669
1215
    strcpy(network.ifr_name, interface);
1670
1216
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1671
1217
    if(ret == -1){
1672
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1218
      perror("ioctl SIOCGIFFLAGS");
1673
1219
#ifdef __linux__
1674
1220
      if(restore_loglevel){
1675
1221
        ret = klogctl(7, NULL, 0);
1676
1222
        if(ret == -1){
1677
 
          perror_plus("klogctl");
 
1223
          perror("klogctl");
1678
1224
        }
1679
1225
      }
1680
1226
#endif  /* __linux__ */
1681
 
      exitcode = EX_OSERR;
1682
 
      /* Lower privileges */
1683
 
      errno = 0;
1684
 
      ret = seteuid(uid);
1685
 
      if(ret == -1){
1686
 
        perror_plus("seteuid");
1687
 
      }
 
1227
      exitcode = EXIT_FAILURE;
1688
1228
      goto end;
1689
1229
    }
1690
1230
    if((network.ifr_flags & IFF_UP) == 0){
1693
1233
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1694
1234
      if(ret == -1){
1695
1235
        take_down_interface = false;
1696
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1697
 
        exitcode = EX_OSERR;
 
1236
        perror("ioctl SIOCSIFFLAGS");
 
1237
        exitcode = EXIT_FAILURE;
1698
1238
#ifdef __linux__
1699
1239
        if(restore_loglevel){
1700
1240
          ret = klogctl(7, NULL, 0);
1701
1241
          if(ret == -1){
1702
 
            perror_plus("klogctl");
 
1242
            perror("klogctl");
1703
1243
          }
1704
1244
        }
1705
1245
#endif  /* __linux__ */
1706
 
        /* Lower privileges */
1707
 
        errno = 0;
1708
 
        ret = seteuid(uid);
1709
 
        if(ret == -1){
1710
 
          perror_plus("seteuid");
1711
 
        }
1712
1246
        goto end;
1713
1247
      }
1714
1248
    }
1715
 
    /* Sleep checking until interface is running.
1716
 
       Check every 0.25s, up to total time of delay */
 
1249
    /* sleep checking until interface is running */
1717
1250
    for(int i=0; i < delay * 4; i++){
1718
1251
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1719
1252
      if(ret == -1){
1720
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1253
        perror("ioctl SIOCGIFFLAGS");
1721
1254
      } else if(network.ifr_flags & IFF_RUNNING){
1722
1255
        break;
1723
1256
      }
1724
1257
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1725
1258
      ret = nanosleep(&sleeptime, NULL);
1726
1259
      if(ret == -1 and errno != EINTR){
1727
 
        perror_plus("nanosleep");
 
1260
        perror("nanosleep");
1728
1261
      }
1729
1262
    }
1730
1263
    if(not take_down_interface){
1731
1264
      /* We won't need the socket anymore */
1732
1265
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1733
1266
      if(ret == -1){
1734
 
        perror_plus("close");
 
1267
        perror("close");
1735
1268
      }
1736
1269
    }
1737
1270
#ifdef __linux__
1739
1272
      /* Restores kernel loglevel to default */
1740
1273
      ret = klogctl(7, NULL, 0);
1741
1274
      if(ret == -1){
1742
 
        perror_plus("klogctl");
 
1275
        perror("klogctl");
1743
1276
      }
1744
1277
    }
1745
1278
#endif  /* __linux__ */
1746
 
    /* Lower privileges */
1747
 
    errno = 0;
1748
 
    if(take_down_interface){
1749
 
      /* Lower privileges */
1750
 
      ret = seteuid(uid);
1751
 
      if(ret == -1){
1752
 
        perror_plus("seteuid");
1753
 
      }
1754
 
    } else {
1755
 
      /* Lower privileges permanently */
1756
 
      ret = setuid(uid);
1757
 
      if(ret == -1){
1758
 
        perror_plus("setuid");
1759
 
      }
1760
 
    }
 
1279
  }
 
1280
  
 
1281
  if(quit_now){
 
1282
    goto end;
 
1283
  }
 
1284
  
 
1285
  uid = getuid();
 
1286
  gid = getgid();
 
1287
  
 
1288
  errno = 0;
 
1289
  setgid(gid);
 
1290
  if(ret == -1){
 
1291
    perror("setgid");
 
1292
  }
 
1293
  
 
1294
  ret = setuid(uid);
 
1295
  if(ret == -1){
 
1296
    perror("setuid");
1761
1297
  }
1762
1298
  
1763
1299
  if(quit_now){
1767
1303
  ret = init_gnutls_global(pubkey, seckey);
1768
1304
  if(ret == -1){
1769
1305
    fprintf(stderr, "init_gnutls_global failed\n");
1770
 
    exitcode = EX_UNAVAILABLE;
 
1306
    exitcode = EXIT_FAILURE;
1771
1307
    goto end;
1772
1308
  } else {
1773
1309
    gnutls_initialized = true;
1777
1313
    goto end;
1778
1314
  }
1779
1315
  
 
1316
  tempdir_created = true;
1780
1317
  if(mkdtemp(tempdir) == NULL){
1781
 
    perror_plus("mkdtemp");
 
1318
    tempdir_created = false;
 
1319
    perror("mkdtemp");
1782
1320
    goto end;
1783
1321
  }
1784
 
  tempdir_created = true;
1785
1322
  
1786
1323
  if(quit_now){
1787
1324
    goto end;
1789
1326
  
1790
1327
  if(not init_gpgme(pubkey, seckey, tempdir)){
1791
1328
    fprintf(stderr, "init_gpgme failed\n");
1792
 
    exitcode = EX_UNAVAILABLE;
 
1329
    exitcode = EXIT_FAILURE;
1793
1330
    goto end;
1794
1331
  } else {
1795
1332
    gpgme_initialized = true;
1805
1342
    char *address = strrchr(connect_to, ':');
1806
1343
    if(address == NULL){
1807
1344
      fprintf(stderr, "No colon in address\n");
1808
 
      exitcode = EX_USAGE;
 
1345
      exitcode = EXIT_FAILURE;
1809
1346
      goto end;
1810
1347
    }
1811
1348
    
1819
1356
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1820
1357
       or tmpmax != (uint16_t)tmpmax){
1821
1358
      fprintf(stderr, "Bad port number\n");
1822
 
      exitcode = EX_USAGE;
 
1359
      exitcode = EXIT_FAILURE;
1823
1360
      goto end;
1824
1361
    }
1825
1362
  
1841
1378
    if(quit_now){
1842
1379
      goto end;
1843
1380
    }
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){
 
1381
    
 
1382
    ret = start_mandos_communication(address, port, if_index, af);
 
1383
    if(ret < 0){
 
1384
      exitcode = EXIT_FAILURE;
 
1385
    } else {
1854
1386
      exitcode = EXIT_SUCCESS;
1855
1387
    }
1856
 
 
1857
1388
    goto end;
1858
1389
  }
1859
1390
  
1883
1414
  if(mc.server == NULL){
1884
1415
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1885
1416
            avahi_strerror(error));
1886
 
    exitcode = EX_UNAVAILABLE;
 
1417
    exitcode = EXIT_FAILURE;
1887
1418
    goto end;
1888
1419
  }
1889
1420
  
1898
1429
  if(sb == NULL){
1899
1430
    fprintf(stderr, "Failed to create service browser: %s\n",
1900
1431
            avahi_strerror(avahi_server_errno(mc.server)));
1901
 
    exitcode = EX_UNAVAILABLE;
 
1432
    exitcode = EXIT_FAILURE;
1902
1433
    goto end;
1903
1434
  }
1904
1435
  
1911
1442
  if(debug){
1912
1443
    fprintf(stderr, "Starting Avahi loop search\n");
1913
1444
  }
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
 
  }
 
1445
  
 
1446
  avahi_simple_poll_loop(mc.simple_poll);
1921
1447
  
1922
1448
 end:
1923
1449
  
1944
1470
  if(gpgme_initialized){
1945
1471
    gpgme_release(mc.ctx);
1946
1472
  }
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
1473
  
1959
1474
  /* Take down the network interface */
1960
1475
  if(take_down_interface){
1961
 
    /* Re-raise priviliges */
1962
 
    errno = 0;
1963
 
    ret = seteuid(0);
 
1476
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1964
1477
    if(ret == -1){
1965
 
      perror_plus("seteuid");
 
1478
      perror("ioctl SIOCGIFFLAGS");
 
1479
    } else if(network.ifr_flags & IFF_UP) {
 
1480
      network.ifr_flags &= ~IFF_UP; /* clear flag */
 
1481
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1482
      if(ret == -1){
 
1483
        perror("ioctl SIOCSIFFLAGS");
 
1484
      }
1966
1485
    }
1967
 
    if(geteuid() == 0){
1968
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1969
 
      if(ret == -1){
1970
 
        perror_plus("ioctl SIOCGIFFLAGS");
1971
 
      } else if(network.ifr_flags & IFF_UP) {
1972
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1973
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1974
 
        if(ret == -1){
1975
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1976
 
        }
1977
 
      }
1978
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1979
 
      if(ret == -1){
1980
 
        perror_plus("close");
1981
 
      }
1982
 
      /* Lower privileges permanently */
1983
 
      errno = 0;
1984
 
      ret = setuid(uid);
1985
 
      if(ret == -1){
1986
 
        perror_plus("setuid");
1987
 
      }
 
1486
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1487
    if(ret == -1){
 
1488
      perror("close");
1988
1489
    }
1989
1490
  }
1990
1491
  
1991
 
  /* Removes the GPGME temp directory and all files inside */
 
1492
  /* Removes the temp directory used by GPGME */
1992
1493
  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];
 
1494
    DIR *d;
 
1495
    struct dirent *direntry;
 
1496
    d = opendir(tempdir);
 
1497
    if(d == NULL){
 
1498
      if(errno != ENOENT){
 
1499
        perror("opendir");
 
1500
      }
 
1501
    } else {
 
1502
      while(true){
 
1503
        direntry = readdir(d);
 
1504
        if(direntry == NULL){
 
1505
          break;
 
1506
        }
 
1507
        /* Skip "." and ".." */
 
1508
        if(direntry->d_name[0] == '.'
 
1509
           and (direntry->d_name[1] == '\0'
 
1510
                or (direntry->d_name[1] == '.'
 
1511
                    and direntry->d_name[2] == '\0'))){
 
1512
          continue;
 
1513
        }
1999
1514
        char *fullname = NULL;
2000
1515
        ret = asprintf(&fullname, "%s/%s", tempdir,
2001
1516
                       direntry->d_name);
2002
1517
        if(ret < 0){
2003
 
          perror_plus("asprintf");
 
1518
          perror("asprintf");
2004
1519
          continue;
2005
1520
        }
2006
1521
        ret = remove(fullname);
2010
1525
        }
2011
1526
        free(fullname);
2012
1527
      }
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");
 
1528
      closedir(d);
2020
1529
    }
2021
1530
    ret = rmdir(tempdir);
2022
1531
    if(ret == -1 and errno != ENOENT){
2023
 
      perror_plus("rmdir");
 
1532
      perror("rmdir");
2024
1533
    }
2025
1534
  }
2026
1535
  
2027
1536
  if(quit_now){
2028
1537
    sigemptyset(&old_sigterm_action.sa_mask);
2029
1538
    old_sigterm_action.sa_handler = SIG_DFL;
2030
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2031
 
                                            &old_sigterm_action,
2032
 
                                            NULL));
 
1539
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
2033
1540
    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());
 
1541
      perror("sigaction");
 
1542
    }
 
1543
    raise(signal_received);
2044
1544
  }
2045
1545
  
2046
1546
  return exitcode;