/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

* plugins.d/mandos-client.c (good_interface): Use SIOCGIFFLAGS instead
                                              of reading
                                              /sys/class/net/*/flags.

Show diffs side-by-side

added added

removed removed

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